aGrUM 3.0.0
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 >
57 GumIDWriter< GUM_SCALAR >::GumIDWriter(bool binary, int indent) : IDWriter< GUM_SCALAR >() {
58 _binary_ = binary;
59 _indent_ = (indent < -1) ? -1 : indent;
60 GUM_CONSTRUCTOR(GumIDWriter);
61 }
62
63 template < GUM_Numeric GUM_SCALAR >
64 GumIDWriter< GUM_SCALAR >::~GumIDWriter() {
65 GUM_DESTRUCTOR(GumIDWriter);
66 }
67
68 template < GUM_Numeric GUM_SCALAR >
69 void GumIDWriter< GUM_SCALAR >::write(std::ostream& output,
70 const InfluenceDiagram< GUM_SCALAR >& id) {
71 if (!output.good()) GUM_ERROR(IOError, "Input/Output error : stream not writable.")
72
73 ordered_json content;
74 content["type"] = "ID";
75 content["GumJsonVersion"] = "1.0";
76
77 // classify nodes by type (always write all three arrays, even if empty)
78 content["chance"] = ordered_json::array();
79 content["utility"] = ordered_json::array();
80 content["decision"] = ordered_json::array();
81 for (const auto& node: id.nodes()) {
82 const auto fast = id.variable(node).toFast();
83 if (id.isChanceNode(node)) {
84 content["chance"].push_back(fast);
85 } else if (id.isUtilityNode(node)) {
86 content["utility"].push_back(fast);
87 } else {
88 content["decision"].push_back(fast);
89 }
90 }
91
92 // parents for every node (all types)
93 content["parents"] = ordered_json::object();
94 for (const auto& node: id.nodes()) {
95 ordered_json parentList = ordered_json::array();
96 const auto& name = id.variable(node).name();
97 if (id.isChanceNode(node)) {
98 const auto& cpt = id.cpt(node);
99 for (Idx i = 1; i < cpt.nbrDim(); i++)
100 parentList.push_back(cpt.variable(i).name());
101 } else if (id.isUtilityNode(node)) {
102 const auto& ut = id.utility(node);
103 for (Idx i = 1; i < ut.nbrDim(); i++)
104 parentList.push_back(ut.variable(i).name());
105 } else {
106 // decision node: parents from the DAG
107 for (const auto& p: id.parents(node))
108 parentList.push_back(id.variable(p).name());
109 }
110 content["parents"][name] = parentList;
111 }
112
113 // CPT values for chance nodes
114 for (const auto& node: id.nodes()) {
115 if (!id.isChanceNode(node)) continue;
116 json vals;
117 const auto& cpt = id.cpt(node);
118 Instantiation I(cpt);
119 for (I.setFirst(); !I.end(); ++I)
120 vals.push_back(cpt[I]);
121 content["cpt"][id.variable(node).name()] = vals;
122 }
123
124 // reward values for utility nodes
125 for (const auto& node: id.nodes()) {
126 if (!id.isUtilityNode(node)) continue;
127 json vals;
128 const auto& ut = id.utility(node);
129 Instantiation I(ut);
130 for (I.setFirst(); !I.end(); ++I)
131 vals.push_back(ut[I]);
132 content["reward"][id.variable(node).name()] = vals;
133 }
134
135 // properties
136 for (const auto& prop: id.properties())
137 content["properties"][prop] = id.property(prop);
138
139 if (_binary_) {
140 _writeVector_(output, json::to_msgpack(content));
141 } else {
142 output << content.dump(_indent_);
143 }
144
145 if (output.fail()) {
146 GUM_ERROR(IOError, "Writing in the ostream failed. Check if the stream is writable.")
147 }
148 }
149
150 template < GUM_Numeric GUM_SCALAR >
151 void GumIDWriter< GUM_SCALAR >::write(std::string_view filePath,
152 InfluenceDiagram< GUM_SCALAR >& id) {
153 id.updateMetaData();
154 write(filePath, static_cast< const InfluenceDiagram< GUM_SCALAR >& >(id));
155 }
156
157 template < GUM_Numeric GUM_SCALAR >
158 void GumIDWriter< GUM_SCALAR >::write(std::string_view filePath,
159 const InfluenceDiagram< GUM_SCALAR >& id) {
160 std::ofstream output(std::string(filePath),
161 _binary_ ? (std::ios_base::trunc | std::ios::binary)
162 : std::ios_base::trunc);
163 write(output, id);
164 output.close();
165 if (output.fail()) { GUM_ERROR(IOError, "Writing in the ostream failed.") }
166 }
167
168 template < GUM_Numeric GUM_SCALAR >
169 std::string GumIDWriter< GUM_SCALAR >::toString(const InfluenceDiagram< GUM_SCALAR >& id) {
170 std::ostringstream oss;
171 write(oss, id);
172 return oss.str();
173 }
174
175} // namespace gum
176
177#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.
GumIDWriter(bool binary=false, int indent=-1)
Default constructor.
Pure virtual class for exporting an ID.
Definition IDWriter.h:76
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
void _writeVector_(std::ostream &os, const std::vector< uint8_t > &vec)
Writes a length-prefixed byte vector to a binary stream (bgum format).