aGrUM 3.3.2
a C++ library for (probabilistic) graphical models
credalNet_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/agrum.h>
45
48#include <agrum/CN/credalNet.h>
49
52
53namespace gum {
54 namespace credal {
55
56 template < GUM_Numeric GUM_SCALAR >
59
60 _src_bn_ = BayesNet< GUM_SCALAR >();
61 _src_bn_min_ = BayesNet< GUM_SCALAR >();
62 _src_bn_max_ = BayesNet< GUM_SCALAR >();
63
64 GUM_CONSTRUCTOR(CredalNet);
65 }
66
67 template < GUM_Numeric GUM_SCALAR >
68 NodeId CredalNet< GUM_SCALAR >::addVariable(std::string_view name, const Size& card) {
69 LabelizedVariable var(name, "node " + std::string{name}, card);
70
71 NodeId a = _src_bn_.add(var);
72 NodeId b = _src_bn_min_.add(var);
73 NodeId c = _src_bn_max_.add(var);
74
75 if (a != b || a != c /*|| b != c*/)
77 "addVariable : not the same id over all networks : " << a << ", " << b << ", "
78 << c);
79
80 return a;
81 }
82
83 template < GUM_Numeric GUM_SCALAR >
84 void CredalNet< GUM_SCALAR >::addArc(const NodeId& tail, const NodeId& head) {
85 _src_bn_.addArc(tail, head);
86 _src_bn_min_.addArc(tail, head);
87 _src_bn_max_.addArc(tail, head);
88 }
89
90 template < GUM_Numeric GUM_SCALAR >
92 const NodeId& id,
93 const std::vector< std::vector< std::vector< GUM_SCALAR > > >& cpt) {
94 const Tensor< GUM_SCALAR >* const tensor(&_src_bn_.cpt(id));
95
96 auto var_dSize = _src_bn_.variable(id).domainSize();
97
98 if (auto entry_size = tensor->domainSize() / var_dSize; cpt.size() != entry_size)
100 "setCPTs : entry sizes of cpts does not match for node id : "
101 << id << " : " << cpt.size() << " != " << entry_size);
102
103 for (const auto& cset: cpt) {
104 if (cset.size() == 0)
106 "setCPTs : vertices in credal set does not match for node id : "
107 << id << " with 0 vertices");
108
109 for (const auto& vertex: cset) {
110 if (vertex.size() != var_dSize)
112 "setCPTs : variable modalities in cpts does "
113 "not match for node id : "
114 << id << " with vertex " << vertex << " : " << vertex.size()
115 << " != " << var_dSize);
116
117 GUM_SCALAR sum = 0;
118
119 for (const auto& prob: vertex) {
120 sum += prob;
121 }
122
123 if (!gum::isCloseToOne(sum, GUM_SCALAR(config().epsilonStandard())))
125 "setCPTs : a vertex coordinates does not "
126 "sum to one for node id : "
127 << id << " with vertex " << vertex);
128 }
129 }
130
131 _credalNet_src_cpt_.insert(id, cpt);
132 }
133
134 template < GUM_Numeric GUM_SCALAR >
136 const Size& entry,
137 const std::vector< std::vector< GUM_SCALAR > >& cpt) {
138 const Tensor< GUM_SCALAR >* const tensor(&_src_bn_.cpt(id));
139
140 auto var_dSize = _src_bn_.variable(id).domainSize();
141 auto entry_size = tensor->domainSize() / var_dSize;
142
143 if (entry >= entry_size)
145 "setCPT : entry is greater or equal than entry size "
146 "(entries start at 0 up to entry_size - 1) : "
147 << entry << " >= " << entry_size);
148
149 if (cpt.size() == 0) GUM_ERROR(SizeError, "setCPT : empty credal set for entry : " << entry)
150
151 for (const auto& vertex: cpt) {
152 if (vertex.size() != var_dSize)
154 "setCPT : variable modalities in cpts does not "
155 "match for node id : "
156 << id << " with vertex " << vertex << " at entry " << entry << " : "
157 << vertex.size() << " != " << var_dSize);
158
159 GUM_SCALAR sum = 0;
160
161 for (const auto& prob: vertex) {
162 sum += prob;
163 }
164
165 if (!gum::isCloseToOne(sum, GUM_SCALAR(config().epsilonStandard())))
167 "setCPT : a vertex coordinates does not sum to one for node id : "
168 << id << " at entry " << entry << " with vertex " << vertex);
169 }
170
171 // !! auto does NOT use adress (if available) unless explicitly asked !!
172 auto& node_cpt = _credalNet_src_cpt_.getWithDefault(
173 id,
174 std::vector< std::vector< std::vector< GUM_SCALAR > > >(entry_size));
175
176 if (node_cpt[entry].size() != 0)
178 "setCPT : vertices of entry id " << entry
179 << " already set to : " << node_cpt[entry]
180 << ", cannot insert : " << cpt);
181
182 node_cpt[entry] = cpt;
183
185 }
186
187 template < GUM_Numeric GUM_SCALAR >
189 Instantiation ins,
190 const std::vector< std::vector< GUM_SCALAR > >& cpt) {
191 const Tensor< GUM_SCALAR >* const tensor(&_src_bn_.cpt(id));
192
193 auto var_dSize = _src_bn_.variable(id).domainSize();
194 auto entry_size = tensor->domainSize() / var_dSize;
195
196 // to be sure of entry index reorder ins according to the bayes net
197 // tensors
198 // ( of the credal net )
199 // it WONT throw an error if the sequences are not equal not because of
200 // order
201 // but content, so we double check (before & after order correction)
202 // beware of slaves & master
203 Instantiation ref(tensor);
204 ref.forgetMaster();
205
206 ins.forgetMaster();
207
208 const auto& vseq = ref.variablesSequence();
209
210 if (ins.variablesSequence() != vseq) {
211 ins.reorder(ref);
212
213 if (ins.variablesSequence() != vseq)
215 "setCPT : instantiation : "
216 << ins << " is not valid for node id " << id
217 << " which accepts instantiations such as (order is not "
218 "important) : "
219 << ref);
220 }
221
222 Idx entry = 0, jump = 1;
223
224 for (Idx i = 0, end = ins.nbrDim(); i < end; i++) {
225 if (_src_bn_.nodeId(ins.variable(i)) == id) continue;
226
227 entry += ins.val(i) * jump;
228
229 jump *= ins.variable(i).domainSize();
230 }
231
232 if (entry >= entry_size)
234 "setCPT : entry is greater or equal than entry size "
235 "(entries start at 0 up to entry_size - 1) : "
236 << entry << " >= " << entry_size);
237
238 if (cpt.size() == 0) GUM_ERROR(SizeError, "setCPT : empty credal set for entry : " << entry)
239
240 for (const auto& vertex: cpt) {
241 if (vertex.size() != var_dSize)
243 "setCPT : variable modalities in cpts does not "
244 "match for node id : "
245 << id << " with vertex " << vertex << " at entry " << entry << " : "
246 << vertex.size() << " != " << var_dSize);
247
248 GUM_SCALAR sum = 0;
249
250 for (const auto& prob: vertex) {
251 sum += prob;
252 }
253
254 if (!gum::isCloseToOne(sum, GUM_SCALAR(config().epsilonStandard())))
256 "setCPT : a vertex coordinates does not sum to one for node id : "
257 << id << " at entry " << entry << " with vertex " << vertex);
258 }
259
260 auto& node_cpt = _credalNet_src_cpt_.getWithDefault(
261 id,
262 std::vector< std::vector< std::vector< GUM_SCALAR > > >(entry_size));
263
264 if (node_cpt[entry].size() != 0)
266 "setCPT : vertices of entry : " << ins << " id " << entry
267 << " already set to : " << node_cpt[entry]
268 << ", cannot insert : " << cpt);
269
270 node_cpt[entry] = cpt;
271
273 }
274
275 template < GUM_Numeric GUM_SCALAR >
277 const std::vector< GUM_SCALAR >& lower,
278 const std::vector< GUM_SCALAR >& upper) {
279 try {
280 _src_bn_min_.cpt(id).fillWith(lower);
281 _src_bn_max_.cpt(id).fillWith(upper);
282 } catch (const SizeError&) {
284 "fillConstraints : sizes does not match in fillWith for node id : " << id);
285 }
286 }
287
288 template < GUM_Numeric GUM_SCALAR >
290 const Idx& entry,
291 const std::vector< GUM_SCALAR >& lower,
292 const std::vector< GUM_SCALAR >& upper) {
293 Tensor< GUM_SCALAR >* const tensor_min(
294 const_cast< Tensor< GUM_SCALAR >* const >(&_src_bn_min_.cpt(id)));
295 Tensor< GUM_SCALAR >* const tensor_max(
296 const_cast< Tensor< GUM_SCALAR >* const >(&_src_bn_max_.cpt(id)));
297
298 auto var_dSize = _src_bn_.variable(id).domainSize();
299
300 if (lower.size() != var_dSize || upper.size() != var_dSize)
302 "setCPT : variable modalities in cpts does not match for node id : "
303 << id << " with sizes of constraints : ( " << lower.size() << " || "
304 << upper.size() << " ) != " << var_dSize);
305
306 auto entry_size = tensor_min->domainSize() / var_dSize;
307
308 if (entry >= entry_size)
310 "setCPT : entry is greater or equal than entry size "
311 "(entries start at 0 up to entry_size - 1) : "
312 << entry << " >= " << entry_size);
313
314 Instantiation min(tensor_min);
315 Instantiation max(tensor_max);
316 min.setFirst();
317 max.setFirst();
318
319 Idx pos = 0;
320
321 while (pos != entry) {
322 ++min;
323 ++max;
324 ++pos;
325 }
326
327 for (Size i = 0; i < var_dSize; i++) {
328 tensor_min->set(min, lower[i]);
329 tensor_max->set(max, upper[i]);
330 ++min;
331 ++max;
332 }
333 }
334
335 template < GUM_Numeric GUM_SCALAR >
337 Instantiation ins,
338 const std::vector< GUM_SCALAR >& lower,
339 const std::vector< GUM_SCALAR >& upper) {
340 const Tensor< GUM_SCALAR >* const tensor(&_src_bn_.cpt(id));
341 /*
342 auto var_dSize = _src_bn_.variable ( id ).domainSize();
343 auto entry_size = tensor->domainSize() / var_dSize;
344 */
345 // to be sure of entry index reorder ins according to the bayes net
346 // tensors
347 // ( of the credal net )
348 // it WONT throw an error if the sequences are not equal not because of
349 // order
350 // but content, so we double check (before & after order correction)
351 // beware of slaves & master
352 Instantiation ref(tensor);
353 ref.forgetMaster();
354
355 ins.forgetMaster();
356
357 const auto& vseq = ref.variablesSequence();
358
359 if (ins.variablesSequence() != vseq) {
360 ins.reorder(ref);
361
362 if (ins.variablesSequence() != vseq)
364 "setCPT : instantiation : "
365 << ins << " is not valid for node id " << id
366 << " which accepts instantiations such as (order is not "
367 "important) : "
368 << ref);
369 }
370
371 Idx entry = 0, jump = 1;
372
373 for (Idx i = 0, end = ins.nbrDim(); i < end; i++) {
374 if (_src_bn_.nodeId(ins.variable(i)) == id) continue;
375
376 entry += ins.val(i) * jump;
377
378 jump *= ins.variable(i).domainSize();
379 }
380
381 /*
382 if ( entry >= entry_size )
383 GUM_ERROR ( SizeError, "setCPT : entry is greater or equal than entry
384 size
385 (entries start at 0 up to entry_size - 1) : " << entry << " >= " <<
386 entry_size
387 );
388
389 if ( lower.size() != var_dSize || upper.size() != var_dSize )
390 GUM_ERROR ( SizeError, "setCPT : variable modalities in cpts does not
391 match
392 for node id : " << id << " with sizes of constraints : ( "<< lower.size()
393 << "
394 || " << upper.size() << " ) != " << var_dSize );
395 */
396 fillConstraint(id, entry, lower, upper);
397 }
398
401
402 template < GUM_Numeric GUM_SCALAR >
406
407 template < GUM_Numeric GUM_SCALAR >
409 return _src_bn_.variable(id).domainSize();
410 }
411
413
414 template < GUM_Numeric GUM_SCALAR >
415 CredalNet< GUM_SCALAR >::CredalNet(std::string_view src_min_num, std::string_view src_max_den) {
416 _initParams_();
417 _initCNNets_(src_min_num, src_max_den);
418
419 GUM_CONSTRUCTOR(CredalNet);
420 }
421
422 template < GUM_Numeric GUM_SCALAR >
423 CredalNet< GUM_SCALAR >::CredalNet(const BayesNet< GUM_SCALAR >& src_min_num,
424 const BayesNet< GUM_SCALAR >& src_max_den) {
425 _initParams_();
426 _initCNNets_(src_min_num, src_max_den);
427
428 GUM_CONSTRUCTOR(CredalNet);
429 }
430
431 template < GUM_Numeric GUM_SCALAR >
433 if (_current_bn_ != nullptr) delete _current_bn_;
434
436
437 if (_current_nodeType_ != nullptr) delete _current_nodeType_;
438
439 GUM_DESTRUCTOR(CredalNet);
440 }
441
442 // from BNs with numerators & denominators or cpts & denominators to credal
443 template < GUM_Numeric GUM_SCALAR >
444 void CredalNet< GUM_SCALAR >::bnToCredal(GUM_SCALAR beta, bool oneNet) {
445 this->bnToCredal(beta, oneNet, false);
446 }
447
448 template < GUM_Numeric GUM_SCALAR >
449 void CredalNet< GUM_SCALAR >::bnToCredal(GUM_SCALAR beta, bool oneNet, bool keepZeroes) {
450 GUM_SCALAR epsi_min = 1.;
451 GUM_SCALAR epsi_max = 0.;
452 GUM_SCALAR epsi_moy = 0.;
453 GUM_SCALAR epsi_den = 0.;
454
455 for (auto node: src_bn().nodes()) {
456 const Tensor< GUM_SCALAR >* const tensor(&_src_bn_.cpt(node));
457
458 Tensor< GUM_SCALAR >* const tensor_min(
459 const_cast< Tensor< GUM_SCALAR >* const >(&_src_bn_min_.cpt(node)));
460 Tensor< GUM_SCALAR >* const tensor_max(
461 const_cast< Tensor< GUM_SCALAR >* const >(&_src_bn_max_.cpt(node)));
462
463 Size var_dSize = _src_bn_.variable(node).domainSize();
464 Size entry_size = tensor->domainSize() / var_dSize;
465
466 Instantiation ins(tensor);
467 Instantiation ins_min(tensor_min);
468 Instantiation ins_max(tensor_max);
469
470 ins.setFirst();
471 ins_min.setFirst();
472 ins_max.setFirst();
473
474 std::vector< GUM_SCALAR > vertex(var_dSize);
475
476 for (Size entry = 0; entry < entry_size; entry++) {
477 GUM_SCALAR den;
478
479 if (oneNet) den = 0;
480 else den = tensor_max->get(ins_max);
481
482 Size nbm = 0;
483
484 for (Size modality = 0; modality < var_dSize; modality++) {
485 vertex[modality] = tensor->get(ins);
486
487 if (oneNet) {
488 den += vertex[modality];
489
490 if (vertex[modality] < 1 && vertex[modality] > 0)
492 "bnToCredal : the BayesNet contains "
493 "probabilities and not event counts "
494 "although user precised oneNet = "
495 << oneNet);
496 }
497
498 if (vertex[modality] > 0) nbm++;
499
500 ++ins;
501 }
502
504 if (!oneNet) {
505 GUM_SCALAR sum = 0;
506
507 for (auto modality = vertex.cbegin(), theEnd = vertex.cend(); modality != theEnd;
508 ++modality) {
509 sum += *modality;
510 }
511
512 if (std::fabs(1. - sum) > _epsRedund_) {
514 _src_bn_.variable(node).name()
515 << "(" << _epsRedund_ << ") does not sum to one for" << " " << entry
516 << std::endl
517 << vertex << std::endl
518 << ins << std::endl);
519 }
520 }
521
523
524 GUM_SCALAR epsilon;
525
526 if (beta == 0) epsilon = 0;
527 else if (den == 0 || beta == 1) epsilon = GUM_SCALAR(1.0);
528 else epsilon = GUM_SCALAR(std::pow(beta, std::log1p(den)));
529
530 epsi_moy += epsilon;
531 epsi_den += 1;
532
533 if (epsilon > epsi_max) epsi_max = epsilon;
534
535 if (epsilon < epsi_min) epsi_min = epsilon;
536
537 GUM_SCALAR min, max;
538
539 for (Size modality = 0; modality < var_dSize; modality++) {
540 if ((vertex[modality] > 0 && nbm > 1) || !keepZeroes) {
541 min = GUM_SCALAR((1. - epsilon) * vertex[modality]);
542
543 if (oneNet) min = GUM_SCALAR(min * 1.0 / den);
544
545 max = GUM_SCALAR(min + epsilon);
546 } else {
547 // if ( ( vertex[modality] == 0 && keepZeroes ) || (
548 // vertex[modality] > 0 && nbm <= 1 ) || ( vertex[modality] == 0
549 // && nbm <= 1 ) ) {
550 min = vertex[modality];
551
552 if (oneNet) min = GUM_SCALAR(min * 1.0 / den);
553
554 max = min;
555 }
556
557 tensor_min->set(ins_min, min);
558 tensor_max->set(ins_max, max);
559
560 ++ins_min;
561 ++ins_max;
562 } // end of : for each modality
563 } // end of : for each entry
564 } // end of : for each variable
565
566 _epsilonMin_ = epsi_min;
567 _epsilonMax_ = epsi_max;
568 _epsilonMoy_ = (GUM_SCALAR)epsi_moy / (GUM_SCALAR)epsi_den;
569
571 }
572
573 template < GUM_Numeric GUM_SCALAR >
575 for (auto node: _src_bn_.nodes()) {
576 const Tensor< GUM_SCALAR >* const tensor(&_src_bn_.cpt(node));
577
578 auto var_dSize = _src_bn_.variable(node).domainSize();
579 auto entry_size = tensor->domainSize() / var_dSize;
580
581 Instantiation ins(tensor);
582
583 ins.setFirst();
584
585 std::vector< GUM_SCALAR > vertex(var_dSize);
586
587 for (Size entry = 0; entry < entry_size; entry++) {
588 bool zeroes = false;
589 Instantiation ins_prev = ins;
590
591 for (Size modality = 0; modality < var_dSize; modality++) {
592 vertex[modality] = tensor->get(ins);
593
594 if (vertex[modality] < 1 && vertex[modality] > 0)
596 "lagrangeNormalization : the BayesNet "
597 "contains probabilities and not event "
598 "counts.");
599
600 if (!zeroes && vertex[modality] == 0) { zeroes = true; }
601
602 ++ins;
603 }
604
605 if (zeroes) {
606 ins = ins_prev;
607
608 for (Size modality = 0; modality < var_dSize; modality++) {
609 tensor->set(ins, tensor->get(ins) + 1);
610 ++ins;
611 }
612 }
613 } // end of : for each entry
614 } // end of : for each variable
615 }
616
617 template < GUM_Numeric GUM_SCALAR >
618 void CredalNet< GUM_SCALAR >::idmLearning(const Idx s, const bool keepZeroes) {
619 for (auto node: _src_bn_.nodes()) {
620 const Tensor< GUM_SCALAR >* const tensor(&_src_bn_.cpt(node));
621
622 Tensor< GUM_SCALAR >* const tensor_min(
623 const_cast< Tensor< GUM_SCALAR >* const >(&_src_bn_min_.cpt(node)));
624 Tensor< GUM_SCALAR >* const tensor_max(
625 const_cast< Tensor< GUM_SCALAR >* const >(&_src_bn_max_.cpt(node)));
626
627 Size var_dSize = _src_bn_.variable(node).domainSize();
628 Size entry_size = tensor->domainSize() / var_dSize;
629
630 Instantiation ins(tensor);
631 Instantiation ins_min(tensor_min);
632 Instantiation ins_max(tensor_max);
633
634 ins.setFirst();
635 ins_min.setFirst();
636 ins_max.setFirst();
637
638 std::vector< GUM_SCALAR > vertex(var_dSize);
639
640 for (Size entry = 0; entry < entry_size; entry++) {
641 GUM_SCALAR den = 0;
642 Size nbm = 0;
643
644 for (Size modality = 0; modality < var_dSize; modality++) {
645 vertex[modality] = tensor->get(ins);
646
647 if (vertex[modality] < 1 && vertex[modality] > 0)
649 "idmLearning : the BayesNet contains "
650 "probabilities and not event counts.");
651
652 den += vertex[modality];
653
654 if (vertex[modality] > 0) nbm++;
655
656 ++ins;
657 }
658
659 if (nbm > 1 || !keepZeroes) den += s;
660
661 GUM_SCALAR min, max;
662
663 for (Size modality = 0; modality < var_dSize; modality++) {
664 min = vertex[modality];
665 max = min;
666
667 if ((vertex[modality] > 0 && nbm > 1) || !keepZeroes) { max += s; }
668
669 min = GUM_SCALAR(min * 1.0 / den);
670 max = GUM_SCALAR(max * 1.0 / den);
671
672 tensor_min->set(ins_min, min);
673 tensor_max->set(ins_max, max);
674
675 ++ins_min;
676 ++ins_max;
677 } // end of : for each modality
678 } // end of : for each entry
679 } // end of : for each variable
680
681 _epsilonMin_ = GUM_SCALAR(s);
682 _epsilonMax_ = GUM_SCALAR(s);
683 _epsilonMoy_ = GUM_SCALAR(s);
685 }
686
687 /* no need for lrs : (max ... min ... max) vertices from bnToCredal() */
688 template < GUM_Numeric GUM_SCALAR >
690 if (!_credalNet_src_cpt_.empty()) _credalNet_src_cpt_.clear();
691
692 _credalNet_src_cpt_.resize(_src_bn_.size());
693
694 for (auto node: _src_bn_.nodes()) {
695 const Tensor< GUM_SCALAR >* const tensor_min(&_src_bn_min_.cpt(node));
696 const Tensor< GUM_SCALAR >* const tensor_max(&_src_bn_max_.cpt(node));
697
698 Size var_dSize = _src_bn_.variable(node).domainSize();
699 Size entry_size = tensor_min->domainSize() / var_dSize;
700
701 std::vector< std::vector< std::vector< GUM_SCALAR > > > var_cpt(entry_size);
702
703 Instantiation ins_min(tensor_min);
704 Instantiation ins_max(tensor_max);
705
706 ins_min.setFirst();
707 ins_max.setFirst();
708
709 std::vector< GUM_SCALAR > lower(var_dSize);
710 std::vector< GUM_SCALAR > upper(var_dSize);
711
712 // the tolerance is read once per node, not at each test
713 const double epsilon = config().epsilonStandard();
714
715 for (Size entry = 0; entry < entry_size; entry++) {
716 for (Size modality = 0; modality < var_dSize; modality++, ++ins_min, ++ins_max) {
717 lower[modality] = tensor_min->get(ins_min);
718 upper[modality] = tensor_max->get(ins_max);
719 }
720
721 bool all_equals = true;
722 std::vector< std::vector< GUM_SCALAR > > vertices;
723
724 for (Size modality = 0; modality < var_dSize; modality++) {
725 if (std::fabs(upper[modality] - lower[modality]) < epsilon) continue;
726
727 all_equals = false;
728 std::vector< GUM_SCALAR > vertex(var_dSize);
729 vertex[modality] = upper[modality];
730
731 for (Size mod = 0; mod < var_dSize; mod++) {
732 if (modality != mod) vertex[mod] = lower[mod];
733 }
734
735 GUM_SCALAR total = 0;
736
737 auto vsize = vertex.size();
738
739 for (Size i = 0; i < vsize; i++)
740 total += vertex[i];
741
742 if (std::fabs(total - 1.) > epsilon)
744 _src_bn_.variable(node).name()
745 << " does not sum to one for " << entry << std::endl
746 << vertex << std::endl);
747
748 vertices.push_back(vertex);
749 }
750
751 if (all_equals) {
752 std::vector< GUM_SCALAR > vertex(var_dSize);
753
754 for (Size modality = 0; modality < var_dSize; modality++)
755 vertex[modality] = lower[modality];
756
757 GUM_SCALAR total = 0.;
758
759 auto vsize = vertex.size();
760
761 for (Size i = 0; i < vsize; i++)
762 total += vertex[i];
763
764 if (std::fabs(total - 1.) > epsilon)
766 _src_bn_.variable(node).name()
767 << " does not sum to one for " << entry << std::endl
768 << vertex << std::endl);
769
770 vertices.push_back(vertex);
771 }
772
773 var_cpt[entry] = vertices;
774 }
775
776 _credalNet_src_cpt_.insert(node, var_cpt);
777 } // end of : for each variable (node)
778
779 // get precise/credal/vacuous status of each variable
782 }
783
784 /* uses lrsWrapper */
785 template < GUM_Numeric GUM_SCALAR >
787 if (!_credalNet_src_cpt_.empty()) _credalNet_src_cpt_.clear();
788
789 _credalNet_src_cpt_.resize(_src_bn_.size());
790
791 LRSWrapper< GUM_SCALAR > lrsWrapper;
792
793 for (auto node: _src_bn_.nodes()) {
794 const Tensor< GUM_SCALAR >* const tensor_min(&_src_bn_min_.cpt(node));
795 const Tensor< GUM_SCALAR >* const tensor_max(&_src_bn_max_.cpt(node));
796
797 Size var_dSize = _src_bn_.variable(node).domainSize();
798 Size entry_size = tensor_min->domainSize() / var_dSize;
799
800 std::vector< std::vector< std::vector< GUM_SCALAR > > > var_cpt(entry_size);
801
802 Instantiation ins_min(tensor_min);
803 Instantiation ins_max(tensor_max);
804
805 ins_min.setFirst();
806 ins_max.setFirst();
807
808 lrsWrapper.setUpH(var_dSize);
809
810 for (Size entry = 0; entry < entry_size; entry++) {
811 for (Size modality = 0; modality < var_dSize; modality++) {
812 if (tensor_min->get(ins_min) > tensor_max->get(ins_max)) {
814 "For variable "
815 << _src_bn_.variable(node).name() << " (at " << ins_min
816 << "), the min is greater than the max : " << tensor_min->get(ins_min)
817 << ">" << tensor_max->get(ins_max) << ".");
818 }
819 lrsWrapper.fillH(tensor_min->get(ins_min), tensor_max->get(ins_max), modality);
820 ++ins_min;
821 ++ins_max;
822 }
823
824 lrsWrapper.H2V();
825 var_cpt[entry] = lrsWrapper.getOutput();
826 lrsWrapper.nextHInput();
827 }
828
829 _credalNet_src_cpt_.insert(node, var_cpt);
830 } // end of : for each variable (node)
831
832 // get precise/credal/vacuous status of each variable
835 }
836
837 /* call lrs */
838 template < GUM_Numeric GUM_SCALAR >
840 if (!_credalNet_src_cpt_.empty()) _credalNet_src_cpt_.clear();
841
842 _credalNet_src_cpt_.resize(_src_bn_.size());
843
844 for (auto node: _src_bn_.nodes()) {
845 const Tensor< GUM_SCALAR >* const tensor_min(&_src_bn_min_.cpt(node));
846 const Tensor< GUM_SCALAR >* const tensor_max(&_src_bn_max_.cpt(node));
847
848 auto var_dSize = _src_bn_.variable(node).domainSize();
849 auto entry_size = tensor_min->domainSize() / var_dSize;
850
851 std::vector< std::vector< std::vector< GUM_SCALAR > > > var_cpt(entry_size);
852
853 Instantiation ins_min(tensor_min);
854 Instantiation ins_max(tensor_max);
855
856 ins_min.setFirst();
857 ins_max.setFirst();
858
859 // use iterator
860 for (Size entry = 0; entry < entry_size; entry++) {
861 std::vector< std::vector< GUM_SCALAR > > vertices;
862 std::vector< GUM_SCALAR > vertex(var_dSize); // if not interval
863
864 std::vector< std::vector< GUM_SCALAR > > inequalities(
865 var_dSize * 2,
866 std::vector< GUM_SCALAR >(var_dSize + 1, 0));
867
868 std::vector< GUM_SCALAR > sum_ineq1(var_dSize + 1, -1);
869 std::vector< GUM_SCALAR > sum_ineq2(var_dSize + 1, 1);
870 sum_ineq1[0] = 1;
871 sum_ineq2[0] = -1;
872
873 bool isInterval = false;
874
875 for (Size modality = 0; modality < var_dSize; modality++) {
876 inequalities[modality * 2][0] = -tensor_min->get(ins_min);
877 inequalities[modality * 2 + 1][0] = tensor_max->get(ins_max);
878 inequalities[modality * 2][modality + 1] = 1;
879 inequalities[modality * 2 + 1][modality + 1] = -1;
880
881 vertex[modality] = inequalities[modality * 2 + 1][0];
882
883 if (!isInterval
884 && (-inequalities[modality * 2][0] != inequalities[modality * 2 + 1][0]))
885 isInterval = true;
886
887 ++ins_min;
888 ++ins_max;
889 }
890
891 inequalities.push_back(sum_ineq1);
892 inequalities.push_back(sum_ineq2);
893
894 if (!isInterval) {
895 vertices.push_back(vertex);
896 } else {
897 try {
898 _H2Vlrs_(inequalities, vertices);
899 // __H2Vcdd ( inequalities, vertices );
900 } catch (const std::exception& err) {
901 std::cout << err.what() << std::endl;
902 throw;
903 }
904 } // end of : is interval
905
906 if (entry == 0 && vertices.size() >= 2) {
907 auto tmp = vertices[0];
908 vertices[0] = vertices[1];
909 vertices[1] = tmp;
910 }
911
912 var_cpt[entry] = vertices;
913 } // end of : for each entry
914
915 _credalNet_src_cpt_.insert(node, var_cpt);
916 // std::cout << _src_bn_.variable(node_idIt).name() << std::endl;
917 // std::cout << var_cpt << std::endl;
918 } // end of : for each variable (node)
919
920 // get precise/credal/vacuous status of each variable
923 }
924
929 template < GUM_Numeric GUM_SCALAR >
930 void CredalNet< GUM_SCALAR >::saveBNsMinMax(std::string_view min_path,
931 std::string_view max_path) {
933
934 std::string minfilename(min_path); //"min.bif";
935 std::string maxfilename(max_path); //"max.bif";
936 std::ofstream min_file(minfilename.c_str(), std::ios::out | std::ios::trunc);
937 std::ofstream max_file(maxfilename.c_str(), std::ios::out | std::ios::trunc);
938
939 if (!min_file.good())
940 GUM_ERROR(IOError, "bnToCredal() : could not open stream : min_file : " << minfilename);
941
942 if (!max_file.good()) {
943 min_file.close();
944 GUM_ERROR(IOError, "bnToCredal() : could not open stream : min_file : " << maxfilename);
945 }
946
947 try {
948 writer.write(min_file, _src_bn_min_);
949 writer.write(max_file, _src_bn_max_);
950 } catch (Exception& err) {
951 GUM_SHOWERROR(err);
952 min_file.close();
953 max_file.close();
954 throw(err);
955 }
956
957 min_file.close();
958 max_file.close();
959 }
960
961 template < GUM_Numeric GUM_SCALAR >
963 // don't forget to delete the old one ( _current_), if necessary at the end
964 auto bin_bn = new BayesNet< GUM_SCALAR >();
965
966 // __bnCopy ( * _bin_bn_ );
967 // delete old one too
968 auto credalNet_bin_cpt
970
971 // delete old one too
972 auto bin_nodeType = new NodeProperty< NodeType >();
973
974 const BayesNet< GUM_SCALAR >* current_bn;
976 credalNet_current_cpt;
977
978 if (this->_current_bn_ == nullptr) current_bn = &this->_src_bn_;
979 else current_bn = this->_current_bn_;
980
981 if (this->_credalNet_current_cpt_ == nullptr)
982 credalNet_current_cpt = &this->_credalNet_src_cpt_;
983 else credalNet_current_cpt = this->_credalNet_current_cpt_;
984
985 if (!_var_bits_.empty()) _var_bits_.clear();
986
987 bin_bn->beginTopologyTransformation();
988
989 for (auto node: current_bn->nodes()) {
990 auto var_dSize = current_bn->variable(node).domainSize();
991
992 if (var_dSize != 2) {
993 unsigned long b;
994 unsigned long c;
995 superiorPow(static_cast< unsigned long >(var_dSize), b, c);
996 Size nb_bits{b};
997
998 std::string bit_name;
999 std::vector< NodeId > bits(nb_bits);
1000
1001 for (Size bit = 0; bit < nb_bits; bit++) {
1002 bit_name = current_bn->variable(node).name() + "-b";
1003 bit_name += std::to_string(bit);
1004
1005 LabelizedVariable var_bit(bit_name, "node " + bit_name, 2);
1006 NodeId iD = bin_bn->add(var_bit);
1007
1008 bits[bit] = iD;
1009 } // end of : for each bit
1010
1011 _var_bits_.insert(node, bits);
1012 } // end of : if variable is not binary
1013 else {
1014 const std::string bit_name = current_bn->variable(node).name();
1015 LabelizedVariable var_bit(bit_name, "node " + bit_name, 2);
1016 const NodeId iD = bin_bn->add(var_bit);
1017
1018 _var_bits_.insert(node, std::vector< NodeId >(1, iD));
1019 }
1020 } // end of : for each original variable
1021
1022 for (auto node: current_bn->nodes()) {
1023 if (NodeSet parents = current_bn->parents(node); !parents.empty()) {
1024 for (auto par: current_bn->parents(node)) {
1025 for (Size parent_bit = 0, spbits = static_cast< Size >(_var_bits_[par].size());
1026 parent_bit < spbits;
1027 parent_bit++)
1028 for (Size var_bit = 0, mbits = static_cast< Size >(_var_bits_[node].size());
1029 var_bit < mbits;
1030 var_bit++)
1031 bin_bn->addArc(_var_bits_[par][parent_bit], _var_bits_[node][var_bit]);
1032 }
1033 }
1034
1035 // arcs with one's bits
1036 const auto bitsize = _var_bits_[node].size();
1037
1038 for (Size bit_c = 1; bit_c < bitsize; bit_c++)
1039 for (Size bit_p = 0; bit_p < bit_c; bit_p++)
1040 bin_bn->addArc(_var_bits_[node][bit_p], _var_bits_[node][bit_c]);
1041 } // end of : for each original variable
1042
1043 bin_bn->endTopologyTransformation();
1044
1045 // binarization of cpts
1046
1047 const auto varsize = current_bn->size();
1048
1049 for (Size var = 0; var < varsize; var++) {
1050 const auto bitsize = _var_bits_[var].size();
1051
1052 for (Size i = 0; i < bitsize; i++) {
1053 Tensor< GUM_SCALAR > const* tensor(&bin_bn->cpt(_var_bits_[var][i]));
1054 Instantiation ins(tensor);
1055 ins.setFirst();
1056
1057 auto entry_size = tensor->domainSize() / 2;
1058 std::vector< std::vector< std::vector< GUM_SCALAR > > > var_cpt(entry_size);
1059
1060 Size old_conf = 0;
1061
1062 for (Size conf = 0; conf < entry_size; conf++) {
1063 std::vector< std::vector< GUM_SCALAR > > pvar_cpt;
1064 auto verticessize = (*credalNet_current_cpt)[var][old_conf].size();
1065
1066 for (Size old_distri = 0; old_distri < verticessize; old_distri++) {
1067 const std::vector< GUM_SCALAR >& vertex
1068 = (*credalNet_current_cpt)[var][old_conf][old_distri];
1069 auto vertexsize = vertex.size();
1070
1071 std::vector< Idx > incc(vertexsize, 0);
1072
1073 for (Size preced = 0; preced < i; preced++) {
1074 auto bit_pos = ins.pos(bin_bn->variable(_var_bits_[var][preced]));
1075 auto val = ins.val(bit_pos);
1076
1077 Size pas = Size(int2Pow(preced));
1078 Size elem;
1079
1080 if (val == 0) elem = 0;
1081 else elem = pas;
1082
1083 while (elem < vertexsize) {
1084 incc[elem]++;
1085 elem++;
1086
1087 if (elem % pas == 0) elem += pas;
1088 }
1089 }
1090
1091 Size pas = Size(int2Pow(i));
1092
1093 std::vector< GUM_SCALAR > distri(2, 0);
1094 int pos = 1;
1095
1096 for (Size elem = 0; elem < vertexsize; elem++) {
1097 if (elem % pas == 0) pos = -pos;
1098
1099 if (incc[elem] == i)
1100 (pos < 0) ? (distri[0] += vertex[elem]) : (distri[1] += vertex[elem]);
1101 }
1102
1103 if (i > 0) {
1104 GUM_SCALAR den = distri[0] + distri[1];
1105
1106 if (den == 0) {
1107 distri[0] = 0;
1108 distri[1] = 0;
1109 } else {
1110 distri[0] /= den;
1111 distri[1] /= den;
1112 }
1113 }
1114
1115 pvar_cpt.push_back(distri);
1116 } // end of old distris
1117
1118 // get min/max approx, 2 vertices
1119 std::vector< std::vector< GUM_SCALAR > > vertices(2, std::vector< GUM_SCALAR >(2, 1));
1120 vertices[1][1] = 0;
1121
1122 const auto new_verticessize = pvar_cpt.size();
1123
1124 for (Size v = 0; v < new_verticessize; v++) {
1125 if (pvar_cpt[v][1] < vertices[0][1]) vertices[0][1] = pvar_cpt[v][1];
1126
1127 if (pvar_cpt[v][1] > vertices[1][1]) vertices[1][1] = pvar_cpt[v][1];
1128 }
1129
1130 vertices[0][0] = 1 - vertices[0][1];
1131 vertices[1][0] = 1 - vertices[1][1];
1132
1133 pvar_cpt = vertices;
1134
1135 var_cpt[conf] = pvar_cpt;
1136
1137 ++ins;
1138 ++ins;
1139
1140 old_conf++;
1141
1142 if (old_conf == (*credalNet_current_cpt)[var].size()) old_conf = 0;
1143 } // end of new parent conf
1144
1145 credalNet_bin_cpt->insert(_var_bits_[var][i], var_cpt);
1146 } // end of bit i
1147 } // end of old variable
1148
1149 bin_bn->beginTopologyTransformation();
1150
1151 /* indicatrices variables */
1152 const auto old_varsize = _var_bits_.size();
1153
1154 for (Size i = 0; i < old_varsize; i++) {
1155 auto bitsize = _var_bits_[i].size();
1156
1157 // binary variable
1158 if (bitsize == 1) continue;
1159
1160 auto old_card = _src_bn_.variable(i).domainSize();
1161
1162 for (Size mod = 0; mod < old_card; mod++) {
1163 auto ss_str = std::format("{}-v{}", _src_bn_.variable(i).name(), mod);
1164
1165 LabelizedVariable var(ss_str, "node " + ss_str, 2);
1166 const NodeId indic = bin_bn->add(var);
1167
1168 // arcs from one's bits
1169 for (Size bit = 0; bit < bitsize; bit++)
1170 bin_bn->addArc(_var_bits_[i][bit], indic);
1171
1172 // cpt
1173 Size num = Size(int2Pow(long(bitsize)));
1174
1175 std::vector< std::vector< std::vector< GUM_SCALAR > > > icpt(num);
1176
1177 for (Size entry = 0; entry < num; entry++) {
1178 std::vector< std::vector< GUM_SCALAR > > vertices(1, std::vector< GUM_SCALAR >(2, 0));
1179
1180 if (mod == entry) vertices[0][1] = 1;
1181 else vertices[0][0] = 1;
1182
1183 icpt[entry] = vertices;
1184 }
1185
1186 credalNet_bin_cpt->insert(indic, icpt);
1187
1188 bin_nodeType->insert(indic, NodeType::Indic);
1189 } // end of each modality, i.e. as many indicatrice
1190 }
1191
1192 bin_bn->endTopologyTransformation();
1193
1194 if (this->_current_bn_ != nullptr) delete this->_current_bn_;
1195
1196 this->_current_bn_ = bin_bn;
1197
1198 if (this->_credalNet_current_cpt_ != nullptr) delete this->_credalNet_current_cpt_;
1199
1200 this->_credalNet_current_cpt_ = credalNet_bin_cpt;
1201
1202 if (this->_current_nodeType_ != nullptr) delete this->_current_nodeType_;
1203
1204 this->_current_nodeType_ = bin_nodeType;
1205
1206 _sort_varType_(); // will fill _bin_nodeType_ except for NodeType::Indic
1207 // variables
1208
1210 }
1211
1212 template < GUM_Numeric GUM_SCALAR >
1219
1220 template < GUM_Numeric GUM_SCALAR >
1225
1226 template < GUM_Numeric GUM_SCALAR >
1229 if (_current_nodeType_ != nullptr) return (*(_current_nodeType_))[id];
1230
1231 return _original_nodeType_[id];
1232 }
1233
1234 template < GUM_Numeric GUM_SCALAR >
1237 return _original_nodeType_[id];
1238 }
1239
1240 template < GUM_Numeric GUM_SCALAR >
1244
1245 template < GUM_Numeric GUM_SCALAR >
1249
1250 // only if CN is binary !!
1251 template < GUM_Numeric GUM_SCALAR >
1253 // ASSUMPTION: NodeIds are dense 0..N-1 (no nodes ever removed from the BN).
1254 // If sparse NodeIds are introduced, indexing by node will go out of bounds.
1255 _binCptMin_.resize(current_bn().size());
1256 _binCptMax_.resize(current_bn().size());
1257
1258 for (auto node: current_bn().nodes()) {
1259 auto pConf = credalNet_currentCpt()[node].size();
1260 std::vector< GUM_SCALAR > min(pConf);
1261 std::vector< GUM_SCALAR > max(pConf);
1262
1263 for (Size pconf = 0; pconf < pConf; pconf++) {
1264 GUM_SCALAR v1, v2;
1265 v1 = credalNet_currentCpt()[node][pconf][0][1];
1266
1267 if (credalNet_currentCpt()[node][pconf].size() > 1)
1268 v2 = credalNet_currentCpt()[node][pconf][1][1];
1269 else v2 = v1;
1270
1271 GUM_SCALAR delta = v1 - v2;
1272 min[pconf] = (delta >= 0) ? v2 : v1;
1273 max[pconf] = (delta >= 0) ? v1 : v2;
1274 }
1275
1276 _binCptMin_[node] = min;
1277 _binCptMax_[node] = max;
1278 }
1279
1281 }
1282
1283 template < GUM_Numeric GUM_SCALAR >
1284 const std::vector< std::vector< GUM_SCALAR > >&
1288
1289 template < GUM_Numeric GUM_SCALAR >
1290 const std::vector< std::vector< GUM_SCALAR > >&
1294
1295 template < GUM_Numeric GUM_SCALAR >
1296 const GUM_SCALAR& CredalNet< GUM_SCALAR >::epsilonMin() const {
1297 return _epsilonMin_;
1298 }
1299
1300 template < GUM_Numeric GUM_SCALAR >
1301 const GUM_SCALAR& CredalNet< GUM_SCALAR >::epsilonMax() const {
1302 return _epsilonMax_;
1303 }
1304
1305 template < GUM_Numeric GUM_SCALAR >
1306 const GUM_SCALAR& CredalNet< GUM_SCALAR >::epsilonMean() const {
1307 return _epsilonMoy_;
1308 }
1309
1310 template < GUM_Numeric GUM_SCALAR >
1312 std::stringstream output;
1313 const BayesNet< GUM_SCALAR >* bn_ptr = (_current_bn_ != nullptr) ? _current_bn_ : &_src_bn_;
1316
1317 for (auto node: bn_ptr->nodes()) {
1318 const Tensor< GUM_SCALAR >* tensor(&bn_ptr->cpt(node));
1319 auto pconfs = tensor->domainSize() / bn_ptr->variable(node).domainSize();
1320
1321 output << "\n" << bn_ptr->variable(node) << "\n";
1322
1323 Instantiation ins(tensor);
1324 ins.forgetMaster();
1325 ins.erase(bn_ptr->variable(node));
1326 ins.setFirst();
1327
1328 for (Size pconf = 0; pconf < pconfs; pconf++) {
1329 output << ins << " : ";
1330 output << (*cpt_ptr)[node][pconf] << "\n";
1331
1332 if (pconf < pconfs - 1) ++ins;
1333 }
1334 }
1335
1336 output << "\n";
1337
1338 return output.str();
1339 }
1340
1341 template < GUM_Numeric GUM_SCALAR >
1343 return toDot(dot::DotOptions());
1344 }
1345
1346 template < GUM_Numeric GUM_SCALAR >
1347 std::string CredalNet< GUM_SCALAR >::toDot(const dot::DotOptions& options) const {
1348 const auto& bn = current_bn();
1349 const auto style = dot::DotStyle::readCredalNet();
1350 dot::DotWriter writer(true);
1351 dot::writePreamble(writer, style, options);
1352
1353 for (const auto node: bn.nodes()) {
1354 const auto& name = bn.variable(node).name();
1355 auto attributes = dot::nodeAttributes(style,
1356 options.node(node),
1357 "",
1358 "(" + std::to_string(node) + ") " + name);
1359 dot::addDefaultAttribute(attributes, "peripheries", "1");
1360 dot::addDefaultAttribute(attributes, "sides", "7");
1361 dot::addDefaultAttribute(attributes, "shape", "polygon");
1362 writer.node(name, attributes);
1363 }
1364
1365 for (const auto& arc: bn.arcs()) {
1366 auto attributes = dot::arcAttributes(options.arc(arc.tail(), arc.head()));
1367 dot::addDefaultAttribute(attributes,
1368 "tooltip",
1369 std::to_string(arc.tail()) + "&nbsp;&rarr;&nbsp;"
1370 + std::to_string(arc.head()));
1371 dot::addDefaultAttribute(attributes, "fontsize", "10");
1372 writer.edge(bn.variable(arc.tail()).name(), bn.variable(arc.head()).name(), attributes);
1373 }
1374
1375 return writer.str();
1376 }
1377
1378 template < GUM_Numeric GUM_SCALAR >
1379 const BayesNet< GUM_SCALAR >& CredalNet< GUM_SCALAR >::current_bn() const {
1380 if (_current_bn_ != nullptr) return *_current_bn_;
1381
1382 return _src_bn_;
1383 }
1384
1385 template < GUM_Numeric GUM_SCALAR >
1386 const BayesNet< GUM_SCALAR >& CredalNet< GUM_SCALAR >::src_bn() const {
1387 return _src_bn_;
1388 }
1389
1391
1393
1394 template < GUM_Numeric GUM_SCALAR >
1396 _epsilonMin_ = 0;
1397 _epsilonMax_ = 0;
1398 _epsilonMoy_ = 0;
1399
1400 _epsRedund_ = GUM_SCALAR(config().epsilonStandard());
1401
1402 // farey algorithm
1403 _epsF_ = GUM_SCALAR(config().epsilonStandard());
1404 _denMax_ = GUM_SCALAR(1e6); // beware LRSWrapper
1405
1406 // continued fractions, beware LRSWrapper
1407 // decimal paces ( _epsC_ * _precisionC_ == 1)
1408 _precisionC_ = GUM_SCALAR(1e6);
1409 _deltaC_ = 5;
1410
1411 // old custom algorithm
1412 _precision_ = GUM_SCALAR(1e6); // beware LRSWrapper
1413
1414 _current_bn_ = nullptr;
1415 _credalNet_current_cpt_ = nullptr;
1416 _current_nodeType_ = nullptr;
1417
1419 }
1420
1421 template < GUM_Numeric GUM_SCALAR >
1422 void CredalNet< GUM_SCALAR >::_initCNNets_(std::string_view src_min_num,
1423 std::string_view src_max_den) {
1424 BIFReader< GUM_SCALAR > reader(&_src_bn_, src_min_num);
1425 std::string other;
1426
1427 if (src_max_den.compare("") != 0) other = src_max_den;
1428 else other = src_min_num;
1429
1430 BIFReader< GUM_SCALAR > reader_min(&_src_bn_min_, src_min_num);
1431 BIFReader< GUM_SCALAR > reader_max(&_src_bn_max_, other);
1432
1433 reader.proceed();
1434 reader_min.proceed();
1435 reader_max.proceed();
1436 }
1437
1438 template < GUM_Numeric GUM_SCALAR >
1439 void CredalNet< GUM_SCALAR >::_initCNNets_(const BayesNet< GUM_SCALAR >& src_min_num,
1440 const BayesNet< GUM_SCALAR >& src_max_den) {
1441 _src_bn_ = src_min_num;
1442 _src_bn_min_ = src_min_num;
1443
1444 if (src_max_den.size() > 0) _src_bn_max_ = src_max_den;
1445 else _src_bn_max_ = src_min_num;
1446 }
1447
1448 template < GUM_Numeric GUM_SCALAR >
1450 const std::vector< std::vector< std::vector< GUM_SCALAR > > >& var_cpt) const {
1451 Size vertices_size = 0;
1452
1453 for (auto entry = var_cpt.cbegin(), theEnd = var_cpt.cend(); entry != theEnd; ++entry) {
1454 if (entry->size() > vertices_size) vertices_size = Size(entry->size());
1455 }
1456
1457 return int(vertices_size);
1458 }
1459
1460 template < GUM_Numeric GUM_SCALAR >
1461 void CredalNet< GUM_SCALAR >::_bnCopy_(BayesNet< GUM_SCALAR >& dest) {
1462 const BayesNet< GUM_SCALAR >* bn_ptr = (_current_bn_ != nullptr) ? _current_bn_ : &_src_bn_;
1463
1464 for (auto node: bn_ptr->nodes())
1465 dest.add(bn_ptr->variable(node));
1466
1467 dest.beginTopologyTransformation();
1468
1469 for (auto node: bn_ptr->nodes()) {
1470 for (auto parent_idIt: bn_ptr->cpt(node).variablesSequence()) {
1471 if (bn_ptr->nodeId(*parent_idIt) != node) dest.addArc(bn_ptr->nodeId(*parent_idIt), node);
1472 } // end of : for each parent in order of appearence
1473 } // end of : for each variable
1474
1475 dest.endTopologyTransformation();
1476 }
1477
1478 /*
1479 // cdd can use real values, not just rationals / integers
1480 template< GumScalar GUM_SCALAR >
1481 void CredalNet< GUM_SCALAR >:: _H2Vcdd_ ( const std::vector< std::vector<
1482 GUM_SCALAR > > & h_rep, std::vector< std::vector< GUM_SCALAR > > & v_rep )
1483 const {
1484 dd_set_global_constants();
1485
1486 dd_MatrixPtr M, G;
1487 dd_PolyhedraPtr poly;
1488 dd_ErrorType err;
1489
1490 unsigned int rows = h_rep.size();
1491 unsigned int cols = 0;
1492 if( h_rep.size() > 0 )
1493 cols = h_rep[0].size();
1494
1495 M = dd_CreateMatrix( rows, cols);
1496
1497 for ( unsigned int row = 0; row < rows; row++ )
1498 for ( unsigned int col = 0; col < cols; col++ )
1499 dd_set_d( M->matrix[row][col], h_rep[row][col] );
1500
1501 M->representation = dd_Inequality;
1502
1503 poly = dd_DDMatrix2Poly(M, &err);
1504 G = dd_CopyGenerators(poly);
1505
1506 rows = G->rowsize;
1507 cols = G->colsize;
1508
1509 v_rep.clear();
1510 for ( unsigned int row = 0; row < rows; row++ ) {
1511 std::vector< GUM_SCALAR > aRow(cols - 1);
1512
1513 if ( *G->matrix[row][0] != 1 )
1514 GUM_ERROR(OperationNotAllowed, " __H2Vcdd : not reading a vertex")
1515
1516 for ( unsigned int col = 0; col < cols - 1; col++ )
1517 aRow[col] = *G->matrix[row][ col + 1 ];
1518
1519 v_rep.push_back(aRow);
1520 }
1521
1522 dd_FreeMatrix(M);
1523 dd_FreeMatrix(G);
1524 dd_FreePolyhedra(poly);
1525
1526 dd_free_global_constants();
1527 }
1528 */
1529
1530 template < GUM_Numeric GUM_SCALAR >
1531 void CredalNet< GUM_SCALAR >::_H2Vlrs_(const std::vector< std::vector< GUM_SCALAR > >& h_rep,
1532 std::vector< std::vector< GUM_SCALAR > >& v_rep) const {
1533 // write H rep file
1534 int64_t num, den;
1535
1536 std::string sinefile = getUniqueFileName(); // generate unique file name, we
1537 // need to add .ine or .ext for lrs
1538 // to know which input it is (Hrep
1539 // to Vrep or Vrep to Hrep)
1540 sinefile += ".ine";
1541
1542 std::ofstream h_file(sinefile.c_str(), std::ios::out | std::ios::trunc);
1543
1544 if (!h_file.good())
1545 GUM_ERROR(IOError, " __H2Vlrs : could not open lrs input file : " << sinefile)
1546
1547 h_file << "H - representation\n";
1548 h_file << "begin\n";
1549 h_file << h_rep.size() << ' ' << h_rep[0].size() << " rational\n";
1550
1551 for (auto it = h_rep.cbegin(), theEnd = h_rep.cend(); it != theEnd; ++it) {
1552 for (auto it2 = it->cbegin(), theEnd2 = it->cend(); it2 != theEnd2; ++it2) {
1553 // get integer fraction from decimal value
1554 // smallest numerator & denominator is farley, also
1555 // best precision
1557 den,
1558 ((*it2 > 0) ? *it2 : -*it2),
1559 int64_t(_denMax_),
1560 _epsF_);
1561
1562 h_file << ((*it2 > 0) ? num : -num) << '/' << den << ' ';
1563 }
1564
1565 h_file << '\n';
1566 }
1567
1568 h_file << "end\n";
1569 h_file.close();
1570
1571 // call lrs
1572 std::string extfile(sinefile);
1573 extfile += ".ext";
1574
1575 std::string lrs_arg0 = "lrs";
1576 std::string lrs_arg1 = sinefile;
1577 std::string lrs_arg2 = extfile;
1578 char* lrs_argv[3] = {lrs_arg0.data(), lrs_arg1.data(), lrs_arg2.data()};
1579
1580 // it may need to redirect stdout to a file
1581 lrs_main(3, lrs_argv);
1582
1583 // read V rep file
1584 std::ifstream v_file(extfile.c_str() /*extfilename.c_str()*/, std::ios::in);
1585
1586 if (!v_file.good()) GUM_ERROR(IOError, " __H2Vlrs : could not open lrs output file : ")
1587
1588 std::string line, tmp;
1589 char * cstr, *p;
1590 GUM_SCALAR probability;
1591
1592 std::string::size_type pos;
1593 bool keep_going = true;
1594 // int vertices;
1595
1596 std::vector< GUM_SCALAR > vertex;
1597
1598 v_file.ignore(256, 'l');
1599
1600 while (v_file.good() && keep_going) {
1601 getline(v_file, line);
1602
1603 if (line.size() == 0) continue;
1604 else if (line.compare("end") == 0) {
1605 keep_going = false;
1606 // this is to get vertices number :
1607 /*getline ( v_file, line );
1608 std::string::size_type pos, end_pos;
1609 pos = line.find ( "vertices = " );
1610 end_pos = line.find ( "rays", pos + 9 );
1611 vertices = atoi ( line.substr ( pos + 9, end_pos - pos - 9 ).c_str()
1612 );*/
1613 break;
1614 } else if (line[1] != '1') {
1616 " __H2Vlrs : reading something other than a vertex from "
1617 "lrs output file : ");
1618 }
1619
1620 line = line.substr(2);
1621 cstr = new char[line.size() + 1];
1622 strcpy(cstr, line.c_str());
1623
1624 p = strtok(cstr, " ");
1625
1626 while (p != nullptr) {
1627 tmp = p;
1628
1629 if (tmp.compare("1") == 0 || tmp.compare("0") == 0)
1630 probability = GUM_SCALAR(atof(tmp.c_str()));
1631 else {
1632 pos = tmp.find("/");
1633 probability = GUM_SCALAR(atof(tmp.substr(0, pos).c_str())
1634 / atof(tmp.substr(pos + 1, tmp.size()).c_str()));
1635 }
1636
1637 vertex.push_back(probability);
1638 p = strtok(nullptr, " ");
1639 } // end of : for all tokens
1640
1641 delete[] cstr;
1642
1643 // compute is_redund using multiple threads:
1644 // compute the max number of threads to use (avoid nested threads)
1645 const Size nb_threads = ThreadExecutor::nbRunningThreadsExecutors() == 0
1647 : 1; // no nested multithreading
1648
1649 const auto nsize = v_rep.size();
1650 const auto real_nb_threads = std::min(nb_threads, nsize);
1651
1652 // prepare the data used by the threads
1653 const auto ranges = gum::dispatchRangeToThreads(0, nsize, (unsigned int)(real_nb_threads));
1654 std::vector< Size > t_redund(real_nb_threads); // use Size to avoid false sharing
1655
1656 // create the function to be executed by the threads
1657 auto threadedExec = [this, ranges, &t_redund, vertex, v_rep](const std::size_t this_thread,
1658 const std::size_t nb_threads) {
1659 const auto vsize = vertex.size();
1660 auto& thread_redund = t_redund[this_thread];
1661
1662 for (Idx i = ranges[this_thread].first, end = ranges[this_thread].second; i < end; i++) {
1663 thread_redund = 1;
1664 for (Idx modality = 0; modality < vsize; ++modality) {
1665 if (std::fabs(vertex[modality] - v_rep[i][modality]) > _epsRedund_) {
1666 thread_redund = 0;
1667 break;
1668 }
1669 }
1670
1671 if (thread_redund) return;
1672 }
1673 };
1674
1675 // launch the threads
1676 ThreadExecutor::execute(real_nb_threads, threadedExec);
1677
1678 // aggregate the results
1679 bool is_redund = false;
1680 for (const auto thread_redund: t_redund) {
1681 if (thread_redund) {
1682 is_redund = true;
1683 break;
1684 }
1685 }
1686
1687
1688 /*
1689 // old openMP code:
1690 #pragma omp parallel
1691 {
1692 int this_thread = threadsOMP::getThreadNumber();
1693 int num_threads = threadsOMP::getNumberOfRunningThreads();
1694
1695 auto begin_pos = (this_thread + 0) * v_rep.size() / num_threads;
1696 auto end_pos = (this_thread + 1) * v_rep.size() / num_threads;
1697
1698 for (auto p = begin_pos; p < end_pos; p++) {
1699 #pragma omp flush(is_redund)
1700
1701 if (is_redund) break;
1702
1703 bool thread_redund = true;
1704
1705 auto vsize = vertex.size();
1706
1707 for (Size modality = 0; modality < vsize; modality++) {
1708 if (std::fabs(vertex[modality] - v_rep[p][modality]) > _epsRedund_) {
1709 thread_redund = false;
1710 break;
1711 }
1712 }
1713
1714 if (thread_redund) {
1715 is_redund = true;
1716 #pragma omp flush(is_redund)
1717 int i=0; // this line to work around a weird syntax error with msvc
1718 }
1719 } // end of : each thread for
1720 } // end of : parallel
1721 */
1722
1723 if (!is_redund) v_rep.push_back(vertex);
1724
1725 vertex.clear();
1726 } // end of : file
1727
1728 v_file.close();
1729
1730 if (std::remove(sinefile.c_str()) != 0) GUM_ERROR(IOError, "error removing : " + sinefile)
1731
1732 if (std::remove(extfile.c_str()) != 0) GUM_ERROR(IOError, "error removing : " + extfile)
1733 }
1734
1735 template < GUM_Numeric GUM_SCALAR >
1737 const BayesNet< GUM_SCALAR >* bn_ptr = (_current_bn_ != nullptr) ? _current_bn_ : &_src_bn_;
1740 NodeProperty< NodeType >* nodeType_ptr
1742
1743 for (auto node: bn_ptr->nodes()) {
1744 // indicatrices are already present
1745 if (nodeType_ptr->exists(node)) continue;
1746
1747 bool precise = true, vacuous = true;
1748
1749 for (auto entry = (*cpt_ptr)[node].cbegin(), theEnd2 = (*cpt_ptr)[node].cend();
1750 entry != theEnd2;
1751 ++entry) {
1752 auto vertices = entry->size();
1753 auto var_dSize = (*entry)[0].size();
1754
1755 if (precise && vertices > 1) precise = false;
1756
1757 if (vacuous && vertices == var_dSize) {
1758 std::vector< bool > elem(var_dSize, false);
1759
1760 for (auto vertex = entry->cbegin(), vEnd = entry->cend(); vertex != vEnd; ++vertex) {
1761 for (auto probability = vertex->cbegin(), pEnd = vertex->cend(); probability != pEnd;
1762 ++probability) {
1763 if (*probability == 1) {
1764 elem[probability - vertex->begin()] = true;
1765 break;
1766 }
1767 } // end of : for each modality
1768 } // end of : for each vertex
1769
1770 for (auto probability = elem.cbegin(); probability != elem.cend(); ++probability)
1771 if (*probability == false) vacuous = false;
1772 } // end of : if vertices == dSize
1773 else
1774 vacuous = false;
1775
1776 if (vacuous == false && precise == false) {
1777 nodeType_ptr->insert(node, NodeType::Credal);
1778 break;
1779 }
1780 } // end of : for each parents entry
1781
1782 if (vacuous) nodeType_ptr->insert(node, NodeType::Vacuous);
1783 else if (precise) nodeType_ptr->insert(node, NodeType::Precise);
1784 } // end of : for each variable
1785 }
1786 } // namespace credal
1787} // namespace gum
Definition of templatized reader of BIF files for Bayesian networks.
Definition BIFReader.h:150
Size proceed() override
parse.
Writes a IBayesNet in the BIF format.
Definition BIFWriter.h:79
void write(std::ostream &output, IBayesNet< GUM_SCALAR > &bn)
Writes a Bayesian network in the output stream.
Exception base for CPT error.
double epsilonStandard() const noexcept
virtual Size domainSize() const =0
Exception : a similar element already exists.
Base class for all aGrUM's exceptions.
Definition exceptions.h:133
value_type & insert(const Key &key, const Val &val)
Adds a new element (actually a copy of this element) into the hash table.
void clear()
Removes all the elements in the hash table.
bool exists(const Key &key) const
Checks whether there exists an element with a given key in the hashtable.
Exception : input/output problem.
Class for assigning/browsing values to tuples of discrete variables.
const Sequence< const DiscreteVariable * > & variablesSequence() const final
Returns the sequence of DiscreteVariable of this instantiation.
Idx pos(const DiscreteVariable &v) const final
Returns the position of the variable v.
Instantiation()
Default constructor: creates an empty tuple.
void erase(const DiscreteVariable &v) final
Removes a variable from the Instantiation.
void reorder(const Sequence< const DiscreteVariable * > &v)
Reorder vars of this instantiation giving the order in v.
Idx val(Idx i) const
Returns the current value of the variable at position i.
void setFirst()
Assign the first values to the tuple of the Instantiation.
const DiscreteVariable & variable(Idx i) const final
Returns the variable at position i in the tuple.
Idx nbrDim() const final
Returns the number of variables in the Instantiation.
bool forgetMaster()
Deassociate the master MultiDimAdressable, if any.
class LabelizedVariable
Exception : operation not allowed.
static void farey(int64_t &numerator, int64_t &denominator, const GUM_SCALAR &number, const int64_t &den_max=1000000L, const GUM_SCALAR &zero=static_cast< GUM_SCALAR >(config().epsilonStandard()))
Find the rational close enough to a given ( decimal ) number in [-1,1] and whose denominator is not h...
Exception : problem with size.
void _H2Vlrs_(const std::vector< std::vector< GUM_SCALAR > > &h_rep, std::vector< std::vector< GUM_SCALAR > > &v_rep) const
void _initParams_()
Initialize private constant variables after the Constructor has been called.
GUM_SCALAR _epsilonMoy_
The average perturbation of the BayesNet provided as input for this CredalNet.
Definition credalNet.h:585
void setCPTs(const NodeId &id, const std::vector< std::vector< std::vector< GUM_SCALAR > > > &cpt)
Set the vertices of the credal sets ( all of the conditionals ) of a given node
GUM_SCALAR _deltaC_
5 by default, used by fracC as number of decimals.
Definition credalNet.h:572
Size domainSize(const NodeId &id)
Get the cardinality of a node
std::string toDot() const
BayesNet< GUM_SCALAR > _src_bn_max_
BayesNet used to store upper probabilities.
Definition credalNet.h:615
void _initCNNets_(std::string_view src_min_num, std::string_view src_max_den)
Initialize private BayesNet variables after the Constructor has been called.
BayesNet< GUM_SCALAR > * _current_bn_
Up-to-date BayesNet (used as a DAG).
Definition credalNet.h:618
void _intervalToCredal_()
Computes the vertices of each credal set according to their interval definition (does not use lrs).
std::string toString() const
bool _hasComputedBinaryCPTMinMax_
Used by L2U, to know if lower and upper probabilities over the second modality has been stored in ord...
Definition credalNet.h:637
NodeProperty< std::vector< std::vector< std::vector< GUM_SCALAR > > > > _credalNet_src_cpt_
This CredalNet original CPTs.
Definition credalNet.h:621
const GUM_SCALAR & epsilonMax() const
void _bnCopy_(BayesNet< GUM_SCALAR > &bn_dest)
bool hasComputedBinaryCPTMinMax() const
GUM_SCALAR _precision_
Precision used by frac.
Definition credalNet.h:602
const NodeProperty< std::vector< std::vector< std::vector< GUM_SCALAR > > > > & credalNet_currentCpt() const
void bnToCredal(GUM_SCALAR beta, bool oneNet, bool keepZeroes)
Perturbates the BayesNet provided as input for this CredalNet by generating intervals instead of poin...
void intervalToCredal()
Computes the vertices of each credal set according to their interval definition (uses lrs).
const GUM_SCALAR & epsilonMean() const
std::vector< std::vector< GUM_SCALAR > > _binCptMin_
Used with binary networks to speed-up L2U inference.
Definition credalNet.h:644
void saveBNsMinMax(std::string_view min_path, std::string_view max_path)
If this CredalNet was built over a perturbed BayesNet, one can save the intervals as two BayesNet.
void approximatedBinarization()
Approximate binarization.
const BayesNet< GUM_SCALAR > & src_bn() const
int _find_dNode_card_(const std::vector< std::vector< std::vector< GUM_SCALAR > > > &var_cpt) const
BayesNet< GUM_SCALAR > _src_bn_
Original BayesNet (used as a DAG).
Definition credalNet.h:610
void computeBinaryCPTMinMax()
Used with binary networks to speed-up L2U inference.
const NodeProperty< std::vector< std::vector< std::vector< GUM_SCALAR > > > > & credalNet_srcCpt() const
NodeType currentNodeType(const NodeId &id) const
NodeProperty< NodeType > _original_nodeType_
The NodeType of each node from the ORIGINAL network.
Definition credalNet.h:631
void lagrangeNormalization()
Normalize counts of a BayesNet storing counts of each events such that no probability is 0.
NodeProperty< std::vector< std::vector< std::vector< GUM_SCALAR > > > > * _credalNet_current_cpt_
This CredalNet up-to-date CPTs.
Definition credalNet.h:625
bool isSeparatelySpecified() const
void _sort_varType_()
Set the NodeType of each node
void idmLearning(const Idx s=0, const bool keepZeroes=false)
Learns parameters from a BayesNet storing counts of events.
GUM_SCALAR _epsilonMax_
The highest perturbation of the BayesNet provided as input for this CredalNet.
Definition credalNet.h:581
std::vector< std::vector< GUM_SCALAR > > _binCptMax_
Used with binary networks to speed-up L2U inference.
Definition credalNet.h:652
NodeType nodeType(const NodeId &id) const
Instantiation instantiation(const NodeId &id)
Get an Instantiation from a node id, useful to fill the constraints of the network
bool _separatelySpecified_
TRUE if this CredalNet is separately and interval specified, FALSE otherwise.
Definition credalNet.h:607
void setCPT(const NodeId &id, const Size &entry, const std::vector< std::vector< GUM_SCALAR > > &cpt)
Set the vertices of one credal set of a given node ( any instantiation index )
NodeProperty< std::vector< NodeId > > _var_bits_
Corresponding bits of each variable.
Definition credalNet.h:628
const std::vector< std::vector< GUM_SCALAR > > & get_binaryCPT_max() const
Used with binary networks to speed-up L2U inference.
BayesNet< GUM_SCALAR > _src_bn_min_
BayesNet used to store lower probabilities.
Definition credalNet.h:613
NodeId addVariable(std::string_view name, const Size &card)
Adds a discrete node into the network.
const BayesNet< GUM_SCALAR > & current_bn() const
void addArc(const NodeId &tail, const NodeId &head)
Adds an arc between two nodes.
const std::vector< std::vector< GUM_SCALAR > > & get_binaryCPT_min() const
Used with binary networks to speed-up L2U inference.
void fillConstraints(const NodeId &id, const std::vector< GUM_SCALAR > &lower, const std::vector< GUM_SCALAR > &upper)
Set the interval constraints of the credal sets of a given node (all instantiations )
GUM_SCALAR _epsilonMin_
The lowest perturbation of the BayesNet provided as input for this CredalNet.
Definition credalNet.h:577
const GUM_SCALAR & epsilonMin() const
NodeProperty< NodeType > * _current_nodeType_
The NodeType of each node from the up-to-date network.
Definition credalNet.h:633
GUM_SCALAR _denMax_
Highest possible denominator allowed when using farey.
Definition credalNet.h:599
void fillConstraint(const NodeId &id, const Idx &entry, const std::vector< GUM_SCALAR > &lower, const std::vector< GUM_SCALAR > &upper)
Set the interval constraints of a credal set of a given node ( from an instantiation index )
GUM_SCALAR _epsRedund_
Value under which a decimal number is considered to be zero when computing redundant vertices.
Definition credalNet.h:590
GUM_SCALAR _precisionC_
1e6 by default, used by fracC as precision.
Definition credalNet.h:570
NodeType
NodeType to speed-up computations in some algorithms.
Definition credalNet.h:104
CredalNet()
Constructor used to create a CredalNet step by step, i.e.
GUM_SCALAR _epsF_
Value under which a decimal number is considered to be zero when using farey.
Definition credalNet.h:595
Class template acting as a wrapper for Lexicographic Reverse Search by David Avis.
Definition LrsWrapper.h:121
const matrix & getOutput() const
Get the output matrix solution of the problem.
void H2V()
H-representation to V-representation.
void fillH(const GUM_SCALAR &min, const GUM_SCALAR &max, const Size &modal)
Creates the H-representation of min <= p(X=modal | .) <= max and add it to the problem input _input_.
void setUpH(const Size &card)
Sets up an H-representation.
void nextHInput()
Reset the wrapper for next computation for a H-representation with the same variable cardinality and ...
The options given to a toDot(const DotOptions&).
Definition dotOptions.h:110
const DotArcOptions * arc(Size tail, Size head) const
the options of the arc from tail to head, or nullptr if none was given for it
const DotNodeOptions * node(Size node) const
the options of a node, or nullptr if none was given for it
Writes a graph in the dot language, statement after statement, in the order of the calls.
Definition dotWriter.h:100
void edge(std::string_view from, std::string_view to, const DotAttributes &attributes={})
an edge from from to to (-> in a directed graph, -- in an undirected one).
std::string str() const
The graph written so far, closed. It can be called at any moment, and the writer can be used after.
void node(std::string_view id, const DotAttributes &attributes={})
a node, whose identifier is id (quoted).
Typed, documented, sectioned configuration singleton read from an .ini content.
Class representing Credal Networks.
The statements common to the graphs drawn with graphviz : preamble, attributes of nodes and arcs.
#define GUM_ERROR(type, msg)
Definition exceptions.h:76
#define GUM_SHOWERROR(e)
Definition exceptions.h:89
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
Size NodeId
Type for node ids.
HashTable< NodeId, VAL > NodeProperty
Property on graph elements.
Set< NodeId > NodeSet
Some typdefs and define for shortcuts ...
GUM_SHARED_PUBLIC uint64_t int2Pow(uint64_t exponent)
Specialized base 2 pow function with integer.
Definition pow_inl.h:70
GUM_SHARED_PUBLIC void superiorPow(unsigned long card, unsigned long &num_bits, unsigned long &new_card)
Compute the superior and closest power of two of an integer.
Definition pow_inl.h:79
std::string getUniqueFileName()
Returns a path to a unique file name.
Useful macros for maths.
namespace for all credal networks entities
Definition agrum.h:61
DotAttributes nodeAttributes(const DotStyle &style, const DotNodeOptions *options, std::string_view defaultLabel, std::string_view defaultTooltip)
The attributes of a node : its label and tooltip, and its colors if the options give some.
void writePreamble(DotWriter &writer, const DotStyle &style, const DotOptions &options, std::string_view defaultLabel)
Writes the beginning of a graph, as pyAgrum displays it.
void addDefaultAttribute(DotAttributes &attributes, std::string_view key, std::string_view value)
Adds an attribute at the beginning of the list, unless the list already gives a value for this key : ...
DotAttributes arcAttributes(const DotArcOptions *options)
The attributes of an arc or an edge given by the options : color, penwidth, label,...
gum is the global namespace for all aGrUM entities
Definition agrum.h:46
std::vector< std::pair< Idx, Idx > > dispatchRangeToThreads(const Idx beg, const Idx end, const unsigned int nb_threads)
returns a vector equally splitting elements of a range among threads
Definition threads.cpp:76
Configuration & config()
A short name for Configuration::instance() : gum::config().epsilonStandard(). It is not inline so tha...
bool isCloseToOne(T x, T tol=static_cast< T >(config().epsilonFine()))
Is |x - 1| <= tol ? By default, tol is the key core.epsilonFine of the configuration.
unsigned int getNumberOfThreads()
returns the max number of threads used by default when entering the next parallel region
static DotStyle readCredalNet()
the style of the credal networks : the colors of the nodes are the ones of the section credalnet
Definition dotStyle.cpp:91
static void execute(std::size_t nb_threads, FUNCTION exec_func, ARGS &&... func_args)
executes a function using several threads
static int nbRunningThreadsExecutors()
indicates how many threadExecutors are currently running
Utilities for manipulating strings.