aGrUM 3.1.1
a C++ library for (probabilistic) graphical models
GeneralizedCNFWriter_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/GeneralizedCNFWriter.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(GeneralizedCNFWriter);
59 }
60
61 // Default destructor.
62 template < GUM_Numeric GUM_SCALAR, template < class > class IApproximationPolicy >
64 GUM_DESTRUCTOR(GeneralizedCNFWriter);
65 }
66
67 //
68 // Writes a Bayesian network in the output stream using the BN format.
69 //
70 // @param ouput 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 Size num = 0;
82 Size 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 const auto& var = bn.variable(node);
94
95 for (Idx i = 0; i < var.domainSize(); i++) {
96 auto str = std::format("{}_{}", var.name(), var.label(i));
97 vartable.insert(str, ++num);
98 strfile << std::format("{}::{}\n", num, str);
99 }
100
101 const Tensor< GUM_SCALAR >& cpt = bn.cpt(node);
102
103 Instantiation inst(cpt);
104
105 for (inst.setFirst(); !inst.end(); ++inst) {
106 auto strinst = std::format("{}_val={}", inst.toString(), this->fromExact(cpt[inst]));
107
108 protable.insert(inst.toString(), ++numparam);
109 strfile2 << std::format("{}::{}\n", numparam, strinst);
110 }
111 }
112
113 for (auto node: bn.nodes()) {
114 const auto& var = bn.variable(node);
115 std::stringstream str0, str1, str2, str3;
116
117 for (Idx i = 0; i < var.domainSize(); i++) {
118 auto stri
119 = std::format("{}_{}", var.name(), var.label(i)); //= bn.variable(iter).name()+"_"+
120 // bn.variable(iter).label( i ) ;
121 str0 << std::format("{} ", vartable[stri]);
122
123 for (Idx j = i + 1; j < var.domainSize(); j++) {
124 auto strj = std::format("{}_{}", var.name(), var.label(j));
125 str1 << std::format("-{} -{} 0\n", vartable[stri], vartable[strj]);
126 clause++;
127 }
128 }
129
130 str0 << "0\n";
131 clause++;
132 clausstr << str0.str() << str1.str();
133 const Tensor< GUM_SCALAR >& cpt = bn.cpt(node);
134 Instantiation inst(cpt);
135
136 for (inst.setFirst(); !inst.end(); ++inst) {
137 for (Idx i = 0; i < inst.nbrDim(); i++) {
138 auto str = std::format("{}_{}", inst.variable(i).name(), inst.val(inst.variable(i)));
139 str2 << std::format("-{} ", vartable[str]);
140 str3 << std::format("-{} {} 0\n", protable[inst.toString()], vartable[str]);
141 clause++;
142 }
143
144 str2 << std::format("{} 0\n", protable[inst.toString()]);
145 clause++;
146 }
147
148 clausstr << str2.str() << str3.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 auto strinst = std::format("{}_val={}", inst.toString(), this->fromExact(cpt[inst]));
203
204 protable.insert(inst.toString(), ++numparam);
205 strfile2 << std::format("{}::{}\n", numparam, strinst);
206 }
207 }
208
209 for (auto node: bn.nodes()) {
210 const auto& var = bn.variable(node);
211 std::stringstream str0, str1, str2, str3;
212
213 for (Idx i = 0; i < var.domainSize(); i++) {
214 auto stri
215 = std::format("{}_{}", var.name(), var.label(i)); //= bn.variable(iter).name()+"_"+
216 // bn.variable(iter).label( i ) ;
217 str0 << std::format("{} ", vartable[stri]);
218
219 for (Idx j = i + 1; j < var.domainSize(); j++) {
220 auto strj = std::format("{}_{}", var.name(), var.label(j));
221 str1 << std::format("-{} -{} 0\n", vartable[stri], vartable[strj]);
222 clause++;
223 }
224 }
225
226 str0 << "0\n";
227 clause++;
228 clausstr << str0.str() << str1.str();
229 const Tensor< GUM_SCALAR >& cpt = bn.cpt(node);
230 Instantiation inst(cpt);
231
232 for (inst.setFirst(); !inst.end(); ++inst) {
233 for (Idx i = 0; i < inst.nbrDim(); i++) {
234 auto str = std::format("{}_{}", inst.variable(i).name(), inst.val(inst.variable(i)));
235 str2 << std::format("-{} ", vartable[str]);
236 str3 << std::format("-{} {} 0\n", protable[inst.toString()], vartable[str]);
237 clause++;
238 }
239
240 str2 << std::format("{} 0\n", protable[inst.toString()]);
241 clause++;
242 }
243
244 clausstr << str2.str() << str3.str();
245 }
246
247 output << std::format("p cnf {} {}\n", num + numparam, clause) << clausstr.str() << '\n';
248 output.flush();
249 outputvar << strfile.str() << strfile2.str();
250 outputvar.flush();
251 outputvar.close();
252 output.close();
253
254 if (outputvar.fail()) GUM_ERROR(IOError, "Writing in the ostream failed.")
255
256 if (output.fail()) GUM_ERROR(IOError, "Writing in the ostream failed.")
257 }
258
259 // Returns a bloc defining a variable's CPT in the BN format.
260 /*template<GumScalar GUM_SCALAR, template<class> class IApproximationPolicy >
261 std::string
262 CNFWriter<GUM_SCALAR>:: _variableCPT_( const Tensor<GUM_SCALAR>& cpt ) {
263 std::stringstream str;
264 str << "";
265 return str.str();
266 }
267
268 // Returns the header of the BN file.
269 template<GumScalar GUM_SCALAR,> INLINE
270 std::string
271 CNFWriter<GUM_SCALAR>:: _header_( const IBayesNet<GUM_SCALAR>& ) {
272 std::stringstream str;
273 str << "";
274 return str.str();
275 }
276
277 // Returns a bloc defining a variable in the BN format.
278 template<GumScalar GUM_SCALAR> INLINE
279 std::string
280 CNFWriter<GUM_SCALAR>:: _variableBloc_( const DiscreteVariable& var ) {
281 std::stringstream str;
282 str << "" ;
283 return str.str();
284 }*/
285
286 // Returns the modalities labels of the variables in varsSeq
287
288} /* namespace gum */
289
290#endif // DOXYGEN_SHOULD_SKIP_THIS
Definition of classe for BN file output manipulation.
<agrum/BN/io/cnf/GeneralizedCNFWriter.h>
GeneralizedCNFWriter()
Default constructor.
void _doWrite(std::ostream &output, const IBayesNet< GUM_SCALAR > &bn) final
Writes a Bayesian network in the output stream using the BN format.
~GeneralizedCNFWriter() override
Destructor.
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
std::size_t Size
In aGrUM, hashed values are unsigned long int.
Definition types.h:74
Size Idx
Type for indexes.
Definition types.h:79
gum is the global namespace for all aGrUM entities
Definition agrum.h:46