54#ifndef DOXYGEN_SHOULD_SKIP_THIS
65 template < GUM_Numeric GUM_SCALAR >
68 bool use_binary_join_tree) :
70 _use_binary_join_tree_(use_binary_join_tree) {
72 _triangulation_ =
new DefaultTriangulation;
75 const auto& graph = this->MRF().internalGraph();
76 _node_to_factors_.resize(graph.size());
78 for (
const auto node: graph)
79 _node_to_factors_.insert(node, empty);
80 for (
const auto& factor: this->MRF().factors()) {
81 for (
const auto node: factor.first) {
82 _node_to_factors_[node].insert(factor.second);
87 GUM_CONSTRUCTOR(ShaferShenoyMRFInference);
91 template < GUM_Numeric GUM_SCALAR >
92 ShaferShenoyMRFInference< GUM_SCALAR >::~ShaferShenoyMRFInference() {
94 for (
const auto& pot: _arc_to_created_tensors_)
102 for (
auto pot: _clique_ss_tensor_) {
103 if (_clique_tensors_[pot.first].size() > 1)
delete pot.second;
106 for (
auto potset: _clique_tensors_) {
107 for (
auto pot: potset.second)
112 for (
const auto& pot: _target_posteriors_)
114 for (
const auto& pot: _joint_target_posteriors_)
118 if (_JT_ !=
nullptr)
delete _JT_;
119 if (_junctionTree_ !=
nullptr)
delete _junctionTree_;
120 delete _triangulation_;
123 GUM_DESTRUCTOR(ShaferShenoyMRFInference);
127 template < GUM_Numeric GUM_SCALAR >
128 void ShaferShenoyMRFInference< GUM_SCALAR >::setTriangulation(
129 const Triangulation& new_triangulation) {
130 delete _triangulation_;
131 _triangulation_ = new_triangulation.newFactory();
132 _is_new_jt_needed_ =
true;
133 this->setOutdatedStructureState_();
137 template < GUM_Numeric GUM_SCALAR >
138 const JoinTree* ShaferShenoyMRFInference< GUM_SCALAR >::joinTree() {
139 if (_is_new_jt_needed_) _createNewJT_();
145 template < GUM_Numeric GUM_SCALAR >
146 const JunctionTree* ShaferShenoyMRFInference< GUM_SCALAR >::junctionTree() {
147 if (_is_new_jt_needed_) _createNewJT_();
149 return _junctionTree_;
153 template < GUM_Numeric GUM_SCALAR >
154 void ShaferShenoyMRFInference< GUM_SCALAR >::_setProjectionFunction_(
155 Tensor< GUM_SCALAR > (*proj)(
const Tensor< GUM_SCALAR >&,
const gum::VariableSet&)) {
156 _projection_op_ = proj;
160 _invalidateAllMessages_();
164 template < GUM_Numeric GUM_SCALAR >
165 void ShaferShenoyMRFInference< GUM_SCALAR >::_setCombinationFunction_(
166 Tensor< GUM_SCALAR > (*comb)(
const Tensor< GUM_SCALAR >&,
const Tensor< GUM_SCALAR >&)) {
167 _combination_op_ = comb;
171 _invalidateAllMessages_();
175 template < GUM_Numeric GUM_SCALAR >
176 void ShaferShenoyMRFInference< GUM_SCALAR >::_invalidateAllMessages_() {
178 for (
auto& pot: _separator_tensors_)
179 pot.second =
nullptr;
181 for (
auto& mess_computed: _messages_computed_)
182 mess_computed.second =
false;
185 for (
const auto& pot: _arc_to_created_tensors_)
186 if (pot.second !=
nullptr)
delete pot.second;
187 _arc_to_created_tensors_.clear();
190 for (
const auto& pot: _target_posteriors_)
192 _target_posteriors_.clear();
193 for (
const auto& pot: _joint_target_posteriors_)
195 _joint_target_posteriors_.clear();
198 if (this->isInferenceReady() || this->isInferenceDone()) this->setOutdatedTensorsState_();
202 template < GUM_Numeric GUM_SCALAR >
203 void ShaferShenoyMRFInference< GUM_SCALAR >::onEvidenceAdded_(
const NodeId
id,
204 bool isHardEvidence) {
208 if (isHardEvidence || !_graph_.exists(
id)) _is_new_jt_needed_ =
true;
211 _evidence_changes_.insert(
id, EvidenceChangeType::EVIDENCE_ADDED);
217 _evidence_changes_[id] = EvidenceChangeType::EVIDENCE_MODIFIED;
223 template < GUM_Numeric GUM_SCALAR >
224 void ShaferShenoyMRFInference< GUM_SCALAR >::onEvidenceErased_(
const NodeId
id,
225 bool isHardEvidence) {
228 if (isHardEvidence) _is_new_jt_needed_ =
true;
231 _evidence_changes_.insert(
id, EvidenceChangeType::EVIDENCE_ERASED);
238 if (_evidence_changes_[
id] == EvidenceChangeType::EVIDENCE_ADDED)
239 _evidence_changes_.erase(
id);
240 else _evidence_changes_[id] = EvidenceChangeType::EVIDENCE_ERASED;
246 template < GUM_Numeric GUM_SCALAR >
247 void ShaferShenoyMRFInference< GUM_SCALAR >::onAllEvidenceErased_(
bool has_hard_evidence) {
248 if (has_hard_evidence || !this->hardEvidenceNodes().empty()) _is_new_jt_needed_ =
true;
250 for (
const auto node: this->softEvidenceNodes()) {
252 _evidence_changes_.insert(node, EvidenceChangeType::EVIDENCE_ERASED);
259 if (_evidence_changes_[node] == EvidenceChangeType::EVIDENCE_ADDED)
260 _evidence_changes_.erase(node);
261 else _evidence_changes_[node] = EvidenceChangeType::EVIDENCE_ERASED;
268 template < GUM_Numeric GUM_SCALAR >
269 void ShaferShenoyMRFInference< GUM_SCALAR >::onEvidenceChanged_(
const NodeId
id,
270 bool hasChangedSoftHard) {
271 if (hasChangedSoftHard) _is_new_jt_needed_ =
true;
274 _evidence_changes_.insert(
id, EvidenceChangeType::EVIDENCE_MODIFIED);
284 template < GUM_Numeric GUM_SCALAR >
285 void ShaferShenoyMRFInference< GUM_SCALAR >::onMarginalTargetAdded_(
const NodeId
id) {}
288 template < GUM_Numeric GUM_SCALAR >
289 void ShaferShenoyMRFInference< GUM_SCALAR >::onMarginalTargetErased_(
const NodeId
id) {}
292 template < GUM_Numeric GUM_SCALAR >
293 void ShaferShenoyMRFInference< GUM_SCALAR >::onJointTargetAdded_(
const NodeSet& set) {}
296 template < GUM_Numeric GUM_SCALAR >
297 void ShaferShenoyMRFInference< GUM_SCALAR >::onJointTargetErased_(
const NodeSet& set) {}
300 template < GUM_Numeric GUM_SCALAR >
301 void ShaferShenoyMRFInference< GUM_SCALAR >::onAllMarginalTargetsAdded_() {}
304 template < GUM_Numeric GUM_SCALAR >
305 void ShaferShenoyMRFInference< GUM_SCALAR >::onAllMarginalTargetsErased_() {}
308 template < GUM_Numeric GUM_SCALAR >
309 void ShaferShenoyMRFInference< GUM_SCALAR >::onMRFChanged_(
310 const IMarkovRandomField< GUM_SCALAR >* mn) {}
313 template < GUM_Numeric GUM_SCALAR >
314 void ShaferShenoyMRFInference< GUM_SCALAR >::onAllJointTargetsErased_() {}
317 template < GUM_Numeric GUM_SCALAR >
318 void ShaferShenoyMRFInference< GUM_SCALAR >::onAllTargetsErased_() {}
321 template < GUM_Numeric GUM_SCALAR >
322 bool ShaferShenoyMRFInference< GUM_SCALAR >::_isNewJTNeeded_()
const {
325 if ((_JT_ ==
nullptr) || _is_new_jt_needed_)
return true;
331 const auto& hard_ev_nodes = this->hardEvidenceNodes();
332 for (
const auto node: this->targets()) {
333 if (!_graph_.exists(node) && !hard_ev_nodes.exists(node))
return true;
337 const std::vector< NodeId >& JT_elim_order = _triangulation_->eliminationOrder();
338 NodeProperty< int > elim_order(Size(JT_elim_order.size()));
339 for (std::size_t i = std::size_t(0), size = JT_elim_order.size(); i < size; ++i)
340 elim_order.insert(JT_elim_order[i], (
int)i);
343 for (
const auto& joint_target: this->jointTargets()) {
346 NodeId first_eliminated_node = std::numeric_limits< NodeId >::max();
347 int elim_number = std::numeric_limits< int >::max();
348 unobserved_set.clear();
349 for (
const auto node: joint_target) {
350 if (!_graph_.exists(node)) {
351 if (!hard_ev_nodes.exists(node))
return true;
353 unobserved_set.insert(node);
354 if (elim_order[node] < elim_number) {
355 elim_number = elim_order[node];
356 first_eliminated_node = node;
360 if (!unobserved_set.empty()) {
364 const auto clique_id = _node_to_clique_[first_eliminated_node];
365 const auto& clique = _JT_->clique(clique_id);
366 for (
const auto node: unobserved_set) {
367 if (!clique.contains(node))
return true;
374 for (
const auto& change: _evidence_changes_) {
375 if ((change.second == EvidenceChangeType::EVIDENCE_ADDED) && !_graph_.exists(change.first))
384 template < GUM_Numeric GUM_SCALAR >
385 void ShaferShenoyMRFInference< GUM_SCALAR >::_createNewJT_() {
397 const auto& mn = this->MRF();
398 _graph_ = mn.internalGraph();
403 for (
const auto& nodeset: this->jointTargets()) {
404 for (
auto iter1 = nodeset.cbegin(); iter1 != nodeset.cend(); ++iter1) {
406 for (++iter2; iter2 != nodeset.cend(); ++iter2) {
407 _graph_.addEdge(*iter1, *iter2);
413 _hard_ev_nodes_ = this->hardEvidenceNodes();
414 for (
const auto node: _hard_ev_nodes_) {
415 _graph_.eraseNode(node);
422 if (_JT_ !=
nullptr)
delete _JT_;
423 if (_junctionTree_ !=
nullptr)
delete _junctionTree_;
425 const auto& domain_sizes = this->domainSizes();
426 _triangulation_->setGraph(&_graph_, &domain_sizes);
427 const JunctionTree& triang_jt = _triangulation_->junctionTree();
428 if (_use_binary_join_tree_) {
429 BinaryJoinTreeConverterDefault bjt_converter;
431 _JT_ =
new CliqueGraph(bjt_converter.convert(triang_jt, domain_sizes, emptyset));
433 _JT_ =
new CliqueGraph(triang_jt);
435 _junctionTree_ =
new CliqueGraph(triang_jt);
439 const std::vector< NodeId >& JT_elim_order = _triangulation_->eliminationOrder();
440 Size size_elim_order = JT_elim_order.size();
441 NodeProperty< int > elim_order(size_elim_order);
442 for (Idx i = Idx(0); i < size_elim_order; ++i)
443 elim_order.insert(JT_elim_order[i], (
int)i);
447 _factor_to_clique_.clear();
448 _factor_to_clique_.resize(mn.factors().size());
449 for (
const auto& factor: mn.factors()) {
450 const auto& nodes = factor.first;
451 NodeId first_eliminated_node = std::numeric_limits< NodeId >::max();
452 int elim_number = std::numeric_limits< int >::max();
453 for (
const auto node: nodes) {
454 if (_graph_.exists(node) && (elim_order[node] < elim_number)) {
455 elim_number = elim_order[node];
456 first_eliminated_node = node;
460 if (elim_number != std::numeric_limits< int >::max()) {
464 _factor_to_clique_.insert(
466 _triangulation_->createdJunctionTreeClique(first_eliminated_node));
472 _node_to_clique_.clear();
473 _node_to_clique_.resize(_graph_.size());
474 NodeProperty< double > node_to_clique_size(_graph_.size());
475 for (
const auto node: _graph_) {
476 _node_to_clique_.insert(node, std::numeric_limits< NodeId >::max());
477 node_to_clique_size.insert(node, std::numeric_limits< double >::max());
479 double overall_size = 0;
480 for (
const auto clique_id: *_JT_) {
482 const auto& clique_nodes = _JT_->clique(clique_id);
483 double clique_size = 1.0;
484 for (
const auto node: clique_nodes)
485 clique_size *=
double(domain_sizes[node]);
486 overall_size += clique_size;
490 for (
const auto node: clique_nodes) {
491 if (clique_size < node_to_clique_size[node]) {
492 _node_to_clique_[node] = clique_id;
493 node_to_clique_size[node] = clique_size;
499 _joint_target_to_clique_.clear();
500 for (
const auto& set: this->jointTargets()) {
501 NodeId first_eliminated_node = std::numeric_limits< NodeId >::max();
502 int elim_number = std::numeric_limits< int >::max();
506 for (
const auto node: set) {
507 if (!_hard_ev_nodes_.contains(node)) {
510 if (elim_order[node] < elim_number) {
511 elim_number = elim_order[node];
512 first_eliminated_node = node;
517 if (elim_number != std::numeric_limits< int >::max()) {
518 _joint_target_to_clique_.insert(
520 _triangulation_->createdJunctionTreeClique(first_eliminated_node));
525 _computeJoinTreeRoots_();
530 for (
const auto& pot: _clique_ss_tensor_) {
531 if (_clique_tensors_[pot.first].size() > 1)
delete pot.second;
533 _clique_ss_tensor_.clear();
534 for (
const auto& potlist: _clique_tensors_)
535 for (
const auto pot: potlist.second)
537 _clique_tensors_.clear();
540 for (
const auto& pot: _arc_to_created_tensors_)
542 _arc_to_created_tensors_.clear();
547 _hard_ev_projected_factors_.clear();
550 _node_to_soft_evidence_.clear();
554 _ScheduleMultiDimSet_ empty_set;
555 for (
const auto node: *_JT_) {
556 _clique_tensors_.insert(node, empty_set);
557 _clique_ss_tensor_.insert(node,
nullptr);
565 _separator_tensors_.clear();
566 _messages_computed_.clear();
567 for (
const auto& edge: _JT_->edges()) {
568 const Arc arc1(edge.first(), edge.second());
569 _separator_tensors_.insert(arc1,
nullptr);
570 _messages_computed_.insert(arc1,
false);
571 const Arc arc2(edge.second(), edge.first());
572 _separator_tensors_.insert(arc2,
nullptr);
573 _messages_computed_.insert(arc2,
false);
577 for (
const auto& pot: _target_posteriors_)
579 _target_posteriors_.clear();
580 for (
const auto& pot: _joint_target_posteriors_)
582 _joint_target_posteriors_.clear();
587 _use_schedules_ = (overall_size > _schedule_threshold_);
590 const NodeProperty< const Tensor< GUM_SCALAR >* >& evidence = this->evidence();
591 for (
const auto node: this->softEvidenceNodes()) {
592 if (
auto p = _node_to_clique_.tryGet(node)) {
593 auto ev_pot =
new ScheduleMultiDim< Tensor< GUM_SCALAR > >(*evidence[node],
false);
594 _node_to_soft_evidence_.insert(node, ev_pot);
595 _clique_tensors_[*p].insert(ev_pot);
603 if (_use_schedules_) {
605 _initializeJTCliques_(schedule);
607 _initializeJTCliques_();
612 _evidence_changes_.clear();
613 _is_new_jt_needed_ =
false;
617 template < GUM_Numeric GUM_SCALAR >
618 void ShaferShenoyMRFInference< GUM_SCALAR >::_initializeJTCliques_() {
619 const auto& mn = this->MRF();
625 const NodeProperty< const Tensor< GUM_SCALAR >* >& evidence = this->evidence();
626 const NodeProperty< Idx >& hard_evidence = this->hardEvidence();
628 for (
const auto& factor: mn.factors()) {
629 const auto& factor_nodes = factor.first;
630 const auto& pot = *(factor.second);
631 const auto& variables = pot.variablesSequence();
634 NodeSet hard_nodes(factor_nodes.size());
635 bool graph_contains_nodes =
false;
636 for (
const auto node: factor_nodes) {
637 if (_hard_ev_nodes_.contains(node)) hard_nodes.insert(node);
638 else if (_graph_.exists(node)) graph_contains_nodes =
true;
644 if (hard_nodes.empty()) {
645 auto sched_cpt =
new ScheduleMultiDim< Tensor< GUM_SCALAR > >(pot,
false);
646 _clique_tensors_[_factor_to_clique_[&pot]].insert(sched_cpt);
652 if (hard_nodes.size() == factor_nodes.size()) {
653 Instantiation inst(pot);
654 for (Size i = 0; i < hard_nodes.size(); ++i) {
655 inst.chgVal(*variables[i], hard_evidence[mn.nodeId(*(variables[i]))]);
657 _constants_.insert(&pot, pot.get(inst));
662 if (!graph_contains_nodes)
continue;
666 _TensorSet_ marg_factor_set(1 + hard_nodes.size());
667 marg_factor_set.insert(&pot);
668 for (
const auto node: hard_nodes) {
669 marg_factor_set.insert(evidence[node]);
670 hard_variables.
insert(&(mn.variable(node)));
674 MultiDimCombineAndProjectDefault< Tensor< GUM_SCALAR > > combine_and_project(
678 _TensorSet_ new_factor_list
679 = combine_and_project.execute(marg_factor_set, hard_variables);
682 if (new_factor_list.size() != 1) {
683 for (
const auto pot: new_factor_list) {
684 if (!marg_factor_set.contains(pot))
delete pot;
687 "the projection of a tensor containing " <<
"hard evidence is empty!");
689 auto new_factor =
const_cast< Tensor< GUM_SCALAR >*
>(*(new_factor_list.begin()));
690 auto projected_factor
691 =
new ScheduleMultiDim< Tensor< GUM_SCALAR > >(std::move(*new_factor));
694 _clique_tensors_[_factor_to_clique_[&pot]].insert(projected_factor);
695 _hard_ev_projected_factors_.insert(&pot, projected_factor);
704 MultiDimCombinationDefault< Tensor< GUM_SCALAR > > fast_combination(_combination_op_);
705 for (
const auto& xpotset: _clique_tensors_) {
706 const auto& potset = xpotset.second;
707 if (potset.size() > 0) {
712 if (potset.size() == 1) {
713 _clique_ss_tensor_[xpotset.first] = *(potset.cbegin());
715 _TensorSet_ p_potset(potset.size());
716 for (
const auto pot: potset)
718 &(
static_cast< const ScheduleMultiDim< Tensor< GUM_SCALAR >
>* >(pot)->multiDim()));
720 Tensor< GUM_SCALAR >* joint
721 =
const_cast< Tensor< GUM_SCALAR >*
>(fast_combination.execute(p_potset));
722 _clique_ss_tensor_[xpotset.first]
723 =
new ScheduleMultiDim< Tensor< GUM_SCALAR > >(std::move(*joint));
731 template < GUM_Numeric GUM_SCALAR >
732 void ShaferShenoyMRFInference< GUM_SCALAR >::_initializeJTCliques_(Schedule& schedule) {
733 const auto& mn = this->MRF();
739 const NodeProperty< const Tensor< GUM_SCALAR >* >& evidence = this->evidence();
740 const NodeProperty< Idx >& hard_evidence = this->hardEvidence();
742 for (
const auto& factor: mn.factors()) {
743 const auto& factor_nodes = factor.first;
744 const auto& pot = *(factor.second);
745 const auto& variables = pot.variablesSequence();
749 bool graph_contains_nodes =
false;
750 for (
const auto node: factor_nodes) {
751 if (_hard_ev_nodes_.contains(node)) hard_nodes.insert(node);
752 else if (_graph_.exists(node)) graph_contains_nodes =
true;
758 if (hard_nodes.empty()) {
759 auto sched_cpt =
new ScheduleMultiDim< Tensor< GUM_SCALAR > >(pot,
false);
760 _clique_tensors_[_factor_to_clique_[&pot]].insert(sched_cpt);
766 if (hard_nodes.size() == factor_nodes.size()) {
767 Instantiation inst(pot);
768 for (Size i = 0; i < hard_nodes.size(); ++i) {
769 inst.chgVal(*variables[i], hard_evidence[mn.nodeId(*(variables[i]))]);
771 _constants_.insert(&pot, pot.get(inst));
776 if (!graph_contains_nodes)
continue;
780 _ScheduleMultiDimSet_ marg_factor_set(1 + hard_nodes.size());
781 const IScheduleMultiDim* sched_pot
782 = schedule.insertTable< Tensor< GUM_SCALAR > >(pot,
false);
783 marg_factor_set.insert(sched_pot);
785 for (
const auto node: hard_nodes) {
786 const IScheduleMultiDim* pot
787 = schedule.insertTable< Tensor< GUM_SCALAR > >(*evidence[node],
false);
788 marg_factor_set.insert(pot);
789 hard_variables.
insert(&(mn.variable(node)));
793 MultiDimCombineAndProjectDefault< Tensor< GUM_SCALAR > > combine_and_project(
797 _ScheduleMultiDimSet_ new_factor_list
798 = combine_and_project.schedule(schedule, marg_factor_set, hard_variables);
801 if (new_factor_list.size() != 1) {
803 "the projection of a tensor containing " <<
"hard evidence is empty!");
805 auto projected_factor =
const_cast< ScheduleMultiDim< Tensor< GUM_SCALAR >
>* >(
806 static_cast< const ScheduleMultiDim< Tensor< GUM_SCALAR >
>* >(
807 *new_factor_list.begin()));
808 const_cast< ScheduleOperator*
>(schedule.scheduleMultiDimCreator(projected_factor))
809 ->makeResultsPersistent(
true);
811 _clique_tensors_[_factor_to_clique_[&pot]].insert(projected_factor);
812 _hard_ev_projected_factors_.insert(&pot, projected_factor);
816 this->scheduler().execute(schedule);
823 MultiDimCombinationDefault< Tensor< GUM_SCALAR > > fast_combination(_combination_op_);
824 for (
const auto& xpotset: _clique_tensors_) {
825 const auto& potset = xpotset.second;
826 if (potset.size() > 0) {
831 if (potset.size() == 1) {
832 _clique_ss_tensor_[xpotset.first] = *(potset.cbegin());
835 for (
const auto pot: potset) {
836 schedule.emplaceScheduleMultiDim(*pot);
839 auto joint =
const_cast< ScheduleMultiDim< Tensor< GUM_SCALAR >
>* >(
840 static_cast< const ScheduleMultiDim< Tensor< GUM_SCALAR >
>* >(
841 fast_combination.schedule(schedule, potset)));
842 const_cast< ScheduleOperator*
>(schedule.scheduleMultiDimCreator(joint))
843 ->makeResultsPersistent(
true);
844 _clique_ss_tensor_[xpotset.first] = joint;
848 this->scheduler().execute(schedule);
852 template < GUM_Numeric GUM_SCALAR >
853 void ShaferShenoyMRFInference< GUM_SCALAR >::updateOutdatedStructure_() {
855 if (_isNewJTNeeded_()) {
861 updateOutdatedTensors_();
866 template < GUM_Numeric GUM_SCALAR >
867 void ShaferShenoyMRFInference< GUM_SCALAR >::_diffuseMessageInvalidations_(
870 NodeSet& invalidated_cliques) {
872 invalidated_cliques.insert(to_id);
875 const Arc arc(from_id, to_id);
876 bool& message_computed = _messages_computed_[arc];
877 if (message_computed) {
878 message_computed =
false;
879 _separator_tensors_[arc] =
nullptr;
880 if (_arc_to_created_tensors_.exists(arc)) {
881 delete _arc_to_created_tensors_[arc];
882 _arc_to_created_tensors_.erase(arc);
886 for (
const auto node_id: _JT_->neighbours(to_id)) {
887 if (node_id != from_id) _diffuseMessageInvalidations_(to_id, node_id, invalidated_cliques);
894 template < GUM_Numeric GUM_SCALAR >
895 void ShaferShenoyMRFInference< GUM_SCALAR >::updateOutdatedTensors_() {
900 NodeProperty< bool > ss_tensor_to_deallocate(_clique_tensors_.size());
901 for (
const auto& potset: _clique_tensors_) {
902 ss_tensor_to_deallocate.insert(potset.first, (potset.second.size() > 1));
912 const auto& mn = this->MRF();
913 NodeSet hard_nodes_changed(_hard_ev_nodes_.size());
914 Set< const Tensor< GUM_SCALAR >* > hard_projected_factors_changed(mn.factors().size());
915 for (
const auto node: _hard_ev_nodes_) {
916 if (_evidence_changes_.exists(node)) {
917 hard_nodes_changed.insert(node);
918 for (
const auto pot: _node_to_factors_[node]) {
919 if (_hard_ev_projected_factors_.exists(pot)
920 && !hard_projected_factors_changed.exists(pot)) {
921 hard_projected_factors_changed.insert(pot);
927 NodeSet hard_cliques_changed(hard_projected_factors_changed.size());
928 for (
const auto pot: hard_projected_factors_changed) {
929 const auto chgPot = _hard_ev_projected_factors_[pot];
930 const NodeId chgClique = _factor_to_clique_[pot];
931 _clique_tensors_[chgClique].erase(chgPot);
932 _hard_ev_projected_factors_.erase(pot);
933 if (!hard_cliques_changed.contains(chgClique)) hard_cliques_changed.insert(chgClique);
945 NodeSet invalidated_cliques(_JT_->size());
946 for (
const auto& pair: _evidence_changes_) {
947 if (
auto p = _node_to_clique_.tryGet(pair.first)) {
948 const auto clique = *p;
949 invalidated_cliques.insert(clique);
950 for (
const auto neighbor: _JT_->neighbours(clique)) {
951 _diffuseMessageInvalidations_(clique, neighbor, invalidated_cliques);
958 for (
const auto clique: hard_cliques_changed) {
959 invalidated_cliques.insert(clique);
960 for (
const auto neighbor: _JT_->neighbours(clique)) {
961 _diffuseMessageInvalidations_(clique, neighbor, invalidated_cliques);
967 for (
const auto clique: invalidated_cliques) {
968 if (ss_tensor_to_deallocate[clique]) {
969 delete _clique_ss_tensor_[clique];
970 _clique_ss_tensor_[clique] =
nullptr;
977 if (!_target_posteriors_.empty()) {
978 for (
auto iter = _target_posteriors_.beginSafe(); iter != _target_posteriors_.endSafe();
982 if (_graph_.exists(iter.key())
983 && (invalidated_cliques.exists(_node_to_clique_[iter.key()]))) {
985 _target_posteriors_.erase(iter);
988 else if (hard_nodes_changed.contains(iter.key())) {
990 _target_posteriors_.erase(iter);
997 for (
auto iter = _joint_target_posteriors_.beginSafe();
998 iter != _joint_target_posteriors_.endSafe();
1002 const auto clique = _joint_target_to_clique_.tryGet(iter.key());
1003 if (!clique || invalidated_cliques.exists(*clique)) {
1005 _joint_target_posteriors_.erase(iter);
1008 bool has_unevidenced_node =
false;
1009 for (
const auto node: iter.key()) {
1010 if (!hard_nodes_changed.exists(node)) {
1011 has_unevidenced_node =
true;
1015 if (!has_unevidenced_node) {
1017 _joint_target_posteriors_.erase(iter);
1024 for (
const auto& pot_pair: _node_to_soft_evidence_) {
1025 delete pot_pair.second;
1026 _clique_tensors_[_node_to_clique_[pot_pair.first]].erase(pot_pair.second);
1028 _node_to_soft_evidence_.clear();
1030 const auto& evidence = this->evidence();
1031 for (
const auto node: this->softEvidenceNodes()) {
1032 auto ev_pot =
new ScheduleMultiDim< Tensor< GUM_SCALAR > >(*evidence[node],
false);
1033 _node_to_soft_evidence_.insert(node, ev_pot);
1034 _clique_tensors_[_node_to_clique_[node]].insert(ev_pot);
1044 if (_use_schedules_) {
1046 for (
const auto pot: hard_projected_factors_changed) {
1047 _ScheduleMultiDimSet_ marg_pot_set;
1048 const auto sched_pot = schedule.insertTable< Tensor< GUM_SCALAR > >(*pot,
false);
1049 marg_pot_set.insert(sched_pot);
1050 const auto& variables = pot->variablesSequence();
1052 for (
const auto var: variables) {
1053 NodeId xnode = mn.nodeId(*var);
1054 if (_hard_ev_nodes_.exists(xnode)) {
1056 = schedule.insertTable< Tensor< GUM_SCALAR > >(*evidence[xnode],
false);
1057 marg_pot_set.insert(ev_pot);
1058 hard_variables.
insert(var);
1063 MultiDimCombineAndProjectDefault< Tensor< GUM_SCALAR > > combine_and_project(
1067 _ScheduleMultiDimSet_ new_pot_list
1068 = combine_and_project.schedule(schedule, marg_pot_set, hard_variables);
1071 if (new_pot_list.size() != 1) {
1073 "the projection of a tensor containing " <<
"hard evidence is empty!");
1075 auto projected_pot =
const_cast< ScheduleMultiDim< Tensor< GUM_SCALAR >
>* >(
1076 static_cast< const ScheduleMultiDim< Tensor< GUM_SCALAR >
>* >(*new_pot_list.begin()));
1077 const_cast< ScheduleOperator*
>(schedule.scheduleMultiDimCreator(projected_pot))
1078 ->makeResultsPersistent(
true);
1079 _clique_tensors_[_factor_to_clique_[pot]].insert(projected_pot);
1080 _hard_ev_projected_factors_.insert(pot, projected_pot);
1086 MultiDimCombinationDefault< Tensor< GUM_SCALAR > > fast_combination(_combination_op_);
1087 for (
const auto clique: invalidated_cliques) {
1088 const auto& potset = _clique_tensors_[clique];
1090 if (potset.size() > 0) {
1095 if (potset.size() == 1) {
1096 _clique_ss_tensor_[clique] = *(potset.cbegin());
1098 for (
const auto pot: potset)
1099 if (!schedule.existsScheduleMultiDim(pot->id()))
1100 schedule.emplaceScheduleMultiDim(*pot);
1101 auto joint =
const_cast< ScheduleMultiDim< Tensor< GUM_SCALAR >
>* >(
1102 static_cast< const ScheduleMultiDim< Tensor< GUM_SCALAR >
>* >(
1103 fast_combination.schedule(schedule, potset)));
1104 const_cast< ScheduleOperator*
>(schedule.scheduleMultiDimCreator(joint))
1105 ->makeResultsPersistent(
true);
1106 _clique_ss_tensor_[clique] = joint;
1110 this->scheduler().execute(schedule);
1112 for (
const auto pot: hard_projected_factors_changed) {
1113 _TensorSet_ marg_pot_set;
1114 marg_pot_set.insert(pot);
1115 const auto& variables = pot->variablesSequence();
1118 for (
const auto var: variables) {
1119 NodeId xnode = mn.nodeId(*var);
1120 if (_hard_ev_nodes_.exists(xnode)) {
1121 marg_pot_set.insert(evidence[xnode]);
1122 hard_variables.
insert(var);
1127 MultiDimCombineAndProjectDefault< Tensor< GUM_SCALAR > > combine_and_project(
1131 _TensorSet_ new_pot_list = combine_and_project.execute(marg_pot_set, hard_variables);
1134 if (new_pot_list.size() != 1) {
1136 "the projection of a tensor containing " <<
"hard evidence is empty!");
1138 Tensor< GUM_SCALAR >* xprojected_pot
1139 =
const_cast< Tensor< GUM_SCALAR >*
>(*new_pot_list.begin());
1141 =
new ScheduleMultiDim< Tensor< GUM_SCALAR > >(std::move(*xprojected_pot));
1142 delete xprojected_pot;
1143 _clique_tensors_[_factor_to_clique_[pot]].insert(projected_pot);
1144 _hard_ev_projected_factors_.insert(pot, projected_pot);
1150 MultiDimCombinationDefault< Tensor< GUM_SCALAR > > fast_combination(_combination_op_);
1151 for (
const auto clique: invalidated_cliques) {
1152 const auto& potset = _clique_tensors_[clique];
1154 if (potset.size() > 0) {
1159 if (potset.size() == 1) {
1160 _clique_ss_tensor_[clique] = *(potset.cbegin());
1162 _TensorSet_ p_potset(potset.size());
1163 for (
const auto pot: potset)
1165 static_cast< const ScheduleMultiDim< Tensor< GUM_SCALAR >
>* >(pot)->multiDim()));
1167 Tensor< GUM_SCALAR >* joint
1168 =
const_cast< Tensor< GUM_SCALAR >*
>(fast_combination.execute(p_potset));
1169 _clique_ss_tensor_[clique]
1170 =
new ScheduleMultiDim< Tensor< GUM_SCALAR > >(std::move(*joint));
1178 const auto& hard_evidence = this->hardEvidence();
1179 for (
auto& node_cst: _constants_) {
1180 const Tensor< GUM_SCALAR >& pot = *(node_cst.first);
1181 Instantiation inst(pot);
1182 for (
const auto var: pot.variablesSequence()) {
1183 inst.chgVal(*var, hard_evidence[mn.nodeId(*var)]);
1185 node_cst.second = pot.get(inst);
1189 _evidence_changes_.clear();
1193 template < GUM_Numeric GUM_SCALAR >
1194 void ShaferShenoyMRFInference< GUM_SCALAR >::_computeJoinTreeRoots_() {
1199 for (
const auto node: this->targets()) {
1200 if (
auto p = _node_to_clique_.tryGet(node)) { clique_targets.insert(*p); }
1202 for (
const auto& set: this->jointTargets()) {
1203 if (
auto p = _joint_target_to_clique_.tryGet(set)) { clique_targets.insert(*p); }
1212 template < GUM_Numeric GUM_SCALAR >
1213 void ShaferShenoyMRFInference< GUM_SCALAR >::_collectMessage_(Schedule& schedule,
1216 for (
const auto other: _JT_->neighbours(
id)) {
1217 if ((other != from) && !_messages_computed_[
Arc(other,
id)])
1218 _collectMessage_(schedule, other,
id);
1221 if ((
id != from) && !_messages_computed_[
Arc(
id, from)]) {
1222 _produceMessage_(schedule,
id, from);
1227 template < GUM_Numeric GUM_SCALAR >
1228 void ShaferShenoyMRFInference< GUM_SCALAR >::_collectMessage_(NodeId
id, NodeId from) {
1229 for (
const auto other: _JT_->neighbours(
id)) {
1230 if ((other != from) && !_messages_computed_[
Arc(other,
id)]) _collectMessage_(other,
id);
1233 if ((
id != from) && !_messages_computed_[
Arc(
id, from)]) { _produceMessage_(
id, from); }
1237 template < GUM_Numeric GUM_SCALAR >
1238 const IScheduleMultiDim* ShaferShenoyMRFInference< GUM_SCALAR >::_marginalizeOut_(
1240 Set< const IScheduleMultiDim* > pot_list,
1245 for (
const auto pot: pot_list) {
1246 if (!schedule.existsScheduleMultiDim(pot->id())) schedule.emplaceScheduleMultiDim(*pot);
1251 MultiDimCombineAndProjectDefault< Tensor< GUM_SCALAR > > combine_and_project(_combination_op_,
1253 _ScheduleMultiDimSet_ new_pot_list = combine_and_project.schedule(schedule, pot_list, del_vars);
1256 if (new_pot_list.size() == 1)
return *(new_pot_list.begin());
1257 MultiDimCombinationDefault< Tensor< GUM_SCALAR > > fast_combination(_combination_op_);
1258 return fast_combination.schedule(schedule, new_pot_list);
1262 template < GUM_Numeric GUM_SCALAR >
1263 const IScheduleMultiDim* ShaferShenoyMRFInference< GUM_SCALAR >::_marginalizeOut_(
1264 Set< const IScheduleMultiDim* >& pot_list,
1267 _TensorSet_ xpot_list(pot_list.size());
1268 for (
auto pot: pot_list)
1270 &(
static_cast< const ScheduleMultiDim< Tensor< GUM_SCALAR >
>* >(pot)->multiDim()));
1274 MultiDimCombineAndProjectDefault< Tensor< GUM_SCALAR > > combine_and_project(_combination_op_,
1276 _TensorSet_ xnew_pot_list = combine_and_project.execute(xpot_list, del_vars);
1279 const Tensor< GUM_SCALAR >* xres_pot;
1280 if (xnew_pot_list.size() == 1) {
1281 xres_pot = *(xnew_pot_list.begin());
1285 MultiDimCombinationDefault< Tensor< GUM_SCALAR > > fast_combination(_combination_op_);
1286 xres_pot = fast_combination.execute(xnew_pot_list);
1287 for (
const auto pot: xnew_pot_list) {
1288 if (!xpot_list.contains(pot) && (pot != xres_pot))
delete pot;
1293 ScheduleMultiDim< Tensor< GUM_SCALAR > >* res_pot;
1294 if (xpot_list.contains(xres_pot))
1295 res_pot =
new ScheduleMultiDim< Tensor< GUM_SCALAR > >(*xres_pot,
false);
1297 res_pot =
new ScheduleMultiDim< Tensor< GUM_SCALAR > >(
1298 std::move(
const_cast< Tensor< GUM_SCALAR >&
>(*xres_pot)));
1306 template < GUM_Numeric GUM_SCALAR >
1307 void ShaferShenoyMRFInference< GUM_SCALAR >::_produceMessage_(Schedule& schedule,
1311 _ScheduleMultiDimSet_ pot_list;
1312 if (_clique_ss_tensor_[from_id] !=
nullptr) pot_list.insert(_clique_ss_tensor_[from_id]);
1315 for (
const auto other_id: _JT_->neighbours(from_id)) {
1316 if (other_id != to_id) {
1317 const auto separator_pot = _separator_tensors_[
Arc(other_id, from_id)];
1318 if (separator_pot !=
nullptr) pot_list.insert(separator_pot);
1323 const NodeSet& from_clique = _JT_->clique(from_id);
1324 const NodeSet& separator = _JT_->separator(from_id, to_id);
1327 const auto& mn = this->MRF();
1329 for (
const auto node: from_clique) {
1330 if (!separator.contains(node)) {
1331 del_vars.
insert(&(mn.variable(node)));
1333 kept_vars.
insert(&(mn.variable(node)));
1339 const IScheduleMultiDim* new_pot = _marginalizeOut_(schedule, pot_list, del_vars, kept_vars);
1342 const Arc arc(from_id, to_id);
1343 if (!pot_list.exists(new_pot)) {
1344 if (!_arc_to_created_tensors_.exists(arc)) {
1345 _arc_to_created_tensors_.insert(arc, new_pot);
1348 auto op = schedule.scheduleMultiDimCreator(new_pot);
1349 if (op !=
nullptr)
const_cast< ScheduleOperator*
>(op)->makeResultsPersistent(
true);
1353 _separator_tensors_[arc] = new_pot;
1354 _messages_computed_[arc] =
true;
1358 template < GUM_Numeric GUM_SCALAR >
1359 void ShaferShenoyMRFInference< GUM_SCALAR >::_produceMessage_(NodeId from_id, NodeId to_id) {
1361 _ScheduleMultiDimSet_ pot_list;
1362 if (_clique_ss_tensor_[from_id] !=
nullptr) pot_list.insert(_clique_ss_tensor_[from_id]);
1365 for (
const auto other_id: _JT_->neighbours(from_id)) {
1366 if (other_id != to_id) {
1367 const auto separator_pot = _separator_tensors_[
Arc(other_id, from_id)];
1368 if (separator_pot !=
nullptr) pot_list.insert(separator_pot);
1373 const NodeSet& from_clique = _JT_->clique(from_id);
1374 const NodeSet& separator = _JT_->separator(from_id, to_id);
1377 const auto& mn = this->MRF();
1379 for (
const auto node: from_clique) {
1380 if (!separator.contains(node)) {
1381 del_vars.
insert(&(mn.variable(node)));
1383 kept_vars.
insert(&(mn.variable(node)));
1389 const IScheduleMultiDim* new_pot = _marginalizeOut_(pot_list, del_vars, kept_vars);
1392 const Arc arc(from_id, to_id);
1393 if (!pot_list.exists(new_pot)) {
1394 if (!_arc_to_created_tensors_.exists(arc)) { _arc_to_created_tensors_.insert(arc, new_pot); }
1397 _separator_tensors_[arc] = new_pot;
1398 _messages_computed_[arc] =
true;
1402 template < GUM_Numeric GUM_SCALAR >
1403 void ShaferShenoyMRFInference< GUM_SCALAR >::onModelChanged_(
const GraphicalModel* mn) {
1404 JointTargetedMRFInference< GUM_SCALAR >::onModelChanged_(mn);
1405 _partition_function_.reset();
1409 template < GUM_Numeric GUM_SCALAR >
1410 void ShaferShenoyMRFInference< GUM_SCALAR >::makeInference_() {
1411 if (_use_schedules_) {
1415 for (
const auto node: this->targets()) {
1419 if (_graph_.exists(node)) {
1420 _collectMessage_(schedule, _node_to_clique_[node], _node_to_clique_[node]);
1428 for (
const auto& set: _joint_target_to_clique_)
1429 _collectMessage_(schedule, set.second, set.second);
1432 this->scheduler().execute(schedule);
1435 for (
const auto node: this->targets()) {
1439 if (_graph_.exists(node)) {
1440 _collectMessage_(_node_to_clique_[node], _node_to_clique_[node]);
1448 for (
const auto& set: _joint_target_to_clique_)
1449 _collectMessage_(set.second, set.second);
1454 template < GUM_Numeric GUM_SCALAR >
1455 Tensor< GUM_SCALAR >*
1456 ShaferShenoyMRFInference< GUM_SCALAR >::unnormalizedJointPosterior_(NodeId
id) {
1457 if (_use_schedules_) {
1459 return _unnormalizedJointPosterior_(schedule,
id);
1461 return _unnormalizedJointPosterior_(
id);
1466 template < GUM_Numeric GUM_SCALAR >
1467 Tensor< GUM_SCALAR >*
1468 ShaferShenoyMRFInference< GUM_SCALAR >::_unnormalizedJointPosterior_(Schedule& schedule,
1470 const auto& mn = this->MRF();
1474 if (this->hardEvidenceNodes().
contains(
id)) {
1475 return new Tensor< GUM_SCALAR >(*(this->evidence()[
id]));
1478 auto& scheduler = this->scheduler();
1482 const NodeId clique_of_id = _node_to_clique_[id];
1483 _collectMessage_(schedule, clique_of_id, clique_of_id);
1488 _ScheduleMultiDimSet_ pot_list;
1489 if (_clique_ss_tensor_[clique_of_id] !=
nullptr)
1490 pot_list.insert(_clique_ss_tensor_[clique_of_id]);
1493 for (
const auto other: _JT_->neighbours(clique_of_id))
1494 pot_list.insert(_separator_tensors_[
Arc(other, clique_of_id)]);
1497 const NodeSet& nodes = _JT_->clique(clique_of_id);
1500 for (
const auto node: nodes) {
1501 if (node !=
id) del_vars.
insert(&(mn.variable(node)));
1506 auto resulting_pot =
const_cast< ScheduleMultiDim< Tensor< GUM_SCALAR >
>* >(
1507 static_cast< const ScheduleMultiDim< Tensor< GUM_SCALAR >
>* >(
1508 _marginalizeOut_(schedule, pot_list, del_vars, kept_vars)));
1509 Tensor< GUM_SCALAR >* joint =
nullptr;
1511 scheduler.execute(schedule);
1515 if (pot_list.exists(resulting_pot)) {
1516 joint =
new Tensor< GUM_SCALAR >(resulting_pot->multiDim());
1518 joint = resulting_pot->exportMultiDim();
1524 bool nonzero_found =
false;
1525 for (Instantiation inst(*joint); !inst.end(); ++inst) {
1526 if (joint->get(inst)) {
1527 nonzero_found =
true;
1531 if (!nonzero_found) {
1535 "some evidence entered into the Markov "
1536 "net are incompatible (their joint proba = 0)");
1542 template < GUM_Numeric GUM_SCALAR >
1543 Tensor< GUM_SCALAR >*
1544 ShaferShenoyMRFInference< GUM_SCALAR >::_unnormalizedJointPosterior_(NodeId
id) {
1545 const auto& mn = this->MRF();
1549 if (this->hardEvidenceNodes().
contains(
id)) {
1550 return new Tensor< GUM_SCALAR >(*(this->evidence()[
id]));
1555 NodeId clique_of_id = _node_to_clique_[id];
1556 _collectMessage_(clique_of_id, clique_of_id);
1561 _ScheduleMultiDimSet_ pot_list;
1562 if (_clique_ss_tensor_[clique_of_id] !=
nullptr)
1563 pot_list.insert(_clique_ss_tensor_[clique_of_id]);
1566 for (
const auto other: _JT_->neighbours(clique_of_id))
1567 pot_list.insert(_separator_tensors_[
Arc(other, clique_of_id)]);
1570 const NodeSet& nodes = _JT_->clique(clique_of_id);
1573 for (
const auto node: nodes) {
1574 if (node !=
id) del_vars.
insert(&(mn.variable(node)));
1579 auto resulting_pot =
const_cast< ScheduleMultiDim< Tensor< GUM_SCALAR >
>* >(
1580 static_cast< const ScheduleMultiDim< Tensor< GUM_SCALAR >
>* >(
1581 _marginalizeOut_(pot_list, del_vars, kept_vars)));
1582 Tensor< GUM_SCALAR >* joint =
nullptr;
1586 if (pot_list.exists(resulting_pot)) {
1587 joint =
new Tensor< GUM_SCALAR >(resulting_pot->multiDim());
1589 joint = resulting_pot->exportMultiDim();
1590 delete resulting_pot;
1596 bool nonzero_found =
false;
1597 for (Instantiation inst(*joint); !inst.end(); ++inst) {
1598 if (joint->get(inst)) {
1599 nonzero_found =
true;
1603 if (!nonzero_found) {
1607 "some evidence entered into the Markov "
1608 "net are incompatible (their joint proba = 0)");
1614 template < GUM_Numeric GUM_SCALAR >
1615 const Tensor< GUM_SCALAR >& ShaferShenoyMRFInference< GUM_SCALAR >::posterior_(NodeId
id) {
1617 if (
auto p = _target_posteriors_.tryGet(
id)) {
return *(*p); }
1620 auto joint = unnormalizedJointPosterior_(
id);
1621 if (joint->sum() != 1)
1623 _target_posteriors_.insert(
id, joint);
1629 template < GUM_Numeric GUM_SCALAR >
1630 Tensor< GUM_SCALAR >*
1631 ShaferShenoyMRFInference< GUM_SCALAR >::unnormalizedJointPosterior_(
const NodeSet& set) {
1632 if (_use_schedules_) {
1634 return _unnormalizedJointPosterior_(schedule, set);
1636 return _unnormalizedJointPosterior_(set);
1641 template < GUM_Numeric GUM_SCALAR >
1642 Tensor< GUM_SCALAR >*
1643 ShaferShenoyMRFInference< GUM_SCALAR >::_unnormalizedJointPosterior_(Schedule& schedule,
1644 const NodeSet& set) {
1647 NodeSet targets = set, hard_ev_nodes;
1648 for (
const auto node: this->hardEvidenceNodes()) {
1649 if (targets.contains(node)) {
1650 targets.erase(node);
1651 hard_ev_nodes.insert(node);
1655 auto& scheduler = this->scheduler();
1659 const auto& evidence = this->evidence();
1660 if (targets.empty()) {
1661 if (set.size() == 1) {
1662 return new Tensor< GUM_SCALAR >(*evidence[*set.begin()]);
1664 _ScheduleMultiDimSet_ pot_list;
1665 for (
const auto node: set) {
1666 auto new_pot_ev = schedule.insertTable< Tensor< GUM_SCALAR > >(*evidence[node],
false);
1667 pot_list.insert(new_pot_ev);
1671 MultiDimCombinationDefault< Tensor< GUM_SCALAR > > fast_combination(_combination_op_);
1672 const IScheduleMultiDim* pot = fast_combination.schedule(schedule, pot_list);
1673 auto schedule_pot =
const_cast< ScheduleMultiDim< Tensor< GUM_SCALAR >
>* >(
1674 static_cast< const ScheduleMultiDim< Tensor< GUM_SCALAR >
>* >(pot));
1675 scheduler.execute(schedule);
1676 auto result = schedule_pot->exportMultiDim();
1686 NodeId clique_of_set;
1687 if (
auto p_clique = _joint_target_to_clique_.tryGet(set)) {
1688 clique_of_set = *p_clique;
1695 for (
const auto node: targets) {
1696 if (!_graph_.exists(node)) {
1698 "The variable " << this->MRF().variable(node).name() <<
"(" << node
1699 <<
") does not belong to this optimized inference.")
1705 const std::vector< NodeId >& JT_elim_order = _triangulation_->eliminationOrder();
1706 NodeProperty< int > elim_order(Size(JT_elim_order.size()));
1707 for (std::size_t i = std::size_t(0), size = JT_elim_order.size(); i < size; ++i)
1708 elim_order.insert(JT_elim_order[i], (
int)i);
1709 NodeId first_eliminated_node = *(targets.begin());
1710 int elim_number = elim_order[first_eliminated_node];
1711 for (
const auto node: targets) {
1712 if (elim_order[node] < elim_number) {
1713 elim_number = elim_order[node];
1714 first_eliminated_node = node;
1718 clique_of_set = _triangulation_->createdJunctionTreeClique(first_eliminated_node);
1722 const NodeSet& clique_nodes = _JT_->clique(clique_of_set);
1723 for (
const auto node: targets) {
1724 if (!clique_nodes.contains(node)) {
1726 this->MRF().names(set) <<
"(" << set <<
")"
1727 <<
" is not addressable in this optimized inference.")
1732 _joint_target_to_clique_.
insert(set, clique_of_set);
1736 _collectMessage_(schedule, clique_of_set, clique_of_set);
1741 _ScheduleMultiDimSet_ pot_list;
1742 if (_clique_ss_tensor_[clique_of_set] !=
nullptr) {
1743 auto pot = _clique_ss_tensor_[clique_of_set];
1744 if (!schedule.existsScheduleMultiDim(pot->id())) schedule.emplaceScheduleMultiDim(*pot);
1745 pot_list.insert(_clique_ss_tensor_[clique_of_set]);
1749 for (
const auto other: _JT_->neighbours(clique_of_set)) {
1750 const auto pot = _separator_tensors_[
Arc(other, clique_of_set)];
1751 if (pot !=
nullptr) pot_list.insert(pot);
1756 const NodeSet& nodes = _JT_->clique(clique_of_set);
1759 const auto& mn = this->MRF();
1760 for (
const auto node: nodes) {
1761 if (!targets.contains(node)) {
1762 del_vars.
insert(&(mn.variable(node)));
1764 kept_vars.
insert(&(mn.variable(node)));
1770 const IScheduleMultiDim* new_pot = _marginalizeOut_(schedule, pot_list, del_vars, kept_vars);
1771 scheduler.execute(schedule);
1772 ScheduleMultiDim< Tensor< GUM_SCALAR > >* resulting_pot
1773 =
const_cast< ScheduleMultiDim< Tensor< GUM_SCALAR >
>* >(
1774 static_cast< const ScheduleMultiDim< Tensor< GUM_SCALAR >
>* >(new_pot));
1778 Tensor< GUM_SCALAR >* joint =
nullptr;
1779 if (pot_list.exists(resulting_pot)) {
1780 joint =
new Tensor< GUM_SCALAR >(resulting_pot->multiDim());
1782 joint = resulting_pot->exportMultiDim();
1787 bool nonzero_found =
false;
1788 for (Instantiation inst(*joint); !inst.end(); ++inst) {
1789 if ((*joint)[inst]) {
1790 nonzero_found =
true;
1794 if (!nonzero_found) {
1798 "some evidence entered into the Markov "
1799 "net are incompatible (their joint proba = 0)");
1806 template < GUM_Numeric GUM_SCALAR >
1807 Tensor< GUM_SCALAR >*
1808 ShaferShenoyMRFInference< GUM_SCALAR >::_unnormalizedJointPosterior_(
const NodeSet& set) {
1811 NodeSet targets = set, hard_ev_nodes;
1812 for (
const auto node: this->hardEvidenceNodes()) {
1813 if (targets.contains(node)) {
1814 targets.erase(node);
1815 hard_ev_nodes.insert(node);
1821 const auto& evidence = this->evidence();
1822 if (targets.empty()) {
1823 if (set.size() == 1) {
1824 return new Tensor< GUM_SCALAR >(*evidence[*set.begin()]);
1826 _TensorSet_ pot_list;
1827 for (
const auto node: set) {
1828 pot_list.insert(evidence[node]);
1832 MultiDimCombinationDefault< Tensor< GUM_SCALAR > > fast_combination(_combination_op_);
1833 const Tensor< GUM_SCALAR >* pot = fast_combination.execute(pot_list);
1835 return const_cast< Tensor< GUM_SCALAR >*
>(pot);
1843 NodeId clique_of_set;
1844 if (
auto p_clique = _joint_target_to_clique_.tryGet(set)) {
1845 clique_of_set = *p_clique;
1852 for (
const auto node: targets) {
1853 if (!_graph_.exists(node)) {
1855 "The variable " << this->MRF().variable(node).name() <<
"(" << node
1856 <<
") does not belong to this optimized inference.")
1862 const std::vector< NodeId >& JT_elim_order = _triangulation_->eliminationOrder();
1863 NodeProperty< int > elim_order(Size(JT_elim_order.size()));
1864 for (std::size_t i = std::size_t(0), size = JT_elim_order.size(); i < size; ++i)
1865 elim_order.insert(JT_elim_order[i], (
int)i);
1866 NodeId first_eliminated_node = *(targets.begin());
1867 int elim_number = elim_order[first_eliminated_node];
1868 for (
const auto node: targets) {
1869 if (elim_order[node] < elim_number) {
1870 elim_number = elim_order[node];
1871 first_eliminated_node = node;
1875 clique_of_set = _triangulation_->createdJunctionTreeClique(first_eliminated_node);
1879 const NodeSet& clique_nodes = _JT_->clique(clique_of_set);
1880 for (
const auto node: targets) {
1881 if (!clique_nodes.contains(node)) {
1887 _joint_target_to_clique_.
insert(set, clique_of_set);
1891 _collectMessage_(clique_of_set, clique_of_set);
1896 _ScheduleMultiDimSet_ pot_list;
1897 if (_clique_ss_tensor_[clique_of_set] !=
nullptr) {
1898 auto pot = _clique_ss_tensor_[clique_of_set];
1899 if (pot !=
nullptr) pot_list.insert(_clique_ss_tensor_[clique_of_set]);
1903 for (
const auto other: _JT_->neighbours(clique_of_set)) {
1904 const auto pot = _separator_tensors_[
Arc(other, clique_of_set)];
1905 if (pot !=
nullptr) pot_list.insert(pot);
1910 const NodeSet& nodes = _JT_->clique(clique_of_set);
1913 const auto& mn = this->MRF();
1914 for (
const auto node: nodes) {
1915 if (!targets.contains(node)) {
1916 del_vars.
insert(&(mn.variable(node)));
1918 kept_vars.
insert(&(mn.variable(node)));
1924 const IScheduleMultiDim* new_pot = _marginalizeOut_(pot_list, del_vars, kept_vars);
1925 ScheduleMultiDim< Tensor< GUM_SCALAR > >* resulting_pot
1926 =
const_cast< ScheduleMultiDim< Tensor< GUM_SCALAR >
>* >(
1927 static_cast< const ScheduleMultiDim< Tensor< GUM_SCALAR >
>* >(new_pot));
1931 Tensor< GUM_SCALAR >* joint =
nullptr;
1932 if (pot_list.exists(resulting_pot)) {
1933 joint =
new Tensor< GUM_SCALAR >(resulting_pot->multiDim());
1935 joint = resulting_pot->exportMultiDim();
1941 bool nonzero_found =
false;
1942 for (Instantiation inst(*joint); !inst.end(); ++inst) {
1943 if ((*joint)[inst]) {
1944 nonzero_found =
true;
1948 if (!nonzero_found) {
1952 "some evidence entered into the Markov "
1953 "net are incompatible (their joint proba = 0)");
1960 template < GUM_Numeric GUM_SCALAR >
1961 const Tensor< GUM_SCALAR >&
1962 ShaferShenoyMRFInference< GUM_SCALAR >::jointPosterior_(
const NodeSet& set) {
1964 if (
auto p = _joint_target_posteriors_.tryGet(set)) {
return *(*p); }
1967 auto joint = unnormalizedJointPosterior_(set);
1969 _joint_target_posteriors_.insert(set, joint);
1975 template < GUM_Numeric GUM_SCALAR >
1976 const Tensor< GUM_SCALAR >&
1977 ShaferShenoyMRFInference< GUM_SCALAR >::jointPosterior_(
const NodeSet& wanted_target,
1978 const NodeSet& declared_target) {
1980 if (
auto p = _joint_target_posteriors_.tryGet(wanted_target))
return *(*p);
1986 if (!_joint_target_posteriors_.exists(declared_target)) { jointPosterior_(declared_target); }
1989 const auto& mn = this->MRF();
1991 for (
const auto node: declared_target)
1992 if (!wanted_target.contains(node)) del_vars.
insert(&(mn.variable(node)));
1994 =
new Tensor< GUM_SCALAR >(_joint_target_posteriors_[declared_target]->sumOut(del_vars));
1998 _joint_target_posteriors_.insert(wanted_target, pot);
1999 if (
auto clique = _joint_target_to_clique_.tryGet(declared_target)) {
2000 const NodeId clique_id = *clique;
2001 if (!_joint_target_to_clique_.exists(wanted_target))
2002 _joint_target_to_clique_.insert(wanted_target, clique_id);
2008 template < GUM_Numeric GUM_SCALAR >
2009 GUM_SCALAR ShaferShenoyMRFInference< GUM_SCALAR >::evidenceProbability() {
2011 if (!this->hasEvidence())
return GUM_SCALAR(1);
2014 if (!_partition_function_) {
2015 ShaferShenoyMRFInference< GUM_SCALAR > no_evidence(&this->MRF());
2016 _partition_function_ = no_evidence._evidenceMass_();
2018 return _evidenceMass_() / *_partition_function_;
2021 template < GUM_Numeric GUM_SCALAR >
2022 GUM_SCALAR ShaferShenoyMRFInference< GUM_SCALAR >::_evidenceMass_() {
2024 this->makeInference();
2032 GUM_SCALAR prob_ev = 1;
2033 for (
const auto root: _roots_) {
2035 NodeId node = *(_JT_->clique(root).begin());
2036 Tensor< GUM_SCALAR >* tmp = unnormalizedJointPosterior_(node);
2037 prob_ev *= tmp->sum();
2041 for (
const auto& projected_cpt: _constants_)
2042 prob_ev *= projected_cpt.second;
2047 template < GUM_Numeric GUM_SCALAR >
2048 bool ShaferShenoyMRFInference< GUM_SCALAR >::isExactJointComputable_(
const NodeSet& vars) {
2049 if (JointTargetedMRFInference< GUM_SCALAR >::isExactJointComputable_(vars))
return true;
2051 this->prepareInference();
2053 for (
const auto& node: this->_JT_->nodes()) {
2054 const auto clique = _JT_->clique(node);
2055 if (vars == clique)
return true;
2060 template < GUM_Numeric GUM_SCALAR >
2061 NodeSet ShaferShenoyMRFInference< GUM_SCALAR >::superForJointComputable_(
const NodeSet& vars) {
2062 const auto superset = JointTargetedMRFInference< GUM_SCALAR >::superForJointComputable_(vars);
2063 if (!superset.empty())
return superset;
2065 this->prepareInference();
2067 for (
const auto& node: _JT_->nodes()) {
2068 const auto clique = _JT_->clique(node);
2069 if (vars.isStrictSubsetOf(clique))
return clique;
2077 template < GUM_Numeric GUM_SCALAR >
2078 static Tensor< GUM_SCALAR > SSNewMNmultiTensor(
const Tensor< GUM_SCALAR >& t1,
2079 const Tensor< GUM_SCALAR >& t2) {
2084 template < GUM_Numeric GUM_SCALAR >
2085 static Tensor< GUM_SCALAR > SSNewMNprojTensor(
const Tensor< GUM_SCALAR >& t1,
2087 return t1.sumOut(del_vars);
2090 template < GUM_Numeric GUM_SCALAR >
2091 void ShaferShenoyMRFInference< GUM_SCALAR >::onStateChanged_() {}
Implementation of Shafer-Shenoy's algorithm for inference in Markov random fields.
An algorithm for converting a join tree into a binary join tree.
Exception : a similar element already exists.
<agrum/MRF/inference/evidenceMRFInference.h>
Exception : fatal (unknown ?) error.
Class representing the minimal interface for Markov random field.
Exception : several evidence are incompatible together (proba=0).
<agrum/MRF/inference/jointTargetedMRFInference.h>
void insert(const Key &k)
Inserts a new element into the set.
ShaferShenoyMRFInference(const IMarkovRandomField< GUM_SCALAR > *MN, bool use_binary_join_tree=true)
default constructor
Exception : a looked-for element could not be found.
#define GUM_ERROR(type, msg)
Set< NodeId > NodeSet
Some typdefs and define for shortcuts ...
GUM_SHARED_PUBLIC bool contains(std::string_view s, std::string_view needle)
true if needle in s
Header files of gum::Instantiation.
Selection of the roots of the connected components of a junction tree.
gum is the global namespace for all aGrUM entities
Set< const DiscreteVariable * > VariableSet
NodeSet junctionTreeRoots(const JunctionTree &jt, const GraphicalModel &model, const NodeSet &preferred)
Returns one root for each connected component of a junction tree.
CliqueGraph JoinTree
a join tree is a clique graph satisfying the running intersection property (but some cliques may be i...
CliqueGraph JunctionTree
a junction tree is a clique graph satisfying the running intersection property and such that no cliqu...