aGrUM 3.1.1
a C++ library for (probabilistic) graphical models
FactorisedValuesCNFWriter_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/cnf/FactorisedValuesCNFWriter.h> // to ease IDE parser
45#ifndef DOXYGEN_SHOULD_SKIP_THIS
46
47// to ease parsing in IDE
49
50namespace gum {
51
52 /* =========================================================================*/
53 /* === GUM_BN_WRITER === */
54 /* =========================================================================*/
55 // Default constructor.
56 template < GUM_Numeric GUM_SCALAR, template < class > class IApproximationPolicy >
58 GUM_CONSTRUCTOR(FactorisedValuesCNFWriter);
59 }
60
61 // Default destructor.
62 template < GUM_Numeric GUM_SCALAR, template < class > class IApproximationPolicy >
64 GUM_DESTRUCTOR(FactorisedValuesCNFWriter);
65 }
66
67 //
68 // Writes a Bayesian network in the output stream using the BN format.
69 //
70 // @param output The output stream.
71 // @param bn The Bayesian network writen in output.
72 // @throws Raised if an I/O error occurs.
73 template < GUM_Numeric GUM_SCALAR, template < class > class IApproximationPolicy >
75 std::ostream& output,
76 const IBayesNet< GUM_SCALAR >& bn) {
77 if (!output.good()) GUM_ERROR(IOError, "Input/Output error : stream not writable.")
78
79 std::stringstream strfile, strfile2;
80
81 Idx num = 0;
82 Idx numparam = 0;
83
84 for (auto node: bn.nodes())
85 numparam += bn.variable(node).domainSize();
86
87 Idx clause = 0;
88 std::stringstream clausstr;
89 gum::HashTable< std::string, Idx > vartable; // key name::label val num;
90 gum::HashTable< std::string, Idx > protable;
91
92 for (auto node: bn.nodes()) {
93 for (Idx i = 0; i < bn.variable(node).domainSize(); i++) {
94 auto str = std::format("{}_{}", bn.variable(node).name(), bn.variable(node).label(i));
95 vartable.insert(str, ++num);
96 strfile << std::format("{}::{}\n", num, str);
97 }
98
99 const Tensor< GUM_SCALAR >& cpt = bn.cpt(node);
100
101 Instantiation inst(cpt);
102
103 for (inst.setFirst(); !inst.end(); ++inst) {
104 auto strinst = std::format("{}_val={}", inst.toString(), this->fromExact(cpt[inst]));
105
106 if (!protable.exists(strinst)) {
107 protable.insert(inst.toString(), ++numparam);
108 strfile2 << std::format("{}::{}\n", numparam, strinst);
109 }
110 }
111 }
112
113 for (auto node: bn.nodes()) {
114 std::stringstream str0, str2;
115
116 for (Idx i = 0; i < bn.variable(node).domainSize(); i++) {
117 auto stri = std::format("{}_{}",
118 bn.variable(node).name(),
119 bn.variable(node).label(i)); //= bn.variable(iter).name()+"_"+
120 // bn.variable(iter).label( i ) ;
121 str0 << std::format("{} ", vartable[stri]);
122 }
123
124 str0 << "0\n";
125 clause++;
126 clausstr << str0.str();
127 const Tensor< GUM_SCALAR >& cpt = bn.cpt(node);
128 Instantiation inst(cpt);
129
130 for (inst.setFirst(); !inst.end(); ++inst) {
131 if (this->fromExact(cpt[inst]) != 1.0) {
132 for (Idx i = 0; i < inst.nbrDim(); i++) {
133 auto str = std::format("{}_{}", inst.variable(i).name(), inst.val(inst.variable(i)));
134 str2 << std::format("-{} ", vartable[str]);
135 }
136
137 if (this->fromExact(cpt[inst])) {
138 auto strinst
139 = std::format("{}_val={}", bn.variable(node).name(), this->fromExact(cpt[inst]));
140 str2 << protable[strinst];
141 }
142
143 str2 << " 0\n";
144 clause++;
145 }
146 }
147
148 clausstr << str2.str();
149 }
150
151 output << std::format("p cnf {} {}\n", num + numparam, clause) << clausstr.str() << '\n';
152 output.flush();
153 }
154
155 // Writes a Bayesian network in the referenced file using the BN format.
156 // If the file doesn't exists, it is created.
157 // If the file exists, it's content will be erased.
158 //
159 // @param filePath The path to the file used to write the Bayesian network.
160 // @param bn The Bayesian network writed in the file.
161 // @throws Raised if an I/O error occurs.
162 template < GUM_Numeric GUM_SCALAR, template < class > class IApproximationPolicy >
164 std::string_view filePath,
165 const IBayesNet< GUM_SCALAR >& bn) {
166 std::ofstream output(std::filesystem::path{filePath}, std::ios_base::trunc);
167 std::ofstream outputvar(std::string{filePath} + ".var", std::ios_base::trunc);
168
169 if (!output.good()) GUM_ERROR(IOError, "Input/Output error : " << filePath << " not writable.")
170
171 std::stringstream strfile, strfile2;
172
173 if (!outputvar.good())
174 GUM_ERROR(IOError,
175 "Input/Output error : " << (std::string(filePath) + ".var") << " not writable.")
176
177 Idx num = 0;
178 Idx numparam = 0;
179
180 for (auto node: bn.nodes())
181 numparam += bn.variable(node).domainSize();
182
183 Idx clause = 0;
184 std::stringstream clausstr;
185 gum::HashTable< std::string, Idx > vartable; // key name::label val num;
186 gum::HashTable< std::string, Idx > protable;
187
188 for (auto node: bn.nodes()) {
189 const auto& var = bn.variable(node);
190
191 for (Idx i = 0; i < var.domainSize(); i++) {
192 auto str = std::format("{}_{}", var.name(), var.label(i));
193 vartable.insert(str, ++num);
194 strfile << std::format("{}::{}\n", num, str);
195 }
196
197 const Tensor< GUM_SCALAR >& cpt = bn.cpt(node);
198
199 Instantiation inst(cpt);
200
201 for (inst.setFirst(); !inst.end(); ++inst) {
202 if (this->fromExact(cpt[inst]) && this->fromExact(cpt[inst]) != 1.0) {
203 auto strinst = std::format("{}_val={}", var.name(), this->fromExact(cpt[inst]));
204
205 if (!protable.exists(strinst)) {
206 protable.insert(strinst, ++numparam);
207 strfile2 << std::format("{}::{}\n", numparam, strinst);
208 }
209 }
210 }
211 }
212
213 for (auto node: bn.nodes()) {
214 std::stringstream str0, str2;
215
216 for (Idx i = 0; i < bn.variable(node).domainSize(); i++) {
217 auto stri = std::format("{}_{}",
218 bn.variable(node).name(),
219 bn.variable(node).label(i)); //= bn.variable(iter).name()+"_"+
220 // bn.variable(iter).label( i ) ;
221 str0 << std::format("{} ", vartable[stri]);
222 }
223
224 str0 << "0\n";
225 clause++;
226 clausstr << str0.str();
227 const Tensor< GUM_SCALAR >& cpt = bn.cpt(node);
228 Instantiation inst(cpt);
229
230 for (inst.setFirst(); !inst.end(); ++inst) {
231 if (this->fromExact(cpt[inst]) != 1.0) {
232 for (Idx i = 0; i < inst.nbrDim(); i++) {
233 auto str = std::format("{}_{}", inst.variable(i).name(), inst.val(inst.variable(i)));
234 str2 << std::format("-{} ", vartable[str]);
235 }
236
237 if (this->fromExact(cpt[inst])) {
238 auto strinst
239 = std::format("{}_val={}", bn.variable(node).name(), this->fromExact(cpt[inst]));
240 str2 << protable[strinst];
241 }
242
243 str2 << " 0\n";
244 clause++;
245 }
246 }
247
248 clausstr << str2.str();
249 }
250
251 output << std::format("p cnf {} {}\n", num + numparam, clause) << clausstr.str() << '\n';
252 output.flush();
253 outputvar << strfile.str() << strfile2.str();
254 outputvar.flush();
255 outputvar.close();
256 output.close();
257
258 if (outputvar.fail()) GUM_ERROR(IOError, "Writing in the ostream failed.")
259
260 if (output.fail()) GUM_ERROR(IOError, "Writing in the ostream failed.")
261 }
262
263 // Returns a bloc defining a variable's CPT in the BN format.
264 /* template<GumScalar GUM_SCALAR> INLINE
265 std::string
266 OCNFWriter<GUM_SCALAR>:: _variableCPT_( const Tensor<GUM_SCALAR>& cpt )
267 {
268 std::stringstream str;
269 str << "";
270 return str.str();
271 }
272
273 // Returns the header of the BN file.
274 template<GumScalar GUM_SCALAR> INLINE
275 std::string
276 OCNFWriter<GUM_SCALAR>:: _header_( const IBayesNet<GUM_SCALAR>& ) {
277 std::stringstream str;
278 str << "";
279 return str.str();
280 }
281
282 // Returns a bloc defining a variable in the BN format.
283 template<GumScalar GUM_SCALAR> INLINE
284 std::string
285 OCNFWriter<GUM_SCALAR>:: _variableBloc_( const DiscreteVariable& var ) {
286 std::stringstream str;
287 str << "" ;
288 return str.str();
289 }*/
290
291 // Returns the modalities labels of the variables in varsSeq
292
293} /* namespace gum */
294
295#endif // DOXYGEN_SHOULD_SKIP_THIS
Definition of classe for BN file output manipulation.
<agrum/BN/io/cnf/FactorisedValuesCNFWriter.h>
~FactorisedValuesCNFWriter() override
Destructor.
void _doWrite(std::ostream &output, const IBayesNet< GUM_SCALAR > &bn) final
Writes a Bayesian network in the output stream using the BN format.
FactorisedValuesCNFWriter()
Default constructor.
The class for generic Hash Tables.
Definition hashTable.h:640
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.
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