aGrUM 3.0.0
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
50
51# include <agrum/base/external/json/json.hpp>
52using json = nlohmann::json;
53using ordered_json = nlohmann::ordered_json;
54
55namespace gum {
56 // Default constructor.
57 template < GUM_Numeric GUM_SCALAR >
58 GumBNWriter< GUM_SCALAR >::GumBNWriter(bool binary, int indent) : BNWriter< GUM_SCALAR >() {
59 _binary_ = binary;
60 _indent_ = (indent < -1) ? -1 : indent;
61 GUM_CONSTRUCTOR(GumBNWriter);
62 }
63
64 // Default destructor.
65 template < GUM_Numeric GUM_SCALAR >
66 GumBNWriter< GUM_SCALAR >::~GumBNWriter() {
67 GUM_DESTRUCTOR(GumBNWriter);
68 }
69
70 //
71 // Writes a Bayesian network in the output stream using the BN format.
72 //
73 // @param ouput The output stream.
74 // @param bn The Bayesian network writen in output.
75 // @throws Raised if an I/O error occurs.
76 template < GUM_Numeric GUM_SCALAR >
77 void GumBNWriter< GUM_SCALAR >::_doWrite(std::ostream& output,
78 const IBayesNet< GUM_SCALAR >& bn) {
79 if (!output.good()) GUM_ERROR(IOError, "Input/Output error : stream not writable.");
80
81 ordered_json content;
82 content["type"] = "BN";
83 content["GumJsonVersion"] = "1.0";
84
85 // add variables (always written, even empty, so the section always exists)
86 content["nodes"] = ordered_json::array();
87 for (const auto& node: bn.nodes()) {
88 content["nodes"].push_back(bn.variable(node).toFast());
89 }
90 // add parents (always written, even empty, so the section always exists)
91 content["parents"] = ordered_json::object();
92 for (const auto& node: bn.nodes()) {
93 ordered_json parentList = ordered_json::array();
94 const auto& cpt = bn.cpt(node);
95 for (Idx i = 1; i < cpt.nbrDim(); i++)
96 parentList.push_back(cpt.variable(i).name());
97 content["parents"][bn.variable(node).name()] = parentList;
98 }
99 // add cpts (always written, even empty, so the section always exists)
100 content["cpt"] = ordered_json::object();
101 for (const auto& node: bn.nodes()) {
102 json cptValues;
103 const auto& cpt = bn.cpt(node);
104 Instantiation I(cpt);
105 for (I.setFirst(); !I.end(); ++I) {
106 cptValues.push_back(cpt[I]);
107 }
108 content["cpt"][bn.variable(node).name()] = cptValues;
109 }
110 // add properties
111 for (const auto& prop: bn.properties()) {
112 content["properties"][prop] = bn.property(prop);
113 }
114
115 // write the content in the output stream
116 if (_binary_) {
117 // binary mode
118 _writeVector_(output, json::to_msgpack(content));
119 } else {
120 // text mode
121 output << content.dump(_indent_); // pretty print with 2 spaces indentation
122 }
123
124 if (output.fail()) {
125 GUM_ERROR(IOError, "Writing in the ostream failed. Check if the stream is writable.")
126 }
127 }
128
129 // Writes a Bayesian network in the referenced file using the BN format.
130 // If the file doesn't exists, it is created.
131 // If the file exists, it's content will be erased.
132 //
133 // @param filePath The path to the file used to write the Bayesian network.
134 // @param bn The Bayesian network writed in the file.
135 // @throws Raised if an I/O error occurs.
136 template < GUM_Numeric GUM_SCALAR >
137 void GumBNWriter< GUM_SCALAR >::_doWrite(std::string_view filePath,
138 const IBayesNet< GUM_SCALAR >& bn) {
139 std::ofstream output(std::string(filePath),
140 _binary_ ? (std::ios_base::trunc | std::ios::binary)
141 : std::ios_base::trunc);
142
143 _doWrite(output, bn);
144
145 output.close();
146 if (output.fail()) { GUM_ERROR(IOError, "Writing in the ostream failed.") }
147 }
148
149} // namespace gum
150#endif // DOXYGEN_SHOULD_SKIP_THIS
Definition of classe for GUM (json) file output manipulation.
Shared binary I/O helpers for GUM (jgum/bgum) serialization.
virtual class for writing a BN to a file.
Definition BNWriter.h:79
GumBNWriter(bool binary=false, int indent=-1)
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
void _writeVector_(std::ostream &os, const std::vector< uint8_t > &vec)
Writes a length-prefixed byte vector to a binary stream (bgum format).