aGrUM 3.3.2
a C++ library for (probabilistic) graphical models
influenceDiagram_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
51
52#include <algorithm>
53#include <cstdio>
54#include <functional>
55#include <iostream>
56
62
63namespace gum {
64 template < GUM_Numeric GUM_SCALAR >
66 std::string node,
67 std::string_view domain) {
68 bool isUtil = false;
69 bool isDeci = false;
70 bool isChanc = false;
71 std::string ds(domain);
72 switch (*(node.begin())) {
73 case '*' :
74 isDeci = true;
75 node.erase(0, 1);
76 break;
77 case '$' :
78 isUtil = true;
79 ds = "[1]";
80 node.erase(0, 1);
81 break;
82 default : isChanc = true;
83 }
84 auto v = fastVariable< GUM_SCALAR >(node, ds);
85
86 NodeId res;
87 if (infdiag.exists(v->name())) {
88 res = infdiag.idFromName(v->name());
89 } else {
90 if (isChanc) res = infdiag.addChanceNode(*v);
91 else if (isDeci) res = infdiag.addDecisionNode(*v);
92 else if (isUtil) res = infdiag.addUtilityNode(*v);
93 else
95 "No type (chance, decision or utility) for the node '" << node << "'.")
96 }
97
98 return res;
99 }
100
101 template < GUM_Numeric GUM_SCALAR >
102 InfluenceDiagram< GUM_SCALAR >
103 InfluenceDiagram< GUM_SCALAR >::fastPrototype(std::string_view dotlike, Size domainSize) {
104 return fastPrototype(dotlike, "[" + std::to_string(domainSize) + "]");
105 }
106
107 template < GUM_Numeric GUM_SCALAR >
110 std::string_view domain) {
112
113 auto resolve
114 = [&](const std::string& node) { return build_node_for_ID(infdiag, node, domain); };
115 auto addArc = [&](NodeId tail, NodeId head, const std::string&) { infdiag.addArc(tail, head); };
116 auto addEdge = [&](NodeId, NodeId, const std::string& token) {
118 "fastPrototype: '" << token << "' is preceded by '-' but an InfluenceDiagram "
119 << "does not support edges")
120 };
121
122 for (const auto& chaine: split(remove_newline(dotlike), ";")) {
123 using namespace detail;
124 fastGraphWalkTokens(fastGraphTokenize(chaine), dotlike, resolve, addArc, addEdge);
125 }
126
127 for (const auto n: infdiag.nodes()) {
128 if (infdiag.isChanceNode(n)) infdiag.cpt(n).randomCPT();
129 else if (infdiag.isUtilityNode(n)) { infdiag.utility(n).random().scale(50).translate(-10); }
130 }
131
132 infdiag.setProperty("name", "anonymousID");
133 return infdiag;
134 }
135
136 // ===========================================================================
137 // Constructors / Destructors
138 // ===========================================================================
139
140 /*
141 * Default constructor.
142 */
143 template < GUM_Numeric GUM_SCALAR >
147
148 /*
149 * Destructor.
150 */
151 template < GUM_Numeric GUM_SCALAR >
156
157 template < GUM_Numeric GUM_SCALAR >
159 :
160 DAGmodel(std::move(source)), _tensorMap_(std::move(source._tensorMap_)),
161 _utilityMap_(std::move(source._utilityMap_)),
162 _temporalOrder_(std::move(source._temporalOrder_)) {
163 GUM_CONS_MOV(InfluenceDiagram)
164 }
165
166 template < GUM_Numeric GUM_SCALAR >
169 if (this != &source) {
171 DAGmodel::operator=(std::move(source));
172 _tensorMap_ = std::move(source._tensorMap_);
173 _utilityMap_ = std::move(source._utilityMap_);
174 _temporalOrder_ = std::move(source._temporalOrder_);
175 GUM_OP_MOV(InfluenceDiagram)
176 }
177 return *this;
178 }
179
180 /*
181 * Copy Constructor
182 */
183 template < GUM_Numeric GUM_SCALAR >
188
189 /*
190 * Copy Operator
191 */
192 template < GUM_Numeric GUM_SCALAR >
195 if (this != &source) {
196 clear();
197 // Copying tables and structure
199 }
200
201 return *this;
202 }
203
204 template < GUM_Numeric GUM_SCALAR >
206 // Removing previous tensors
207 removeTables_();
208 this->varMap_.clear();
209 dag_.clear();
210 _tensorMap_.clear();
211 _utilityMap_.clear();
212 }
213
214 /*
215 * Removing ancient table
216 */
217 template < GUM_Numeric GUM_SCALAR >
219 for (const auto& [node, tensor]: _tensorMap_)
220 delete tensor;
221 for (const auto& [node, tensor]: _utilityMap_)
222 delete tensor;
223 }
224
225 /*
226 * Copying tables from another influence diagram
227 */
228 template < GUM_Numeric GUM_SCALAR >
230 const InfluenceDiagram< GUM_SCALAR >& IDsource) {
231 for (auto node: IDsource.nodes()) {
232 if (IDsource.isChanceNode(node)) addChanceNode(IDsource.variable(node), node);
233 else if (IDsource.isUtilityNode(node)) addUtilityNode(IDsource.variable(node), node);
234 else // decision node
235 addDecisionNode(IDsource.variable(node), node);
236 }
237 // we add arc in the same order of the tensors
238 for (auto node: IDsource.nodes()) {
239 const auto& s = IDsource.variable(node).name();
240 if (IDsource.isChanceNode(node)) {
241 for (Idx par = 1; par <= IDsource.parents(node).size(); par++)
242 addArc(IDsource.cpt(node).variable(par).name(), s);
243 } else if (IDsource.isUtilityNode(node)) {
244 for (Idx par = 1; par <= IDsource.parents(node).size(); par++)
245 addArc(IDsource.utility(node).variable(par).name(), s);
246 } else { // decision node
247 // here the order does not depend on a Tensor
248 for (NodeId par: IDsource.parents(node))
249 addArc(par, node);
250 }
251 }
252
253 // Copying tensors
254 for (auto node: IDsource.nodes()) {
255 const auto& s = IDsource.variable(node).name();
256 if (IDsource.isChanceNode(node)) {
257 cpt(node).fillWith(IDsource.cpt(s));
258 } else if (IDsource.isUtilityNode(node)) {
259 utility(node).fillWith(IDsource.utility(s));
260 }
261 }
262 }
263
264 template < GUM_Numeric GUM_SCALAR >
266 return toDot(dot::DotOptions());
267 }
268
269 template < GUM_Numeric GUM_SCALAR >
270 std::string InfluenceDiagram< GUM_SCALAR >::toDot(const dot::DotOptions& options) const {
271 const auto style = dot::InfluenceDiagramDotStyle::read();
272 dot::DotWriter writer(true, this->propertyWithDefault("name", ""));
273 dot::writePreamble(writer, style, options);
274
275 // the nodes of a kind, whose default look is the one of the kind
276 const auto writeNodes = [&](const std::function< bool(NodeId) >& isOfThisKind,
277 const std::string& bgColor,
278 const std::string& fgColor,
279 const std::string& shape) {
280 writer.nodeDefaults({{"fillcolor", bgColor},
281 {"fontcolor", fgColor},
282 {"style", "filled"},
283 {"shape", shape},
284 {"height", "0"},
285 {"margin", "0.1"}});
286
287 // a font color which is adaptive is resolved against the background of the kind
288 auto kindStyle = static_cast< dot::DotStyle >(style);
289 kindStyle.nodeBgColor = bgColor;
290 for (const auto node: dag_.nodes()) {
291 if (!isOfThisKind(node)) continue;
292 const auto& name = variable(node).name();
293 writer.node(name,
294 dot::nodeAttributes(kindStyle,
295 options.node(node),
296 "",
297 "(" + std::to_string(node) + ") " + name));
298 }
299 };
300
301 writeNodes([this](NodeId n) { return isChanceNode(n); },
302 style.chanceBgColor,
303 style.chanceFgColor,
304 style.chanceShape);
305 writeNodes([this](NodeId n) { return isDecisionNode(n); },
306 style.decisionBgColor,
307 style.decisionFgColor,
308 style.decisionShape);
309 writeNodes([this](NodeId n) { return isUtilityNode(n); },
310 style.utilityBgColor,
311 style.utilityFgColor,
312 style.utilityShape);
313
314 for (const auto& arc: dag_.arcs()) {
315 auto attributes = dot::arcAttributes(options.arc(arc.tail(), arc.head()));
316 if (isDecisionNode(arc.head()))
317 dot::addDefaultAttribute(attributes, "style", style.decisionArcStyle);
318 else if (isUtilityNode(arc.head()))
319 dot::addDefaultAttribute(attributes, "style", style.utilityArcStyle);
320 writer.edge(variable(arc.tail()).name(), variable(arc.head()).name(), attributes);
321 }
322
323 return writer.str();
324 }
325
326 template < GUM_Numeric GUM_SCALAR >
328 std::stringstream output;
329
330 output << "Influence Diagram{" << std::endl;
331 output << std::format(" chance: {},\n", chanceNodeSize());
332 output << std::format(" utility: {},\n", utilityNodeSize());
333 output << std::format(" decision: {},\n", decisionNodeSize());
334 output << std::format(" arcs: {},\n", dag().sizeArcs());
335
336 if (double dSize = log10DomainSize(); dSize > 6)
337 output << std::format(" domainSize: 10^{}", dSize);
338 else output << std::format(" domainSize: {}", std::round(std::pow(10.0, dSize)));
339
340 output << std::endl << "}";
341
342 return output.str();
343 }
344
345 // ===========================================================================
346 // Variable manipulation methods.
347 // ===========================================================================
348
349 /*
350 * Returns the CPT of a chance variable.
351 */
352 template < GUM_Numeric GUM_SCALAR >
353 const Tensor< GUM_SCALAR >& InfluenceDiagram< GUM_SCALAR >::cpt(NodeId varId) const {
354 return *(_tensorMap_[varId]);
355 }
356
357 /*
358 * Returns the utility table of a utility node.
359 */
360 template < GUM_Numeric GUM_SCALAR >
361 const Tensor< GUM_SCALAR >& InfluenceDiagram< GUM_SCALAR >::utility(NodeId varId) const {
362 return *(_utilityMap_[varId]);
363 }
364
365 /*
366 * Return true if node is a utility one
367 */
368 template < GUM_Numeric GUM_SCALAR >
370 return _utilityMap_.exists(varId);
371 }
372
373 /*
374 * Return true if node is a utility one
375 */
376 template < GUM_Numeric GUM_SCALAR >
378 bool ret = true;
379
380 if (isUtilityNode(varId) || isChanceNode(varId)) ret = false;
381
382 return ret;
383 }
384
385 /*
386 * Return true if node is a chance one
387 */
388 template < GUM_Numeric GUM_SCALAR >
390 return _tensorMap_.exists(varId);
391 }
392
393 /*
394 * Returns the number of utility nodes
395 */
396 template < GUM_Numeric GUM_SCALAR >
400
401 /*
402 * Returns the number of chance nodes
403 */
404 template < GUM_Numeric GUM_SCALAR >
408
409 /*
410 * Returns the number of decision nodes
411 */
412 template < GUM_Numeric GUM_SCALAR >
414 return (size() - _utilityMap_.size() - _tensorMap_.size());
415 }
416
417 /*
418 * Add a chance variable, it's associate node and it's CPT. The id of the new
419 * variable is automatically generated.
420 */
421 template < GUM_Numeric GUM_SCALAR >
423 return addChanceNode(var, varId);
424 }
425
426 /*
427 * Add a utility variable, it's associate node and it's UT. The id of the new
428 * variable is automatically generated.
429 * @Throws : Gum::InvalidArgument if var has more than one state
430 */
431 template < GUM_Numeric GUM_SCALAR >
433 auto newMultiDim = new MultiDimArray< GUM_SCALAR >();
434 NodeId res;
435
436 try {
437 res = addUtilityNode(var, newMultiDim, varId);
438 } catch (Exception const&) {
439 if (newMultiDim != nullptr) delete newMultiDim;
440 throw;
441 }
442
443 return res;
444 }
445
446 /*
447 * Add a decision variable. The id of the new
448 * variable is automatically generated.
449 */
450 template < GUM_Numeric GUM_SCALAR >
452 NodeId varId) {
453 return addNode_(var, varId);
454 }
455
456 /*
457 * Add a chance variable, it's associate node and it's CPT. The id of the new
458 * variable is automatically generated.
459 */
460 template < GUM_Numeric GUM_SCALAR >
462 auto newMultiDim = new MultiDimArray< GUM_SCALAR >();
463 NodeId res;
464
465 try {
466 res = addChanceNode(var, newMultiDim, varId);
467 } catch (Exception const&) {
468 delete newMultiDim;
469 throw;
470 }
471
472 return res;
473 }
474
475 /*
476 * Add a chance variable, it's associate node and it's CPT. The id of the new
477 * variable is automatically generated.
478 */
479 template < GUM_Numeric GUM_SCALAR >
480 NodeId
483 NodeId DesiredId) {
484 NodeId proposedId = addNode_(var, DesiredId);
485
486 auto varcpt = new Tensor< GUM_SCALAR >(aContent);
487 (*varcpt) << variable(proposedId);
488 _tensorMap_.insert(proposedId, varcpt);
489
490 return proposedId;
491 }
492
493 /*
494 * Add a utility variable, it's associate node and it's UT. The id of the new
495 * variable is automatically generated.
496 * @Throws : Gum::InvalidArgument if var has more than one state
497 */
498 template < GUM_Numeric GUM_SCALAR >
499 NodeId
502 NodeId DesiredId) {
503 if (var.domainSize() != 1) {
505 "Utility var have no state ( which implicates a "
506 "single label for data output reasons ).")
507 }
508
509 NodeId proposedId = addNode_(var, DesiredId);
510
511 auto varut = new Tensor< GUM_SCALAR >(aContent);
512
513 (*varut) << variable(proposedId);
514
515 _utilityMap_.insert(proposedId, varut);
516
517 return proposedId;
518 }
519
520 /*
521 * Add a node
522 */
523 template < GUM_Numeric GUM_SCALAR >
525 NodeId DesiredId) {
526 // None thread safe code!
527 NodeId proposedId;
528
529 if (DesiredId == 0) proposedId = dag_.nextNodeId();
530 else proposedId = DesiredId;
531
532 this->varMap_.insert(proposedId, variableType);
533
534 dag_.addNodeWithId(proposedId);
535
536 // end critical section
537 return proposedId;
538 }
539
540 /*
541 * Erase a Variable from the network and remove the variable from
542 * all children of id.
543 * If no variable matches the id, then nothing is done.
544 */
545 template < GUM_Numeric GUM_SCALAR >
547 if (this->varMap_.exists(varId)) {
548 // Reduce the variable child's CPT or Utility Table if necessary
549 for (const auto chi: dag_.children(varId))
550 if (isChanceNode(chi)) _tensorMap_[chi]->erase(variable(varId));
551 else if (isUtilityNode(chi)) _utilityMap_[chi]->erase(variable(varId));
552
553 if (isChanceNode(varId)) {
554 delete _tensorMap_[varId];
555 _tensorMap_.erase(varId);
556 } else if (isUtilityNode(varId)) {
557 delete _utilityMap_[varId];
558 _utilityMap_.erase(varId);
559 }
560
561 this->varMap_.erase(varId);
562 dag_.eraseNode(varId);
563 }
564 }
565
566 /*
567 * Erase a Variable from the network and remove the variable from
568 * all children of var.
569 * If no variable matches, then nothing is done.
570 */
571 template < GUM_Numeric GUM_SCALAR >
573 erase(this->varMap_.get(var));
574 }
575
576 /* we allow the user to change the name of a variable
577 */
578 template < GUM_Numeric GUM_SCALAR >
579 void InfluenceDiagram< GUM_SCALAR >::changeVariableName(NodeId id, std::string_view new_name) {
580 this->varMap_.changeName(id, new_name);
581 }
582
583 // ===========================================================================
584 // @name Arc manipulation methods.
585 // ===========================================================================
586 /*
587 * Add an arc in the ID, and update diagram's chance nodes cpt if necessary.
588 */
589 template < GUM_Numeric GUM_SCALAR >
591 if (isUtilityNode(tail)) { GUM_ERROR(InvalidArc, "Tail cannot be a utility node") }
592
593 dag_.addArc(tail, head);
594
595 if (isChanceNode(head))
596 // Add parent in the child's CPT
597 (*(_tensorMap_[head])) << variable(tail);
598 else if (isUtilityNode(head)) {
599 // Add parent in the child's UT
600 (*(_utilityMap_[head])) << variable(tail);
601 }
602 }
603
604 /*
605 * Removes an arc in the ID, and update diagram chance nodes cpt if necessary.
606 *
607 * If (tail, head) doesn't exist, the nothing happens.
608 */
609 template < GUM_Numeric GUM_SCALAR >
611 if (dag_.existsArc(arc)) {
612 NodeId head = arc.head();
613 NodeId tail = arc.tail();
614 dag_.eraseArc(arc);
615
616 if (isChanceNode(head))
617 // Removes parent in the child's CPT
618 (*(_tensorMap_[head])) >> variable(tail);
619 else if (isUtilityNode(head))
620 // Removes parent in the child's UT
621 (*(_utilityMap_[head])) >> variable(tail);
622 }
623 }
624
625 /*
626 * Removes an arc in the ID, and update diagram chance nodes cpt if necessary.
627 *
628 * If (tail, head) doesn't exist, the nothing happens.
629 */
630 template < GUM_Numeric GUM_SCALAR >
632 eraseArc(Arc(tail, head));
633 }
634
635 // ===========================================================================
636 // Graphical methods
637 // ===========================================================================
638
639 /*
640 * The node's id are coherent with the variables and nodes of the topology.
641 */
642 template < GUM_Numeric GUM_SCALAR >
644 for (const auto node: dag_.nodes())
645 if (!isUtilityNode(node)) graph.addNodeWithId(node);
646
647 for (const auto node: dag_.nodes()) {
648 if (!isDecisionNode(node))
649 for (const auto par: dag_.parents(node)) {
650 if (isChanceNode(node)) graph.addEdge(node, par);
651
652 for (const auto par2: dag_.parents(node))
653 if (par != par2) graph.addEdge(par, par2);
654 }
655 }
656 }
657
658 /*
659 * True if a directed path exist with all decision nodes
660 */
661 template < GUM_Numeric GUM_SCALAR >
663 const Sequence< NodeId > order = topologicalOrder();
664
665 // Finding first decision node
666 Sequence< NodeId >::const_iterator orderIter = order.begin();
667
668 while ((orderIter != order.end()) && (!isDecisionNode(*orderIter)))
669 ++orderIter;
670
671 if (orderIter == order.end()) return true;
672
673 NodeId parentDecision = (*orderIter);
674 ++orderIter;
675
676 // Checking path between decisions nodes
677 while (orderIter != order.end()) {
678 if (isDecisionNode(*orderIter)) {
679 if (!existsPathBetween(parentDecision, *orderIter)) return false;
680
681 parentDecision = *orderIter;
682 }
683
684 ++orderIter;
685 }
686
687 return true;
688 }
689
690 /*
691 * Returns true if a path exists between source and destination
692 */
693 template < GUM_Numeric GUM_SCALAR >
695 List< NodeId > nodeFIFO;
696 // mark[node] contains 0 if not visited
697 // mark[node] = predecessor if visited
698 NodeProperty< int > mark = dag_.nodesPropertyFromVal(-1);
699 NodeId current;
700
701 mark[src] = (int)src;
702 nodeFIFO.pushBack(src);
703
704 while (!nodeFIFO.empty()) {
705 current = nodeFIFO.front();
706 nodeFIFO.popFront();
707
708 for (const auto new_one: dag_.children(current)) {
709 if (mark[new_one] != -1) continue; // if this node is already marked, continue
710
711 mark[new_one] = (int)current;
712
713 if (new_one == dest) break; // if we reach *orderIter, stop.
714
715 nodeFIFO.pushBack(new_one);
716 }
717 }
718
719 if (mark[dest] == -1) return false;
720
721 return true;
722 }
723
724 /*
725 * Returns the decision graph
726 */
727 template < GUM_Numeric GUM_SCALAR >
729 gum::DAG temporalGraph;
730
731 for (const auto node: dag_.nodes()) {
732 if (isDecisionNode(node)) {
733 if (!temporalGraph.existsNode(node)) temporalGraph.addNodeWithId(node);
734
735 for (const auto chi: getChildrenDecision_(node)) {
736 if (!temporalGraph.existsNode(chi)) temporalGraph.addNodeWithId(chi);
737
738 temporalGraph.addArc(node, chi);
739 }
740 }
741 }
742
743 return temporalGraph;
744 }
745
746 /*
747 * Returns the list of children decision for a given nodeId
748 */
749 template < GUM_Numeric GUM_SCALAR >
752 Sequence< NodeId > childrenSeq;
753
754 List< NodeId > nodeFIFO;
755 NodeId current;
756
757 // mark[node] contains false if not visited
758 // mark[node] contains true if visited
759 NodeProperty< bool > mark = dag_.nodesPropertyFromVal(false);
760
761 mark[parentDecision] = true;
762
763 nodeFIFO.pushBack(parentDecision);
764
765 while (!nodeFIFO.empty()) {
766 current = nodeFIFO.front();
767 nodeFIFO.popFront();
768
769 for (const auto new_one: dag_.children(current)) {
770 if (mark[new_one]) continue; // if this node is already marked, continue
771
772 mark[new_one] = true;
773
774 if (!isDecisionNode(new_one)) nodeFIFO.pushBack(new_one);
775 else childrenSeq.insert(new_one);
776 }
777 }
778
779 return childrenSeq;
780 }
781
782 /*
783 * Returns the sequence of decision nodes
784 * @throw NotFound if such a sequence does not exist
785 */
786 template < GUM_Numeric GUM_SCALAR >
787 std::vector< NodeId > InfluenceDiagram< GUM_SCALAR >::decisionOrder() const {
788 if (!decisionOrderExists()) { GUM_ERROR(NotFound, "No decision path exists") }
789
790 std::vector< NodeId > decisionSequence;
791
792 for (const auto elt: topologicalOrder())
793 if (isDecisionNode(elt)) decisionSequence.push_back(elt);
794
795 return decisionSequence;
796 }
797
798 /*
799 * Returns partial temporal ordering
800 * @throw NotFound if such a sequence does not exist
801 */
802 template < GUM_Numeric GUM_SCALAR >
804 if (clear) {
805 _temporalOrder_.clear();
806
807 std::vector< NodeId > order = decisionOrder();
808 NodeSet nodeList = dag_.asNodeSet();
809
810 for (auto i: order) {
811 NodeSet partialOrderedSet;
812
813 for (const auto par: dag_.parents(i)) {
814 if (nodeList.contains(par) && isChanceNode(par)) {
815 partialOrderedSet.insert(par);
816 nodeList.erase(par);
817 }
818 }
819
820 if (!partialOrderedSet.empty()) _temporalOrder_.pushFront(partialOrderedSet);
821
822 NodeSet decisionSet;
823
824 decisionSet.insert(i);
825
826 _temporalOrder_.pushFront(decisionSet);
827 }
828
829 NodeSet lastSet; //= new gum::NodeSet();
830
831 for (const auto node: nodeList)
832 if (isChanceNode(node)) lastSet.insert(node);
833
834 if (!lastSet.empty()) _temporalOrder_.pushFront(lastSet);
835 }
836
837 return _temporalOrder_;
838 }
839
840 template < GUM_Numeric GUM_SCALAR >
841 NodeId InfluenceDiagram< GUM_SCALAR >::addChanceNode(std::string_view fast_description,
842 unsigned int default_nbrmod) {
843 auto v = fastVariable< GUM_SCALAR >(std::string(fast_description), default_nbrmod);
844 if (v->domainSize() < 2) GUM_ERROR(OperationNotAllowed, v->name() << " has a domain size <2")
845 return addChanceNode(*v);
846 }
847
848 template < GUM_Numeric GUM_SCALAR >
849 NodeId InfluenceDiagram< GUM_SCALAR >::addUtilityNode(std::string_view fast_description) {
850 auto v = fastVariable< GUM_SCALAR >(std::string(fast_description), 1);
851 if (v->domainSize() >= 2)
853 v->name() << " has a domain size >= 2 which is impossible for a utility node")
854 return addUtilityNode(*v);
855 }
856
857 template < GUM_Numeric GUM_SCALAR >
859 unsigned int default_nbrmod) {
860 auto v = fastVariable< GUM_SCALAR >(std::string(fast_description), default_nbrmod);
861 if (v->domainSize() < 2) GUM_ERROR(OperationNotAllowed, v->name() << " has a domain size <2")
862 return addDecisionNode(*v);
863 }
864
865 template < GUM_Numeric GUM_SCALAR >
866 NodeId InfluenceDiagram< GUM_SCALAR >::add(std::string_view fast_description,
867 unsigned int default_nbrmod) {
868 std::string node(fast_description);
869 switch (*(node.begin())) {
870 case '*' : node.erase(0, 1); return addDecisionNode(node, default_nbrmod);
871 case '$' : node.erase(0, 1); return addUtilityNode(node);
872 default : return addChanceNode(fast_description, default_nbrmod);
873 }
874 }
875
877 template < GUM_Numeric GUM_SCALAR >
879 for (const auto node: nodes())
880 if (isChanceNode(node)) _tensorMap_[node]->beginMultipleChanges();
881 else if (this->isUtilityNode(node)) _utilityMap_[node]->beginMultipleChanges();
882 }
883
885 template < GUM_Numeric GUM_SCALAR >
887 for (const auto node: nodes())
888 if (isChanceNode(node)) _tensorMap_[node]->endMultipleChanges();
889 else if (isUtilityNode(node)) _utilityMap_[node]->endMultipleChanges();
890 }
891
892 template < GUM_Numeric GUM_SCALAR >
894 if (size() != from.size()) { return false; }
895
896 if (sizeArcs() != from.sizeArcs()) { return false; }
897
898 // alignment of variables between the 2 BNs
900
901 for (auto node: nodes()) {
902 const auto& v1 = variable(node);
903 if (!from.exists(v1.name())) return false;
904 const auto& v2 = from.variableFromName(v1.name());
905 if (v1 != v2) { return false; }
906
907 if (isChanceNode(v1.name()) && !from.isChanceNode(v2.name())) { return false; }
908 if (isUtilityNode(v1.name()) && !from.isUtilityNode(v2.name())) { return false; }
909 if (isDecisionNode(v1.name()) && !from.isDecisionNode(v2.name())) { return false; }
910
911 alignment.insert(&variable(node), &from.variableFromName(v1.name()));
912 }
913
914 auto check_pot
915 = [&](const gum::Tensor< GUM_SCALAR >& p1, const gum::Tensor< GUM_SCALAR >& p2) -> bool {
916 if (p1.nbrDim() != p2.nbrDim()) { return false; }
917
918 if (p1.domainSize() != p2.domainSize()) { return false; }
919
920 Instantiation i(p1);
921 Instantiation j(p2);
922 // the tolerance applies to the squared difference: two values are equal when
923 // |a - b| <= sqrt(epsilonStandard), i.e. 1e-3 by default
924 const GUM_SCALAR tolerance = static_cast< GUM_SCALAR >(config().epsilonStandard());
925
926 for (i.setFirst(); !i.end(); i.inc()) {
927 for (Idx indice = 0; indice < p1.nbrDim(); ++indice) {
928 const DiscreteVariable* p = &(i.variable(indice));
929 j.chgVal(*(alignment.second(p)), i.val(*p));
930 }
931
932 if (std::pow(p1.get(i) - p2.get(j), (GUM_SCALAR)2) > tolerance) { return false; }
933 }
934 return true;
935 };
936 for (auto node: nodes()) {
937 NodeId fromnode = from.idFromName(variable(node).name());
938 if (isChanceNode(node)) {
939 if (!check_pot(cpt(node), from.cpt(fromnode))) { return false; }
940 } else if (isUtilityNode(node)) {
941 if (!check_pot(utility(node), from.utility(fromnode))) { return false; }
942 }
943 }
944
945 return true;
946 }
947
948 template < GUM_Numeric GUM_SCALAR >
949 const Tensor< GUM_SCALAR >& InfluenceDiagram< GUM_SCALAR >::cpt(std::string_view name) const {
950 return cpt(idFromName(name));
951 }
952
953 template < GUM_Numeric GUM_SCALAR >
954 const Tensor< GUM_SCALAR >& InfluenceDiagram< GUM_SCALAR >::utility(std::string_view name) const {
955 return utility(idFromName(name));
956 }
957
958 template < GUM_Numeric GUM_SCALAR >
959 bool InfluenceDiagram< GUM_SCALAR >::isUtilityNode(std::string_view name) const {
960 return isUtilityNode(idFromName(name));
961 }
962
963 template < GUM_Numeric GUM_SCALAR >
964 bool InfluenceDiagram< GUM_SCALAR >::isDecisionNode(std::string_view name) const {
965 return isDecisionNode(idFromName(name));
966 }
967
968 template < GUM_Numeric GUM_SCALAR >
969 bool InfluenceDiagram< GUM_SCALAR >::isChanceNode(std::string_view name) const {
970 return isChanceNode(idFromName(name));
971 }
972
973 template < GUM_Numeric GUM_SCALAR >
974 const DiscreteVariable& InfluenceDiagram< GUM_SCALAR >::variable(std::string_view name) const {
975 return variable(idFromName(name));
976 }
977
978 template < GUM_Numeric GUM_SCALAR >
979 void InfluenceDiagram< GUM_SCALAR >::erase(std::string_view name) {
980 erase(idFromName(name));
981 }
982
983 template < GUM_Numeric GUM_SCALAR >
985 std::string_view new_name) {
986 changeVariableName(idFromName(name), new_name);
987 }
988
989 template < GUM_Numeric GUM_SCALAR >
990 void InfluenceDiagram< GUM_SCALAR >::addArc(std::string_view tail, std::string_view head) {
991 addArc(idFromName(tail), idFromName(head));
992 }
993
994 template < GUM_Numeric GUM_SCALAR >
995 void InfluenceDiagram< GUM_SCALAR >::eraseArc(std::string_view tail, std::string_view head) {
996 eraseArc(idFromName(tail), idFromName(head));
997 }
998
999 template < GUM_Numeric GUM_SCALAR >
1001 std::string_view dest) const {
1002 return existsPathBetween(idFromName(src), idFromName(dest));
1003 }
1004
1005} // namespace gum
The base class for all directed edges.
GUM_NODISCARD NodeId head() const
returns the head of the arc
GUM_NODISCARD NodeId tail() const
returns the tail of the arc
Arc(NodeId tail, NodeId head)
basic constructor. Creates tail -> head.
const T2 & second(const T1 &first) const
Returns the second value of a pair given its first value.
void insert(const T1 &first, const T2 &second)
Inserts a new association in the gum::Bijection.
Set of pairs of elements with fast search for both elements.
Definition bijection.h:1640
double epsilonStandard() const noexcept
Base class for dag.
Definition DAG.h:121
void addArc(NodeId tail, NodeId head) final
insert a new arc into the directed graph
Definition DAG_inl.h:75
DAG dag_
The DAG of this Directed Graphical Model.
Definition DAGmodel.h:291
DAGmodel()
Default constructor.
Definition DAGmodel.cpp:49
Size size() const final
Returns the number of variables in this Directed Graphical Model.
Size sizeArcs() const
Returns the number of arcs in this Directed Graphical Model.
Sequence< NodeId > topologicalOrder() const
The topological order stays the same as long as no variable or arcs are added or erased src the topol...
DAG dag() const
Returns a named copy of the internal DAG: each node id is assigned the name of the corresponding vari...
DAGmodel & operator=(const DAGmodel &source)
Private copy operator.
Definition DAGmodel.cpp:62
bool exists(NodeId node) const final
Return true if this node exists in this graphical model.
const NodeSet & parents(const NodeId id) const
returns the set of nodes with arc ingoing to a given node
const NodeGraphPart & nodes() const final
Returns a named copy of the internal DAG: each node id is assigned the name of the corresponding vari...
VariableNodeMap varMap_
Mapping between NodeIds and discrete variables.
Base class for discrete random variable.
virtual Size domainSize() const =0
Base class for all aGrUM's exceptions.
Definition exceptions.h:133
Exception : fatal (unknown ?) error.
void setProperty(std::string_view name, std::string_view value)
Add or change a property of this GraphicalModel.
double log10DomainSize() const
const std::string & propertyWithDefault(std::string_view name, const std::string &byDefault) const
Return the value of the property name of this GraphicalModel.
Class representing an Influence Diagram.
void beginTopologyTransformation()
When inserting/removing arcs, node CPTs/utilities change their dimension with a cost in time.
List< NodeSet > _temporalOrder_
The temporal order.
NodeId idFromName(std::string_view name) const override
Returns the NodeId of a variable given its name.
Size chanceNodeSize() const
Returns the number of chance nodes.
InfluenceDiagram()
Default constructor.
const List< NodeSet > & getPartialTemporalOrder(bool clear=true) const
Returns partial temporal ordering.
NodeId addChanceNode(const DiscreteVariable &variable, NodeId id=0)
Add a chance variable, it's associate node and it's CPT.
void addArc(NodeId tail, NodeId head)
Add an arc in the ID, and update diagram's tensor nodes cpt if necessary.
void endTopologyTransformation()
terminates a sequence of insertions/deletions of arcs by adjusting all CPTs/utilities dimensions.
static InfluenceDiagram< GUM_SCALAR > fastPrototype(std::string_view dotlike, Size domainSize)
Create an Influence Diagram with a dot-like syntax which specifies:
void removeTables_()
Removing ancient table.
void eraseArc(const Arc &arc)
Removes an arc in the ID, and update diagram's tensor nodes cpt if necessary.
NodeProperty< Tensor< GUM_SCALAR > * > _tensorMap_
Mapping between tensor variable's id and their CPT.
virtual void moralGraph_(UndiGraph &graph) const
Returns the moral graph of this InfluenceDiagram.
NodeId addNode_(const DiscreteVariable &variableType, NodeId DesiredId)
Add a node.
std::string toDot() const
bool decisionOrderExists() const
True if a directed path exist with all decision nodes.
bool isChanceNode(NodeId varId) const
Returns true if node is a chance one.
InfluenceDiagram< GUM_SCALAR > & operator=(const InfluenceDiagram< GUM_SCALAR > &source)
Copy Operator.
NodeId add(const DiscreteVariable &variable, NodeId id=0)
Add a chance variable, it's associate node and it's CPT.
NodeId addUtilityNode(const DiscreteVariable &variable, NodeId id=0)
Add a utility variable, it's associate node and it's UT.
std::string toString() const
void copyStructureAndTables_(const InfluenceDiagram< GUM_SCALAR > &IDsource)
Copying tables from another influence diagram.
NodeId addDecisionNode(const DiscreteVariable &variable, NodeId id=0)
Add a decision variable.
const DiscreteVariable & variableFromName(std::string_view name) const override
Returns a constant reference over a variable given its name.
bool isUtilityNode(NodeId varId) const
Returns true if node is a utility one.
bool operator==(const InfluenceDiagram< GUM_SCALAR > &other) const
Size utilityNodeSize() const
Returns the number of utility nodes.
NodeProperty< Tensor< GUM_SCALAR > * > _utilityMap_
Mapping between utility variable's id and their utility table.
gum::DAG getDecisionGraph() const
Returns the temporal Graph.
void changeVariableName(NodeId id, std::string_view new_name)
we allow the user to change the name of a variable
bool isDecisionNode(NodeId varId) const
Returns true if node is a decision one.
const DiscreteVariable & variable(std::string_view name) const
Returns the CPT of a tensor variable.
Sequence< NodeId > getChildrenDecision_(NodeId parentDecision) const
Returns the list of children decision for a given nodeId.
Size decisionNodeSize() const
Returns the number of decision nodes.
void erase(NodeId id)
Erase a Variable from the network and remove the variable from all his children.
virtual const Tensor< GUM_SCALAR > & cpt(NodeId varId) const
Returns the CPT of a tensor variable.
std::vector< NodeId > decisionOrder() const
Returns the sequence of decision nodes in the directed path.
virtual const Tensor< GUM_SCALAR > & utility(NodeId varId) const
Returns the utility table of a utility node.
bool existsPathBetween(NodeId src, NodeId dest) const
Returns true if a path exists between two nodes.
~InfluenceDiagram() override
Destructor.
Class for assigning/browsing values to tuples of discrete variables.
Instantiation & chgVal(const DiscreteVariable &v, Idx newval)
Assign newval to variable v in the Instantiation.
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.
const DiscreteVariable & variable(Idx i) const final
Returns the variable at position i in the tuple.
Exception : there is something wrong with an arc.
Exception: at least one argument passed to a function is not what was expected.
Exception : there is something wrong with an edge.
Generic doubly linked lists.
Definition list.h:378
Val & front() const
Returns a reference to first element of a list, if any.
Definition list_tpl.h:1694
Val & pushBack(const Val &val)
Inserts a new element (a copy) at the end of the chained list.
Definition list_tpl.h:1481
bool empty() const noexcept
Returns a boolean indicating whether the chained list is empty.
Definition list_tpl.h:1822
void popFront()
Removes the first element of a List, if any.
Definition list_tpl.h:1816
MultiDimArray()
Default constructor.
Idx nbrDim() const final
Returns the number of vars in the multidimensional container.
Size domainSize() const final
Returns the product of the variables domain size.
GUM_ELEMENT get(const Instantiation &i) const final
Default implementation of MultiDimContainer::get().
bool existsNode(const NodeId id) const
returns true iff the NodeGraphPart contains the given nodeId
virtual void addNodeWithId(const NodeId id)
try to insert a node with the given id
Exception : the element we looked for cannot be found.
Exception : operation not allowed.
SequenceIterator< Key > const_iterator
Types for STL compliance.
Definition sequence.h:1006
bool contains(const Key &k) const
Indicates whether a given elements belong to the set.
Definition set_tpl.h:468
bool empty() const noexcept
Indicates whether the set is the empty set.
Definition set_tpl.h:613
void insert(const Key &k)
Inserts a new element into the set.
Definition set_tpl.h:510
void erase(const Key &k)
Erases an element from the set.
Definition set_tpl.h:553
aGrUM's Tensor is a multi-dimensional array with tensor operators.
Definition tensor.h:85
Base class for undirected graphs.
Definition undiGraph.h:134
const std::string & name() const
returns the name of the variable
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 nodeDefaults(const DotAttributes &attributes)
node [attributes];, the default attributes of the nodes that follow (none : does nothing).
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.
The statements common to the graphs drawn with graphviz : preamble, attributes of nodes and arcs.
#define GUM_ERROR(type, msg)
Definition exceptions.h:76
Builds a graph from a "fast" DOT-like textual description.
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 std::string remove_newline(std::string_view s)
remove all newlines in a string
std::vector< std::string > split(std::string_view str, std::string_view delim)
Split str using the delimiter.
Class representing Influence Diagrams.
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
NodeId build_node_for_ID(gum::InfluenceDiagram< GUM_SCALAR > &infdiag, std::string node, std::string_view domain)
Configuration & config()
A short name for Configuration::instance() : gum::config().epsilonStandard(). It is not inline so tha...
std::unique_ptr< DiscreteVariable > fastVariable(std::string var_description, Size default_domain_size)
Create a pointer on a Discrete Variable from a "fast" syntax.
The look shared by all the graphs: size, direction, layout, colors of the arcs and of the nodes.
Definition dotStyle.h:76
std::string nodeBgColor
background color of the nodes
Definition dotStyle.h:86
static InfluenceDiagramDotStyle read()
Definition dotStyle.cpp:133