aGrUM 3.3.2
a C++ library for (probabilistic) graphical models
GumBNWriter_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/BN/io/GUM/GumBNWriter.h> // to ease IDE parser
45#ifndef DOXYGEN_SHOULD_SKIP_THIS
46
47// to ease parsing in IDE
52
53# include <agrum/base/external/json/json.hpp>
54using json = nlohmann::json;
55using ordered_json = nlohmann::ordered_json;
56
57namespace gum {
58 // Default constructor.
59 template < GUM_Numeric GUM_SCALAR >
61
62 template < GUM_Numeric GUM_SCALAR >
63 GumBNWriter< GUM_SCALAR >::GumBNWriter(bool binary, int indent) : BNWriter< GUM_SCALAR >() {
64 _binary_ = binary;
65 _indent_ = (indent < -1) ? -1 : indent;
66 GUM_CONSTRUCTOR(GumBNWriter);
67 }
68
69 // Default destructor.
70 template < GUM_Numeric GUM_SCALAR >
71 GumBNWriter< GUM_SCALAR >::~GumBNWriter() {
72 GUM_DESTRUCTOR(GumBNWriter);
73 }
74
75 //
76 // Writes a Bayesian network in the output stream using the BN format.
77 //
78 // @param ouput The output stream.
79 // @param bn The Bayesian network writen in output.
80 // @throws Raised if an I/O error occurs.
81 template < GUM_Numeric GUM_SCALAR >
82 void GumBNWriter< GUM_SCALAR >::_doWrite(std::ostream& output,
83 const IBayesNet< GUM_SCALAR >& bn) {
84 if (!output.good()) GUM_ERROR(IOError, "Input/Output error : stream not writable.");
85
86 ordered_json content;
87 content["type"] = "BN";
88 content["GumJsonVersion"] = "1.0";
89
90 // add variables (always written, even empty, so the section always exists)
91 content["nodes"] = ordered_json::array();
92 for (const auto& node: bn.nodes()) {
93 content["nodes"].push_back(bn.variable(node).toFast());
94 }
95 // add parents (always written, even empty, so the section always exists)
96 content["parents"] = ordered_json::object();
97 auto& parentsObj = content["parents"].template get_ref< ordered_json::object_t& >();
98 parentsObj.reserve(bn.size());
99 for (const auto& node: bn.nodes()) {
100 ordered_json parentList = ordered_json::array();
101 const auto& cpt = bn.cpt(node);
102 for (Idx i = 1; i < cpt.nbrDim(); i++)
103 parentList.push_back(cpt.variable(i).name());
104 parentsObj.emplace_back(bn.variable(node).name(), std::move(parentList));
105 }
106 // add cpts (always written, even empty, so the section always exists)
107 content["cpt"] = ordered_json::object();
108 auto& cptObj = content["cpt"].template get_ref< ordered_json::object_t& >();
109 cptObj.reserve(bn.size());
110 for (const auto& node: bn.nodes()) {
111 const auto& cpt = bn.cpt(node);
112
113 if (const auto* agg
115 cpt.content())) {
116 std::string name = agg->aggregatorName();
117 const auto bracket = name.find('[');
118 if (bracket != std::string::npos) name.erase(bracket);
119
120 ordered_json aggJson;
121 aggJson["kind"] = "aggregator";
122 aggJson["name"] = name;
123 if (const auto value = agg->value()) aggJson["value"] = *value;
124
125 cptObj.emplace_back(bn.variable(node).name(), std::move(aggJson));
126 continue;
127 }
128
129 if (const auto* ici = dynamic_cast< const MultiDimICIModel< GUM_SCALAR >* >(cpt.content())) {
130 ordered_json weights = ordered_json::object();
131 for (Idx i = 1; i < cpt.nbrDim(); i++)
132 weights[cpt.variable(i).name()] = ici->causalWeight(cpt.variable(i));
133
134 ordered_json iciJson;
135 iciJson["kind"] = "ici";
136 iciJson["name"] = ici->name();
137 iciJson["externalWeight"] = ici->externalWeight();
138 iciJson["causalWeights"] = weights;
139
140 cptObj.emplace_back(bn.variable(node).name(), std::move(iciJson));
141 continue;
142 }
143
144 json cptValues;
145 Instantiation I(cpt);
146 for (I.setFirst(); !I.end(); ++I) {
147 cptValues.push_back(cpt[I]);
148 }
149 cptObj.emplace_back(bn.variable(node).name(), std::move(cptValues));
150 }
151 // add properties
152 for (const auto& prop: bn.properties()) {
153 content["properties"][prop] = bn.property(prop);
154 }
155
156 // write the content in the output stream
157 if (_binary_) {
158 // binary mode
159 _writeVector_(output, json::to_msgpack(content));
160 } else {
161 // text mode
162 output << content.dump(_indent_); // pretty print with 2 spaces indentation
163 }
164
165 if (output.fail()) {
166 GUM_ERROR(IOError, "Writing in the ostream failed. Check if the stream is writable.")
167 }
168 }
169
170 // Writes a Bayesian network in the referenced file using the BN format.
171 // If the file doesn't exists, it is created.
172 // If the file exists, it's content will be erased.
173 //
174 // @param filePath The path to the file used to write the Bayesian network.
175 // @param bn The Bayesian network writed in the file.
176 // @throws Raised if an I/O error occurs.
177 template < GUM_Numeric GUM_SCALAR >
178 void GumBNWriter< GUM_SCALAR >::_doWrite(std::string_view filePath,
179 const IBayesNet< GUM_SCALAR >& bn) {
180 std::ofstream output(std::string(filePath),
181 _binary_ ? (std::ios_base::trunc | std::ios::binary)
182 : std::ios_base::trunc);
183
184 _doWrite(output, bn);
185
186 output.close();
187 if (output.fail()) { GUM_ERROR(IOError, "Writing in the ostream failed.") }
188 }
189
190} // namespace gum
191#endif // DOXYGEN_SHOULD_SKIP_THIS
Definition of classe for GUM (json) file output manipulation.
Shared binary I/O helpers for GUM (jgum/bgum) serialization.
Writes a IBayesNet in the GUM json format.
Definition GumBNWriter.h:80
GumBNWriter(bool binary=false)
Default constructor.
Exception : input/output problem.
#define GUM_ERROR(type, msg)
Definition exceptions.h:76
MultiDimAggregator.
Abstract base class for all multi dimensionnal Causal Independency models.
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).