aGrUM 3.3.2
a C++ library for (probabilistic) graphical models
GumIDWriter_tpl.h
Go to the documentation of this file.
1/****************************************************************************
2 * This file is part of the aGrUM/pyAgrum library. *
3 * *
4 * Copyright (c) 2005-2026 by *
5 * - Pierre-Henri WUILLEMIN(_at_LIP6) *
6 * - Christophe GONZALES(_at_AMU) *
7 * *
8 * The aGrUM/pyAgrum library is free software; you can redistribute it *
9 * and/or modify it under the terms of either : *
10 * *
11 * - the GNU Lesser General Public License as published by *
12 * the Free Software Foundation, either version 3 of the License, *
13 * or (at your option) any later version, *
14 * - the MIT license (MIT), *
15 * - or both in dual license, as here. *
16 * *
17 * (see https://agrum.gitlab.io/articles/dual-licenses-lgplv3mit.html) *
18 * *
19 * This aGrUM/pyAgrum library is distributed in the hope that it will be *
20 * useful, but WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
21 * INCLUDING BUT NOT LIMITED TO THE WARRANTIES MERCHANTABILITY or FITNESS *
22 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *
23 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
24 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, *
25 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR *
26 * OTHER DEALINGS IN THE SOFTWARE. *
27 * *
28 * See LICENCES for more details. *
29 * *
30 * SPDX-FileCopyrightText: Copyright 2005-2026 *
31 * - Pierre-Henri WUILLEMIN(_at_LIP6) *
32 * - Christophe GONZALES(_at_AMU) *
33 * SPDX-License-Identifier: LGPL-3.0-or-later OR MIT *
34 * *
35 * Contact : info_at_agrum_dot_org *
36 * homepage : http://agrum.gitlab.io *
37 * gitlab : https://gitlab.com/agrumery/agrum *
38 * *
39 ****************************************************************************/
40
41
42#pragma once
43
44#include <agrum/ID/io/GUM/GumIDWriter.h> // to ease IDE parser
45#ifndef DOXYGEN_SHOULD_SKIP_THIS
46
47// to ease parsing in IDE
50
51# include <agrum/base/external/json/json.hpp>
52using json = nlohmann::json;
53using ordered_json = nlohmann::ordered_json;
54
55namespace gum {
56 template < GUM_Numeric GUM_SCALAR >
58
59 template < GUM_Numeric GUM_SCALAR >
60 GumIDWriter< GUM_SCALAR >::GumIDWriter(bool binary, int indent) : IDWriter< GUM_SCALAR >() {
61 _binary_ = binary;
62 _indent_ = (indent < -1) ? -1 : indent;
63 GUM_CONSTRUCTOR(GumIDWriter);
64 }
65
66 template < GUM_Numeric GUM_SCALAR >
67 GumIDWriter< GUM_SCALAR >::~GumIDWriter() {
68 GUM_DESTRUCTOR(GumIDWriter);
69 }
70
71 template < GUM_Numeric GUM_SCALAR >
72 void GumIDWriter< GUM_SCALAR >::write(std::ostream& output,
73 const InfluenceDiagram< GUM_SCALAR >& id) {
74 if (!output.good()) GUM_ERROR(IOError, "Input/Output error : stream not writable.")
75
76 ordered_json content;
77 content["type"] = "ID";
78 content["GumJsonVersion"] = "1.0";
79
80 // classify nodes by type (always write all three arrays, even if empty)
81 content["chance"] = ordered_json::array();
82 content["utility"] = ordered_json::array();
83 content["decision"] = ordered_json::array();
84 for (const auto& node: id.nodes()) {
85 const auto fast = id.variable(node).toFast();
86 if (id.isChanceNode(node)) {
87 content["chance"].push_back(fast);
88 } else if (id.isUtilityNode(node)) {
89 content["utility"].push_back(fast);
90 } else {
91 content["decision"].push_back(fast);
92 }
93 }
94
95 // parents for every node (all types)
96 content["parents"] = ordered_json::object();
97 for (const auto& node: id.nodes()) {
98 ordered_json parentList = ordered_json::array();
99 const auto& name = id.variable(node).name();
100 if (id.isChanceNode(node)) {
101 const auto& cpt = id.cpt(node);
102 for (Idx i = 1; i < cpt.nbrDim(); i++)
103 parentList.push_back(cpt.variable(i).name());
104 } else if (id.isUtilityNode(node)) {
105 const auto& ut = id.utility(node);
106 for (Idx i = 1; i < ut.nbrDim(); i++)
107 parentList.push_back(ut.variable(i).name());
108 } else {
109 // decision node: parents from the DAG
110 for (const auto& p: id.parents(node))
111 parentList.push_back(id.variable(p).name());
112 }
113 content["parents"][name] = parentList;
114 }
115
116 // CPT values for chance nodes
117 for (const auto& node: id.nodes()) {
118 if (!id.isChanceNode(node)) continue;
119 json vals;
120 const auto& cpt = id.cpt(node);
121 Instantiation I(cpt);
122 for (I.setFirst(); !I.end(); ++I)
123 vals.push_back(cpt[I]);
124 content["cpt"][id.variable(node).name()] = vals;
125 }
126
127 // reward values for utility nodes
128 for (const auto& node: id.nodes()) {
129 if (!id.isUtilityNode(node)) continue;
130 json vals;
131 const auto& ut = id.utility(node);
132 Instantiation I(ut);
133 for (I.setFirst(); !I.end(); ++I)
134 vals.push_back(ut[I]);
135 content["reward"][id.variable(node).name()] = vals;
136 }
137
138 // properties
139 for (const auto& prop: id.properties())
140 content["properties"][prop] = id.property(prop);
141
142 if (_binary_) {
143 _writeVector_(output, json::to_msgpack(content));
144 } else {
145 output << content.dump(_indent_);
146 }
147
148 if (output.fail()) {
149 GUM_ERROR(IOError, "Writing in the ostream failed. Check if the stream is writable.")
150 }
151 }
152
153 template < GUM_Numeric GUM_SCALAR >
154 void GumIDWriter< GUM_SCALAR >::write(std::string_view filePath,
155 InfluenceDiagram< GUM_SCALAR >& id) {
156 id.updateMetaData();
157 write(filePath, static_cast< const InfluenceDiagram< GUM_SCALAR >& >(id));
158 }
159
160 template < GUM_Numeric GUM_SCALAR >
161 void GumIDWriter< GUM_SCALAR >::write(std::string_view filePath,
162 const InfluenceDiagram< GUM_SCALAR >& id) {
163 std::ofstream output(std::string(filePath),
164 _binary_ ? (std::ios_base::trunc | std::ios::binary)
165 : std::ios_base::trunc);
166 write(output, id);
167 output.close();
168 if (output.fail()) { GUM_ERROR(IOError, "Writing in the ostream failed.") }
169 }
170
171 template < GUM_Numeric GUM_SCALAR >
172 std::string GumIDWriter< GUM_SCALAR >::toString(const InfluenceDiagram< GUM_SCALAR >& id) {
173 std::ostringstream oss;
174 write(oss, id);
175 return oss.str();
176 }
177
178} // namespace gum
179
180#endif // DOXYGEN_SHOULD_SKIP_THIS
Shared binary I/O helpers for GUM (jgum/bgum) serialization.
Definition of class for GUM (json) file output for Influence Diagrams.
Writes an InfluenceDiagram in the GUM json format.
Definition GumIDWriter.h:72
GumIDWriter(bool binary=false)
Default constructor.
Exception : input/output problem.
#define GUM_ERROR(type, msg)
Definition exceptions.h:76
gum is the global namespace for all aGrUM entities
Definition agrum.h:46
int defaultJgumIndent()
The indentation used by the GUM writers (jgum text format) when none is given: the value of the key j...
GUM_SHARED_PUBLIC void _writeVector_(std::ostream &os, const std::vector< uint8_t > &vec)
Writes a length-prefixed byte vector to a binary stream (bgum format).