aGrUM 3.3.2
a C++ library for (probabilistic) graphical models
gum::BayesNet< GUM_SCALAR > Class Template Reference

Class representing a Bayesian network. More...

#include <agrum/BN/BayesNet.h>

Inheritance diagram for gum::BayesNet< GUM_SCALAR >:
[legend]
Collaboration diagram for gum::BayesNet< GUM_SCALAR >:
[legend]

Public Member Functions

NodeId addNoisyAND (const DiscreteVariable &var, GUM_SCALAR external_weight, NodeId id)
 Add a variable, its associate node and a noisyAND implementation.
NodeId addNoisyAND (const DiscreteVariable &var, GUM_SCALAR external_weight)
 Add a variable, its associate node and a noisyAND implementation.
NodeId addLogit (const DiscreteVariable &var, GUM_SCALAR external_weight, NodeId id)
 Add a variable, its associate node and a Logit implementation.
NodeId addLogit (const DiscreteVariable &var, GUM_SCALAR external_weight)
 Add a variable, its associate node and a Logit implementation.
NodeId addOR (const DiscreteVariable &var)
 Add a variable, it's associate node and an OR implementation.
NodeId addAND (const DiscreteVariable &var)
 Add a variable, it's associate node and an AND implementation.
void addWeightedArc (NodeId tail, NodeId head, GUM_SCALAR causalWeight)
 Add an arc in the BN, and update arc.head's CPT.
void addWeightedArc (std::string_view tail, std::string_view head, GUM_SCALAR causalWeight)
 Add an arc in the BN, and update arc.head's CPT.
void generateCPTs () const
 randomly generates CPTs for a given structure
void generateCPT (NodeId node) const
 randomly generate CPT for a given node in a given structure
void generateCPT (std::string_view name) const
void changeTensor (NodeId id, Tensor< GUM_SCALAR > *newPot)
 change the CPT associated to nodeId to newPot delete the old CPT associated to nodeId.
void changeTensor (std::string_view name, Tensor< GUM_SCALAR > *newPot)
BayesNet< GUM_SCALAR > contextualize (const gum::Instantiation &observations, const gum::Instantiation &interventions) const
 create a contextual BN from this and a set of hard observations and hard interventions.
NodeId idFromName (std::string_view name) const override
 Returns the NodeId of a variable given its name.
const VariableNodeMap & variableNodeMap () const override
 Returns a constant reference to the VariableNodeMap of this model.
const DiscreteVariable & variable (NodeId id) const override
 Returns a constant reference over a variable given its node id.
NodeId nodeId (const DiscreteVariable &var) const override
 Returns the NodeId of a variable.
const DiscreteVariable & variableFromName (std::string_view name) const override
 Returns a constant reference over a variable given its name.
std::vector< std::string > check () const
 Check if the BayesNet is consistent (variables, CPT).
bool operator== (const IBayesNet< GUM_SCALAR > &from) const
 This operator compares 2 BNs !
Size dim () const
 Returns the dimension (the number of free parameters) in this bayes net.
Size maxVarDomainSize () const
GUM_SCALAR minParam () const
GUM_SCALAR maxParam () const
GUM_SCALAR minNonZeroParam () const
GUM_SCALAR maxNonOneParam () const
virtual std::string toDot () const
virtual std::string toDot (const dot::DotOptions &options) const
 A dot representation of this IBayesNet, with the options given by the caller.
std::string toString () const
Tensor< GUM_SCALAR > evEq (std::string_view name, double value) const
Tensor< GUM_SCALAR > evIn (std::string_view name, double val1, double val2) const
Tensor< GUM_SCALAR > evLt (std::string_view name, double value) const
Tensor< GUM_SCALAR > evGt (std::string_view name, double value) const
Size memoryFootprint () const
 compute the (approximated) footprint in memory of the model (the footprints of CPTs)
bool hasSameStructure (const DAGmodel &other) const
NodeSet minimalCondSet (NodeId target, const NodeSet &soids) const
NodeSet minimalCondSet (const NodeSet &targets, const NodeSet &soids) const
NodeSet minimalCondSet (std::string_view target, const std::vector< std::string > &soids) const
NodeSet minimalCondSet (const std::vector< std::string > &targets, const std::vector< std::string > &soids) const
const DAG & internalDag () const
 Returns a const reference to the internal (unnamed) DAG. O(1), no copy. Use for stable references or pointers (e.g. graph listeners). For named node access, use dag() instead.
double log10DomainSize () const
Constructors and Destructor
 BayesNet ()
 Default constructor.
 BayesNet (std::string_view name)
 Default constructor.
 ~BayesNet () override
 Destructor.
 BayesNet (const BayesNet< GUM_SCALAR > &source)
 Copy constructor.
 BayesNet (BayesNet< GUM_SCALAR > &&source)
 Move constructor.
Operators
BayesNet< GUM_SCALAR > & operator= (const BayesNet< GUM_SCALAR > &source)
 Copy operator.
BayesNet< GUM_SCALAR > & operator= (BayesNet< GUM_SCALAR > &&source)
 Move operator.
Variable manipulation methods
const Tensor< GUM_SCALAR > & cpt (NodeId varId) const final
 Returns the CPT of a variable.
const Tensor< GUM_SCALAR > & cpt (std::string_view name) const
 Returns the CPT of a variable.
NodeId add (const DiscreteVariable &var)
 Add a variable to the gum::BayesNet.
NodeId add (std::string_view fast_description, unsigned int default_nbrmod=2)
 Use "fast" syntax to add a variable in the BayesNet.
NodeId add (const DiscreteVariable &var, MultiDimImplementation< GUM_SCALAR > *aContent)
 Add a variable to the gum::BayesNet.
NodeId add (const DiscreteVariable &var, NodeId id)
 Add a variable to the gum::BayesNet.
NodeId add (const DiscreteVariable &var, MultiDimImplementation< GUM_SCALAR > *aContent, NodeId id)
 Add a variable to the gum::BayesNet.
void clear ()
 clear the whole Bayes net *
void erase (NodeId varId)
 Remove a variable from the gum::BayesNet.
void erase (std::string_view name)
 Removes a variable from the gum::BayesNet.
void erase (const DiscreteVariable &var)
 Remove a variable from the gum::BayesNet.
const DiscreteVariable & variable (std::string_view name) const
 Returns a gum::DiscreteVariable given its name in the gum::BayesNet.
void changeVariableName (NodeId id, std::string_view new_name)
 Changes a variable's name in the gum::BayesNet.
void changeVariableName (std::string_view name, std::string_view new_name)
 Changes a variable's name.
void changeVariableLabel (NodeId id, std::string_view old_label, std::string_view new_label)
 Changes a variable's label in the gum::BayesNet.
void changeVariableLabel (std::string_view name, std::string_view old_label, std::string_view new_label)
 Changes a variable's name.
Arc manipulation methods.
void addArc (NodeId tail, NodeId head)
 Add an arc in the BN, and update arc.head's CPT.
void addArc (std::string_view tail, std::string_view head)
 Add an arc in the BN, and update arc.head's CPT.
void eraseArc (const Arc &arc)
 Removes an arc in the BN, and update head's CTP.
void eraseArc (NodeId tail, NodeId head)
 Removes an arc in the BN, and update head's CTP.
void eraseArc (std::string_view tail, std::string_view head)
 Removes an arc in the BN, and update head's CTP.
void beginTopologyTransformation ()
 When inserting/removing arcs, node CPTs change their dimension with a cost in time.
void endTopologyTransformation ()
 terminates a sequence of insertions/deletions of arcs by adjusting all CPTs dimensions.
void reverseArc (NodeId tail, NodeId head)
 Reverses an arc while preserving the same joint distribution.
void reverseArc (std::string_view tail, std::string_view head)
 Reverses an arc while preserving the same joint distribution.
void reverseArc (const Arc &arc)
 Reverses an arc while preserving the same joint distribution.
Accessors for nodes with CI or logical implementation
NodeId addNoisyOR (const DiscreteVariable &var, GUM_SCALAR external_weight)
 Add a variable, it's associate node and a gum::noisyOR implementation.
NodeId addNoisyORNet (const DiscreteVariable &var, GUM_SCALAR external_weight)
 Add a variable, it's associate node and a gum::noisyOR implementation.
NodeId addNoisyORCompound (const DiscreteVariable &var, GUM_SCALAR external_weight)
 Add a variable, it's associate node and a gum::noisyOR implementation.
NodeId addNoisyOR (const DiscreteVariable &var, GUM_SCALAR external_weight, NodeId id)
 Add a variable, its associate node and a noisyOR implementation.
NodeId addNoisyORNet (const DiscreteVariable &var, GUM_SCALAR external_weight, NodeId id)
 Add a variable, its associate node and a noisyOR implementation.
NodeId addNoisyORCompound (const DiscreteVariable &var, GUM_SCALAR external_weight, NodeId id)
 Add a variable, its associate node and a noisyOR implementation.
NodeId addAMPLITUDE (const DiscreteVariable &var)
 Others aggregators.
NodeId addCOUNT (const DiscreteVariable &var, Idx value=1)
 Others aggregators.
NodeId addEXISTS (const DiscreteVariable &var, Idx value=1)
 Others aggregators.
NodeId addFORALL (const DiscreteVariable &var, Idx value=1)
 Others aggregators.
NodeId addMAX (const DiscreteVariable &var)
 Others aggregators.
NodeId addMEDIAN (const DiscreteVariable &var)
 Others aggregators.
NodeId addMIN (const DiscreteVariable &var)
 Others aggregators.
NodeId addSUM (const DiscreteVariable &var)
 Others aggregators.
Joint Probability manipulation methods
GUM_SCALAR jointProbability (const Instantiation &i) const
 Compute a parameter of the joint probability for the BN (given an instantiation of the vars).
GUM_SCALAR log2JointProbability (const Instantiation &i) const
 Compute a parameter of the log joint probability for the BN (given an instantiation of the vars).
Variable manipulation methods.
DAG dag () const
 Returns a named copy of the internal DAG: each node id is assigned the name of the corresponding variable.
Size size () const final
 Returns the number of variables in this Directed Graphical Model.
Size sizeArcs () const
 Returns the number of arcs in this Directed Graphical Model.
const NodeGraphPart & nodes () const final
 Returns a named copy of the internal DAG: each node id is assigned the name of the corresponding variable.
bool exists (NodeId node) const final
 Return true if this node exists in this graphical model.
bool exists (std::string_view name) const final
 Returns a named copy of the internal DAG: each node id is assigned the name of the corresponding variable.
Arc manipulation methods.
const ArcSet & arcs () const
 return true if the arc tail->head exists in the DAGmodel
bool existsArc (const NodeId tail, const NodeId head) const
 return true if the arc tail->head exists in the DAGmodel
bool existsArc (std::string_view nametail, std::string_view namehead) const
 return true if the arc tail->head exists in the DAGmodel
const NodeSet & parents (const NodeId id) const
 returns the set of nodes with arc ingoing to a given node
const NodeSet & parents (std::string_view name) const
 return true if the arc tail->head exists in the DAGmodel
NodeSet parents (const NodeSet &ids) const
 returns the parents of a set of nodes
NodeSet parents (const std::vector< std::string > &names) const
 return true if the arc tail->head exists in the DAGmodel
NodeSet family (const NodeId id) const final
 returns the parents of a node and the node
NodeSet family (std::string_view name) const final
 return true if the arc tail->head exists in the DAGmodel
const NodeSet & children (const NodeId id) const
 returns the set of nodes with arc outgoing from a given node
const NodeSet & children (std::string_view name) const
 return true if the arc tail->head exists in the DAGmodel
NodeSet children (const NodeSet &ids) const
 returns the children of a set of nodes
NodeSet children (const std::vector< std::string > &names) const
 return true if the arc tail->head exists in the DAGmodel
NodeSet descendants (const NodeId id) const
 returns the set of nodes with directed path outgoing from a given node
NodeSet descendants (std::string_view name) const
 return true if the arc tail->head exists in the DAGmodel
NodeSet ancestors (const NodeId id) const
 returns the set of nodes with directed path ingoing to a given node
NodeSet ancestors (std::string_view name) const
 return true if the arc tail->head exists in the DAGmodel
Graphical methods
UndiGraph moralizedAncestralGraph (const NodeSet &nodes) const
 build a UndiGraph by moralizing the Ancestral Graph of a set of Nodes
UndiGraph moralizedAncestralGraph (const std::vector< std::string > &nodenames) const
 build a UndiGraph by moralizing the Ancestral Graph of a set of Nodes
bool isIndependent (NodeId X, NodeId Y, const NodeSet &Z) const final
 check if node X and node Y are independent given nodes Z
bool isIndependent (const NodeSet &X, const NodeSet &Y, const NodeSet &Z) const final
 check if nodes X and nodes Y are independent given nodes Z
bool isIndependent (std::string_view Xname, std::string_view Yname, const std::vector< std::string > &Znames) const
 build a UndiGraph by moralizing the Ancestral Graph of a set of Nodes
bool isIndependent (const std::vector< std::string > &Xnames, const std::vector< std::string > &Ynames, const std::vector< std::string > &Znames) const
 build a UndiGraph by moralizing the Ancestral Graph of a set of Nodes
UndiGraph moralGraph () const
 The node's id are coherent with the variables and nodes of the topology.
Sequence< NodeId > topologicalOrder () const
 The topological order stays the same as long as no variable or arcs are added or erased src the topology.
NodeProperty< NodeId > connectedComponents () const
 Returns the weakly connected components of the underlying DAG. Each node maps to the id of its component root.
Getter and setters
const std::string & property (std::string_view name) const
 Return the value of the property name of this GraphicalModel.
const std::string & propertyWithDefault (std::string_view name, const std::string &byDefault) const
 Return the value of the property name of this GraphicalModel.
void setProperty (std::string_view name, std::string_view value)
 Add or change a property of this GraphicalModel.
std::vector< std::string > properties () const
 List of all the names of property in the Graphical model.
bool existsProperty (std::string_view name) const
 check wether a property exists in this GraphicalModel
void updateMetaData ()
 update the meta data of this Graphical Model (version, creation date, last modification date) This method is called by the writers ONLY before writing the model to a file.
Variable manipulation methods.
virtual bool empty () const
 Return true if this graphical model is empty.
std::vector< std::string > names (const std::vector< NodeId > &ids) const
 transform a vector of NodeId in a vector of names
std::vector< std::string > names (const NodeSet &ids) const
 transform a NodeSet in a vector of names
std::vector< NodeId > ids (const std::vector< std::string > &names) const
 transform a vector of names into a vector of nodeId
NodeSet nodeset (const std::vector< std::string > &names) const
 transform a vector of names into a NodeSet
gum::VariableSet variables (const std::vector< std::string > &l) const
 transform a vector of names into a VariableeSet
gum::VariableSet variables (const NodeSet &ids) const
 transform a vector of NodeId into a VariableeSet
Instantiation completeInstantiation () const
 Get an instantiation over all the variables of the model.

Static Public Member Functions

static BayesNet< GUM_SCALAR > fastPrototype (std::string_view dotlike, Size domainSize)
 Create a Bayesian network with a dot-like syntax which specifies:
static BayesNet< GUM_SCALAR > fastPrototype (std::string_view dotlike, std::string_view domainSize="[2]")
static std::string spaceCplxToString (double dSize, int dim, Size usedMem)
 send to the stream the space complexity with 3 parametrs

Protected Member Functions

void _nameNodes_ (NodeGraphPart &g) const
 Names every node of g using variable(id).name() for each node id in g.

Protected Attributes

DAG dag_
 The DAG of this Directed Graphical Model.
VariableNodeMap varMap_
 Mapping between NodeIds and discrete variables.

Private Member Functions

void _clearTensors_ ()
 clear all tensors
void _copyTensors_ (const BayesNet< GUM_SCALAR > &source)
 copy of tensors from a BN to another, using names of vars as ref.
void _unsafeChangeTensor_ (NodeId id, Tensor< GUM_SCALAR > *newPot)
 change the CPT associated to nodeId to newPot delete the old CPT associated to nodeId.
NodeId _addAggregator_ (std::string_view aggregatorType, const DiscreteVariable &var, Idx value=1)
 Generic factory for aggregator nodes, dispatching on the aggregator's name.
NodeId _addICIModel_ (std::string_view iciType, const DiscreteVariable &var, GUM_SCALAR externalWeight)
 Generic factory for ICI model nodes, dispatching on the implementation's name.
void _checkNodeExists_ (NodeId id) const
const HashTable< std::string, std::string > & _properties_ () const
 Return the properties of this Directed Graphical Model.

Private Attributes

NodeProperty< Tensor< GUM_SCALAR > * > _probaMap_
 Mapping between the variable's id and their CPT.
HashTable< std::string, std::string > _propertiesMap_
 The properties of this Directed Graphical Model.

Friends

class BayesNetFactory< GUM_SCALAR >
class GumBNReader< GUM_SCALAR >
class AggregatorDecomposition< GUM_SCALAR >

Detailed Description

template<GUM_Numeric GUM_SCALAR>
class gum::BayesNet< GUM_SCALAR >

Class representing a Bayesian network.

Bayesian networks are a probabilistic graphical model in which nodes are random variables and the probability distribution is defined by the product:

\(P(X_1, \ldots, X_n) = \prod_{i=1}^{n} P(X_i | \pi(X_i))\),

where \(\pi(X_i)\) is the parent of \(X_i\).

The probability distribution can be represented as a directed acyclic graph (DAG) where:

  • Nodes are discrete random variables.
  • An arc A -> B represent a dependency between variables A and B, i.e. B conditional probability distribution is defined as \(P(B| \pi(B)\).

After a variable is added to the BN, it's domain cannot change. But it arcs are added, the data in its CPT are lost.

You should look a the gum::BayesNetFactory class which can help build Bayesian networks.

You can print a BayesNet using gum::operator<<(std::ostream&, const BayesNet<GUM_SCALAR>&).

Definition at line 99 of file BayesNet.h.

Constructor & Destructor Documentation

◆ BayesNet() [1/4]

template<GUM_Numeric GUM_SCALAR>
gum::BayesNet< GUM_SCALAR >::BayesNet ( )

Default constructor.

Definition at line 119 of file BayesNet_tpl.h.

121 }
Class representing a Bayesian network.
Definition BayesNet.h:99
BayesNet()
Default constructor.
IBayesNet()
Default constructor.

References BayesNet(), and gum::IBayesNet< GUM_SCALAR >::IBayesNet().

Referenced by BayesNet(), BayesNet(), BayesNet(), ~BayesNet(), operator=(), and operator=().

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

◆ BayesNet() [2/4]

template<GUM_Numeric GUM_SCALAR>
gum::BayesNet< GUM_SCALAR >::BayesNet ( std::string_view name)
explicit

Default constructor.

Parameters
nameThe BayesNet's name.

Definition at line 124 of file BayesNet_tpl.h.

References BayesNet(), and gum::IBayesNet< GUM_SCALAR >::IBayesNet().

Here is the call graph for this function:

◆ ~BayesNet()

template<GUM_Numeric GUM_SCALAR>
gum::BayesNet< GUM_SCALAR >::~BayesNet ( )
override

Destructor.

Definition at line 166 of file BayesNet_tpl.h.

166 {
168 for (const auto& p: _probaMap_) {
169 delete p.second;
170 }
171 }
NodeProperty< Tensor< GUM_SCALAR > * > _probaMap_
Mapping between the variable's id and their CPT.
Definition BayesNet.h:657

References BayesNet(), and _probaMap_.

Here is the call graph for this function:

◆ BayesNet() [3/4]

template<GUM_Numeric GUM_SCALAR>
gum::BayesNet< GUM_SCALAR >::BayesNet ( const BayesNet< GUM_SCALAR > & source)

Copy constructor.

Definition at line 129 of file BayesNet_tpl.h.

129 :
132
134 }
void _copyTensors_(const BayesNet< GUM_SCALAR > &source)
copy of tensors from a BN to another, using names of vars as ref.

References BayesNet(), gum::IBayesNet< GUM_SCALAR >::IBayesNet(), and _copyTensors_().

Here is the call graph for this function:

◆ BayesNet() [4/4]

template<GUM_Numeric GUM_SCALAR>
gum::BayesNet< GUM_SCALAR >::BayesNet ( BayesNet< GUM_SCALAR > && source)

Move constructor.

Definition at line 137 of file BayesNet_tpl.h.

References gum::IBayesNet< GUM_SCALAR >::IBayesNet(), and _probaMap_.

Here is the call graph for this function:

Member Function Documentation

◆ _addAggregator_()

template<GUM_Numeric GUM_SCALAR>
NodeId gum::BayesNet< GUM_SCALAR >::_addAggregator_ ( std::string_view aggregatorType,
const DiscreteVariable & var,
Idx value = 1 )
private

Generic factory for aggregator nodes, dispatching on the aggregator's name.

Note
Not part of the public API: used by GumBNReader to reconstruct aggregator nodes serialized in the compact jgum/bgum format.

Definition at line 451 of file BayesNet_tpl.h.

453 {
455 if (type == "and") return addAND(var);
456 if (type == "or") return addOR(var);
457 if (type == "amplitude") return addAMPLITUDE(var);
458 if (type == "count") return addCOUNT(var, value);
459 if (type == "exists") return addEXISTS(var, value);
460 if (type == "forall") return addFORALL(var, value);
461 if (type == "max") return addMAX(var);
462 if (type == "median") return addMEDIAN(var);
463 if (type == "min") return addMIN(var);
464 if (type == "sum") return addSUM(var);
465 GUM_ERROR(NotFound, "Unknown aggregator type: " << aggregatorType)
466 }
NodeId addCOUNT(const DiscreteVariable &var, Idx value=1)
Others aggregators.
NodeId addAMPLITUDE(const DiscreteVariable &var)
Others aggregators.
NodeId addAND(const DiscreteVariable &var)
Add a variable, it's associate node and an AND implementation.
NodeId addMAX(const DiscreteVariable &var)
Others aggregators.
NodeId addEXISTS(const DiscreteVariable &var, Idx value=1)
Others aggregators.
NodeId addSUM(const DiscreteVariable &var)
Others aggregators.
NodeId addFORALL(const DiscreteVariable &var, Idx value=1)
Others aggregators.
NodeId addMIN(const DiscreteVariable &var)
Others aggregators.
NodeId addMEDIAN(const DiscreteVariable &var)
Others aggregators.
NodeId addOR(const DiscreteVariable &var)
Add a variable, it's associate node and an OR implementation.

References addAMPLITUDE(), addAND(), addCOUNT(), addEXISTS(), addFORALL(), addMAX(), addMEDIAN(), addMIN(), addOR(), addSUM(), GUM_ERROR, and gum::toLower().

Here is the call graph for this function:

◆ _addICIModel_()

template<GUM_Numeric GUM_SCALAR>
NodeId gum::BayesNet< GUM_SCALAR >::_addICIModel_ ( std::string_view iciType,
const DiscreteVariable & var,
GUM_SCALAR externalWeight )
private

Generic factory for ICI model nodes, dispatching on the implementation's name.

Note
Not part of the public API: used by GumBNReader to reconstruct ICI model nodes serialized in the compact jgum/bgum format.

Definition at line 501 of file BayesNet_tpl.h.

503 {
504 if (iciType == "MultiDimNoisyORCompound") return addNoisyORCompound(var, externalWeight);
505 if (iciType == "MultiDimNoisyORNet") return addNoisyORNet(var, externalWeight);
506 if (iciType == "MultiDimNoisyAND") return addNoisyAND(var, externalWeight);
507 if (iciType == "MultiDimLogit") return addLogit(var, externalWeight);
508 GUM_ERROR(NotFound, "Unknown ICI model type: " << iciType)
509 }
NodeId addLogit(const DiscreteVariable &var, GUM_SCALAR external_weight, NodeId id)
Add a variable, its associate node and a Logit implementation.
NodeId addNoisyORNet(const DiscreteVariable &var, GUM_SCALAR external_weight)
Add a variable, it's associate node and a gum::noisyOR implementation.
NodeId addNoisyAND(const DiscreteVariable &var, GUM_SCALAR external_weight, NodeId id)
Add a variable, its associate node and a noisyAND implementation.
NodeId addNoisyORCompound(const DiscreteVariable &var, GUM_SCALAR external_weight)
Add a variable, it's associate node and a gum::noisyOR implementation.

References addLogit(), addNoisyAND(), addNoisyORCompound(), addNoisyORNet(), and GUM_ERROR.

Here is the call graph for this function:

◆ _checkNodeExists_()

INLINE void gum::DAGmodel::_checkNodeExists_ ( NodeId id) const
privateinherited
Exceptions
NotFoundif id is not a node of the model

Definition at line 83 of file DAGmodel_inl.h.

83 {
84 if (!dag_.exists(id)) GUM_ERROR(NotFound, "No node with id " << id << " in the model")
85 }
DAG dag_
The DAG of this Directed Graphical Model.
Definition DAGmodel.h:291
bool exists(const NodeId id) const
alias for existsNode
#define GUM_ERROR(type, msg)
Definition exceptions.h:76

References dag_, gum::NodeGraphPart::exists(), and GUM_ERROR.

Referenced by ancestors(), children(), descendants(), family(), and parents().

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

◆ _clearTensors_()

template<GUM_Numeric GUM_SCALAR>
void gum::BayesNet< GUM_SCALAR >::_clearTensors_ ( )
private

clear all tensors

Definition at line 587 of file BayesNet_tpl.h.

587 {
588 // Removing previous tensors
589 for (const auto& elt: _probaMap_) {
590 delete elt.second;
591 }
592
593 _probaMap_.clear();
594 }

Referenced by operator=(), and operator=().

Here is the caller graph for this function:

◆ _copyTensors_()

template<GUM_Numeric GUM_SCALAR>
void gum::BayesNet< GUM_SCALAR >::_copyTensors_ ( const BayesNet< GUM_SCALAR > & source)
private

copy of tensors from a BN to another, using names of vars as ref.

Definition at line 598 of file BayesNet_tpl.h.

598 {
599 // Copying tensors
600
601 for (const auto& src: source._probaMap_) {
602 // First we build the node's CPT
603 auto copy_array = new Tensor< GUM_SCALAR >();
604 copy_array->beginMultipleChanges();
605 for (gum::Idx i = 0; i < src.second->nbrDim(); i++) {
606 (*copy_array) << variableFromName(src.second->variable(i).name());
607 }
608 copy_array->endMultipleChanges();
609 copy_array->copyFrom(*(src.second));
610
611 // We add the CPT to the CPT hashmap
612 _probaMap_.insert(src.first, copy_array);
613 }
614 }
const DiscreteVariable & variable(std::string_view name) const
Returns a gum::DiscreteVariable given its name in the gum::BayesNet.
const DiscreteVariable & variableFromName(std::string_view name) const override
Returns a constant reference over a variable given its name.
const std::string & name() const
returns the name of the variable

Referenced by BayesNet(), and operator=().

Here is the caller graph for this function:

◆ _nameNodes_()

INLINE void gum::GraphicalModel::_nameNodes_ ( NodeGraphPart & g) const
protectedinherited

Names every node of g using variable(id).name() for each node id in g.

Call this before returning any newly constructed graph from a model method.

Definition at line 175 of file graphicalModel_inl.h.

175 {
176 for (auto id: g)
177 g.setName(id, variable(id).name());
178 }
virtual const DiscreteVariable & variable(NodeId id) const =0
Returns a constant reference over a variable given it's node id.

References gum::NodeGraphPart::setName(), and variable().

Referenced by gum::DAGmodel::dag(), family(), gum::UGmodel::graph(), and gum::DAGmodel::moralGraph().

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

◆ _properties_()

INLINE const HashTable< std::string, std::string > & gum::GraphicalModel::_properties_ ( ) const
privateinherited

Return the properties of this Directed Graphical Model.

Definition at line 67 of file graphicalModel_inl.h.

67 {
68 return _propertiesMap_;
69 }
HashTable< std::string, std::string > _propertiesMap_
The properties of this Directed Graphical Model.

References _propertiesMap_.

Referenced by property().

Here is the caller graph for this function:

◆ _unsafeChangeTensor_()

template<GUM_Numeric GUM_SCALAR>
void gum::BayesNet< GUM_SCALAR >::_unsafeChangeTensor_ ( NodeId id,
Tensor< GUM_SCALAR > * newPot )
private

change the CPT associated to nodeId to newPot delete the old CPT associated to nodeId.

Warning
no verification of dimensions are performer
See also
changeTensor

Definition at line 650 of file BayesNet_tpl.h.

650 {
651 delete _probaMap_[id];
653 }

◆ add() [1/5]

template<GUM_Numeric GUM_SCALAR>
NodeId gum::BayesNet< GUM_SCALAR >::add ( const DiscreteVariable & var)

Add a variable to the gum::BayesNet.

Add a gum::DiscreteVariable, it's associated gum::NodeId and it's gum::Tensor.

The variable is added by copy to the gum::BayesNet. The variable's gum::Tensor implementation will be a gum::MultiDimArray.

Parameters
varThe variable added by copy.
Returns
Returns the variable's id in the gum::BayesNet.
Exceptions
DuplicateLabelRaised if variable.name() is already used in this gum::BayesNet.

Definition at line 192 of file BayesNet_tpl.h.

192 {
193 auto ptr = new MultiDimArray< GUM_SCALAR >();
194 try {
195 return add(var, ptr);
196 } catch (Exception const&) {
197 delete ptr;
198 throw;
199 }
200 }
NodeId add(const DiscreteVariable &var)
Add a variable to the gum::BayesNet.
MultiDimArray()
Default constructor.

References gum::MultiDimArray< GUM_ELEMENT >::MultiDimArray(), and add().

Referenced by add(), add(), add(), addAMPLITUDE(), addAND(), addCOUNT(), addEXISTS(), addFORALL(), addLogit(), addLogit(), addMAX(), addMEDIAN(), addMIN(), addNoisyAND(), addNoisyAND(), addNoisyORCompound(), addNoisyORNet(), addNoisyORNet(), addOR(), addSUM(), gum::build_node(), and gum::BayesNetFragment< GUM_SCALAR >::toBN().

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

◆ add() [2/5]

template<GUM_Numeric GUM_SCALAR>
NodeId gum::BayesNet< GUM_SCALAR >::add ( const DiscreteVariable & var,
MultiDimImplementation< GUM_SCALAR > * aContent )

Add a variable to the gum::BayesNet.

Add a gum::DiscreteVariable, it's associated gum::NodeId and it's gum::Tensor.

The variable is added by copy to the gum::BayesNet.

Parameters
varThe variable added by copy.
aContentThe gum::MultiDimImplementation to use for this variable's gum::Tensor implementation.
Returns
Returns the variable's id in the gum::BayesNet.
Exceptions
DuplicateLabelRaised if variable.name() is already used in this gum::BayesNet.

Definition at line 211 of file BayesNet_tpl.h.

212 {
213 NodeId proposedId = dag().nextNodeId();
214
215 return add(var, aContent, proposedId);
216 }
DAG dag() const
Returns a named copy of the internal DAG: each node id is assigned the name of the corresponding vari...

References add(), and gum::DAGmodel::dag().

Here is the call graph for this function:

◆ add() [3/5]

template<GUM_Numeric GUM_SCALAR>
NodeId gum::BayesNet< GUM_SCALAR >::add ( const DiscreteVariable & var,
MultiDimImplementation< GUM_SCALAR > * aContent,
NodeId id )

Add a variable to the gum::BayesNet.

Add a gum::DiscreteVariable, it's associated gum::NodeId and it's gum::Tensor.

Parameters
varThe variable added by copy.
aContentThe gum::MultiDimImplementation to use for this variable's gum::Tensor implementation.
idThe variable's forced gum::NodeId in the gum::BayesNet.
Returns
Returns the variable's id in the gum::BayesNet.
Exceptions
DuplicateElementRaised id is already used.
DuplicateLabelRaised if variable.name() is already used in this gum::BayesNet.

Definition at line 231 of file BayesNet_tpl.h.

233 {
234 this->varMap_.insert(id, var);
235 this->dag_.addNodeWithId(id);
236
238 (*cpt) << variable(id);
239 _probaMap_.insert(id, cpt);
240 return id;
241 }
const Tensor< GUM_SCALAR > & cpt(NodeId varId) const final
Returns the CPT of a variable.
VariableNodeMap varMap_
Mapping between NodeIds and discrete variables.

References _probaMap_, cpt(), gum::DAGmodel::dag_, variable(), and gum::DiscreteGraphicalModel::varMap_.

Here is the call graph for this function:

◆ add() [4/5]

template<GUM_Numeric GUM_SCALAR>
NodeId gum::BayesNet< GUM_SCALAR >::add ( const DiscreteVariable & var,
NodeId id )

Add a variable to the gum::BayesNet.

Add a gum::DiscreteVariable, it's associated gum::NodeId and it's gum::Tensor.

The variable is added by copy to the gum::BayesNet. The variable's gum::Tensor implementation will be a gum::MultiDimArray.

Parameters
varThe variable added by copy.
idThe variable's forced gum::NodeId in the gum::BayesNet.
Returns
Returns the variable's id in the gum::BayesNet.
Exceptions
DuplicateElementRaised id is already used.
DuplicateLabelRaised if variable.name() is already used in this gum::BayesNet.

Definition at line 219 of file BayesNet_tpl.h.

219 {
220 auto ptr = new MultiDimArray< GUM_SCALAR >();
221
222 try {
223 return add(var, ptr, id);
224 } catch (Exception const&) {
225 delete ptr;
226 throw;
227 }
228 }

◆ add() [5/5]

template<GUM_Numeric GUM_SCALAR>
NodeId gum::BayesNet< GUM_SCALAR >::add ( std::string_view fast_description,
unsigned int default_nbrmod = 2 )

Use "fast" syntax to add a variable in the BayesNet.

  • a : range variable from 0 to default_nbrmod-1
  • a[5] : range variable from 0 to 5
  • a[-3,5] : range variable from -3 to 5
  • a[1,3.14,5,3] : discretized variable
  • a{x|y|z} : labelized variable
  • a{-3|0|3|100} : integer variable
Parameters
fast_description(str) following "fast" syntax description
default_nbrmod(int) nbr of modality if fast_description do not indicate it. default_nbrmod=1 is the way to create a variable with only one value (for instance for reward in influence diagram).
Exceptions
DuplicateLabelRaised if variable.name() is already used in this gum::BayesNet.
NotAllowedif nbrmod<2

Definition at line 203 of file BayesNet_tpl.h.

204 {
206 if (v->domainSize() < 2) GUM_ERROR(OperationNotAllowed, v->name() << " has a domain size <2")
207 return add(*v);
208 }

References add(), gum::fastVariable(), and GUM_ERROR.

Here is the call graph for this function:

◆ addAMPLITUDE()

template<GUM_Numeric GUM_SCALAR>
NodeId gum::BayesNet< GUM_SCALAR >::addAMPLITUDE ( const DiscreteVariable & var)

Others aggregators.

MIN, MAX, MEDIAN, AMPLITUDE and SUM are computed on the values of the parents (DiscreteVariable::numerical()), and the result is mapped onto the closest value of the aggregator (DiscreteVariable::closestIndex(), saturated at both bounds). AMPLITUDE and SUM need numerical variables; MIN, MAX and MEDIAN accept labelized variables (order of the labels) or numerical ones, but not both. An incompatible variable is rejected (TypeError) when it is added (here or by addArc()).

Definition at line 393 of file BayesNet_tpl.h.

393 {
395 }

References add().

Referenced by _addAggregator_().

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

◆ addAND()

template<GUM_Numeric GUM_SCALAR>
NodeId gum::BayesNet< GUM_SCALAR >::addAND ( const DiscreteVariable & var)

Add a variable, it's associate node and an AND implementation.

The id of the new variable is automatically generated.

Warning
AND is implemented as a gum::aggregator::And which means that if parents are not boolean, all value>1 is True
Parameters
varThe variable added by copy.
Returns
the id of the added variable.
Exceptions
SizeErrorif variable.domainSize()>2

Definition at line 398 of file BayesNet_tpl.h.

398 {
399 if (var.domainSize() > 2) GUM_ERROR(SizeError, "an AND has to be boolean")
400
402 }

References add(), gum::DiscreteVariable::domainSize(), and GUM_ERROR.

Referenced by _addAggregator_().

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

◆ addArc() [1/2]

template<GUM_Numeric GUM_SCALAR>
void gum::BayesNet< GUM_SCALAR >::addArc ( NodeId tail,
NodeId head )

Add an arc in the BN, and update arc.head's CPT.

Parameters
headand
tailas NodeId
Exceptions
InvalidEdgeIf arc.tail and/or arc.head are not in the BN.
DuplicateElementif the arc already exists
TypeError(or OutOfBounds for a noisy model) if the CPT of head refuses tail as a new parent (e.g. a labelized parent for a SUM aggregator). The arc is not added then.

Definition at line 280 of file BayesNet_tpl.h.

280 {
281 if (this->dag_.existsArc(tail, head)) {
282 GUM_ERROR(DuplicateElement, "The arc (" << tail << "," << head << ") already exists.")
283 }
284
285 this->dag_.addArc(tail, head);
286 // Add parent in the child's CPT (it may be refused, e.g. by an aggregator or a noisy model)
287 try {
288 (*(_probaMap_[head])) << variable(tail);
289 } catch (Exception const&) {
290 this->dag_.eraseArc(Arc(tail, head));
291 throw;
292 }
293 }
Arc(NodeId tail, NodeId head)
basic constructor. Creates tail -> head.

References gum::Arc::Arc(), _probaMap_, gum::DAGmodel::dag_, GUM_ERROR, and variable().

Referenced by addArc(), addWeightedArc(), fastPrototype(), and gum::BayesNetFragment< GUM_SCALAR >::toBN().

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

◆ addArc() [2/2]

template<GUM_Numeric GUM_SCALAR>
void gum::BayesNet< GUM_SCALAR >::addArc ( std::string_view tail,
std::string_view head )

Add an arc in the BN, and update arc.head's CPT.

Exceptions
gum::DuplicateElementif the arc already exists

Definition at line 296 of file BayesNet_tpl.h.

296 {
297 try {
298 addArc(this->idFromName(tail), this->idFromName(head));
299 } catch (DuplicateElement const&) {
300 GUM_ERROR(DuplicateElement, "The arc " << tail << "->" << head << " already exists.")
301 }
302 }
NodeId idFromName(std::string_view name) const override
Returns the NodeId of a variable given its name.
void addArc(NodeId tail, NodeId head)
Add an arc in the BN, and update arc.head's CPT.

References addArc(), and idFromName().

Here is the call graph for this function:

◆ addCOUNT()

template<GUM_Numeric GUM_SCALAR>
NodeId gum::BayesNet< GUM_SCALAR >::addCOUNT ( const DiscreteVariable & var,
Idx value = 1 )

Others aggregators.

MIN, MAX, MEDIAN, AMPLITUDE and SUM are computed on the values of the parents (DiscreteVariable::numerical()), and the result is mapped onto the closest value of the aggregator (DiscreteVariable::closestIndex(), saturated at both bounds). AMPLITUDE and SUM need numerical variables; MIN, MAX and MEDIAN accept labelized variables (order of the labels) or numerical ones, but not both. An incompatible variable is rejected (TypeError) when it is added (here or by addArc()).

Definition at line 405 of file BayesNet_tpl.h.

405 {
407 }

References add().

Referenced by _addAggregator_().

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

◆ addEXISTS()

template<GUM_Numeric GUM_SCALAR>
NodeId gum::BayesNet< GUM_SCALAR >::addEXISTS ( const DiscreteVariable & var,
Idx value = 1 )

Others aggregators.

MIN, MAX, MEDIAN, AMPLITUDE and SUM are computed on the values of the parents (DiscreteVariable::numerical()), and the result is mapped onto the closest value of the aggregator (DiscreteVariable::closestIndex(), saturated at both bounds). AMPLITUDE and SUM need numerical variables; MIN, MAX and MEDIAN accept labelized variables (order of the labels) or numerical ones, but not both. An incompatible variable is rejected (TypeError) when it is added (here or by addArc()).

Definition at line 410 of file BayesNet_tpl.h.

410 {
411 if (var.domainSize() > 2) GUM_ERROR(SizeError, "an EXISTS has to be boolean")
412
414 }

References add(), gum::DiscreteVariable::domainSize(), and GUM_ERROR.

Referenced by _addAggregator_().

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

◆ addFORALL()

template<GUM_Numeric GUM_SCALAR>
NodeId gum::BayesNet< GUM_SCALAR >::addFORALL ( const DiscreteVariable & var,
Idx value = 1 )

Others aggregators.

MIN, MAX, MEDIAN, AMPLITUDE and SUM are computed on the values of the parents (DiscreteVariable::numerical()), and the result is mapped onto the closest value of the aggregator (DiscreteVariable::closestIndex(), saturated at both bounds). AMPLITUDE and SUM need numerical variables; MIN, MAX and MEDIAN accept labelized variables (order of the labels) or numerical ones, but not both. An incompatible variable is rejected (TypeError) when it is added (here or by addArc()).

Definition at line 417 of file BayesNet_tpl.h.

417 {
418 if (var.domainSize() > 2) GUM_ERROR(SizeError, "an EXISTS has to be boolean")
419
421 }

References add(), gum::DiscreteVariable::domainSize(), and GUM_ERROR.

Referenced by _addAggregator_().

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

◆ addLogit() [1/2]

template<GUM_Numeric GUM_SCALAR>
NodeId gum::BayesNet< GUM_SCALAR >::addLogit ( const DiscreteVariable & var,
GUM_SCALAR external_weight )

Add a variable, its associate node and a Logit implementation.

The id of the new variable is automatically generated.

Parameters
varThe variable added by copy.
external_weightsee gum::MultiDimLogit
Returns
the id of the added variable.

Definition at line 496 of file BayesNet_tpl.h.

496 {
498 }

References add().

Here is the call graph for this function:

◆ addLogit() [2/2]

template<GUM_Numeric GUM_SCALAR>
NodeId gum::BayesNet< GUM_SCALAR >::addLogit ( const DiscreteVariable & var,
GUM_SCALAR external_weight,
NodeId id )

Add a variable, its associate node and a Logit implementation.

Parameters
varThe variable added by copy
external_weightsee gum::MultiDimLogit
idproposed gum::nodeId for the variable
Warning
give an id should be reserved for rare and specific situations !!!
Returns
the id of the added variable.

Definition at line 526 of file BayesNet_tpl.h.

528 {
530 }

References add().

Referenced by _addICIModel_().

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

◆ addMAX()

template<GUM_Numeric GUM_SCALAR>
NodeId gum::BayesNet< GUM_SCALAR >::addMAX ( const DiscreteVariable & var)

Others aggregators.

MIN, MAX, MEDIAN, AMPLITUDE and SUM are computed on the values of the parents (DiscreteVariable::numerical()), and the result is mapped onto the closest value of the aggregator (DiscreteVariable::closestIndex(), saturated at both bounds). AMPLITUDE and SUM need numerical variables; MIN, MAX and MEDIAN accept labelized variables (order of the labels) or numerical ones, but not both. An incompatible variable is rejected (TypeError) when it is added (here or by addArc()).

Definition at line 424 of file BayesNet_tpl.h.

424 {
426 }

References add().

Referenced by _addAggregator_().

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

◆ addMEDIAN()

template<GUM_Numeric GUM_SCALAR>
NodeId gum::BayesNet< GUM_SCALAR >::addMEDIAN ( const DiscreteVariable & var)

Others aggregators.

MIN, MAX, MEDIAN, AMPLITUDE and SUM are computed on the values of the parents (DiscreteVariable::numerical()), and the result is mapped onto the closest value of the aggregator (DiscreteVariable::closestIndex(), saturated at both bounds). AMPLITUDE and SUM need numerical variables; MIN, MAX and MEDIAN accept labelized variables (order of the labels) or numerical ones, but not both. An incompatible variable is rejected (TypeError) when it is added (here or by addArc()).

Definition at line 429 of file BayesNet_tpl.h.

429 {
431 }

References add().

Referenced by _addAggregator_().

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

◆ addMIN()

template<GUM_Numeric GUM_SCALAR>
NodeId gum::BayesNet< GUM_SCALAR >::addMIN ( const DiscreteVariable & var)

Others aggregators.

MIN, MAX, MEDIAN, AMPLITUDE and SUM are computed on the values of the parents (DiscreteVariable::numerical()), and the result is mapped onto the closest value of the aggregator (DiscreteVariable::closestIndex(), saturated at both bounds). AMPLITUDE and SUM need numerical variables; MIN, MAX and MEDIAN accept labelized variables (order of the labels) or numerical ones, but not both. An incompatible variable is rejected (TypeError) when it is added (here or by addArc()).

Definition at line 434 of file BayesNet_tpl.h.

434 {
436 }

References add().

Referenced by _addAggregator_().

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

◆ addNoisyAND() [1/2]

template<GUM_Numeric GUM_SCALAR>
NodeId gum::BayesNet< GUM_SCALAR >::addNoisyAND ( const DiscreteVariable & var,
GUM_SCALAR external_weight )

Add a variable, its associate node and a noisyAND implementation.

The id of the new variable is automatically generated.

Parameters
varThe variable added by copy.
external_weightsee gum::MultiDimNoisyAND
Returns
the id of the added variable.

Definition at line 490 of file BayesNet_tpl.h.

491 {
493 }

References add().

Here is the call graph for this function:

◆ addNoisyAND() [2/2]

template<GUM_Numeric GUM_SCALAR>
NodeId gum::BayesNet< GUM_SCALAR >::addNoisyAND ( const DiscreteVariable & var,
GUM_SCALAR external_weight,
NodeId id )

Add a variable, its associate node and a noisyAND implementation.

Parameters
varThe variable added by copy
external_weightsee gum::MultiDimNoisyAND
idproposed gum::nodeId for the variable
Warning
give an id should be reserved for rare and specific situations !!!
Returns
the id of the added variable.

Definition at line 519 of file BayesNet_tpl.h.

521 {
523 }

References add().

Referenced by _addICIModel_().

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

◆ addNoisyOR() [1/2]

template<GUM_Numeric GUM_SCALAR>
NodeId gum::BayesNet< GUM_SCALAR >::addNoisyOR ( const DiscreteVariable & var,
GUM_SCALAR external_weight )

Add a variable, it's associate node and a gum::noisyOR implementation.

The id of the new variable is automatically generated. Since it seems that the 'classical' noisyOR is the Compound noisyOR, we keep the gum::BayesNet::addNoisyOR as an alias for gum::BayesNet::addNoisyORCompound

Parameters
varThe variable added by copy.
external_weightsee ref gum::MultiDimNoisyORNet,gum::MultiDimNoisyORCompound
Returns
the id of the added variable.

Definition at line 472 of file BayesNet_tpl.h.

473 {
475 }

References addNoisyORCompound().

Here is the call graph for this function:

◆ addNoisyOR() [2/2]

template<GUM_Numeric GUM_SCALAR>
NodeId gum::BayesNet< GUM_SCALAR >::addNoisyOR ( const DiscreteVariable & var,
GUM_SCALAR external_weight,
NodeId id )

Add a variable, its associate node and a noisyOR implementation.

Since it seems that the 'classical' noisyOR is the Compound noisyOR, we keep the addNoisyOR as an alias for addNoisyORCompound.

Parameters
varThe variable added by copy.
external_weightsee gum::MultiDimNoisyORNet, gum::MultiDimNoisyORCompound
idThe chosen id
Warning
give an id should be reserved for rare and specific situations !!!
Returns
the id of the added variable.
Exceptions
DuplicateElementif id is already used

Definition at line 512 of file BayesNet_tpl.h.

514 {
516 }

◆ addNoisyORCompound() [1/2]

template<GUM_Numeric GUM_SCALAR>
NodeId gum::BayesNet< GUM_SCALAR >::addNoisyORCompound ( const DiscreteVariable & var,
GUM_SCALAR external_weight )

Add a variable, it's associate node and a gum::noisyOR implementation.

The id of the new variable is automatically generated. Since it seems that the 'classical' noisyOR is the Compound noisyOR, we keep the gum::BayesNet::addNoisyOR as an alias for gum::BayesNet::addNoisyORCompound

Parameters
varThe variable added by copy.
external_weightsee ref gum::MultiDimNoisyORNet,gum::MultiDimNoisyORCompound
Returns
the id of the added variable.

Definition at line 478 of file BayesNet_tpl.h.

References add().

Referenced by _addICIModel_(), and addNoisyOR().

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

◆ addNoisyORCompound() [2/2]

template<GUM_Numeric GUM_SCALAR>
NodeId gum::BayesNet< GUM_SCALAR >::addNoisyORCompound ( const DiscreteVariable & var,
GUM_SCALAR external_weight,
NodeId id )

Add a variable, its associate node and a noisyOR implementation.

Since it seems that the 'classical' noisyOR is the Compound noisyOR, we keep the addNoisyOR as an alias for addNoisyORCompound.

Parameters
varThe variable added by copy.
external_weightsee gum::MultiDimNoisyORNet, gum::MultiDimNoisyORCompound
idThe chosen id
Warning
give an id should be reserved for rare and specific situations !!!
Returns
the id of the added variable.
Exceptions
DuplicateElementif id is already used

Definition at line 533 of file BayesNet_tpl.h.

535 {
537 }

◆ addNoisyORNet() [1/2]

template<GUM_Numeric GUM_SCALAR>
NodeId gum::BayesNet< GUM_SCALAR >::addNoisyORNet ( const DiscreteVariable & var,
GUM_SCALAR external_weight )

Add a variable, it's associate node and a gum::noisyOR implementation.

The id of the new variable is automatically generated. Since it seems that the 'classical' noisyOR is the Compound noisyOR, we keep the gum::BayesNet::addNoisyOR as an alias for gum::BayesNet::addNoisyORCompound

Parameters
varThe variable added by copy.
external_weightsee ref gum::MultiDimNoisyORNet,gum::MultiDimNoisyORCompound
Returns
the id of the added variable.

Definition at line 484 of file BayesNet_tpl.h.

485 {
487 }

References add().

Referenced by _addICIModel_().

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

◆ addNoisyORNet() [2/2]

template<GUM_Numeric GUM_SCALAR>
NodeId gum::BayesNet< GUM_SCALAR >::addNoisyORNet ( const DiscreteVariable & var,
GUM_SCALAR external_weight,
NodeId id )

Add a variable, its associate node and a noisyOR implementation.

Since it seems that the 'classical' noisyOR is the Compound noisyOR, we keep the addNoisyOR as an alias for addNoisyORCompound.

Parameters
varThe variable added by copy.
external_weightsee gum::MultiDimNoisyORNet, gum::MultiDimNoisyORCompound
idThe chosen id
Warning
give an id should be reserved for rare and specific situations !!!
Returns
the id of the added variable.
Exceptions
DuplicateElementif id is already used

Definition at line 540 of file BayesNet_tpl.h.

542 {
544 }

References add().

Here is the call graph for this function:

◆ addOR()

template<GUM_Numeric GUM_SCALAR>
NodeId gum::BayesNet< GUM_SCALAR >::addOR ( const DiscreteVariable & var)

Add a variable, it's associate node and an OR implementation.

The id of the new variable is automatically generated.

Warning
OR is implemented as a gum::aggregator::Or which means that if parents are not boolean, all value>1 is True
Parameters
varThe variable added by copy.
Returns
the id of the added variable.
Exceptions
SizeErrorif variable.domainSize()>2

Definition at line 439 of file BayesNet_tpl.h.

439 {
440 if (var.domainSize() > 2) GUM_ERROR(SizeError, "an OR has to be boolean")
441
443 }

References add(), gum::DiscreteVariable::domainSize(), and GUM_ERROR.

Referenced by _addAggregator_().

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

◆ addSUM()

template<GUM_Numeric GUM_SCALAR>
NodeId gum::BayesNet< GUM_SCALAR >::addSUM ( const DiscreteVariable & var)

Others aggregators.

MIN, MAX, MEDIAN, AMPLITUDE and SUM are computed on the values of the parents (DiscreteVariable::numerical()), and the result is mapped onto the closest value of the aggregator (DiscreteVariable::closestIndex(), saturated at both bounds). AMPLITUDE and SUM need numerical variables; MIN, MAX and MEDIAN accept labelized variables (order of the labels) or numerical ones, but not both. An incompatible variable is rejected (TypeError) when it is added (here or by addArc()).

Definition at line 446 of file BayesNet_tpl.h.

446 {
448 }

References add().

Referenced by _addAggregator_().

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

◆ addWeightedArc() [1/2]

template<GUM_Numeric GUM_SCALAR>
void gum::BayesNet< GUM_SCALAR >::addWeightedArc ( NodeId tail,
NodeId head,
GUM_SCALAR causalWeight )

Add an arc in the BN, and update arc.head's CPT.

Parameters
headand
tailas NodeId
causalWeightsee gum::MultiDimICIModel
Exceptions
InvalidArcIf arc.tail and/or arc.head are not in the BN.
InvalidArcIf variable in arc.head is not a NoisyOR variable.

Definition at line 547 of file BayesNet_tpl.h.

547 {
548 if (auto* CImodel
549 = dynamic_cast< const MultiDimICIModel< GUM_SCALAR >* >(cpt(head).content())) {
550 // or is OK
551 addArc(tail, head);
552
553 try {
554 CImodel->causalWeight(variable(tail), causalWeight);
555 } catch (Exception const&) {
557 throw;
558 }
559 } else {
561 "Head variable (" << variable(head).name() << ") is not a CIModel variable !")
562 }
563 }
void eraseArc(const Arc &arc)
Removes an arc in the BN, and update head's CTP.

References addArc(), cpt(), eraseArc(), and variable().

Referenced by addWeightedArc().

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

◆ addWeightedArc() [2/2]

template<GUM_Numeric GUM_SCALAR>
void gum::BayesNet< GUM_SCALAR >::addWeightedArc ( std::string_view tail,
std::string_view head,
GUM_SCALAR causalWeight )

Add an arc in the BN, and update arc.head's CPT.

Parameters
headand
tailas std::string
causalWeightsee gum::MultiDimICIModel
Exceptions
NotFoundif no node with sun names is found
InvalidArcIf arc.tail and/or arc.head are not in the BN.
InvalidArcIf variable in arc.head is not a NoisyOR variable.

Definition at line 761 of file BayesNet_tpl.h.

763 {
765 }
void addWeightedArc(NodeId tail, NodeId head, GUM_SCALAR causalWeight)
Add an arc in the BN, and update arc.head's CPT.

References addWeightedArc(), and idFromName().

Here is the call graph for this function:

◆ ancestors() [1/2]

INLINE NodeSet gum::DAGmodel::ancestors ( const NodeId id) const
inherited

returns the set of nodes with directed path ingoing to a given node

Note that the set of nodes returned may be empty if no path within the ArcGraphPart is ingoing to the given node.

Parameters
idthe node which is the head of a directed path with the returned nodes
namethe name of the node which is the head of a directed path with the returned nodes
Exceptions
NotFoundif the node does not exist in the model

Definition at line 167 of file DAGmodel_inl.h.

167 {
168 auto res = dag_.ancestors(id);
169 if (res.empty()) _checkNodeExists_(id);
170 return res;
171 }
void _checkNodeExists_(NodeId id) const
NodeSet ancestors(NodeId id) const
returns the set of all ancestors of id (nodes from which id is reachable)

References _checkNodeExists_(), gum::DiGraph::ancestors(), dag_, and gum::Set< Key >::empty().

Here is the call graph for this function:

◆ ancestors() [2/2]

INLINE NodeSet gum::DAGmodel::ancestors ( std::string_view name) const
inherited

return true if the arc tail->head exists in the DAGmodel

Parameters
tailthe nodeId (or the name) of the tail in tail->head
headthe nodeId (or the name) of the head in tail->head
Returns
true if the arc exists

Definition at line 173 of file DAGmodel_inl.h.

173 {
174 return dag_.ancestors(idFromName(name));
175 }
NodeId idFromName(std::string_view name) const override
Returns the NodeId of a variable given its name.

References gum::DiGraph::ancestors(), dag_, and gum::DiscreteGraphicalModel::idFromName().

Here is the call graph for this function:

◆ arcs()

INLINE const ArcSet & gum::DAGmodel::arcs ( ) const
inherited

return true if the arc tail->head exists in the DAGmodel

Parameters
tailthe nodeId (or the name) of the tail in tail->head
headthe nodeId (or the name) of the head in tail->head
Returns
true if the arc exists

Definition at line 73 of file DAGmodel_inl.h.

73{ return dag_.arcs(); }
const ArcSet & arcs() const
returns the set of arcs stored within the ArcGraphPart

References gum::ArcGraphPart::arcs(), and dag_.

Referenced by gum::EssentialGraph::_buildEssentialGraph_(), hasSameStructure(), gum::MarkovBlanket::hasSameStructure(), and gum::BayesNetFragment< GUM_SCALAR >::toBN().

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

◆ beginTopologyTransformation()

template<GUM_Numeric GUM_SCALAR>
void gum::BayesNet< GUM_SCALAR >::beginTopologyTransformation ( )

When inserting/removing arcs, node CPTs change their dimension with a cost in time.

begin Multiple Change for all CPTs

These functions delay the CPTs change to be done just once at the end of a sequence of topology modification. begins a sequence of insertions/deletions of arcs without changing the dimensions of the CPTs.

Definition at line 573 of file BayesNet_tpl.h.

573 {
574 for (const auto node: nodes())
575 _probaMap_[node]->beginMultipleChanges();
576 }
const NodeGraphPart & nodes() const final
Returns a named copy of the internal DAG: each node id is assigned the name of the corresponding vari...

References _probaMap_, and gum::DAGmodel::nodes().

Here is the call graph for this function:

◆ changeTensor() [1/2]

template<GUM_Numeric GUM_SCALAR>
void gum::BayesNet< GUM_SCALAR >::changeTensor ( NodeId id,
Tensor< GUM_SCALAR > * newPot )

change the CPT associated to nodeId to newPot delete the old CPT associated to nodeId.

Exceptions
NotAllowedif newPot has not the same signature as probaMap[NodeId]

Definition at line 630 of file BayesNet_tpl.h.

630 {
631 if (cpt(id).nbrDim() != newPot->nbrDim()) {
633 "cannot exchange tensors with different "
634 "dimensions for variable with id "
635 << id)
636 }
637
638 for (Idx i = 0; i < cpt(id).nbrDim(); i++) {
639 if (&cpt(id).variable(i) != &(newPot->variable(i))) {
641 "cannot exchange tensors because, for variable with id " << id << ", dimension "
642 << i << " differs. ")
643 }
644 }
645
647 }
void _unsafeChangeTensor_(NodeId id, Tensor< GUM_SCALAR > *newPot)
change the CPT associated to nodeId to newPot delete the old CPT associated to nodeId.

References cpt().

Referenced by changeTensor().

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

◆ changeTensor() [2/2]

template<GUM_Numeric GUM_SCALAR>
void gum::BayesNet< GUM_SCALAR >::changeTensor ( std::string_view name,
Tensor< GUM_SCALAR > * newPot )

Definition at line 656 of file BayesNet_tpl.h.

656 {
658 }
void changeTensor(NodeId id, Tensor< GUM_SCALAR > *newPot)
change the CPT associated to nodeId to newPot delete the old CPT associated to nodeId.

References changeTensor(), and idFromName().

Here is the call graph for this function:

◆ changeVariableLabel() [1/2]

template<GUM_Numeric GUM_SCALAR>
void gum::BayesNet< GUM_SCALAR >::changeVariableLabel ( NodeId id,
std::string_view old_label,
std::string_view new_label )

Changes a variable's label in the gum::BayesNet.

This will change the gum::LabelizedVariable names in the gum::BayesNet.

Exceptions
DuplicateLabelRaised if new_label is already used in this gum::LabelizedVariable.
NotFoundRaised if no variable matches id or if the variable is not a LabelizedVariable

Definition at line 179 of file BayesNet_tpl.h.

181 {
183 GUM_ERROR(NotFound, "Variable " << id << " is not a LabelizedVariable.")
184
186 if (var == nullptr) GUM_ERROR(TypeError, "Variable " << id << " is not a LabelizedVariable.")
187
189 }

References GUM_ERROR, gum::LABELIZED, and variable().

Referenced by changeVariableLabel().

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

◆ changeVariableLabel() [2/2]

template<GUM_Numeric GUM_SCALAR>
void gum::BayesNet< GUM_SCALAR >::changeVariableLabel ( std::string_view name,
std::string_view old_label,
std::string_view new_label )

Changes a variable's name.

Definition at line 744 of file BayesNet_tpl.h.

746 {
748 }
void changeVariableLabel(NodeId id, std::string_view old_label, std::string_view new_label)
Changes a variable's label in the gum::BayesNet.

References changeVariableLabel(), and idFromName().

Here is the call graph for this function:

◆ changeVariableName() [1/2]

template<GUM_Numeric GUM_SCALAR>
void gum::BayesNet< GUM_SCALAR >::changeVariableName ( NodeId id,
std::string_view new_name )

Changes a variable's name in the gum::BayesNet.

This will change the gum::DiscreteVariable names in the gum::BayesNet.

Exceptions
DuplicateLabelRaised if newName is already used in this gum::BayesNet.
NotFoundRaised if no variable matches id.

Definition at line 174 of file BayesNet_tpl.h.

174 {
175 this->varMap_.changeName(id, new_name);
176 }

Referenced by changeVariableName().

Here is the caller graph for this function:

◆ changeVariableName() [2/2]

template<GUM_Numeric GUM_SCALAR>
void gum::BayesNet< GUM_SCALAR >::changeVariableName ( std::string_view name,
std::string_view new_name )

Changes a variable's name.

Definition at line 738 of file BayesNet_tpl.h.

739 {
741 }
void changeVariableName(NodeId id, std::string_view new_name)
Changes a variable's name in the gum::BayesNet.

References changeVariableName(), and idFromName().

Here is the call graph for this function:

◆ check()

template<GUM_Numeric GUM_SCALAR>
std::vector< std::string > gum::IBayesNet< GUM_SCALAR >::check ( ) const
inherited

Check if the BayesNet is consistent (variables, CPT).

A distribution is considered normalized if its sum is in [1-e, 1+e], where e is the standard tolerance of the configuration (core.epsilonStandard, 1e-6 by default). A sum that is out of this interval but in [1-c, 1+c], where c is the coarse tolerance (core.epsilonCoarse, 1e-2 by default), is reported with the hint "(normalization problem ?)".

Returns
a list of comments on the consistency of the Bayes Net

Definition at line 320 of file IBayesNet_tpl.h.

320 {
322
323 const double epsilon = config().epsilonStandard();
324 const double error_epsilon = config().epsilonCoarse();
325
326 // CHECKING domain
327 for (const auto i: nodes())
328 if (variable(i).domainSize() < 2) {
330 s << "Variable " << variable(i).name() << ": not consistent (domainSize=1).";
331 comments.push_back(s.str());
332 }
333
334 // CHECKING parameters are probabilities
335 // >0
336 for (const auto i: nodes()) {
337 const auto [amin, minval] = cpt(i).argmin();
338 if (minval < (GUM_SCALAR)0.0) {
340 s << "Variable " << variable(i).name() << " : P(" << *(amin.begin()) << ") < 0.0";
341 comments.push_back(s.str());
342 }
343 }
344 // <1
345 for (const auto i: nodes()) {
346 const auto [amax, maxval] = cpt(i).argmax();
347 if (maxval > (GUM_SCALAR)1.0) {
349 s << "Variable " << variable(i).name() << " : P(" << *(amax.begin()) << ") > 1.0";
350 comments.push_back(s.str());
351 }
352 }
353
354 // CHECKING distributions sum to 1
355 for (const auto i: nodes()) {
356 const auto p = cpt(i).sumOut({&variable(i)});
357 const auto [amin, minval] = p.argmin();
358 if (minval < (GUM_SCALAR)(1.0 - epsilon)) {
360 s << "Variable " << variable(i).name() << " : ";
361 if (!parents(i).empty()) s << "with (at least) parents " << *(amin.begin()) << ", ";
362 s << "the CPT sum to less than 1";
363 if (minval > (GUM_SCALAR)(1.0 - error_epsilon)) s << " (normalization problem ?)";
364 s << ".";
365 comments.push_back(s.str());
366 continue;
367 }
368 const auto [amax, maxval] = p.argmax();
369 if (maxval > (GUM_SCALAR)(1.0 + epsilon)) {
371 s << "Variable " << variable(i).name() << " : ";
372 if (!parents(i).empty()) s << "with (at least) parents " << *(amax.begin()) << ", ";
373 s << "the CPT sum to more than 1";
374 if (maxval < (GUM_SCALAR)(1.0 + error_epsilon)) s << " (normalization problem ?)";
375 s << ".";
376 comments.push_back(s.str());
377 }
378 }
379
380 return comments;
381 }
const NodeSet & parents(const NodeId id) const
returns the set of nodes with arc ingoing to a given node
const DiscreteVariable & variable(NodeId id) const override
Returns a constant reference over a variable given its node id.
virtual bool empty() const
Return true if this graphical model is empty.
Class representing the minimal interface for Bayesian network with no numerical data.
Definition IBayesNet.h:79
virtual const Tensor< GUM_SCALAR > & cpt(NodeId varId) const =0
Returns the CPT of a variable.

References gum::config(), cpt(), gum::GraphicalModel::empty(), gum::Configuration::epsilonCoarse(), gum::Configuration::epsilonStandard(), gum::DAGmodel::nodes(), gum::DAGmodel::parents(), and gum::DiscreteGraphicalModel::variable().

Referenced by cpt().

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

◆ children() [1/4]

INLINE const NodeSet & gum::DAGmodel::children ( const NodeId id) const
inherited

returns the set of nodes with arc outgoing from a given node

Note that the set of nodes returned may be empty if no node is outgoing from the given node.

Parameters
idthe node which is the tail of an arc with the returned nodes
namethe name of the node which is the tail of an arc with the returned nodes
Exceptions
NotFoundif the node does not exist in the model

Definition at line 109 of file DAGmodel_inl.h.

109 {
110 const NodeSet& res = dag_.children(id);
111 if (res.empty()) _checkNodeExists_(id);
112 return res;
113 }
NodeSet children(const NodeSet &ids) const
returns the set of nodes which consists in the node and its parents returns the set of children of a ...
Set< NodeId > NodeSet
Some typdefs and define for shortcuts ...

Referenced by gum::BayesNet< GUM_SCALAR >::erase(), gum::prm::ClassBayesNet< GUM_SCALAR >::toDot(), and gum::prm::InstanceBayesNet< GUM_SCALAR >::toDot().

Here is the caller graph for this function:

◆ children() [2/4]

INLINE NodeSet gum::DAGmodel::children ( const NodeSet & ids) const
inherited

returns the children of a set of nodes

Exceptions
NotFoundif one of the nodes does not exist in the model

Definition at line 119 of file DAGmodel_inl.h.

119 {
120 for (const auto id: ids)
122 return dag_.children(ids);
123 }
std::vector< NodeId > ids(const std::vector< std::string > &names) const
transform a vector of names into a vector of nodeId

References _checkNodeExists_(), and gum::GraphicalModel::ids().

Here is the call graph for this function:

◆ children() [3/4]

INLINE NodeSet gum::DAGmodel::children ( const std::vector< std::string > & names) const
inherited

return true if the arc tail->head exists in the DAGmodel

Parameters
tailthe nodeId (or the name) of the tail in tail->head
headthe nodeId (or the name) of the head in tail->head
Returns
true if the arc exists

Definition at line 126 of file DAGmodel_inl.h.

126 {
127 return dag_.children(nodeset(names));
128 }
std::vector< std::string > names(const std::vector< NodeId > &ids) const
transform a vector of NodeId in a vector of names
NodeSet nodeset(const std::vector< std::string > &names) const
transform a vector of names into a NodeSet

References gum::ArcGraphPart::children(), dag_, gum::GraphicalModel::names(), and gum::GraphicalModel::nodeset().

Here is the call graph for this function:

◆ children() [4/4]

INLINE const NodeSet & gum::DAGmodel::children ( std::string_view name) const
inherited

return true if the arc tail->head exists in the DAGmodel

Parameters
tailthe nodeId (or the name) of the tail in tail->head
headthe nodeId (or the name) of the head in tail->head
Returns
true if the arc exists

Definition at line 115 of file DAGmodel_inl.h.

115 {
116 return dag_.children(idFromName(name));
117 }

◆ clear()

template<GUM_Numeric GUM_SCALAR>
void gum::BayesNet< GUM_SCALAR >::clear ( )

clear the whole Bayes net *

Definition at line 270 of file BayesNet_tpl.h.

270 {
271 if (!this->empty()) {
272 auto l = this->nodes();
273 for (const auto no: l) {
274 this->erase(no);
275 }
276 }
277 }
void erase(NodeId varId)
Remove a variable from the gum::BayesNet.

References gum::GraphicalModel::empty(), erase(), and gum::DAGmodel::nodes().

Here is the call graph for this function:

◆ completeInstantiation()

INLINE Instantiation gum::GraphicalModel::completeInstantiation ( ) const
inherited

Get an instantiation over all the variables of the model.

Definition at line 104 of file graphicalModel_inl.h.

104 {
105 Instantiation I;
106
107 for (const auto node: nodes())
108 I << variable(node);
109
110 return I;
111 }
virtual const NodeGraphPart & nodes() const =0
Returns the number of variables in this Directed Graphical Model.

References nodes(), and variable().

Referenced by nodes().

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

◆ connectedComponents()

INLINE NodeProperty< NodeId > gum::DAGmodel::connectedComponents ( ) const
inherited

Returns the weakly connected components of the underlying DAG. Each node maps to the id of its component root.

Definition at line 153 of file DAGmodel_inl.h.

153 {
154 return dag_.connectedComponents();
155 }
NodeProperty< NodeId > connectedComponents() const
returns a property {node:id of weakly connected component}

References gum::DiGraph::connectedComponents(), and dag_.

Here is the call graph for this function:

◆ contextualize()

template<GUM_Numeric GUM_SCALAR>
BayesNet< GUM_SCALAR > gum::BayesNet< GUM_SCALAR >::contextualize ( const gum::Instantiation & observations,
const gum::Instantiation & interventions ) const

create a contextual BN from this and a set of hard observations and hard interventions.

Parameters
observationsthe hard observations
interventionsthe hard interventions
Returns
a new BN with the same structure as this, but with the CPTs modified to reflect the observations and interventions
Warning
The original BN is not modified. The returned BN is not a copy of the original BN, but a new BN with copied variables and modified structure and CPTs.
Exceptions
ArgumentErrorif the observations and interventions are not mutually exclusive

Definition at line 662 of file BayesNet_tpl.h.

663 {
665 for (gum::Idx i = 0; i < observations.nbrDim(); i++) {
666 if (interventions.contains(observations.variable(i))) {
668 "Cannot have both an observation and an intervention on the same variable")
669 }
671 }
672 for (gum::Idx i = 0; i < interventions.nbrDim(); i++) {
674 }
675 all.setVals(observations);
676 all.setVals(interventions);
677
679
681
683 for (gum::Idx i = 0; i < observations.nbrDim(); i++) {
685 const gum::NodeId nod = this->idFromName(nam);
686 for (gum::NodeId child: this->children(nod)) {
688 }
689 }
690 for (gum::Idx i = 0; i < interventions.nbrDim(); i++) {
692 const gum::NodeId nod = this->idFromName(nam);
693 for (gum::NodeId child: this->children(nod)) {
695 }
696 for (gum::NodeId par: this->parents(nod)) {
697 const auto v1 = bn.idFromName(this->variable(par).name());
698 const auto v2 = bn.idFromName(nam);
699 if (bn.existsArc(v1, v2)) bn.eraseArc(v1, v2);
700 }
701 cpt_changed.insert(bn.idFromName(nam));
704 interventions.val(i)));
705 }
707
708 for (gum::Idx i = 0; i < all.nbrDim(); i++) {
709 const gum::NodeId nod = this->idFromName(all.variable(i).name());
710 for (gum::NodeId child: this->children(nod)) {
711 if (!cpt_changed.contains(child)) {
712 cpt_changed.insert(child);
714 .fillWith(this->cpt(child).extract(all));
715 }
716 }
717 }
718
719 return bn;
720 }
void endTopologyTransformation()
terminates a sequence of insertions/deletions of arcs by adjusting all CPTs dimensions.
void beginTopologyTransformation()
When inserting/removing arcs, node CPTs change their dimension with a cost in time.
bool existsArc(const NodeId tail, const NodeId head) const
return true if the arc tail->head exists in the DAGmodel
const NodeSet & children(const NodeId id) const
returns the set of nodes with arc outgoing from a given node

◆ cpt() [1/2]

template<GUM_Numeric GUM_SCALAR>
const Tensor< GUM_SCALAR > & gum::BayesNet< GUM_SCALAR >::cpt ( NodeId varId) const
finalvirtual

Returns the CPT of a variable.

Parameters
varIdA variable's id in the gum::BayesNet.
Returns
The variable's CPT.
Exceptions
NotFoundIf no variable's id matches varId.

Implements gum::IBayesNet< GUM_SCALAR >.

Definition at line 244 of file BayesNet_tpl.h.

244 {
245 return *(_probaMap_[varId]);
246 }

References _probaMap_.

Referenced by add(), addWeightedArc(), changeTensor(), cpt(), reverseArc(), and gum::BayesNetFragment< GUM_SCALAR >::toBN().

Here is the caller graph for this function:

◆ cpt() [2/2]

template<GUM_Numeric GUM_SCALAR>
const Tensor< GUM_SCALAR > & gum::BayesNet< GUM_SCALAR >::cpt ( std::string_view name) const

Returns the CPT of a variable.

Definition at line 723 of file BayesNet_tpl.h.

723 {
724 return cpt(idFromName(name));
725 }

References cpt(), and idFromName().

Here is the call graph for this function:

◆ dag()

INLINE DAG gum::DAGmodel::dag ( ) const
nodiscardinherited

Returns a named copy of the internal DAG: each node id is assigned the name of the corresponding variable.

O(n) — allocates a new DAG. For a stable reference (listeners, long-lived pointers), use internalDag().

Definition at line 61 of file DAGmodel_inl.h.

61 {
62 DAG g = dag_;
63 _nameNodes_(g);
64 return g;
65 }
void _nameNodes_(NodeGraphPart &g) const
Names every node of g using variable(id).name() for each node id in g.

References gum::GraphicalModel::_nameNodes_(), and dag_.

Referenced by gum::BayesNetFragment< GUM_SCALAR >::BayesNetFragment(), gum::MarginalTargetedInference< GUM_SCALAR >::MarginalTargetedInference(), gum::BayesNet< GUM_SCALAR >::add(), gum::BayesNet< GUM_SCALAR >::reverseArc(), and gum::InfluenceDiagram< GUM_SCALAR >::toString().

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

◆ descendants() [1/2]

INLINE NodeSet gum::DAGmodel::descendants ( const NodeId id) const
inherited

returns the set of nodes with directed path outgoing from a given node

Note that the set of nodes returned may be empty if no path within the ArcGraphPart is outgoing from the given node.

Parameters
idthe node which is the tail of a directed path with the returned nodes
namethe name of the node which is the tail of a directed path with the returned nodes
Exceptions
NotFoundif the node does not exist in the model

Definition at line 157 of file DAGmodel_inl.h.

157 {
158 auto res = dag_.descendants(id);
159 if (res.empty()) _checkNodeExists_(id);
160 return res;
161 }
NodeSet descendants(NodeId id) const
returns the set of all descendants of id (nodes reachable from id)

References _checkNodeExists_(), dag_, gum::DiGraph::descendants(), and gum::Set< Key >::empty().

Here is the call graph for this function:

◆ descendants() [2/2]

INLINE NodeSet gum::DAGmodel::descendants ( std::string_view name) const
inherited

return true if the arc tail->head exists in the DAGmodel

Parameters
tailthe nodeId (or the name) of the tail in tail->head
headthe nodeId (or the name) of the head in tail->head
Returns
true if the arc exists

Definition at line 163 of file DAGmodel_inl.h.

163 {
164 return dag_.descendants(idFromName(name));
165 }

References dag_, gum::DiGraph::descendants(), and gum::DiscreteGraphicalModel::idFromName().

Here is the call graph for this function:

◆ dim()

template<GUM_Numeric GUM_SCALAR>
Size gum::IBayesNet< GUM_SCALAR >::dim ( ) const
inherited

Returns the dimension (the number of free parameters) in this bayes net.

\( dim(G)=\sum_{i \in nodes} ((r_i-1)\cdot q_i) \) where \( r_i \) is the number of instantiations of node \( i \) and \( q_i \) is the number of instantiations of its parents.

Definition at line 116 of file IBayesNet_tpl.h.

116 {
117 Size dim = 0;
118
119 for (auto node: nodes()) {
120 Size q = 1;
121
122 for (auto parent: parents(node))
123 q *= variable(parent).domainSize();
124
125 dim += (variable(node).domainSize() - 1) * q;
126 }
127
128 return dim;
129 }
Size dim() const
Returns the dimension (the number of free parameters) in this bayes net.

References dim(), gum::DAGmodel::nodes(), gum::DAGmodel::parents(), and gum::DiscreteGraphicalModel::variable().

Referenced by cpt(), and dim().

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

◆ empty()

INLINE bool gum::GraphicalModel::empty ( ) const
virtualinherited

Return true if this graphical model is empty.

Definition at line 114 of file graphicalModel_inl.h.

114{ return size() == 0; }
virtual Size size() const =0
Returns the number of variables in this Directed Graphical Model.

References size().

Referenced by gum::IBayesNet< GUM_SCALAR >::check(), gum::BayesNet< GUM_SCALAR >::clear(), and size().

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

◆ endTopologyTransformation()

template<GUM_Numeric GUM_SCALAR>
void gum::BayesNet< GUM_SCALAR >::endTopologyTransformation ( )

terminates a sequence of insertions/deletions of arcs by adjusting all CPTs dimensions.

end Multiple Change for all CPTs

Definition at line 580 of file BayesNet_tpl.h.

580 {
581 for (const auto node: nodes())
582 _probaMap_[node]->endMultipleChanges();
583 }

References _probaMap_, and gum::DAGmodel::nodes().

Here is the call graph for this function:

◆ erase() [1/3]

template<GUM_Numeric GUM_SCALAR>
void gum::BayesNet< GUM_SCALAR >::erase ( const DiscreteVariable & var)

Remove a variable from the gum::BayesNet.

Removes the corresponding variable from the gum::BayesNet and from all of it's children gum::Tensor.

If no variable matches the given variable, then nothing is done.

Parameters
varA reference on the variable to remove.

Definition at line 249 of file BayesNet_tpl.h.

249 {
250 erase(this->varMap_.get(var));
251 }

References erase(), and gum::DiscreteGraphicalModel::varMap_.

Here is the call graph for this function:

◆ erase() [2/3]

template<GUM_Numeric GUM_SCALAR>
void gum::BayesNet< GUM_SCALAR >::erase ( NodeId varId)

Remove a variable from the gum::BayesNet.

Removes the corresponding variable from the gum::BayesNet and from all of it's children gum::Tensor.

If no variable matches the given id, then nothing is done.

Parameters
varIdThe variable's id to remove.

Definition at line 254 of file BayesNet_tpl.h.

254 {
255 if (this->varMap_.exists(varId)) {
256 // Reduce the variable child's CPT
257 for (const NodeSet& children = this->children(varId); const auto c: children) {
258 _probaMap_[c]->erase(variable(varId));
259 }
260
261 delete _probaMap_[varId];
262
263 _probaMap_.erase(varId);
264 this->varMap_.erase(varId);
265 this->dag_.eraseNode(varId);
266 }
267 }

References _probaMap_, gum::DAGmodel::children(), gum::DAGmodel::dag_, variable(), and gum::DiscreteGraphicalModel::varMap_.

Referenced by clear(), erase(), and erase().

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

◆ erase() [3/3]

template<GUM_Numeric GUM_SCALAR>
void gum::BayesNet< GUM_SCALAR >::erase ( std::string_view name)

Removes a variable from the gum::BayesNet.

Definition at line 728 of file BayesNet_tpl.h.

728 {
730 }

References erase(), and idFromName().

Here is the call graph for this function:

◆ eraseArc() [1/3]

template<GUM_Numeric GUM_SCALAR>
void gum::BayesNet< GUM_SCALAR >::eraseArc ( const Arc & arc)

Removes an arc in the BN, and update head's CTP.

If (tail, head) doesn't exist, the nothing happens.

Parameters
arcThe arc removed.

Definition at line 305 of file BayesNet_tpl.h.

305 {
306 if (this->varMap_.exists(arc.tail()) && this->varMap_.exists(arc.head())) {
307 NodeId head = arc.head();
308 NodeId tail = arc.tail();
309 this->dag_.eraseArc(arc);
310 // Remove parent from child's CPT
311 (*(_probaMap_[head])) >> variable(tail);
312 }
313 }
bool exists(NodeId id) const
Return true if id matches a node.

References gum::DAGmodel::dag_, gum::Arc::head(), gum::Arc::tail(), and gum::DiscreteGraphicalModel::varMap_.

Referenced by addWeightedArc(), eraseArc(), and eraseArc().

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

◆ eraseArc() [2/3]

template<GUM_Numeric GUM_SCALAR>
void gum::BayesNet< GUM_SCALAR >::eraseArc ( NodeId tail,
NodeId head )

Removes an arc in the BN, and update head's CTP.

If (tail, head) doesn't exist, the nothing happens.

Parameters
headand
tailas NodeId

Definition at line 316 of file BayesNet_tpl.h.

316 {
318 }

References gum::Arc::Arc(), and eraseArc().

Here is the call graph for this function:

◆ eraseArc() [3/3]

template<GUM_Numeric GUM_SCALAR>
void gum::BayesNet< GUM_SCALAR >::eraseArc ( std::string_view tail,
std::string_view head )

Removes an arc in the BN, and update head's CTP.

Definition at line 751 of file BayesNet_tpl.h.

751 {
753 }

References eraseArc(), and idFromName().

Here is the call graph for this function:

◆ evEq()

template<GUM_Numeric GUM_SCALAR>
Tensor< GUM_SCALAR > gum::IBayesNet< GUM_SCALAR >::evEq ( std::string_view name,
double value ) const
inherited
Returns
a Tensor for a (numerical) discrete variable representing an evidence with a float as observed value

Definition at line 384 of file IBayesNet_tpl.h.

384 {
386 }
const DiscreteVariable & variableFromName(std::string_view name) const override
Returns a constant reference over a variable given its name.
static Tensor< GUM_SCALAR > evEq(const DiscreteVariable &v, double val)
numerical evidence generator

References gum::Tensor< GUM_SCALAR >::evEq(), and gum::DiscreteGraphicalModel::variableFromName().

Referenced by cpt().

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

◆ evGt()

template<GUM_Numeric GUM_SCALAR>
Tensor< GUM_SCALAR > gum::IBayesNet< GUM_SCALAR >::evGt ( std::string_view name,
double value ) const
inherited
Returns
a Tensor for a (numerical) discrete variable representing an evidence with an observed value greater than the parameter

Definition at line 395 of file IBayesNet_tpl.h.

395 {
397 }
static Tensor< GUM_SCALAR > evGt(const DiscreteVariable &v, double val)
numerical evidence generator

References gum::Tensor< GUM_SCALAR >::evGt(), and gum::DiscreteGraphicalModel::variableFromName().

Referenced by cpt().

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

◆ evIn()

template<GUM_Numeric GUM_SCALAR>
Tensor< GUM_SCALAR > gum::IBayesNet< GUM_SCALAR >::evIn ( std::string_view name,
double val1,
double val2 ) const
inherited
Returns
a Tensor for a (numerical) discrete variable representing an evidence with a interval of float as observed value

Definition at line 390 of file IBayesNet_tpl.h.

390 {
392 }
static Tensor< GUM_SCALAR > evIn(const DiscreteVariable &v, double val1, double val2)
numerical evidence generator

References gum::Tensor< GUM_SCALAR >::evIn(), and gum::DiscreteGraphicalModel::variableFromName().

Referenced by cpt().

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

◆ evLt()

template<GUM_Numeric GUM_SCALAR>
Tensor< GUM_SCALAR > gum::IBayesNet< GUM_SCALAR >::evLt ( std::string_view name,
double value ) const
inherited
Returns
a Tensor for a (numerical) discrete variable representing an evidence with an observed value less than the parameter

Definition at line 400 of file IBayesNet_tpl.h.

400 {
402 }
static Tensor< GUM_SCALAR > evLt(const DiscreteVariable &v, double val)
numerical evidence generator

References gum::Tensor< GUM_SCALAR >::evLt(), and gum::DiscreteGraphicalModel::variableFromName().

Referenced by cpt().

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

◆ exists() [1/2]

INLINE bool gum::DAGmodel::exists ( NodeId node) const
finalvirtualinherited

Return true if this node exists in this graphical model.

Implements gum::GraphicalModel.

Definition at line 141 of file DAGmodel_inl.h.

141{ return dag_.exists(node); }

References dag_, and gum::NodeGraphPart::exists().

Referenced by gum::build_node(), gum::build_node_for_ID(), hasSameStructure(), gum::MarkovBlanket::hasSameStructure(), gum::IBayesNet< GUM_SCALAR >::operator==(), and gum::InfluenceDiagram< GUM_SCALAR >::operator==().

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

◆ exists() [2/2]

INLINE bool gum::DAGmodel::exists ( std::string_view name) const
finalvirtualinherited

Returns a named copy of the internal DAG: each node id is assigned the name of the corresponding variable.

O(n) — allocates a new DAG. For a stable reference (listeners, long-lived pointers), use internalDag().

Implements gum::GraphicalModel.

Definition at line 143 of file DAGmodel_inl.h.

143 {
144 return variableNodeMap().exists(name);
145 }
const VariableNodeMap & variableNodeMap() const override
Returns a constant reference to the VariableNodeMap of this model.

References gum::VariableNodeMap::exists(), and gum::DiscreteGraphicalModel::variableNodeMap().

Here is the call graph for this function:

◆ existsArc() [1/2]

INLINE bool gum::DAGmodel::existsArc ( const NodeId tail,
const NodeId head ) const
inherited

return true if the arc tail->head exists in the DAGmodel

Parameters
tailthe nodeId (or the name) of the tail in tail->head
headthe nodeId (or the name) of the head in tail->head
Returns
true if the arc exists

Definition at line 75 of file DAGmodel_inl.h.

75 {
76 return dag_.existsArc(tail, head);
77 }
bool existsArc(const Arc &arc) const
indicates whether a given arc exists

References dag_, and gum::ArcGraphPart::existsArc().

Referenced by existsArc(), gum::BayesNet< GUM_SCALAR >::reverseArc(), gum::BayesNetFragment< GUM_SCALAR >::toDot(), and gum::BayesNetFragment< GUM_SCALAR >::whenArcDeleted().

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

◆ existsArc() [2/2]

INLINE bool gum::DAGmodel::existsArc ( std::string_view nametail,
std::string_view namehead ) const
inherited

return true if the arc tail->head exists in the DAGmodel

Parameters
tailthe nodeId (or the name) of the tail in tail->head
headthe nodeId (or the name) of the head in tail->head
Returns
true if the arc exists

Definition at line 79 of file DAGmodel_inl.h.

79 {
80 return existsArc(idFromName(nametail), idFromName(namehead));
81 }

References existsArc(), and gum::DiscreteGraphicalModel::idFromName().

Here is the call graph for this function:

◆ existsProperty()

INLINE bool gum::GraphicalModel::existsProperty ( std::string_view name) const
inherited

check wether a property exists in this GraphicalModel

Definition at line 170 of file graphicalModel_inl.h.

170 {
171 return _propertiesMap_.exists(name);
172 }
bool exists(const Key &key) const
Checks whether there exists an element with a given key in the hashtable.

References _propertiesMap_, and gum::HashTable< Key, Val >::exists().

Here is the call graph for this function:

◆ family() [1/2]

INLINE NodeSet gum::DAGmodel::family ( const NodeId id) const
finalvirtualinherited

returns the parents of a node and the node

Parameters
idthe node which is the head of an arc with the returned nodes
namethe name of the node the node which is the head of an arc with the returned nodes
Exceptions
NotFoundif the node does not exist in the model

Implements gum::GraphicalModel.

Definition at line 100 of file DAGmodel_inl.h.

100 {
102 return dag_.family(id);
103 }
NodeSet family(NodeId id) const
returns { id } ∪ parents(id)

References _checkNodeExists_(), dag_, and gum::DiGraph::family().

Here is the call graph for this function:

◆ family() [2/2]

INLINE NodeSet gum::DAGmodel::family ( std::string_view name) const
finalvirtualinherited

return true if the arc tail->head exists in the DAGmodel

Parameters
tailthe nodeId (or the name) of the tail in tail->head
headthe nodeId (or the name) of the head in tail->head
Returns
true if the arc exists

Implements gum::GraphicalModel.

Definition at line 105 of file DAGmodel_inl.h.

105 {
106 return dag_.family(idFromName(name));
107 }

References dag_, gum::DiGraph::family(), and gum::DiscreteGraphicalModel::idFromName().

Here is the call graph for this function:

◆ fastPrototype() [1/2]

template<GUM_Numeric GUM_SCALAR>
BayesNet< GUM_SCALAR > gum::BayesNet< GUM_SCALAR >::fastPrototype ( std::string_view dotlike,
Size domainSize )
static

Create a Bayesian network with a dot-like syntax which specifies:

  • the structure "a->b->c;b->d<-e;".
  • the type of the variables with different syntax:

Note that if the dot-like string contains such a specification more than once for a variable, the first specification will be used.

Parameters
dotlikethe string containing the specification
domainSizethe default domain size for variables
Returns
the resulting Bayesian network

Definition at line 91 of file BayesNet_tpl.h.

92 {
93 return fastPrototype(dotlike, "[" + std::to_string(domainSize) + "]");
94 }
static BayesNet< GUM_SCALAR > fastPrototype(std::string_view dotlike, Size domainSize)
Create a Bayesian network with a dot-like syntax which specifies:

References fastPrototype().

Referenced by fastPrototype().

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

◆ fastPrototype() [2/2]

template<GUM_Numeric GUM_SCALAR>
BayesNet< GUM_SCALAR > gum::BayesNet< GUM_SCALAR >::fastPrototype ( std::string_view dotlike,
std::string_view domainSize = "[2]" )
static

Definition at line 97 of file BayesNet_tpl.h.

98 {
100
101 auto resolve = [&](const std::string& node) { return build_node(bn, node, domain); };
102 auto addArc = [&](NodeId tail, NodeId head, const std::string&) { bn.addArc(tail, head); };
103 auto addEdge = [&](NodeId, NodeId, const std::string& token) {
105 "fastPrototype: '" << token << "' is preceded by '-' but a BayesNet "
106 << "does not support edges")
107 };
108
109 for (const auto& chaine: split(remove_newline(dotlike), ";")) {
110 using namespace detail;
112 }
114 bn.setProperty("name", "anonymousBN");
115 return bn;
116 }
void generateCPTs() const
randomly generates CPTs for a given structure
void setProperty(std::string_view name, std::string_view value)
Add or change a property of this GraphicalModel.

References addArc(), gum::build_node(), generateCPTs(), GUM_ERROR, gum::remove_newline(), gum::GraphicalModel::setProperty(), and gum::split().

Here is the call graph for this function:

◆ generateCPT() [1/2]

template<GUM_Numeric GUM_SCALAR>
void gum::BayesNet< GUM_SCALAR >::generateCPT ( NodeId node) const

randomly generate CPT for a given node in a given structure

Definition at line 623 of file BayesNet_tpl.h.

623 {
625
627 }
void generateCPT(NodeId node) const
randomly generate CPT for a given node in a given structure

Referenced by generateCPT(), and generateCPTs().

Here is the caller graph for this function:

◆ generateCPT() [2/2]

template<GUM_Numeric GUM_SCALAR>
void gum::BayesNet< GUM_SCALAR >::generateCPT ( std::string_view name) const

Definition at line 768 of file BayesNet_tpl.h.

768 {
770 }

References generateCPT(), and idFromName().

Here is the call graph for this function:

◆ generateCPTs()

template<GUM_Numeric GUM_SCALAR>
void gum::BayesNet< GUM_SCALAR >::generateCPTs ( ) const

randomly generates CPTs for a given structure

Definition at line 617 of file BayesNet_tpl.h.

617 {
618 for (const auto node: nodes())
620 }

References generateCPT(), and gum::DAGmodel::nodes().

Referenced by fastPrototype().

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

◆ hasSameStructure()

bool gum::DAGmodel::hasSameStructure ( const DAGmodel & other) const
inherited
Returns
true if all the named node are the same and all the named arcs are the same

Definition at line 87 of file DAGmodel.cpp.

87 {
88 if (this == &other) return true;
89
90 if (size() != other.size()) return false;
91
92 if (sizeArcs() != other.sizeArcs()) return false;
93
94 for (const auto& nid: nodes()) {
95 if (!other.exists(variable(nid).name())) return false;
96 }
97
98 for (const auto& arc: arcs()) {
99 if (!other.arcs().exists(Arc(other.idFromName(variable(arc.tail()).name()),
100 other.idFromName(variable(arc.head()).name()))))
101 return false;
102 }
103
104 return true;
105 }
const ArcSet & arcs() const
return true if the arc tail->head exists in the DAGmodel
Size size() const final
Returns the number of variables in this Directed Graphical Model.
Size sizeArcs() const
Returns the number of arcs in this Directed Graphical Model.

References DAGmodel(), arcs(), exists(), gum::Set< Key >::exists(), gum::DiscreteGraphicalModel::idFromName(), gum::Variable::name(), nodes(), size(), sizeArcs(), and gum::DiscreteGraphicalModel::variable().

Here is the call graph for this function:

◆ idFromName()

template<GUM_Numeric GUM_SCALAR>
INLINE NodeId gum::DiscreteGraphicalModel::idFromName ( std::string_view name) const
overridevirtual

Returns the NodeId of a variable given its name.

Exceptions
NotFoundif no such name exists in the model.

Implements gum::GraphicalModel.

Definition at line 104 of file discreteGraphicalModel_inl.h.

61 {
62 return varMap_.idFromName(name);
63 }

Referenced by addArc(), addWeightedArc(), gum::build_node(), changeTensor(), changeVariableLabel(), changeVariableName(), cpt(), erase(), eraseArc(), generateCPT(), reverseArc(), and variable().

Here is the caller graph for this function:

◆ ids()

INLINE std::vector< NodeId > gum::GraphicalModel::ids ( const std::vector< std::string > & names) const
inherited

transform a vector of names into a vector of nodeId

Returns
the vector of names

Definition at line 139 of file graphicalModel_inl.h.

139 {
140 std::vector< NodeId > res;
141 const VariableNodeMap& v = variableNodeMap();
142 std::transform(names.cbegin(),
143 names.cend(),
144 std::back_inserter(res),
145 [&v](const std::string& n) { return v.idFromName(n); });
146 return res;
147 }
virtual const VariableNodeMap & variableNodeMap() const =0
Returns a constant reference to the VariableNodeMap of this Graphical Model.

References names(), and variableNodeMap().

Referenced by gum::DAGmodel::children(), exists(), names(), names(), and gum::DAGmodel::parents().

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

◆ internalDag()

INLINE const DAG & gum::DAGmodel::internalDag ( ) const
inherited

Returns a const reference to the internal (unnamed) DAG. O(1), no copy. Use for stable references or pointers (e.g. graph listeners). For named node access, use dag() instead.

Definition at line 58 of file DAGmodel_inl.h.

58{ return dag_; }

References dag_.

Referenced by gum::BayesNetFragment< GUM_SCALAR >::BayesNetFragment(), gum::MarkovBlanket::MarkovBlanket(), gum::BayesNetFragment< GUM_SCALAR >::installCPT(), gum::BayesNetFragment< GUM_SCALAR >::isInstalledNode(), gum::BayesBall::relevantTensors(), gum::dSeparationAlgorithm::relevantTensors(), gum::BayesNetFragment< GUM_SCALAR >::toBN(), gum::BayesNetFragment< GUM_SCALAR >::toDot(), and gum::BayesNetFragment< GUM_SCALAR >::whenArcDeleted().

Here is the caller graph for this function:

◆ isIndependent() [1/4]

INLINE bool gum::DAGmodel::isIndependent ( const NodeSet & X,
const NodeSet & Y,
const NodeSet & Z ) const
finalvirtualinherited

check if nodes X and nodes Y are independent given nodes Z

Implements gum::GraphicalModel.

Definition at line 192 of file DAGmodel_inl.h.

192 {
193 return dag_.dSeparation(X, Y, Z);
194 }
bool dSeparation(NodeId X, NodeId Y, const NodeSet &Z) const
check if node X and node Y are independent given nodes Z (in the sense of d-separation)
Definition DAG.cpp:80

◆ isIndependent() [2/4]

INLINE bool gum::DAGmodel::isIndependent ( const std::vector< std::string > & Xnames,
const std::vector< std::string > & Ynames,
const std::vector< std::string > & Znames ) const
inherited

build a UndiGraph by moralizing the Ancestral Graph of a set of Nodes

Parameters
nodesthe set of nodeId
nodenamesthe vector of names of nodes
Returns
the moralized ancestral graph

Definition at line 220 of file DAGmodel_inl.h.

222 {
223 return isIndependent(nodeset(Xnames), nodeset(Ynames), nodeset(Znames));
224 }
bool isIndependent(NodeId X, NodeId Y, const NodeSet &Z) const final
check if node X and node Y are independent given nodes Z

References isIndependent(), and gum::GraphicalModel::nodeset().

Here is the call graph for this function:

◆ isIndependent() [3/4]

INLINE bool gum::DAGmodel::isIndependent ( NodeId X,
NodeId Y,
const NodeSet & Z ) const
finalvirtualinherited

check if node X and node Y are independent given nodes Z

Implements gum::GraphicalModel.

Definition at line 188 of file DAGmodel_inl.h.

188 {
189 return dag_.dSeparation(X, Y, Z);
190 }

References dag_, and gum::DAG::dSeparation().

Referenced by isIndependent().

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

◆ isIndependent() [4/4]

INLINE bool gum::DAGmodel::isIndependent ( std::string_view Xname,
std::string_view Yname,
const std::vector< std::string > & Znames ) const
inherited

build a UndiGraph by moralizing the Ancestral Graph of a set of Nodes

Parameters
nodesthe set of nodeId
nodenamesthe vector of names of nodes
Returns
the moralized ancestral graph

Definition at line 214 of file DAGmodel_inl.h.

216 {
217 return isIndependent(idFromName(Xname), idFromName(Yname), nodeset(Znames));
218 }

◆ jointProbability()

template<GUM_Numeric GUM_SCALAR>
GUM_SCALAR gum::IBayesNet< GUM_SCALAR >::jointProbability ( const Instantiation & i) const
inherited

Compute a parameter of the joint probability for the BN (given an instantiation of the vars).

Warning
a variable not present in the instantiation is assumed to be instantiated to 0.

Definition at line 236 of file IBayesNet_tpl.h.

236 {
237 auto value = (GUM_SCALAR)1.0;
238
240
241 for (auto node: nodes()) {
242 if ((tmp = cpt(node)[i]) == (GUM_SCALAR)0) { return (GUM_SCALAR)0; }
243
244 value *= tmp;
245 }
246
247 return value;
248 }

Referenced by cpt().

Here is the caller graph for this function:

◆ log10DomainSize()

INLINE double gum::GraphicalModel::log10DomainSize ( ) const
inherited

Definition at line 93 of file graphicalModel_inl.h.

93 {
94 double dSize = 0.0;
95
96 for (const auto node: nodes()) {
97 dSize += std::log10(variable(node).domainSize());
98 }
99
100 return dSize;
101 }

References nodes().

Referenced by gum::IMarkovRandomField< GUM_SCALAR >::toString(), gum::InfluenceDiagram< GUM_SCALAR >::toString(), and variableFromName().

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

◆ log2JointProbability()

template<GUM_Numeric GUM_SCALAR>
GUM_SCALAR gum::IBayesNet< GUM_SCALAR >::log2JointProbability ( const Instantiation & i) const
inherited

Compute a parameter of the log joint probability for the BN (given an instantiation of the vars).

Compute a parameter of the joint probability for the BN (given an instantiation of the vars).

Warning
a variable not present in the instantiation is assumed to be instantiated to 0.

Definition at line 254 of file IBayesNet_tpl.h.

254 {
255 auto value = (GUM_SCALAR)0.0;
256
258
259 for (auto node: nodes()) {
260 if ((tmp = cpt(node)[i]) == (GUM_SCALAR)0) {
262 }
263
264 value += std::log2(cpt(node)[i]);
265 }
266
267 return value;
268 }

Referenced by cpt().

Here is the caller graph for this function:

◆ maxNonOneParam()

template<GUM_Numeric GUM_SCALAR>
GUM_SCALAR gum::IBayesNet< GUM_SCALAR >::maxNonOneParam ( ) const
inherited
Returns
the biggest value (not equal to 1) in the CPTs of *this
Warning
can return one if no other value in the CPTs than one....

Definition at line 172 of file IBayesNet_tpl.h.

172 {
173 GUM_SCALAR res = 0.0;
174 for (auto node: nodes()) {
175 auto v = cpt(node).maxNonOne();
176 if (v > res) { res = v; }
177 }
178 return res;
179 }

References cpt(), and gum::DAGmodel::nodes().

Referenced by cpt().

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

◆ maxParam()

template<GUM_Numeric GUM_SCALAR>
GUM_SCALAR gum::IBayesNet< GUM_SCALAR >::maxParam ( ) const
inherited
Returns
the biggest value in the CPTs of *this

Definition at line 152 of file IBayesNet_tpl.h.

152 {
153 GUM_SCALAR res = 1.0;
154 for (auto node: nodes()) {
155 auto v = cpt(node).max();
156 if (v > res) { res = v; }
157 }
158 return res;
159 }

References cpt(), and gum::DAGmodel::nodes().

Referenced by cpt().

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

◆ maxVarDomainSize()

template<GUM_Numeric GUM_SCALAR>
Size gum::IBayesNet< GUM_SCALAR >::maxVarDomainSize ( ) const
inherited
Returns
the biggest domainSize among the variables of *this

Definition at line 132 of file IBayesNet_tpl.h.

132 {
133 Size res = 0;
134 for (auto node: nodes()) {
135 auto v = variable(node).domainSize();
136 if (v > res) { res = v; }
137 }
138 return res;
139 }

References gum::DAGmodel::nodes(), and gum::DiscreteGraphicalModel::variable().

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

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

◆ memoryFootprint()

template<GUM_Numeric GUM_SCALAR>
Size gum::IBayesNet< GUM_SCALAR >::memoryFootprint ( ) const
inherited

compute the (approximated) footprint in memory of the model (the footprints of CPTs)

Returns
the size in bytes

Definition at line 182 of file IBayesNet_tpl.h.

182 {
183 Size usedMem = 0;
184
185 for (auto node: nodes())
187 return usedMem;
188 }
Size memoryFootprint() const
compute the (approximated) footprint in memory of the model (the footprints of CPTs)

References cpt(), and gum::DAGmodel::nodes().

Referenced by cpt().

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

◆ minimalCondSet() [1/4]

INLINE NodeSet gum::DAGmodel::minimalCondSet ( const NodeSet & targets,
const NodeSet & soids ) const
inherited

Definition at line 200 of file DAGmodel_inl.h.

200 {
201 return dag_.minimalCondSet(targets, soids);
202 }
NodeSet minimalCondSet(NodeId target, const NodeSet &soids) const
Definition DAG.cpp:88

References dag_, and gum::DAG::minimalCondSet().

Here is the call graph for this function:

◆ minimalCondSet() [2/4]

INLINE NodeSet gum::DAGmodel::minimalCondSet ( const std::vector< std::string > & targets,
const std::vector< std::string > & soids ) const
inherited

Definition at line 209 of file DAGmodel_inl.h.

210 {
211 return dag_.minimalCondSet(nodeset(targets), nodeset(soids));
212 }

◆ minimalCondSet() [3/4]

INLINE NodeSet gum::DAGmodel::minimalCondSet ( NodeId target,
const NodeSet & soids ) const
inherited

Definition at line 196 of file DAGmodel_inl.h.

196 {
197 return dag_.minimalCondSet(target, soids);
198 }

References dag_, and gum::DAG::minimalCondSet().

Referenced by gum::ASTposteriorProba< GUM_SCALAR >::_compute_knw_from_bn().

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

◆ minimalCondSet() [4/4]

INLINE NodeSet gum::DAGmodel::minimalCondSet ( std::string_view target,
const std::vector< std::string > & soids ) const
inherited

Definition at line 204 of file DAGmodel_inl.h.

205 {
206 return dag_.minimalCondSet(idFromName(target), nodeset(soids));
207 }

◆ minNonZeroParam()

template<GUM_Numeric GUM_SCALAR>
GUM_SCALAR gum::IBayesNet< GUM_SCALAR >::minNonZeroParam ( ) const
inherited
Returns
the smallest value (not equal to 0) in the CPTs of *this
Warning
can return 0 if no other value in the CPTs than 0...

Definition at line 162 of file IBayesNet_tpl.h.

162 {
163 GUM_SCALAR res = 1.0;
164 for (auto node: nodes()) {
165 auto v = cpt(node).minNonZero();
166 if (v < res) { res = v; }
167 }
168 return res;
169 }

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

Here is the caller graph for this function:

◆ minParam()

template<GUM_Numeric GUM_SCALAR>
GUM_SCALAR gum::IBayesNet< GUM_SCALAR >::minParam ( ) const
inherited
Returns
the smallest value in the CPTs of *this

Definition at line 142 of file IBayesNet_tpl.h.

142 {
143 GUM_SCALAR res = 1.0;
144 for (auto node: nodes()) {
145 auto v = cpt(node).min();
146 if (v < res) { res = v; }
147 }
148 return res;
149 }

References cpt(), and gum::DAGmodel::nodes().

Referenced by cpt().

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

◆ moralGraph()

UndiGraph gum::DAGmodel::moralGraph ( ) const
inherited

The node's id are coherent with the variables and nodes of the topology.

Definition at line 81 of file DAGmodel.cpp.

81 {
82 auto g = dag_.moralGraph();
83 _nameNodes_(g);
84 return g;
85 }
UndiGraph moralGraph() const
build a UndiGraph by moralizing the dag
Definition DAG.cpp:74

References gum::GraphicalModel::_nameNodes_(), dag_, and gum::DAG::moralGraph().

Referenced by gum::prm::SVE< GUM_SCALAR >::_eliminateNodes_(), gum::prm::SVED< GUM_SCALAR >::_eliminateNodes_(), gum::prm::SVE< GUM_SCALAR >::_eliminateNodesWithEvidence_(), gum::prm::SVED< GUM_SCALAR >::_eliminateNodesWithEvidence_(), gum::prm::SVE< GUM_SCALAR >::_initLiftedNodes_(), and gum::prm::SVED< GUM_SCALAR >::_initLiftedNodes_().

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

◆ moralizedAncestralGraph() [1/2]

INLINE UndiGraph gum::DAGmodel::moralizedAncestralGraph ( const NodeSet & nodes) const
inherited

build a UndiGraph by moralizing the Ancestral Graph of a set of Nodes

Parameters
nodesthe set of nodeId
nodenamesthe vector of names of nodes
Returns
the moralized ancestral graph

Definition at line 182 of file DAGmodel_inl.h.

182 {
184 _nameNodes_(g);
185 return g;
186 }
UndiGraph moralizedAncestralGraph(const NodeSet &nodes) const
build a UndiGraph by moralizing the Ancestral Graph of a set of Nodes
Definition DAG.cpp:76

Referenced by moralizedAncestralGraph().

Here is the caller graph for this function:

◆ moralizedAncestralGraph() [2/2]

INLINE UndiGraph gum::DAGmodel::moralizedAncestralGraph ( const std::vector< std::string > & nodenames) const
inherited

build a UndiGraph by moralizing the Ancestral Graph of a set of Nodes

Parameters
nodesthe set of nodeId
nodenamesthe vector of names of nodes
Returns
the moralized ancestral graph

Definition at line 178 of file DAGmodel_inl.h.

178 {
179 return moralizedAncestralGraph(nodeset(nodenames));
180 }
UndiGraph moralizedAncestralGraph(const NodeSet &nodes) const
build a UndiGraph by moralizing the Ancestral Graph of a set of Nodes

References moralizedAncestralGraph(), and gum::GraphicalModel::nodeset().

Here is the call graph for this function:

◆ names() [1/2]

INLINE std::vector< std::string > gum::GraphicalModel::names ( const NodeSet & ids) const
inherited

transform a NodeSet in a vector of names

Returns
the vector of names

Definition at line 129 of file graphicalModel_inl.h.

129 {
130 const VariableNodeMap& v = variableNodeMap();
131 std::vector< std::string > res;
132 for (auto n: ids) {
133 res.push_back(v.name(n));
134 }
135 return res;
136 }

References ids(), gum::VariableNodeMap::name(), and variableNodeMap().

Here is the call graph for this function:

◆ names() [2/2]

INLINE std::vector< std::string > gum::GraphicalModel::names ( const std::vector< NodeId > & ids) const
inherited

transform a vector of NodeId in a vector of names

Returns
the vector of names

Definition at line 117 of file graphicalModel_inl.h.

117 {
118 std::vector< std::string > res;
119 const VariableNodeMap& v = variableNodeMap();
120
121 std::ranges::transform(ids, std::back_inserter(res), [&v](const NodeId n) {
122 return v[n].name();
123 });
124
125 return res;
126 }
Size NodeId
Type for node ids.

References ids().

Referenced by gum::DAGmodel::children(), exists(), ids(), nodeset(), and gum::DAGmodel::parents().

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

◆ nodeId()

template<GUM_Numeric GUM_SCALAR>
INLINE NodeId gum::DiscreteGraphicalModel::nodeId ( const DiscreteVariable & var) const
overridevirtual

Returns the NodeId of a variable.

Exceptions
NotFoundif no variable matches var.

Implements gum::GraphicalModel.

Definition at line 98 of file discreteGraphicalModel_inl.h.

56 {
57 return varMap_.get(var);
58 }

◆ nodes()

INLINE const NodeGraphPart & gum::DAGmodel::nodes ( ) const
finalvirtualinherited

Returns a named copy of the internal DAG: each node id is assigned the name of the corresponding variable.

O(n) — allocates a new DAG. For a stable reference (listeners, long-lived pointers), use internalDag().

Implements gum::GraphicalModel.

Definition at line 147 of file DAGmodel_inl.h.

147 {
148 return static_cast< const NodeGraphPart& >(dag_);
149 }

References dag_.

Referenced by gum::BayesNetFragment< GUM_SCALAR >::BayesNetFragment(), gum::Estimator< GUM_SCALAR >::Estimator(), gum::BayesNetFragment< GUM_SCALAR >::~BayesNetFragment(), gum::EssentialGraph::_buildEssentialGraph_(), gum::credal::CNMonteCarloSampling< GUM_SCALAR, BNInferenceEngine >::_verticesSampling_(), gum::BayesNet< GUM_SCALAR >::beginTopologyTransformation(), gum::InfluenceDiagram< GUM_SCALAR >::beginTopologyTransformation(), gum::IBayesNet< GUM_SCALAR >::check(), gum::BayesNetFragment< GUM_SCALAR >::checkConsistency(), gum::BayesNet< GUM_SCALAR >::clear(), gum::InfluenceDiagram< GUM_SCALAR >::copyStructureAndTables_(), gum::IBayesNet< GUM_SCALAR >::dim(), gum::BayesNet< GUM_SCALAR >::endTopologyTransformation(), gum::InfluenceDiagram< GUM_SCALAR >::endTopologyTransformation(), gum::InfluenceDiagram< GUM_SCALAR >::fastPrototype(), gum::BayesNet< GUM_SCALAR >::generateCPTs(), gum::getMaxModality(), hasSameStructure(), gum::IBayesNet< GUM_SCALAR >::maxNonOneParam(), gum::IBayesNet< GUM_SCALAR >::maxParam(), gum::IBayesNet< GUM_SCALAR >::maxVarDomainSize(), gum::IBayesNet< GUM_SCALAR >::memoryFootprint(), gum::IBayesNet< GUM_SCALAR >::minParam(), gum::prm::ClassBayesNet< GUM_SCALAR >::modalities(), gum::prm::InstanceBayesNet< GUM_SCALAR >::modalities(), gum::IBayesNet< GUM_SCALAR >::operator==(), gum::InfluenceDiagram< GUM_SCALAR >::operator==(), gum::Estimator< GUM_SCALAR >::setFromBN(), gum::BayesNetFragment< GUM_SCALAR >::toBN(), gum::prm::ClassBayesNet< GUM_SCALAR >::toDot(), gum::prm::InstanceBayesNet< GUM_SCALAR >::toDot(), and gum::ImportanceSampling< GUM_SCALAR >::unsharpenBN_().

◆ nodeset()

NodeSet gum::GraphicalModel::nodeset ( const std::vector< std::string > & names) const
inherited

transform a vector of names into a NodeSet

Returns
NodeSet

Definition at line 102 of file graphicalModel.cpp.

102 {
103 NodeSet res;
104 for (const auto& name: names) {
105 res.insert(idFromName(name));
106 }
107 return res;
108 }
virtual NodeId idFromName(std::string_view name) const =0
Getter by name.

References idFromName(), gum::Set< Key >::insert(), and names().

Referenced by gum::DAGmodel::children(), exists(), gum::DAGmodel::isIndependent(), gum::UGmodel::isIndependent(), gum::UGmodel::isIndependent(), gum::DAGmodel::moralizedAncestralGraph(), and gum::DAGmodel::parents().

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

◆ operator=() [1/2]

template<GUM_Numeric GUM_SCALAR>
BayesNet< GUM_SCALAR > & gum::BayesNet< GUM_SCALAR >::operator= ( BayesNet< GUM_SCALAR > && source)

Move operator.

Parameters
sourceThe moved BayesNet.
Returns
The moved-to BayesNet.

Definition at line 155 of file BayesNet_tpl.h.

155 {
156 if (this != &source) {
161 }
162 return *this;
163 }
void _clearTensors_()
clear all tensors
IBayesNet< GUM_SCALAR > & operator=(const IBayesNet< GUM_SCALAR > &source)
Copy operator.

References BayesNet(), _clearTensors_(), _probaMap_, and gum::IBayesNet< GUM_SCALAR >::operator=().

Here is the call graph for this function:

◆ operator=() [2/2]

template<GUM_Numeric GUM_SCALAR>
BayesNet< GUM_SCALAR > & gum::BayesNet< GUM_SCALAR >::operator= ( const BayesNet< GUM_SCALAR > & source)

Copy operator.

Parameters
sourceThe copied BayesNet.
Returns
The copy of source.

Definition at line 143 of file BayesNet_tpl.h.

143 {
144 if (this != &source) {
149 }
150
151 return *this;
152 }

References BayesNet(), _clearTensors_(), _copyTensors_(), and gum::IBayesNet< GUM_SCALAR >::operator=().

Here is the call graph for this function:

◆ operator==()

template<GUM_Numeric GUM_SCALAR>
bool gum::IBayesNet< GUM_SCALAR >::operator== ( const IBayesNet< GUM_SCALAR > & from) const
inherited

This operator compares 2 BNs !

Warning
To identify nodes between BNs, it is assumed that they share the same name.
Returns
true if the src and this are equal.

Definition at line 271 of file IBayesNet_tpl.h.

271 {
272 if (size() != from.size()) { return false; }
273
274 if (sizeArcs() != from.sizeArcs()) { return false; }
275
276 for (auto node: nodes()) {
277 const auto& v1 = variable(node);
278 if (!from.exists(v1.name())) { return false; }
279 const auto& v2 = from.variableFromName(v1.name());
280 if (v1 != v2) { return false; }
281 }
282
283 for (auto node: nodes()) {
285
286 if (cpt(node).nbrDim() != from.cpt(fromnode).nbrDim()) { return false; }
287
288 if (cpt(node).domainSize() != from.cpt(fromnode).domainSize()) { return false; }
289
290 for (Idx i = 0; i < cpt(node).nbrDim(); ++i) {
291 if (!from.cpt(fromnode).contains(from.variableFromName(cpt(node).variable(i).name()))) {
292 return false;
293 }
294 }
295
298
300 for (i.setFirst(); !i.end(); i.inc()) {
301 for (Idx indice = 0; indice < cpt(node).nbrDim(); ++indice) {
302 const DiscreteVariable* p = &(i.variable(indice));
303 j.chgVal(j.pos(from.variableFromName(p->name())), i.val(*p));
304 }
305
306 if (cmp(cpt(node).get(i), from.cpt(fromnode).get(j))) { return false; }
307 }
308 }
309
310 return true;
311 }
bool exists(NodeId node) const final
Return true if this node exists in this graphical model.

References IBayesNet(), gum::Instantiation::chgVal(), cpt(), gum::Instantiation::end(), gum::DAGmodel::exists(), gum::DiscreteGraphicalModel::idFromName(), gum::Instantiation::inc(), gum::Variable::name(), gum::Instantiation::nbrDim(), gum::DAGmodel::nodes(), gum::Instantiation::pos(), gum::Instantiation::setFirst(), gum::DAGmodel::size(), gum::DAGmodel::sizeArcs(), gum::Instantiation::val(), gum::DiscreteGraphicalModel::variable(), gum::Instantiation::variable(), and gum::DiscreteGraphicalModel::variableFromName().

Referenced by cpt().

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

◆ parents() [1/4]

INLINE const NodeSet & gum::DAGmodel::parents ( const NodeId id) const
inherited

returns the set of nodes with arc ingoing to a given node

Note that the set of nodes returned may be empty if no arc within the ArcGraphPart is ingoing into the given node.

Parameters
idthe node which is the head of an arc with the returned nodes
namethe name of the node the node which is the head of an arc with the returned nodes
Exceptions
NotFoundif the node does not exist in the model

Definition at line 89 of file DAGmodel_inl.h.

89 {
90 const NodeSet& res = dag_.parents(id);
91 if (res.empty()) _checkNodeExists_(id);
92 return res;
93 }
const NodeSet & parents(NodeId id) const
returns the set of nodes with arc ingoing to a given node

References _checkNodeExists_(), dag_, gum::Set< Key >::empty(), and gum::ArcGraphPart::parents().

Referenced by gum::IBayesNet< GUM_SCALAR >::check(), gum::BayesNetFragment< GUM_SCALAR >::checkConsistency(), gum::InfluenceDiagram< GUM_SCALAR >::copyStructureAndTables_(), gum::IBayesNet< GUM_SCALAR >::dim(), gum::ASTposteriorProba< GUM_SCALAR >::eval(), gum::BayesNetFragment< GUM_SCALAR >::installCPT(), gum::BayesNetFragment< GUM_SCALAR >::installCPT_(), gum::prm::ClassBayesNet< GUM_SCALAR >::toDot(), and gum::prm::InstanceBayesNet< GUM_SCALAR >::toDot().

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

◆ parents() [2/4]

INLINE NodeSet gum::DAGmodel::parents ( const NodeSet & ids) const
inherited

returns the parents of a set of nodes

Exceptions
NotFoundif one of the nodes does not exist in the model

Definition at line 130 of file DAGmodel_inl.h.

130 {
131 for (const auto id: ids)
133 return dag_.parents(ids);
134 }

References gum::GraphicalModel::ids().

Here is the call graph for this function:

◆ parents() [3/4]

INLINE NodeSet gum::DAGmodel::parents ( const std::vector< std::string > & names) const
inherited

return true if the arc tail->head exists in the DAGmodel

Parameters
tailthe nodeId (or the name) of the tail in tail->head
headthe nodeId (or the name) of the head in tail->head
Returns
true if the arc exists

Definition at line 137 of file DAGmodel_inl.h.

137 {
138 return dag_.parents(nodeset(names));
139 }

References dag_, gum::GraphicalModel::names(), gum::GraphicalModel::nodeset(), and gum::ArcGraphPart::parents().

Here is the call graph for this function:

◆ parents() [4/4]

INLINE const NodeSet & gum::DAGmodel::parents ( std::string_view name) const
inherited

return true if the arc tail->head exists in the DAGmodel

Parameters
tailthe nodeId (or the name) of the tail in tail->head
headthe nodeId (or the name) of the head in tail->head
Returns
true if the arc exists

Definition at line 96 of file DAGmodel_inl.h.

96 {
97 return dag_.parents(idFromName(name));
98 }

References dag_, gum::DiscreteGraphicalModel::idFromName(), and gum::ArcGraphPart::parents().

Here is the call graph for this function:

◆ properties()

INLINE std::vector< std::string > gum::GraphicalModel::properties ( ) const
inherited

List of all the names of property in the Graphical model.

Definition at line 79 of file graphicalModel_inl.h.

79 {
80 std::vector< std::string > prop;
81 for (const auto& [p, v]: _propertiesMap_)
82 prop.push_back(p);
83 return prop;
84 }

References _propertiesMap_.

◆ property()

INLINE const std::string & gum::GraphicalModel::property ( std::string_view name) const
inherited

Return the value of the property name of this GraphicalModel.

Exceptions
NotFoundRaised if no name property is found.

Definition at line 60 of file graphicalModel_inl.h.

60 {
61 auto p = _properties_().tryGet(name);
62 if (!p) { GUM_ERROR(NotFound, "The following property does not exists: " << name) }
63 return *p;
64 }
const HashTable< std::string, std::string > & _properties_() const
Return the properties of this Directed Graphical Model.
optional_ref< Val > tryGet(const Key &key)
Returns a pointer to the value associated with a given key, or nullptr if the key does not exist.

References _properties_(), GUM_ERROR, and gum::HashTable< Key, Val >::tryGet().

Here is the call graph for this function:

◆ propertyWithDefault()

INLINE const std::string & gum::GraphicalModel::propertyWithDefault ( std::string_view name,
const std::string & byDefault ) const
inherited

Return the value of the property name of this GraphicalModel.

return byDefault if the property name is not found

Definition at line 72 of file graphicalModel_inl.h.

73 {
74 auto p = _propertiesMap_.tryGet(name);
75 return p ? *p : byDefault;
76 }

References _propertiesMap_, and gum::HashTable< Key, Val >::tryGet().

Referenced by gum::IMarkovRandomField< GUM_SCALAR >::toDot(), gum::InfluenceDiagram< GUM_SCALAR >::toDot(), and gum::IMarkovRandomField< GUM_SCALAR >::toDotAsFactorGraph().

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

◆ reverseArc() [1/3]

template<GUM_Numeric GUM_SCALAR>
void gum::BayesNet< GUM_SCALAR >::reverseArc ( const Arc & arc)

Reverses an arc while preserving the same joint distribution.

This method uses Shachter's 1986 algorithm for reversing an arc in the Bayes net while preserving the same joint distribution. By performing this reversal, we also add new arcs (required to not alter the joint distribution)

Exceptions
InvalidArcexception if the arc does not exist or if its reversal would induce a directed cycle.

Definition at line 321 of file BayesNet_tpl.h.

321 {
322 // check that the arc exists
323 if (!this->varMap_.exists(arc.tail()) || !this->varMap_.exists(arc.head())
324 || !dag().existsArc(arc)) {
325 GUM_ERROR(InvalidArc, "a non-existing arc cannot be reversed")
326 }
327
328 NodeId tail = arc.tail();
329 NodeId head = arc.head();
330
331 // check that the reversal does not induce a cycle
332 try {
333 DAG d = dag();
334 d.eraseArc(arc);
335 d.addArc(head, tail);
336 } catch (Exception const&) {
337 GUM_ERROR(InvalidArc, "this arc reversal would induce a directed cycle")
338 }
339
340 // with the same notations as Shachter (1986), "evaluating influence
341 // diagrams", p.878, we shall first compute the product of probabilities:
342 // pi_j^old (x_j | x_c^old(j) ) * pi_i^old (x_i | x_c^old(i) )
344
345 // modify the topology of the graph: add to tail all the parents of head
346 // and add to head all the parents of tail
349 for (const auto node: this->parents(tail))
350 new_parents.insert(node);
351 for (const auto node: this->parents(head))
352 new_parents.insert(node);
353 // remove arc (head, tail)
354 eraseArc(arc);
355
356 // add the necessary arcs to the tail
357 for (const auto p: new_parents) {
358 if ((p != tail) && !dag().existsArc(p, tail)) { addArc(p, tail); }
359 }
360
361 addArc(head, tail);
362 // add the necessary arcs to the head
364
365 for (const auto p: new_parents) {
366 if ((p != head) && !dag().existsArc(p, head)) { addArc(p, head); }
367 }
368
370
371 // update the conditional distributions of head and tail
373 del_vars << &(variable(tail));
375
376 auto& cpt_head = const_cast< Tensor< GUM_SCALAR >& >(cpt(head));
378
380 auto& cpt_tail = const_cast< Tensor< GUM_SCALAR >& >(cpt(tail));
382 }

References gum::DAG::addArc(), cpt(), gum::DAGmodel::dag(), gum::ArcGraphPart::eraseArc(), gum::DAGmodel::existsArc(), GUM_ERROR, gum::Arc::head(), gum::Arc::tail(), and gum::DiscreteGraphicalModel::varMap_.

Here is the call graph for this function:

◆ reverseArc() [2/3]

template<GUM_Numeric GUM_SCALAR>
void gum::BayesNet< GUM_SCALAR >::reverseArc ( NodeId tail,
NodeId head )

Reverses an arc while preserving the same joint distribution.

This method uses Shachter's 1986 algorithm for reversing an arc in the Bayes net while preserving the same joint distribution. By performing this reversal, we also add new arcs (required to not alter the joint distribution)

Exceptions
InvalidArcexception if the arc does not exist or if its reversal would induce a directed cycle.

Definition at line 385 of file BayesNet_tpl.h.

385 {
387 }
void reverseArc(NodeId tail, NodeId head)
Reverses an arc while preserving the same joint distribution.

References gum::Arc::Arc(), and reverseArc().

Referenced by reverseArc(), and reverseArc().

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

◆ reverseArc() [3/3]

template<GUM_Numeric GUM_SCALAR>
void gum::BayesNet< GUM_SCALAR >::reverseArc ( std::string_view tail,
std::string_view head )

Reverses an arc while preserving the same joint distribution.

This method uses Shachter's 1986 algorithm for reversing an arc in the Bayes net while preserving the same joint distribution. By performing this reversal, we also add new arcs (required to not alter the joint distribution)

Exceptions
InvalidArcexception if the arc does not exist or if its reversal would induce a directed cycle.

Definition at line 756 of file BayesNet_tpl.h.

756 {
758 }

References idFromName(), and reverseArc().

Here is the call graph for this function:

◆ setProperty()

INLINE void gum::GraphicalModel::setProperty ( std::string_view name,
std::string_view value )
inherited

Add or change a property of this GraphicalModel.

Definition at line 87 of file graphicalModel_inl.h.

87 {
88 if (auto p = _propertiesMap_.tryGet(name)) *p = value;
89 else _propertiesMap_.insert(std::string(name), std::string(value));
90 }
value_type & insert(const Key &key, const Val &val)
Adds a new element (actually a copy of this element) into the hash table.

References _propertiesMap_, gum::HashTable< Key, Val >::insert(), and gum::HashTable< Key, Val >::tryGet().

Referenced by gum::IBayesNet< GUM_SCALAR >::IBayesNet(), gum::IMarkovRandomField< GUM_SCALAR >::IMarkovRandomField(), gum::BayesNet< GUM_SCALAR >::fastPrototype(), and gum::InfluenceDiagram< GUM_SCALAR >::fastPrototype().

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

◆ size()

INLINE Size gum::DAGmodel::size ( ) const
finalvirtualinherited

Returns the number of variables in this Directed Graphical Model.

Implements gum::GraphicalModel.

Definition at line 68 of file DAGmodel_inl.h.

68{ return dag_.size(); }
Size size() const
alias for sizeNodes

References dag_, and gum::NodeGraphPart::size().

Referenced by gum::InfluenceDiagram< GUM_SCALAR >::copyStructureAndTables_(), gum::InfluenceDiagram< GUM_SCALAR >::decisionNodeSize(), hasSameStructure(), gum::MarkovBlanket::hasSameStructure(), gum::IBayesNet< GUM_SCALAR >::operator==(), gum::InfluenceDiagram< GUM_SCALAR >::operator==(), gum::prm::ClassBayesNet< GUM_SCALAR >::toDot(), and gum::prm::InstanceBayesNet< GUM_SCALAR >::toDot().

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

◆ sizeArcs()

INLINE Size gum::DAGmodel::sizeArcs ( ) const
inherited

Returns the number of arcs in this Directed Graphical Model.

Definition at line 71 of file DAGmodel_inl.h.

71{ return dag_.sizeArcs(); }
Size sizeArcs() const
indicates the number of arcs stored within the ArcGraphPart

References dag_, and gum::ArcGraphPart::sizeArcs().

Referenced by hasSameStructure(), gum::MarkovBlanket::hasSameStructure(), gum::IBayesNet< GUM_SCALAR >::operator==(), gum::InfluenceDiagram< GUM_SCALAR >::operator==(), and gum::InfluenceDiagram< GUM_SCALAR >::toString().

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

◆ spaceCplxToString()

std::string gum::GraphicalModel::spaceCplxToString ( double dSize,
int dim,
Size usedMem )
staticinherited

send to the stream the space complexity with 3 parametrs

Parameters
sthe stream
dSizethe log10domainSize
dimthe dimension
usedMemthe memory needed for the params

Definition at line 110 of file graphicalModel.cpp.

110 {
111 std::string result;
112 if (dSize > 6) result = std::format("domainSize: 10^{:.6g}", dSize);
113 else result = std::format("domainSize: {}", (long long)std::round(std::pow(10.0, dSize)));
114
115 result += std::format(", dim: {}, mem: ", dim);
116
117 if (const Size go = usedMem / (1024 * 1024 * 1024); go > 0) result += std::format("{}Go ", go);
118 if (const Size mo = (usedMem / (1024 * 1024)) % 1024; mo > 0)
119 result += std::format("{}Mo ", mo);
120 if (const Size ko = (usedMem / 1024) % 1024; ko > 0) result += std::format("{}Ko ", ko);
121 result += std::format("{}o", usedMem % 1024);
122 return result;
123 }
std::size_t Size
In aGrUM, hashed values are unsigned long int.
Definition types.h:74

Referenced by isIndependent().

Here is the caller graph for this function:

◆ toDot() [1/2]

template<GUM_Numeric GUM_SCALAR>
std::string gum::IBayesNet< GUM_SCALAR >::toDot ( ) const
virtualinherited
Returns
Returns a dot representation of this IBayesNet.

Reimplemented in gum::prm::ClassBayesNet< GUM_SCALAR >, and gum::prm::InstanceBayesNet< GUM_SCALAR >.

Definition at line 200 of file IBayesNet_tpl.h.

200 {
201 return toDot(dot::DotOptions());
202 }
virtual std::string toDot() const

References toDot().

Referenced by cpt(), and toDot().

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

◆ toDot() [2/2]

template<GUM_Numeric GUM_SCALAR>
std::string gum::IBayesNet< GUM_SCALAR >::toDot ( const dot::DotOptions & options) const
virtualinherited

A dot representation of this IBayesNet, with the options given by the caller.

The nodes are named after the variables, with the tooltip "(id) name"; the options are indexed by the identifiers of the nodes.

Reimplemented in gum::BayesNetFragment< GUM_SCALAR >.

Definition at line 205 of file IBayesNet_tpl.h.

205 {
206 const auto style = dot::DotStyle::read();
207 dot::DotWriter writer(true, this->propertyWithDefault("name", ""));
209
210 for (const auto node: nodes()) {
211 const auto& name = variable(node).name();
212 writer.node(name,
214 options.node(node),
215 "",
216 "(" + std::to_string(node) + ") " + name));
217 }
218
219 for (const auto& arc: arcs()) {
220 auto attributes = dot::arcAttributes(options.arc(arc.tail(), arc.head()));
222 "tooltip",
223 std::to_string(arc.tail()) + "&nbsp;&rarr;&nbsp;"
224 + std::to_string(arc.head()));
225 dot::addDefaultAttribute(attributes, "fontsize", "10");
226 writer.edge(variable(arc.tail()).name(), variable(arc.head()).name(), attributes);
227 }
228
229 return writer.str();
230 }
const std::string & propertyWithDefault(std::string_view name, const std::string &byDefault) const
Return the value of the property name of this GraphicalModel.
void writePreamble(DotWriter &writer, const DotStyle &style, const DotOptions &options, std::string_view defaultLabel)
Writes the beginning of a graph, as pyAgrum displays it.
void addDefaultAttribute(DotAttributes &attributes, std::string_view key, std::string_view value)
Adds an attribute at the beginning of the list, unless the list already gives a value for this key : ...
DotAttributes arcAttributes(const DotArcOptions *options)
The attributes of an arc or an edge given by the options : color, penwidth, label,...
static DotStyle read()
the style of the graphs of the section notebook
Definition dotStyle.cpp:89

◆ topologicalOrder()

INLINE Sequence< NodeId > gum::DAGmodel::topologicalOrder ( ) const
inherited

The topological order stays the same as long as no variable or arcs are added or erased src the topology.

Parameters
clearIf false returns the previously created topology.

Definition at line 151 of file DAGmodel_inl.h.

151{ return dag_.topologicalOrder(); }
Sequence< NodeId > topologicalOrder() const
Build and return a topological order.

References dag_, and gum::DiGraph::topologicalOrder().

Referenced by gum::EssentialGraph::_buildEssentialGraph_(), gum::InfluenceDiagramGenerator< GUM_SCALAR >::_checkTemporalOrder_(), gum::InfluenceDiagram< GUM_SCALAR >::decisionOrder(), and gum::InfluenceDiagram< GUM_SCALAR >::decisionOrderExists().

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

◆ toString()

template<GUM_Numeric GUM_SCALAR>
std::string gum::IBayesNet< GUM_SCALAR >::toString ( ) const
inherited
Returns
Returns a string representation of this IBayesNet.

Definition at line 191 of file IBayesNet_tpl.h.

191 {
193 s << std::format("BN{{nodes: {}, arcs: {}, ", size(), dag().sizeArcs());
195 s << "}";
196 return s.str();
197 }
double log10DomainSize() const
static std::string spaceCplxToString(double dSize, int dim, Size usedMem)
send to the stream the space complexity with 3 parametrs

Referenced by cpt(), and gum::operator<<().

Here is the caller graph for this function:

◆ updateMetaData()

void gum::GraphicalModel::updateMetaData ( )
inherited

update the meta data of this Graphical Model (version, creation date, last modification date) This method is called by the writers ONLY before writing the model to a file.

Definition at line 81 of file graphicalModel.cpp.

81 {
82 auto const time = std::chrono::time_point_cast< std::chrono::milliseconds >(
83 std::chrono::system_clock::now());
84 auto const currentdate = std::format("{:%Y-%m-%d %T}", time);
85
86 const std::string currentSoftware = "aGrUM " GUM_VERSION;
87 if (auto software = _propertiesMap_.tryGet("software")) {
88 *software = currentSoftware;
89 } else {
90 _propertiesMap_.insert("software", currentSoftware);
91 }
92
93 if (!_propertiesMap_.tryGet("creation")) { _propertiesMap_.insert("creation", currentdate); }
94
95 if (auto lastModification = _propertiesMap_.tryGet("lastModification")) {
96 *lastModification = currentdate;
97 } else {
98 _propertiesMap_.insert("lastModification", currentdate);
99 }
100 }

References _propertiesMap_, gum::HashTable< Key, Val >::insert(), and gum::HashTable< Key, Val >::tryGet().

Here is the call graph for this function:

◆ variable() [1/2]

template<GUM_Numeric GUM_SCALAR>
INLINE const DiscreteVariable & gum::DiscreteGraphicalModel::variable ( NodeId id) const
overridevirtual

Returns a constant reference over a variable given its node id.

Exceptions
NotFoundif no variable's id matches id.

Implements gum::GraphicalModel.

Definition at line 92 of file discreteGraphicalModel_inl.h.

51 {
52 return varMap_.get(id);
53 }

◆ variable() [2/2]

template<GUM_Numeric GUM_SCALAR>
const DiscreteVariable & gum::BayesNet< GUM_SCALAR >::variable ( std::string_view name) const

Returns a gum::DiscreteVariable given its name in the gum::BayesNet.

Definition at line 733 of file BayesNet_tpl.h.

733 {
734 return variable(idFromName(name));
735 }

References idFromName(), and variable().

Referenced by add(), addArc(), addWeightedArc(), changeVariableLabel(), erase(), gum::getMaxModality(), and variable().

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

◆ variableFromName()

template<GUM_Numeric GUM_SCALAR>
INLINE const DiscreteVariable & gum::DiscreteGraphicalModel::variableFromName ( std::string_view name) const
overridevirtual

Returns a constant reference over a variable given its name.

Exceptions
NotFoundif no such name exists in the model.

Implements gum::GraphicalModel.

Definition at line 110 of file discreteGraphicalModel_inl.h.

66 {
67 return varMap_.variableFromName(name);
68 }

◆ variableNodeMap()

template<GUM_Numeric GUM_SCALAR>
INLINE const VariableNodeMap & gum::DiscreteGraphicalModel::variableNodeMap ( ) const
overridevirtual

Returns a constant reference to the VariableNodeMap of this model.

Implements gum::GraphicalModel.

Definition at line 86 of file discreteGraphicalModel_inl.h.

48{ return varMap_; }

◆ variables() [1/2]

INLINE VariableSet gum::GraphicalModel::variables ( const NodeSet & ids) const
inherited

transform a vector of NodeId into a VariableeSet

Returns
NodeSet

Definition at line 160 of file graphicalModel_inl.h.

160 {
161 VariableSet s;
162 const VariableNodeMap& v = variableNodeMap();
163 for (const auto& node: l) {
164 s.insert(&v.get(node));
165 }
166 return s;
167 }
Set< const DiscreteVariable * > VariableSet

◆ variables() [2/2]

INLINE VariableSet gum::GraphicalModel::variables ( const std::vector< std::string > & l) const
inherited

transform a vector of names into a VariableeSet

Returns
NodeSet

Definition at line 150 of file graphicalModel_inl.h.

150 {
151 VariableSet s;
152 const VariableNodeMap& v = variableNodeMap();
153 for (const auto& name: l) {
154 s.insert(&v.variableFromName(name));
155 }
156 return s;
157 }

References gum::Set< Key >::insert(), gum::VariableNodeMap::variableFromName(), and variableNodeMap().

Referenced by exists().

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

◆ AggregatorDecomposition< GUM_SCALAR >

template<GUM_Numeric GUM_SCALAR>
friend class AggregatorDecomposition< GUM_SCALAR >
friend

Definition at line 697 of file BayesNet.h.

References gum::BayesNet< double >.

◆ BayesNetFactory< GUM_SCALAR >

template<GUM_Numeric GUM_SCALAR>
friend class BayesNetFactory< GUM_SCALAR >
friend

Definition at line 697 of file BayesNet.h.

◆ GumBNReader< GUM_SCALAR >

template<GUM_Numeric GUM_SCALAR>
friend class GumBNReader< GUM_SCALAR >
friend

Definition at line 697 of file BayesNet.h.

Member Data Documentation

◆ _probaMap_

template<GUM_Numeric GUM_SCALAR>
NodeProperty< Tensor< GUM_SCALAR >* > gum::BayesNet< GUM_SCALAR >::_probaMap_
private

Mapping between the variable's id and their CPT.

Definition at line 657 of file BayesNet.h.

Referenced by BayesNet(), ~BayesNet(), add(), addArc(), beginTopologyTransformation(), cpt(), endTopologyTransformation(), erase(), and operator=().

◆ _propertiesMap_

HashTable< std::string, std::string > gum::GraphicalModel::_propertiesMap_
privateinherited

The properties of this Directed Graphical Model.

Definition at line 262 of file graphicalModel.h.

Referenced by GraphicalModel(), GraphicalModel(), _properties_(), existsProperty(), operator=(), operator=(), properties(), propertyWithDefault(), setProperty(), and updateMetaData().

◆ dag_

DAG gum::DAGmodel::dag_
protectedinherited

The DAG of this Directed Graphical Model.

Definition at line 291 of file DAGmodel.h.

Referenced by DAGmodel(), DAGmodel(), _checkNodeExists_(), gum::prm::ClassBayesNet< GUM_SCALAR >::_get_(), gum::prm::ClassBayesNet< GUM_SCALAR >::_init_(), gum::prm::InstanceBayesNet< GUM_SCALAR >::_init_(), gum::BayesNet< GUM_SCALAR >::add(), gum::BayesNet< GUM_SCALAR >::addArc(), gum::InfluenceDiagram< GUM_SCALAR >::addArc(), gum::InfluenceDiagram< GUM_SCALAR >::addNode_(), ancestors(), ancestors(), arcs(), children(), connectedComponents(), dag(), descendants(), descendants(), gum::BayesNet< GUM_SCALAR >::erase(), gum::InfluenceDiagram< GUM_SCALAR >::erase(), gum::BayesNet< GUM_SCALAR >::eraseArc(), gum::InfluenceDiagram< GUM_SCALAR >::eraseArc(), exists(), existsArc(), gum::InfluenceDiagram< GUM_SCALAR >::existsPathBetween(), family(), family(), gum::InfluenceDiagram< GUM_SCALAR >::getChildrenDecision_(), gum::InfluenceDiagram< GUM_SCALAR >::getDecisionGraph(), gum::InfluenceDiagram< GUM_SCALAR >::getPartialTemporalOrder(), gum::BayesNetFragment< GUM_SCALAR >::installArc_(), gum::BayesNetFragment< GUM_SCALAR >::installNode(), internalDag(), isIndependent(), minimalCondSet(), minimalCondSet(), moralGraph(), gum::InfluenceDiagram< GUM_SCALAR >::moralGraph_(), nodes(), operator=(), operator=(), parents(), parents(), parents(), size(), sizeArcs(), gum::InfluenceDiagram< GUM_SCALAR >::toDot(), topologicalOrder(), gum::BayesNetFragment< GUM_SCALAR >::uninstallArc_(), and gum::BayesNetFragment< GUM_SCALAR >::uninstallNode().

◆ varMap_


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