aGrUM 3.3.2
a C++ library for (probabilistic) graphical models
inferenceEngine_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
48
49#include <algorithm>
50
51#include <agrum/agrum.h>
52
55
56namespace gum {
57 namespace credal {
58
59 /*template< GumScalar GUM_SCALAR >
60 InferenceEngine< GUM_SCALAR >::InferenceEngine () : ApproximationScheme() {
61 std::cout << "InferenceEngine construct ()" << std::endl;
62 GUM_CONSTRUCTOR ( InferenceEngine )
63 }*/
64
65 template < GUM_Numeric GUM_SCALAR >
76
77 template < GUM_Numeric GUM_SCALAR >
81
82 template < GUM_Numeric GUM_SCALAR >
86
87 template < GUM_Numeric GUM_SCALAR >
89 evidence_.clear();
90 query_.clear();
91 /*
92 marginalMin_.clear();
93 marginalMax_.clear();
94 oldMarginalMin_.clear();
95 oldMarginalMax_.clear();
96 */
98 /*
99 expectationMin_.clear();
100 expectationMax_.clear();
101 */
103
104 // marginalSets_.clear();
106
107 dynamicExpMin_.clear();
108 dynamicExpMax_.clear();
109
110 //_modal.clear();
111
112 //_t0.clear();
113 //_t1.clear();
114 }
115
116 /*
117 template< GumScalar GUM_SCALAR >
118 void InferenceEngine< GUM_SCALAR >::setIterStop ( const int &iter_stop ) {
119 iterStop_ = iter_stop;
120 }*/
121
122 template < GUM_Numeric GUM_SCALAR >
124 storeBNOpt_ = value;
125 }
126
127 template < GUM_Numeric GUM_SCALAR >
129 storeVertices_ = value;
130
131 if (value) initMarginalSets_();
132 }
133
134 template < GUM_Numeric GUM_SCALAR >
136 bool oldValue = repetitiveInd_;
137 repetitiveInd_ = repetitive;
138
139 // do not compute clusters more than once
140 if (repetitiveInd_ && !oldValue) repetitiveInit_();
141 }
142
143 template < GUM_Numeric GUM_SCALAR >
147
148 /*
149 template< GumScalar GUM_SCALAR >
150 int InferenceEngine< GUM_SCALAR >::iterStop () const {
151 return iterStop_;
152 }*/
153
154 template < GUM_Numeric GUM_SCALAR >
158
159 template < GUM_Numeric GUM_SCALAR >
163
164 template < GUM_Numeric GUM_SCALAR >
165 VarMod2BNsMap< GUM_SCALAR >* InferenceEngine< GUM_SCALAR >::getVarMod2BNsMap() {
166 return &dbnOpt_;
167 }
168
169 template < GUM_Numeric GUM_SCALAR >
171 std::ifstream mod_stream(std::string(path), std::ios::in);
172
173 if (!mod_stream.good()) {
175 "void InferenceEngine< GUM_SCALAR "
176 ">::insertModals(const std::string & path) : "
177 "could not open input file : "
178 << path);
179 }
180
181 if (!modal_.empty()) modal_.clear();
182
183 std::string line, tmp;
184 char * cstr, *p;
185
186 while (mod_stream.good()) {
187 getline(mod_stream, line);
188
189 if (line.size() == 0) continue;
190
191 cstr = new char[line.size() + 1];
192 strcpy(cstr, line.c_str());
193
194 p = strtok(cstr, " ");
195 tmp = p;
196
197 std::vector< GUM_SCALAR > values;
198 p = strtok(nullptr, " ");
199
200 while (p != nullptr) {
201 values.push_back(GUM_SCALAR(atof(p)));
202 p = strtok(nullptr, " ");
203 } // end of : line
205 modal_.insert(tmp, values); //[tmp] = values;
206
207 delete[] p;
208 delete[] cstr;
209 } // end of : file
211 mod_stream.close();
212
214 }
216 template < GUM_Numeric GUM_SCALAR >
218 const std::map< std::string, std::vector< GUM_SCALAR > >& modals) {
219 if (!modal_.empty()) modal_.clear();
220
221 for (auto it = modals.cbegin(), theEnd = modals.cend(); it != theEnd; ++it) {
222 if (!credalNet_->current_bn().exists(it->first)) continue;
223
224 NodeId id = credalNet_->current_bn().idFromName(it->first);
225
226 // check that modals are net compatible
227 auto dSize = credalNet_->current_bn().variable(id).domainSize();
228
229 if (dSize != it->second.size()) continue;
230
231 // GUM_ERROR(OperationNotAllowed, "void InferenceEngine< GUM_SCALAR
232 // >::insertModals( const std::map< std::string, std::vector< GUM_SCALAR
233 // > >
234 // &modals) : modalities does not respect variable cardinality : " <<
235 // credalNet_->current_bn().variable( id ).name() << " : " << dSize << "
236 // != "
237 // << it->second.size());
238
239 modal_.insert(it->first, it->second); //[ it->first ] = it->second;
241
242 //_modal = modals;
243
244 initExpectations_();
245 }
246
247 template < GUM_Numeric GUM_SCALAR >
249 const std::map< std::string, std::vector< GUM_SCALAR > >& eviMap) {
250 if (!evidence_.empty()) evidence_.clear();
251
252 for (auto it = eviMap.cbegin(), theEnd = eviMap.cend(); it != theEnd; ++it) {
253 if (!credalNet_->current_bn().exists(it->first)) continue;
254
255 NodeId id = credalNet_->current_bn().idFromName(it->first);
256
257 evidence_.insert(id, it->second);
258 }
259
260 // forces the computation of the begin iterator to avoid subsequent data races
261 // @TODO make HashTableConstIterator constructors thread safe
262 evidence_.begin();
263 }
265 // check that observed variables DO exists in the network (otherwise Lazy
266 // report
267 // an error and app crash)
268 template < GUM_Numeric GUM_SCALAR >
270 const NodeProperty< std::vector< GUM_SCALAR > >& evidence) {
271 if (!evidence_.empty()) evidence_.clear();
272
273 // use cbegin() to get const_iterator when available in aGrUM hashtables
274 for (const auto& elt: evidence) {
275 if (!credalNet_->current_bn().exists(elt.first)) continue;
276
277 evidence_.insert(elt.first, elt.second);
278 }
279
280 // forces the computation of the begin iterator to avoid subsequent data races
281 // @TODO make HashTableConstIterator constructors thread safe
282 evidence_.begin();
283 }
284
285 template < GUM_Numeric GUM_SCALAR >
287 std::ifstream evi_stream(std::string(path), std::ios::in);
288
289 if (!evi_stream.good()) {
291 "void InferenceEngine< GUM_SCALAR "
292 ">::insertEvidence(const std::string & path) : could not "
293 "open input file : "
294 << path);
295 }
296
297 if (!evidence_.empty()) evidence_.clear();
298
299 std::string line, tmp;
300 char * cstr, *p;
301
302 while (evi_stream.good() && std::strcmp(line.c_str(), "[EVIDENCE]") != 0) {
303 getline(evi_stream, line);
304 }
305
306 while (evi_stream.good()) {
307 getline(evi_stream, line);
308
309 if (std::strcmp(line.c_str(), "[QUERY]") == 0) break;
310
311 if (line.size() == 0) continue;
312
313 cstr = new char[line.size() + 1];
314 strcpy(cstr, line.c_str());
316 p = strtok(cstr, " ");
317 tmp = p;
318
319 // if user input is wrong
320 NodeId node = -1;
321
322 if (!credalNet_->current_bn().exists(tmp)) continue;
323 node = credalNet_->current_bn().idFromName(tmp);
324
325 std::vector< GUM_SCALAR > values;
326 p = strtok(nullptr, " ");
328 while (p != nullptr) {
329 values.push_back(GUM_SCALAR(atof(p)));
330 p = strtok(nullptr, " ");
331 } // end of : line
332
333 evidence_.insert(node, values);
334
335 delete[] p;
336 delete[] cstr;
337 } // end of : file
338
339 evi_stream.close();
340
341 // forces the computation of the begin iterator to avoid subsequent data races
342 // @TODO make HashTableConstIterator constructors thread safe
343 evidence_.begin();
344 }
345
346 template < GUM_Numeric GUM_SCALAR >
348 const NodeProperty< std::vector< bool > >& query) {
349 if (!query_.empty()) query_.clear();
350
351 for (const auto& elt: query) {
352 if (!credalNet_->current_bn().exists(elt.first)) continue;
353
354 query_.insert(elt.first, elt.second);
356 }
357
358 template < GUM_Numeric GUM_SCALAR >
360 std::ifstream evi_stream(std::string(path), std::ios::in);
361
362 if (!evi_stream.good()) {
364 "void InferenceEngine< GUM_SCALAR >::insertQuery(const "
365 "std::string & path) : could not open input file : "
366 << path);
367 }
368
369 if (!query_.empty()) query_.clear();
370
371 std::string line, tmp;
372 char * cstr, *p;
373
374 while (evi_stream.good() && std::strcmp(line.c_str(), "[QUERY]") != 0) {
375 getline(evi_stream, line);
376 }
377
378 while (evi_stream.good()) {
379 getline(evi_stream, line);
381 if (std::strcmp(line.c_str(), "[EVIDENCE]") == 0) break;
382
383 if (line.size() == 0) continue;
384
385 cstr = new char[line.size() + 1];
386 strcpy(cstr, line.c_str());
387
388 p = strtok(cstr, " ");
389 tmp = p;
390
391 // if user input is wrong
392 NodeId node = -1;
393
394 if (!credalNet_->current_bn().exists(tmp)) continue;
395 node = credalNet_->current_bn().idFromName(tmp);
396
397 auto dSize = credalNet_->current_bn().variable(node).domainSize();
399 p = strtok(nullptr, " ");
400
401 if (p == nullptr) {
402 query_.insert(node, std::vector< bool >(dSize, true));
403 } else {
404 std::vector< bool > values(dSize, false);
405
406 while (p != nullptr) {
407 if ((Size)atoi(p) >= dSize)
409 "void InferenceEngine< GUM_SCALAR "
410 ">::insertQuery(const std::string & path) : "
411 "query modality is higher or equal to "
412 "cardinality");
413
414 values[atoi(p)] = true;
415 p = strtok(nullptr, " ");
416 } // end of : line
417
418 query_.insert(node, values);
419 }
421 delete[] p;
422 delete[] cstr;
423 } // end of : file
424
425 evi_stream.close();
426 }
427
428 template < GUM_Numeric GUM_SCALAR >
429 Tensor< GUM_SCALAR >
430 InferenceEngine< GUM_SCALAR >::marginalMin(std::string_view varName) const {
431 return marginalMin(credalNet_->current_bn().idFromName(varName));
433
434 template < GUM_Numeric GUM_SCALAR >
435 Tensor< GUM_SCALAR >
436 InferenceEngine< GUM_SCALAR >::marginalMax(std::string_view varName) const {
437 return marginalMax(credalNet_->current_bn().idFromName(varName));
439
440 template < GUM_Numeric GUM_SCALAR >
442 Tensor< GUM_SCALAR > res;
443 res.add(credalNet_->current_bn().variable(id));
444 res.fillWith(marginalMin_[id]);
445 return res;
446 }
447
448 template < GUM_Numeric GUM_SCALAR >
450 Tensor< GUM_SCALAR > res;
451 res.add(credalNet_->current_bn().variable(id));
452 res.fillWith(marginalMax_[id]);
453 return res;
454 }
455
456 template < GUM_Numeric GUM_SCALAR >
457 const GUM_SCALAR&
458 InferenceEngine< GUM_SCALAR >::expectationMin(std::string_view varName) const {
459 return expectationMin_[credalNet_->current_bn().idFromName(varName)];
460 }
461
462 template < GUM_Numeric GUM_SCALAR >
463 const GUM_SCALAR&
464 InferenceEngine< GUM_SCALAR >::expectationMax(std::string_view varName) const {
465 return expectationMax_[credalNet_->current_bn().idFromName(varName)];
466 }
467
468 template < GUM_Numeric GUM_SCALAR >
469 const GUM_SCALAR& InferenceEngine< GUM_SCALAR >::expectationMin(const NodeId id) const {
470 return expectationMin_[id];
471 }
472
473 template < GUM_Numeric GUM_SCALAR >
474 const GUM_SCALAR& InferenceEngine< GUM_SCALAR >::expectationMax(const NodeId id) const {
475 return expectationMax_[id];
476 }
477
478 template < GUM_Numeric GUM_SCALAR >
479 const std::vector< GUM_SCALAR >&
480 InferenceEngine< GUM_SCALAR >::dynamicExpMin(std::string_view varName) const {
481 std::string errTxt = "const std::vector< GUM_SCALAR > & InferenceEngine< "
482 "GUM_SCALAR >::dynamicExpMin ( const std::string & "
483 "varName ) const : ";
484
485 if (dynamicExpMin_.empty())
486 GUM_ERROR(OperationNotAllowed, errTxt + "_dynamicExpectations() needs to be called before")
488 auto p = dynamicExpMin_.tryGet(varName);
489 if (!p /*dynamicExpMin_.find(varName) == dynamicExpMin_.end()*/)
490 GUM_ERROR(NotFound, errTxt + "variable name not found : " << varName)
491
492 return *p;
493 }
495 template < GUM_Numeric GUM_SCALAR >
496 const std::vector< GUM_SCALAR >&
497 InferenceEngine< GUM_SCALAR >::dynamicExpMax(std::string_view varName) const {
498 std::string errTxt = "const std::vector< GUM_SCALAR > & InferenceEngine< "
499 "GUM_SCALAR >::dynamicExpMax ( const std::string & "
500 "varName ) const : ";
502 if (dynamicExpMax_.empty())
503 GUM_ERROR(OperationNotAllowed, errTxt + "_dynamicExpectations() needs to be called before")
504
505 auto p = dynamicExpMax_.tryGet(varName);
506 if (!p /*dynamicExpMin_.find(varName) == dynamicExpMin_.end()*/)
507 GUM_ERROR(NotFound, errTxt + "variable name not found : " << varName)
509 return *p;
510 }
511
512 template < GUM_Numeric GUM_SCALAR >
513 const std::vector< std::vector< GUM_SCALAR > >&
515 return marginalSets_[id];
516 }
517
518 template < GUM_Numeric GUM_SCALAR >
519 void InferenceEngine< GUM_SCALAR >::saveMarginals(std::string_view path) const {
520 std::ofstream m_stream(std::string(path), std::ios::out | std::ios::trunc);
521
522 if (!m_stream.good()) {
524 "void InferenceEngine< GUM_SCALAR >::saveMarginals(const "
525 "std::string & path) const : could not open output file "
526 ": " << path);
527 }
528
529 for (const auto& elt: marginalMin_) {
530 Size esize = Size(elt.second.size());
531
532 for (Size mod = 0; mod < esize; mod++) {
533 m_stream << credalNet_->current_bn().variable(elt.first).name() << " " << mod << " "
534 << (elt.second)[mod] << " " << marginalMax_[elt.first][mod] << std::endl;
535 }
536 }
537
538 m_stream.close();
539 }
540
541 template < GUM_Numeric GUM_SCALAR >
542 void InferenceEngine< GUM_SCALAR >::saveExpectations(std::string_view path) const {
543 if (dynamicExpMin_.empty()) //_modal.empty())
544 return;
545
546 // else not here, to keep the const (natural with a saving process)
547 // else if(dynamicExpMin_.empty() || dynamicExpMax_.empty())
548 //_dynamicExpectations(); // works with or without a dynamic network
549
550 std::ofstream m_stream(std::string(path), std::ios::out | std::ios::trunc);
551
552 if (!m_stream.good()) {
554 "void InferenceEngine< GUM_SCALAR "
555 ">::saveExpectations(const std::string & path) : could "
556 "not open output file : "
557 << path);
558 }
559
560 for (const auto& elt: dynamicExpMin_) {
561 m_stream << elt.first; // it->first;
563 // iterates over a vector
564 for (const auto& elt2: elt.second) {
565 m_stream << " " << elt2;
566 }
567
568 m_stream << std::endl;
569 }
570
571 for (const auto& elt: dynamicExpMax_) {
572 m_stream << elt.first;
573
574 // iterates over a vector
575 for (const auto& elt2: elt.second) {
576 m_stream << " " << elt2;
577 }
578
579 m_stream << std::endl;
581
582 m_stream.close();
583 }
584
585 template < GUM_Numeric GUM_SCALAR >
587 std::stringstream output;
588 output << std::endl;
589
590 // use cbegin() when available
591 for (const auto& elt: marginalMin_) {
592 Size esize = Size(elt.second.size());
593
594 for (Size mod = 0; mod < esize; mod++) {
595 output << "P(" << credalNet_->current_bn().variable(elt.first).name() << "=" << mod
596 << "|e) = [ ";
597 output << marginalMin_[elt.first][mod] << ", " << marginalMax_[elt.first][mod] << " ]";
598
599 if (!query_.empty()) {
600 if (auto p_query = query_.tryGet(elt.first); p_query && (*p_query)[mod])
601 output << " QUERY";
602 }
603
604 output << std::endl;
605 }
606
607 output << std::endl;
608 }
609
610 return output.str();
611 }
612
613 template < GUM_Numeric GUM_SCALAR >
614 void InferenceEngine< GUM_SCALAR >::saveVertices(std::string_view path) const {
615 std::ofstream m_stream(std::string(path), std::ios::out | std::ios::trunc);
616
617 if (!m_stream.good()) {
619 "void InferenceEngine< GUM_SCALAR >::saveVertices(const "
620 "std::string & path) : could not open outpul file : "
621 << path);
622 }
623
624 for (const auto& elt: marginalSets_) {
625 m_stream << credalNet_->current_bn().variable(elt.first).name() << std::endl;
626
627 for (const auto& elt2: elt.second) {
628 m_stream << "[";
629 bool first = true;
630
631 for (const auto& elt3: elt2) {
632 if (!first) { m_stream << ","; }
633 first = false;
634 m_stream << elt3;
635 }
636
637 m_stream << "]\n";
638 }
639 }
640
641 m_stream.close();
642 }
643
644 template < GUM_Numeric GUM_SCALAR >
646 marginalMin_.clear();
647 marginalMax_.clear();
648 oldMarginalMin_.clear();
649 oldMarginalMax_.clear();
650
651 for (auto node: credalNet_->current_bn().nodes()) {
652 auto dSize = credalNet_->current_bn().variable(node).domainSize();
653 marginalMin_.insert(node, std::vector< GUM_SCALAR >(dSize, 1));
654 oldMarginalMin_.insert(node, std::vector< GUM_SCALAR >(dSize, 1));
655
656 marginalMax_.insert(node, std::vector< GUM_SCALAR >(dSize, 0));
657 oldMarginalMax_.insert(node, std::vector< GUM_SCALAR >(dSize, 0));
658 }
659
660 // now that we know the sizes of marginalMin_ and marginalMax_, we can
661 // dispatch their processes to the threads
663 }
664
665 template < GUM_Numeric GUM_SCALAR >
667 marginalSets_.clear();
668
669 if (!storeVertices_) return;
670
671 for (auto node: credalNet_->current_bn().nodes())
672 marginalSets_.insert(node, std::vector< std::vector< GUM_SCALAR > >());
673 }
674
675 // since only monitored variables in modal_ will be alble to compute
676 // expectations, it is useless to initialize those for all variables
677 // modal_ variables will always be checked further, so it is not necessary
678 // to
679 // check it here, but doing so will use less memory
680 template < GUM_Numeric GUM_SCALAR >
682 expectationMin_.clear();
683 expectationMax_.clear();
684
685 if (modal_.empty()) return;
686
687 for (auto node: credalNet_->current_bn().nodes()) {
688 std::string var_name, time_step;
689
690 var_name = credalNet_->current_bn().variable(node).name();
691 auto delim = var_name.find_first_of("_");
692 var_name = var_name.substr(0, delim);
693
694 auto p_modal = modal_.tryGet(var_name);
695 if (!p_modal) continue;
696
697 expectationMin_.insert(node, p_modal->back());
698 expectationMax_.insert(node, p_modal->front());
699 }
700 }
701
702 template < GUM_Numeric GUM_SCALAR >
706
707 template < GUM_Numeric GUM_SCALAR >
709 // no modals, no expectations computed during inference
710 if (expectationMin_.empty() || modal_.empty()) return;
711
712 // already called by the algorithm or the user
713 if (dynamicExpMax_.size() > 0 && dynamicExpMin_.size() > 0) return;
714
715 using innerMap = typename gum::HashTable< int, GUM_SCALAR >;
716
717 using outerMap = typename gum::HashTable< std::string, innerMap >;
718
719
720 // if non dynamic, directly save expectationMin_ et Max (same but faster)
721 outerMap expectationsMin, expectationsMax;
722
723 for (const auto& elt: expectationMin_) {
724 std::string var_name, time_step;
725
726 var_name = credalNet_->current_bn().variable(elt.first).name();
727 auto delim = var_name.find_first_of("_");
728 time_step = var_name.substr(delim + 1, var_name.size());
729 var_name = var_name.substr(0, delim);
730
731 // to be sure (don't store not monitored variables' expectations)
732 // although it
733 // should be taken care of before this point
734 if (!modal_.exists(var_name)) continue;
735
736 expectationsMin.getWithDefault(var_name, innerMap())
737 .getWithDefault(atoi(time_step.c_str()), 0)
738 = elt.second; // we iterate with min iterators
739 expectationsMax.getWithDefault(var_name, innerMap())
740 .getWithDefault(atoi(time_step.c_str()), 0) = expectationMax_[elt.first];
741 }
742
743 for (const auto& elt: expectationsMin) {
744 typename std::vector< GUM_SCALAR > dynExp(elt.second.size());
745
746 for (const auto& elt2: elt.second)
747 dynExp[elt2.first] = elt2.second;
748
749 dynamicExpMin_.insert(elt.first, dynExp);
750 }
751
752 for (const auto& elt: expectationsMax) {
753 typename std::vector< GUM_SCALAR > dynExp(elt.second.size());
754
755 for (const auto& elt2: elt.second) {
756 dynExp[elt2.first] = elt2.second;
757 }
758
759 dynamicExpMax_.insert(elt.first, dynExp);
760 }
761 }
762
763 template < GUM_Numeric GUM_SCALAR >
765 timeSteps_ = 0;
766 t0_.clear();
767 t1_.clear();
768
769 // t = 0 vars belongs to t0_ as keys
770 for (auto node: credalNet_->current_bn().internalDag().nodes()) {
771 std::string var_name = credalNet_->current_bn().variable(node).name();
772 auto delim = var_name.find_first_of("_");
773
774 if (delim > var_name.size()) {
776 "void InferenceEngine< GUM_SCALAR "
777 ">::repetitiveInit_() : the network does not "
778 "appear to be dynamic");
779 }
780
781 std::string time_step = var_name.substr(delim + 1, 1);
782
783 if (time_step.compare("0") == 0) t0_.insert(node, std::vector< NodeId >());
784 }
785
786 // t = 1 vars belongs to either t0_ as member value or t1_ as keys
787 for (const auto& node: credalNet_->current_bn().internalDag().nodes()) {
788 std::string var_name = credalNet_->current_bn().variable(node).name();
789 auto delim = var_name.find_first_of("_");
790 std::string time_step = var_name.substr(delim + 1, var_name.size());
791 var_name = var_name.substr(0, delim);
792 delim = time_step.find_first_of("_");
793 time_step = time_step.substr(0, delim);
794
795 if (time_step.compare("1") == 0) {
796 bool found = false;
797
798 for (const auto& elt: t0_) {
799 std::string var_0_name = credalNet_->current_bn().variable(elt.first).name();
800 delim = var_0_name.find_first_of("_");
801 var_0_name = var_0_name.substr(0, delim);
802
803 if (var_name.compare(var_0_name) == 0) {
804 const Tensor< GUM_SCALAR >* tensor(&credalNet_->current_bn().cpt(node));
805 const Tensor< GUM_SCALAR >* tensor2(&credalNet_->current_bn().cpt(elt.first));
806
807 if (tensor->domainSize() == tensor2->domainSize()) t0_[elt.first].push_back(node);
808 else t1_.insert(node, std::vector< NodeId >());
809
810 found = true;
811 break;
812 }
813 }
814
815 if (!found) { t1_.insert(node, std::vector< NodeId >()); }
816 }
817 }
818
819 // t > 1 vars belongs to either t0_ or t1_ as member value
820 // remember timeSteps_
821 for (auto node: credalNet_->current_bn().internalDag().nodes()) {
822 std::string var_name = credalNet_->current_bn().variable(node).name();
823 auto delim = var_name.find_first_of("_");
824 std::string time_step = var_name.substr(delim + 1, var_name.size());
825 var_name = var_name.substr(0, delim);
826 delim = time_step.find_first_of("_");
827 time_step = time_step.substr(0, delim);
828
829 if (time_step.compare("0") != 0 && time_step.compare("1") != 0) {
830 // keep max time_step
831 if (atoi(time_step.c_str()) > timeSteps_) timeSteps_ = atoi(time_step.c_str());
832
833 std::string var_0_name;
834 bool found = false;
835
836 for (const auto& elt: t0_) {
837 std::string var_0_name = credalNet_->current_bn().variable(elt.first).name();
838 delim = var_0_name.find_first_of("_");
839 var_0_name = var_0_name.substr(0, delim);
840
841 if (var_name.compare(var_0_name) == 0) {
842 const Tensor< GUM_SCALAR >* tensor(&credalNet_->current_bn().cpt(node));
843 const Tensor< GUM_SCALAR >* tensor2(&credalNet_->current_bn().cpt(elt.first));
844
845 if (tensor->domainSize() == tensor2->domainSize()) {
846 t0_[elt.first].push_back(node);
847 found = true;
848 break;
849 }
850 }
851 }
852
853 if (!found) {
854 for (const auto& elt: t1_) {
855 std::string var_0_name = credalNet_->current_bn().variable(elt.first).name();
856 auto delim = var_0_name.find_first_of("_");
857 var_0_name = var_0_name.substr(0, delim);
858
859 if (var_name.compare(var_0_name) == 0) {
860 const Tensor< GUM_SCALAR >* tensor(&credalNet_->current_bn().cpt(node));
861 const Tensor< GUM_SCALAR >* tensor2(&credalNet_->current_bn().cpt(elt.first));
862
863 if (tensor->domainSize() == tensor2->domainSize()) {
864 t1_[elt.first].push_back(node);
865 break;
866 }
867 }
868 }
869 }
870 }
871 }
872 }
873
874 template < GUM_Numeric GUM_SCALAR >
876 const NodeId& id,
877 const std::vector< GUM_SCALAR >& vertex) {
878 std::string var_name = credalNet_->current_bn().variable(id).name();
879 auto delim = var_name.find_first_of("_");
880
881 var_name = var_name.substr(0, delim);
882
883 if (auto p_modal = modal_.tryGet(var_name)) {
884 GUM_SCALAR exp = 0;
885 auto vsize = vertex.size();
886
887 for (Size mod = 0; mod < vsize; mod++)
888 exp += vertex[mod] * (*p_modal)[mod];
889
890 if (exp > expectationMax_[id]) expectationMax_[id] = exp;
891
892 if (exp < expectationMin_[id]) expectationMin_[id] = exp;
893 }
894 }
895
896 template < GUM_Numeric GUM_SCALAR >
898 const std::vector< GUM_SCALAR >& vertex,
899 const bool& elimRedund) {
900 auto& nodeCredalSet = marginalSets_[id];
901 auto dsize = vertex.size();
902
903 bool eq = true;
904 const double epsilon = config().epsilonStandard();
905
906 for (auto it = nodeCredalSet.cbegin(), itEnd = nodeCredalSet.cend(); it != itEnd; ++it) {
907 eq = true;
908
909 for (Size i = 0; i < dsize; i++) {
910 if (std::fabs(vertex[i] - (*it)[i]) > epsilon) {
911 eq = false;
912 break;
913 }
914 }
915
916 if (eq) break;
917 }
918
919 if (!eq || nodeCredalSet.size() == 0) {
920 nodeCredalSet.push_back(vertex);
921 } else return;
922
923 // because of next lambda return condition
924 if (nodeCredalSet.size() == 1) return;
925
926 // check that the point and all previously added ones are not inside the
927 // actual
928 // polytope
929 auto itEnd = std::remove_if(
930 nodeCredalSet.begin(),
931 nodeCredalSet.end(),
932 [&](const std::vector< GUM_SCALAR >& v) -> bool {
933 for (auto jt = v.cbegin(),
934 jtEnd = v.cend(),
935 minIt = marginalMin_[id].cbegin(),
936 minItEnd = marginalMin_[id].cend(),
937 maxIt = marginalMax_[id].cbegin(),
938 maxItEnd = marginalMax_[id].cend();
939 jt != jtEnd && minIt != minItEnd && maxIt != maxItEnd;
940 ++jt, ++minIt, ++maxIt) {
941 if ((std::fabs(*jt - *minIt) < epsilon || std::fabs(*jt - *maxIt) < epsilon)
942 && std::fabs(*minIt - *maxIt) > epsilon)
943 return false;
944 }
945 return true;
946 });
947
948 nodeCredalSet.erase(itEnd, nodeCredalSet.end());
949
950 // we need at least 2 points to make a convex combination
951 if (!elimRedund || nodeCredalSet.size() <= 2) return;
952
953 // there may be points not inside the polytope but on one of it's facet,
954 // meaning it's still a convex combination of vertices of this facet. Here
955 // we
956 // need lrs.
957 LRSWrapper< GUM_SCALAR > lrsWrapper;
958 lrsWrapper.setUpV((unsigned int)dsize, (unsigned int)(nodeCredalSet.size()));
959
960 for (const auto& vtx: nodeCredalSet)
961 lrsWrapper.fillV(vtx);
962
963 lrsWrapper.elimRedundVrep();
964
965 marginalSets_[id] = lrsWrapper.getOutput();
966 }
967
968 template < GUM_Numeric GUM_SCALAR >
973
974 template < GUM_Numeric GUM_SCALAR >
979
980 template < GUM_Numeric GUM_SCALAR >
982 // compute the number of threads and prepare for the result
983 const Size nb_threads = ThreadExecutor::nbRunningThreadsExecutors() == 0
984 ? this->threadRanges_.size() - 1
985 : 1; // no nested multithreading
986 std::vector< GUM_SCALAR > tEps(nb_threads, std::numeric_limits< GUM_SCALAR >::max());
987
988 // create the function to be executed by the threads
989 auto threadedEps = [this, &tEps](const std::size_t this_thread,
990 const std::size_t nb_threads,
991 const std::vector< std::pair< NodeId, Idx > >& ranges) {
992 auto& this_tEps = tEps[this_thread];
993 GUM_SCALAR delta;
994
995 // below, we will loop over indices i and j of marginalMin_ and
996 // marginalMax_. Index i represents nodes and j allow to parse their
997 // domain. To parse all the domains of all the nodes, we should theorically
998 // use 2 loops. However, here, we will use one loop: we start with node i
999 // and parse its domain with index j. When this is done, we move to the
1000 // next node, and so on. The underlying idea is that, by doing so, we
1001 // need not parse in this function the whole domain of a node: we can start
1002 // the loop at a given value of node i and complete the loop on another
1003 // value of another node. These values are computed in Vector threadRanges_
1004 // by Method dispatchMarginalsToThreads_(), which dispatches the loops
1005 // among threads
1006 auto i = ranges[this_thread].first;
1007 auto j = ranges[this_thread].second;
1008 auto domain_size = this->marginalMax_[i].size();
1009 const auto end_i = ranges[this_thread + 1].first;
1010 auto end_j = ranges[this_thread + 1].second;
1011 const auto marginalMax_size = this->marginalMax_.size();
1012
1013 while ((i < end_i) || (j < end_j)) {
1014 // on min
1015 delta = marginalMin_[i][j] - oldMarginalMin_[i][j];
1016 delta = (delta < 0) ? (-delta) : delta;
1017 this_tEps = (this_tEps < delta) ? delta : this_tEps;
1018
1019 // on max
1020 delta = marginalMax_[i][j] - oldMarginalMax_[i][j];
1021 delta = (delta < 0) ? (-delta) : delta;
1022 this_tEps = (this_tEps < delta) ? delta : this_tEps;
1023
1024 oldMarginalMin_[i][j] = marginalMin_[i][j];
1025 oldMarginalMax_[i][j] = marginalMax_[i][j];
1026
1027 if (++j == domain_size) {
1028 j = 0;
1029 ++i;
1030 if (i < marginalMax_size) domain_size = this->marginalMax_[i].size();
1031 }
1032 }
1033 };
1034
1035 // launch the threads
1037 nb_threads,
1038 threadedEps,
1039 (nb_threads == 1)
1040 ? std::vector< std::pair< NodeId, Idx > >{{0, 0}, {this->marginalMin_.size(), 0}}
1041 : this->threadRanges_);
1042
1043 // aggregate all the results
1044 GUM_SCALAR eps = tEps[0];
1045 for (const auto nb: tEps)
1046 if (eps < nb) eps = nb;
1047
1048 return eps;
1049 }
1050
1051 /*
1052 // old openMP code:
1053 GUM_SCALAR eps = 0;
1054 #pragma omp parallel
1055 {
1056 GUM_SCALAR tEps = 0;
1057 GUM_SCALAR delta;
1058
1060 int nsize = int(marginalMin_.size());
1061
1062 #pragma omp for
1063
1064 for (int i = 0; i < nsize; i++) {
1065 auto dSize = marginalMin_[i].size();
1066
1067 for (Size j = 0; j < dSize; j++) {
1068 // on min
1069 delta = marginalMin_[i][j] - oldMarginalMin_[i][j];
1070 delta = (delta < 0) ? (-delta) : delta;
1071 tEps = (tEps < delta) ? delta : tEps;
1072
1073 // on max
1074 delta = marginalMax_[i][j] - oldMarginalMax_[i][j];
1075 delta = (delta < 0) ? (-delta) : delta;
1076 tEps = (tEps < delta) ? delta : tEps;
1077
1078 oldMarginalMin_[i][j] = marginalMin_[i][j];
1079 oldMarginalMax_[i][j] = marginalMax_[i][j];
1080 }
1081 } // end of : all variables
1082
1083 #pragma omp critical(epsilon_max)
1084 {
1085 #pragma omp flush(eps)
1086 eps = (eps < tEps) ? tEps : eps;
1087 }
1088 }
1089
1090 return eps;
1091 }
1092 */
1093
1094
1095 template < GUM_Numeric GUM_SCALAR >
1097 // we compute the number of elements in the 2 loops (over i,j in marginalMin_[i][j])
1098 Size nb_elements = 0;
1099 const auto marginalMin_size = this->marginalMin_.size();
1100 for (const auto& marg_i: this->marginalMin_)
1101 nb_elements += marg_i.second.size();
1102
1103 // distribute evenly the elements among the threads
1104 auto nb_threads = ThreadNumberManager::getNumberOfThreads();
1105 if (nb_elements < nb_threads) nb_threads = nb_elements;
1106
1107 // the result that we return is a vector of pairs (NodeId, Idx). For thread number i, the
1108 // pair at index i is the beginning of the range that the thread will have to process: this
1109 // is the part of the marginal distribution vector of node NodeId starting at index Idx.
1110 // The pair at index i+1 is the end of this range (not included)
1111 threadRanges_.clear();
1112 threadRanges_.reserve(nb_threads + 1);
1113
1114 // try to balance the number of elements among the threads
1115 Idx nb_elts_par_thread = nb_elements / nb_threads;
1116 Idx rest_elts = nb_elements - nb_elts_par_thread * nb_threads;
1117
1118 NodeId current_node = 0;
1119 Idx current_domain_index = 0;
1120 Size current_domain_size = this->marginalMin_[0].size();
1121 threadRanges_.emplace_back(current_node, current_domain_index);
1122
1123 for (Idx i = Idx(0); i < nb_threads; ++i) {
1124 // compute the end of the threads, assuming that the current node has a domain
1125 // sufficiently large
1126 current_domain_index += nb_elts_par_thread;
1127 if (rest_elts != Idx(0)) {
1128 ++current_domain_index;
1129 --rest_elts;
1130 }
1131
1132 // if the current node is not sufficient to hold all the elements that
1133 // the current thread should process. So we should add elements of the
1134 // next nodes
1135 while (current_domain_index >= current_domain_size) {
1136 current_domain_index -= current_domain_size;
1137 ++current_node;
1138 current_domain_index = 0;
1139 if (current_node != marginalMin_size) {
1140 current_domain_size = this->marginalMin_[current_node].size();
1141 }
1142 }
1143
1144 // now we can store the range if elements
1145 threadRanges_.emplace_back(current_node, current_domain_index);
1146
1147 // compute the next begin_node
1148 if (current_domain_index == current_domain_size) {
1149 ++current_node;
1150 current_domain_index = 0;
1151 }
1152 }
1153 }
1154
1155 template < GUM_Numeric GUM_SCALAR >
1157 const std::vector< GUM_SCALAR >& vals) {
1158 evidence_.insert(id, vals);
1159 // forces the computation of the begin iterator to avoid subsequent data races
1160 // @TODO make HashTableConstIterator constructors thread safe
1161 evidence_.begin();
1162 }
1163
1165 template < GUM_Numeric GUM_SCALAR >
1167 std::vector< GUM_SCALAR > vals(this->credalNet_->current_bn().variable(id).domainSize(), 0);
1168 vals[val] = 1;
1169 addEvidence(id, vals);
1170 }
1171
1173 template < GUM_Numeric GUM_SCALAR >
1174 void InferenceEngine< GUM_SCALAR >::addEvidence(std::string_view nodeName, const Idx val) {
1175 addEvidence(this->credalNet_->current_bn().idFromName(nodeName), val);
1176 }
1177
1179 template < GUM_Numeric GUM_SCALAR >
1180 void InferenceEngine< GUM_SCALAR >::addEvidence(NodeId id, std::string_view label) {
1181 addEvidence(id, this->credalNet_->current_bn().variable(id)[label]);
1182 }
1183
1185 template < GUM_Numeric GUM_SCALAR >
1186 void InferenceEngine< GUM_SCALAR >::addEvidence(std::string_view nodeName,
1187 std::string_view label) {
1188 const NodeId id = this->credalNet_->current_bn().idFromName(nodeName);
1189 addEvidence(id, this->credalNet_->current_bn().variable(id)[label]);
1190 }
1191
1192 template < GUM_Numeric GUM_SCALAR >
1193 void InferenceEngine< GUM_SCALAR >::addEvidence(std::string_view nodeName,
1194 const std::vector< GUM_SCALAR >& vals) {
1195 addEvidence(this->credalNet_->current_bn().idFromName(nodeName), vals);
1196 }
1197
1198 template < GUM_Numeric GUM_SCALAR >
1199 void InferenceEngine< GUM_SCALAR >::addEvidence(const Tensor< GUM_SCALAR >& pot) {
1200 const auto id = this->credalNet_->current_bn().idFromName(pot.variable(0).name());
1201 std::vector< GUM_SCALAR > vals(this->credalNet_->current_bn().variable(id).domainSize(), 0);
1202 Instantiation I(pot);
1203 for (I.setFirst(); !I.end(); I.inc()) {
1204 vals[I.val(0)] = pot[I];
1205 }
1206 addEvidence(id, vals);
1207 }
1208
1209 template < GUM_Numeric GUM_SCALAR >
1213
1214 } // namespace credal
1215} // namespace gum
ApproximationScheme()
Build a scheme whose parameters are read from the configuration.
double epsilon() const override
Returns the value of epsilon.
double epsilonStandard() const noexcept
The class for generic Hash Tables.
Definition hashTable.h:640
void clear()
Removes all the elements in the hash table.
std::string messageApproximationScheme() const
Returns the approximation scheme message.
Exception : input/output problem.
Class for assigning/browsing values to tuples of discrete variables.
bool end() const
Returns true if the Instantiation reached the end.
void inc()
Operator increment.
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.
Exception: at least one argument passed to a function is not what was expected.
Exception : the element we looked for cannot be found.
Exception : operation not allowed.
Exception : out of bound.
aGrUM's Tensor is a multi-dimensional array with tensor operators.
Definition tensor.h:85
Size getNumberOfThreads() const override
returns the current max number of threads used by the class containing this ThreadNumberManager
Class template representing a Credal Network.
Definition credalNet.h:101
void updateExpectations_(const NodeId &id, const std::vector< GUM_SCALAR > &vertex)
Given a node id and one of it's possible vertex obtained during inference, update this node lower and...
void repetitiveInit_()
Initialize t0_ and t1_ clusters.
void dynamicExpectations()
Compute dynamic expectations.
margi oldMarginalMax_
Old upper marginals used to compute epsilon.
const std::string getApproximationSchemeMsg()
Get approximation scheme state.
margi evidence_
Holds observed variables states.
const std::vector< GUM_SCALAR > & dynamicExpMin(std::string_view varName) const
Get the lower dynamic expectation of a given variable prefix (without the time step included,...
void dispatchMarginalsToThreads_()
computes Vector threadRanges_, that assigns some part of marginalMin_ and marginalMax_ to the threads
cluster t1_
Clusters of nodes used with dynamic networks.
dynExpe dynamicExpMin_
Lower dynamic expectations.
bool storeBNOpt_
Iterations limit stopping rule used by some algorithms such as CNMonteCarloSampling.
~InferenceEngine() override
Destructor.
void saveExpectations(std::string_view path) const
Saves expectations to file.
void insertModalsFile(std::string_view path)
Insert variables modalities from file to compute expectations.
void initExpectations_()
Initialize lower and upper expectations before inference, with the lower expectation being initialize...
void saveVertices(std::string_view path) const
Saves vertices to file.
void insertQueryFile(std::string_view path)
Insert query variables states from file.
void updateCredalSets_(const NodeId &id, const std::vector< GUM_SCALAR > &vertex, const bool &elimRedund=false)
Given a node id and one of it's possible vertex, update it's credal set.
bool repetitiveInd_
True if using repetitive independence ( dynamic network only ), False otherwise.
const NodeProperty< std::vector< NodeId > > & getT1Cluster() const
Get the t1_ cluster.
virtual const GUM_SCALAR computeEpsilon_()
Compute approximation scheme epsilon using the old marginals and the new ones.
const std::vector< std::vector< GUM_SCALAR > > & vertices(const NodeId id) const
Get the vertice of a given node id.
InferenceEngine(const CredalNet< GUM_SCALAR > &credalNet)
Construtor.
void initMarginalSets_()
Initialize credal set vertices with empty sets.
margi oldMarginalMin_
Old lower marginals used to compute epsilon.
bool storeVertices_
True if credal sets vertices are stored, False otherwise.
dynExpe dynamicExpMax_
Upper dynamic expectations.
const std::vector< GUM_SCALAR > & dynamicExpMax(std::string_view varName) const
Get the upper dynamic expectation of a given variable prefix (without the time step included,...
std::string toString() const
Print all nodes marginals to standart output.
void insertQuery(const NodeProperty< std::vector< bool > > &query)
Insert query variables and states from Property.
bool repetitiveInd() const
Get the current independence status.
NodeProperty< std::vector< bool > > query
void dynamicExpectations_()
Rearrange lower and upper expectations to suit dynamic networks.
bool storeVertices() const
Get the number of iterations without changes used to stop some algorithms.
const CredalNet< GUM_SCALAR > * credalNet_
A pointer to the Credal Net used.
void setRepetitiveInd(const bool repetitive)
virtual void addEvidence(NodeId id, const Idx val) final
adds a new hard evidence on node id
virtual void eraseAllEvidence()
removes all the evidence entered into the network
expe expectationMax_
Upper expectations, if some variables modalities were inserted.
void insertEvidence(const std::map< std::string, std::vector< GUM_SCALAR > > &eviMap)
Insert evidence from map.
void insertModals(const std::map< std::string, std::vector< GUM_SCALAR > > &modals)
Insert variables modalities from map to compute expectations.
query query_
Holds the query nodes states.
virtual void insertEvidenceFile(std::string_view path)
Insert evidence from file.
Tensor< GUM_SCALAR > marginalMin(const NodeId id) const
Get the lower marginals of a given node id.
void saveMarginals(std::string_view path) const
Saves marginals to file.
const CredalNet< GUM_SCALAR > & credalNet() const
Get this credal network.
VarMod2BNsMap< GUM_SCALAR > * getVarMod2BNsMap()
Get optimum IBayesNet.
cluster t0_
Clusters of nodes used with dynamic networks.
const GUM_SCALAR & expectationMin(const NodeId id) const
Get the lower expectation of a given node id.
dynExpe modal_
Variables modalities used to compute expectations.
expe expectationMin_
Lower expectations, if some variables modalities were inserted.
Tensor< GUM_SCALAR > marginalMax(const NodeId id) const
Get the upper marginals of a given node id.
const GUM_SCALAR & expectationMax(const NodeId id) const
Get the upper expectation of a given node id.
int timeSteps_
The number of time steps of this network (only useful for dynamic networks).
std::vector< std::pair< NodeId, Idx > > threadRanges_
the ranges of elements of marginalMin_ and marginalMax_ processed by each thread
const NodeProperty< std::vector< NodeId > > & getT0Cluster() const
Get the t0_ cluster.
void initMarginals_()
Initialize lower and upper old marginals and marginals before inference, with the lower marginal bein...
VarMod2BNsMap< GUM_SCALAR > dbnOpt_
Object used to efficiently store optimal bayes net during inference, for some algorithms.
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 setUpV(const Size &card, const Size &vertices)
Sets up a V-representation.
void elimRedundVrep()
V-Redundancy elimination.
void fillV(const std::vector< GUM_SCALAR > &vertex)
Creates the V-representation of a polytope by adding a vertex to the problem input _input_.
Complete concept for GUM_SCALAR template parameter.
Definition concepts.h:148
Typed, documented, sectioned configuration singleton read from an .ini content.
#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
Size NodeId
Type for node ids.
HashTable< NodeId, VAL > NodeProperty
Property on graph elements.
Abstract class representing CredalNet inference engines.
namespace for all credal networks entities
Definition agrum.h:61
gum is the global namespace for all aGrUM entities
Definition agrum.h:46
Configuration & config()
A short name for Configuration::instance() : gum::config().epsilonStandard(). It is not inline so tha...
STL namespace.
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