aGrUM 3.1.1
a C++ library for (probabilistic) graphical models
gum::credal::MultipleInferenceEngine< GUM_SCALAR, BNInferenceEngine > Class Template Referenceabstract

Class template representing a CredalNet inference engine using one or more IBayesNet inference engines such as LazyPropagation. More...

#include <multipleInferenceEngine.h>

Inheritance diagram for gum::credal::MultipleInferenceEngine< GUM_SCALAR, BNInferenceEngine >:
Collaboration diagram for gum::credal::MultipleInferenceEngine< GUM_SCALAR, BNInferenceEngine >:

Public Types

enum class  ApproximationSchemeSTATE : char {
  Undefined , Continue , Epsilon , Rate ,
  Limit , TimeLimit , Stopped
}
 The different state of an approximation scheme. More...

Public Member Functions

virtual void addEvidence (NodeId id, const Idx val) final
 adds a new hard evidence on node id
virtual void addEvidence (std::string_view nodeName, const Idx val) final
 adds a new hard evidence on node named nodeName
virtual void addEvidence (NodeId id, std::string_view label) final
 adds a new hard evidence on node id
virtual void addEvidence (std::string_view nodeName, std::string_view label) final
 adds a new hard evidence on node named nodeName
virtual void addEvidence (NodeId id, const std::vector< GUM_SCALAR > &vals) final
 adds a new evidence on node id (might be soft or hard)
virtual void addEvidence (std::string_view nodeName, const std::vector< GUM_SCALAR > &vals) final
 adds a new evidence on node named nodeName (might be soft or hard)
virtual void addEvidence (const Tensor< GUM_SCALAR > &pot) final
 adds a new evidence on node id (might be soft or hard)
Constructors / Destructors
 MultipleInferenceEngine (const CredalNet< GUM_SCALAR > &credalNet)
 Constructor.
 ~MultipleInferenceEngine () override
 Destructor.
Post-inference methods
void eraseAllEvidence () override
 Erase all inference related data to perform another one.
Pure virtual methods
void makeInference () override=0
 To be redefined by each credal net algorithm.
Getters and setters
VarMod2BNsMap< GUM_SCALAR > * getVarMod2BNsMap ()
 Get optimum IBayesNet.
const CredalNet< GUM_SCALAR > & credalNet () const
 Get this credal network.
const NodeProperty< std::vector< NodeId > > & getT0Cluster () const
 Get the t0_ cluster.
const NodeProperty< std::vector< NodeId > > & getT1Cluster () const
 Get the t1_ cluster.
void setRepetitiveInd (const bool repetitive)
void storeVertices (const bool value)
bool storeVertices () const
 Get the number of iterations without changes used to stop some algorithms.
void storeBNOpt (const bool value)
bool storeBNOpt () const
bool repetitiveInd () const
 Get the current independence status.
Pre-inference initialization methods
void insertModalsFile (std::string_view path)
 Insert variables modalities from file to compute expectations.
void insertModals (const std::map< std::string, std::vector< GUM_SCALAR > > &modals)
 Insert variables modalities from map to compute expectations.
virtual void insertEvidenceFile (std::string_view path)
 Insert evidence from file.
void insertEvidence (const std::map< std::string, std::vector< GUM_SCALAR > > &eviMap)
 Insert evidence from map.
void insertEvidence (const NodeProperty< std::vector< GUM_SCALAR > > &evidence)
 Insert evidence from Property.
void insertQueryFile (std::string_view path)
 Insert query variables states from file.
void insertQuery (const NodeProperty< std::vector< bool > > &query)
 Insert query variables and states from Property.
Post-inference methods
Tensor< GUM_SCALAR > marginalMin (const NodeId id) const
 Get the lower marginals of a given node id.
Tensor< GUM_SCALAR > marginalMin (std::string_view varName) const
 Get the lower marginals of a given variable name.
Tensor< GUM_SCALAR > marginalMax (const NodeId id) const
 Get the upper marginals of a given node id.
Tensor< GUM_SCALAR > marginalMax (std::string_view varName) const
 Get the upper marginals of a given variable name.
const GUM_SCALAR & expectationMin (const NodeId id) const
 Get the lower expectation of a given node id.
const GUM_SCALAR & expectationMin (std::string_view varName) const
 Get the lower expectation of a given variable name.
const GUM_SCALAR & expectationMax (const NodeId id) const
 Get the upper expectation of a given node id.
const GUM_SCALAR & expectationMax (std::string_view varName) const
 Get the upper expectation of a given variable name.
const std::vector< GUM_SCALAR > & dynamicExpMin (std::string_view varName) const
 Get the lower dynamic expectation of a given variable prefix (without the time step included, i.e.
const std::vector< GUM_SCALAR > & dynamicExpMax (std::string_view varName) const
 Get the upper dynamic expectation of a given variable prefix (without the time step included, i.e.
const std::vector< std::vector< GUM_SCALAR > > & vertices (const NodeId id) const
 Get the vertice of a given node id.
void saveMarginals (std::string_view path) const
 Saves marginals to file.
void saveExpectations (std::string_view path) const
 Saves expectations to file.
void saveVertices (std::string_view path) const
 Saves vertices to file.
void dynamicExpectations ()
 Compute dynamic expectations.
std::string toString () const
 Print all nodes marginals to standart output.
const std::string getApproximationSchemeMsg ()
 Get approximation scheme state.
Getters and setters
void setEpsilon (double eps) override
 Given that we approximate f(t), stopping criterion on |f(t+1)-f(t)|.
double epsilon () const override
 Returns the value of epsilon.
void disableEpsilon () override
 Disable stopping criterion on epsilon.
void enableEpsilon () override
 Enable stopping criterion on epsilon.
bool isEnabledEpsilon () const override
 Returns true if stopping criterion on epsilon is enabled, false otherwise.
void setMinEpsilonRate (double rate) override
 Given that we approximate f(t), stopping criterion on d/dt(|f(t+1)-f(t)|).
double minEpsilonRate () const override
 Returns the value of the minimal epsilon rate.
void disableMinEpsilonRate () override
 Disable stopping criterion on epsilon rate.
void enableMinEpsilonRate () override
 Enable stopping criterion on epsilon rate.
bool isEnabledMinEpsilonRate () const override
 Returns true if stopping criterion on epsilon rate is enabled, false otherwise.
void setMaxIter (Size max) override
 Stopping criterion on number of iterations.
Size maxIter () const override
 Returns the criterion on number of iterations.
void disableMaxIter () override
 Disable stopping criterion on max iterations.
void enableMaxIter () override
 Enable stopping criterion on max iterations.
bool isEnabledMaxIter () const override
 Returns true if stopping criterion on max iterations is enabled, false otherwise.
void setMaxTime (double timeout) override
 Stopping criterion on timeout.
double maxTime () const override
 Returns the timeout (in seconds).
double currentTime () const override
 Returns the current running time in second.
void disableMaxTime () override
 Disable stopping criterion on timeout.
void enableMaxTime () override
 Enable stopping criterion on timeout.
bool isEnabledMaxTime () const override
 Returns true if stopping criterion on timeout is enabled, false otherwise.
void setPeriodSize (Size p) override
 How many samples between two stopping is enable.
Size periodSize () const override
 Returns the period size.
void setVerbosity (bool v) override
 Set the verbosity on (true) or off (false).
bool verbosity () const override
 Returns true if verbosity is enabled.
ApproximationSchemeSTATE stateApproximationScheme () const override
 Returns the approximation scheme state.
Size nbrIterations () const override
 Returns the number of iterations.
const std::vector< double > & history () const override
 Returns the scheme history.
void initApproximationScheme ()
 Initialise the scheme.
bool startOfPeriod () const
 Returns true if we are at the beginning of a period (compute error is mandatory).
void updateApproximationScheme (unsigned int incr=1)
 Update the scheme w.r.t the new error and increment steps.
Size remainingBurnIn () const
 Returns the remaining burn in.
void stopApproximationScheme ()
 Stop the approximation scheme.
bool continueApproximationScheme (double error)
 Update the scheme w.r.t the new error.
Getters and setters
std::string messageApproximationScheme () const
 Returns the approximation scheme message.
Accessors/Modifiers
void setNumberOfThreads (Size nb) override
 sets the number max of threads to be used by the class containing this ThreadNumberManager
Size getNumberOfThreads () const override
 returns the current max number of threads used by the class containing this ThreadNumberManager
bool isGumNumberOfThreadsOverriden () const override
 indicates whether the class containing this ThreadNumberManager set its own number of threads

Public Attributes

Signaler< Size, double, doubleonProgress
 Progression, error and time.
Signaler< std::string_view > onStop
 Criteria messageApproximationScheme.

Protected Member Functions

Protected initialization methods

Fusion of threads optimal IBayesNet.

void initThreadsData_ (const Size &num_threads, const bool _storeVertices_, const bool _storeBNOpt_)
 Initialize threads data.
Protected algorithms methods
bool updateThread_ (Size this_thread, const NodeId &id, const std::vector< GUM_SCALAR > &vertex, const bool &elimRedund=false)
 Update thread information (marginals, expectations, IBayesNet, vertices) for a given node id.
void updateMarginals_ ()
 Fusion of threads marginals.
const GUM_SCALAR computeEpsilon_ () override
 Compute epsilon and update old marginals.
void updateOldMarginals_ ()
 Update old marginals (from current marginals).
Proptected post-inference methods
void optFusion_ ()
 Fusion of threads optimal IBayesNet.
void expFusion_ ()
 Fusion of threads expectations.
void verticesFusion_ ()
Protected initialization methods
void repetitiveInit_ ()
 Initialize t0_ and t1_ clusters.
void initExpectations_ ()
 Initialize lower and upper expectations before inference, with the lower expectation being initialized on the highest modality and the upper expectation being initialized on the lowest modality.
void initMarginals_ ()
 Initialize lower and upper old marginals and marginals before inference, with the lower marginal being 1 and the upper 0.
void dispatchMarginalsToThreads_ ()
 computes Vector threadRanges_, that assigns some part of marginalMin_ and marginalMax_ to the threads
void initMarginalSets_ ()
 Initialize credal set vertices with empty sets.
Protected algorithms methods
void updateExpectations_ (const NodeId &id, const std::vector< GUM_SCALAR > &vertex)
 Given a node id and one of it's possible vertex obtained during inference, update this node lower and upper expectations.
void updateCredalSets_ (const NodeId &id, const std::vector< GUM_SCALAR > &vertex, const bool &elimRedund=false)
 Given a node id and one of it's possible vertex, update it's credal set.
Proptected post-inference methods
void dynamicExpectations_ ()
 Rearrange lower and upper expectations to suit dynamic networks.

Protected Attributes

_margis_ l_marginalMin_
 Threads lower marginals, one per thread.
_margis_ l_marginalMax_
 Threads upper marginals, one per thread.
_expes_ l_expectationMin_
 Threads lower expectations, one per thread.
_expes_ l_expectationMax_
 Threads upper expectations, one per thread.
_modals_ l_modal_
 Threads modalities.
_credalSets_ l_marginalSets_
 Threads vertices.
_margis_ l_evidence_
 Threads evidence.
_clusters_ l_clusters_
 Threads clusters.
std::vector< _bnet_ * > workingSet_
 Threads IBayesNet.
std::vector< List< const Tensor< GUM_SCALAR > * > * > workingSetE_
 Threads evidence.
std::vector< BNInferenceEngine * > l_inferenceEngine_
 Threads BNInferenceEngine.
std::vector< VarMod2BNsMap< GUM_SCALAR > * > l_optimalNet_
 Threads optimal IBayesNet.
std::vector< std::mt19937 > generators_
 the generators used for computing random values
const CredalNet< GUM_SCALAR > * credalNet_
 A pointer to the Credal Net used.
margi oldMarginalMin_
 Old lower marginals used to compute epsilon.
margi oldMarginalMax_
 Old upper marginals used to compute epsilon.
margi marginalMin_
 Lower marginals.
margi marginalMax_
 Upper marginals.
credalSet marginalSets_
 Credal sets vertices, if enabled.
expe expectationMin_
 Lower expectations, if some variables modalities were inserted.
expe expectationMax_
 Upper expectations, if some variables modalities were inserted.
dynExpe dynamicExpMin_
 Lower dynamic expectations.
dynExpe dynamicExpMax_
 Upper dynamic expectations.
dynExpe modal_
 Variables modalities used to compute expectations.
margi evidence_
 Holds observed variables states.
query query_
 Holds the query nodes states.
cluster t0_
 Clusters of nodes used with dynamic networks.
cluster t1_
 Clusters of nodes used with dynamic networks.
bool storeVertices_
 True if credal sets vertices are stored, False otherwise.
bool repetitiveInd_
 True if using repetitive independence ( dynamic network only ), False otherwise.
bool storeBNOpt_
 Iterations limit stopping rule used by some algorithms such as CNMonteCarloSampling.
VarMod2BNsMap< GUM_SCALAR > dbnOpt_
 Object used to efficiently store optimal bayes net during inference, for some algorithms.
std::vector< std::pair< NodeId, Idx > > threadRanges_
 the ranges of elements of marginalMin_ and marginalMax_ processed by each thread
int timeSteps_
 The number of time steps of this network (only useful for dynamic networks).
Size threadMinimalNbOps_ {Size(20)}
double current_epsilon_
 Current epsilon.
double last_epsilon_
 Last epsilon value.
double current_rate_
 Current rate.
Size current_step_
 The current step.
Timer timer_
 The timer.
ApproximationSchemeSTATE current_state_
 The current state.
std::vector< doublehistory_
 The scheme history, used only if verbosity == true.
double eps_
 Threshold for convergence.
bool enabled_eps_
 If true, the threshold convergence is enabled.
double min_rate_eps_
 Threshold for the epsilon rate.
bool enabled_min_rate_eps_
 If true, the minimal threshold for epsilon rate is enabled.
double max_time_
 The timeout.
bool enabled_max_time_
 If true, the timeout is enabled.
Size max_iter_
 The maximum iterations.
bool enabled_max_iter_
 If true, the maximum iterations stopping criterion is enabled.
Size burn_in_
 Number of iterations before checking stopping criteria.
Size period_size_
 Checking criteria frequency.
bool verbosity_
 If true, verbosity is enabled.

Private Types

using _infE_ = InferenceEngine< GUM_SCALAR >
 To easily access InferenceEngine< GUM_SCALAR > methods.
using _cluster_ = NodeProperty< std::vector< NodeId > >
using _credalSet_ = NodeProperty< std::vector< std::vector< GUM_SCALAR > > >
using _margi_ = NodeProperty< std::vector< GUM_SCALAR > >
using _expe_ = NodeProperty< GUM_SCALAR >
using _bnet_ = IBayesNet< GUM_SCALAR >
using _margis_ = std::vector< _margi_ >
using _expes_ = std::vector< _expe_ >
using _credalSets_ = std::vector< _credalSet_ >
using _clusters_ = std::vector< std::vector< _cluster_ > >
using _modals_ = std::vector< HashTable< std::string, std::vector< GUM_SCALAR > > >
using credalSet = NodeProperty< std::vector< std::vector< GUM_SCALAR > > >
using margi = NodeProperty< std::vector< GUM_SCALAR > >
using expe = NodeProperty< GUM_SCALAR >
using dynExpe = typename gum::HashTable< std::string, std::vector< GUM_SCALAR > >
using query = NodeProperty< std::vector< bool > >
using cluster = NodeProperty< std::vector< NodeId > >

Private Member Functions

void _updateThreadCredalSets_ (Size this_thread, const NodeId &id, const std::vector< GUM_SCALAR > &vertex, const bool &elimRedund)
 Ask for redundancy elimination of a node credal set of a calling thread.
void stopScheme_ (ApproximationSchemeSTATE new_state)
 Stop the scheme given a new state.

Private Attributes

Size _nb_threads_ {0}
 the max number of threads used by the class

Detailed Description

template<GUM_Numeric GUM_SCALAR, class BNInferenceEngine>
class gum::credal::MultipleInferenceEngine< GUM_SCALAR, BNInferenceEngine >

Class template representing a CredalNet inference engine using one or more IBayesNet inference engines such as LazyPropagation.

Extends InferenceEngine< GUM_SCALAR >. Used for outer multi-threading such as CNMonteCarloSampling.

Template Parameters
GUM_SCALARA floating type ( float, double, long double ... ).
BNInferenceEngineA IBayesNet inference engine such as LazyPropagation.
Author
Matthieu HOURBRACQ and Pierre-Henri WUILLEMIN(_at_LIP6)

Definition at line 74 of file multipleInferenceEngine.h.

Member Typedef Documentation

◆ _bnet_

template<GUM_Numeric GUM_SCALAR, class BNInferenceEngine>
using gum::credal::MultipleInferenceEngine< GUM_SCALAR, BNInferenceEngine >::_bnet_ = IBayesNet< GUM_SCALAR >
private

Definition at line 84 of file multipleInferenceEngine.h.

◆ _cluster_

template<GUM_Numeric GUM_SCALAR, class BNInferenceEngine>
using gum::credal::MultipleInferenceEngine< GUM_SCALAR, BNInferenceEngine >::_cluster_ = NodeProperty< std::vector< NodeId > >
private

Definition at line 79 of file multipleInferenceEngine.h.

◆ _clusters_

template<GUM_Numeric GUM_SCALAR, class BNInferenceEngine>
using gum::credal::MultipleInferenceEngine< GUM_SCALAR, BNInferenceEngine >::_clusters_ = std::vector< std::vector< _cluster_ > >
private

Definition at line 88 of file multipleInferenceEngine.h.

◆ _credalSet_

template<GUM_Numeric GUM_SCALAR, class BNInferenceEngine>
using gum::credal::MultipleInferenceEngine< GUM_SCALAR, BNInferenceEngine >::_credalSet_ = NodeProperty< std::vector< std::vector< GUM_SCALAR > > >
private

Definition at line 80 of file multipleInferenceEngine.h.

◆ _credalSets_

template<GUM_Numeric GUM_SCALAR, class BNInferenceEngine>
using gum::credal::MultipleInferenceEngine< GUM_SCALAR, BNInferenceEngine >::_credalSets_ = std::vector< _credalSet_ >
private

Definition at line 87 of file multipleInferenceEngine.h.

◆ _expe_

template<GUM_Numeric GUM_SCALAR, class BNInferenceEngine>
using gum::credal::MultipleInferenceEngine< GUM_SCALAR, BNInferenceEngine >::_expe_ = NodeProperty< GUM_SCALAR >
private

Definition at line 82 of file multipleInferenceEngine.h.

◆ _expes_

template<GUM_Numeric GUM_SCALAR, class BNInferenceEngine>
using gum::credal::MultipleInferenceEngine< GUM_SCALAR, BNInferenceEngine >::_expes_ = std::vector< _expe_ >
private

Definition at line 86 of file multipleInferenceEngine.h.

◆ _infE_

template<GUM_Numeric GUM_SCALAR, class BNInferenceEngine>
using gum::credal::MultipleInferenceEngine< GUM_SCALAR, BNInferenceEngine >::_infE_ = InferenceEngine< GUM_SCALAR >
private

To easily access InferenceEngine< GUM_SCALAR > methods.

Definition at line 77 of file multipleInferenceEngine.h.

◆ _margi_

template<GUM_Numeric GUM_SCALAR, class BNInferenceEngine>
using gum::credal::MultipleInferenceEngine< GUM_SCALAR, BNInferenceEngine >::_margi_ = NodeProperty< std::vector< GUM_SCALAR > >
private

Definition at line 81 of file multipleInferenceEngine.h.

◆ _margis_

template<GUM_Numeric GUM_SCALAR, class BNInferenceEngine>
using gum::credal::MultipleInferenceEngine< GUM_SCALAR, BNInferenceEngine >::_margis_ = std::vector< _margi_ >
private

Definition at line 85 of file multipleInferenceEngine.h.

◆ _modals_

template<GUM_Numeric GUM_SCALAR, class BNInferenceEngine>
using gum::credal::MultipleInferenceEngine< GUM_SCALAR, BNInferenceEngine >::_modals_ = std::vector< HashTable< std::string, std::vector< GUM_SCALAR > > >
private

Definition at line 90 of file multipleInferenceEngine.h.

◆ cluster

template<GUM_Numeric GUM_SCALAR>
using gum::credal::InferenceEngine< GUM_SCALAR >::cluster = NodeProperty< std::vector< NodeId > >
privateinherited

Definition at line 82 of file inferenceEngine.h.

◆ credalSet

template<GUM_Numeric GUM_SCALAR>
using gum::credal::InferenceEngine< GUM_SCALAR >::credalSet = NodeProperty< std::vector< std::vector< GUM_SCALAR > > >
privateinherited

Definition at line 75 of file inferenceEngine.h.

◆ dynExpe

template<GUM_Numeric GUM_SCALAR>
using gum::credal::InferenceEngine< GUM_SCALAR >::dynExpe = typename gum::HashTable< std::string, std::vector< GUM_SCALAR > >
privateinherited

Definition at line 79 of file inferenceEngine.h.

◆ expe

template<GUM_Numeric GUM_SCALAR>
using gum::credal::InferenceEngine< GUM_SCALAR >::expe = NodeProperty< GUM_SCALAR >
privateinherited

Definition at line 77 of file inferenceEngine.h.

◆ margi

template<GUM_Numeric GUM_SCALAR>
using gum::credal::InferenceEngine< GUM_SCALAR >::margi = NodeProperty< std::vector< GUM_SCALAR > >
privateinherited

Definition at line 76 of file inferenceEngine.h.

◆ query

template<GUM_Numeric GUM_SCALAR>
using gum::credal::InferenceEngine< GUM_SCALAR >::query = NodeProperty< std::vector< bool > >
privateinherited

Definition at line 81 of file inferenceEngine.h.

Member Enumeration Documentation

◆ ApproximationSchemeSTATE

The different state of an approximation scheme.

Enumerator
Undefined 
Continue 
Epsilon 
Rate 
Limit 
TimeLimit 
Stopped 

Definition at line 87 of file IApproximationSchemeConfiguration.h.

87 : char {
88 Undefined,
89 Continue,
90 Epsilon,
91 Rate,
92 Limit,
93 TimeLimit,
94 Stopped
95 };

Constructor & Destructor Documentation

◆ MultipleInferenceEngine()

template<GUM_Numeric GUM_SCALAR, class BNInferenceEngine>
gum::credal::MultipleInferenceEngine< GUM_SCALAR, BNInferenceEngine >::MultipleInferenceEngine ( const CredalNet< GUM_SCALAR > & credalNet)
explicit

Constructor.

Parameters
credalNetThe CredalNet to be used.

Definition at line 51 of file multipleInferenceEngine_tpl.h.

52 :
55 }
InferenceEngine(const CredalNet< GUM_SCALAR > &credalNet)
Construtor.
const CredalNet< GUM_SCALAR > & credalNet() const
Get this credal network.
Class template representing a CredalNet inference engine using one or more IBayesNet inference engine...
MultipleInferenceEngine(const CredalNet< GUM_SCALAR > &credalNet)
Constructor.

References gum::credal::InferenceEngine< GUM_SCALAR >::InferenceEngine(), MultipleInferenceEngine(), and gum::credal::InferenceEngine< GUM_SCALAR >::credalNet().

Referenced by MultipleInferenceEngine(), and ~MultipleInferenceEngine().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ ~MultipleInferenceEngine()

template<GUM_Numeric GUM_SCALAR, class BNInferenceEngine>
gum::credal::MultipleInferenceEngine< GUM_SCALAR, BNInferenceEngine >::~MultipleInferenceEngine ( )
override

Destructor.

Definition at line 58 of file multipleInferenceEngine_tpl.h.

References MultipleInferenceEngine().

Here is the call graph for this function:

Member Function Documentation

◆ _updateThreadCredalSets_()

template<GUM_Numeric GUM_SCALAR, class BNInferenceEngine>
void gum::credal::MultipleInferenceEngine< GUM_SCALAR, BNInferenceEngine >::_updateThreadCredalSets_ ( Size this_thread,
const NodeId & id,
const std::vector< GUM_SCALAR > & vertex,
const bool & elimRedund )
inlineprivate

Ask for redundancy elimination of a node credal set of a calling thread.

Called by updateThread_ if vertices are stored.

Parameters
this_threadthe id of the thread executing this method
idA constant reference to the node id whose credal set is to be checked for redundancy.
vertexThe vertex to add to the credal set.
elimRedundtrue if redundancy elimination is to be performed, false otherwise and by default.

Definition at line 218 of file multipleInferenceEngine_tpl.h.

222 {
224 Size dsize = Size(vertex.size());
225
226 bool eq = true;
227
228 for (auto it = nodeCredalSet.cbegin(), itEnd = nodeCredalSet.cend(); it != itEnd; ++it) {
229 eq = true;
230
231 for (Size i = 0; i < dsize; i++) {
232 if (std::fabs(vertex[i] - (*it)[i]) > 1e-6) {
233 eq = false;
234 break;
235 }
236 }
237
238 if (eq) break;
239 }
240
241 if (!eq || nodeCredalSet.size() == 0) {
242 nodeCredalSet.push_back(vertex);
243 return;
244 } else return;
245
248 if (nodeCredalSet.size() == 1) return;
249
250 // check that the point and all previously added ones are not inside the
251 // actual
252 // polytope
253 auto itEnd = std::remove_if(
254 nodeCredalSet.begin(),
255 nodeCredalSet.end(),
256 [&](const std::vector< GUM_SCALAR >& v) -> bool {
257 for (auto jt = v.cbegin(),
258 jtEnd = v.cend(),
259 minIt = l_marginalMin_[tId][id].cbegin(),
260 minItEnd = l_marginalMin_[tId][id].cend(),
261 maxIt = l_marginalMax_[tId][id].cbegin(),
262 maxItEnd = l_marginalMax_[tId][id].cend();
263 jt != jtEnd && minIt != minItEnd && maxIt != maxItEnd;
264 ++jt, ++minIt, ++maxIt) {
265 if ((std::fabs(*jt - *minIt) < 1e-6 || std::fabs(*jt - *maxIt) < 1e-6)
266 && std::fabs(*minIt - *maxIt) > 1e-6)
267 return false;
268 }
269 return true;
270 });
271
272 nodeCredalSet.erase(itEnd, nodeCredalSet.end());
273
274 // we need at least 2 points to make a convex combination
275 if (!elimRedund || nodeCredalSet.size() <= 2) return;
276
277 // there may be points not inside the polytope but on one of it's facet,
278 // meaning it's still a convex combination of vertices of this facet. Here
279 // we need lrs.
280 Size setSize = Size(nodeCredalSet.size());
281
283 lrsWrapper.setUpV(dsize, setSize);
284
285 for (const auto& vtx: nodeCredalSet)
286 lrsWrapper.fillV(vtx);
287
288 lrsWrapper.elimRedundVrep();
289
290 l_marginalSets_[tId][id] = lrsWrapper.getOutput();
291 }
_credalSets_ l_marginalSets_
Threads vertices.
std::size_t Size
In aGrUM, hashed values are unsigned long int.
Definition types.h:74

◆ addEvidence() [1/7]

template<GUM_Numeric GUM_SCALAR>
void gum::credal::InferenceEngine< GUM_SCALAR >::addEvidence ( const Tensor< GUM_SCALAR > & pot)
finalvirtualinherited

adds a new evidence on node id (might be soft or hard)

Exceptions
UndefinedElementif the tensor is defined over several nodes
UndefinedElementif the node on which the tensor is defined does not belong to the Bayesian network
InvalidArgumentif the node of the tensor already has an evidence
FatalErrorif pot=[0,0,...,0]

Definition at line 1197 of file inferenceEngine_tpl.h.

1197 {
1198 const auto id = this->credalNet_->current_bn().idFromName(pot.variable(0).name());
1199 std::vector< GUM_SCALAR > vals(this->credalNet_->current_bn().variable(id).domainSize(), 0);
1201 for (I.setFirst(); !I.end(); I.inc()) {
1202 vals[I.val(0)] = pot[I];
1203 }
1204 addEvidence(id, vals);
1205 }
Abstract class template representing a CredalNet inference engine.
const CredalNet< GUM_SCALAR > * credalNet_
A pointer to the Credal Net used.
virtual void addEvidence(NodeId id, const Idx val) final
adds a new hard evidence on node id

References addEvidence(), credalNet_, gum::Instantiation::end(), gum::Instantiation::inc(), gum::Instantiation::setFirst(), and gum::Instantiation::val().

Here is the call graph for this function:

◆ addEvidence() [2/7]

template<GUM_Numeric GUM_SCALAR>
void gum::credal::InferenceEngine< GUM_SCALAR >::addEvidence ( NodeId id,
const Idx val )
finalvirtualinherited

adds a new hard evidence on node id

Exceptions
UndefinedElementif id does not belong to the Bayesian network
InvalidArgumentif val is not a value for id
InvalidArgumentif id already has an evidence

Definition at line 1164 of file inferenceEngine_tpl.h.

1164 {
1165 std::vector< GUM_SCALAR > vals(this->credalNet_->current_bn().variable(id).domainSize(), 0);
1166 vals[val] = 1;
1167 addEvidence(id, vals);
1168 }

References addEvidence(), and credalNet_.

Referenced by addEvidence(), addEvidence(), addEvidence(), addEvidence(), addEvidence(), and addEvidence().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ addEvidence() [3/7]

template<GUM_Numeric GUM_SCALAR>
void gum::credal::InferenceEngine< GUM_SCALAR >::addEvidence ( NodeId id,
const std::vector< GUM_SCALAR > & vals )
finalvirtualinherited

adds a new evidence on node id (might be soft or hard)

Exceptions
UndefinedElementif id does not belong to the Bayesian network
InvalidArgumentif id already has an evidence
FatalErrorif vals=[0,0,...,0]
InvalidArgumentif the size of vals is different from the domain size of node id

Definition at line 1154 of file inferenceEngine_tpl.h.

1155 {
1156 evidence_.insert(id, vals);
1157 // forces the computation of the begin iterator to avoid subsequent data races
1158 // @TODO make HashTableConstIterator constructors thread safe
1159 evidence_.begin();
1160 }
margi evidence_
Holds observed variables states.

References evidence_.

◆ addEvidence() [4/7]

template<GUM_Numeric GUM_SCALAR>
void gum::credal::InferenceEngine< GUM_SCALAR >::addEvidence ( NodeId id,
std::string_view label )
finalvirtualinherited

adds a new hard evidence on node id

Exceptions
UndefinedElementif id does not belong to the Bayesian network
InvalidArgumentif val is not a value for id
InvalidArgumentif id already has an evidence

Definition at line 1178 of file inferenceEngine_tpl.h.

1178 {
1179 addEvidence(id, this->credalNet_->current_bn().variable(id)[label]);
1180 }

References addEvidence(), and credalNet_.

Here is the call graph for this function:

◆ addEvidence() [5/7]

template<GUM_Numeric GUM_SCALAR>
void gum::credal::InferenceEngine< GUM_SCALAR >::addEvidence ( std::string_view nodeName,
const Idx val )
finalvirtualinherited

adds a new hard evidence on node named nodeName

Exceptions
UndefinedElementif nodeName does not belong to the Bayesian network
InvalidArgumentif val is not a value for id
InvalidArgumentif nodeName already has an evidence

Definition at line 1172 of file inferenceEngine_tpl.h.

1172 {
1173 addEvidence(this->credalNet_->current_bn().idFromName(nodeName), val);
1174 }

References addEvidence(), and credalNet_.

Here is the call graph for this function:

◆ addEvidence() [6/7]

template<GUM_Numeric GUM_SCALAR>
void gum::credal::InferenceEngine< GUM_SCALAR >::addEvidence ( std::string_view nodeName,
const std::vector< GUM_SCALAR > & vals )
finalvirtualinherited

adds a new evidence on node named nodeName (might be soft or hard)

Exceptions
UndefinedElementif id does not belong to the Bayesian network
InvalidArgumentif nodeName already has an evidence
FatalErrorif vals=[0,0,...,0]
InvalidArgumentif the size of vals is different from the domain size of node nodeName

Definition at line 1191 of file inferenceEngine_tpl.h.

1192 {
1193 addEvidence(this->credalNet_->current_bn().idFromName(nodeName), vals);
1194 }

References addEvidence(), and credalNet_.

Here is the call graph for this function:

◆ addEvidence() [7/7]

template<GUM_Numeric GUM_SCALAR>
void gum::credal::InferenceEngine< GUM_SCALAR >::addEvidence ( std::string_view nodeName,
std::string_view label )
finalvirtualinherited

adds a new hard evidence on node named nodeName

Exceptions
UndefinedElementif nodeName does not belong to the Bayesian network
InvalidArgumentif val is not a value for id
InvalidArgumentif nodeName already has an evidence

Definition at line 1184 of file inferenceEngine_tpl.h.

1185 {
1186 const NodeId id = this->credalNet_->current_bn().idFromName(nodeName);
1187 addEvidence(id, this->credalNet_->current_bn().variable(id)[label]);
1188 }

References addEvidence(), and credalNet_.

Here is the call graph for this function:

◆ computeEpsilon_()

template<GUM_Numeric GUM_SCALAR, class BNInferenceEngine>
const GUM_SCALAR gum::credal::MultipleInferenceEngine< GUM_SCALAR, BNInferenceEngine >::computeEpsilon_ ( )
inlineoverrideprotectedvirtual

Compute epsilon and update old marginals.

Returns
Epsilon.

Reimplemented from gum::credal::InferenceEngine< GUM_SCALAR >.

Definition at line 369 of file multipleInferenceEngine_tpl.h.

369 {
370 // compute the number of threads (avoid nested threads)
372 ? this->threadRanges_.size() - 1
373 : 1; // no nested multithreading
374
376
377 // create the function to be executed by the threads
378 auto threadedExec = [this, &tEps](const std::size_t this_thread,
381 auto& this_tEps = tEps[this_thread];
382 GUM_SCALAR delta = 0;
383
384 auto i = this->threadRanges_[this_thread].first;
385 auto j = this->threadRanges_[this_thread].second;
386 auto domain_size = this->marginalMax_[i].size();
387 const auto end_i = this->threadRanges_[this_thread + 1].first;
388 auto end_j = this->threadRanges_[this_thread + 1].second;
389 const auto marginalMax_size = this->marginalMax_.size();
390
391 while ((i < end_i) || (j < end_j)) {
392 // on min
393 delta = this->marginalMin_[i][j] - this->oldMarginalMin_[i][j];
394 delta = (delta < 0) ? (-delta) : delta;
396
397 // on max
398 delta = this->marginalMax_[i][j] - this->oldMarginalMax_[i][j];
399 delta = (delta < 0) ? (-delta) : delta;
401
402 this->oldMarginalMin_[i][j] = this->marginalMin_[i][j];
403 this->oldMarginalMax_[i][j] = this->marginalMax_[i][j];
404
405 if (++j == domain_size) {
406 j = 0;
407 ++i;
408 if (i < marginalMax_size) domain_size = this->marginalMax_[i].size();
409 }
410 }
411 };
412
413 // launch the threads
417 (nb_threads == 1)
418 ? std::vector< std::pair< NodeId, Idx > >{{0, 0}, {this->marginalMin_.size(), 0}}
419 : this->threadRanges_);
420
421 // aggregate all the results
422 GUM_SCALAR eps = tEps[0];
423 for (const auto nb: tEps)
424 if (eps < nb) eps = nb;
425
426 return eps;
427 }
margi oldMarginalMax_
Old upper marginals used to compute epsilon.
margi marginalMax_
Upper marginals.
margi oldMarginalMin_
Old lower marginals used to compute epsilon.
margi marginalMin_
Lower marginals.
std::vector< std::pair< NodeId, Idx > > threadRanges_
the ranges of elements of marginalMin_ and marginalMax_ processed by each thread
static void execute(std::size_t nb_threads, FUNCTION exec_func, ARGS &&... func_args)
executes a function using several threads
static int nbRunningThreadsExecutors()
indicates how many threadExecutors are currently running

References computeEpsilon_(), gum::threadsSTL::ThreadExecutor::execute(), gum::credal::InferenceEngine< GUM_SCALAR >::marginalMax_, gum::credal::InferenceEngine< GUM_SCALAR >::marginalMin_, gum::threadsSTL::ThreadExecutor::nbRunningThreadsExecutors(), gum::credal::InferenceEngine< GUM_SCALAR >::oldMarginalMax_, gum::credal::InferenceEngine< GUM_SCALAR >::oldMarginalMin_, and gum::credal::InferenceEngine< GUM_SCALAR >::threadRanges_.

Referenced by computeEpsilon_().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ continueApproximationScheme()

bool gum::ApproximationScheme::continueApproximationScheme ( double error)
inherited

Update the scheme w.r.t the new error.

Test the stopping criterion that are enabled.

Parameters
errorThe new error value.
Returns
false if state become != ApproximationSchemeSTATE::Continue
Exceptions
OperationNotAllowedRaised if state != ApproximationSchemeSTATE::Continue.

Definition at line 69 of file approximationScheme.cpp.

69 {
70 // For coherence, we fix the time used in the method
71
72 double timer_step = timer_.step();
73
75 if (timer_step > max_time_) {
77 return false;
78 }
79 }
80
81 if (!startOfPeriod()) { return true; }
82
85 OperationNotAllowed,
86 "state of the approximation scheme is not correct : " << messageApproximationScheme());
87 }
88
89 if (verbosity()) { history_.push_back(error); }
90
92 if (current_step_ >= max_iter_) {
94 return false;
95 }
96 }
97
99 current_epsilon_ = error; // eps rate isEnabled needs it so affectation was
100 // moved from eps isEnabled below
101
102 if (enabled_eps_) {
103 if (current_epsilon_ <= eps_) {
105 return false;
106 }
107 }
108
109 if (last_epsilon_ >= 0.) {
110 if (current_epsilon_ > .0) {
111 // ! current_epsilon_ can be 0. AND epsilon
112 // isEnabled can be disabled !
114 }
115 // limit with current eps ---> 0 is | 1 - ( last_eps / 0 ) | --->
116 // infinity the else means a return false if we isEnabled the rate below,
117 // as we would have returned false if epsilon isEnabled was enabled
118 else {
120 }
121
125 return false;
126 }
127 }
128 }
129
131 if (onProgress.hasListener()) {
133 }
134
135 return true;
136 } else {
137 return false;
138 }
139 }
Size current_step_
The current step.
double current_epsilon_
Current epsilon.
double last_epsilon_
Last epsilon value.
double eps_
Threshold for convergence.
bool enabled_max_time_
If true, the timeout is enabled.
Size max_iter_
The maximum iterations.
bool enabled_eps_
If true, the threshold convergence is enabled.
ApproximationSchemeSTATE current_state_
The current state.
double min_rate_eps_
Threshold for the epsilon rate.
std::vector< double > history_
The scheme history, used only if verbosity == true.
double current_rate_
Current rate.
ApproximationSchemeSTATE stateApproximationScheme() const override
Returns the approximation scheme state.
bool startOfPeriod() const
Returns true if we are at the beginning of a period (compute error is mandatory).
bool enabled_max_iter_
If true, the maximum iterations stopping criterion is enabled.
void stopScheme_(ApproximationSchemeSTATE new_state)
Stop the scheme given a new state.
bool verbosity() const override
Returns true if verbosity is enabled.
bool enabled_min_rate_eps_
If true, the minimal threshold for epsilon rate is enabled.
Signaler< Size, double, double > onProgress
Progression, error and time.
std::string messageApproximationScheme() const
Returns the approximation scheme message.
#define GUM_ERROR(type, msg)
Definition exceptions.h:76
#define GUM_EMIT3(signal, arg1, arg2, arg3)
Definition signaler.h:291

References gum::IApproximationSchemeConfiguration::Continue, current_epsilon_, current_rate_, current_state_, current_step_, enabled_eps_, enabled_max_iter_, enabled_max_time_, enabled_min_rate_eps_, eps_, gum::IApproximationSchemeConfiguration::Epsilon, GUM_EMIT3, GUM_ERROR, history_, last_epsilon_, gum::IApproximationSchemeConfiguration::Limit, max_iter_, max_time_, gum::IApproximationSchemeConfiguration::messageApproximationScheme(), min_rate_eps_, gum::IApproximationSchemeConfiguration::onProgress, gum::IApproximationSchemeConfiguration::Rate, startOfPeriod(), stateApproximationScheme(), stopScheme_(), gum::IApproximationSchemeConfiguration::TimeLimit, timer_, and verbosity().

Referenced by gum::GibbsBNdistance< GUM_SCALAR >::computeKL_(), gum::MCBNDistance< GUM_SCALAR >::computeKL_(), gum::learning::GreedyHillClimbing::learnStructure(), gum::learning::GreedyThickThinning::learnStructure(), gum::learning::LocalSearchWithTabuList::learnStructure(), gum::SamplingInference< GUM_SCALAR >::loopApproxInference_(), gum::credal::CNLoopyPropagation< GUM_SCALAR >::makeInferenceByOrderedArcs_(), gum::credal::CNLoopyPropagation< GUM_SCALAR >::makeInferenceByRandomOrder_(), and gum::credal::CNLoopyPropagation< GUM_SCALAR >::makeInferenceNodeToNeighbours_().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ credalNet()

template<GUM_Numeric GUM_SCALAR>
const CredalNet< GUM_SCALAR > & gum::credal::InferenceEngine< GUM_SCALAR >::credalNet ( ) const
inherited

Get this credal network.

Returns
A constant reference to this CredalNet.

Definition at line 82 of file inferenceEngine_tpl.h.

82 {
83 return *credalNet_;
84 }

References credalNet_.

Referenced by gum::credal::CNLoopyPropagation< GUM_SCALAR >::CNLoopyPropagation(), InferenceEngine(), and gum::credal::MultipleInferenceEngine< GUM_SCALAR, BNInferenceEngine >::MultipleInferenceEngine().

Here is the caller graph for this function:

◆ currentTime()

INLINE double gum::ApproximationScheme::currentTime ( ) const
overridevirtualinherited

Returns the current running time in second.

Returns
Returns the current running time in second.

Implements gum::IApproximationSchemeConfiguration.

Definition at line 137 of file approximationScheme_inl.h.

137{ return timer_.step(); }

References timer_.

◆ disableEpsilon()

INLINE void gum::ApproximationScheme::disableEpsilon ( )
overridevirtualinherited

Disable stopping criterion on epsilon.

Implements gum::IApproximationSchemeConfiguration.

Definition at line 75 of file approximationScheme_inl.h.

75{ enabled_eps_ = false; }

References enabled_eps_.

Referenced by gum::learning::EMApproximationScheme::EMApproximationScheme(), and gum::learning::EMApproximationScheme::setMinEpsilonRate().

Here is the caller graph for this function:

◆ disableMaxIter()

INLINE void gum::ApproximationScheme::disableMaxIter ( )
overridevirtualinherited

Disable stopping criterion on max iterations.

Implements gum::IApproximationSchemeConfiguration.

Definition at line 116 of file approximationScheme_inl.h.

116{ enabled_max_iter_ = false; }

References enabled_max_iter_.

Referenced by gum::learning::GreedyHillClimbing::GreedyHillClimbing(), and gum::learning::GreedyThickThinning::GreedyThickThinning().

Here is the caller graph for this function:

◆ disableMaxTime()

INLINE void gum::ApproximationScheme::disableMaxTime ( )
overridevirtualinherited

Disable stopping criterion on timeout.

Returns
Disable stopping criterion on timeout.

Implements gum::IApproximationSchemeConfiguration.

Definition at line 140 of file approximationScheme_inl.h.

140{ enabled_max_time_ = false; }

References enabled_max_time_.

Referenced by gum::learning::GreedyHillClimbing::GreedyHillClimbing(), and gum::learning::GreedyThickThinning::GreedyThickThinning().

Here is the caller graph for this function:

◆ disableMinEpsilonRate()

INLINE void gum::ApproximationScheme::disableMinEpsilonRate ( )
overridevirtualinherited

Disable stopping criterion on epsilon rate.

Implements gum::IApproximationSchemeConfiguration.

Definition at line 96 of file approximationScheme_inl.h.

96{ enabled_min_rate_eps_ = false; }

References enabled_min_rate_eps_.

Referenced by gum::learning::GreedyHillClimbing::GreedyHillClimbing(), gum::learning::GreedyThickThinning::GreedyThickThinning(), gum::GibbsBNdistance< GUM_SCALAR >::computeKL_(), gum::MCBNDistance< GUM_SCALAR >::computeKL_(), and gum::learning::EMApproximationScheme::setEpsilon().

Here is the caller graph for this function:

◆ dispatchMarginalsToThreads_()

template<GUM_Numeric GUM_SCALAR>
void gum::credal::InferenceEngine< GUM_SCALAR >::dispatchMarginalsToThreads_ ( )
protectedinherited

computes Vector threadRanges_, that assigns some part of marginalMin_ and marginalMax_ to the threads

Definition at line 1094 of file inferenceEngine_tpl.h.

1094 {
1095 // we compute the number of elements in the 2 loops (over i,j in marginalMin_[i][j])
1096 Size nb_elements = 0;
1097 const auto marginalMin_size = this->marginalMin_.size();
1098 for (const auto& marg_i: this->marginalMin_)
1099 nb_elements += marg_i.second.size();
1100
1101 // distribute evenly the elements among the threads
1104
1105 // the result that we return is a vector of pairs (NodeId, Idx). For thread number i, the
1106 // pair at index i is the beginning of the range that the thread will have to process: this
1107 // is the part of the marginal distribution vector of node NodeId starting at index Idx.
1108 // The pair at index i+1 is the end of this range (not included)
1109 threadRanges_.clear();
1110 threadRanges_.reserve(nb_threads + 1);
1111
1112 // try to balance the number of elements among the threads
1115
1116 NodeId current_node = 0;
1118 Size current_domain_size = this->marginalMin_[0].size();
1120
1121 for (Idx i = Idx(0); i < nb_threads; ++i) {
1122 // compute the end of the threads, assuming that the current node has a domain
1123 // sufficiently large
1125 if (rest_elts != Idx(0)) {
1127 --rest_elts;
1128 }
1129
1130 // if the current node is not sufficient to hold all the elements that
1131 // the current thread should process. So we should add elements of the
1132 // next nodes
1135 ++current_node;
1139 }
1140 }
1141
1142 // now we can store the range if elements
1144
1145 // compute the next begin_node
1147 ++current_node;
1149 }
1150 }
1151 }
Size getNumberOfThreads() const override
returns the current max number of threads used by the class containing this ThreadNumberManager
Size Idx
Type for indexes.
Definition types.h:79

References gum::ThreadNumberManager::getNumberOfThreads(), and threadRanges_.

Referenced by initMarginals_().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ dynamicExpectations()

template<GUM_Numeric GUM_SCALAR>
void gum::credal::InferenceEngine< GUM_SCALAR >::dynamicExpectations ( )
inherited

Compute dynamic expectations.

See also
dynamicExpectations_ Only call this if an algorithm does not call it by itself.

Definition at line 702 of file inferenceEngine_tpl.h.

702 {
704 }
void dynamicExpectations_()
Rearrange lower and upper expectations to suit dynamic networks.

References dynamicExpectations_().

Here is the call graph for this function:

◆ dynamicExpectations_()

template<GUM_Numeric GUM_SCALAR>
void gum::credal::InferenceEngine< GUM_SCALAR >::dynamicExpectations_ ( )
protectedinherited

Rearrange lower and upper expectations to suit dynamic networks.

Definition at line 707 of file inferenceEngine_tpl.h.

707 {
708 // no modals, no expectations computed during inference
709 if (expectationMin_.empty() || modal_.empty()) return;
710
711 // already called by the algorithm or the user
712 if (dynamicExpMax_.size() > 0 && dynamicExpMin_.size() > 0) return;
713
715
717
718
719 // if non dynamic, directly save expectationMin_ et Max (same but faster)
721
722 for (const auto& elt: expectationMin_) {
724
725 var_name = credalNet_->current_bn().variable(elt.first).name();
726 auto delim = var_name.find_first_of("_");
727 time_step = var_name.substr(delim + 1, var_name.size());
728 var_name = var_name.substr(0, delim);
729
730 // to be sure (don't store not monitored variables' expectations)
731 // although it
732 // should be taken care of before this point
733 if (!modal_.exists(var_name)) continue;
734
735 expectationsMin.getWithDefault(var_name, innerMap())
736 .getWithDefault(atoi(time_step.c_str()), 0)
737 = elt.second; // we iterate with min iterators
738 expectationsMax.getWithDefault(var_name, innerMap())
739 .getWithDefault(atoi(time_step.c_str()), 0) = expectationMax_[elt.first];
740 }
741
742 for (const auto& elt: expectationsMin) {
743 typename std::vector< GUM_SCALAR > dynExp(elt.second.size());
744
745 for (const auto& elt2: elt.second)
746 dynExp[elt2.first] = elt2.second;
747
748 dynamicExpMin_.insert(elt.first, dynExp);
749 }
750
751 for (const auto& elt: expectationsMax) {
752 typename std::vector< GUM_SCALAR > dynExp(elt.second.size());
753
754 for (const auto& elt2: elt.second) {
755 dynExp[elt2.first] = elt2.second;
756 }
757
758 dynamicExpMax_.insert(elt.first, dynExp);
759 }
760 }
dynExpe dynamicExpMin_
Lower dynamic expectations.
dynExpe dynamicExpMax_
Upper dynamic expectations.
expe expectationMax_
Upper expectations, if some variables modalities were inserted.
dynExpe modal_
Variables modalities used to compute expectations.
expe expectationMin_
Lower expectations, if some variables modalities were inserted.

References credalNet_, dynamicExpMax_, dynamicExpMin_, expectationMax_, expectationMin_, and modal_.

Referenced by dynamicExpectations().

Here is the caller graph for this function:

◆ dynamicExpMax()

template<GUM_Numeric GUM_SCALAR>
const std::vector< GUM_SCALAR > & gum::credal::InferenceEngine< GUM_SCALAR >::dynamicExpMax ( std::string_view varName) const
inherited

Get the upper dynamic expectation of a given variable prefix (without the time step included, i.e.

call with "temp" to get "temp_0", ..., "temp_T").

Parameters
varNameThe variable name prefix which upper expectation we want.
Returns
A constant reference to the variable upper expectation over all time steps.

Definition at line 496 of file inferenceEngine_tpl.h.

496 {
497 std::string errTxt = "const std::vector< GUM_SCALAR > & InferenceEngine< "
498 "GUM_SCALAR >::dynamicExpMax ( const std::string & "
499 "varName ) const : ";
500
501 if (dynamicExpMax_.empty())
502 GUM_ERROR(OperationNotAllowed, errTxt + "_dynamicExpectations() needs to be called before")
503
505 if (!p /*dynamicExpMin_.find(varName) == dynamicExpMin_.end()*/)
506 GUM_ERROR(NotFound, errTxt + "variable name not found : " << varName)
507
508 return *p;
509 }

References InferenceEngine(), and dynamicExpMax().

Referenced by dynamicExpMax().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ dynamicExpMin()

template<GUM_Numeric GUM_SCALAR>
const std::vector< GUM_SCALAR > & gum::credal::InferenceEngine< GUM_SCALAR >::dynamicExpMin ( std::string_view varName) const
inherited

Get the lower dynamic expectation of a given variable prefix (without the time step included, i.e.

call with "temp" to get "temp_0", ..., "temp_T").

Parameters
varNameThe variable name prefix which lower expectation we want.
Returns
A constant reference to the variable lower expectation over all time steps.

Definition at line 479 of file inferenceEngine_tpl.h.

479 {
480 std::string errTxt = "const std::vector< GUM_SCALAR > & InferenceEngine< "
481 "GUM_SCALAR >::dynamicExpMin ( const std::string & "
482 "varName ) const : ";
483
484 if (dynamicExpMin_.empty())
485 GUM_ERROR(OperationNotAllowed, errTxt + "_dynamicExpectations() needs to be called before")
486
488 if (!p /*dynamicExpMin_.find(varName) == dynamicExpMin_.end()*/)
489 GUM_ERROR(NotFound, errTxt + "variable name not found : " << varName)
490
491 return *p;
492 }

◆ enableEpsilon()

INLINE void gum::ApproximationScheme::enableEpsilon ( )
overridevirtualinherited

Enable stopping criterion on epsilon.

Implements gum::IApproximationSchemeConfiguration.

Definition at line 78 of file approximationScheme_inl.h.

78{ enabled_eps_ = true; }

References enabled_eps_.

◆ enableMaxIter()

INLINE void gum::ApproximationScheme::enableMaxIter ( )
overridevirtualinherited

Enable stopping criterion on max iterations.

Implements gum::IApproximationSchemeConfiguration.

Definition at line 119 of file approximationScheme_inl.h.

119{ enabled_max_iter_ = true; }

References enabled_max_iter_.

◆ enableMaxTime()

INLINE void gum::ApproximationScheme::enableMaxTime ( )
overridevirtualinherited

Enable stopping criterion on timeout.

Implements gum::IApproximationSchemeConfiguration.

Definition at line 143 of file approximationScheme_inl.h.

143{ enabled_max_time_ = true; }

References enabled_max_time_.

◆ enableMinEpsilonRate()

INLINE void gum::ApproximationScheme::enableMinEpsilonRate ( )
overridevirtualinherited

Enable stopping criterion on epsilon rate.

Implements gum::IApproximationSchemeConfiguration.

Definition at line 99 of file approximationScheme_inl.h.

99{ enabled_min_rate_eps_ = true; }

References enabled_min_rate_eps_.

Referenced by gum::learning::EMApproximationScheme::EMApproximationScheme(), gum::GibbsBNdistance< GUM_SCALAR >::computeKL_(), and gum::MCBNDistance< GUM_SCALAR >::computeKL_().

Here is the caller graph for this function:

◆ epsilon()

INLINE double gum::ApproximationScheme::epsilon ( ) const
overridevirtualinherited

Returns the value of epsilon.

Returns
Returns the value of epsilon.

Implements gum::IApproximationSchemeConfiguration.

Definition at line 72 of file approximationScheme_inl.h.

72{ return eps_; }

References eps_.

Referenced by gum::ImportanceSampling< GUM_SCALAR >::onContextualize_(), and gum::ImportanceSampling< GUM_SCALAR >::unsharpenBN_().

Here is the caller graph for this function:

◆ eraseAllEvidence()

template<GUM_Numeric GUM_SCALAR, class BNInferenceEngine>
void gum::credal::MultipleInferenceEngine< GUM_SCALAR, BNInferenceEngine >::eraseAllEvidence ( )
overridevirtual

Erase all inference related data to perform another one.

You need to insert evidence again if needed but modalities are kept. You can insert new ones by using the appropriate method which will delete the old ones.

Reimplemented from gum::credal::InferenceEngine< GUM_SCALAR >.

Definition at line 782 of file multipleInferenceEngine_tpl.h.

782 {
784 Size tsize = Size(workingSet_.size());
785
786 // delete pointers
787 for (Size bn = 0; bn < tsize; bn++) {
789
790 if (workingSet_[bn] != nullptr) delete workingSet_[bn];
791
793 if (l_inferenceEngine_[bn] != nullptr) delete l_optimalNet_[bn];
794
795 if (this->workingSetE_[bn] != nullptr) {
796 for (const auto ev: *workingSetE_[bn])
797 delete ev;
798
799 delete workingSetE_[bn];
800 }
801
802 if (l_inferenceEngine_[bn] != nullptr) delete l_inferenceEngine_[bn];
803 }
804
805 // this is important, those will be resized with the correct number of
806 // threads.
807
808 workingSet_.clear();
809 workingSetE_.clear();
810 l_inferenceEngine_.clear();
811 l_optimalNet_.clear();
812
813 l_marginalMin_.clear();
814 l_marginalMax_.clear();
815 l_expectationMin_.clear();
816 l_expectationMax_.clear();
817 l_modal_.clear();
818 l_marginalSets_.clear();
819 l_evidence_.clear();
820 l_clusters_.clear();
821 }
bool storeBNOpt_
Iterations limit stopping rule used by some algorithms such as CNMonteCarloSampling.
bool storeVertices_
True if credal sets vertices are stored, False otherwise.
virtual void eraseAllEvidence()
removes all the evidence entered into the network
_margis_ l_marginalMin_
Threads lower marginals, one per thread.
_expes_ l_expectationMax_
Threads upper expectations, one per thread.
_expes_ l_expectationMin_
Threads lower expectations, one per thread.
std::vector< _bnet_ * > workingSet_
Threads IBayesNet.
std::vector< BNInferenceEngine * > l_inferenceEngine_
Threads BNInferenceEngine.
std::vector< VarMod2BNsMap< GUM_SCALAR > * > l_optimalNet_
Threads optimal IBayesNet.
_margis_ l_marginalMax_
Threads upper marginals, one per thread.
std::vector< List< const Tensor< GUM_SCALAR > * > * > workingSetE_
Threads evidence.

References gum::credal::InferenceEngine< GUM_SCALAR >::eraseAllEvidence(), eraseAllEvidence(), l_clusters_, l_evidence_, l_expectationMax_, l_expectationMin_, l_inferenceEngine_, l_marginalMax_, l_marginalMin_, l_marginalSets_, l_modal_, l_optimalNet_, gum::credal::InferenceEngine< GUM_SCALAR >::storeBNOpt_, gum::credal::InferenceEngine< GUM_SCALAR >::storeVertices_, workingSet_, and workingSetE_.

Referenced by eraseAllEvidence().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ expectationMax() [1/2]

template<GUM_Numeric GUM_SCALAR>
const GUM_SCALAR & gum::credal::InferenceEngine< GUM_SCALAR >::expectationMax ( const NodeId id) const
inherited

Get the upper expectation of a given node id.

Parameters
idThe node id which upper expectation we want.
Returns
A constant reference to this node upper expectation.

Definition at line 473 of file inferenceEngine_tpl.h.

473 {
474 return expectationMax_[id];
475 }

References expectationMax_.

◆ expectationMax() [2/2]

template<GUM_Numeric GUM_SCALAR>
const GUM_SCALAR & gum::credal::InferenceEngine< GUM_SCALAR >::expectationMax ( std::string_view varName) const
inherited

Get the upper expectation of a given variable name.

Parameters
varNameThe variable name which upper expectation we want.
Returns
A constant reference to this variable upper expectation.

Definition at line 463 of file inferenceEngine_tpl.h.

463 {
464 return expectationMax_[credalNet_->current_bn().idFromName(varName)];
465 }

References credalNet_, and expectationMax_.

◆ expectationMin() [1/2]

template<GUM_Numeric GUM_SCALAR>
const GUM_SCALAR & gum::credal::InferenceEngine< GUM_SCALAR >::expectationMin ( const NodeId id) const
inherited

Get the lower expectation of a given node id.

Parameters
idThe node id which lower expectation we want.
Returns
A constant reference to this node lower expectation.

Definition at line 468 of file inferenceEngine_tpl.h.

468 {
469 return expectationMin_[id];
470 }

References expectationMin_.

◆ expectationMin() [2/2]

template<GUM_Numeric GUM_SCALAR>
const GUM_SCALAR & gum::credal::InferenceEngine< GUM_SCALAR >::expectationMin ( std::string_view varName) const
inherited

Get the lower expectation of a given variable name.

Parameters
varNameThe variable name which lower expectation we want.
Returns
A constant reference to this variable lower expectation.

Definition at line 457 of file inferenceEngine_tpl.h.

457 {
458 return expectationMin_[credalNet_->current_bn().idFromName(varName)];
459 }

References credalNet_, and expectationMin_.

◆ expFusion_()

template<GUM_Numeric GUM_SCALAR, class BNInferenceEngine>
void gum::credal::MultipleInferenceEngine< GUM_SCALAR, BNInferenceEngine >::expFusion_ ( )
protected

Fusion of threads expectations.

Definition at line 576 of file multipleInferenceEngine_tpl.h.

576 {
577 // don't create threads if there are no modalities to compute expectations
578 if (this->modal_.empty()) return;
579
580 // compute the max number of threads to use (avoid nested threads)
583 : 1; // no nested multithreading
584
585 // we can compute expectations from vertices of the final credal set
587 // create the function to be executed by the threads
588 auto threadedExec = [this](const std::size_t this_thread,
593 std::string var_name = workingSet_[work_index]->variable(i).name();
594 auto delim = var_name.find_first_of("_");
595 var_name = var_name.substr(0, delim);
596
597 if (!l_modal_[work_index].exists(var_name)) continue;
598
599 for (const auto& vertex: _infE_::marginalSets_[i]) {
600 GUM_SCALAR exp = 0;
601 Size vsize = Size(vertex.size());
602
603 for (Size mod = 0; mod < vsize; mod++)
605
607
609 }
610 }
611 };
612
613 const Size working_size = workingSet_.size();
615 if (!this->l_modal_[work_index].empty()) {
616 // compute the ranges over which the threads will work
617 const auto nsize = workingSet_[work_index]->size();
619 const auto ranges
622 }
623 }
624
625 return;
626 }
627
628 // create the function to be executed by the threads
629 auto threadedExec = [this](const std::size_t this_thread,
634 std::string var_name = workingSet_[work_index]->variable(i).name();
635 auto delim = var_name.find_first_of("_");
636 var_name = var_name.substr(0, delim);
637
638 if (!l_modal_[work_index].exists(var_name)) continue;
639
641
642 for (Idx tId = 0; tId < tsize; tId++) {
643 if (l_expectationMax_[tId][i] > this->expectationMax_[i])
645
646 if (l_expectationMin_[tId][i] < this->expectationMin_[i])
648 } // end of : each thread
649 } // end of : each variable
650 };
651
652 const Size working_size = workingSet_.size();
654 if (!this->l_modal_[work_index].empty()) {
655 const auto nsize = Size(workingSet_[work_index]->size());
657 const auto ranges
660 }
661 }
662 }
credalSet marginalSets_
Credal sets vertices, if enabled.
std::vector< std::pair< Idx, Idx > > dispatchRangeToThreads(const Idx beg, const Idx end, const unsigned int nb_threads)
returns a vector equally splitting elements of a range among threads
Definition threads.cpp:76

References gum::dispatchRangeToThreads(), gum::threadsSTL::ThreadExecutor::execute(), gum::credal::InferenceEngine< GUM_SCALAR >::expectationMax_, gum::credal::InferenceEngine< GUM_SCALAR >::expectationMin_, expFusion_(), gum::ThreadNumberManager::getNumberOfThreads(), l_expectationMax_, l_expectationMin_, l_modal_, gum::credal::InferenceEngine< GUM_SCALAR >::marginalSets_, gum::credal::InferenceEngine< GUM_SCALAR >::modal_, gum::threadsSTL::ThreadExecutor::nbRunningThreadsExecutors(), gum::credal::InferenceEngine< GUM_SCALAR >::storeVertices_, and workingSet_.

Referenced by expFusion_().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ getApproximationSchemeMsg()

template<GUM_Numeric GUM_SCALAR>
const std::string gum::credal::InferenceEngine< GUM_SCALAR >::getApproximationSchemeMsg ( )
inherited

Get approximation scheme state.

Returns
A constant string about approximation scheme state.

Definition at line 1208 of file inferenceEngine_tpl.h.

1208 {
1209 return this->messageApproximationScheme();
1210 }

References gum::IApproximationSchemeConfiguration::messageApproximationScheme().

Here is the call graph for this function:

◆ getNumberOfThreads()

Size gum::ThreadNumberManager::getNumberOfThreads ( ) const
nodiscardoverridevirtualinherited

◆ getT0Cluster()

template<GUM_Numeric GUM_SCALAR>
const NodeProperty< std::vector< NodeId > > & gum::credal::InferenceEngine< GUM_SCALAR >::getT0Cluster ( ) const
inherited

Get the t0_ cluster.

Returns
A constant reference to the t0_ cluster.

Definition at line 968 of file inferenceEngine_tpl.h.

968 {
969 return t0_;
970 }
cluster t0_
Clusters of nodes used with dynamic networks.

References t0_.

◆ getT1Cluster()

template<GUM_Numeric GUM_SCALAR>
const NodeProperty< std::vector< NodeId > > & gum::credal::InferenceEngine< GUM_SCALAR >::getT1Cluster ( ) const
inherited

Get the t1_ cluster.

Returns
A constant reference to the t1_ cluster.

Definition at line 974 of file inferenceEngine_tpl.h.

974 {
975 return t1_;
976 }
cluster t1_
Clusters of nodes used with dynamic networks.

References t1_.

◆ getVarMod2BNsMap()

template<GUM_Numeric GUM_SCALAR>
VarMod2BNsMap< GUM_SCALAR > * gum::credal::InferenceEngine< GUM_SCALAR >::getVarMod2BNsMap ( )
inherited

Get optimum IBayesNet.

Returns
A pointer to the optimal net object.

Definition at line 164 of file inferenceEngine_tpl.h.

164 {
165 return &dbnOpt_;
166 }
VarMod2BNsMap< GUM_SCALAR > dbnOpt_
Object used to efficiently store optimal bayes net during inference, for some algorithms.

References dbnOpt_.

◆ history()

INLINE const std::vector< double > & gum::ApproximationScheme::history ( ) const
overridevirtualinherited

Returns the scheme history.

Returns
Returns the scheme history.
Exceptions
OperationNotAllowedRaised if the scheme did not performed or if verbosity is set to false.

Implements gum::IApproximationSchemeConfiguration.

Definition at line 179 of file approximationScheme_inl.h.

179 {
181 GUM_ERROR(OperationNotAllowed, "state of the approximation scheme is udefined")
182 }
183
184 if (!verbosity()) GUM_ERROR(OperationNotAllowed, "No history when verbosity=false")
185
186 return history_;
187 }

References GUM_ERROR, stateApproximationScheme(), and gum::IApproximationSchemeConfiguration::Undefined.

Here is the call graph for this function:

◆ initApproximationScheme()

INLINE void gum::ApproximationScheme::initApproximationScheme ( )
inherited

Initialise the scheme.

Definition at line 190 of file approximationScheme_inl.h.

190 {
192 current_step_ = 0;
194 history_.clear();
195 timer_.reset();
196 }

References ApproximationScheme(), gum::IApproximationSchemeConfiguration::Continue, current_state_, current_step_, and initApproximationScheme().

Referenced by gum::GibbsBNdistance< GUM_SCALAR >::computeKL_(), gum::MCBNDistance< GUM_SCALAR >::computeKL_(), initApproximationScheme(), gum::learning::GreedyHillClimbing::learnStructure(), gum::learning::GreedyThickThinning::learnStructure(), gum::learning::LocalSearchWithTabuList::learnStructure(), gum::SamplingInference< GUM_SCALAR >::loopApproxInference_(), gum::credal::CNLoopyPropagation< GUM_SCALAR >::makeInference(), and gum::SamplingInference< GUM_SCALAR >::onStateChanged_().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ initExpectations_()

template<GUM_Numeric GUM_SCALAR>
void gum::credal::InferenceEngine< GUM_SCALAR >::initExpectations_ ( )
protectedinherited

Initialize lower and upper expectations before inference, with the lower expectation being initialized on the highest modality and the upper expectation being initialized on the lowest modality.

Definition at line 680 of file inferenceEngine_tpl.h.

680 {
681 expectationMin_.clear();
682 expectationMax_.clear();
683
684 if (modal_.empty()) return;
685
686 for (auto node: credalNet_->current_bn().nodes()) {
688
689 var_name = credalNet_->current_bn().variable(node).name();
690 auto delim = var_name.find_first_of("_");
691 var_name = var_name.substr(0, delim);
692
693 auto p_modal = modal_.tryGet(var_name);
694 if (!p_modal) continue;
695
696 expectationMin_.insert(node, p_modal->back());
697 expectationMax_.insert(node, p_modal->front());
698 }
699 }

References credalNet_, expectationMax_, expectationMin_, and modal_.

Referenced by eraseAllEvidence().

Here is the caller graph for this function:

◆ initMarginals_()

template<GUM_Numeric GUM_SCALAR>
void gum::credal::InferenceEngine< GUM_SCALAR >::initMarginals_ ( )
protectedinherited

Initialize lower and upper old marginals and marginals before inference, with the lower marginal being 1 and the upper 0.

Definition at line 644 of file inferenceEngine_tpl.h.

644 {
645 marginalMin_.clear();
646 marginalMax_.clear();
647 oldMarginalMin_.clear();
648 oldMarginalMax_.clear();
649
650 for (auto node: credalNet_->current_bn().nodes()) {
651 auto dSize = credalNet_->current_bn().variable(node).domainSize();
654
657 }
658
659 // now that we know the sizes of marginalMin_ and marginalMax_, we can
660 // dispatch their processes to the threads
662 }
void dispatchMarginalsToThreads_()
computes Vector threadRanges_, that assigns some part of marginalMin_ and marginalMax_ to the threads

References credalNet_, dispatchMarginalsToThreads_(), marginalMax_, marginalMin_, oldMarginalMax_, and oldMarginalMin_.

Referenced by InferenceEngine(), and eraseAllEvidence().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ initMarginalSets_()

template<GUM_Numeric GUM_SCALAR>
void gum::credal::InferenceEngine< GUM_SCALAR >::initMarginalSets_ ( )
protectedinherited

Initialize credal set vertices with empty sets.

Definition at line 665 of file inferenceEngine_tpl.h.

665 {
666 marginalSets_.clear();
667
668 if (!storeVertices_) return;
669
670 for (auto node: credalNet_->current_bn().nodes())
672 }

References credalNet_, marginalSets_, and storeVertices_.

Referenced by eraseAllEvidence(), and storeVertices().

Here is the caller graph for this function:

◆ initThreadsData_()

template<GUM_Numeric GUM_SCALAR, class BNInferenceEngine>
void gum::credal::MultipleInferenceEngine< GUM_SCALAR, BNInferenceEngine >::initThreadsData_ ( const Size & num_threads,
const bool _storeVertices_,
const bool _storeBNOpt_ )
protected

Initialize threads data.

Parameters
num_threadsThe number of threads.
_storeVertices_True if vertices should be stored, False otherwise.
_storeBNOpt_True if optimal IBayesNet should be stored, false otherwise.

Definition at line 63 of file multipleInferenceEngine_tpl.h.

66 {
67 workingSet_.clear();
68 workingSet_.resize(num_threads, nullptr);
69 workingSetE_.clear();
70 workingSetE_.resize(num_threads, nullptr);
71
72 l_marginalMin_.clear();
74 l_marginalMax_.clear();
76 l_expectationMin_.clear();
78 l_expectationMax_.clear();
80
81 l_clusters_.clear();
83
84 if (_storeVertices_) {
85 l_marginalSets_.clear();
87 }
88
89 if (_storeBNOpt_) {
90 for (Size ptr = 0; ptr < this->l_optimalNet_.size(); ptr++)
91 if (this->l_optimalNet_[ptr] != nullptr) delete l_optimalNet_[ptr];
92
93 l_optimalNet_.clear();
95 }
96
97 l_modal_.clear();
98 l_modal_.resize(num_threads);
99
101 this->oldMarginalMin_ = this->marginalMin_;
102 this->oldMarginalMax_.clear();
103 this->oldMarginalMax_ = this->marginalMax_;
104
105 // init the random number generators
106 generators_.clear();
107 generators_.resize(num_threads);
109 for (auto& generator: generators_) {
110 generator.seed(seed);
111 seed = generator();
112 }
113 }
std::vector< std::mt19937 > generators_
the generators used for computing random values
unsigned int currentRandomGeneratorValue()
returns the current generator's value

References l_clusters_, l_expectationMax_, l_expectationMin_, l_marginalMax_, l_marginalMin_, l_marginalSets_, l_modal_, l_optimalNet_, gum::credal::InferenceEngine< GUM_SCALAR >::marginalMax_, gum::credal::InferenceEngine< GUM_SCALAR >::marginalMin_, gum::credal::InferenceEngine< GUM_SCALAR >::oldMarginalMax_, gum::credal::InferenceEngine< GUM_SCALAR >::oldMarginalMin_, workingSet_, and workingSetE_.

◆ insertEvidence() [1/2]

template<GUM_Numeric GUM_SCALAR>
void gum::credal::InferenceEngine< GUM_SCALAR >::insertEvidence ( const NodeProperty< std::vector< GUM_SCALAR > > & evidence)
inherited

Insert evidence from Property.

Parameters
evidenceThe on nodes Property containing likelihoods.

Definition at line 268 of file inferenceEngine_tpl.h.

269 {
270 if (!evidence_.empty()) evidence_.clear();
271
272 // use cbegin() to get const_iterator when available in aGrUM hashtables
273 for (const auto& elt: evidence) {
274 if (!credalNet_->current_bn().exists(elt.first)) continue;
275
276 evidence_.insert(elt.first, elt.second);
277 }
278
279 // forces the computation of the begin iterator to avoid subsequent data races
280 // @TODO make HashTableConstIterator constructors thread safe
281 evidence_.begin();
282 }

References credalNet_, and evidence_.

◆ insertEvidence() [2/2]

template<GUM_Numeric GUM_SCALAR>
void gum::credal::InferenceEngine< GUM_SCALAR >::insertEvidence ( const std::map< std::string, std::vector< GUM_SCALAR > > & eviMap)
inherited

Insert evidence from map.

Parameters
eviMapThe map variable name - likelihood.

Definition at line 247 of file inferenceEngine_tpl.h.

248 {
249 if (!evidence_.empty()) evidence_.clear();
250
251 for (auto it = eviMap.cbegin(), theEnd = eviMap.cend(); it != theEnd; ++it) {
252 if (!credalNet_->current_bn().exists(it->first)) continue;
253
254 NodeId id = credalNet_->current_bn().idFromName(it->first);
255
256 evidence_.insert(id, it->second);
257 }
258
259 // forces the computation of the begin iterator to avoid subsequent data races
260 // @TODO make HashTableConstIterator constructors thread safe
261 evidence_.begin();
262 }

References credalNet_, and evidence_.

◆ insertEvidenceFile()

template<GUM_Numeric GUM_SCALAR>
void gum::credal::InferenceEngine< GUM_SCALAR >::insertEvidenceFile ( std::string_view path)
virtualinherited

Insert evidence from file.

Parameters
pathThe path to the evidence file.

Reimplemented in gum::credal::CNLoopyPropagation< GUM_SCALAR >, and gum::credal::CNMonteCarloSampling< GUM_SCALAR, BNInferenceEngine >.

Definition at line 285 of file inferenceEngine_tpl.h.

285 {
287
288 if (!evi_stream.good()) {
290 "void InferenceEngine< GUM_SCALAR "
291 ">::insertEvidence(const std::string & path) : could not "
292 "open input file : "
293 << path);
294 }
295
296 if (!evidence_.empty()) evidence_.clear();
297
299 char * cstr, *p;
300
301 while (evi_stream.good() && std::strcmp(line.c_str(), "[EVIDENCE]") != 0) {
303 }
304
305 while (evi_stream.good()) {
307
308 if (std::strcmp(line.c_str(), "[QUERY]") == 0) break;
309
310 if (line.size() == 0) continue;
311
312 cstr = new char[line.size() + 1];
313 strcpy(cstr, line.c_str());
314
315 p = strtok(cstr, " ");
316 tmp = p;
317
318 // if user input is wrong
319 NodeId node = -1;
320
321 if (!credalNet_->current_bn().exists(tmp)) continue;
322 node = credalNet_->current_bn().idFromName(tmp);
323
325 p = strtok(nullptr, " ");
326
327 while (p != nullptr) {
328 values.push_back(GUM_SCALAR(atof(p)));
329 p = strtok(nullptr, " ");
330 } // end of : line
331
332 evidence_.insert(node, values);
333
334 delete[] p;
335 delete[] cstr;
336 } // end of : file
337
338 evi_stream.close();
339
340 // forces the computation of the begin iterator to avoid subsequent data races
341 // @TODO make HashTableConstIterator constructors thread safe
342 evidence_.begin();
343 }

References evidence_, and GUM_ERROR.

Referenced by gum::credal::CNLoopyPropagation< GUM_SCALAR >::insertEvidenceFile(), and gum::credal::CNMonteCarloSampling< GUM_SCALAR, BNInferenceEngine >::insertEvidenceFile().

Here is the caller graph for this function:

◆ insertModals()

template<GUM_Numeric GUM_SCALAR>
void gum::credal::InferenceEngine< GUM_SCALAR >::insertModals ( const std::map< std::string, std::vector< GUM_SCALAR > > & modals)
inherited

Insert variables modalities from map to compute expectations.

Parameters
modalsThe map variable name - modalities.

Definition at line 216 of file inferenceEngine_tpl.h.

217 {
218 if (!modal_.empty()) modal_.clear();
219
220 for (auto it = modals.cbegin(), theEnd = modals.cend(); it != theEnd; ++it) {
221 if (!credalNet_->current_bn().exists(it->first)) continue;
222
223 NodeId id = credalNet_->current_bn().idFromName(it->first);
224
225 // check that modals are net compatible
226 auto dSize = credalNet_->current_bn().variable(id).domainSize();
227
228 if (dSize != it->second.size()) continue;
229
230 // GUM_ERROR(OperationNotAllowed, "void InferenceEngine< GUM_SCALAR
231 // >::insertModals( const std::map< std::string, std::vector< GUM_SCALAR
232 // > >
233 // &modals) : modalities does not respect variable cardinality : " <<
234 // credalNet_->current_bn().variable( id ).name() << " : " << dSize << "
235 // != "
236 // << it->second.size());
237
238 modal_.insert(it->first, it->second); //[ it->first ] = it->second;
239 }
240
241 //_modal = modals;
242
244 }
void initExpectations_()
Initialize lower and upper expectations before inference, with the lower expectation being initialize...

References credalNet_, and modal_.

◆ insertModalsFile()

template<GUM_Numeric GUM_SCALAR>
void gum::credal::InferenceEngine< GUM_SCALAR >::insertModalsFile ( std::string_view path)
inherited

Insert variables modalities from file to compute expectations.

Parameters
pathThe path to the modalities file.

Definition at line 169 of file inferenceEngine_tpl.h.

169 {
171
172 if (!mod_stream.good()) {
174 "void InferenceEngine< GUM_SCALAR "
175 ">::insertModals(const std::string & path) : "
176 "could not open input file : "
177 << path);
178 }
179
180 if (!modal_.empty()) modal_.clear();
181
183 char * cstr, *p;
184
185 while (mod_stream.good()) {
187
188 if (line.size() == 0) continue;
189
190 cstr = new char[line.size() + 1];
191 strcpy(cstr, line.c_str());
192
193 p = strtok(cstr, " ");
194 tmp = p;
195
197 p = strtok(nullptr, " ");
198
199 while (p != nullptr) {
200 values.push_back(GUM_SCALAR(atof(p)));
201 p = strtok(nullptr, " ");
202 } // end of : line
203
204 modal_.insert(tmp, values); //[tmp] = values;
205
206 delete[] p;
207 delete[] cstr;
208 } // end of : file
209
210 mod_stream.close();
211
213 }

References GUM_ERROR, and modal_.

◆ insertQuery()

template<GUM_Numeric GUM_SCALAR>
void gum::credal::InferenceEngine< GUM_SCALAR >::insertQuery ( const NodeProperty< std::vector< bool > > & query)
inherited

Insert query variables and states from Property.

Parameters
queryThe on nodes Property containing queried variables states.

Definition at line 346 of file inferenceEngine_tpl.h.

347 {
348 if (!query_.empty()) query_.clear();
349
350 for (const auto& elt: query) {
351 if (!credalNet_->current_bn().exists(elt.first)) continue;
352
353 query_.insert(elt.first, elt.second);
354 }
355 }
NodeProperty< std::vector< bool > > query
query query_
Holds the query nodes states.

References query_.

◆ insertQueryFile()

template<GUM_Numeric GUM_SCALAR>
void gum::credal::InferenceEngine< GUM_SCALAR >::insertQueryFile ( std::string_view path)
inherited

Insert query variables states from file.

Parameters
pathThe path to the query file.

Definition at line 358 of file inferenceEngine_tpl.h.

358 {
360
361 if (!evi_stream.good()) {
363 "void InferenceEngine< GUM_SCALAR >::insertQuery(const "
364 "std::string & path) : could not open input file : "
365 << path);
366 }
367
368 if (!query_.empty()) query_.clear();
369
371 char * cstr, *p;
372
373 while (evi_stream.good() && std::strcmp(line.c_str(), "[QUERY]") != 0) {
375 }
376
377 while (evi_stream.good()) {
379
380 if (std::strcmp(line.c_str(), "[EVIDENCE]") == 0) break;
381
382 if (line.size() == 0) continue;
383
384 cstr = new char[line.size() + 1];
385 strcpy(cstr, line.c_str());
386
387 p = strtok(cstr, " ");
388 tmp = p;
389
390 // if user input is wrong
391 NodeId node = -1;
392
393 if (!credalNet_->current_bn().exists(tmp)) continue;
394 node = credalNet_->current_bn().idFromName(tmp);
395
396 auto dSize = credalNet_->current_bn().variable(node).domainSize();
397
398 p = strtok(nullptr, " ");
399
400 if (p == nullptr) {
401 query_.insert(node, std::vector< bool >(dSize, true));
402 } else {
404
405 while (p != nullptr) {
406 if ((Size)atoi(p) >= dSize)
408 "void InferenceEngine< GUM_SCALAR "
409 ">::insertQuery(const std::string & path) : "
410 "query modality is higher or equal to "
411 "cardinality");
412
413 values[atoi(p)] = true;
414 p = strtok(nullptr, " ");
415 } // end of : line
416
417 query_.insert(node, values);
418 }
419
420 delete[] p;
421 delete[] cstr;
422 } // end of : file
423
424 evi_stream.close();
425 }

References GUM_ERROR.

◆ isEnabledEpsilon()

INLINE bool gum::ApproximationScheme::isEnabledEpsilon ( ) const
overridevirtualinherited

Returns true if stopping criterion on epsilon is enabled, false otherwise.

Returns
Returns true if stopping criterion on epsilon is enabled, false otherwise.

Implements gum::IApproximationSchemeConfiguration.

Definition at line 82 of file approximationScheme_inl.h.

82{ return enabled_eps_; }

References enabled_eps_.

◆ isEnabledMaxIter()

INLINE bool gum::ApproximationScheme::isEnabledMaxIter ( ) const
overridevirtualinherited

Returns true if stopping criterion on max iterations is enabled, false otherwise.

Returns
Returns true if stopping criterion on max iterations is enabled, false otherwise.

Implements gum::IApproximationSchemeConfiguration.

Definition at line 123 of file approximationScheme_inl.h.

123{ return enabled_max_iter_; }

References enabled_max_iter_.

◆ isEnabledMaxTime()

INLINE bool gum::ApproximationScheme::isEnabledMaxTime ( ) const
overridevirtualinherited

Returns true if stopping criterion on timeout is enabled, false otherwise.

Returns
Returns true if stopping criterion on timeout is enabled, false otherwise.

Implements gum::IApproximationSchemeConfiguration.

Definition at line 147 of file approximationScheme_inl.h.

147{ return enabled_max_time_; }

References enabled_max_time_.

◆ isEnabledMinEpsilonRate()

INLINE bool gum::ApproximationScheme::isEnabledMinEpsilonRate ( ) const
overridevirtualinherited

Returns true if stopping criterion on epsilon rate is enabled, false otherwise.

Returns
Returns true if stopping criterion on epsilon rate is enabled, false otherwise.

Implements gum::IApproximationSchemeConfiguration.

Definition at line 103 of file approximationScheme_inl.h.

103{ return enabled_min_rate_eps_; }

References enabled_min_rate_eps_.

Referenced by gum::GibbsBNdistance< GUM_SCALAR >::computeKL_(), and gum::MCBNDistance< GUM_SCALAR >::computeKL_().

Here is the caller graph for this function:

◆ isGumNumberOfThreadsOverriden()

bool gum::ThreadNumberManager::isGumNumberOfThreadsOverriden ( ) const
nodiscardoverridevirtualinherited

indicates whether the class containing this ThreadNumberManager set its own number of threads

Implements gum::IThreadNumberManager.

Referenced by gum::learning::IBNLearner::createParamEstimator_(), and gum::learning::IBNLearner::createScore_().

Here is the caller graph for this function:

◆ makeInference()

template<GUM_Numeric GUM_SCALAR, class BNInferenceEngine>
void gum::credal::MultipleInferenceEngine< GUM_SCALAR, BNInferenceEngine >::makeInference ( )
overridepure virtual

To be redefined by each credal net algorithm.

Starts the inference.

Implements gum::credal::InferenceEngine< GUM_SCALAR >.

Implemented in gum::credal::CNMonteCarloSampling< GUM_SCALAR, BNInferenceEngine >.

◆ marginalMax() [1/2]

template<GUM_Numeric GUM_SCALAR>
gum::Tensor< GUM_SCALAR > gum::credal::InferenceEngine< GUM_SCALAR >::marginalMax ( const NodeId id) const
inherited

Get the upper marginals of a given node id.

Parameters
idThe node id which upper marginals we want.
Returns
A constant reference to this node upper marginals.

Definition at line 448 of file inferenceEngine_tpl.h.

448 {
450 res.add(credalNet_->current_bn().variable(id));
451 res.fillWith(marginalMax_[id]);
452 return res;
453 }

Referenced by marginalMax().

Here is the caller graph for this function:

◆ marginalMax() [2/2]

template<GUM_Numeric GUM_SCALAR>
Tensor< GUM_SCALAR > gum::credal::InferenceEngine< GUM_SCALAR >::marginalMax ( std::string_view varName) const
inherited

Get the upper marginals of a given variable name.

Parameters
varNameThe variable name which upper marginals we want.
Returns
A constant reference to this variable upper marginals.

Definition at line 435 of file inferenceEngine_tpl.h.

435 {
436 return marginalMax(credalNet_->current_bn().idFromName(varName));
437 }
Tensor< GUM_SCALAR > marginalMax(const NodeId id) const
Get the upper marginals of a given node id.

References credalNet_, and marginalMax().

Here is the call graph for this function:

◆ marginalMin() [1/2]

template<GUM_Numeric GUM_SCALAR>
gum::Tensor< GUM_SCALAR > gum::credal::InferenceEngine< GUM_SCALAR >::marginalMin ( const NodeId id) const
inherited

Get the lower marginals of a given node id.

Parameters
idThe node id which lower marginals we want.
Returns
A constant reference to this node lower marginals.

Definition at line 440 of file inferenceEngine_tpl.h.

440 {
442 res.add(credalNet_->current_bn().variable(id));
443 res.fillWith(marginalMin_[id]);
444 return res;
445 }

References credalNet_, and marginalMin_.

Referenced by marginalMin().

Here is the caller graph for this function:

◆ marginalMin() [2/2]

template<GUM_Numeric GUM_SCALAR>
Tensor< GUM_SCALAR > gum::credal::InferenceEngine< GUM_SCALAR >::marginalMin ( std::string_view varName) const
inherited

Get the lower marginals of a given variable name.

Parameters
varNameThe variable name which lower marginals we want.
Returns
A constant reference to this variable lower marginals.

Definition at line 429 of file inferenceEngine_tpl.h.

429 {
430 return marginalMin(credalNet_->current_bn().idFromName(varName));
431 }
Tensor< GUM_SCALAR > marginalMin(const NodeId id) const
Get the lower marginals of a given node id.

References credalNet_, and marginalMin().

Here is the call graph for this function:

◆ maxIter()

INLINE Size gum::ApproximationScheme::maxIter ( ) const
overridevirtualinherited

Returns the criterion on number of iterations.

Returns
Returns the criterion on number of iterations.

Implements gum::IApproximationSchemeConfiguration.

Definition at line 113 of file approximationScheme_inl.h.

113{ return max_iter_; }

References max_iter_.

◆ maxTime()

INLINE double gum::ApproximationScheme::maxTime ( ) const
overridevirtualinherited

Returns the timeout (in seconds).

Returns
Returns the timeout (in seconds).

Implements gum::IApproximationSchemeConfiguration.

Definition at line 134 of file approximationScheme_inl.h.

134{ return max_time_; }

References max_time_.

◆ messageApproximationScheme()

std::string gum::IApproximationSchemeConfiguration::messageApproximationScheme ( ) const
inherited

Returns the approximation scheme message.

Returns
Returns the approximation scheme message.

Definition at line 64 of file IApproximationSchemeConfiguration.cpp.

64 {
65 switch (stateApproximationScheme()) {
66 case ApproximationSchemeSTATE::Continue : return "in progress";
67
69 return std::format("stopped with epsilon={}", epsilon());
70
72 return std::format("stopped with rate={}", minEpsilonRate());
73
75 return std::format("stopped with max iteration={}", maxIter());
76
78 return std::format("stopped with timeout={}", maxTime());
79
80 case ApproximationSchemeSTATE::Stopped : return "stopped on request";
81
82 case ApproximationSchemeSTATE::Undefined : return "undefined state";
83 }
84 return {};
85 }
virtual double epsilon() const =0
Returns the value of epsilon.
virtual ApproximationSchemeSTATE stateApproximationScheme() const =0
Returns the approximation scheme state.
virtual double minEpsilonRate() const =0
Returns the value of the minimal epsilon rate.
virtual Size maxIter() const =0
Returns the criterion on number of iterations.
virtual double maxTime() const =0
Returns the timeout (in seconds).

References Continue, Epsilon, epsilon(), Limit, maxIter(), maxTime(), minEpsilonRate(), Rate, stateApproximationScheme(), Stopped, TimeLimit, and Undefined.

Referenced by gum::ApproximationScheme::continueApproximationScheme(), gum::credal::InferenceEngine< GUM_SCALAR >::getApproximationSchemeMsg(), and gum::credal::MultipleInferenceEngine< GUM_SCALAR, LazyPropagation< GUM_SCALAR > >::isEnabledMaxIter().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ minEpsilonRate()

INLINE double gum::ApproximationScheme::minEpsilonRate ( ) const
overridevirtualinherited

Returns the value of the minimal epsilon rate.

Returns
Returns the value of the minimal epsilon rate.

Implements gum::IApproximationSchemeConfiguration.

Definition at line 93 of file approximationScheme_inl.h.

93{ return min_rate_eps_; }

References min_rate_eps_.

◆ nbrIterations()

INLINE Size gum::ApproximationScheme::nbrIterations ( ) const
overridevirtualinherited

Returns the number of iterations.

Returns
Returns the number of iterations.
Exceptions
OperationNotAllowedRaised if the scheme did not perform.

Implements gum::IApproximationSchemeConfiguration.

Definition at line 170 of file approximationScheme_inl.h.

170 {
172 GUM_ERROR(OperationNotAllowed, "state of the approximation scheme is undefined")
173 }
174
175 return current_step_;
176 }

References current_step_, GUM_ERROR, stateApproximationScheme(), and gum::IApproximationSchemeConfiguration::Undefined.

Referenced by gum::GibbsBNdistance< GUM_SCALAR >::computeKL_(), and gum::MCBNDistance< GUM_SCALAR >::computeKL_().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ optFusion_()

template<GUM_Numeric GUM_SCALAR, class BNInferenceEngine>
void gum::credal::MultipleInferenceEngine< GUM_SCALAR, BNInferenceEngine >::optFusion_ ( )
protected

Fusion of threads optimal IBayesNet.

Definition at line 735 of file multipleInferenceEngine_tpl.h.

735 {
736 using dBN = std::vector< bool >;
737
738 Size nsize = Size(workingSet_[0]->size());
739
740 // no parallel insert in hash-tables (OptBN)
741 for (Idx i = 0; i < nsize; i++) {
742 // we don't store anything for observed variables
743 if (_infE_::evidence_.exists(i)) continue;
744
746
747 for (Size j = 0; j < dSize; j++) {
748 // go through all threads
750 keymin[0] = i;
751 keymin[1] = j;
752 keymin[2] = 0;
754 keymax[2] = 1;
755
756 Size tsize = Size(l_marginalMin_.size());
757
758 for (Size tId = 0; tId < tsize; tId++) {
759 if (l_marginalMin_[tId][i][j] == this->marginalMin_[i][j]) {
760 const std::vector< dBN* >& tOpts = l_optimalNet_[tId]->getBNOptsFromKey(keymin);
761 Size osize = Size(tOpts.size());
762
763 for (Size bn = 0; bn < osize; bn++) {
764 _infE_::dbnOpt_.insert(*tOpts[bn], keymin);
765 }
766 }
767
768 if (l_marginalMax_[tId][i][j] == this->marginalMax_[i][j]) {
769 const std::vector< dBN* >& tOpts = l_optimalNet_[tId]->getBNOptsFromKey(keymax);
770 Size osize = Size(tOpts.size());
771
772 for (Size bn = 0; bn < osize; bn++) {
773 _infE_::dbnOpt_.insert(*tOpts[bn], keymax);
774 }
775 }
776 } // end of : all threads
777 } // end of : all modalities
778 } // end of : all variables
779 }

References gum::credal::InferenceEngine< GUM_SCALAR >::dbnOpt_, gum::credal::InferenceEngine< GUM_SCALAR >::evidence_, l_marginalMax_, l_marginalMin_, l_optimalNet_, gum::credal::InferenceEngine< GUM_SCALAR >::marginalMax_, gum::credal::InferenceEngine< GUM_SCALAR >::marginalMin_, optFusion_(), and workingSet_.

Referenced by optFusion_().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ periodSize()

INLINE Size gum::ApproximationScheme::periodSize ( ) const
overridevirtualinherited

Returns the period size.

Returns
Returns the period size.

Implements gum::IApproximationSchemeConfiguration.

Definition at line 156 of file approximationScheme_inl.h.

156{ return period_size_; }
Size period_size_
Checking criteria frequency.

References period_size_.

◆ remainingBurnIn()

INLINE Size gum::ApproximationScheme::remainingBurnIn ( ) const
inherited

Returns the remaining burn in.

Returns
Returns the remaining burn in.

Definition at line 213 of file approximationScheme_inl.h.

213 {
214 if (burn_in_ > current_step_) {
215 return burn_in_ - current_step_;
216 } else {
217 return 0;
218 }
219 }
Size burn_in_
Number of iterations before checking stopping criteria.

References burn_in_, and current_step_.

◆ repetitiveInd()

template<GUM_Numeric GUM_SCALAR>
bool gum::credal::InferenceEngine< GUM_SCALAR >::repetitiveInd ( ) const
inherited

Get the current independence status.

Returns
True if repetitive, False otherwise.

Definition at line 143 of file inferenceEngine_tpl.h.

143 {
144 return repetitiveInd_;
145 }
bool repetitiveInd_
True if using repetitive independence ( dynamic network only ), False otherwise.

References repetitiveInd_.

◆ repetitiveInit_()

template<GUM_Numeric GUM_SCALAR>
void gum::credal::InferenceEngine< GUM_SCALAR >::repetitiveInit_ ( )
protectedinherited

Initialize t0_ and t1_ clusters.

Definition at line 763 of file inferenceEngine_tpl.h.

763 {
764 timeSteps_ = 0;
765 t0_.clear();
766 t1_.clear();
767
768 // t = 0 vars belongs to t0_ as keys
769 for (auto node: credalNet_->current_bn().internalDag().nodes()) {
770 std::string var_name = credalNet_->current_bn().variable(node).name();
771 auto delim = var_name.find_first_of("_");
772
773 if (delim > var_name.size()) {
775 "void InferenceEngine< GUM_SCALAR "
776 ">::repetitiveInit_() : the network does not "
777 "appear to be dynamic");
778 }
779
780 std::string time_step = var_name.substr(delim + 1, 1);
781
782 if (time_step.compare("0") == 0) t0_.insert(node, std::vector< NodeId >());
783 }
784
785 // t = 1 vars belongs to either t0_ as member value or t1_ as keys
786 for (const auto& node: credalNet_->current_bn().internalDag().nodes()) {
787 std::string var_name = credalNet_->current_bn().variable(node).name();
788 auto delim = var_name.find_first_of("_");
789 std::string time_step = var_name.substr(delim + 1, var_name.size());
790 var_name = var_name.substr(0, delim);
791 delim = time_step.find_first_of("_");
792 time_step = time_step.substr(0, delim);
793
794 if (time_step.compare("1") == 0) {
795 bool found = false;
796
797 for (const auto& elt: t0_) {
798 std::string var_0_name = credalNet_->current_bn().variable(elt.first).name();
799 delim = var_0_name.find_first_of("_");
800 var_0_name = var_0_name.substr(0, delim);
801
802 if (var_name.compare(var_0_name) == 0) {
803 const Tensor< GUM_SCALAR >* tensor(&credalNet_->current_bn().cpt(node));
804 const Tensor< GUM_SCALAR >* tensor2(&credalNet_->current_bn().cpt(elt.first));
805
806 if (tensor->domainSize() == tensor2->domainSize()) t0_[elt.first].push_back(node);
807 else t1_.insert(node, std::vector< NodeId >());
808
809 found = true;
810 break;
811 }
812 }
813
814 if (!found) { t1_.insert(node, std::vector< NodeId >()); }
815 }
816 }
817
818 // t > 1 vars belongs to either t0_ or t1_ as member value
819 // remember timeSteps_
820 for (auto node: credalNet_->current_bn().internalDag().nodes()) {
821 std::string var_name = credalNet_->current_bn().variable(node).name();
822 auto delim = var_name.find_first_of("_");
823 std::string time_step = var_name.substr(delim + 1, var_name.size());
824 var_name = var_name.substr(0, delim);
825 delim = time_step.find_first_of("_");
826 time_step = time_step.substr(0, delim);
827
828 if (time_step.compare("0") != 0 && time_step.compare("1") != 0) {
829 // keep max time_step
830 if (atoi(time_step.c_str()) > timeSteps_) timeSteps_ = atoi(time_step.c_str());
831
833 bool found = false;
834
835 for (const auto& elt: t0_) {
836 std::string var_0_name = credalNet_->current_bn().variable(elt.first).name();
837 delim = var_0_name.find_first_of("_");
838 var_0_name = var_0_name.substr(0, delim);
839
840 if (var_name.compare(var_0_name) == 0) {
841 const Tensor< GUM_SCALAR >* tensor(&credalNet_->current_bn().cpt(node));
842 const Tensor< GUM_SCALAR >* tensor2(&credalNet_->current_bn().cpt(elt.first));
843
844 if (tensor->domainSize() == tensor2->domainSize()) {
845 t0_[elt.first].push_back(node);
846 found = true;
847 break;
848 }
849 }
850 }
851
852 if (!found) {
853 for (const auto& elt: t1_) {
854 std::string var_0_name = credalNet_->current_bn().variable(elt.first).name();
855 auto delim = var_0_name.find_first_of("_");
856 var_0_name = var_0_name.substr(0, delim);
857
858 if (var_name.compare(var_0_name) == 0) {
859 const Tensor< GUM_SCALAR >* tensor(&credalNet_->current_bn().cpt(node));
860 const Tensor< GUM_SCALAR >* tensor2(&credalNet_->current_bn().cpt(elt.first));
861
862 if (tensor->domainSize() == tensor2->domainSize()) {
863 t1_[elt.first].push_back(node);
864 break;
865 }
866 }
867 }
868 }
869 }
870 }
871 }
int timeSteps_
The number of time steps of this network (only useful for dynamic networks).

References credalNet_, GUM_ERROR, t0_, t1_, and timeSteps_.

Referenced by setRepetitiveInd().

Here is the caller graph for this function:

◆ saveExpectations()

template<GUM_Numeric GUM_SCALAR>
void gum::credal::InferenceEngine< GUM_SCALAR >::saveExpectations ( std::string_view path) const
inherited

Saves expectations to file.

Parameters
pathThe path to the file to be used.

Definition at line 541 of file inferenceEngine_tpl.h.

541 {
542 if (dynamicExpMin_.empty()) //_modal.empty())
543 return;
544
545 // else not here, to keep the const (natural with a saving process)
546 // else if(dynamicExpMin_.empty() || dynamicExpMax_.empty())
547 //_dynamicExpectations(); // works with or without a dynamic network
548
550
551 if (!m_stream.good()) {
553 "void InferenceEngine< GUM_SCALAR "
554 ">::saveExpectations(const std::string & path) : could "
555 "not open output file : "
556 << path);
557 }
558
559 for (const auto& elt: dynamicExpMin_) {
560 m_stream << elt.first; // it->first;
561
562 // iterates over a vector
563 for (const auto& elt2: elt.second) {
564 m_stream << " " << elt2;
565 }
566
568 }
569
570 for (const auto& elt: dynamicExpMax_) {
571 m_stream << elt.first;
572
573 // iterates over a vector
574 for (const auto& elt2: elt.second) {
575 m_stream << " " << elt2;
576 }
577
579 }
580
581 m_stream.close();
582 }

◆ saveMarginals()

template<GUM_Numeric GUM_SCALAR>
void gum::credal::InferenceEngine< GUM_SCALAR >::saveMarginals ( std::string_view path) const
inherited

Saves marginals to file.

Parameters
pathThe path to the file to be used.

Definition at line 518 of file inferenceEngine_tpl.h.

518 {
520
521 if (!m_stream.good()) {
523 "void InferenceEngine< GUM_SCALAR >::saveMarginals(const "
524 "std::string & path) const : could not open output file "
525 ": " << path);
526 }
527
528 for (const auto& elt: marginalMin_) {
529 Size esize = Size(elt.second.size());
530
531 for (Size mod = 0; mod < esize; mod++) {
532 m_stream << credalNet_->current_bn().variable(elt.first).name() << " " << mod << " "
533 << (elt.second)[mod] << " " << marginalMax_[elt.first][mod] << std::endl;
534 }
535 }
536
537 m_stream.close();
538 }

◆ saveVertices()

template<GUM_Numeric GUM_SCALAR>
void gum::credal::InferenceEngine< GUM_SCALAR >::saveVertices ( std::string_view path) const
inherited

Saves vertices to file.

Parameters
pathThe path to the file to be used.

Definition at line 613 of file inferenceEngine_tpl.h.

613 {
615
616 if (!m_stream.good()) {
618 "void InferenceEngine< GUM_SCALAR >::saveVertices(const "
619 "std::string & path) : could not open outpul file : "
620 << path);
621 }
622
623 for (const auto& elt: marginalSets_) {
624 m_stream << credalNet_->current_bn().variable(elt.first).name() << std::endl;
625
626 for (const auto& elt2: elt.second) {
627 m_stream << "[";
628 bool first = true;
629
630 for (const auto& elt3: elt2) {
631 if (!first) { m_stream << ","; }
632 first = false;
633 m_stream << elt3;
634 }
635
636 m_stream << "]\n";
637 }
638 }
639
640 m_stream.close();
641 }

References credalNet_, GUM_ERROR, and marginalSets_.

◆ setEpsilon()

INLINE void gum::ApproximationScheme::setEpsilon ( double eps)
overridevirtualinherited

Given that we approximate f(t), stopping criterion on |f(t+1)-f(t)|.

If the criterion was disabled it will be enabled.

Parameters
epsThe new epsilon value.
Exceptions
OutOfBoundsRaised if eps < 0.

Implements gum::IApproximationSchemeConfiguration.

Reimplemented in gum::learning::EMApproximationScheme.

Definition at line 64 of file approximationScheme_inl.h.

64 {
65 if (eps < 0.) { GUM_ERROR(OutOfBounds, "eps should be >=0") }
66
67 eps_ = eps;
68 enabled_eps_ = true;
69 }

References enabled_eps_, eps_, and GUM_ERROR.

Referenced by gum::GibbsBNdistance< GUM_SCALAR >::GibbsBNdistance(), gum::GibbsBNdistance< GUM_SCALAR >::GibbsBNdistance(), gum::GibbsSampling< GUM_SCALAR >::GibbsSampling(), gum::learning::GreedyHillClimbing::GreedyHillClimbing(), gum::learning::GreedyThickThinning::GreedyThickThinning(), gum::MCBNDistance< GUM_SCALAR >::MCBNDistance(), gum::MCBNDistance< GUM_SCALAR >::MCBNDistance(), gum::SamplingInference< GUM_SCALAR >::SamplingInference(), and gum::learning::EMApproximationScheme::setEpsilon().

Here is the caller graph for this function:

◆ setMaxIter()

INLINE void gum::ApproximationScheme::setMaxIter ( Size max)
overridevirtualinherited

Stopping criterion on number of iterations.

If the criterion was disabled it will be enabled.

Parameters
maxThe maximum number of iterations.
Exceptions
OutOfBoundsRaised if max <= 1.

Implements gum::IApproximationSchemeConfiguration.

Definition at line 106 of file approximationScheme_inl.h.

106 {
107 if (max < 1) { GUM_ERROR(OutOfBounds, "max should be >=1") }
108 max_iter_ = max;
109 enabled_max_iter_ = true;
110 }

References enabled_max_iter_, GUM_ERROR, and max_iter_.

Referenced by gum::GibbsBNdistance< GUM_SCALAR >::GibbsBNdistance(), gum::GibbsBNdistance< GUM_SCALAR >::GibbsBNdistance(), gum::MCBNDistance< GUM_SCALAR >::MCBNDistance(), gum::MCBNDistance< GUM_SCALAR >::MCBNDistance(), and gum::SamplingInference< GUM_SCALAR >::SamplingInference().

Here is the caller graph for this function:

◆ setMaxTime()

INLINE void gum::ApproximationScheme::setMaxTime ( double timeout)
overridevirtualinherited

Stopping criterion on timeout.

If the criterion was disabled it will be enabled.

Parameters
timeoutThe timeout value in seconds.
Exceptions
OutOfBoundsRaised if timeout <= 0.0.

Implements gum::IApproximationSchemeConfiguration.

Definition at line 127 of file approximationScheme_inl.h.

127 {
128 if (timeout <= 0.) { GUM_ERROR(OutOfBounds, "timeout should be >0.") }
129 max_time_ = timeout;
130 enabled_max_time_ = true;
131 }

References enabled_max_time_, GUM_ERROR, and max_time_.

Referenced by gum::GibbsBNdistance< GUM_SCALAR >::GibbsBNdistance(), gum::GibbsBNdistance< GUM_SCALAR >::GibbsBNdistance(), gum::MCBNDistance< GUM_SCALAR >::MCBNDistance(), gum::MCBNDistance< GUM_SCALAR >::MCBNDistance(), and gum::SamplingInference< GUM_SCALAR >::SamplingInference().

Here is the caller graph for this function:

◆ setMinEpsilonRate()

INLINE void gum::ApproximationScheme::setMinEpsilonRate ( double rate)
overridevirtualinherited

Given that we approximate f(t), stopping criterion on d/dt(|f(t+1)-f(t)|).

If the criterion was disabled it will be enabled

Parameters
rateThe minimal epsilon rate.
Exceptions
OutOfBoundsif rate<0

Implements gum::IApproximationSchemeConfiguration.

Reimplemented in gum::learning::EMApproximationScheme.

Definition at line 85 of file approximationScheme_inl.h.

85 {
86 if (rate < 0) { GUM_ERROR(OutOfBounds, "rate should be >=0") }
87
88 min_rate_eps_ = rate;
90 }

References enabled_min_rate_eps_, GUM_ERROR, and min_rate_eps_.

Referenced by gum::GibbsBNdistance< GUM_SCALAR >::GibbsBNdistance(), gum::GibbsBNdistance< GUM_SCALAR >::GibbsBNdistance(), gum::GibbsSampling< GUM_SCALAR >::GibbsSampling(), gum::MCBNDistance< GUM_SCALAR >::MCBNDistance(), gum::MCBNDistance< GUM_SCALAR >::MCBNDistance(), gum::SamplingInference< GUM_SCALAR >::SamplingInference(), and gum::learning::EMApproximationScheme::setMinEpsilonRate().

Here is the caller graph for this function:

◆ setNumberOfThreads()

void gum::ThreadNumberManager::setNumberOfThreads ( Size nb)
overridevirtualinherited

sets the number max of threads to be used by the class containing this ThreadNumberManager

Parameters
nbthe number of threads to be used. If this number is set to 0, then it is defaulted to aGrUM's number of threads

Implements gum::IThreadNumberManager.

Referenced by gum::learning::IBNLearner::setNumberOfThreads(), and gum::ScheduledInference::setNumberOfThreads().

Here is the caller graph for this function:

◆ setPeriodSize()

INLINE void gum::ApproximationScheme::setPeriodSize ( Size p)
overridevirtualinherited

How many samples between two stopping is enable.

Parameters
pThe new period value.
Exceptions
OutOfBoundsRaised if p < 1.

Implements gum::IApproximationSchemeConfiguration.

Definition at line 150 of file approximationScheme_inl.h.

150 {
151 if (p < 1) { GUM_ERROR(OutOfBounds, "p should be >=1") }
152
153 period_size_ = p;
154 }

References GUM_ERROR.

Referenced by gum::GibbsBNdistance< GUM_SCALAR >::GibbsBNdistance(), gum::GibbsBNdistance< GUM_SCALAR >::GibbsBNdistance(), gum::MCBNDistance< GUM_SCALAR >::MCBNDistance(), gum::MCBNDistance< GUM_SCALAR >::MCBNDistance(), and gum::SamplingInference< GUM_SCALAR >::SamplingInference().

Here is the caller graph for this function:

◆ setRepetitiveInd()

template<GUM_Numeric GUM_SCALAR>
void gum::credal::InferenceEngine< GUM_SCALAR >::setRepetitiveInd ( const bool repetitive)
inherited
Parameters
repetitiveTrue if repetitive independence is to be used, false otherwise. Only useful with dynamic networks.

Definition at line 134 of file inferenceEngine_tpl.h.

134 {
137
138 // do not compute clusters more than once
140 }
void repetitiveInit_()
Initialize t0_ and t1_ clusters.

References repetitiveInd_, and repetitiveInit_().

Here is the call graph for this function:

◆ setVerbosity()

INLINE void gum::ApproximationScheme::setVerbosity ( bool v)
overridevirtualinherited

Set the verbosity on (true) or off (false).

Parameters
vIf true, then verbosity is turned on.

Implements gum::IApproximationSchemeConfiguration.

Definition at line 159 of file approximationScheme_inl.h.

159{ verbosity_ = v; }
bool verbosity_
If true, verbosity is enabled.

References verbosity_.

Referenced by gum::GibbsBNdistance< GUM_SCALAR >::GibbsBNdistance(), gum::GibbsBNdistance< GUM_SCALAR >::GibbsBNdistance(), gum::MCBNDistance< GUM_SCALAR >::MCBNDistance(), gum::MCBNDistance< GUM_SCALAR >::MCBNDistance(), and gum::SamplingInference< GUM_SCALAR >::SamplingInference().

Here is the caller graph for this function:

◆ startOfPeriod()

INLINE bool gum::ApproximationScheme::startOfPeriod ( ) const
inherited

Returns true if we are at the beginning of a period (compute error is mandatory).

Returns
Returns true if we are at the beginning of a period (compute error is mandatory).

Definition at line 200 of file approximationScheme_inl.h.

200 {
201 if (current_step_ < burn_in_) { return false; }
202
203 if (period_size_ == 1) { return true; }
204
205 return ((current_step_ - burn_in_) % period_size_ == 0);
206 }

Referenced by continueApproximationScheme().

Here is the caller graph for this function:

◆ stateApproximationScheme()

INLINE IApproximationSchemeConfiguration::ApproximationSchemeSTATE gum::ApproximationScheme::stateApproximationScheme ( ) const
overridevirtualinherited

Returns the approximation scheme state.

Returns
Returns the approximation scheme state.

Implements gum::IApproximationSchemeConfiguration.

Definition at line 165 of file approximationScheme_inl.h.

165 {
166 return current_state_;
167 }

Referenced by continueApproximationScheme(), history(), and nbrIterations().

Here is the caller graph for this function:

◆ stopApproximationScheme()

INLINE void gum::ApproximationScheme::stopApproximationScheme ( )
inherited

Stop the approximation scheme.

Definition at line 222 of file approximationScheme_inl.h.

Referenced by gum::learning::GreedyHillClimbing::learnStructure(), gum::learning::GreedyThickThinning::learnStructure(), gum::learning::LocalSearchWithTabuList::learnStructure(), and gum::credal::CNLoopyPropagation< GUM_SCALAR >::makeInferenceNodeToNeighbours_().

Here is the caller graph for this function:

◆ stopScheme_()

INLINE void gum::ApproximationScheme::stopScheme_ ( ApproximationSchemeSTATE new_state)
privateinherited

Stop the scheme given a new state.

Parameters
new_stateThe scheme new state.

Definition at line 231 of file approximationScheme_inl.h.

231 {
232 if (new_state == ApproximationSchemeSTATE::Continue) { return; }
233
234 if (new_state == ApproximationSchemeSTATE::Undefined) { return; }
235
236 current_state_ = new_state;
237 timer_.pause();
238
239 if (onStop.hasListener()) { GUM_EMIT1(onStop, messageApproximationScheme()); }
240 }
Signaler< std::string_view > onStop
Criteria messageApproximationScheme.
#define GUM_EMIT1(signal, arg1)
Definition signaler.h:289

References gum::IApproximationSchemeConfiguration::Continue, and gum::IApproximationSchemeConfiguration::Undefined.

Referenced by continueApproximationScheme(), and gum::credal::MultipleInferenceEngine< GUM_SCALAR, LazyPropagation< GUM_SCALAR > >::disableMaxIter().

Here is the caller graph for this function:

◆ storeBNOpt() [1/2]

template<GUM_Numeric GUM_SCALAR>
bool gum::credal::InferenceEngine< GUM_SCALAR >::storeBNOpt ( ) const
inherited
Returns
True if optimal bayes net are stored for each variable and each modality, False otherwise.

Definition at line 159 of file inferenceEngine_tpl.h.

159 {
160 return storeBNOpt_;
161 }

References storeBNOpt_.

◆ storeBNOpt() [2/2]

template<GUM_Numeric GUM_SCALAR>
void gum::credal::InferenceEngine< GUM_SCALAR >::storeBNOpt ( const bool value)
inherited
Parameters
valueTrue if optimal Bayesian networks are to be stored for each variable and each modality.

Definition at line 122 of file inferenceEngine_tpl.h.

122 {
124 }

References storeBNOpt_.

◆ storeVertices() [1/2]

template<GUM_Numeric GUM_SCALAR>
bool gum::credal::InferenceEngine< GUM_SCALAR >::storeVertices ( ) const
inherited

Get the number of iterations without changes used to stop some algorithms.

Returns
the number of iterations. int iterStop () const;
True if vertice are stored, False otherwise.

Definition at line 154 of file inferenceEngine_tpl.h.

154 {
155 return storeVertices_;
156 }

References storeVertices_.

◆ storeVertices() [2/2]

template<GUM_Numeric GUM_SCALAR>
void gum::credal::InferenceEngine< GUM_SCALAR >::storeVertices ( const bool value)
inherited
Parameters
valueTrue if vertices are to be stored, false otherwise.

Definition at line 127 of file inferenceEngine_tpl.h.

127 {
129
131 }
void initMarginalSets_()
Initialize credal set vertices with empty sets.

References initMarginalSets_(), and storeVertices_.

Here is the call graph for this function:

◆ toString()

template<GUM_Numeric GUM_SCALAR>
std::string gum::credal::InferenceEngine< GUM_SCALAR >::toString ( ) const
inherited

Print all nodes marginals to standart output.

Definition at line 585 of file inferenceEngine_tpl.h.

585 {
587 output << std::endl;
588
589 // use cbegin() when available
590 for (const auto& elt: marginalMin_) {
591 Size esize = Size(elt.second.size());
592
593 for (Size mod = 0; mod < esize; mod++) {
594 output << "P(" << credalNet_->current_bn().variable(elt.first).name() << "=" << mod
595 << "|e) = [ ";
596 output << marginalMin_[elt.first][mod] << ", " << marginalMax_[elt.first][mod] << " ]";
597
598 if (!query_.empty()) {
599 if (auto p_query = query_.tryGet(elt.first); p_query && (*p_query)[mod])
600 output << " QUERY";
601 }
602
603 output << std::endl;
604 }
605
606 output << std::endl;
607 }
608
609 return output.str();
610 }

◆ updateApproximationScheme()

INLINE void gum::ApproximationScheme::updateApproximationScheme ( unsigned int incr = 1)
inherited

◆ updateCredalSets_()

template<GUM_Numeric GUM_SCALAR>
void gum::credal::InferenceEngine< GUM_SCALAR >::updateCredalSets_ ( const NodeId & id,
const std::vector< GUM_SCALAR > & vertex,
const bool & elimRedund = false )
inlineprotectedinherited

Given a node id and one of it's possible vertex, update it's credal set.

To maximise efficiency, don't pass a vertex we know is inside the polytope (i.e. not at an extreme value for any modality)

Parameters
idThe id of the node to be updated
vertexA (tensor) vertex of the node credal set
elimRedundremove redundant vertex (inside a facet)

Definition at line 896 of file inferenceEngine_tpl.h.

898 {
900 auto dsize = vertex.size();
901
902 bool eq = true;
903
904 for (auto it = nodeCredalSet.cbegin(), itEnd = nodeCredalSet.cend(); it != itEnd; ++it) {
905 eq = true;
906
907 for (Size i = 0; i < dsize; i++) {
908 if (std::fabs(vertex[i] - (*it)[i]) > 1e-6) {
909 eq = false;
910 break;
911 }
912 }
913
914 if (eq) break;
915 }
916
917 if (!eq || nodeCredalSet.size() == 0) {
918 nodeCredalSet.push_back(vertex);
919 } else return;
920
921 // because of next lambda return condition
922 if (nodeCredalSet.size() == 1) return;
923
924 // check that the point and all previously added ones are not inside the
925 // actual
926 // polytope
927 auto itEnd = std::remove_if(
928 nodeCredalSet.begin(),
929 nodeCredalSet.end(),
930 [&](const std::vector< GUM_SCALAR >& v) -> bool {
931 for (auto jt = v.cbegin(),
932 jtEnd = v.cend(),
933 minIt = marginalMin_[id].cbegin(),
934 minItEnd = marginalMin_[id].cend(),
935 maxIt = marginalMax_[id].cbegin(),
936 maxItEnd = marginalMax_[id].cend();
937 jt != jtEnd && minIt != minItEnd && maxIt != maxItEnd;
938 ++jt, ++minIt, ++maxIt) {
939 if ((std::fabs(*jt - *minIt) < 1e-6 || std::fabs(*jt - *maxIt) < 1e-6)
940 && std::fabs(*minIt - *maxIt) > 1e-6)
941 return false;
942 }
943 return true;
944 });
945
946 nodeCredalSet.erase(itEnd, nodeCredalSet.end());
947
948 // we need at least 2 points to make a convex combination
949 if (!elimRedund || nodeCredalSet.size() <= 2) return;
950
951 // there may be points not inside the polytope but on one of it's facet,
952 // meaning it's still a convex combination of vertices of this facet. Here
953 // we
954 // need lrs.
956 lrsWrapper.setUpV((unsigned int)dsize, (unsigned int)(nodeCredalSet.size()));
957
958 for (const auto& vtx: nodeCredalSet)
960
961 lrsWrapper.elimRedundVrep();
962
963 marginalSets_[id] = lrsWrapper.getOutput();
964 }

References marginalSets_.

Referenced by gum::credal::CNLoopyPropagation< GUM_SCALAR >::computeExpectations_(), and gum::credal::MultipleInferenceEngine< GUM_SCALAR, BNInferenceEngine >::verticesFusion_().

Here is the caller graph for this function:

◆ updateExpectations_()

template<GUM_Numeric GUM_SCALAR>
void gum::credal::InferenceEngine< GUM_SCALAR >::updateExpectations_ ( const NodeId & id,
const std::vector< GUM_SCALAR > & vertex )
inlineprotectedinherited

Given a node id and one of it's possible vertex obtained during inference, update this node lower and upper expectations.

Parameters
idThe id of the node to be updated
vertexA (tensor) vertex of the node credal set

Definition at line 874 of file inferenceEngine_tpl.h.

876 {
877 std::string var_name = credalNet_->current_bn().variable(id).name();
878 auto delim = var_name.find_first_of("_");
879
880 var_name = var_name.substr(0, delim);
881
882 if (auto p_modal = modal_.tryGet(var_name)) {
883 GUM_SCALAR exp = 0;
884 auto vsize = vertex.size();
885
886 for (Size mod = 0; mod < vsize; mod++)
887 exp += vertex[mod] * (*p_modal)[mod];
888
890
892 }
893 }

References credalNet_, expectationMax_, expectationMin_, and modal_.

Referenced by gum::credal::CNLoopyPropagation< GUM_SCALAR >::computeExpectations_().

Here is the caller graph for this function:

◆ updateMarginals_()

template<GUM_Numeric GUM_SCALAR, class BNInferenceEngine>
void gum::credal::MultipleInferenceEngine< GUM_SCALAR, BNInferenceEngine >::updateMarginals_ ( )
inlineprotected

Fusion of threads marginals.

Definition at line 294 of file multipleInferenceEngine_tpl.h.

294 {
295 // compute the max number of threads to use (avoid nested threads)
297 ? this->threadRanges_.size() - 1
298 : 1; // no nested multithreading
299
300 // create the function to be executed by the threads
301 auto threadedExec = [this](const std::size_t this_thread,
304 auto i = this->threadRanges_[this_thread].first;
305 auto j = this->threadRanges_[this_thread].second;
306 auto domain_size = this->marginalMax_[i].size();
307 const auto end_i = this->threadRanges_[this_thread + 1].first;
308 auto end_j = this->threadRanges_[this_thread + 1].second;
309 const auto marginalMax_size = this->marginalMax_.size();
310 const auto tsize = Size(l_marginalMin_.size());
311
312 while ((i < end_i) || (j < end_j)) {
313 // go through all work indices
314 for (Idx tId = 0; tId < tsize; tId++) {
315 if (l_marginalMin_[tId][i][j] < this->marginalMin_[i][j])
316 this->marginalMin_[i][j] = l_marginalMin_[tId][i][j];
317
318 if (l_marginalMax_[tId][i][j] > this->marginalMax_[i][j])
319 this->marginalMax_[i][j] = l_marginalMax_[tId][i][j];
320 }
321
322 if (++j == domain_size) {
323 j = 0;
324 ++i;
325 if (i < marginalMax_size) domain_size = this->marginalMax_[i].size();
326 }
327 }
328 };
329
330 // launch the threads
334 (nb_threads == 1)
335 ? std::vector< std::pair< NodeId, Idx > >{{0, 0}, {this->marginalMin_.size(), 0}}
336 : this->threadRanges_);
337 }

References gum::threadsSTL::ThreadExecutor::execute(), l_marginalMax_, l_marginalMin_, gum::credal::InferenceEngine< GUM_SCALAR >::marginalMax_, gum::credal::InferenceEngine< GUM_SCALAR >::marginalMin_, gum::threadsSTL::ThreadExecutor::nbRunningThreadsExecutors(), gum::credal::InferenceEngine< GUM_SCALAR >::threadRanges_, and updateMarginals_().

Referenced by updateMarginals_().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ updateOldMarginals_()

template<GUM_Numeric GUM_SCALAR, class BNInferenceEngine>
void gum::credal::MultipleInferenceEngine< GUM_SCALAR, BNInferenceEngine >::updateOldMarginals_ ( )
protected

Update old marginals (from current marginals).

Call this once to initialize old marginals (after burn-in for example) and then use computeEpsilon_ which does the same job but compute epsilon too.

Definition at line 473 of file multipleInferenceEngine_tpl.h.

473 {
474#pragma omp parallel
475 {
477 long nsize = long(workingSet_[threadId]->size());
478
479#pragma omp for
480
481 for (long i = 0; i < nsize; i++) {
483
484 for (Size j = 0; j < dSize; j++) {
485 Size tsize = Size(l_marginalMin_.size());
486
487 // go through all threads
488 for (Size tId = 0; tId < tsize; tId++) {
489 if (l_marginalMin_[tId][i][j] < this->oldMarginalMin_[i][j])
490 this->oldMarginalMin_[i][j] = l_marginalMin_[tId][i][j];
491
492 if (l_marginalMax_[tId][i][j] > this->oldMarginalMax_[i][j])
493 this->oldMarginalMax_[i][j] = l_marginalMax_[tId][i][j];
494 } // end of : all threads
495 } // end of : all modalities
496 } // end of : all variables
497 } // end of : parallel region
498 }
unsigned int getThreadNumber()
Get the calling thread id.

References gum::threadsOMP::getThreadNumber(), l_marginalMax_, l_marginalMin_, gum::credal::InferenceEngine< GUM_SCALAR >::oldMarginalMax_, gum::credal::InferenceEngine< GUM_SCALAR >::oldMarginalMin_, updateOldMarginals_(), and workingSet_.

Referenced by updateOldMarginals_().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ updateThread_()

template<GUM_Numeric GUM_SCALAR, class BNInferenceEngine>
bool gum::credal::MultipleInferenceEngine< GUM_SCALAR, BNInferenceEngine >::updateThread_ ( Size this_thread,
const NodeId & id,
const std::vector< GUM_SCALAR > & vertex,
const bool & elimRedund = false )
inlineprotected

Update thread information (marginals, expectations, IBayesNet, vertices) for a given node id.

Parameters
this_threadthe id of the thread executing this method
idThe id of the node to be updated.
vertexThe vertex.
elimRedundtrue if redundancy elimination is to be performed, false otherwise and by default.
Returns
True if the IBayesNet is kept (for now), False otherwise.

Definition at line 116 of file multipleInferenceEngine_tpl.h.

120 {
121 // save E(X) if we don't save vertices
123 std::string var_name = workingSet_[tId]->variable(id).name();
124 auto delim = var_name.find_first_of("_");
125 var_name = var_name.substr(0, delim);
126
127 if (l_modal_[tId].exists(var_name)) {
128 GUM_SCALAR exp = 0;
129 Size vsize = Size(vertex.size());
130
131 for (Size mod = 0; mod < vsize; mod++)
133
135
137 }
138 } // end of : if modal (map) not empty
139
140 bool newOne = false;
141 bool added = false;
142 bool result = false;
143 // for burn in, we need to keep checking on local marginals and not global
144 // ones
145 // (faster inference)
146 // we also don't want to store dbn for observed variables since there will
147 // be a
148 // huge number of them (probably all of them).
149 Size vsize = Size(vertex.size());
150
151 for (Size mod = 0; mod < vsize; mod++) {
152 if (vertex[mod] < l_marginalMin_[tId][id][mod]) {
154 newOne = true;
155
158 key[0] = id;
159 key[1] = mod;
160 key[2] = 0;
161
162 if (l_optimalNet_[tId]->insert(key, true)) result = true;
163 }
164 }
165
166 if (vertex[mod] > l_marginalMax_[tId][id][mod]) {
168 newOne = true;
169
172 key[0] = id;
173 key[1] = mod;
174 key[2] = 1;
175
176 if (l_optimalNet_[tId]->insert(key, true)) result = true;
177 }
178 } else if (vertex[mod] == l_marginalMin_[tId][id][mod]
179 || vertex[mod] == l_marginalMax_[tId][id][mod]) {
180 newOne = true;
181
183 && !_infE_::evidence_.exists(id)) {
185 key[0] = id;
186 key[1] = mod;
187 key[2] = 0;
188
189 if (l_optimalNet_[tId]->insert(key, false)) result = true;
190 }
191
193 && !_infE_::evidence_.exists(id)) {
195 key[0] = id;
196 key[1] = mod;
197 key[2] = 1;
198
199 if (l_optimalNet_[tId]->insert(key, false)) result = true;
200 }
201 }
202
203 // store point to compute credal set vertices.
204 // check for redundancy at each step or at the end ?
207 added = true;
208 }
209 }
210
211 // if all variables didn't get better marginals, we will delete
212 if (_infE_::storeBNOpt_ && result) return true;
213
214 return false;
215 }
void _updateThreadCredalSets_(Size this_thread, const NodeId &id, const std::vector< GUM_SCALAR > &vertex, const bool &elimRedund)
Ask for redundancy elimination of a node credal set of a calling thread.

References gum::credal::InferenceEngine< GUM_SCALAR >::evidence_, l_expectationMax_, l_expectationMin_, l_marginalMin_, l_modal_, gum::credal::InferenceEngine< GUM_SCALAR >::storeBNOpt_, gum::credal::InferenceEngine< GUM_SCALAR >::storeVertices_, and workingSet_.

◆ verbosity()

INLINE bool gum::ApproximationScheme::verbosity ( ) const
overridevirtualinherited

Returns true if verbosity is enabled.

Returns
Returns true if verbosity is enabled.

Implements gum::IApproximationSchemeConfiguration.

Definition at line 161 of file approximationScheme_inl.h.

161{ return verbosity_; }

References verbosity_.

Referenced by ApproximationScheme(), gum::learning::EMApproximationScheme::EMApproximationScheme(), and continueApproximationScheme().

Here is the caller graph for this function:

◆ vertices()

template<GUM_Numeric GUM_SCALAR>
const std::vector< std::vector< GUM_SCALAR > > & gum::credal::InferenceEngine< GUM_SCALAR >::vertices ( const NodeId id) const
inherited

Get the vertice of a given node id.

Parameters
idThe node id which vertice we want.
Returns
A constant reference to this node vertice.

Definition at line 513 of file inferenceEngine_tpl.h.

513 {
514 return marginalSets_[id];
515 }

References marginalSets_.

Referenced by gum::credal::CNLoopyPropagation< GUM_SCALAR >::computeExpectations_().

Here is the caller graph for this function:

◆ verticesFusion_()

template<GUM_Numeric GUM_SCALAR, class BNInferenceEngine>
void gum::credal::MultipleInferenceEngine< GUM_SCALAR, BNInferenceEngine >::verticesFusion_ ( )
protected
Deprecated
Fusion of threads vertices.

Definition at line 501 of file multipleInferenceEngine_tpl.h.

501 {
502 // don't create threads if there are no vertices saved
503 if (!_infE_::storeVertices_) return;
504
505 // compute the max number of threads to use (avoid nested threads)
508 : 1; // no nested multithreading
509
510 // create the function to be executed by the threads
511 Size tsize = Size(l_marginalMin_.size());
512 auto threadedExec = [this, tsize](const std::size_t this_thread,
517 // go through all threads
518 for (Size tId = 0; tId < tsize; ++tId) {
520
521 // for each vertex, if we are at any opt marginal, add it to the set
522 for (const auto& vtx: nodeThreadCredalSet) {
523 // we run redundancy elimination at each step because there could
524 // be 100000 threads and the set will be so huge...
525 // BUT not if vertices are of dimension 2 ! opt check and equality
526 // should be enough
527 _infE_::updateCredalSets_(i, vtx, (vtx.size() > 2) ? true : false);
528 } // end of : nodeThreadCredalSet
529 } // end of : all threads
530 } // end of : all variables
531 };
532
533 const Size working_size = workingSet_.size();
535 // compute the ranges over which the threads will work
536 const auto nsize = workingSet_[work_index]->size();
538 const auto ranges = gum::dispatchRangeToThreads(0, nsize, (unsigned int)(real_nb_threads));
540 }
541 }
void updateCredalSets_(const NodeId &id, const std::vector< GUM_SCALAR > &vertex, const bool &elimRedund=false)
Given a node id and one of it's possible vertex, update it's credal set.

References gum::dispatchRangeToThreads(), gum::threadsSTL::ThreadExecutor::execute(), gum::ThreadNumberManager::getNumberOfThreads(), l_marginalMin_, l_marginalSets_, gum::threadsSTL::ThreadExecutor::nbRunningThreadsExecutors(), gum::credal::InferenceEngine< GUM_SCALAR >::storeVertices_, gum::credal::InferenceEngine< GUM_SCALAR >::updateCredalSets_(), verticesFusion_(), and workingSet_.

Referenced by verticesFusion_().

Here is the call graph for this function:
Here is the caller graph for this function:

Member Data Documentation

◆ _nb_threads_

Size gum::ThreadNumberManager::_nb_threads_ {0}
privateinherited

the max number of threads used by the class

Definition at line 126 of file threadNumberManager.h.

126{0};

◆ burn_in_

Size gum::ApproximationScheme::burn_in_
protectedinherited

◆ credalNet_

◆ current_epsilon_

double gum::ApproximationScheme::current_epsilon_
protectedinherited

Current epsilon.

Definition at line 378 of file approximationScheme.h.

Referenced by continueApproximationScheme().

◆ current_rate_

double gum::ApproximationScheme::current_rate_
protectedinherited

Current rate.

Definition at line 384 of file approximationScheme.h.

Referenced by continueApproximationScheme().

◆ current_state_

ApproximationSchemeSTATE gum::ApproximationScheme::current_state_
protectedinherited

The current state.

Definition at line 393 of file approximationScheme.h.

Referenced by ApproximationScheme(), continueApproximationScheme(), and initApproximationScheme().

◆ current_step_

◆ dbnOpt_

template<GUM_Numeric GUM_SCALAR>
VarMod2BNsMap< GUM_SCALAR > gum::credal::InferenceEngine< GUM_SCALAR >::dbnOpt_
protectedinherited

Object used to efficiently store optimal bayes net during inference, for some algorithms.

Definition at line 160 of file inferenceEngine.h.

Referenced by InferenceEngine(), getVarMod2BNsMap(), and gum::credal::MultipleInferenceEngine< GUM_SCALAR, BNInferenceEngine >::optFusion_().

◆ dynamicExpMax_

template<GUM_Numeric GUM_SCALAR>
dynExpe gum::credal::InferenceEngine< GUM_SCALAR >::dynamicExpMax_
protectedinherited

Upper dynamic expectations.

If the network if not dynamic it's content is the same as expectationMax_.

Definition at line 113 of file inferenceEngine.h.

Referenced by dynamicExpectations_(), and eraseAllEvidence().

◆ dynamicExpMin_

template<GUM_Numeric GUM_SCALAR>
dynExpe gum::credal::InferenceEngine< GUM_SCALAR >::dynamicExpMin_
protectedinherited

Lower dynamic expectations.

If the network is not dynamic it's content is the same as expectationMin_.

Definition at line 110 of file inferenceEngine.h.

Referenced by dynamicExpectations_(), and eraseAllEvidence().

◆ enabled_eps_

bool gum::ApproximationScheme::enabled_eps_
protectedinherited

If true, the threshold convergence is enabled.

Definition at line 402 of file approximationScheme.h.

Referenced by ApproximationScheme(), continueApproximationScheme(), disableEpsilon(), enableEpsilon(), isEnabledEpsilon(), and setEpsilon().

◆ enabled_max_iter_

bool gum::ApproximationScheme::enabled_max_iter_
protectedinherited

If true, the maximum iterations stopping criterion is enabled.

Definition at line 420 of file approximationScheme.h.

Referenced by ApproximationScheme(), continueApproximationScheme(), disableMaxIter(), enableMaxIter(), isEnabledMaxIter(), and setMaxIter().

◆ enabled_max_time_

bool gum::ApproximationScheme::enabled_max_time_
protectedinherited

If true, the timeout is enabled.

Definition at line 414 of file approximationScheme.h.

Referenced by ApproximationScheme(), continueApproximationScheme(), disableMaxTime(), enableMaxTime(), isEnabledMaxTime(), and setMaxTime().

◆ enabled_min_rate_eps_

bool gum::ApproximationScheme::enabled_min_rate_eps_
protectedinherited

If true, the minimal threshold for epsilon rate is enabled.

Definition at line 408 of file approximationScheme.h.

Referenced by ApproximationScheme(), continueApproximationScheme(), disableMinEpsilonRate(), enableMinEpsilonRate(), isEnabledMinEpsilonRate(), and setMinEpsilonRate().

◆ eps_

double gum::ApproximationScheme::eps_
protectedinherited

Threshold for convergence.

Definition at line 399 of file approximationScheme.h.

Referenced by ApproximationScheme(), continueApproximationScheme(), epsilon(), and setEpsilon().

◆ evidence_

◆ expectationMax_

template<GUM_Numeric GUM_SCALAR>
expe gum::credal::InferenceEngine< GUM_SCALAR >::expectationMax_
protectedinherited

◆ expectationMin_

template<GUM_Numeric GUM_SCALAR>
expe gum::credal::InferenceEngine< GUM_SCALAR >::expectationMin_
protectedinherited

◆ generators_

template<GUM_Numeric GUM_SCALAR, class BNInferenceEngine>
std::vector< std::mt19937 > gum::credal::MultipleInferenceEngine< GUM_SCALAR, BNInferenceEngine >::generators_
protected

the generators used for computing random values

Definition at line 141 of file multipleInferenceEngine.h.

◆ history_

std::vector< double > gum::ApproximationScheme::history_
protectedinherited

The scheme history, used only if verbosity == true.

Definition at line 396 of file approximationScheme.h.

Referenced by continueApproximationScheme().

◆ l_clusters_

template<GUM_Numeric GUM_SCALAR, class BNInferenceEngine>
_clusters_ gum::credal::MultipleInferenceEngine< GUM_SCALAR, BNInferenceEngine >::l_clusters_
protected

◆ l_evidence_

template<GUM_Numeric GUM_SCALAR, class BNInferenceEngine>
_margis_ gum::credal::MultipleInferenceEngine< GUM_SCALAR, BNInferenceEngine >::l_evidence_
protected

Threads evidence.

Definition at line 125 of file multipleInferenceEngine.h.

Referenced by eraseAllEvidence().

◆ l_expectationMax_

template<GUM_Numeric GUM_SCALAR, class BNInferenceEngine>
_expes_ gum::credal::MultipleInferenceEngine< GUM_SCALAR, BNInferenceEngine >::l_expectationMax_
protected

Threads upper expectations, one per thread.

Definition at line 119 of file multipleInferenceEngine.h.

Referenced by eraseAllEvidence(), expFusion_(), initThreadsData_(), and updateThread_().

◆ l_expectationMin_

template<GUM_Numeric GUM_SCALAR, class BNInferenceEngine>
_expes_ gum::credal::MultipleInferenceEngine< GUM_SCALAR, BNInferenceEngine >::l_expectationMin_
protected

Threads lower expectations, one per thread.

Definition at line 117 of file multipleInferenceEngine.h.

Referenced by eraseAllEvidence(), expFusion_(), initThreadsData_(), and updateThread_().

◆ l_inferenceEngine_

template<GUM_Numeric GUM_SCALAR, class BNInferenceEngine>
std::vector< BNInferenceEngine* > gum::credal::MultipleInferenceEngine< GUM_SCALAR, BNInferenceEngine >::l_inferenceEngine_
protected

Threads BNInferenceEngine.

Definition at line 136 of file multipleInferenceEngine.h.

Referenced by eraseAllEvidence().

◆ l_marginalMax_

template<GUM_Numeric GUM_SCALAR, class BNInferenceEngine>
_margis_ gum::credal::MultipleInferenceEngine< GUM_SCALAR, BNInferenceEngine >::l_marginalMax_
protected

Threads upper marginals, one per thread.

Definition at line 115 of file multipleInferenceEngine.h.

Referenced by eraseAllEvidence(), initThreadsData_(), optFusion_(), updateMarginals_(), and updateOldMarginals_().

◆ l_marginalMin_

template<GUM_Numeric GUM_SCALAR, class BNInferenceEngine>
_margis_ gum::credal::MultipleInferenceEngine< GUM_SCALAR, BNInferenceEngine >::l_marginalMin_
protected

Threads lower marginals, one per thread.

Definition at line 113 of file multipleInferenceEngine.h.

Referenced by eraseAllEvidence(), initThreadsData_(), optFusion_(), updateMarginals_(), updateOldMarginals_(), updateThread_(), and verticesFusion_().

◆ l_marginalSets_

template<GUM_Numeric GUM_SCALAR, class BNInferenceEngine>
_credalSets_ gum::credal::MultipleInferenceEngine< GUM_SCALAR, BNInferenceEngine >::l_marginalSets_
protected

Threads vertices.

Definition at line 123 of file multipleInferenceEngine.h.

Referenced by eraseAllEvidence(), initThreadsData_(), and verticesFusion_().

◆ l_modal_

template<GUM_Numeric GUM_SCALAR, class BNInferenceEngine>
_modals_ gum::credal::MultipleInferenceEngine< GUM_SCALAR, BNInferenceEngine >::l_modal_
protected

Threads modalities.

Definition at line 121 of file multipleInferenceEngine.h.

Referenced by eraseAllEvidence(), expFusion_(), initThreadsData_(), and updateThread_().

◆ l_optimalNet_

template<GUM_Numeric GUM_SCALAR, class BNInferenceEngine>
std::vector< VarMod2BNsMap< GUM_SCALAR >* > gum::credal::MultipleInferenceEngine< GUM_SCALAR, BNInferenceEngine >::l_optimalNet_
protected

Threads optimal IBayesNet.

Definition at line 138 of file multipleInferenceEngine.h.

Referenced by eraseAllEvidence(), initThreadsData_(), and optFusion_().

◆ last_epsilon_

double gum::ApproximationScheme::last_epsilon_
protectedinherited

Last epsilon value.

Definition at line 381 of file approximationScheme.h.

Referenced by continueApproximationScheme().

◆ marginalMax_

◆ marginalMin_

◆ marginalSets_

template<GUM_Numeric GUM_SCALAR>
credalSet gum::credal::InferenceEngine< GUM_SCALAR >::marginalSets_
protectedinherited

◆ max_iter_

Size gum::ApproximationScheme::max_iter_
protectedinherited

The maximum iterations.

Definition at line 417 of file approximationScheme.h.

Referenced by ApproximationScheme(), continueApproximationScheme(), maxIter(), and setMaxIter().

◆ max_time_

double gum::ApproximationScheme::max_time_
protectedinherited

The timeout.

Definition at line 411 of file approximationScheme.h.

Referenced by ApproximationScheme(), continueApproximationScheme(), maxTime(), and setMaxTime().

◆ min_rate_eps_

double gum::ApproximationScheme::min_rate_eps_
protectedinherited

Threshold for the epsilon rate.

Definition at line 405 of file approximationScheme.h.

Referenced by ApproximationScheme(), continueApproximationScheme(), minEpsilonRate(), and setMinEpsilonRate().

◆ modal_

◆ oldMarginalMax_

◆ oldMarginalMin_

◆ onProgress

◆ onStop

Signaler< std::string_view > gum::IApproximationSchemeConfiguration::onStop
inherited

Criteria messageApproximationScheme.

Definition at line 84 of file IApproximationSchemeConfiguration.h.

Referenced by gum::learning::IBNLearner::distributeStop().

◆ period_size_

Size gum::ApproximationScheme::period_size_
protectedinherited

Checking criteria frequency.

Definition at line 426 of file approximationScheme.h.

Referenced by ApproximationScheme(), and periodSize().

◆ query_

template<GUM_Numeric GUM_SCALAR>
query gum::credal::InferenceEngine< GUM_SCALAR >::query_
protectedinherited

Holds the query nodes states.

Definition at line 121 of file inferenceEngine.h.

Referenced by eraseAllEvidence(), and insertQuery().

◆ repetitiveInd_

template<GUM_Numeric GUM_SCALAR>
bool gum::credal::InferenceEngine< GUM_SCALAR >::repetitiveInd_
protectedinherited

◆ storeBNOpt_

◆ storeVertices_

◆ t0_

template<GUM_Numeric GUM_SCALAR>
cluster gum::credal::InferenceEngine< GUM_SCALAR >::t0_
protectedinherited

Clusters of nodes used with dynamic networks.

Any node key in t0_ is present at \( t=0 \) and any node belonging to the node set of this key share the same CPT than the key. Used for sampling with repetitive independence.

Definition at line 129 of file inferenceEngine.h.

Referenced by gum::credal::CNMonteCarloSampling< GUM_SCALAR, BNInferenceEngine >::_mcThreadDataCopy_(), getT0Cluster(), and repetitiveInit_().

◆ t1_

template<GUM_Numeric GUM_SCALAR>
cluster gum::credal::InferenceEngine< GUM_SCALAR >::t1_
protectedinherited

Clusters of nodes used with dynamic networks.

Any node key in t1_ is present at \( t=1 \) and any node belonging to the node set of this key share the same CPT than the key. Used for sampling with repetitive independence.

Definition at line 136 of file inferenceEngine.h.

Referenced by gum::credal::CNMonteCarloSampling< GUM_SCALAR, BNInferenceEngine >::_mcThreadDataCopy_(), getT1Cluster(), and repetitiveInit_().

◆ threadMinimalNbOps_

template<GUM_Numeric GUM_SCALAR>
Size gum::credal::InferenceEngine< GUM_SCALAR >::threadMinimalNbOps_ {Size(20)}
protectedinherited

◆ threadRanges_

template<GUM_Numeric GUM_SCALAR>
std::vector< std::pair< NodeId, Idx > > gum::credal::InferenceEngine< GUM_SCALAR >::threadRanges_
protectedinherited

the ranges of elements of marginalMin_ and marginalMax_ processed by each thread

these ranges are stored into a vector of pairs (NodeId, Idx). For thread number i, the pair at index i is the beginning of the range that the thread will have to process: this is the part of the marginal distribution vector of node NodeId starting at index Idx. The pair at index i+1 is the end of this range (not included).

Warning
the size of threadRanges_ is the number of threads + 1.

Definition at line 172 of file inferenceEngine.h.

Referenced by computeEpsilon_(), gum::credal::MultipleInferenceEngine< GUM_SCALAR, BNInferenceEngine >::computeEpsilon_(), dispatchMarginalsToThreads_(), and gum::credal::MultipleInferenceEngine< GUM_SCALAR, BNInferenceEngine >::updateMarginals_().

◆ timer_

◆ timeSteps_

template<GUM_Numeric GUM_SCALAR>
int gum::credal::InferenceEngine< GUM_SCALAR >::timeSteps_
protectedinherited

The number of time steps of this network (only useful for dynamic networks).

Deprecated

Definition at line 179 of file inferenceEngine.h.

Referenced by repetitiveInit_().

◆ verbosity_

bool gum::ApproximationScheme::verbosity_
protectedinherited

If true, verbosity is enabled.

Definition at line 429 of file approximationScheme.h.

Referenced by ApproximationScheme(), setVerbosity(), and verbosity().

◆ workingSet_

template<GUM_Numeric GUM_SCALAR, class BNInferenceEngine>
std::vector< _bnet_* > gum::credal::MultipleInferenceEngine< GUM_SCALAR, BNInferenceEngine >::workingSet_
protected

◆ workingSetE_

template<GUM_Numeric GUM_SCALAR, class BNInferenceEngine>
std::vector< List< const Tensor< GUM_SCALAR >* >* > gum::credal::MultipleInferenceEngine< GUM_SCALAR, BNInferenceEngine >::workingSetE_
protected

Threads evidence.

Definition at line 133 of file multipleInferenceEngine.h.

Referenced by eraseAllEvidence(), and initThreadsData_().


The documentation for this class was generated from the following files: