aGrUM  0.20.3
a C++ library for (probabilistic) graphical models
inferenceEngine.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 #ifndef __INFERENCE_ENGINE__H__
23 #define __INFERENCE_ENGINE__H__
24 
25 /**
26  * @file
27  * @brief Abstract class representing CredalNet inference engines
28  * @author Matthieu HOURBRACQ and Pierre-Henri WUILLEMIN(@LIP6)
29  */
30 #include <map>
31 
32 #include <agrum/CN/polytope/LrsWrapper.h>
33 #include <agrum/CN/tools/varMod2BNsMap.h>
34 #include <agrum/tools/core/approximations/approximationScheme.h>
35 #include <agrum/tools/core/exceptions.h>
36 #include <agrum/tools/core/math/pow.h>
37 #include <agrum/tools/core/math/rational.h>
38 
39 namespace gum {
40  namespace credal {
41 
42  /**
43  * @class InferenceEngine
44  * @headerfile inferenceEngine.h <agrum/CN/inferenceEngine.h>
45  * @brief Abstract class template representing a CredalNet inference engine.
46  * Used
47  * by credal network inference algorithms such as CNLoopyPropagation (inner
48  * multi-threading) or CNMonteCarloSampling (outer multi-threading).
49  * @ingroup cn_group
50  * @tparam GUM_SCALAR A floating type ( float, double, long double ... ).
51  * @author Matthieu HOURBRACQ and Pierre-Henri WUILLEMIN(@LIP6)
52  */
53  template < typename GUM_SCALAR >
55  private:
56  //@beforeMerging swapping from typedef to using
60 
61  using dynExpe = typename gum::HashTable< std::string, std::vector< GUM_SCALAR > >;
62 
63  using query = NodeProperty< std::vector< bool > >;
65 
66  protected:
67  /** @brief A pointer to the Credal Net used. */
69 
70  /** @brief Old lower marginals used to compute epsilon. */
72  /** @brief Old upper marginals used to compute epsilon. */
74 
75  /** @brief Lower marginals. */
77  /** @brief Upper marginals. */
79 
80  /** @brief Credal sets vertices, if enabled */
82 
83  /** @brief Lower expectations, if some variables modalities were inserted.
84  */
86  /** @brief Upper expectations, if some variables modalities were inserted.
87  */
89 
90  /** @brief Lower dynamic expectations. If the network is not dynamic it's
91  * content is the same as expectationMin_. */
93  /** @brief Upper dynamic expectations. If the network if not dynamic it's
94  * content is the same as expectationMax_. */
96 
97  /** @brief Variables modalities used to compute expectations. */
99 
100  /** @brief Holds observed variables states. */
102  /** @brief Holds the query nodes states. */
104 
105  /** @brief Clusters of nodes used with dynamic networks. Any node key in
106  * t0_ is
107  * present at \f$ t=0 \f$ and any node belonging to the node set of this
108  * key
109  * share the same CPT than the key. Used for sampling with repetitive
110  * independence. */
112  /** @brief Clusters of nodes used with dynamic networks. Any node key in
113  * t1_ is
114  * present at \f$ t=1 \f$ and any node belonging to the node set of this
115  * key
116  * share the same CPT than the key. Used for sampling with repetitive
117  * independence. */
119 
120  /** @brief \c True if credal sets vertices are stored, \c False otherwise.
121  * \c
122  * False by default. */
124  /** @brief \c True if using repetitive independence ( dynamic network only
125  * ),
126  * \c False otherwise. \c False by default. */
128  /** @brief Iterations limit stopping rule used by some algorithms such as
129  * CNMonteCarloSampling. The algorithms stops if no changes occured within
130  * 1000
131  * iterations by default. */
132  /// int iterStop_;
133  /** @brief \c True is optimal bayes net are stored, for each variable and
134  * each
135  * modality, \c False otherwise. Not all algorithms offers this option. \c
136  * False by default. */
138  /** @brief Object used to efficiently store optimal bayes net during
139  * inference,
140  * for some algorithms. */
142 
143  /**
144  * @deprecated
145  * @brief The number of time steps of this network (only usefull for
146  * dynamic
147  * networks). */
149 
150  /// @name Protected initialization methods
151  /// @{
152  /**
153  * Initialize t0_ and t1_ clusters.
154  */
155  void repetitiveInit_();
156 
157  /**
158  * Initialize lower and upper expectations before inference, with the
159  * lower
160  * expectation being initialized on the highest modality and the upper
161  * expectation being initialized on the lowest modality.
162  */
163  void initExpectations_();
164 
165  /**
166  * Initialize lower and upper old marginals and marginals before
167  * inference,
168  * with the lower marginal being 1 and the upper 0.
169  */
170  void initMarginals_();
171 
172  /**
173  * Initialize credal set vertices with empty sets.
174  */
175  void initMarginalSets_();
176 
177  /// @}
178 
179  /// @name Protected algorithms methods
180  /// @{
181  /**
182  * Compute approximation scheme epsilon using the old marginals and the
183  *new
184  *ones. Highest delta on either lower or upper marginal is epsilon.
185  *
186  * Also updates oldMarginals to current marginals.
187  *
188  * @return Epsilon.
189  */
190  inline const GUM_SCALAR computeEpsilon_();
191 
192  /**
193  * Given a node id and one of it's possible vertex obtained during
194  *inference,
195  *update this node lower and upper expectations.
196  *
197  * @param id The id of the node to be updated
198  * @param vertex A (potential) vertex of the node credal set
199  */
200  inline void updateExpectations_(const NodeId& id, const std::vector< GUM_SCALAR >& vertex);
201 
202  /**
203  * Given a node id and one of it's possible vertex, update it's credal
204  *set.
205  * To maximise efficiency, don't pass a vertex we know is inside the
206  *polytope
207  *(i.e. not at an extreme value for any modality)
208  *
209  * @param id The id of the node to be updated
210  * @param vertex A (potential) vertex of the node credal set
211  * @param elimRedund remove redundant vertex (inside a facet)
212  */
213  inline void updateCredalSets_(const NodeId& id,
214  const std::vector< GUM_SCALAR >& vertex,
215  const bool& elimRedund = false);
216 
217  /// @}
218 
219  /// @name Proptected post-inference methods
220  /// @{
221  /**
222  * Rearrange lower and upper expectations to suit dynamic networks.
223  */
224  void dynamicExpectations_();
225  /// @}
226 
227  public:
228  /// @name Constructors / Destructors
229  /// @{
230 
231  // InferenceEngine ();
232  /**
233  * Construtor.
234  *
235  * @param credalNet The credal net to be used with this inference engine.
236  */
237  explicit InferenceEngine(const CredalNet< GUM_SCALAR >& credalNet);
238  /**
239  * Destructor.
240  */
241  virtual ~InferenceEngine();
242 
243  /// @}
244 
245  /// @name Pure virtual methods
246  /// @{
247  /** To be redefined by each credal net algorithm. Starts the inference. */
248  virtual void makeInference() = 0;
249  /// @}
250 
251  /// @name Getters and setters
252  /// @{
253  /**
254  * Get optimum IBayesNet.
255  * @return A pointer to the optimal net object.
256  */
258 
259  /**
260  * Get this creadal network.
261  * @return A constant reference to this CredalNet.
262  */
263  const CredalNet< GUM_SCALAR >& credalNet() const;
264 
265  /**
266  * Get the t0_ cluster.
267  * @return A constant reference to the t0_ cluster.
268  */
269  const NodeProperty< std::vector< NodeId > >& getT0Cluster() const;
270 
271  /**
272  * Get the t1_ cluster.
273  * @return A constant reference to the t1_ cluster.
274  */
275  const NodeProperty< std::vector< NodeId > >& getT1Cluster() const;
276 
277  /**
278  * @param repetitive \c True if repetitive independence is to be used,
279  * false
280  * otherwise. Only usefull with dynamic networks.
281  */
282  void setRepetitiveInd(const bool repetitive);
283 
284  /**
285  * @param value \c True if vertices are to be stored, false otherwise.
286  */
287  void storeVertices(const bool value);
288  /**
289  * @param value \c True if optimal Bayesian networks are to be stored for
290  * each
291  * variable and each modality.
292  */
293  void storeBNOpt(const bool value);
294 
295  /**
296  * Get the current independence status.
297  * @return \c True if repetitive, \c False otherwise.
298  */
299  bool repetitiveInd() const;
300  /**
301  * Get the number of iterations without changes used to stop some
302  * algorithms.
303  * @return the number of iterations.
304  */
305  /// int iterStop () const;
306  /**
307  * @return \c True if vertice are stored, \c False otherwise.
308  */
309  bool storeVertices() const;
310  /**
311  * @return \c True if optimal bayes net are stored for each variable and
312  * each
313  * modality, \c False otherwise.
314  */
315  bool storeBNOpt() const;
316  /// @}
317 
318  /// @name Pre-inference initialization methods
319  /// @{
320  /**
321  * Insert variables modalities from file to compute expectations.
322  * @param path The path to the modalities file.
323  */
324  void insertModalsFile(const std::string& path);
325 
326  /**
327  * Insert variables modalities from map to compute expectations.
328  * @param modals The map variable name - modalities.
329  */
330  void insertModals(const std::map< std::string, std::vector< GUM_SCALAR > >& modals);
331 
332  /**
333  * Insert evidence from file.
334  * @param path The path to the evidence file.
335  */
336  virtual void insertEvidenceFile(const std::string& path);
337 
338  /**
339  * Insert evidence from map.
340  * @param eviMap The map variable name - likelihood.
341  */
342  void insertEvidence(const std::map< std::string, std::vector< GUM_SCALAR > >& eviMap);
343 
344  /**
345  * Insert evidence from Property.
346  * @param evidence The on nodes Property containing likelihoods.
347  */
349 
350  /**
351  * Insert query variables states from file.
352  * @param path The path to the query file.
353  */
354  void insertQueryFile(const std::string& path);
355 
356  /**
357  * Insert query variables and states from Property.
358  * @param query The on nodes Property containing queried variables states.
359  */
360  void insertQuery(const NodeProperty< std::vector< bool > >& query);
361 
362  /// @}
363 
364  /// @name Post-inference methods
365  /// @{
366  /**
367  * Erase all inference related data to perform another one. You need to
368  * insert
369  * evidence again if needed but modalities are kept. You can insert new
370  * ones by
371  * using the appropriate method which will delete the old ones.
372  */
373  virtual void eraseAllEvidence();
374 
375  /**
376  * Get the lower marginals of a given node id.
377  * @param id The node id which lower marginals we want.
378  * @return A constant reference to this node lower marginals.
379  */
380  Potential< GUM_SCALAR > marginalMin(const NodeId id) const;
381 
382  /**
383  * Get the upper marginals of a given node id.
384  * @param id The node id which upper marginals we want.
385  * @return A constant reference to this node upper marginals.
386  */
387  Potential< GUM_SCALAR > marginalMax(const NodeId id) const;
388 
389  /**
390  * Get the lower marginals of a given variable name.
391  * @param varName The variable name which lower marginals we want.
392  * @return A constant reference to this variable lower marginals.
393  */
394  Potential< GUM_SCALAR > marginalMin(const std::string& varName) const;
395 
396  /**
397  * Get the upper marginals of a given variable name.
398  * @param varName The variable name which upper marginals we want.
399  * @return A constant reference to this variable upper marginals.
400  */
401  Potential< GUM_SCALAR > marginalMax(const std::string& varName) const;
402 
403  /**
404  * Get the lower expectation of a given node id.
405  * @param id The node id which lower expectation we want.
406  * @return A constant reference to this node lower expectation.
407  */
408  const GUM_SCALAR& expectationMin(const NodeId id) const;
409 
410  /**
411  * Get the upper expectation of a given node id.
412  * @param id The node id which upper expectation we want.
413  * @return A constant reference to this node upper expectation.
414  */
415  const GUM_SCALAR& expectationMax(const NodeId id) const;
416 
417  /**
418  * Get the lower expectation of a given variable name.
419  * @param varName The variable name which lower expectation we want.
420  * @return A constant reference to this variable lower expectation.
421  */
422  const GUM_SCALAR& expectationMin(const std::string& varName) const;
423 
424  /**
425  * Get the upper expectation of a given variable name.
426  * @param varName The variable name which upper expectation we want.
427  * @return A constant reference to this variable upper expectation.
428  */
429  const GUM_SCALAR& expectationMax(const std::string& varName) const;
430 
431  /**
432  * Get the lower dynamic expectation of a given variable prefix (without
433  * the
434  * time step included, i.e. call with "temp" to get "temp_0", ...,
435  * "temp_T").
436  * @param varName The variable name prefix which lower expectation we
437  * want.
438  * @return A constant reference to the variable lower expectation over all
439  * time
440  * steps.
441  */
442  const std::vector< GUM_SCALAR >& dynamicExpMin(const std::string& varName) const;
443 
444  /**
445  * Get the upper dynamic expectation of a given variable prefix (without
446  * the
447  * time step included, i.e. call with "temp" to get "temp_0", ...,
448  * "temp_T").
449  * @param varName The variable name prefix which upper expectation we
450  * want.
451  * @return A constant reference to the variable upper expectation over all
452  * time
453  * steps.
454  */
455  const std::vector< GUM_SCALAR >& dynamicExpMax(const std::string& varName) const;
456 
457  /**
458  * Get the vertice of a given node id.
459  * @param id The node id which vertice we want.
460  * @return A constant reference to this node vertice.
461  */
462  const std::vector< std::vector< GUM_SCALAR > >& vertices(const NodeId id) const;
463 
464  /**
465  * Saves marginals to file.
466  * @param path The path to the file to be used.
467  */
468  void saveMarginals(const std::string& path) const;
469 
470  /**
471  * Saves expectations to file.
472  * @param path The path to the file to be used.
473  */
474  void saveExpectations(const std::string& path) const;
475 
476  /**
477  * Saves vertices to file.
478  * @param path The path to the file to be used.
479  */
480  void saveVertices(const std::string& path) const;
481 
482  /**
483  * Compute dynamic expectations.
484  * @see dynamicExpectations_
485  * Only call this if an algorithm does not call it by itself.
486  */
487  void dynamicExpectations(); // if someone forgets the protected call at
488  // the end
489  // of its own algorithm, the user can call it
490 
491  /**
492  * Print all nodes marginals to standart output.
493  */
494  std::string toString() const;
495 
496  /**
497  * Get approximation scheme state.
498  * @return A constant string about approximation scheme state.
499  */
500  const std::string getApproximationSchemeMsg() { return this->messageApproximationScheme(); }
501 
502  /// @}
503  };
504 
505 
506 #ifndef GUM_NO_EXTERN_TEMPLATE_CLASS
507  extern template class InferenceEngine< double >;
508 #endif
509  } // namespace credal
510 } // namespace gum
511 
512 #include <agrum/CN/inference/inferenceEngine_tpl.h>
513 
514 #endif
Potential< GUM_SCALAR > marginalMax(const NodeId id) const
Get the upper marginals of a given node id.
virtual ~InferenceEngine()
Destructor.
Potential< GUM_SCALAR > marginalMax(const std::string &varName) const
Get the upper marginals of a given variable name.
const GUM_SCALAR & expectationMax(const NodeId id) const
Get the upper expectation of a given node id.
void initExpectations_()
Initialize lower and upper expectations before inference, with the lower expectation being initialize...
void insertModals(const std::map< std::string, std::vector< GUM_SCALAR > > &modals)
Insert variables modalities from map to compute expectations.
margi oldMarginalMin_
Old lower marginals used to compute epsilon.
dynExpe dynamicExpMin_
Lower dynamic expectations.
void insertEvidence(const NodeProperty< std::vector< GUM_SCALAR > > &evidence)
Insert evidence from Property.
Potential< GUM_SCALAR > marginalMin(const std::string &varName) const
Get the lower marginals of a given variable name.
void updateCredalSets_(const NodeId &id, const std::vector< GUM_SCALAR > &vertex, const bool &elimRedund=false)
Given a node id and one of it&#39;s possible vertex, update it&#39;s credal set.
void insertModalsFile(const std::string &path)
Insert variables modalities from file to compute expectations.
INLINE void emplace(Args &&... args)
Definition: set_tpl.h:643
const GUM_SCALAR computeEpsilon_()
Compute approximation scheme epsilon using the old marginals and the new ones.
bool repetitiveInd_
True if using repetitive independence ( dynamic network only ), False otherwise.
bool repetitiveInd() const
Get the current independence status.
bool storeBNOpt_
Iterations limit stopping rule used by some algorithms such as CNMonteCarloSampling.
const std::string getApproximationSchemeMsg()
Get approximation scheme state.
virtual void insertEvidenceFile(const std::string &path)
Insert evidence from file.
void insertQueryFile(const std::string &path)
Insert query variables states from file.
const CredalNet< GUM_SCALAR > * credalNet_
A pointer to the Credal Net used.
bool storeVertices_
True if credal sets vertices are stored, False otherwise.
cluster t1_
Clusters of nodes used with dynamic networks.
bool storeVertices() const
Get the number of iterations without changes used to stop some algorithms.
cluster t0_
Clusters of nodes used with dynamic networks.
void initMarginalSets_()
Initialize credal set vertices with empty sets.
margi oldMarginalMax_
Old upper marginals used to compute epsilon.
const std::vector< std::vector< GUM_SCALAR > > & vertices(const NodeId id) const
Get the vertice of a given node id.
credalSet marginalSets_
Credal sets vertices, if enabled.
VarMod2BNsMap< GUM_SCALAR > * getVarMod2BNsMap()
Get optimum IBayesNet.
const std::vector< GUM_SCALAR > & dynamicExpMax(const std::string &varName) const
Get the upper dynamic expectation of a given variable prefix (without the time step included...
void dynamicExpectations()
Compute dynamic expectations.
void saveVertices(const std::string &path) const
Saves vertices to file.
void saveMarginals(const std::string &path) const
Saves marginals to file.
void storeVertices(const bool value)
void updateExpectations_(const NodeId &id, const std::vector< GUM_SCALAR > &vertex)
Given a node id and one of it&#39;s possible vertex obtained during inference, update this node lower and...
InferenceEngine(const CredalNet< GUM_SCALAR > &credalNet)
Construtor.
dynExpe modal_
Variables modalities used to compute expectations.
std::string toString() const
Print all nodes marginals to standart output.
const CredalNet< GUM_SCALAR > & credalNet() const
Get this creadal network.
margi evidence_
Holds observed variables states.
Potential< GUM_SCALAR > marginalMin(const NodeId id) const
Get the lower marginals of a given node id.
virtual void makeInference()=0
To be redefined by each credal net algorithm.
void initMarginals_()
Initialize lower and upper old marginals and marginals before inference, with the lower marginal bein...
query query_
Holds the query nodes states.
void repetitiveInit_()
Initialize t0_ and t1_ clusters.
dynExpe dynamicExpMax_
Upper dynamic expectations.
VarMod2BNsMap< GUM_SCALAR > dbnOpt_
Object used to efficiently store optimal bayes net during inference, for some algorithms.
void insertQuery(const NodeProperty< std::vector< bool > > &query)
Insert query variables and states from Property.
expe expectationMax_
Upper expectations, if some variables modalities were inserted.
void storeBNOpt(const bool value)
const GUM_SCALAR & expectationMin(const std::string &varName) const
Get the lower expectation of a given variable name.
void dynamicExpectations_()
Rearrange lower and upper expectations to suit dynamic networks.
expe expectationMin_
Lower expectations, if some variables modalities were inserted.
int timeSteps_
The number of time steps of this network (only usefull for dynamic networks).
void setRepetitiveInd(const bool repetitive)
const GUM_SCALAR & expectationMin(const NodeId id) const
Get the lower expectation of a given node id.
margi marginalMax_
Upper marginals.
void saveExpectations(const std::string &path) const
Saves expectations to file.
margi marginalMin_
Lower marginals.
virtual void eraseAllEvidence()
Erase all inference related data to perform another one.
const GUM_SCALAR & expectationMax(const std::string &varName) const
Get the upper expectation of a given variable name.
const std::vector< GUM_SCALAR > & dynamicExpMin(const std::string &varName) const
Get the lower dynamic expectation of a given variable prefix (without the time step included...
namespace for all credal networks entities
Definition: LpInterface.cpp:37