aGrUM 3.3.2
a C++ library for (probabilistic) graphical models
samplingInference_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
56
57namespace gum {
58
59 template < GUM_Numeric GUM_SCALAR >
61 ApproximateInference< GUM_SCALAR >(bn), _estimator_(), _samplingBN_(nullptr) {
62 // epsilon, minimal epsilon rate, maximum number of iterations, period size, verbosity and
63 // timeout
64 this->setFromConfiguration_("sampling", true);
65 GUM_CONSTRUCTOR(SamplingInference);
66 }
67
68 template < GUM_Numeric GUM_SCALAR >
70 GUM_DESTRUCTOR(SamplingInference);
71 if (_samplingBN_ != nullptr) {
72 if (isContextualized) { // otherwise _samplingBN_==&BN()
73 delete _samplingBN_;
74 }
75 }
76 }
77
78 template < GUM_Numeric GUM_SCALAR >
80 this->prepareInference();
81 if (_samplingBN_ == nullptr) return this->BN();
82 else return *_samplingBN_;
83 }
84
85 template < GUM_Numeric GUM_SCALAR >
90
91 template < GUM_Numeric GUM_SCALAR >
94 GUM_SCALAR virtualLBPSize) {
95 _estimator_.setFromLBP(lbp, this->hardEvidenceNodes(), virtualLBPSize);
96 this->isSetEstimator = true;
97 }
98
99 template < GUM_Numeric GUM_SCALAR >
101 return _estimator_.posterior(this->BN().variable(id));
102 }
103
104 template < GUM_Numeric GUM_SCALAR >
105 const Tensor< GUM_SCALAR >&
107 return currentPosterior(this->BN().idFromName(name));
108 }
109
110 template < GUM_Numeric GUM_SCALAR >
111 const Tensor< GUM_SCALAR >& SamplingInference< GUM_SCALAR >::posterior_(NodeId id) {
112 return _estimator_.posterior(this->BN().variable(id));
113 }
114
115 template < GUM_Numeric GUM_SCALAR >
117 // Finding Barren nodes
118
119 BarrenNodesFinder barr_nodes = BarrenNodesFinder(&this->BN().internalDag());
120 barr_nodes.setTargets(&this->targets());
121 barr_nodes.setEvidence(&this->hardEvidenceNodes());
122 const NodeSet& barren = barr_nodes.barrenNodes();
123
124 // creating BN fragment
126 for (const auto elmt: this->BN().internalDag().asNodeSet() - barren)
127 _samplingBN_->installNode(elmt);
128
129 // D-separated nodes
130
132 NodeSet requisite;
133 dsep.requisiteNodes(this->BN().internalDag(),
134 this->BN().nodes().asNodeSet(), // no target for approximateInference
135 this->hardEvidenceNodes(),
136 this->softEvidenceNodes(), // should be empty
137 requisite);
138 requisite += this->hardEvidenceNodes();
139
140 auto nonRequisite = this->BN().internalDag().asNodeSet() - requisite;
141
142 for (const auto elmt: nonRequisite)
143 _samplingBN_->uninstallNode(elmt);
144 for (const auto hard: this->hardEvidenceNodes()) {
146 I.add(this->BN().variable(hard));
147 I.chgVal(this->BN().variable(hard), this->hardEvidence()[hard]);
148
149 for (const auto& child: this->BN().children(hard)) {
150 _samplingBN_->installCPT(child, this->BN().cpt(child).extract(I));
151 }
152 }
153
154 this->isContextualized = true;
156 }
157
158 template < GUM_Numeric GUM_SCALAR >
163
164 template < GUM_Numeric GUM_SCALAR >
166 //@todo This should be in _prepareInference_
167 if (!isContextualized) { this->contextualize(); }
168
171 GUM_SCALAR w = .0; //
172
173 // The estimator may start from a prior counted as virtual samples (e.g. LBP posteriors). As
174 // long as the prior outweighs the samples, the estimation hardly moves: the convergence
175 // criteria (epsilon and rate) would stop the sampling and return the prior. They are suspended
176 // until the samples outnumber the virtual ones (the limits on time and iterations still apply).
177 struct CriteriaSuspension {
179 const bool epsilon;
180 const bool rate;
181 bool suspended = false;
182
183 void suspend() {
184 inference->disableEpsilon();
185 inference->disableMinEpsilonRate();
186 suspended = true;
187 }
188
189 void restore() {
190 if (!suspended) return;
191 if (epsilon) inference->enableEpsilon();
192 if (rate) inference->enableMinEpsilonRate();
193 suspended = false;
194 }
195
196 ~CriteriaSuspension() { restore(); }
197 } criteria{this, this->isEnabledEpsilon(), this->isEnabledMinEpsilonRate()};
198
199 if (!_estimator_.isPriorOutweighed()) criteria.suspend();
200
201 // Burn in
202 Ip = this->burnIn_();
203 do {
204 Ip = this->draw_(&w, Ip);
205 _estimator_.update(Ip, w);
207 if (criteria.suspended && _estimator_.isPriorOutweighed()) criteria.restore();
208 } while (this->continueApproximationScheme(_estimator_.confidence()));
209
210 this->isSetEstimator = false;
211 }
212
213 template < GUM_Numeric GUM_SCALAR >
216
217 I->add(samplingBN().variable(nod));
218 I->chgVal(samplingBN().variable(nod), samplingBN().cpt(nod).extract(Itop).draw());
219 }
220
221 template < GUM_Numeric GUM_SCALAR >
223
224 template < GUM_Numeric GUM_SCALAR >
225 void SamplingInference< GUM_SCALAR >::onEvidenceAdded_(const NodeId id, bool isHardEvidence) {
226 if (!isHardEvidence) {
227 GUM_ERROR(FatalError, "Approximated inference only accept hard evidence")
228 }
229 }
230
231 template < GUM_Numeric GUM_SCALAR >
232 void SamplingInference< GUM_SCALAR >::onEvidenceErased_(const NodeId id, bool isHardEvidence) {}
233
234 template < GUM_Numeric GUM_SCALAR >
235 void SamplingInference< GUM_SCALAR >::onAllEvidenceErased_(bool contains_hard_evidence) {}
236
237 template < GUM_Numeric GUM_SCALAR >
239 bool hasChangedSoftHard) {
240 if (hasChangedSoftHard) {
241 GUM_ERROR(FatalError, "Approximated inference only accept hard evidence")
242 }
243 }
244
245 template < GUM_Numeric GUM_SCALAR >
247
248 template < GUM_Numeric GUM_SCALAR >
250
251 template < GUM_Numeric GUM_SCALAR >
253
254 template < GUM_Numeric GUM_SCALAR >
256
257 template < GUM_Numeric GUM_SCALAR >
259
260 template < GUM_Numeric GUM_SCALAR >
262
263 template < GUM_Numeric GUM_SCALAR >
265
266 template < GUM_Numeric GUM_SCALAR >
268 if (this->isInferenceReady()) {
269 _estimator_.clear();
271 }
272 }
273} // namespace gum
Class representing Fragment of Bayesian networks.
Detect barren nodes for inference in Bayesian networks.
ApproximateInference(const IBayesNet< GUM_SCALAR > *bn)
void updateApproximationScheme(unsigned int incr=1)
Update the scheme w.r.t the new error and increment steps.
bool isEnabledEpsilon() const override
Returns true if stopping criterion on epsilon is enabled, false otherwise.
void disableEpsilon() override
Disable stopping criterion on epsilon.
void setFromConfiguration_(const std::string &section, bool withMaxTime, bool withVerbosity=true)
Set the parameters of the scheme from a section of gum::Configuration.
double epsilon() const override
Returns the value of epsilon.
void enableEpsilon() override
Enable stopping criterion on epsilon.
bool isEnabledMinEpsilonRate() const override
Returns true if stopping criterion on epsilon rate is enabled, false otherwise.
void disableMinEpsilonRate() override
Disable stopping criterion on epsilon rate.
bool continueApproximationScheme(double error)
Update the scheme w.r.t the new error.
void initApproximationScheme()
Initialise the scheme.
void enableMinEpsilonRate() override
Enable stopping criterion on epsilon rate.
Detect barren nodes for inference in Bayesian networks.
void setEvidence(const NodeSet *observed_nodes)
sets the observed nodes in the DAG
void setTargets(const NodeSet *target_nodes)
sets the set of target nodes we are interested in
NodeSet barrenNodes()
returns the set of barren nodes
BarrenNodesFinder(const DAG *dag)
default constructor
Portion of a BN identified by the list of nodes and a BayesNet.
virtual const IBayesNet< GUM_SCALAR > & BN() const final
Returns a constant reference over the IBayesNet referenced by this class.
Exception : fatal (unknown ?) error.
virtual void prepareInference() final
prepare the internal inference structures for the next inference
const NodeSet & softEvidenceNodes() const
returns the set of nodes with soft evidence
virtual bool isInferenceReady() const noexcept final
returns whether the inference object is in a ready state
const NodeProperty< Idx > & hardEvidence() const
indicate for each node with hard evidence which value it took
const NodeSet & hardEvidenceNodes() const
returns the set of nodes with hard evidence
Virtual base class for probabilistic graphical models.
Class representing the minimal interface for Bayesian network with no numerical data.
Definition IBayesNet.h:79
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.
void add(const DiscreteVariable &v) final
Adds a new variable in the Instantiation.
<agrum/BN/inference/loopyBeliefPropagation.h>
virtual const NodeSet & targets() const noexcept final
returns the list of marginal targets
void onEvidenceAdded_(const NodeId id, bool isHardEvidence) override
fired after a new evidence is inserted
const Tensor< GUM_SCALAR > & posterior_(NodeId id) override
Computes and returns the posterior of a node.
const Tensor< GUM_SCALAR > & currentPosterior(NodeId id)
Computes and returns the actual estimation of the posterior of a node.
bool isContextualized
whether the referenced Bayesian network has been "contextualized"
void onEvidenceChanged_(const NodeId id, bool hasChangedSoftHard) override
fired after an evidence is changed, in particular when its status (soft/hard) changes
void onAllMarginalTargetsErased_() override
fired before a all marginal targets are removed
void onEvidenceErased_(const NodeId id, bool isHardEvidence) override
fired before an evidence is removed
void onStateChanged_() override
fired when the stage is changed
void onMarginalTargetAdded_(const NodeId id) override
fired after a new marginal target is inserted
virtual void addVarSample_(NodeId nod, Instantiation *I)
adds a node to current instantiation
SamplingInference(const IBayesNet< GUM_SCALAR > *bn)
default constructor
void onAllEvidenceErased_(bool contains_hard_evidence) override
fired before all the evidence are erased
void updateOutdatedStructure_() override
prepares inference when the latter is in OutdatedStructure state
virtual void setEstimatorFromLBP_(LoopyBeliefPropagation< GUM_SCALAR > *lbp, GUM_SCALAR virtualLBPSize)
Initializes the estimators object linked to the simulation.
virtual void contextualize()
Simplifying the Bayesian network with relevance reasonning to lighten the computational charge.
void onAllMarginalTargetsAdded_() override
fired after all the nodes of the BN are added as marginal targets
virtual Instantiation draw_(GUM_SCALAR *w, Instantiation prev)=0
draws a sample in the Bayesian network given a previous one
virtual void setEstimatorFromBN_()
Initializes the estimators object linked to the simulation.
virtual Instantiation burnIn_()=0
draws samples without updating the estimators
Estimator< GUM_SCALAR > _estimator_
Estimator object designed to approximate target posteriors.
void updateOutdatedTensors_() override
prepares inference when the latter is in OutdatedTensors state
const IBayesNet< GUM_SCALAR > & samplingBN()
get the BayesNet which is used to really perform the sampling
virtual void onContextualize_(BayesNetFragment< GUM_SCALAR > *bn)
fired when Bayesian network is contextualized
~SamplingInference() override
destructor
void onMarginalTargetErased_(const NodeId id) override
fired before a marginal target is removed
void makeInference_() override
makes the inference by generating samples
void onModelChanged_(const GraphicalModel *bn) override
fired after a new Bayes net has been assigned to the engine
bool isSetEstimator
whether the Estimator object has been initialized
BayesNetFragment< GUM_SCALAR > * _samplingBN_
the d-separation algorithm as described in Koller & Friedman (2009)
void requisiteNodes(const DAG &dag, const NodeSet &query, const NodeSet &hardEvidence, const NodeSet &softEvidence, NodeSet &requisite) const
Fill the 'requisite' nodeset with the requisite nodes in dag given a query and evidence.
d-separation analysis (as described in Koller & Friedman 2009)
#define GUM_ERROR(type, msg)
Definition exceptions.h:76
Size NodeId
Type for node ids.
Set< NodeId > NodeSet
Some typdefs and define for shortcuts ...
gum is the global namespace for all aGrUM entities
Definition agrum.h:46
This file contains general methods for simulation-oriented approximate inference.