aGrUM  0.20.3
a C++ library for (probabilistic) graphical models
samplingInference.h
Go to the documentation of this file.
1 /**
2  *
3  * Copyright (c) 2005-2021 by Pierre-Henri WUILLEMIN(@LIP6) & Christophe GONZALES(@AMU)
4  * info_at_agrum_dot_org
5  *
6  * This library is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU Lesser General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  * GNU Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public License
17  * along with this library. If not, see <http://www.gnu.org/licenses/>.
18  *
19  */
20 
21 
22 /**
23  * @file
24  * @brief This file contains general methods for simulation-oriented approximate
25  * inference.
26  *
27  * @author Paul ALAM & Pierre-Henri WUILLEMIN(@LIP6)
28  */
29 
30 #ifndef GUM_SAMPLING_INFERENCE_H
31 #define GUM_SAMPLING_INFERENCE_H
32 
33 #include <agrum/BN/BayesNetFragment.h>
34 #include <agrum/BN/IBayesNet.h>
35 #include <agrum/BN/inference/tools/estimator.h>
36 #include <agrum/BN/inference/tools/gibbsOperator.h>
37 #include <agrum/BN/inference/tools/marginalTargetedInference.h>
38 #include <agrum/tools/core/approximations/approximationScheme.h>
39 #include <agrum/tools/multidim/instantiation.h>
40 
41 namespace gum {
42  /**
43  * @class SamplingInference samplingInference.h
44  * <agrum/BN/inference/samplingInference.h>
45  * @brief A generic class for making sampling inference in Bayesian networks
46  * adapted
47  *
48  * @ingroup bn_approximation
49  *
50  * The goal of this class is to define the genereal scheme used by all
51  * sampling inference algorithms,
52  * which are implemented as derived classes of ApproximateInference.
53  * This class inherits from MarginalTargetedInference for the handling of
54  * marginal targets
55  * and from ApproximationScheme.
56  */
57 
58  template < typename GUM_SCALAR >
60  public:
61  // ############################################################################
62  /// @name Constructors / Destructors
63  // ############################################################################
64  /// @{
65 
66  /// default constructor
67  /** @warning By default, all the nodes of the Bayes net are targets.
68  * @warning note that, by aGrUM's rule, the BN is not copied but only
69  * referenced by the inference algorithm. */
70 
71  explicit SamplingInference(const IBayesNet< GUM_SCALAR >* bn);
72 
73  /// destructor
75 
76  /// Computes and returns the actual estimation of the posterior of a node.
77  /**
78  * @returns a const ref to the posterior probability of the node.
79  * @param id the node for which we need a posterior probability
80  *
81  * @warning for efficiency reasons, the potential is returned by reference.
82  * In order to ensure that the potential may still exist even if the Inference
83  * object is destroyed, the user has to copy it explicitly.
84  *
85  * @throw UndefinedElement if node is not in the set of targets.
86  * @throw NotFound if node is not in the BN.
87  */
89 
90  /// Computes and returns the actual estimation of the posterior of a node by
91  /// its name.
92  /**
93  * @returns a const ref to the posterior probability of the node referred by
94  * name.
95  * @param name the name of the node for which we need a posterior probability
96  *
97  * @warning for efficiency reasons, the potential is returned by reference.
98  * In order to ensure that the potential may still exist even if the Inference
99  * object is destroyed, the user has to copy it explicitly.
100  *
101  * @throw UndefinedElement if node corresponding to name is not in the set of
102  * targets.
103  * @throw NotFound if node corresponding to name is not in the BN.
104  */
105  const Potential< GUM_SCALAR >& currentPosterior(const std::string& name);
106  /// @}
107  /// @}
108 
109 
110  // ############################################################################
111  /// @name Probability computations
112  // ############################################################################
113  /// @{
114  /// get the BayesNet which is used to really perform the sampling
115  const IBayesNet< GUM_SCALAR >& samplingBN();
116 
117  /// Computes and returns the posterior of a node.
118  /**
119  * @returns a const ref to the posterior probability of the node.
120  * @param id the node for which we need a posterior probability
121  *
122  * @warning for efficiency reasons, the potential is returned by reference.
123  * In order to ensure that the potential may still exist even if the Inference
124  * object is destroyed, the user has to copy it explicitly.
125  *
126  * @throw UndefinedElement if node is not in the set of targets.
127  * @throw NotFound if node is not in the BN.
128  */
129  const Potential< GUM_SCALAR >& posterior_(NodeId id) override;
130 
131  /// @}
132 
133 
134  /// Simplifying the Bayesian network with relevance reasonning to lighten the
135  /// computational charge
136  /**
137  * Sets the reference Bayesian network as a BayesNetFragment after having
138  * eliminated nodes
139  * that are idle for simulation and computation, such as barren or d-separated
140  * nodes.
141  * Eliminates the arcs from evidence nodes to it's children, after setting new
142  * CPT's for them.
143  *
144  */
145  virtual void contextualize();
146 
147  // ############################################################################
148  /// @name Estimator objects initializing
149  // ############################################################################
150  /// @{
151 
152 
153  /// Initializes the estimators object linked to the simulation
154  /**
155  * Initializes the estimator object by creating a hashtable between non
156  * evidence nodes and a 0-filled potential which will approximate the node's
157  * posterior
158  *
159  */
160  virtual void setEstimatorFromBN_();
161 
162  /// Initializes the estimators object linked to the simulation
163  /**
164  * @param lbp a LoopyBeliefPropagation object
165  * @param virtualLBPSize the size of the equivalent sampling by LBP
166  *
167  * Initializes the estimator object by creating a hashtable between
168  * non evidence nodes and the current approximation of the node's posterior
169  * obtained by running LoopyBeliefPropagation algorithm
170  *
171  */
172  virtual void setEstimatorFromLBP_(LoopyBeliefPropagation< GUM_SCALAR >* lbp,
173  GUM_SCALAR virtualLBPSize);
174  ///@}
175 
176  protected:
177  /// Estimator object designed to approximate target posteriors
179 
180  /// whether the Estimator object has been initialized
181  bool isSetEstimator = false;
182 
183  /// whether the referenced Bayesian network has been "contextualized"
184  bool isContextualized = false;
185 
186  /// draws samples without updating the estimators
187  virtual Instantiation burnIn_() = 0;
188 
189  /// draws a sample in the Bayesian network given a previous one
190  /**
191  * @param w the weight of sample being generated
192  * @param prev the previous sample generated
193  *
194  */
196 
197  /// makes the inference by generating samples
198  void makeInference_() override;
199  void loopApproxInference_();
200 
201  /// adds a node to current instantiation
202  /**
203  * @param nod the node to add to the sample
204  * @param I the current sample
205  *
206  * generates random value based on the BN's CPT's and adds the node to the
207  * Instantiation with that value
208  */
209  virtual void addVarSample_(NodeId nod, Instantiation* I);
210 
211 
212  /// fired when Bayesian network is contextualized
213  /**
214  * @param bn the contextualized BayesNetFragment
215  * @param targets inference target variables
216  * @param hardEvNodes hard evidence nodes
217  * @param hardEv hard evidences values
218  *
219  */
220  virtual void onContextualize_(BayesNetFragment< GUM_SCALAR >* bn);
221 
222  void onEvidenceAdded_(const NodeId id, bool isHardEvidence) override;
223 
224  void onEvidenceErased_(const NodeId id, bool isHardEvidence) override;
225 
226  void onAllEvidenceErased_(bool contains_hard_evidence) override;
227 
228  void onEvidenceChanged_(const NodeId id, bool hasChangedSoftHard) override;
229 
230  void onModelChanged_(const GraphicalModel* bn) override;
231 
233 
235 
236  void onMarginalTargetAdded_(const NodeId id) override;
237 
238  void onMarginalTargetErased_(const NodeId id) override;
239 
241 
243 
244  void onStateChanged_() override;
245 
246  private:
248  };
249 
250 
251 #ifndef GUM_NO_EXTERN_TEMPLATE_CLASS
252  extern template class SamplingInference< double >;
253 #endif
254 
255 } // namespace gum
256 
257 #include <agrum/BN/inference/tools/samplingInference_tpl.h>
258 #endif
virtual void contextualize()
Simplifying the Bayesian network with relevance reasonning to lighten the computational charge...
virtual Instantiation draw_(GUM_SCALAR *w, Instantiation prev)=0
draws a sample in the Bayesian network given a previous one
SamplingInference(const IBayesNet< GUM_SCALAR > *bn)
default constructor
void onMarginalTargetErased_(const NodeId id) override
fired before a marginal target is removed
INLINE void emplace(Args &&... args)
Definition: set_tpl.h:643
void onStateChanged_() override
fired when the stage is changed
const Potential< GUM_SCALAR > & posterior_(NodeId id) override
Computes and returns the posterior of a node.
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
~SamplingInference() override
destructor
void onAllMarginalTargetsErased_() override
fired before a all marginal targets are removed
void onAllEvidenceErased_(bool contains_hard_evidence) override
fired before all the evidence are erased
BayesNetFragment< GUM_SCALAR > * _samplingBN_
<agrum/BN/inference/samplingInference.h>
Estimator< GUM_SCALAR > _estimator_
Estimator object designed to approximate target posteriors.
void onEvidenceAdded_(const NodeId id, bool isHardEvidence) override
fired after a new evidence is inserted
const Potential< GUM_SCALAR > & currentPosterior(NodeId id)
Computes and returns the actual estimation of the posterior of a node.
void onEvidenceErased_(const NodeId id, bool isHardEvidence) override
fired before an evidence is removed
void onMarginalTargetAdded_(const NodeId id) override
fired after a new marginal target is inserted
virtual void setEstimatorFromLBP_(LoopyBeliefPropagation< GUM_SCALAR > *lbp, GUM_SCALAR virtualLBPSize)
Initializes the estimators object linked to the simulation.
void updateOutdatedPotentials_() override
prepares inference when the latter is in OutdatedPotentials state
virtual Instantiation burnIn_()=0
draws samples without updating the estimators
bool isContextualized
whether the referenced Bayesian network has been "contextualized"
virtual void addVarSample_(NodeId nod, Instantiation *I)
adds a node to current instantiation
bool isSetEstimator
whether the Estimator object has been initialized
const Potential< GUM_SCALAR > & currentPosterior(const std::string &name)
Computes and returns the actual estimation of the posterior of a node by its name.
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
void onEvidenceChanged_(const NodeId id, bool hasChangedSoftHard) override
fired after an evidence is changed, in particular when its status (soft/hard) changes ...
void updateOutdatedStructure_() override
prepares inference when the latter is in OutdatedStructure state
virtual void setEstimatorFromBN_()
Initializes the estimators object linked to the simulation.
void onAllMarginalTargetsAdded_() override
fired after all the nodes of the BN are added as marginal targets