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