aGrUM 3.1.1
a C++ library for (probabilistic) graphical models
netWriter_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#pragma once
42
43#include <agrum/BN/io/net/netWriter.h> // to ease IDE parser
44#pragma once
45#ifndef DOXYGEN_SHOULD_SKIP_THIS
46
47# include <fstream>
48
49// to ease parsing in IDE
51
52namespace gum {
53 /* =========================================================================*/
54 /* === GUM_BN_WRITER === */
55 /* =========================================================================*/
56 // Default constructor.
57 template < GUM_Numeric GUM_SCALAR >
59 GUM_CONSTRUCTOR(NetWriter);
60 }
61
62 // Default destructor.
63 template < GUM_Numeric GUM_SCALAR >
65 GUM_DESTRUCTOR(NetWriter);
66 }
67
68 //
69 // Writes a Bayesian network in the output stream using the BN format.
70 //
71 // @param ouput The output stream.
72 // @param bn The Bayesian network writen in output.
73 // @throws Raised if an I/O error occurs.
74 template < GUM_Numeric GUM_SCALAR >
75 void NetWriter< GUM_SCALAR >::_doWrite(std::ostream& output, const IBayesNet< GUM_SCALAR >& bn) {
76 if (!output.good()) GUM_ERROR(IOError, "Input/Output error : stream not writable.")
77
78 output << _header_(bn) << std::endl;
79
80 for (auto node: bn.nodes())
81 output << _variableBloc_(bn.variable(node)) << std::endl;
82
83 for (auto node: bn.nodes())
84 output << _variableCPT_(bn.cpt(node));
85
86 output << std::endl;
87
88 output.flush();
89
90 if (output.fail()) { GUM_ERROR(IOError, "Writing in the ostream failed.") }
91 }
92
93 // Writes a Bayesian network in the referenced file using the BN format.
94 // If the file doesn't exists, it is created.
95 // If the file exists, it's content will be erased.
96 //
97 // @param filePath The path to the file used to write the Bayesian network.
98 // @param bn The Bayesian network writed in the file.
99 // @throws Raised if an I/O error occurs.
100 template < GUM_Numeric GUM_SCALAR >
101 void NetWriter< GUM_SCALAR >::_doWrite(std::string_view filePath,
102 const IBayesNet< GUM_SCALAR >& bn) {
103 std::ofstream output(std::filesystem::path{filePath}, std::ios_base::trunc);
104
105 _doWrite(output, bn);
106
107 output.close();
108 if (output.fail()) { GUM_ERROR(IOError, "Writing in the ostream failed.") }
109 }
110
111 // Returns a bloc defining a variable's CPT in the BN format.
112 template < GUM_Numeric GUM_SCALAR >
114 std::stringstream str;
115 std::string tab = " "; // poor tabulation
116
117 Instantiation inst(cpt);
118 if (cpt.nbrDim() == 1) {
119 str << std::format("potential ({}) {{\n{}data = ( ", cpt.variable(0).name(), tab);
120
121 for (inst.setFirst(); !inst.end(); ++inst) {
122 str << std::format(" {}", cpt[inst]);
123 ;
124 }
125
126 str << ");";
127 } else { // cpt.domainSize() > 1
128 const Sequence< const DiscreteVariable* >& varsSeq = cpt.variablesSequence();
129
130 Instantiation conds;
131 for (Idx i = 1; i < varsSeq.size(); i++)
132 conds.add(*varsSeq[varsSeq.size() - i]);
133
134 str << std::format("potential ( {} | ", (varsSeq[static_cast< Idx >(0)])->name());
135 for (Idx i = 1; i < varsSeq.size(); i++)
136 str << varsSeq[i]->name() << " ";
137 str << ") {" << std::endl << tab << "data = \n";
138
139 std::string comment;
140 conds.setFirst();
141 while (true) {
142 str << tab << "(";
143 for (Idx i = 0; i < conds.nbrDim(); i++) {
144 if (conds.val(i) != 0) break;
145 str << "(";
146 }
147
148 inst.setVals(conds);
149 for (inst.setFirstVar(*varsSeq[0]); !inst.end(); inst.incVar(*varsSeq[0]))
150 str << std::format(" {}{}", tab, cpt[inst]);
151
152 comment = tab + "% ";
153 for (Idx i = 0; i < conds.nbrDim(); i++) {
154 comment += conds.variable(i).name() + "=" + conds.variable(i).label(conds.val(i)) + tab;
155 }
156
157 ++conds;
158 if (conds.end()) {
159 for (Idx i = 0; i < inst.nbrDim(); i++) {
160 str << ")";
161 }
162 str << ";" << comment;
163 break;
164 } else {
165 for (Idx i = 0; i < conds.nbrDim(); i++) {
166 str << ")";
167 if (conds.val(i) != 0) break;
168 }
169 str << comment << "\n";
170 }
171 }
172 }
173 str << "\n}\n" << std::endl;
174 return str.str();
175 }
176
177 // Returns the header of the BN file.
178 template < GUM_Numeric GUM_SCALAR >
180 std::stringstream str;
181 std::string tab = " "; // poor tabulation
182 str << std::endl << "net {" << std::endl;
183 str << std::format(" name = {};\n", bn.propertyWithDefault("name", "unnamedBN"));
184 str << std::format(" software = \"aGrUM {}\";\n", GUM_VERSION);
185 str << " node_size = (50 50);" << std::endl;
186 str << "}" << std::endl;
187 return str.str();
188 }
189
190 // Returns a bloc defining a variable in the BN format.
191 template < GUM_Numeric GUM_SCALAR >
193 std::stringstream str;
194 std::string tab = " "; // poor tabulation
195 str << std::format("node {} {{\n", var.name());
196 str << tab << "states = (";
197
198 for (Idx i = 0; i < var.domainSize(); i++) {
199 str << var.label(i) << " ";
200 }
201
202 str << ");" << std::endl;
203 str << std::format("{}label = \"{}\";\n", tab, var.name());
204 str << std::format("{}ID = \"{}\";\n", tab, var.name());
205
206 str << "}" << std::endl;
207
208 return str.str();
209 }
210} /* namespace gum */
211
212#endif // DOXYGEN_SHOULD_SKIP_THIS
Base class for discrete random variable.
Class representing the minimal interface for Bayesian network with no numerical data.
Definition IBayesNet.h:75
Class for assigning/browsing values to tuples of discrete variables.
void add(const DiscreteVariable &v) final
Adds a new variable in the Instantiation.
Writes a IBayesNet in the BN format.
Definition netWriter.h:76
static std::string _header_(const IBayesNet< GUM_SCALAR > &bn)
NetWriter()
Default constructor.
std::string _variableCPT_(const Tensor< GUM_SCALAR > &cpt)
void _doWrite(std::ostream &output, const IBayesNet< GUM_SCALAR > &bn) final
Writes a Bayesian network in the output stream using the BN format.
~NetWriter() override
Destructor.
std::string _variableBloc_(const DiscreteVariable &var)
The generic class for storing (ordered) sequences of objects.
Definition sequence.h:994
aGrUM's Tensor is a multi-dimensional array with tensor operators.
Definition tensor.h:85
#define GUM_ERROR(type, msg)
Definition exceptions.h:76
Size Idx
Type for indexes.
Definition types.h:79
gum is the global namespace for all aGrUM entities
Definition agrum.h:46
Definition of class for BN file output manipulation.