aGrUM 3.1.1
a C++ library for (probabilistic) graphical models
BIFWriter_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
44#include <agrum/BN/io/BIF/BIFWriter.h> // to ease IDE parser
45#ifndef DOXYGEN_SHOULD_SKIP_THIS
46
47# include <agrum/agrum.h>
48
49// to ease parsing in IDE
51
52namespace gum {
53
54 /* =========================================================================*/
55 /* === GUM_BIF_WRITER === */
56 /* =========================================================================*/
57 // Default constructor.
58 template < GUM_Numeric GUM_SCALAR >
60 GUM_CONSTRUCTOR(BIFWriter);
61 }
62
63 // Default destructor.
64 template < GUM_Numeric GUM_SCALAR >
66 GUM_DESTRUCTOR(BIFWriter);
67 }
68
69 //
70 // Writes a Bayesian network in the output stream using the BIF format.
71 //
72 // @param ouput The output stream.
73 // @param bn The Bayesian network writen in output.
74 // @throws Raised if an I/O error occurs.
75 template < GUM_Numeric GUM_SCALAR >
76 void BIFWriter< GUM_SCALAR >::_doWrite(std::ostream& output, const IBayesNet< GUM_SCALAR >& bn) {
77 if (!output.good()) { GUM_ERROR(IOError, "Input/Output error : stream not writable.") }
78
79 output << _header_(bn) << std::endl;
80
81 for (const auto node: bn.nodes()) {
82 output << _variableBloc_(bn.variable(node)) << std::endl;
83 }
84
85 for (const auto node: bn.nodes()) {
86 const Tensor< GUM_SCALAR >& proba = bn.cpt(node);
87 output << _variableCPT_(proba);
88 }
89
90 output << std::endl;
91
92 output.flush();
93
94 if (output.fail()) { GUM_ERROR(IOError, "Writing in the ostream failed.") }
95 }
96
97 // Writes a Bayesian network in the referenced file using the BIF format.
98 // If the file doesn't exists, it is created.
99 // If the file exists, it's content will be erased.
100 //
101 // @param filePath The path to the file used to write the Bayesian network.
102 // @param bn The Bayesian network writed in the file.
103 // @throws Raised if an I/O error occurs.
104 template < GUM_Numeric GUM_SCALAR >
105 void BIFWriter< GUM_SCALAR >::_doWrite(std::string_view filePath,
106 const IBayesNet< GUM_SCALAR >& bn) {
107 std::ofstream output(std::filesystem::path{filePath}, std::ios_base::trunc);
108
109 _doWrite(output, bn);
110
111 output.close();
112 if (output.fail()) { GUM_ERROR(IOError, "Writing in the ostream failed.") }
113 }
114
115 // Returns a bloc defining a variable's CPT in the BIF format.
116 template < GUM_Numeric GUM_SCALAR >
118 std::stringstream str;
119 std::string tab = " "; // poor tabulation
120
121 if (cpt.nbrDim() == 1) {
122 Instantiation inst(cpt);
123 str << std::format("probability ({}) {{\n",
124 this->_onlyValidCharsInName(cpt.variable(0).name()));
125 str << tab << "table";
126
127 for (inst.setFirst(); !inst.end(); ++inst) {
128 str << std::format(" {}", cpt[inst]);
129 }
130
131 str << ";" << std::endl << "}" << std::endl;
132 } else if (cpt.domainSize() > 1) {
133 Instantiation inst(cpt);
134 Instantiation condVars; // Instantiation on the conditioning variables
135 const Sequence< const DiscreteVariable* >& varsSeq = cpt.variablesSequence();
136 str << std::format("probability ({} | ",
137 this->_onlyValidCharsInName((varsSeq[(Idx)0])->name()));
138
139 for (Idx i = 1; i < varsSeq.size(); i++) {
140 if (i > 1) str << ", ";
141 str << this->_onlyValidCharsInName(varsSeq[i]->name());
142 condVars << *(varsSeq[i]);
143 }
144 str << ") {" << std::endl;
145
146 for (inst.setFirstIn(condVars); !inst.end(); inst.incIn(condVars)) {
147 str << std::format("{}({})", tab, _variablesLabels_(varsSeq, inst));
148 // Writing the probabilities of the variable
149
150 for (inst.setFirstOut(condVars); !inst.end(); inst.incOut(condVars)) {
151 str << std::format(" {}", cpt[inst]);
152 }
153
154 str << ";" << std::endl;
155
156 inst.unsetOverflow();
157 }
158
159 str << "}" << std::endl;
160 }
161
162 return str.str();
163 }
164
165 // Returns the header of the BIF file.
166 template < GUM_Numeric GUM_SCALAR >
168 std::stringstream str;
169 std::string tab = " "; // poor tabulation
170 str << std::format("network \"{}\" {{\n", bn.propertyWithDefault("name", "unnamedBN"));
171 str << std::format("// written by aGrUM {}\n", GUM_VERSION);
172 str << "}" << std::endl;
173 return str.str();
174 }
175
176 // Returns a bloc defining a variable in the BIF format.
177 template < GUM_Numeric GUM_SCALAR >
179 std::stringstream str;
180 std::string tab = " "; // poor tabulation
181 str << std::format("variable {} {{\n", this->_onlyValidCharsInName(var.name()));
182 str << std::format("{}type discrete[{}] {{", tab, var.domainSize());
183
184 for (Idx i = 0; i < var.domainSize(); i++) {
185 if (i > 0) str << ", ";
186 str << this->_onlyValidCharsInName(var.label(i));
187 }
188
189 str << "};" << std::endl;
190
191 str << "}" << std::endl;
192 return str.str();
193 }
194
195 // Returns the modalities labels of the variables in varsSeq
196 template < GUM_Numeric GUM_SCALAR >
197 std::string
199 const Instantiation& inst) {
200 std::stringstream str;
201 const DiscreteVariable* varPtr = nullptr;
202
203 for (Idx i = 1; i < varsSeq.size(); i++) {
204 if (i > 1) str << ", ";
205 varPtr = varsSeq[i];
206 str << this->_onlyValidCharsInName(varPtr->label(inst.val(*varPtr)));
207 }
208 return str.str();
209 }
210
211 template < GUM_Numeric GUM_SCALAR >
213 this->_validCharInNamesCheck(bn);
214 }
215} /* namespace gum */
216
217#endif // DOXYGEN_SHOULD_SKIP_THIS
Definition of class for BIF file output manipulation.
Writes a IBayesNet in the BIF format.
Definition BIFWriter.h:79
std::string _variablesLabels_(const Sequence< const DiscreteVariable * > &varsSeq, const Instantiation &inst)
BIFWriter()
Default constructor.
std::string _variableCPT_(const Tensor< GUM_SCALAR > &cpt)
std::string _variableBloc_(const DiscreteVariable &var)
void _syntacticalCheck(const IBayesNet< GUM_SCALAR > &bn) final
Check whether the BN is syntactically correct for BIF format.
~BIFWriter() override
Destructor.
void _doWrite(std::ostream &output, const IBayesNet< GUM_SCALAR > &bn) final
Writes a Bayesian network in the output stream using the BIF format.
std::string _header_(const IBayesNet< GUM_SCALAR > &bn)
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.
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