aGrUM 2.3.2
a C++ library for (probabilistic) graphical models
ContextualDependenciesCNFWriter_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-2025 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-2025 *
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#pragma once
41
42
43#ifndef DOXYGEN_SHOULD_SKIP_THIS
44
45// to ease parsing in IDE
47
48namespace gum {
49 /* =========================================================================*/
50 /* === GUM_BN_WRITER === */
51 /* =========================================================================*/
52 // Default constructor.
53 template < typename GUM_SCALAR, template < class > class IApproximationPolicy >
54 INLINE
56 IApproximationPolicy >::ContextualDependenciesCNFWriter() {
57 GUM_CONSTRUCTOR(ContextualDependenciesCNFWriter)
58 }
59
60 // Default destructor.
61 template < typename GUM_SCALAR, template < class > class IApproximationPolicy >
62 INLINE
64 IApproximationPolicy >::~ContextualDependenciesCNFWriter() {
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 < typename GUM_SCALAR, template < class > class IApproximationPolicy >
76 std::ostream& output,
77 const IBayesNet< GUM_SCALAR >& bn) {
78 Instantiation Order;
79
80 for (auto node: bn.topologicalOrder())
81 Order.add(bn.variable(node));
82
83 if (!output.good()) GUM_ERROR(IOError, "Input/Output error : stream not writable.")
84
85 std::stringstream strfile;
86 std::stringstream strfile2;
87
88 Idx num = 0;
89 Idx numvar = 0;
90 Idx clause = 0;
91 std::stringstream clausstr;
92 std::stringstream clausstr2;
93 gum::HashTable< std::string, Idx > vartable;
94 gum::HashTable< std::string, Idx > protable;
95 gum::HashTable<
96 const gum::DiscreteVariable*,
97 gum::HashTable< std::string, gum::Sequence< gum::Sequence< gum::Instantiation* >* >* >* >
98 cptparamval;
99
100 for (auto node: bn.nodes()) {
101 std::stringstream str0;
102 const DiscreteVariable* var = &bn.variable(node);
103
104 for (Idx i = 0; i < var->domainSize(); i++) {
105 std::stringstream stri;
106 stri << var->name() << "_" << var->label(i);
107 vartable.insert(stri.str(), ++num);
108 strfile << num << "::" << stri.str() << "\n";
109 str0 << vartable[stri.str()] << " ";
110 }
111
112 str0 << "0\n";
113 clause++;
114 numvar++;
115 clausstr2 << str0.str();
116 const Tensor< GUM_SCALAR >& cpt = bn.cpt(node);
117 Instantiation inst(cpt);
118 inst.forgetMaster();
119 inst.reorder(Order);
120 cptparamval.insert(
121 var,
122 new gum::HashTable< std::string,
123 gum::Sequence< gum::Sequence< gum::Instantiation* >* >* >());
124
125 for (inst.setFirst(); !inst.end(); ++inst) {
126 if (this->fromExact(cpt[inst]) != 1) {
127 std::stringstream strk;
128 strk << this->fromExact(cpt[inst]);
129 std::string valp = strk.str();
130
131 if (!(cptparamval[var])->exists(valp)) {
132 (cptparamval[var])
133 ->insert(valp, new gum::Sequence< gum::Sequence< gum::Instantiation* >* >());
134
135 (*(cptparamval[var]))[valp]->insert(new gum::Sequence< gum::Instantiation* >);
136
137 if (this->fromExact(cpt[inst])) {
138 std::stringstream strinst;
139 strinst << var->name();
140 strinst << "_val=" << this->fromExact(cpt[inst]);
141
142 if (!protable.exists(strinst.str())) {
143 protable.insert(strinst.str(), ++num);
144 strfile << num << "::" << strinst.str() << "\n";
145 }
146 }
147 }
148
149 (*(cptparamval[var]))[valp]->front()->insert(new gum::Instantiation(inst));
150 }
151 }
152 }
153
154 std::stringstream str2;
155
156 while (!cptparamval.empty()) {
157 auto itvar = cptparamval.begin();
158
159 while (!(itvar.val())->empty()) {
160 auto itpvall = (itvar.val())->begin(); // needed here
161
162 for (auto pv: *itpvall.val()) {
163 gum::Idx linecount = 0;
164 gum::HashTable< std::string,
165 gum::HashTable< const gum::DiscreteVariable*,
166 std::pair< gum::Set< Idx >*,
167 gum::Set< Idx >* >* >* >
168 orderStruct; // set sizeof Hashtable
169
170 for (const auto* seqv: *pv) {
171 if (seqv->nbrDim() > 1) {
172 for (Idx iInst = 0; iInst < seqv->nbrDim(); iInst++) {
173 gum::Instantiation instpro(*seqv, false);
174 instpro.reorder(Order);
175 const gum::DiscreteVariable* var = &(seqv->variable(iInst));
176 instpro.erase(*var); // reorder instance to optimize make sure
177 // key unicity.
178
179 if (!orderStruct.exists(instpro.toString())) {
180 orderStruct.insert(
181 instpro.toString(),
182 new gum::HashTable< const gum::DiscreteVariable*,
183 std::pair< gum::Set< Idx >*, gum::Set< Idx >* >* >());
184 }
185
186 if (!orderStruct[instpro.toString()]->exists(var)) {
187 orderStruct[instpro.toString()]->insert(
188 var,
189 new std::pair< gum::Set< Idx >*, gum::Set< Idx >* >(
190 new gum::Set< Idx >,
191 new gum::Set< Idx >(
192 seqv->variable(iInst).domainSize()))); // set sizeof Hashtable
193 }
194
195 gum::HashTable< const gum::DiscreteVariable*,
196 std::pair< gum::Set< Idx >*, gum::Set< Idx >* >* >* orderStruct2
197 = orderStruct[instpro.toString()];
198 (*orderStruct2)[var]->first->insert(linecount);
199 (*orderStruct2)[var]->second->insert(seqv->val(iInst));
200 }
201 }
202
203 linecount += 1;
204 }
205
206 gum::Set< gum::Idx > elimination;
207 gum::Sequence< gum::Instantiation* >* newSeq = nullptr;
208
209 for (const auto& [first, second]: orderStruct) {
210 bool added = false;
211
212 for (const auto& [first2, second2]: *second) {
213 if (second2->second->size() == first2->domainSize()) {
214 if (!newSeq) newSeq = new gum::Sequence< gum::Instantiation* >();
215
216 if (!added) {
217 added = true;
218 newSeq->insert(
219 new gum::Instantiation(*((*pv)[(*(second2->first->begin()))]), false));
220 newSeq->back()->erase(*first2);
221 }
222
223 elimination = elimination + *(second2->first);
224 }
225 }
226 }
227
228 if (newSeq) {
229 (itpvall.val())->insert(newSeq);
230
231 for (Idx itelem = pv->size(); itelem > 0; itelem--) {
232 if (elimination.exists(itelem - 1)) {
233 delete ((*pv)[itelem - 1]);
234 pv->erase((*pv)[itelem - 1]);
235 }
236 }
237 }
238
239 while (!orderStruct.empty()) {
240 while (!(orderStruct.begin().val())->empty()) {
241 delete orderStruct.begin().val()->begin().val()->first;
242 delete orderStruct.begin().val()->begin().val()->second;
243 (orderStruct.begin().val())
244 ->erase((orderStruct.begin().val())->beginSafe()); // safe iterator needed here
245 }
246
247 delete orderStruct.begin().val();
248 orderStruct.erase(orderStruct.beginSafe()); // safe iterator needed here
249 }
250 }
251
252 while (!(itpvall.val())->empty()) {
253 auto itpv = (itpvall.val())->begin();
254
255 while (!(*itpv)->empty()) {
256 auto itseqv = (*itpv)->begin();
257
258 for (Idx i = 0; i < (*itseqv)->nbrDim(); i++) {
259 std::stringstream str;
260 str << (*itseqv)->variable(i).name() << "_" << (*itseqv)->val((*itseqv)->variable(i));
261 str2 << "-" << vartable[str.str()] << " ";
262 }
263
264 if (itpvall.key() != "0" && itpvall.key() != "0.0") {
265 std::stringstream strinst;
266 strinst << itvar.key()->name();
267 strinst << "_val=" << itpvall.key();
268 str2 << protable[strinst.str()];
269 }
270
271 str2 << " 0\n";
272 clause++;
273 delete (*itseqv);
274 (*itpv)->erase(itseqv);
275 }
276
277 delete (*itpv);
278 (itpvall.val())->erase(itpv);
279 }
280
281 delete (itpvall.val());
282 (itvar.val())->erase(itvar.val()->beginSafe()); // safe iterator needed here
283 }
284
285 delete (itvar.val());
286 cptparamval.erase(cptparamval.beginSafe()); // safe iterator needed here
287 }
288
289 clausstr << str2.str();
290
291 output << "p cnf " << num << " " << clause << "\neclauses " << numvar << "\n"
292 << clausstr.str() << clausstr2.str() << std::endl;
293 output.flush();
294 }
295
296 // Writes a Bayesian network in the referenced file using the BN format.
297 // If the file doesn't exist, it is created.
298 // If the file exists, it's content will be erased.
299 //
300 // @param filePath The path to the file used to write the Bayesian network.
301 // @param bn The Bayesian network writed in the file.
302 // @throws Raised if an I/O error occurs.
303 template < typename GUM_SCALAR, template < class > class IApproximationPolicy >
305 const std::string& filePath,
306 const IBayesNet< GUM_SCALAR >& bn) {
307 std::ofstream output(filePath.c_str(), std::ios_base::trunc);
308 std::ofstream outputvar((filePath + ".var").c_str(), std::ios_base::trunc);
309
310 if (!output.good()) GUM_ERROR(IOError, "Input/Output error : " << filePath << " not writable.")
311
312 std::stringstream strfile, strfile2;
313
314 if (!outputvar.good())
315 GUM_ERROR(IOError, "Input/Output error : " << (filePath + ".var") << " not writable.")
316
317 Idx num = 0;
318 Idx numvar = 0;
319 Idx clause = 0;
320 std::stringstream clausstr, clausstr2;
321 gum::HashTable< std::string, Idx > vartable;
322 gum::HashTable< std::string, Idx > protable;
323 gum::HashTable<
324 const gum::DiscreteVariable*,
325 gum::HashTable< std::string, gum::Sequence< gum::Sequence< gum::Instantiation* >* >* >* >
326 cptparamval;
327
328 Instantiation Order;
329
330 for (auto node: bn.topologicalOrder())
331 Order.add(bn.variable(node));
332
333 for (auto node: bn.nodes()) {
334 std::stringstream str0;
335 const DiscreteVariable* var = &bn.variable(node);
336
337 for (Idx i = 0; i < bn.variable(node).domainSize(); i++) {
338 std::stringstream stri;
339 stri << var->name() << "_" << var->label(i);
340 vartable.insert(stri.str(), ++num);
341 strfile << num << "::" << stri.str() << "\n";
342 str0 << vartable[stri.str()] << " ";
343 }
344
345 str0 << "0\n";
346 clause++;
347 numvar++;
348 clausstr2 << str0.str();
349 const Tensor< GUM_SCALAR >& cpt = bn.cpt(node);
350 Instantiation inst(cpt);
351 inst.forgetMaster();
352 inst.reorder(Order);
353 cptparamval.insert(
354 var,
355 new gum::HashTable< std::string,
356 gum::Sequence< gum::Sequence< gum::Instantiation* >* >* >());
357
358 for (inst.setFirst(); !inst.end(); ++inst) {
359 if (this->fromExact(cpt[inst]) != 1) {
360 std::stringstream strk;
361 strk << this->fromExact(cpt[inst]);
362 std::string valp = strk.str();
363
364 if (!(cptparamval[var])->exists(valp)) {
365 (cptparamval[var])
366 ->insert(
367 valp,
368 new gum::Sequence< gum::Sequence< gum::Instantiation* >* >()); // remember
369 // to
370 // verify
371 // protocole for
372 // param = to 1
373
374 (*(cptparamval[var]))[valp]->insert(new gum::Sequence< gum::Instantiation* >);
375
376 if (this->fromExact(cpt[inst])) {
377 std::stringstream strinst;
378 strinst << var->name();
379 strinst << "_val=" << this->fromExact(cpt[inst]);
380
381 if (!protable.exists(strinst.str())) {
382 protable.insert(strinst.str(), ++num);
383 strfile << num << "::" << strinst.str() << "\n";
384 }
385 }
386 }
387
388 (*(cptparamval[var]))[valp]->front()->insert(new gum::Instantiation(inst));
389 }
390 }
391 }
392
393 std::stringstream str2;
394
395 while (!cptparamval.empty()) {
396 auto itvar = cptparamval.begin();
397
398 while (!(itvar.val())->empty()) {
399 auto itpvall = (itvar.val())->begin();
400
401 for (auto pv: *itpvall.val()) {
402 gum::Idx linecount = 0;
403 gum::HashTable< std::string,
404 gum::HashTable< const gum::DiscreteVariable*,
405 std::pair< gum::Set< Idx >*,
406 gum::Set< Idx >* >* >* >
407 orderStruct; // set sizeof Hashtable
408
409 gum::Set< gum::Idx > elimination;
410 gum::HashTable< std::string, gum::Instantiation* > newSeqpre;
411
412 for (const auto* seqv: *pv) {
413 if (seqv->nbrDim() > 1) {
414 for (Idx iInst = 0; iInst < seqv->nbrDim(); iInst++) {
415 auto instpro = new gum::Instantiation(*seqv, false);
416 const gum::DiscreteVariable* var = &(seqv->variable(iInst));
417 instpro->erase(*var);
418 instpro->reorder(Order);
419
420 if (!orderStruct.exists(instpro->toString())
421 && !newSeqpre.exists(instpro->toString())) {
422 orderStruct.insert(
423 instpro->toString(),
424 new gum::HashTable< const gum::DiscreteVariable*,
425 std::pair< gum::Set< Idx >*, gum::Set< Idx >* >* >());
426 }
427
428 if (orderStruct.exists(instpro->toString())
429 && !orderStruct[instpro->toString()]->exists(var)) {
430 orderStruct[instpro->toString()]->insert(
431 var,
432 new std::pair< gum::Set< Idx >*, gum::Set< Idx >* >(
433 new gum::Set< Idx >,
434 new gum::Set< Idx >(
435 seqv->variable(iInst).domainSize()))); // set sizeof Hashtable
436 }
437
438 if (orderStruct.exists(instpro->toString())
439 && !newSeqpre.exists(instpro->toString())) {
440 gum::HashTable< const gum::DiscreteVariable*,
441 std::pair< gum::Set< Idx >*, gum::Set< Idx >* >* >* orderStruct2
442 = orderStruct[instpro->toString()];
443 (*orderStruct2)[var]->first->insert(linecount);
444 (*orderStruct2)[var]->second->insert(seqv->val(iInst));
445
446 if ((*orderStruct2)[var]->second->size() == var->domainSize()) {
447 newSeqpre.insert(instpro->toString(), instpro);
448
449 for (const auto& elt: *orderStruct2) {
450 elimination = elimination + *(elt.second->first);
451 delete (elt.second->first);
452 delete (elt.second->second);
453 delete (elt.second);
454 }
455
456 orderStruct2->clear();
457
458 delete orderStruct2;
459 orderStruct.erase(instpro->toString());
460 } else delete instpro;
461 } else if (newSeqpre.exists(instpro->toString())) {
462 elimination.insert(linecount);
463 delete instpro;
464 }
465 }
466 }
467
468 linecount += 1;
469 }
470
471 gum::Sequence< gum::Instantiation* >* newSeq = nullptr;
472
473 if (!newSeqpre.empty()) {
474 newSeq = new gum::Sequence< gum::Instantiation* >();
475
476 for (auto& elt: newSeqpre)
477 newSeq->insert(elt.second);
478
479 (itpvall.val())->insert(newSeq);
480
481 for (Idx itelem = pv->size(); itelem > 0; itelem--) {
482 if (elimination.exists(itelem - 1)) {
483 delete ((*pv)[itelem - 1]);
484 pv->erase((*pv)[itelem - 1]);
485 }
486 }
487 }
488
489 while (!orderStruct.empty()) {
490 while (!(orderStruct.begin().val())->empty()) {
491 delete orderStruct.begin().val()->begin().val()->first;
492 delete orderStruct.begin().val()->begin().val()->second;
493 (orderStruct.begin().val())->erase(orderStruct.begin().val()->beginSafe()); // safe
494 // iterator
495 // needed here
496 }
497
498 delete orderStruct.begin().val();
499 orderStruct.erase(orderStruct.beginSafe()); // safe iterator needed here
500 }
501 }
502
503 while (!(itpvall.val())->empty()) {
504 gum::Sequence< gum::Sequence< gum::Instantiation* >* >::iterator_safe itpv
505 = (itpvall.val())->begin();
506
507 while (!(*itpv)->empty()) {
509
510 for (Idx i = 0; i < (*itseqv)->nbrDim(); i++) {
511 std::stringstream str;
512 str << (*itseqv)->variable(i).name() << "_" << (*itseqv)->val((*itseqv)->variable(i));
513 str2 << "-" << vartable[str.str()] << " ";
514 }
515
516 /*if (itpvall.key().compare("0") != 0 &&
517 itpvall.key().compare("0.0") != 0) { */
518 if (itpvall.key() != "0" && itpvall.key() != "0.0") {
519 std::stringstream strinst;
520 strinst << itvar.key()->name();
521 strinst << "_val=" << itpvall.key();
522 str2 << protable[strinst.str()];
523 }
524
525 str2 << " 0\n";
526 clause++;
527 delete (*itseqv);
528 (*itpv)->erase((*itpv)->beginSafe()); // safe iterator needed here
529 }
530
531 delete (*itpv);
532 (itpvall.val())->erase(itpvall.val()->beginSafe()); // safe iterator needed here
533 }
534
535 delete (itpvall.val());
536 (itvar.val())->erase(itvar.val()->beginSafe()); // safe iterator needed here
537 }
538
539 delete (itvar.val());
540 cptparamval.erase(cptparamval.beginSafe()); // safe iterator needed here
541 }
542
543 clausstr << str2.str();
544
545 output << "p cnf " << num << " " << clause << "\neclauses " << numvar << "\n"
546 << clausstr.str() << clausstr2.str() << std::endl;
547 output.flush();
548 outputvar << strfile.str();
549 outputvar.flush();
550
551 outputvar.close();
552 output.close();
553
554 if (outputvar.fail()) GUM_ERROR(IOError, "Writing in the ostream failed.")
555
556 if (output.fail()) GUM_ERROR(IOError, "Writing in the ostream failed.")
557 }
558
559} /* namespace gum */
560
561#endif // DOXYGEN_SHOULD_SKIP_THIS
Definition of classe for BN file output manipulation.
<agrum/BN/io/cnf/ContextualDependenciesCNFWriter.h>
void _doWrite(std::ostream &output, const IBayesNet< GUM_SCALAR > &bn) final
Writes a Bayesian network in the output stream using the BN format.
Base class for discrete random variable.
virtual Size domainSize() const =0
The class for generic Hash Tables.
Definition hashTable.h:637
bool exists(const Key &key) const
Checks whether there exists an element with a given key in the hashtable.
bool empty() const noexcept
Indicates whether the hash table is empty.
value_type & insert(const Key &key, const Val &val)
Adds a new element (actually a copy of this element) into the hash table.
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.
const Key & back() const
Returns the last element of the sequence.
void insert(const Key &k)
Insert an element at the end of the sequence.
The generic class for storing (ordered) sequences of objects.
Definition sequence.h:972
SequenceIteratorSafe< Key > iterator_safe
Types for STL compliance.
Definition sequence.h:985
bool exists(const Key &k) const
Indicates whether a given elements belong to the set.
Definition set_tpl.h:533
void insert(const Key &k)
Inserts a new element into the set.
Definition set_tpl.h:539
aGrUM's Tensor is a multi-dimensional array with tensor operators.
Definition tensor.h:85
#define GUM_ERROR(type, msg)
Definition exceptions.h:72
Size Idx
Type for indexes.
Definition types.h:79
gum is the global namespace for all aGrUM entities
Definition agrum.h:46