51#ifndef DOXYGEN_SHOULD_SKIP_THIS
60# define GUM_SSLI_TRACE_ON(x)
61# define GUM_SSLI_TENSOR_TRACE_ON(x)
65 template < GUM_Numeric GUM_SCALAR >
69 GUM_CONSTRUCTOR(ShaferShenoyLIMIDInference);
73 template < GUM_Numeric GUM_SCALAR >
74 ShaferShenoyLIMIDInference< GUM_SCALAR >::~ShaferShenoyLIMIDInference() {
75 GUM_DESTRUCTOR(ShaferShenoyLIMIDInference);
78 template < GUM_Numeric GUM_SCALAR >
79 void ShaferShenoyLIMIDInference< GUM_SCALAR >::clear() {
80 GraphicalModelInference< GUM_SCALAR >::clear();
81 noForgettingOrder_.clear();
83 reducedJunctionTree_.clear();
84 solvabilityOrder_.clear();
86 unconditionalDecisions_.clear();
88 reversePartialOrder_.clear();
91 template < GUM_Numeric GUM_SCALAR >
92 void ShaferShenoyLIMIDInference< GUM_SCALAR >::onStateChanged_() {}
94 template < GUM_Numeric GUM_SCALAR >
95 void ShaferShenoyLIMIDInference< GUM_SCALAR >::onEvidenceAdded_(
const NodeId
id,
96 bool isHardEvidence) {
97 const InfluenceDiagram< GUM_SCALAR >& infdiag = this->influenceDiagram();
99 if (infdiag.isDecisionNode(
id)) {
104 template < GUM_Numeric GUM_SCALAR >
105 void ShaferShenoyLIMIDInference< GUM_SCALAR >::onEvidenceErased_(
const NodeId
id,
106 bool isHardEvidence) {}
108 template < GUM_Numeric GUM_SCALAR >
109 void ShaferShenoyLIMIDInference< GUM_SCALAR >::onAllEvidenceErased_(
bool contains_hard_evidence) {
112 template < GUM_Numeric GUM_SCALAR >
113 void ShaferShenoyLIMIDInference< GUM_SCALAR >::onEvidenceChanged_(
const NodeId
id,
114 bool hasChangedSoftHard) {}
116 template < GUM_Numeric GUM_SCALAR >
117 void ShaferShenoyLIMIDInference< GUM_SCALAR >::onModelChanged_(
const GraphicalModel* model) {
121 template < GUM_Numeric GUM_SCALAR >
122 void ShaferShenoyLIMIDInference< GUM_SCALAR >::updateOutdatedStructure_() {
126 template < GUM_Numeric GUM_SCALAR >
127 void ShaferShenoyLIMIDInference< GUM_SCALAR >::updateOutdatedTensors_() {}
129 template < GUM_Numeric GUM_SCALAR >
130 void ShaferShenoyLIMIDInference< GUM_SCALAR >::makeInference_() {
131 if (!isSolvable()) {
GUM_ERROR(
FatalError,
"This LIMID/Influence Diagram is not solvable.") }
136 GUM_SSLI_TRACE_ON(
"\n\n")
138 initializingInference_(phi, psi);
141 const auto firstRootIndice = 0;
142 collectingMessage_(phi, psi, node_to_clique_[solvabilityOrder_[firstRootIndice]]);
143 deciding_(phi, psi, solvabilityOrder_[firstRootIndice]);
145 for (Idx nextRootIndice = 1; nextRootIndice < solvabilityOrder_.size(); nextRootIndice++) {
146 if (node_to_clique_[solvabilityOrder_[nextRootIndice - 1]]
147 != node_to_clique_[solvabilityOrder_[nextRootIndice]]) {
148 collectingToFollowingRoot_(phi,
150 node_to_clique_[solvabilityOrder_[nextRootIndice - 1]],
151 node_to_clique_[solvabilityOrder_[nextRootIndice]]);
153 deciding_(phi, psi, solvabilityOrder_[nextRootIndice]);
157 distributingMessage_(phi,
159 node_to_clique_[solvabilityOrder_[solvabilityOrder_.size() - 1]]);
160 computingPosteriors_(phi, psi);
163 template < GUM_Numeric GUM_SCALAR >
164 void ShaferShenoyLIMIDInference< GUM_SCALAR >::initializingInference_(PhiNodeProperty& phi,
165 PsiArcProperty& psi) {
166 const auto& jt = *junctionTree();
167 const auto& infdiag = this->influenceDiagram();
170 for (
const auto node: jt.nodes()) {
171 phi.insert(node, DecisionTensor< GUM_SCALAR >());
172 for (
const auto nei: jt.neighbours(node)) {
173 psi.insert(
Arc(node, nei), DecisionTensor< GUM_SCALAR >());
176 for (
const auto n: jt.clique(node) * jt.clique(nei))
177 varsSeparator_.getWithDefault(
Edge(node, nei), SetOfVars())
178 .insert(&(infdiag.variable(n)));
182 for (
const auto node: infdiag.nodes()) {
183 const auto clik = node_to_clique_[node];
184 if (this->hasEvidence(node)) {
185 auto q = *(this->evidence()[node]);
186 phi[clik].insertProba(q.normalize());
189 if (infdiag.isDecisionNode(node)) {
190 if (!this->hasEvidence(node)) {
191 auto p = (Tensor< GUM_SCALAR >() << infdiag.variable(node)).fillWith(1).normalize();
192 phi[clik].insertProba(p);
194 }
else if (infdiag.isChanceNode(node)) phi[clik].insertProba(infdiag.cpt(node));
195 else if (infdiag.isUtilityNode(node)) phi[clik].insertUtility(infdiag.utility(node));
200 template < GUM_Numeric GUM_SCALAR >
201 void ShaferShenoyLIMIDInference< GUM_SCALAR >::_creatingJunctionTree_() {
202 const auto& infdiag = this->influenceDiagram();
203 auto moral = reduced_.moralGraph();
207 NodeProperty< Size > modalities;
208 for (
const auto node: infdiag.nodes())
209 if (infdiag.isUtilityNode(node)) {
210 moral.eraseNode(node);
212 modalities.insert(node, infdiag.variable(node).domainSize());
214 DefaultTriangulation triangulation(&moral, &modalities);
215 reducedJunctionTree_ = triangulation.junctionTree();
216 _findingCliqueForEachNode_(triangulation);
219 template < GUM_Numeric GUM_SCALAR >
220 void ShaferShenoyLIMIDInference< GUM_SCALAR >::_findingCliqueForEachNode_(
221 DefaultTriangulation& triangulation) {
224 const auto& infdiag = this->influenceDiagram();
225 NodeId first_eliminated_node;
227 node_to_clique_.clear();
228 const std::vector< NodeId >& JT_elim_order = triangulation.eliminationOrder();
229 NodeProperty< Idx > elim_order(Size(JT_elim_order.size()));
230 for (Idx i = Idx(0), size = JT_elim_order.size(); i < size; ++i)
231 elim_order.insert(JT_elim_order[i], (
int)i);
232 for (
const auto node: reduced_.nodes()) {
233 if (infdiag.isUtilityNode(node)) {
236 first_eliminated_node = node;
237 elim_number = std::numeric_limits< NodeId >::max();
240 first_eliminated_node = node;
241 elim_number = elim_order[first_eliminated_node];
244 for (
const auto parent: reduced_.parents(node)) {
245 if (elim_order[parent] < elim_number) {
246 elim_number = elim_order[parent];
247 first_eliminated_node = parent;
255 node_to_clique_.insert(node, triangulation.createdJunctionTreeClique(first_eliminated_node));
259 template < GUM_Numeric GUM_SCALAR >
260 std::pair< GUM_SCALAR, GUM_SCALAR > ShaferShenoyLIMIDInference< GUM_SCALAR >::MEU() {
263 const InfluenceDiagram< GUM_SCALAR >& infdiag = this->influenceDiagram();
264 const auto& jt = *junctionTree();
267 NodeProperty< _UtilityMoments_ > moments;
268 for (const auto clique: jt.nodes())
269 moments.insert(clique, _UtilityMoments_());
270 auto addProba = [&](NodeId node, const Tensor< GUM_SCALAR >& p) {
274 _combineMoments_(moments[node_to_clique_[node]], m);
276 for (
const auto node: infdiag.nodes()) {
277 if (this->hasEvidence(node)) addProba(node, *(this->evidence()[node]));
279 if (infdiag.isChanceNode(node)) addProba(node, infdiag.cpt(node));
280 else if (infdiag.isDecisionNode(node)) addProba(node, strategies_[node]);
281 else if (infdiag.isUtilityNode(node)) {
283 m.util = infdiag.utility(node);
284 m.util2 = m.util * m.util;
286 _combineMoments_(moments[node_to_clique_[node]], m);
294 _UtilityMoments_ total;
295 NodeProperty< NodeId > parent;
296 std::vector< NodeId > order;
297 std::vector< NodeId > stack;
298 for (
const auto root: jt.nodes()) {
299 if (parent.exists(root))
continue;
301 parent.insert(root, root);
302 stack.push_back(root);
303 while (!stack.empty()) {
304 const NodeId clique = stack.back();
306 order.push_back(clique);
307 for (
const auto nei: jt.neighbours(clique))
308 if (!parent.exists(nei)) {
309 parent.insert(nei, clique);
310 stack.push_back(nei);
314 for (
auto iter = order.rbegin(); iter != order.rend(); ++iter) {
315 const NodeId clique = *iter;
316 const NodeId father = parent[clique];
317 if (clique == father) {
318 _combineMoments_(total, _marginalizeMoments_(moments[clique], SetOfVars()));
322 _marginalizeMoments_(moments[clique], varsSeparator_[
Edge(clique, father)]));
327 const GUM_SCALAR phi = total.hasProba ? total.proba.sum() : GUM_SCALAR(1);
328 const GUM_SCALAR mean = total.hasUtility ? total.util.sum() / phi : GUM_SCALAR(0);
329 const GUM_SCALAR mean2 = total.hasUtility ? total.util2.sum() / phi : GUM_SCALAR(0);
330 GUM_SCALAR var = mean2 - mean * mean;
331 if (var < 0) var = 0;
332 return std::pair< GUM_SCALAR, GUM_SCALAR >(mean, var);
335 template < GUM_Numeric GUM_SCALAR >
336 void ShaferShenoyLIMIDInference< GUM_SCALAR >::_combineMoments_(
337 _UtilityMoments_& moments,
338 const _UtilityMoments_& other)
const {
339 if (!other.hasProba && !other.hasUtility)
return;
340 if (!moments.hasProba && !moments.hasUtility) {
346 auto times = [](
const _UtilityMoments_& m,
const Tensor< GUM_SCALAR >& t) {
347 return m.hasProba ? m.proba * t : t;
349 _UtilityMoments_ res;
350 if (moments.hasUtility && other.hasUtility) {
351 res.util = times(moments, other.util) + times(other, moments.util);
352 res.util2 = times(moments, other.util2) + times(other, moments.util2)
353 + (moments.util * other.util).scale(2);
354 }
else if (moments.hasUtility) {
355 res.util = times(other, moments.util);
356 res.util2 = times(other, moments.util2);
357 }
else if (other.hasUtility) {
358 res.util = times(moments, other.util);
359 res.util2 = times(moments, other.util2);
361 res.hasUtility = moments.hasUtility || other.hasUtility;
363 if (other.hasProba) res.proba = times(moments, other.proba);
364 else if (moments.hasProba) res.proba = moments.proba;
365 res.hasProba = moments.hasProba || other.hasProba;
367 moments = std::move(res);
370 template < GUM_Numeric GUM_SCALAR >
371 typename ShaferShenoyLIMIDInference< GUM_SCALAR >::_UtilityMoments_
372 ShaferShenoyLIMIDInference< GUM_SCALAR >::_marginalizeMoments_(
373 const _UtilityMoments_& moments,
374 const SetOfVars& kept)
const {
375 auto marginalize = [&kept](
const Tensor< GUM_SCALAR >& t) {
377 for (
const auto var: t.variablesSequence())
378 if (!kept.contains(var)) del.insert(var);
379 return t.sumOut(del);
381 _UtilityMoments_ res;
382 res.hasProba = moments.hasProba;
383 res.hasUtility = moments.hasUtility;
384 if (res.hasProba) res.proba = marginalize(moments.proba);
385 if (res.hasUtility) {
386 res.util = marginalize(moments.util);
387 res.util2 = marginalize(moments.util2);
392 template < GUM_Numeric GUM_SCALAR >
394 ShaferShenoyLIMIDInference< GUM_SCALAR >::optimalDecision(NodeId decisionId) {
397 const InfluenceDiagram< GUM_SCALAR >& infdiag = this->influenceDiagram();
398 if (!infdiag.isDecisionNode(decisionId))
400 infdiag.variable(decisionId).name()
401 <<
"(" << decisionId <<
") is not a decision node.")
403 return strategies_[decisionId];
406 template < GUM_Numeric GUM_SCALAR >
407 bool ShaferShenoyLIMIDInference< GUM_SCALAR >::isSolvable()
const {
408 return (!solvabilityOrder_.empty());
411 template < GUM_Numeric GUM_SCALAR >
412 void ShaferShenoyLIMIDInference< GUM_SCALAR >::createReduced_() {
415 reducedJunctionTree_.clear();
416 solvabilityOrder_.clear();
417 reversePartialOrder_.clear();
419 unconditionalDecisions_.clear();
421 const InfluenceDiagram< GUM_SCALAR >& infdiag = this->influenceDiagram();
426 for (
auto node: infdiag.nodes()) {
427 reduced_.addNodeWithId(node);
428 if (infdiag.isUtilityNode(node)) { utilities.insert(node); }
431 for (
const auto& arc: infdiag.arcs())
432 reduced_.addArc(arc.tail(), arc.head());
434 _completingNoForgettingAssumption_();
435 _creatingPartialOrder_(utilities);
436 _checkingSolvability_(utilities);
439 _creatingJunctionTree_();
442 this->setState_(GraphicalModelInference< GUM_SCALAR >::StateOfInference::OutdatedStructure);
445 template < GUM_Numeric GUM_SCALAR >
446 void ShaferShenoyLIMIDInference< GUM_SCALAR >::_completingNoForgettingAssumption_() {
448 if (hasNoForgettingAssumption()) {
449 auto last = *(noForgettingOrder_.begin());
450 for (
auto node: noForgettingOrder_)
455 if (!reduced_.existsArc(last, node)) { reduced_.addArc(last, node); }
456 for (
auto par: reduced_.parents(last)) {
457 if (!reduced_.existsArc(par, node)) reduced_.addArc(par, node);
464 template < GUM_Numeric GUM_SCALAR >
465 void ShaferShenoyLIMIDInference< GUM_SCALAR >::_checkingSolvability_(
const NodeSet& utilities) {
466 if (hasNoForgettingAssumption()) {
467 solvabilityOrder_ = noForgettingOrder_;
468 std::reverse(solvabilityOrder_.begin(), solvabilityOrder_.end());
472 solvabilityOrder_.clear();
473 for (
const auto& sen: reversePartialOrder()) {
475 while (!tobetested.empty()) {
476 bool foundOne =
false;
477 for (
const auto& node: tobetested) {
478 const auto us = utilities * reduced_.descendants(node);
480 for (
const auto dec: tobetested)
481 if (dec != node) decs += reduced_.family(dec);
482 if (reduced_.dSeparation(decs, us, reduced_.family(node))) {
483 solvabilityOrder_.push_back(node);
485 tobetested.erase(node);
490 solvabilityOrder_.clear();
497 template < GUM_Numeric GUM_SCALAR >
498 void ShaferShenoyLIMIDInference< GUM_SCALAR >::_reducingLIMID_() {
499 for (
const auto& sen: reversePartialOrder_) {
501 for (
auto p: nonRequisiteNodes_(n))
502 reduced_.eraseArc(
Arc(p, n));
507 template < GUM_Numeric GUM_SCALAR >
508 void ShaferShenoyLIMIDInference< GUM_SCALAR >::_creatingPartialOrder_(
const NodeSet& utilities) {
509 const InfluenceDiagram< GUM_SCALAR >& infdiag = this->influenceDiagram();
510 NodeProperty< Size > level;
512 for (
const auto& node: utilities)
513 level.insert(node, 0);
517 reversePartialOrder_.clear();
518 reversePartialOrder_.resize(infdiag.size());
520 for (
auto node: infdiag.nodes()) {
521 if (infdiag.isUtilityNode(node))
continue;
522 if (reduced_.children(node).isSubsetOrEqual(utilities)) {
524 currents.insert(node);
525 level.insert(node, 0);
526 while (!currents.empty()) {
527 NodeId elt = *(currents.begin());
530 if (infdiag.isDecisionNode(elt)) reversePartialOrder_[level[elt]].insert(elt);
532 for (
auto parent: reduced_.parents(elt)) {
535 bool ok_to_add =
true;
536 for (
auto child: reduced_.children(parent)) {
537 if (!level.exists(child)) {
542 if (infdiag.isDecisionNode(child)) newl += 1;
543 if (lev < newl) lev = newl;
546 currents.insert(parent);
547 if (level.exists(parent)) {
548 if (level[parent] != lev)
550 "Trying to set level[" << parent <<
"] to level=" << lev
551 <<
" but already is " << level[parent]);
553 level.insert(parent, lev);
556 if (max_level < lev) max_level = lev;
563 for (
const auto& k: reversePartialOrder_) {
564 if (k.empty())
break;
567 reversePartialOrder_.
resize(levmax);
570 template < GUM_Numeric GUM_SCALAR >
571 std::vector< NodeSet > ShaferShenoyLIMIDInference< GUM_SCALAR >::reversePartialOrder()
const {
572 return reversePartialOrder_;
575 template < GUM_Numeric GUM_SCALAR >
576 bool ShaferShenoyLIMIDInference< GUM_SCALAR >::hasNoForgettingAssumption()
const {
577 return !noForgettingOrder_.empty();
580 template < GUM_Numeric GUM_SCALAR >
581 void ShaferShenoyLIMIDInference< GUM_SCALAR >::addNoForgettingAssumption(
582 const std::vector< std::string >& names) {
583 addNoForgettingAssumption(this->influenceDiagram().ids(names));
586 template < GUM_Numeric GUM_SCALAR >
587 void ShaferShenoyLIMIDInference< GUM_SCALAR >::addNoForgettingAssumption(
588 const std::vector< NodeId >& ids) {
589 const auto& infdiag = this->influenceDiagram();
590 for (
const auto node: ids) {
592 if (!infdiag.isDecisionNode(node))
594 "Node " << node <<
" (" << infdiag.variable(node).name()
595 <<
") is not a decision node");
597 if (infdiag.decisionNodeSize() != ids.size())
600 noForgettingOrder_ = ids;
604 template < GUM_Numeric GUM_SCALAR >
605 NodeSet ShaferShenoyLIMIDInference< GUM_SCALAR >::nonRequisiteNodes_(NodeId d)
const {
606 const InfluenceDiagram< GUM_SCALAR >& infdiag = this->influenceDiagram();
611 if (reduced_.parents(d).empty()) return res;
614 for (const auto n: reduced_.descendants(d))
615 if (infdiag.isUtilityNode(n)) descUs.insert(n);
617 NodeSet cumul{descUs};
619 auto g = reduced_.moralizedAncestralGraph(cumul);
624 for (
const auto p: reduced_.parents(d)) {
626 for (
const auto u: descUs) {
627 if (g.hasUndirectedPath(p, u, family)) {
632 if (notReq) res << p;
637 template < GUM_Numeric GUM_SCALAR >
638 InfluenceDiagram< GUM_SCALAR > ShaferShenoyLIMIDInference< GUM_SCALAR >::reducedLIMID()
const {
639 const auto& infdiag = this->influenceDiagram();
640 InfluenceDiagram< GUM_SCALAR > res;
641 for (
auto node: infdiag.nodes()) {
642 if (infdiag.isChanceNode(node)) res.addChanceNode(infdiag.variable(node), node);
643 else if (infdiag.isDecisionNode(node)) res.addDecisionNode(infdiag.variable(node), node);
645 res.addUtilityNode(infdiag.variable(node), node);
648 for (
const auto& arc: reduced_.arcs()) {
649 res.addArc(arc.tail(), arc.head());
652 for (
auto node: infdiag.nodes()) {
653 if (infdiag.isChanceNode(node)) res.cpt(node).fillWith(infdiag.cpt(node));
654 else if (infdiag.isUtilityNode(node)) res.utility(node).fillWith(infdiag.utility(node));
661 template < GUM_Numeric GUM_SCALAR >
662 const JunctionTree* ShaferShenoyLIMIDInference< GUM_SCALAR >::junctionTree()
const {
663 if (!isSolvable()) {
GUM_ERROR(
FatalError,
"This LIMID/Influence Diagram is not solvable.") }
664 return &reducedJunctionTree_;
667 template < GUM_Numeric GUM_SCALAR >
668 void ShaferShenoyLIMIDInference< GUM_SCALAR >::collectingMessage_(PhiNodeProperty& phi,
670 const NodeId rootClique) {
671 const auto& jt = *junctionTree();
672 GUM_SSLI_TRACE_ON(
"COLLECTING TO " << rootClique <<
":"
673 << this->influenceDiagram().names(jt.clique(rootClique)))
675 std::function< void(NodeId, NodeId) > parcours = [&](NodeId node, NodeId toRoot) {
676 for (
const auto nei: jt.neighbours(node)) {
677 if (nei != toRoot) parcours(nei, node);
679 transmittingMessage_(phi, psi, node, toRoot);
680 GUM_SSLI_TRACE_ON(
" " << node <<
"->" << toRoot <<
" transmitted")
683 for (
const auto nei: jt.neighbours(rootClique)) {
684 parcours(nei, rootClique);
688 template < GUM_Numeric GUM_SCALAR >
689 void ShaferShenoyLIMIDInference< GUM_SCALAR >::collectingToFollowingRoot_(PhiNodeProperty& phi,
693 GUM_SSLI_TRACE_ON(
"COLLECTING FROM ROOT " << fromClique <<
" TO FOLLOWING ROOT " << toClique)
694 const auto& jt = *junctionTree();
696 std::function<
bool(NodeId, NodeId, NodeId) > revparcours
697 = [&](NodeId node, NodeId from, NodeId target) {
698 if (node == target)
return true;
702 for (
const auto nei: jt.neighbours(node)) {
704 if (revparcours(nei, node, target)) {
710 if (found) { transmittingMessage_(phi, psi, prec, node); }
714 revparcours(toClique, std::numeric_limits< NodeId >::max(), fromClique);
717 template < GUM_Numeric GUM_SCALAR >
718 void ShaferShenoyLIMIDInference< GUM_SCALAR >::deciding_(PhiNodeProperty& phi,
720 NodeId decisionNode) {
721 const auto& infdiag = this->influenceDiagram();
722 GUM_SSLI_TRACE_ON(
"DECIDING for " << infdiag.variable(decisionNode).name())
724 auto& decision = strategies_.getWithDefault(decisionNode, Tensor< GUM_SCALAR >());
726 if (this->hasHardEvidence(decisionNode)) {
727 decision = *(this->evidence()[decisionNode]);
729 DecisionTensor< double > dp;
730 dp = integrating_(phi, psi, node_to_clique_[decisionNode]);
731 GUM_SSLI_TENSOR_TRACE_ON(dp)
734 sev.insert(&infdiag.variable(decisionNode));
735 for (
const auto parent: reduced_.parents(decisionNode)) {
736 sev.insert(&infdiag.variable(parent));
739 GUM_SSLI_TENSOR_TRACE_ON(dp)
742 sev.erase(&infdiag.variable(decisionNode));
743 if (sev.size() == 0) {
744 unconditionalDecisions_.set(decisionNode, dp);
745 }
else if (dp.probPot.sumIn(sev).normalize().max()
748 unconditionalDecisions_.set(
750 DecisionTensor< double >(dp.probPot.sumOut(sev), dp.utilPot.sumOut(sev)));
752 decision = dp.utilPot.putFirst(&infdiag.variable(decisionNode));
754 binarizingMax_(decision, dp.probPot);
755 GUM_SSLI_TENSOR_TRACE_ON(decision)
757 GUM_SSLI_TENSOR_TRACE_ON(phi[node_to_clique_[decisionNode]])
758 phi[node_to_clique_[decisionNode]].insertProba(decision);
759 GUM_SSLI_TENSOR_TRACE_ON(phi[node_to_clique_[decisionNode]])
762 template < GUM_Numeric GUM_SCALAR >
763 void ShaferShenoyLIMIDInference< GUM_SCALAR >::binarizingMax_(
764 const Tensor< GUM_SCALAR >& decision,
765 const Tensor< GUM_SCALAR >& proba)
const {
766 Instantiation I(decision);
767 const auto& firstvar = decision.variable(0);
768 for (I.setFirst(); !I.end(); I.incNotVar(firstvar)) {
769 I.setFirstVar(firstvar);
770 while (proba[I] == 0) {
774 I.setFirstVar(firstvar);
779 Idx argm = I.val(firstvar);
780 GUM_SCALAR umax = decision[I];
781 GUM_SCALAR pmax = proba[I];
782 for (I.incVar(firstvar); !I.end(); I.incVar(firstvar)) {
785 if ((umax < decision[I]) || ((umax == decision[I]) && (pmax < proba[I]))) {
788 argm = I.val(firstvar);
792 for (I.setFirstVar(firstvar); !I.end(); I.incVar(firstvar))
794 I.chgVal(firstvar, argm);
799 template < GUM_Numeric GUM_SCALAR >
800 void ShaferShenoyLIMIDInference< GUM_SCALAR >::distributingMessage_(PhiNodeProperty& phi,
803 const auto& jt = *junctionTree();
804 GUM_SSLI_TRACE_ON(
"DISTRIBUTING FROM " << rootClique <<
":"
805 << this->influenceDiagram().names(jt.clique(rootClique)))
807 std::function< void(NodeId, NodeId) > parcours = [&](NodeId node, NodeId from) {
808 transmittingFinalMessage_(phi, psi, from, node);
809 auto res = integrating_(phi, psi, node);
814 res.utilPot = res.utilPot - psi[
gum::Arc(node, from)].utilPot;
817 GUM_SSLI_TRACE_ON(
" -> phi[" << node <<
"] updated")
818 for (const auto nei: jt.neighbours(node)) {
819 if (nei != from) parcours(nei, node);
823 phi.set(rootClique, integrating_(phi, psi, rootClique));
824 GUM_SSLI_TRACE_ON(
" -> phi[" << rootClique <<
"] updated")
825 GUM_SSLI_TENSOR_TRACE_ON(phi[rootClique])
827 for (const auto nei: jt.neighbours(rootClique)) {
828 parcours(nei, rootClique);
832 template < GUM_Numeric GUM_SCALAR >
833 void ShaferShenoyLIMIDInference< GUM_SCALAR >::transmittingFinalMessage_(PhiNodeProperty& phi,
837 GUM_SSLI_TRACE_ON(fromClique <<
"->" << toClique <<
" [final]")
839 psi.set(Arc(fromClique, toClique),
840 phi[fromClique] ^ varsSeparator_[Edge(fromClique, toClique)]);
843 template < GUM_Numeric GUM_SCALAR >
844 void ShaferShenoyLIMIDInference< GUM_SCALAR >::transmittingMessage_(PhiNodeProperty& phi,
848 GUM_SSLI_TRACE_ON(fromClique <<
"->" << toClique)
849 psi.set(
Arc(fromClique, toClique),
850 integrating_(phi, psi, fromClique, toClique)
851 ^ varsSeparator_[
Edge(fromClique, toClique)]);
854 template < GUM_Numeric GUM_SCALAR >
855 DecisionTensor< double >
856 ShaferShenoyLIMIDInference< GUM_SCALAR >::integrating_(
const PhiNodeProperty& phi,
857 const PsiArcProperty& psi,
859 NodeId except)
const {
860 const auto& jt = *junctionTree();
861 GUM_SSLI_TRACE_ON(
" integrating (except from "
862 << except <<
") in " << inClique <<
":"
863 << this->influenceDiagram().names(jt.clique(inClique)))
864 DecisionTensor< double > res = phi[inClique];
865 for (
const auto nei: jt.neighbours(inClique))
866 if (nei != except) res *= psi[
Arc(nei, inClique)];
871 template < GUM_Numeric GUM_SCALAR >
872 DecisionTensor< double >
873 ShaferShenoyLIMIDInference< GUM_SCALAR >::integrating_(
const PhiNodeProperty& phi,
874 const PsiArcProperty& psi,
875 NodeId inClique)
const {
876 const auto& jt = *junctionTree();
877 GUM_SSLI_TRACE_ON(
" integrating in " << inClique <<
":"
878 << this->influenceDiagram().names(jt.clique(inClique)))
879 DecisionTensor< double > res = phi[inClique];
881 for (
const auto nei: jt.neighbours(inClique))
882 res *= psi[
Arc(nei, inClique)];
887 template < GUM_Numeric GUM_SCALAR >
888 void ShaferShenoyLIMIDInference< GUM_SCALAR >::computingPosteriors_(
const PhiNodeProperty& phi,
889 const PsiArcProperty& psi) {
890 NodeProperty< DecisionTensor< double > > finalphis;
892 const auto& infdiag = this->influenceDiagram();
895 for (
const auto node: infdiag.nodes()) {
896 const auto clik = node_to_clique_[node];
899 const auto& finalphi = phi[clik];
900 GUM_SSLI_TRACE_ON(
"posterior for " << infdiag.variable(node).name())
902 DecisionTensor< GUM_SCALAR > res;
904 if (infdiag.isChanceNode(node)) {
906 sev.insert(&infdiag.variable(node));
907 res = finalphi ^ sev;
908 const auto f = res.probPot.sum();
909 res.probPot.scale(1 / f);
910 }
else if (infdiag.isDecisionNode(node)) {
912 sev.insert(&infdiag.variable(node));
914 for (
const auto par: reduced_.parents(node)) {
920# pragma GCC diagnostic push
921# pragma GCC diagnostic ignored "-Warray-bounds"
923 const auto dp = finalphi ^
family;
926 binarizingMax_(decision, dp.probPot);
927 strategies_.insert(node, decision);
930# pragma GCC diagnostic pop
932 res.probPot.normalize();
933 if (unconditionalDecisions_.exists(node)) {
934 res.utilPot = unconditionalDecisions_[node].utilPot;
940 for (
const auto par: reduced_.parents(node)) {
945 res.probPot.normalize();
946 res.utilPot = infdiag.utility(node);
949 posteriors_.set(node, res);
953 template < GUM_Numeric GUM_SCALAR >
954 const Tensor< GUM_SCALAR >& ShaferShenoyLIMIDInference< GUM_SCALAR >::posterior(NodeId node) {
955 return posteriors_[node].probPot;
958 template < GUM_Numeric GUM_SCALAR >
959 const Tensor< GUM_SCALAR >&
960 ShaferShenoyLIMIDInference< GUM_SCALAR >::posteriorUtility(NodeId node) {
961 return posteriors_[node].utilPot;
964 template < GUM_Numeric GUM_SCALAR >
965 std::pair< GUM_SCALAR, GUM_SCALAR >
966 ShaferShenoyLIMIDInference< GUM_SCALAR >::meanVar(NodeId node) {
967 return posteriors_[node].meanVar();
970 template < GUM_Numeric GUM_SCALAR >
971 DAG ShaferShenoyLIMIDInference< GUM_SCALAR >::reducedGraph()
const {
975 template < GUM_Numeric GUM_SCALAR >
977 ShaferShenoyLIMIDInference< GUM_SCALAR >::optimalDecision(std::string_view decisionName) {
978 return optimalDecision(this->influenceDiagram().idFromName(decisionName));
981 template < GUM_Numeric GUM_SCALAR >
982 const Tensor< GUM_SCALAR >&
983 ShaferShenoyLIMIDInference< GUM_SCALAR >::posterior(std::string_view name) {
984 return posterior(this->influenceDiagram().idFromName(name));
987 template < GUM_Numeric GUM_SCALAR >
988 const Tensor< GUM_SCALAR >&
989 ShaferShenoyLIMIDInference< GUM_SCALAR >::posteriorUtility(std::string_view name) {
990 return posteriorUtility(this->influenceDiagram().idFromName(name));
993 template < GUM_Numeric GUM_SCALAR >
994 std::pair< GUM_SCALAR, GUM_SCALAR >
995 ShaferShenoyLIMIDInference< GUM_SCALAR >::meanVar(std::string_view name) {
996 return meanVar(this->influenceDiagram().idFromName(name));
Implementation of an influence diagram inference algorithm based upon Shaffer-Shenoy's one for bayes ...
The base class for all directed edges.
static Tensor< GUM_SCALAR > divideEvenZero(const Tensor< GUM_SCALAR > &p1, const Tensor< GUM_SCALAR > &p2)
Exception : fatal (unknown ?) error.
<agrum/ID/inference/influenceDiagramInference.h>
Class representing an Influence Diagram.
Exception : node does not exist.
Exception : the element we looked for cannot be found.
Exception : operation not allowed.
void resize(Size new_capacity)
Changes the size of the underlying hash table containing the set.
void insert(const Key &k)
Inserts a new element into the set.
ShaferShenoyLIMIDInference(const InfluenceDiagram< GUM_SCALAR > *infDiag)
Default constructor.
Exception : problem with size.
aGrUM's Tensor is a multi-dimensional array with tensor operators.
Exception : wrong type for this operation.
This file contains abstract class definitions influence diagrams inference classes.
#define GUM_ERROR(type, msg)
Set< NodeId > NodeSet
Some typdefs and define for shortcuts ...
NodeSet family(const G &g, NodeId id)
Returns the family of id : { id } ∪ parents(id).
gum is the global namespace for all aGrUM entities
template class GUM_SHARED_PUBLIC Tensor< double >
CliqueGraph JunctionTree
a junction tree is a clique graph satisfying the running intersection property and such that no cliqu...
Header of the Tensor class.