64 template < GUM_Numeric GUM_SCALAR >
67 std::string_view domain) {
71 std::string ds(domain);
72 switch (*(node.begin())) {
82 default : isChanc =
true;
87 if (infdiag.
exists(v->name())) {
95 "No type (chance, decision or utility) for the node '" << node <<
"'.")
101 template < GUM_Numeric GUM_SCALAR >
102 InfluenceDiagram< GUM_SCALAR >
104 return fastPrototype(dotlike,
"[" + std::to_string(domainSize) +
"]");
107 template < GUM_Numeric GUM_SCALAR >
110 std::string_view domain) {
114 = [&](
const std::string& node) {
return build_node_for_ID(infdiag, node, domain); };
116 auto addEdge = [&](
NodeId,
NodeId,
const std::string& token) {
118 "fastPrototype: '" << token <<
"' is preceded by '-' but an InfluenceDiagram "
119 <<
"does not support edges")
124 fastGraphWalkTokens(fastGraphTokenize(chaine), dotlike, resolve,
addArc, addEdge);
127 for (
const auto n: infdiag.
nodes()) {
143 template < GUM_Numeric GUM_SCALAR >
151 template < GUM_Numeric GUM_SCALAR >
157 template < GUM_Numeric GUM_SCALAR >
166 template < GUM_Numeric GUM_SCALAR >
169 if (
this != &source) {
183 template < GUM_Numeric GUM_SCALAR >
192 template < GUM_Numeric GUM_SCALAR >
195 if (
this != &source) {
204 template < GUM_Numeric GUM_SCALAR >
208 this->varMap_.clear();
211 _utilityMap_.clear();
217 template < GUM_Numeric GUM_SCALAR >
228 template < GUM_Numeric GUM_SCALAR >
231 for (
auto node: IDsource.
nodes()) {
238 for (
auto node: IDsource.
nodes()) {
242 addArc(IDsource.
cpt(node).variable(par).name(), s);
254 for (
auto node: IDsource.
nodes()) {
257 cpt(node).fillWith(IDsource.
cpt(s));
264 template < GUM_Numeric GUM_SCALAR >
269 template < GUM_Numeric GUM_SCALAR >
276 const auto writeNodes = [&](
const std::function<
bool(
NodeId) >& isOfThisKind,
277 const std::string& bgColor,
278 const std::string& fgColor,
279 const std::string& shape) {
281 {
"fontcolor", fgColor},
290 for (
const auto node:
dag_.nodes()) {
291 if (!isOfThisKind(node))
continue;
292 const auto& name =
variable(node).name();
297 "(" + std::to_string(node) +
") " + name));
306 style.decisionBgColor,
307 style.decisionFgColor,
308 style.decisionShape);
310 style.utilityBgColor,
311 style.utilityFgColor,
314 for (
const auto& arc:
dag_.arcs()) {
326 template < GUM_Numeric GUM_SCALAR >
328 std::stringstream output;
330 output <<
"Influence Diagram{" << std::endl;
334 output << std::format(
" arcs: {},\n",
dag().
sizeArcs());
337 output << std::format(
" domainSize: 10^{}", dSize);
338 else output << std::format(
" domainSize: {}", std::round(std::pow(10.0, dSize)));
340 output << std::endl <<
"}";
352 template < GUM_Numeric GUM_SCALAR >
360 template < GUM_Numeric GUM_SCALAR >
368 template < GUM_Numeric GUM_SCALAR >
376 template < GUM_Numeric GUM_SCALAR >
388 template < GUM_Numeric GUM_SCALAR >
396 template < GUM_Numeric GUM_SCALAR >
404 template < GUM_Numeric GUM_SCALAR >
412 template < GUM_Numeric GUM_SCALAR >
421 template < GUM_Numeric GUM_SCALAR >
431 template < GUM_Numeric GUM_SCALAR >
439 if (newMultiDim !=
nullptr)
delete newMultiDim;
450 template < GUM_Numeric GUM_SCALAR >
460 template < GUM_Numeric GUM_SCALAR >
479 template < GUM_Numeric GUM_SCALAR >
486 auto varcpt =
new Tensor< GUM_SCALAR >(aContent);
498 template < GUM_Numeric GUM_SCALAR >
505 "Utility var have no state ( which implicates a "
506 "single label for data output reasons ).")
511 auto varut =
new Tensor< GUM_SCALAR >(aContent);
523 template < GUM_Numeric GUM_SCALAR >
529 if (DesiredId == 0) proposedId =
dag_.nextNodeId();
530 else proposedId = DesiredId;
532 this->
varMap_.insert(proposedId, variableType);
534 dag_.addNodeWithId(proposedId);
545 template < GUM_Numeric GUM_SCALAR >
547 if (this->
varMap_.exists(varId)) {
549 for (
const auto chi:
dag_.children(varId))
562 dag_.eraseNode(varId);
571 template < GUM_Numeric GUM_SCALAR >
578 template < GUM_Numeric GUM_SCALAR >
580 this->
varMap_.changeName(
id, new_name);
589 template < GUM_Numeric GUM_SCALAR >
593 dag_.addArc(tail, head);
609 template < GUM_Numeric GUM_SCALAR >
611 if (
dag_.existsArc(arc)) {
630 template < GUM_Numeric GUM_SCALAR >
642 template < GUM_Numeric GUM_SCALAR >
644 for (
const auto node:
dag_.nodes())
647 for (
const auto node:
dag_.nodes()) {
649 for (
const auto par:
dag_.parents(node)) {
652 for (
const auto par2:
dag_.parents(node))
653 if (par != par2)
graph.addEdge(par, par2);
661 template < GUM_Numeric GUM_SCALAR >
671 if (orderIter == order.
end())
return true;
673 NodeId parentDecision = (*orderIter);
677 while (orderIter != order.
end()) {
681 parentDecision = *orderIter;
693 template < GUM_Numeric GUM_SCALAR >
701 mark[src] = (int)src;
704 while (!nodeFIFO.
empty()) {
705 current = nodeFIFO.
front();
708 for (
const auto new_one:
dag_.children(current)) {
709 if (mark[new_one] != -1)
continue;
711 mark[new_one] = (int)current;
713 if (new_one == dest)
break;
719 if (mark[dest] == -1)
return false;
727 template < GUM_Numeric GUM_SCALAR >
731 for (
const auto node:
dag_.nodes()) {
738 temporalGraph.
addArc(node, chi);
743 return temporalGraph;
749 template < GUM_Numeric GUM_SCALAR >
761 mark[parentDecision] =
true;
765 while (!nodeFIFO.
empty()) {
766 current = nodeFIFO.
front();
769 for (
const auto new_one:
dag_.children(current)) {
770 if (mark[new_one])
continue;
772 mark[new_one] =
true;
775 else childrenSeq.
insert(new_one);
786 template < GUM_Numeric GUM_SCALAR >
790 std::vector< NodeId > decisionSequence;
795 return decisionSequence;
802 template < GUM_Numeric GUM_SCALAR >
810 for (
auto i: order) {
813 for (
const auto par:
dag_.parents(i)) {
815 partialOrderedSet.
insert(par);
831 for (
const auto node: nodeList)
840 template < GUM_Numeric GUM_SCALAR >
842 unsigned int default_nbrmod) {
848 template < GUM_Numeric GUM_SCALAR >
851 if (v->domainSize() >= 2)
853 v->name() <<
" has a domain size >= 2 which is impossible for a utility node")
857 template < GUM_Numeric GUM_SCALAR >
859 unsigned int default_nbrmod) {
865 template < GUM_Numeric GUM_SCALAR >
867 unsigned int default_nbrmod) {
868 std::string node(fast_description);
869 switch (*(node.begin())) {
870 case '*' : node.erase(0, 1);
return addDecisionNode(node, default_nbrmod);
872 default :
return addChanceNode(fast_description, default_nbrmod);
877 template < GUM_Numeric GUM_SCALAR >
879 for (
const auto node:
nodes())
885 template < GUM_Numeric GUM_SCALAR >
887 for (
const auto node:
nodes())
892 template < GUM_Numeric GUM_SCALAR >
894 if (
size() != from.
size()) {
return false; }
901 for (
auto node:
nodes()) {
903 if (!from.
exists(v1.name()))
return false;
905 if (v1 != v2) {
return false; }
916 if (p1.
nbrDim() != p2.nbrDim()) {
return false; }
918 if (p1.
domainSize() != p2.domainSize()) {
return false; }
927 for (
Idx indice = 0; indice < p1.
nbrDim(); ++indice) {
932 if (std::pow(p1.
get(i) - p2.get(j), (GUM_SCALAR)2) > tolerance) {
return false; }
936 for (
auto node:
nodes()) {
939 if (!check_pot(
cpt(node), from.
cpt(fromnode))) {
return false; }
941 if (!check_pot(
utility(node), from.
utility(fromnode))) {
return false; }
948 template < GUM_Numeric GUM_SCALAR >
953 template < GUM_Numeric GUM_SCALAR >
958 template < GUM_Numeric GUM_SCALAR >
963 template < GUM_Numeric GUM_SCALAR >
968 template < GUM_Numeric GUM_SCALAR >
973 template < GUM_Numeric GUM_SCALAR >
978 template < GUM_Numeric GUM_SCALAR >
983 template < GUM_Numeric GUM_SCALAR >
985 std::string_view new_name) {
989 template < GUM_Numeric GUM_SCALAR >
994 template < GUM_Numeric GUM_SCALAR >
999 template < GUM_Numeric GUM_SCALAR >
1001 std::string_view dest)
const {
The base class for all directed edges.
GUM_NODISCARD NodeId head() const
returns the head of the arc
GUM_NODISCARD NodeId tail() const
returns the tail of the arc
Arc(NodeId tail, NodeId head)
basic constructor. Creates tail -> head.
const T2 & second(const T1 &first) const
Returns the second value of a pair given its first value.
void insert(const T1 &first, const T2 &second)
Inserts a new association in the gum::Bijection.
Set of pairs of elements with fast search for both elements.
double epsilonStandard() const noexcept
void addArc(NodeId tail, NodeId head) final
insert a new arc into the directed graph
DAG dag_
The DAG of this Directed Graphical Model.
DAGmodel()
Default constructor.
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.
Sequence< NodeId > topologicalOrder() const
The topological order stays the same as long as no variable or arcs are added or erased src the topol...
DAG dag() const
Returns a named copy of the internal DAG: each node id is assigned the name of the corresponding vari...
DAGmodel & operator=(const DAGmodel &source)
Private copy operator.
bool exists(NodeId node) const final
Return true if this node exists in this graphical model.
const NodeSet & parents(const NodeId id) const
returns the set of nodes with arc ingoing to a given node
const NodeGraphPart & nodes() const final
Returns a named copy of the internal DAG: each node id is assigned the name of the corresponding vari...
VariableNodeMap varMap_
Mapping between NodeIds and discrete variables.
Base class for discrete random variable.
virtual Size domainSize() const =0
Base class for all aGrUM's exceptions.
Exception : fatal (unknown ?) error.
void setProperty(std::string_view name, std::string_view value)
Add or change a property of this GraphicalModel.
double log10DomainSize() const
const std::string & propertyWithDefault(std::string_view name, const std::string &byDefault) const
Return the value of the property name of this GraphicalModel.
Class representing an Influence Diagram.
void beginTopologyTransformation()
When inserting/removing arcs, node CPTs/utilities change their dimension with a cost in time.
List< NodeSet > _temporalOrder_
The temporal order.
NodeId idFromName(std::string_view name) const override
Returns the NodeId of a variable given its name.
Size chanceNodeSize() const
Returns the number of chance nodes.
InfluenceDiagram()
Default constructor.
const List< NodeSet > & getPartialTemporalOrder(bool clear=true) const
Returns partial temporal ordering.
NodeId addChanceNode(const DiscreteVariable &variable, NodeId id=0)
Add a chance variable, it's associate node and it's CPT.
void addArc(NodeId tail, NodeId head)
Add an arc in the ID, and update diagram's tensor nodes cpt if necessary.
void endTopologyTransformation()
terminates a sequence of insertions/deletions of arcs by adjusting all CPTs/utilities dimensions.
static InfluenceDiagram< GUM_SCALAR > fastPrototype(std::string_view dotlike, Size domainSize)
Create an Influence Diagram with a dot-like syntax which specifies:
void removeTables_()
Removing ancient table.
void eraseArc(const Arc &arc)
Removes an arc in the ID, and update diagram's tensor nodes cpt if necessary.
NodeProperty< Tensor< GUM_SCALAR > * > _tensorMap_
Mapping between tensor variable's id and their CPT.
virtual void moralGraph_(UndiGraph &graph) const
Returns the moral graph of this InfluenceDiagram.
NodeId addNode_(const DiscreteVariable &variableType, NodeId DesiredId)
Add a node.
std::string toDot() const
bool decisionOrderExists() const
True if a directed path exist with all decision nodes.
bool isChanceNode(NodeId varId) const
Returns true if node is a chance one.
InfluenceDiagram< GUM_SCALAR > & operator=(const InfluenceDiagram< GUM_SCALAR > &source)
Copy Operator.
NodeId add(const DiscreteVariable &variable, NodeId id=0)
Add a chance variable, it's associate node and it's CPT.
NodeId addUtilityNode(const DiscreteVariable &variable, NodeId id=0)
Add a utility variable, it's associate node and it's UT.
std::string toString() const
void copyStructureAndTables_(const InfluenceDiagram< GUM_SCALAR > &IDsource)
Copying tables from another influence diagram.
NodeId addDecisionNode(const DiscreteVariable &variable, NodeId id=0)
Add a decision variable.
const DiscreteVariable & variableFromName(std::string_view name) const override
Returns a constant reference over a variable given its name.
bool isUtilityNode(NodeId varId) const
Returns true if node is a utility one.
bool operator==(const InfluenceDiagram< GUM_SCALAR > &other) const
Size utilityNodeSize() const
Returns the number of utility nodes.
NodeProperty< Tensor< GUM_SCALAR > * > _utilityMap_
Mapping between utility variable's id and their utility table.
gum::DAG getDecisionGraph() const
Returns the temporal Graph.
void changeVariableName(NodeId id, std::string_view new_name)
we allow the user to change the name of a variable
bool isDecisionNode(NodeId varId) const
Returns true if node is a decision one.
const DiscreteVariable & variable(std::string_view name) const
Returns the CPT of a tensor variable.
Sequence< NodeId > getChildrenDecision_(NodeId parentDecision) const
Returns the list of children decision for a given nodeId.
Size decisionNodeSize() const
Returns the number of decision nodes.
void erase(NodeId id)
Erase a Variable from the network and remove the variable from all his children.
virtual const Tensor< GUM_SCALAR > & cpt(NodeId varId) const
Returns the CPT of a tensor variable.
std::vector< NodeId > decisionOrder() const
Returns the sequence of decision nodes in the directed path.
virtual const Tensor< GUM_SCALAR > & utility(NodeId varId) const
Returns the utility table of a utility node.
bool existsPathBetween(NodeId src, NodeId dest) const
Returns true if a path exists between two nodes.
~InfluenceDiagram() override
Destructor.
Class for assigning/browsing values to tuples of discrete variables.
Instantiation & chgVal(const DiscreteVariable &v, Idx newval)
Assign newval to variable v in the Instantiation.
bool end() const
Returns true if the Instantiation reached the end.
void inc()
Operator increment.
Idx val(Idx i) const
Returns the current value of the variable at position i.
void setFirst()
Assign the first values to the tuple of the Instantiation.
const DiscreteVariable & variable(Idx i) const final
Returns the variable at position i in the tuple.
Exception : there is something wrong with an arc.
Exception: at least one argument passed to a function is not what was expected.
Exception : there is something wrong with an edge.
Generic doubly linked lists.
Val & front() const
Returns a reference to first element of a list, if any.
Val & pushBack(const Val &val)
Inserts a new element (a copy) at the end of the chained list.
bool empty() const noexcept
Returns a boolean indicating whether the chained list is empty.
void popFront()
Removes the first element of a List, if any.
MultiDimArray()
Default constructor.
Idx nbrDim() const final
Returns the number of vars in the multidimensional container.
Size domainSize() const final
Returns the product of the variables domain size.
GUM_ELEMENT get(const Instantiation &i) const final
Default implementation of MultiDimContainer::get().
bool existsNode(const NodeId id) const
returns true iff the NodeGraphPart contains the given nodeId
virtual void addNodeWithId(const NodeId id)
try to insert a node with the given id
Exception : the element we looked for cannot be found.
Exception : operation not allowed.
const iterator & end() const noexcept
void insert(const Key &k)
SequenceIterator< Key > const_iterator
Types for STL compliance.
bool contains(const Key &k) const
Indicates whether a given elements belong to the set.
bool empty() const noexcept
Indicates whether the set is the empty set.
void insert(const Key &k)
Inserts a new element into the set.
void erase(const Key &k)
Erases an element from the set.
aGrUM's Tensor is a multi-dimensional array with tensor operators.
Base class for undirected graphs.
const std::string & name() const
returns the name of the variable
The options given to a toDot(const DotOptions&).
const DotArcOptions * arc(Size tail, Size head) const
the options of the arc from tail to head, or nullptr if none was given for it
const DotNodeOptions * node(Size node) const
the options of a node, or nullptr if none was given for it
Writes a graph in the dot language, statement after statement, in the order of the calls.
void nodeDefaults(const DotAttributes &attributes)
node [attributes];, the default attributes of the nodes that follow (none : does nothing).
void edge(std::string_view from, std::string_view to, const DotAttributes &attributes={})
an edge from from to to (-> in a directed graph, -- in an undirected one).
std::string str() const
The graph written so far, closed. It can be called at any moment, and the writer can be used after.
void node(std::string_view id, const DotAttributes &attributes={})
a node, whose identifier is id (quoted).
Typed, documented, sectioned configuration singleton read from an .ini content.
The statements common to the graphs drawn with graphviz : preamble, attributes of nodes and arcs.
#define GUM_ERROR(type, msg)
Builds a graph from a "fast" DOT-like textual description.
std::size_t Size
In aGrUM, hashed values are unsigned long int.
Size Idx
Type for indexes.
Size NodeId
Type for node ids.
HashTable< NodeId, VAL > NodeProperty
Property on graph elements.
Set< NodeId > NodeSet
Some typdefs and define for shortcuts ...
GUM_SHARED_PUBLIC std::string remove_newline(std::string_view s)
remove all newlines in a string
std::vector< std::string > split(std::string_view str, std::string_view delim)
Split str using the delimiter.
Class representing Influence Diagrams.
DotAttributes nodeAttributes(const DotStyle &style, const DotNodeOptions *options, std::string_view defaultLabel, std::string_view defaultTooltip)
The attributes of a node : its label and tooltip, and its colors if the options give some.
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,...
gum is the global namespace for all aGrUM entities
NodeId build_node_for_ID(gum::InfluenceDiagram< GUM_SCALAR > &infdiag, std::string node, std::string_view domain)
Configuration & config()
A short name for Configuration::instance() : gum::config().epsilonStandard(). It is not inline so tha...
std::unique_ptr< DiscreteVariable > fastVariable(std::string var_description, Size default_domain_size)
Create a pointer on a Discrete Variable from a "fast" syntax.
The look shared by all the graphs: size, direction, layout, colors of the arcs and of the nodes.
std::string nodeBgColor
background color of the nodes
static InfluenceDiagramDotStyle read()