Introduction to pyAgrum¶
pyAgrum is a Python wrapper for the C++ aGrUM library. It provides a high-level interface to the C++ part of aGrUM allowing to create, manage and perform efficient computations with Bayesian Networks.

The module is generated using the SWIG interface generator. Custom-written code was added to make the interface more user friendly.
pyAgrum aims to allow to easily use (as well as to prototype new algorithms on) Bayesian network and other graphical models.
- pyAgrum contains
pyAgrum library¶
Functions from pyAgrum¶
Useful functions in pyAgrum
-
pyAgrum.
about
()¶ about() for pyAgrum
-
pyAgrum.
fastBN
(arcs, domain_size=2)¶ rapid prototyping of BN.
Parameters: - arcs – dot-like simple list of arcs (“a->b->c;a->c->d” for instance). The first apparition of a node name can be enhanced with a “[domain_size]” extension. For instance “a[5]->b->c;a[2]->c->d” will create a BN with a variable “a” whos domain size is a.nbrDim()==5 (the second “a[2]” is not taken into account since the variable has already been created).
- domain_size – the domain size of each created variable.
Returns: the created pyAgrum.BayesNet
-
pyAgrum.
getPosterior
(bn, evs, target)¶ Compute the posterior of a single target (variable) in a BN given evidence
getPosterior uses a VariableElimination inference. If more than one target is needed with the same set of evidence or if the same target is needed with more than one set of evidence, this function is not relevant since it creates a new inference engine every time it is called.
Parameters: - bn (pyAgrum.BayesNet) –
- evs (dictionary) – events map {name/id:val, name/id : [ val1, val2 ], …}
- target – variable name or id
Returns: posterior Potential
Input/Output for bayesian networks¶
-
pyAgrum.
availableBNExts
()¶ Returns: a string which lists all suffixes for supported BN file formats.
-
pyAgrum.
loadBN
(filename, listeners=None, verbose=False, **opts)¶ Parameters: - filename – the name of the input file
- listeners – list of functions to execute
- verbose – whether to print or not warning messages
- system – (for O3PRM) name of the system to flatten in a BN
- classpath – (for O3PRM) list of folders containing classes
Returns: a BN from a file using one of the availableBNExts() suffixes.
Listeners could be added in order to monitor its loading.
Examples
>>> import pyAgrum as gum >>> >>> # creating listeners >>> def foo_listener(progress): >>> if progress==200: >>> print(' BN loaded ') >>> return >>> elif progress==100: >>> car='%' >>> elif progress%10==0: >>> car='#' >>> else: >>> car='.' >>> print(car,end='',flush=True) >>> >>> def bar_listener(progress): >>> if progress==50: >>> print('50%') >>> >>> # loadBN with list of listeners >>> gum.loadBN('./bn.bif',listeners=[foo_listener,bar_listener]) >>> # .........#.........#.........#.........#..50% >>> # .......#.........#.........#.........#.........#.........% | bn loaded
-
pyAgrum.
saveBN
(bn, filename)¶ save a BN into a file using the format corresponding to one of the availableWriteBNExts() suffixes.
Graphs manipulation¶
In aGrUM, graphs are undirected (using edges), directed (using arcs) or mixed (using both arcs and edges). Some other types of graphs are described below. Edges and arcs are represented by pairs of int (nodeId), but these pairs are considered as unordered for edges whereas they are ordered for arcs.
For all types of graphs, nodes are int. If a graph of objects is needed (like pyAgrum.BayesNet
), the objects are mapped to nodeIds.
Edges and Arcs¶
Arc¶
-
class
pyAgrum.
Arc
(*args)¶ pyAgrum.Arc is the representation of an arc between two nodes represented by int : the head and the tail.
- Available ructors:
Arc(tail, head) -> Arc
Arc(src) -> Arc
Parameters: - tail (int) – the tail
- head (int) – the head
- src – the Arc to copy
-
first
(Arc self)¶ Returns: the nodeId of the first node of the arc (the tail) Return type: int
-
head
(Arc self)¶ Returns: the id of the head node Return type: int
-
other
(Arc self, int id)¶ Parameters: id (int) – the nodeId of the head or the tail Returns: the nodeId of the other node Return type: int
-
second
(Arc self)¶ Returns: the nodeId of the second node of the arc (the head) Return type: int
-
tail
(Arc self)¶ Returns: the id of the tail node Return type: int
-
thisown
¶ The membership flag
Edge¶
-
class
pyAgrum.
Edge
(*args)¶ pyAgrum.Edge is the representation of an arc between two nodes represented by int : the first and the second.
- Available ructors :
Edge(aN1,aN2) -> Edge
Edge(src) -> Edge
Parameters: - aN1 (int) – the nodeId of the first node
- aN2 (int) – the nodeId of the secondnode
- src (pyAgrum.Edge) – the Edge to copy
-
first
(Edge self)¶ Returns: the nodeId of the first node of the arc (the tail) Return type: int
-
other
(Edge self, int id)¶ Parameters: id (int) – the nodeId of one of the nodes of the Edge Returns: the nodeId of the other node Return type: int
-
second
(Edge self)¶ Returns: the nodeId of the second node of the arc (the head) Return type: int
-
thisown
¶ The membership flag
Directed Graphs¶
Digraph¶
-
class
pyAgrum.
DiGraph
(*args)¶ DiGraph represents a Directed Graph.
- Available ructors:
DiGraph() -> DiGraph
DiGraph(src) -> DiGraph
Parameters: src (pyAgrum.DiGraph) – the digraph to copy -
addArc
(DiGraph self, int tail, int head)¶ addArc(DiGraph self, int n1, int n2)
Add an arc from tail to head.
Parameters: - tail (int) – the id of the tail node
- head (int) – the id of the head node
Raises: gum.InvalidNode
– If head or tail does not belong to the graph nodes.
-
addNode
(DiGraph self)¶ Returns: the new NodeId Return type: int
-
addNodeWithId
(DiGraph self, int id)¶ Add a node by choosing a new NodeId.
Parameters: id (int) – The id of the new node Raises: gum.DuplicateElement
– If the given id is already used
-
addNodes
(DiGraph self, int n)¶ Add n nodes.
Parameters: n (int) – the number of nodes to add. Returns: the new ids Return type: Set of int
-
arcs
(DiGraph self)¶ Returns: the list of the arcs Return type: List
-
children
(DiGraph self, int id)¶ Parameters: id (int) – the id of the parent Returns: the set of all the children Return type: Set
-
clear
(DiGraph self)¶ Remove all the nodes and arcs from the graph.
-
empty
(DiGraph self)¶ Check if the graph is empty.
Returns: True if the graph is empty Return type: bool
-
emptyArcs
(DiGraph self)¶ Check if the graph doesn’t contains arcs.
Returns: True if the graph doesn’t contains arcs Return type: bool
-
eraseArc
(DiGraph self, int n1, int n2)¶ Erase the arc between n1 and n2.
Parameters: - n1 (int) – the id of the tail node
- n2 (int) – the id of the head node
-
eraseChildren
(DiGraph self, int n)¶ Erase the arcs heading through the node’s children.
Parameters: n (int) – the id of the parent node
-
eraseNode
(DiGraph self, int id)¶ Erase the node and all the related arcs.
Parameters: id (int) – the id of the node
-
eraseParents
(DiGraph self, int n)¶ Erase the arcs coming to the node.
Parameters: n (int) – the id of the child node
-
existsArc
(DiGraph self, int n1, int n2)¶ Check if an arc exists bewteen n1 and n2.
Parameters: - n1 (int) – the id of the tail node
- n2 (int) – the id of the head node
Returns: True if the arc exists
Return type: bool
-
existsNode
(DiGraph self, int id)¶ Check if a node with a certain id exists in the graph.
Parameters: id (int) – the checked id Returns: True if the node exists Return type: bool
-
ids
()¶ Deprecated method in pyAgrum>0.12.0. See nodes instead.
-
nodes
(DiGraph self)¶ Returns: the set of ids Return type: set
-
parents
(DiGraph self, int id)¶ Parameters: id – The id of the child node Returns: the set of the parents ids. Return type: Set
-
size
(DiGraph self)¶ Returns: the number of nodes in the graph Return type: int
-
sizeArcs
(DiGraph self)¶ Returns: the number of arcs in the graph Return type: int
-
thisown
¶ The membership flag
-
toDot
(DiGraph self)¶ Returns: a friendly display of the graph in DOT format Return type: str
-
topologicalOrder
(DiGraph self, bool clear=True)¶ Returns: the list of the nodes Ids in a topological order Return type: List Raises: gum.InvalidDirectedCycle
– If this graph contains cycles
Directed Acyclic Graph¶
-
class
pyAgrum.
DAG
(*args)¶ DAG represents a Directed Acyclic Graph.
- Available ructors:
DAG() -> DAG
DAG(src) -> DAG
Parameters: src – the DAG to copy -
addArc
(DAG self, int tail, int head)¶ addArc(DAG self, int n1, int n2)
Add an arc from tail to head.
Parameters: - tail (int) – the id of the tail node
- head (int) – the id of the head node
Raises: gum.InvalidDirectedCircle
– If any (directed) cycle is created by this arcgum.InvalidNode
– If head or tail does not belong to the graph nodes
-
addNode
(DiGraph self)¶ Returns: the new NodeId Return type: int
-
addNodeWithId
(DiGraph self, int id)¶ Add a node by choosing a new NodeId.
Parameters: id (int) – The id of the new node Raises: gum.DuplicateElement
– If the given id is already used
-
addNodes
(DAG self, int n)¶
-
arcs
(DiGraph self)¶ Returns: the list of the arcs Return type: List
-
children
(DiGraph self, int id)¶ Parameters: id (int) – the id of the parent Returns: the set of all the children Return type: Set
-
clear
(DiGraph self)¶ Remove all the nodes and arcs from the graph.
-
empty
(DiGraph self)¶ Check if the graph is empty.
Returns: True if the graph is empty Return type: bool
-
emptyArcs
(DiGraph self)¶ Check if the graph doesn’t contains arcs.
Returns: True if the graph doesn’t contains arcs Return type: bool
-
eraseArc
(DiGraph self, int n1, int n2)¶ Erase the arc between n1 and n2.
Parameters: - n1 (int) – the id of the tail node
- n2 (int) – the id of the head node
-
eraseChildren
(DiGraph self, int n)¶ Erase the arcs heading through the node’s children.
Parameters: n (int) – the id of the parent node
-
eraseNode
(DiGraph self, int id)¶ Erase the node and all the related arcs.
Parameters: id (int) – the id of the node
-
eraseParents
(DiGraph self, int n)¶ Erase the arcs coming to the node.
Parameters: n (int) – the id of the child node
-
existsArc
(DiGraph self, int n1, int n2)¶ Check if an arc exists bewteen n1 and n2.
Parameters: - n1 (int) – the id of the tail node
- n2 (int) – the id of the head node
Returns: True if the arc exists
Return type: bool
-
existsNode
(DiGraph self, int id)¶ Check if a node with a certain id exists in the graph.
Parameters: id (int) – the checked id Returns: True if the node exists Return type: bool
-
ids
()¶ Deprecated method in pyAgrum>0.12.0. See nodes instead.
-
moralGraph
(DAG self)¶
-
nodes
(DiGraph self)¶ Returns: the set of ids Return type: set
-
parents
(DiGraph self, int id)¶ Parameters: id – The id of the child node Returns: the set of the parents ids. Return type: Set
-
size
(DiGraph self)¶ Returns: the number of nodes in the graph Return type: int
-
sizeArcs
(DiGraph self)¶ Returns: the number of arcs in the graph Return type: int
-
thisown
¶ The membership flag
-
toDot
(DiGraph self)¶ Returns: a friendly display of the graph in DOT format Return type: str
-
topologicalOrder
(DiGraph self, bool clear=True)¶ Returns: the list of the nodes Ids in a topological order Return type: List Raises: gum.InvalidDirectedCycle
– If this graph contains cycles
Undirected Graphs¶
UndiGraph¶
-
class
pyAgrum.
UndiGraph
(*args)¶ UndiGraph represents an Undirected Graph.
- Available ructors:
UndiGraph() -> UndiGraph
UndiGraph(src) -> UndiGraph
Parameters: src – the UndiGraph to copy -
addEdge
(UndiGraph self, int n1, int n2)¶ Insert a new edge into the graph.
Parameters: - n1 (int) – the id of one node of the new inserted edge
- n2 (int) – the id of the other node of the new inserted edge
Raises: gum.InvalidNode
– If n1 or n2 does not belong to the graph nodes.
-
addNode
(UndiGraph self)¶ Returns: the new NodeId Return type: int
-
addNodeWithId
(UndiGraph self, int id)¶ Add a node by choosing a new NodeId.
Parameters: id (int) – The id of the new node Raises: gum.DuplicateElement
– If the given id is already used
-
addNodes
(UndiGraph self, int n)¶ Add n nodes.
Parameters: n (int) – the number of nodes to add. Returns: the new ids Return type: Set of int
-
clear
(UndiGraph self)¶ Remove all the nodes and edges from the graph.
-
edges
(UndiGraph self)¶ Returns: the list of the edges Return type: List
-
empty
(UndiGraph self)¶ Check if the graph is empty.
Returns: True if the graph is empty Return type: bool
-
emptyEdges
(UndiGraph self)¶ Check if the graph doesn’t contains edges.
Returns: True if the graph doesn’t contains edges Return type: bool
-
eraseEdge
(UndiGraph self, int n1, int n2)¶ Erase the edge between n1 and n2.
Parameters: - n1 (int) – the id of the tail node
- n2 (int) – the id of the head node
-
eraseNeighbours
(UndiGraph self, int n)¶ Erase all the edges adjacent to a given node.
Parameters: n (int) – the id of the node
-
eraseNode
(UndiGraph self, int id)¶ Erase the node and all the adjacent edges.
Parameters: id (int) – the id of the node
-
existsEdge
(UndiGraph self, int n1, int n2)¶ Check if an edge exists bewteen n1 and n2.
Parameters: - n1 (int) – the id of one extremity of the edge
- n2 (int) – the id of the other extremity if tge edge
Returns: True if the arc exists
Return type: bool
-
existsNode
(UndiGraph self, int id)¶ Check if a node with a certain id exists in the graph.
Parameters: id (int) – the checked id Returns: True if the node exists Return type: bool
-
hasUndirectedCycle
(UndiGraph self)¶ Checks whether the graph contains cycles.
Returns: True if the graph contains a cycle Return type: bool
-
ids
()¶ Deprecated method in pyAgrum>0.12.0. See nodes instead.
-
neighbours
(UndiGraph self, int id)¶ Parameters: id (int) – the id of the checked node Returns: The set of edges adjacent to the given node Return type: Set
-
nodes
(UndiGraph self)¶ Returns: the set of ids Return type: set
-
partialUndiGraph
(UndiGraph self, Set nodesSet)¶ Parameters: nodesSet (Set) – The set of nodes composing the partial graph Returns: The partial graph formed by the nodes given in parameter Return type: pyAgrum.UndiGraph
-
size
(UndiGraph self)¶ Returns: the number of nodes in the graph Return type: int
-
sizeEdges
(UndiGraph self)¶ Returns: the number of edges in the graph Return type: int
-
thisown
¶ The membership flag
-
toDot
(UndiGraph self)¶ Returns: a friendly display of the graph in DOT format Return type: str
Clique Graph¶
-
class
pyAgrum.
CliqueGraph
(*args)¶ CliqueGraph represents a Clique Graph.
- Available ructors:
CliqueGraph() -> CliqueGraph
CliqueGraph(src) -> CliqueGraph
Parameters: src (pyAgrum.CliqueGraph) – the CliqueGraph to copy -
addEdge
(CliqueGraph self, int first, int second)¶ Insert a new edge into the graph.
Parameters: - n1 (int) – the id of one node of the new inserted edge
- n2 (int) – the id of the other node of the new inserted edge
Raises: gum.InvalidNode
– If n1 or n2 does not belong to the graph nodes.
-
addNode
(CliqueGraph self, Set clique)¶ addNode(CliqueGraph self) -> int addNode(CliqueGraph self, int id, Set clique) addNode(CliqueGraph self, int id)
Returns: the new NodeId Return type: int
-
addNodeWithId
(UndiGraph self, int id)¶ Add a node by choosing a new NodeId.
Parameters: id (int) – The id of the new node Raises: gum.DuplicateElement
– If the given id is already used
-
addNodes
(UndiGraph self, int n)¶ Add n nodes.
Parameters: n (int) – the number of nodes to add. Returns: the new ids Return type: Set of int
-
addToClique
(CliqueGraph self, int clique_id, int node_id)¶ Change the set of nodes included into a given clique and returns the new set
Parameters: - clique_id (int) – the id of the clique
- node_id (int) – the id of the node
Raises: gum.NotFound
– If clique_id does not existgum.DuplicateElement
– If clique_id set already contains the ndoe
-
clear
(CliqueGraph self)¶ Remove all the nodes and edges from the graph.
-
clearEdges
(CliqueGraph self)¶ Remove all edges and their separators
-
clique
(CliqueGraph self, int clique)¶ Parameters: idClique (int) – the id of the clique Returns: The set of nodes included in the clique Return type: Set Raises: gum.NotFound
– If the clique does not belong to the clique graph
-
container
(CliqueGraph self, int idNode)¶ Parameters: idNode (int) – the id of the node Returns: the id of a clique containing the node Return type: int Raises: gum.NotFound
– If no clique contains idNode
-
containerPath
(CliqueGraph self, int node1, int node2)¶ Parameters: - node1 (int) – the id of one node
- node2 (int) – the id of the other node
Returns: a path from a clique containing node1 to a clique containing node2
Return type: List
Raises: gum.NotFound
– If such path cannot be found
-
edges
(UndiGraph self)¶ Returns: the list of the edges Return type: List
-
empty
(UndiGraph self)¶ Check if the graph is empty.
Returns: True if the graph is empty Return type: bool
-
emptyEdges
(UndiGraph self)¶ Check if the graph doesn’t contains edges.
Returns: True if the graph doesn’t contains edges Return type: bool
-
eraseEdge
(CliqueGraph self, Edge edge)¶ Erase the edge between n1 and n2.
Parameters: - n1 (int) – the id of the tail node
- n2 (int) – the id of the head node
-
eraseFromClique
(CliqueGraph self, int clique_id, int node_id)¶ Remove a node from a clique
Parameters: - clique_id (int) – the id of the clique
- node_id (int) – the id of the node
Raises: gum.NotFound
– If clique_id does not exist
-
eraseNeighbours
(UndiGraph self, int n)¶ Erase all the edges adjacent to a given node.
Parameters: n (int) – the id of the node
-
eraseNode
(CliqueGraph self, int node)¶ Erase the node and all the adjacent edges.
Parameters: id (int) – the id of the node
-
existsEdge
(UndiGraph self, int n1, int n2)¶ Check if an edge exists bewteen n1 and n2.
Parameters: - n1 (int) – the id of one extremity of the edge
- n2 (int) – the id of the other extremity if tge edge
Returns: True if the arc exists
Return type: bool
-
existsNode
(UndiGraph self, int id)¶ Check if a node with a certain id exists in the graph.
Parameters: id (int) – the checked id Returns: True if the node exists Return type: bool
-
hasRunningIntersection
(CliqueGraph self)¶ Returns: True if the running intersection property holds Return type: bool
-
hasUndirectedCycle
(UndiGraph self)¶ Checks whether the graph contains cycles.
Returns: True if the graph contains a cycle Return type: bool
-
ids
()¶ Deprecated method in pyAgrum>0.12.0. See nodes instead.
-
isJoinTree
(CliqueGraph self)¶ Returns: True if the graph is a join tree Return type: bool
-
neighbours
(UndiGraph self, int id)¶ Parameters: id (int) – the id of the checked node Returns: The set of edges adjacent to the given node Return type: Set
-
nodes
(UndiGraph self)¶ Returns: the set of ids Return type: set
-
partialUndiGraph
(UndiGraph self, Set nodesSet)¶ Parameters: nodesSet (Set) – The set of nodes composing the partial graph Returns: The partial graph formed by the nodes given in parameter Return type: pyAgrum.UndiGraph
-
separator
(CliqueGraph self, int cliq1, int cliq2)¶ Parameters: - edge (pyAgrum.Edge) – the edge to be checked
- clique1 (int) – one extremity of the edge
- clique (int) – the other extremity of the edge
Returns: the separator included in a given edge
Return type: Set
Raises: gum.NotFound
– If the edge does not belong to the clique graph
-
setClique
(CliqueGraph self, int idClique, Set new_clique)¶ changes the set of nodes included into a given clique
Parameters: - idClique (int) – the id of the clique
- new_clique (Set) – the new set of nodes to be included in the clique
Raises: gum.NotFound
– If idClique is not a clique of the graph
-
size
(UndiGraph self)¶ Returns: the number of nodes in the graph Return type: int
-
sizeEdges
(UndiGraph self)¶ Returns: the number of edges in the graph Return type: int
-
thisown
¶ The membership flag
-
toDot
(CliqueGraph self)¶ Returns: a friendly display of the graph in DOT format Return type: str
-
toDotWithNames
(bn)¶ Parameters: - bn (pyAgrum.BayesNet) –
- Bayesian network (a) –
Returns: a friendly display of the graph in DOT format where ids have been changed according to their correspondance in the BN
Return type: str
Mixed Graph¶
-
class
pyAgrum.
MixedGraph
(*args)¶ MixedGraph represents a Clique Graph.
- Available ructors:
MixedGraph() -> MixedGraph
MixedGraph(src) -> MixedGraph
Parameters: src (pyAgrum.MixedGraph) – the MixedGraph to copy -
addArc
(DiGraph self, int tail, int head)¶ addArc(DiGraph self, int n1, int n2)
Add an arc from tail to head.
Parameters: - tail (int) – the id of the tail node
- head (int) – the id of the head node
Raises: gum.InvalidNode
– If head or tail does not belong to the graph nodes.
-
addEdge
(UndiGraph self, int n1, int n2)¶ Insert a new edge into the graph.
Parameters: - n1 (int) – the id of one node of the new inserted edge
- n2 (int) – the id of the other node of the new inserted edge
Raises: gum.InvalidNode
– If n1 or n2 does not belong to the graph nodes.
-
addNode
(UndiGraph self)¶ Returns: the new NodeId Return type: int
-
addNodeWithId
(UndiGraph self, int id)¶ Add a node by choosing a new NodeId.
Parameters: id (int) – The id of the new node Raises: gum.DuplicateElement
– If the given id is already used
-
addNodes
(UndiGraph self, int n)¶ Add n nodes.
Parameters: n (int) – the number of nodes to add. Returns: the new ids Return type: Set of int
-
arcs
(DiGraph self)¶ Returns: the list of the arcs Return type: List
-
children
(DiGraph self, int id)¶ Parameters: id (int) – the id of the parent Returns: the set of all the children Return type: Set
-
clear
(MixedGraph self)¶ Remove all the nodes and edges from the graph.
-
edges
(UndiGraph self)¶ Returns: the list of the edges Return type: List
-
empty
(UndiGraph self)¶ Check if the graph is empty.
Returns: True if the graph is empty Return type: bool
-
emptyArcs
(DiGraph self)¶ Check if the graph doesn’t contains arcs.
Returns: True if the graph doesn’t contains arcs Return type: bool
-
emptyEdges
(UndiGraph self)¶ Check if the graph doesn’t contains edges.
Returns: True if the graph doesn’t contains edges Return type: bool
-
eraseArc
(DiGraph self, int n1, int n2)¶ Erase the arc between n1 and n2.
Parameters: - n1 (int) – the id of the tail node
- n2 (int) – the id of the head node
-
eraseChildren
(DiGraph self, int n)¶ Erase the arcs heading through the node’s children.
Parameters: n (int) – the id of the parent node
-
eraseEdge
(UndiGraph self, int n1, int n2)¶ Erase the edge between n1 and n2.
Parameters: - n1 (int) – the id of the tail node
- n2 (int) – the id of the head node
-
eraseNeighbours
(UndiGraph self, int n)¶ Erase all the edges adjacent to a given node.
Parameters: n (int) – the id of the node
-
eraseNode
(MixedGraph self, int id)¶ Erase the node and all the adjacent edges.
Parameters: id (int) – the id of the node
-
eraseParents
(DiGraph self, int n)¶ Erase the arcs coming to the node.
Parameters: n (int) – the id of the child node
-
existsArc
(DiGraph self, int n1, int n2)¶ Check if an arc exists bewteen n1 and n2.
Parameters: - n1 (int) – the id of the tail node
- n2 (int) – the id of the head node
Returns: True if the arc exists
Return type: bool
-
existsEdge
(UndiGraph self, int n1, int n2)¶ Check if an edge exists bewteen n1 and n2.
Parameters: - n1 (int) – the id of one extremity of the edge
- n2 (int) – the id of the other extremity if tge edge
Returns: True if the arc exists
Return type: bool
-
existsNode
(UndiGraph self, int id)¶ Check if a node with a certain id exists in the graph.
Parameters: id (int) – the checked id Returns: True if the node exists Return type: bool
-
hasUndirectedCycle
(UndiGraph self)¶ Checks whether the graph contains cycles.
Returns: True if the graph contains a cycle Return type: bool
-
ids
()¶ Deprecated method in pyAgrum>0.12.0. See nodes instead.
-
mixedOrientedPath
(MixedGraph self, int node1, int node2)¶ Parameters: - node1 (int) – the id form which the path begins
- node2 (int) – the id to witch the path ends
Returns: a path from node1 to node2, using edges and/or arcs (following the direction of the arcs)
Return type: List
Raises: gum.NotFound
– If no path can be found between the two nodes
-
mixedUnorientedPath
(MixedGraph self, int node1, int node2)¶ Parameters: - node1 (int) – the id from which the path begins
- node2 (int) – the id to which the path ends
Returns: a path from node1 to node2, using edges and/or arcs (not necessarily following the direction of the arcs)
Return type: List
Raises: gum.NotFound
– If no path can be found between the two nodes
-
neighbours
(UndiGraph self, int id)¶ Parameters: id (int) – the id of the checked node Returns: The set of edges adjacent to the given node Return type: Set
-
nodes
(UndiGraph self)¶ Returns: the set of ids Return type: set
-
parents
(DiGraph self, int id)¶ Parameters: id – The id of the child node Returns: the set of the parents ids. Return type: Set
-
partialUndiGraph
(UndiGraph self, Set nodesSet)¶ Parameters: nodesSet (Set) – The set of nodes composing the partial graph Returns: The partial graph formed by the nodes given in parameter Return type: pyAgrum.UndiGraph
-
size
(UndiGraph self)¶ Returns: the number of nodes in the graph Return type: int
-
sizeArcs
(DiGraph self)¶ Returns: the number of arcs in the graph Return type: int
-
sizeEdges
(UndiGraph self)¶ Returns: the number of edges in the graph Return type: int
-
thisown
¶ The membership flag
-
toDot
(MixedGraph self)¶ Returns: a friendly display of the graph in DOT format Return type: str
-
topologicalOrder
(DiGraph self, bool clear=True)¶ Returns: the list of the nodes Ids in a topological order Return type: List Raises: gum.InvalidDirectedCycle
– If this graph contains cycles
Random Variables¶
aGrUM/pyAgrum is currently dedicated for discrete probability distributions.
There are 3 types of discrete random variables in aGrUM/pyAgrum: LabelizedVariable, DiscretizedVariable and RangeVariable. The 3 types are mainly provided in order to ease modelization. Derived from DiscreteVariable, they share a common API. They essentially differ by the means to create, name and access to their modalities.
Common API for Random Discrete Variables¶
-
class
pyAgrum.
DiscreteVariable
(*args, **kwargs)¶ DiscreteVariable is the base class for discrete random variable.
Available ructors:
DiscreteVariable(aName, aDesc='') -> DiscreteVariable
DiscreteVariable(aDRV) -> DiscreteVariable
Parameters: - aName (str) – The name of the variable
- aDesc (str) – The (optional) description of the variable
- aDRV (pyAgrum.DiscreteVariable) – Another DiscreteVariable that will be copied
-
description
(Variable self)¶ Returns: the description of the variable Return type: str
-
domain
(DiscreteVariable self)¶ Returns: the domain of the variable Return type: str
-
domainSize
(DiscreteVariable self)¶ Returns: the number of modalities in the variable domain Return type: int
-
empty
(DiscreteVariable self)¶ Returns: True if the domain size < 2 Return type: bool
-
index
(DiscreteVariable self, str label)¶ Parameters: label (str) – a label Returns: the indice of the label Return type: int
-
label
(DiscreteVariable self, int i)¶ Parameters: i (int) – the index of the label we wish to return Returns: the indice-th label Return type: str Raises: gum.OutOfBound
– If the variable does not contain the label
-
labels
(DiscreteVariable self)¶ Returns: a tuple containing the labels Return type: tuple
-
name
(Variable self)¶ Returns: the name of the variable Return type: str
-
numerical
(DiscreteVariable self, int indice)¶ Parameters: indice (int) – an index Returns: the numerical representation of the indice-th value Return type: float
-
setDescription
(Variable self, str theValue)¶ set the description of the variable.
Parameters: theValue (str) – the new description of the variable
-
setName
(Variable self, str theValue)¶ sets the name of the variable.
Parameters: theValue (str) – the new description of the variable
-
thisown
¶ The membership flag
-
toDiscretizedVar
(DiscreteVariable self)¶ Returns: the discretized variable Return type: pyAgrum.DiscretizedVariable Raises: gum.RuntimeError
– If the variable is not a DiscretizedVariable
-
toLabelizedVar
(DiscreteVariable self)¶ Returns: the labelized variable Return type: pyAgrum.LabelizedVariable Raises: gum.RuntimeError
– If the variable is not a LabelizedVariable
-
toRangeVar
(DiscreteVariable self)¶ Returns: the range variable Return type: pyAgrum.RangeVariable Raises: gum.RuntimeError
– If the variable is not a RangeVariable
-
toStringWithDescription
(DiscreteVariable self)¶ Returns: a description of the variable Return type: str
-
varType
(DiscreteVariable self)¶ returns the type of variable
Returns: the type of the variable, 0: DiscretizedVariable, 1: LabelizedVariable, 2: RangeVariable Return type: int
Concrete classes for Random Discrete Variables¶
LabelizedVariable¶
-
class
pyAgrum.
LabelizedVariable
(*args)¶ LabelizedVariable is a discrete random variable with a customizable sequence of labels.
Available ructors:
LabelizedVariable(aName, aDesc='', nbrLabel=2) -> LabelizedVariable
LabelizedVariable(aName, aDesc='') -> LabelizedVariable
LabelizedVariable(aLDRV) -> LabelizedVariable
Parameters: - aName (str) – The name of the variable
- aDesc (str) – The (optional) description of the variable
- nbrLabel (int) – The number of labels to create (2 by default)
- aLDRV (pyAgrum.LabelizedVariable) – Another LabelizedVariable that will be copied
Examples
>>> import pyAgrum as gum >>> >>> # creating a variable with 3 labels : '0', '1' and '2' >>> va=gum.LabelizedVariable('a','a labelized variable',3) >>> print(va) >>> ## a<0,1,2> >>> >>> va.addLabel('foo') >>> print(va) >>> ## a<0,1,2,foo> >>> >>> va.chgLabel(1,'bar') >>> print(va) >>> a<0,bar,2,foo> >>> >>> vb=gum.LabelizedVariable('b','b',0).addLabel('A').addLabel('B').addLabel('C') >>> print(vb) >>> ## b<A,B,C> >>> >>> vb.labels() >>> ## ('A', 'B', 'C') >>> >>> vb.isLabel('E') >>> ## False >>> >>> vb.label(2) >>> ## 'B'
-
addLabel
(*args)¶ Add a label with a new index (we assume that we will NEVER remove a label).
Parameters: aLabel (str) – the label to be added to the labelized variable Returns: the labelized variable Return type: pyAgrum.LabelizedVariable Raises: gum.DuplicateElement
– If the variable already contains the label
-
changeLabel
(LabelizedVariable self, int pos, str aLabel)¶ Change the label at the specified index
Parameters: - pos (int) – the index of the label to be changed
- aLabel (str) – the label to be added to the labelized variable
Raises: gum.DuplicatedElement
– If the variable already contains the new labelgum.OutOfBounds
– If the index is greater than the size of the variable
-
description
(Variable self)¶ Returns: the description of the variable Return type: str
-
domain
(LabelizedVariable self)¶ Returns: the domain of the variable as a string Return type: str
-
domainSize
(LabelizedVariable self)¶ Returns: the number of modalities in the variable domain Return type: int
-
empty
(DiscreteVariable self)¶ Returns: True if the domain size < 2 Return type: bool
-
eraseLabels
(LabelizedVariable self)¶ Erase all the labels from the variable.
-
index
(LabelizedVariable self, str label)¶ Parameters: label (str) – a label Returns: the indice of the label Return type: int
-
isLabel
(LabelizedVariable self, str aLabel)¶ Indicates whether the variable already has the label passed in argument
Parameters: aLabel (str) – the label to be tested Returns: True if the label already exists Return type: bool
-
label
(LabelizedVariable self, int i)¶ Parameters: i (int) – the index of the label we wish to return Returns: the indice-th label Return type: str Raises: gum.OutOfBound
– If the variable does not contain the label
-
labels
(DiscreteVariable self)¶ Returns: a tuple containing the labels Return type: tuple
-
name
(Variable self)¶ Returns: the name of the variable Return type: str
-
numerical
(LabelizedVariable self, int indice)¶ Parameters: indice (int) – an index Returns: the numerical representation of the indice-th value Return type: float
-
posLabel
(LabelizedVariable self, str label)¶
-
setDescription
(Variable self, str theValue)¶ set the description of the variable.
Parameters: theValue (str) – the new description of the variable
-
setName
(Variable self, str theValue)¶ sets the name of the variable.
Parameters: theValue (str) – the new description of the variable
-
thisown
¶ The membership flag
-
toDiscretizedVar
(DiscreteVariable self)¶ Returns: the discretized variable Return type: pyAgrum.DiscretizedVariable Raises: gum.RuntimeError
– If the variable is not a DiscretizedVariable
-
toLabelizedVar
(DiscreteVariable self)¶ Returns: the labelized variable Return type: pyAgrum.LabelizedVariable Raises: gum.RuntimeError
– If the variable is not a LabelizedVariable
-
toRangeVar
(DiscreteVariable self)¶ Returns: the range variable Return type: pyAgrum.RangeVariable Raises: gum.RuntimeError
– If the variable is not a RangeVariable
-
toStringWithDescription
(DiscreteVariable self)¶ Returns: a description of the variable Return type: str
-
varType
(LabelizedVariable self)¶ returns the type of variable
Returns: the type of the variable, 0: DiscretizedVariable, 1: LabelizedVariable, 2: RangeVariable Return type: int
DiscretizedVariable¶
-
class
pyAgrum.
DiscretizedVariable
(*args)¶ DiscretizedVariable is a discrete random variable with a set of
ticks
defining intervalls.Available ructors:
DiscretizedVariable(aName, aDesc='') -> DiscretizedVariable
DiscretizedVariable(aDDRV) -> DiscretizedVariable
Parameters: - aName (str) – The name of the variable
- aDesc (str) – The (optional) description of the variable
- aDDRV (pyAgrum.DiscretizedVariable) – Another DiscretizedVariable that will be copied
Examples
>>> import pyAgrum as gum >>> >>> vX=gum.DiscretizedVariable('X','X has been discretized') >>> vX.addTick(1).addTick(2).addTick(3).addTick(3.1415) #doctest: +ELLIPSIS >>> ## <pyAgrum.pyAgrum.DiscretizedVariable;...> >>> print(vX) >>> ## X<[1;2[,[2;3[,[3;3.1415]> >>> >>> vX.isTick(4) >>> ## False >>> >>> vX.labels() >>> ## ('[1;2[', '[2;3[', '[3;3.1415]') >>> >>> # where is the real value 2.5 ? >>> vX.index('2.5') >>> ## 1
-
addTick
(*args)¶ Parameters: aTick (double) – the Tick to be added Returns: the discretized variable Return type: pyAgrum.DiscretizedVariable Raises: gum.DefaultInLabel
– If the tick is already defined
-
description
(Variable self)¶ Returns: the description of the variable Return type: str
-
domain
(DiscretizedVariable self)¶ Returns: the domain of the variable as a string Return type: str
-
domainSize
(DiscretizedVariable self)¶ Returns: the number of modalities in the variable domain Return type: int
-
empty
(DiscreteVariable self)¶ Returns: True if the domain size < 2 Return type: bool
-
eraseTicks
(DiscretizedVariable self)¶ erase all the Ticks
-
index
(DiscretizedVariable self, str label)¶ Parameters: label (str) – a label Returns: the indice of the label Return type: int
-
isTick
(DiscretizedVariable self, double aTick)¶ Parameters: aTick (double) – the Tick to be tested Returns: True if the Tick already exists Return type: bool
-
label
(DiscretizedVariable self, int i)¶ Parameters: i (int) – the index of the label we wish to return Returns: the indice-th label Return type: str Raises: gum.OutOfBound
– If the variable does not contain the label
-
labels
(DiscreteVariable self)¶ Returns: a tuple containing the labels Return type: tuple
-
name
(Variable self)¶ Returns: the name of the variable Return type: str
-
numerical
(DiscretizedVariable self, int indice)¶ Parameters: indice (int) – an index Returns: the numerical representation of the indice-th value Return type: float
-
setDescription
(Variable self, str theValue)¶ set the description of the variable.
Parameters: theValue (str) – the new description of the variable
-
setName
(Variable self, str theValue)¶ sets the name of the variable.
Parameters: theValue (str) – the new description of the variable
-
thisown
¶ The membership flag
-
tick
(DiscretizedVariable self, int i)¶ Indicate the index of the Tick
Parameters: i (int) – the index of the Tick Returns: aTick – the index-th Tick Return type: double Raises: gum.NotFound
– If the index is greater than the number of Ticks
-
ticks
(DiscretizedVariable self)¶ Returns: a tuple containing all the Ticks Return type: tuple
-
toDiscretizedVar
(DiscreteVariable self)¶ Returns: the discretized variable Return type: pyAgrum.DiscretizedVariable Raises: gum.RuntimeError
– If the variable is not a DiscretizedVariable
-
toLabelizedVar
(DiscreteVariable self)¶ Returns: the labelized variable Return type: pyAgrum.LabelizedVariable Raises: gum.RuntimeError
– If the variable is not a LabelizedVariable
-
toRangeVar
(DiscreteVariable self)¶ Returns: the range variable Return type: pyAgrum.RangeVariable Raises: gum.RuntimeError
– If the variable is not a RangeVariable
-
toStringWithDescription
(DiscreteVariable self)¶ Returns: a description of the variable Return type: str
-
varType
(DiscretizedVariable self)¶ returns the type of variable
Returns: the type of the variable, 0: DiscretizedVariable, 1: LabelizedVariable, 2: RangeVariable Return type: int
RangeVariable¶
-
class
pyAgrum.
RangeVariable
(*args)¶ RangeVariable represents a variable with a range of integers as domain.
Available ructors:
RangeVariable(aName, aDesc='',minVal, maxVal) -> RangeVariable
RangeVariable(aName, aDesc='',minVal) -> RangeVariable
RangeVariable(aName, aDesc='') -> RangeVariable
RangeVariable(aRV) -> RangeVariable
Parameters: - aName (str) – The name of the variable
- aDesc (str) – The (optional) description of the variable
- minVal (int) – The minimal integer of the interval
- maxVal (int) – The maximal integer of the interval
- aDV (pyAgrum.RangeVariable) – Another RangeVariable that will be copied
Examples
>>> import pyAgrum as gum >>> >>> vI=gum.gum.RangeVariable('I','I in [4,10]',4,10) >>> print(vI) >>> ## I[4-10] >>> >>> vX.maxVal() >>> ## 10 >>> >>> vX.belongs(1) >>> ## False >>> >>> # where is the value 5 ? >>> vX.index('5') >>> ## 1 >>> >>> vi.labels() >>> ## ('4', '5', '6', '7', '8', '9', '10')
-
belongs
(RangeVariable self, long val)¶ Parameters: val (long) – the value to be tested Returns: True if the value in parameters belongs to the variable’s interval. Return type: bool
-
description
(Variable self)¶ Returns: the description of the variable Return type: str
-
domain
(RangeVariable self)¶ Returns: the domain of the variable Return type: str
-
domainSize
(RangeVariable self)¶ Returns: the number of modalities in the variable domain Return type: int
-
empty
(DiscreteVariable self)¶ Returns: True if the domain size < 2 Return type: bool
-
index
(RangeVariable self, str arg2)¶ Parameters: arg2 (str) – a label Returns: the indice of the label Return type: int
-
label
(RangeVariable self, int indice)¶ Parameters: indice (int) – the index of the label we wish to return Returns: the indice-th label Return type: str Raises: gum.OutOfBound
– If the variable does not contain the label
-
labels
(DiscreteVariable self)¶ Returns: a tuple containing the labels Return type: tuple
-
maxVal
(RangeVariable self)¶ Returns: the upper bound of the variable. Return type: long
-
minVal
(RangeVariable self)¶ Returns: the lower bound of the variable Return type: long
-
name
(Variable self)¶ Returns: the name of the variable Return type: str
-
numerical
(RangeVariable self, int indice)¶ Parameters: indice (int) – an index Returns: the numerical representation of the indice-th value Return type: float
-
setDescription
(Variable self, str theValue)¶ set the description of the variable.
Parameters: theValue (str) – the new description of the variable
-
setMaxVal
(RangeVariable self, long maxVal)¶ Set a new value of the upper bound
Parameters: maxVal (long) – The new value of the upper bound Warning
An error should be raised if the value is lower than the lower bound.
-
setMinVal
(RangeVariable self, long minVal)¶ Set a new value of the lower bound
Parameters: minVal (long) – The new value of the lower bound Warning
An error should be raised if the value is higher than the upper bound.
-
setName
(Variable self, str theValue)¶ sets the name of the variable.
Parameters: theValue (str) – the new description of the variable
-
thisown
¶ The membership flag
-
toDiscretizedVar
(DiscreteVariable self)¶ Returns: the discretized variable Return type: pyAgrum.DiscretizedVariable Raises: gum.RuntimeError
– If the variable is not a DiscretizedVariable
-
toLabelizedVar
(DiscreteVariable self)¶ Returns: the labelized variable Return type: pyAgrum.LabelizedVariable Raises: gum.RuntimeError
– If the variable is not a LabelizedVariable
-
toRangeVar
(DiscreteVariable self)¶ Returns: the range variable Return type: pyAgrum.RangeVariable Raises: gum.RuntimeError
– If the variable is not a RangeVariable
-
toStringWithDescription
(DiscreteVariable self)¶ Returns: a description of the variable Return type: str
-
varType
(RangeVariable self)¶ returns the type of variable
Returns: the type of the variable, 0: DiscretizedVariable, 1: LabelizedVariable, 2: RangeVariable Return type: int
Potential and Instantiation¶
pyAgrum.Potential
is a multi-dimensional array with a pyAgrum.DiscreteVariable
associated to each dimension.
It is used to represent probabilities and utilities tables in aGrUMs’ multidimensional (graphical) models with some conventions.
- The data are stored by iterating over each variable in the sequence.
>>> a=gum.RangeVariable("A","variable A",1,3)
>>> b=gum.RangeVariable("B","variable B",1,2)
>>> p=gum.Potential().add(a).add(b).fillWith([1,2,3,4,5,6]);
>>> print(p)
<A:1|B:1> :: 1 /<A:2|B:1> :: 2 /<A:3|B:1> :: 3 /<A:1|B:2> :: 4 /<A:2|B:2> :: 5 /<A:3|B:2> :: 6
- If a
pyAgrum.Potential
with the sequence ofpyAgrum.DiscreteVariable
X,Y,Z represents a conditional probability Table (CPT), it will be P(X|Y,Z).
>>> print(p.normalizeAsCPT())
<A:1|B:1> :: 0.166667 /<A:2|B:1> :: 0.333333 /<A:3|B:1> :: 0.5 /<A:1|B:2> :: 0.266667 /<A:2|B:2> :: 0.333333 /<A:3|B:2> :: 0.4
- For addressing and looping in a
pyAgrum.Potential
structure, pyAgrum providesInstantiation
class which represents a multi-dimensionnal index.
>>> I=gum.Instantiation(p)
>>> print(I)
<A:1|B:1>
>>> I.inc();print(I)
<A:2|B:1>
>>> I.inc();print(I)
<A:3|B:1>
>>> I.inc();print(I)
<A:1|B:2>
>>> I.setFirst();print("{} -> {}".format(I,p.get(I)))
<A:1|B:1> -> 0.16666666666666666
>>> I["B"]="2";print("{} -> {}".format(I,p.get(I)))
<A:1|B:2> -> 0.26666666666666666
pyAgrum.Potential
include tensor operators (see for instance this notebook).
>>> c=gum.RangeVariable("C","variable C",1,5)
>>> q=gum.Potential().add(a).add(c).fillWith(1)
>>> print(p+q)
<A:1|C:1|B:1> :: 2 /<A:2|C:1|B:1> :: 3 /<A:3|C:1|B:1> :: 4 /<A:1|C:2|B:1> :: 2 /<A:2|C:2|B:1> :: 3 /<A:3|C:2|B:1> :: 4 /<A:1|C:3|B:1> :: 2 /<A:2|C:3|B:1> :: 3 /<A:3|C:3|B:1> :: 4 /<A:1|C:4|B:1> :: 2 /<A:2|C:4|B:1> :: 3 /<A:3|C:4|B:1> :: 4 /<A:1|C:5|B:1> :: 2 /<A:2|C:5|B:1> :: 3 /<A:3|C:5|B:1> :: 4 /<A:1|C:1|B:2> :: 5 /<A:2|C:1|B:2> :: 6 /<A:3|C:1|B:2> :: 7 /<A:1|C:2|B:2> :: 5 /<A:2|C:2|B:2> :: 6 /<A:3|C:2|B:2> :: 7 /<A:1|C:3|B:2> :: 5 /<A:2|C:3|B:2> :: 6 /<A:3|C:3|B:2> :: 7 /<A:1|C:4|B:2> :: 5 /<A:2|C:4|B:2> :: 6 /<A:3|C:4|B:2> :: 7 /<A:1|C:5|B:2> :: 5 /<A:2|C:5|B:2> :: 6 /<A:3|C:5|B:2> :: 7
>>> print((p*q).margSumOut(["B","C"])) # marginalize p*q over B and C(using sum)
<A:1> :: 25 /<A:2> :: 35 /<A:3> :: 45
Instantiation¶
-
class
pyAgrum.
Instantiation
(*args)¶ Class for assigning/browsing values to tuples of discrete variables.
Instantiation is designed to assign values to tuples of variables and to efficiently loop over values of subsets of variables.
Available ructors:
Instantiation() -> Instantiation
Instantiation(aI) -> Instantiation
Parameters: aI (pyAgrum.Instantiation) – The Instantiation we copy Returns: - pyAgrum.Instantiation – An empty tuple or a copy of the one in parameters
- Instantiation is subscriptable therefore values can be easily accessed/modified.
Examples
>>> ## Access the value of A in an instantiation aI >>> valueOfA = aI['A'] >>> ## Modify the value >>> aI['A'] = newValueOfA
-
add
(Instantiation self, DiscreteVariable v)¶ Adds a new variable in the Instantiation.
Parameters: v (pyAgrum.DiscreteVariable) – The new variable added to the Instantiation Raises: DuplicateElement
– If the variable is already in this Instantiation
-
chgVal
(Instantiation self, DiscreteVariable v, int newval)¶ chgVal(Instantiation self, DiscreteVariable v, int newval) -> Instantiation chgVal(Instantiation self, int varPos, int newval) -> Instantiation chgVal(Instantiation self, str var, int newval) -> Instantiation chgVal(Instantiation self, str var, str newval) -> Instantiation
Assign newval to v (or to the variable at position varPos) in the Instantiation.
Parameters: - v (pyAgrum.DiscreteVariable or string) – The variable whose value is assigned (or its name)
- varPos (int) – The index of the variable whose value is assigned in the tuple of variables of the Instantiation
- newval (int or string) – The index of the value assigned (or its name)
Returns: The modified instantiation
Return type: Raises: NotFound
– If variable v does not belong to the instantiation.OutOfBound
– If newval is not a possible value for the variable.
-
clear
(Instantiation self)¶ Erase all variables from an Instantiation.
-
contains
(Instantiation self, DiscreteVariable v)¶ contains(Instantiation self, DiscreteVariable v) -> bool
Indicates whether a given variable belongs to the Instantiation.
Parameters: v (pyAgrum.DiscreteVariable) – The variable for which the test is made. Returns: True if the variable is in the Instantiation. Return type: bool
-
dec
(Instantiation self)¶ Operator –.
-
decIn
(Instantiation self, Instantiation i)¶ Operator – for the variables in i.
Parameters: i (pyAgrum.Instantiation) – The set of variables to decrement in this Instantiation
-
decNotVar
(Instantiation self, DiscreteVariable v)¶ Operator – for vars which are not v.
Parameters: v (pyAgrum.DiscreteVariable) – The variable not to decrement in this Instantiation.
-
decOut
(Instantiation self, Instantiation i)¶ Operator – for the variables not in i.
Parameters: i (pyAgrum.Instantiation) – The set of variables to not decrement in this Instantiation.
-
decVar
(Instantiation self, DiscreteVariable v)¶ Operator – for variable v only.
Parameters: v (pyAgrum.DiscreteVariable) – The variable to decrement in this Instantiation. Raises: NotFound
– If variable v does not belong to the Instantiation.
-
domainSize
(Instantiation self)¶ Returns: The product of the variable’s domain size in the Instantiation. Return type: int
-
empty
(Instantiation self)¶ Returns: True if the instantiation is empty. Return type: bool
-
end
(Instantiation self)¶ Returns: True if the Instantiation reached the end. Return type: bool
-
erase
(Instantiation self, DiscreteVariable v)¶ Parameters: v (pyAgrum.DiscreteVariable) – The variable to be removed from this Instantiation. Raises: NotFound
– If v does not belong to this Instantiation.
-
fromdict
(Instantiation self, PyObject * dict)¶ Change the values in an instantiation from a dict (variable_name:value) where value can be a position (int) or a label (string).
If a variable_name does not occur in the instantiation, nothing is done.
Warning
OutOfBounds raised if a value cannot be found.
-
hamming
(Instantiation self)¶ Returns: the hamming distance of this instantiation. Return type: int
-
inOverflow
(Instantiation self)¶ Returns: True if the current value of the tuple is correct Return type: bool
-
inc
(Instantiation self)¶ Operator ++.
-
incIn
(Instantiation self, Instantiation i)¶ Operator ++ for the variables in i.
Parameters: i (pyAgrum.Instantiation) – The set of variables to increment in this Instantiation.
-
incNotVar
(Instantiation self, DiscreteVariable v)¶ Operator ++ for vars which are not v.
Parameters: v (pyAgrum.DiscreteVariable) – The variable not to increment in this Instantiation.
-
incOut
(Instantiation self, Instantiation i)¶ Operator ++ for the variables not in i.
Parameters: i (Instantiation) – The set of variable to not increment in this Instantiation.
-
incVar
(Instantiation self, DiscreteVariable v)¶ Operator ++ for variable v only.
Parameters: v (pyAgrum.DiscreteVariable) – The variable to increment in this Instantiation. Raises: NotFound
– If variable v does not belong to the Instantiation.
-
nbrDim
(Instantiation self)¶ Returns: The number of variables in the Instantiation. Return type: int
-
pos
(Instantiation self, DiscreteVariable v)¶ Returns: the position of the variable v. Return type: int Parameters: v (pyAgrum.DiscreteVariable) – the variable for which its position is return. Raises: NotFound
– If v does not belong to the instantiation.
-
rend
(Instantiation self)¶ Returns: True if the Instantiation reached the rend. Return type: bool
-
reorder
(Instantiation self, pyAgrum.Sequence< pyAgrum.DiscreteVariable * > v)¶ reorder(Instantiation self, Instantiation i)
Reorder vars of this instantiation giving the order in v (or i).
Parameters: - i (pyAgrum.Instantiation) – The sequence of variables with which to reorder this Instantiation.
- v (list) – The new order of variables for this Instantiation.
-
setFirst
(Instantiation self)¶ Assign the first values to the tuple of the Instantiation.
-
setFirstIn
(Instantiation self, Instantiation i)¶ Assign the first values in the Instantiation for the variables in i.
Parameters: i (pyAgrum.Instantiation) – The variables to which their first value is assigned in this Instantiation.
-
setFirstNotVar
(Instantiation self, DiscreteVariable v)¶ Assign the first values to variables different of v.
Parameters: v (pyAgrum.DiscreteVariable) – The variable that will not be set to its first value in this Instantiation.
-
setFirstOut
(Instantiation self, Instantiation i)¶ Assign the first values in the Instantiation for the variables not in i.
Parameters: i (pyAgrum.Instantiation) – The variable that will not be set to their first value in this Instantiation.
-
setFirstVar
(Instantiation self, DiscreteVariable v)¶ Assign the first value in the Instantiation for var v.
Parameters: v (pyAgrum.DiscreteVariable) – The variable that will be set to its first value in this Instantiation.
-
setLast
(Instantiation self)¶ Assign the last values in the Instantiation.
-
setLastIn
(Instantiation self, Instantiation i)¶ Assign the last values in the Instantiation for the variables in i.
Parameters: i (pyAgrum.Instantiation) – The variables to which their last value is assigned in this Instantiation.
-
setLastNotVar
(Instantiation self, DiscreteVariable v)¶ Assign the last values to variables different of v.
Parameters: v (pyAgrum.DiscreteVariable) – The variable that will not be set to its last value in this Instantiation.
-
setLastOut
(Instantiation self, Instantiation i)¶ Assign the last values in the Instantiation for the variables not in i.
Parameters: i (pyAgrum.Instantiation) – The variables that will not be set to their last value in this Instantiation.
-
setLastVar
(Instantiation self, DiscreteVariable v)¶ Assign the last value in the Instantiation for var v.
Parameters: v (pyAgrum.DiscreteVariable) – The variable that will be set to its last value in this Instantiation.
-
setVals
(Instantiation self, Instantiation i)¶ Assign the values from i in the Instantiation.
Parameters: i (pyAgrum.Instantiation) – An Instantiation in which the new values are searched Returns: a reference to the instantiation Return type: pyAgrum.Instantiation
-
thisown
¶ The membership flag
-
todict
(Instantiation self, bool withLabels=False)¶ Create a dict (variable_name:value) from an instantiation
Parameters: withLabels (boolean) – The value will be a label (string) if True. It will be a position (int) if False. Returns: The dictionary Return type: Dict
-
unsetEnd
(Instantiation self)¶ Alias for unsetOverflow().
-
unsetOverflow
(Instantiation self)¶ Removes the flag overflow.
-
val
(Instantiation self, int i)¶ val(Instantiation self, DiscreteVariable var) -> int
Parameters: - i (int) – The index of the variable.
- var (pyAgrum.DiscreteVariable) – The variable the value of which we wish to know
Returns: the current value of the variable.
Return type: int
Raises: NotFound
– If the element cannot be found.
-
variable
(Instantiation self, int i)¶ variable(Instantiation self, str name) -> DiscreteVariable
Parameters: i (int) – The index of the variable Returns: the variable at position i in the tuple. Return type: pyAgrum.DiscreteVariable Raises: NotFound
– If the element cannot be found.
-
variablesSequence
(Instantiation self)¶ Returns: the sequence of DiscreteVariable of this instantiation. Return type: List
Potential¶
-
class
pyAgrum.
Potential
(*args)¶ Class representing a potential.
Available ructors:
Potential() -> Potential
Potential(src) -> Potential
Parameters: src (pyAgrum.Potential) – The Potential to copy Returns: The new Potential Return type: pyAgrum.Potential -
KL
(Potential self, Potential p)¶ Check the compatibility and compute the Kullback-Leibler divergence between the potential and.
Parameters: p (pyAgrum.Potential) – the potential from which we want to calculate the divergence.
Returns: The value of the divergence
Return type: float
Raises: gum.InvalidArgument
– If p is not compatible with the potential (dimension, variables)gum.FatalError
– If a zero is found in p or the potential and not in the other.
-
abs
(Potential self)¶ Apply abs on every element of the container
Returns: a reference to the modified potential. Return type: pyAgrum.Potential
-
add
(Potential self, DiscreteVariable v)¶ Add a discrete variable to the potential.
Parameters: v (pyAgrum.DiscreteVariable) – the var to be added
Raises: DuplicateElement
– If the variable is already in this Potential.InvalidArgument
– If the variable is empty.
-
argmax
(Potential self)¶
-
argmin
(Potential self)¶
-
contains
(Potential self, DiscreteVariable v)¶ Parameters: v (pyAgrum.Potential) – a DiscreteVariable. Returns: True if the var is in the potential Return type: bool
-
draw
(Potential self)¶ draw a value using the potential as a probability table.
Returns: the index of the drawn value Return type: int
-
empty
(Potential self)¶ Returns: Returns true if no variable is in the potential. Return type: bool
-
entropy
(Potential self)¶ Returns: the entropy of the potential Return type: double
-
extract
(Potential self, Instantiation inst)¶ extract(Potential self, PyObject * dict) -> Potential
create a new Potential extracted from self given a partial instantiation.
Parameters: - inst (pyAgrum.instantiation) – a partial instantiation
- dict (dict) – a dictionnary containing discrete variables (?)
Returns: the new Potential
Return type:
-
fill
(v)¶ Deprecated method in pyAgrum>0.12.0. See fillWith instead.
-
fillWith
(Potential self, Potential src)¶ fillWith(Potential self, Potential src, Vector_string mapSrc) -> Potential fillWith(Potential self, Vector v) -> Potential fillWith(Potential self, double v) -> Potential
Automatically fills the potential with v.
Parameters: v (number or list or pyAgrum.Potential the number of parameters of the Potential) – a value or a list/pyAgrum.Potential containing the values to fill the Potential with. Warning
if v is a list, the size of the list must be the if v is a pyAgrum.Potential. It must to contain variables with exactly the same names and labels but not necessarily the same variables.
Returns: a reference to the modified potentia Return type: pyAgrum.Potential Raises: gum.SizeError
– If v size’s does not matches the domain size.
-
findAll
(Potential self, double v)¶
-
get
(Potential self, Instantiation i)¶ Parameters: i (pyAgrum.Instantiation) – an Instantiation Returns: the value in the Potential at the position given by the instantiation Return type: double
-
isNonZeroMap
(Potential self)¶ Returns: a boolean-like potential using the predicate isNonZero Return type: pyAgrum.Potential
-
margMaxIn
(Potential self, PyObject * varnames)¶ Projection using max as operation.
Parameters: varnames (set) – the set of vars to keep Returns: the projected Potential Return type: pyAgrum.Potential
-
margMaxOut
(Potential self, PyObject * varnames)¶ Projection using max as operation.
Parameters: varnames (set) – the set of vars to eliminate Returns: the projected Potential Return type: pyAgrum.Potential Raises: gum.InvalidArgument
– If varnames contains only one variable that does not exist in the Potential
-
margMinIn
(Potential self, PyObject * varnames)¶ Projection using min as operation.
Parameters: varnames (set) – the set of vars to keep Returns: the projected Potential Return type: pyAgrum.Potential
-
margMinOut
(Potential self, PyObject * varnames)¶ Projection using min as operation.
Parameters: varnames (set) – the set of vars to eliminate Returns: the projected Potential Return type: pyAgrum.Potential Warning
InvalidArgument raised if varnames contains only one variable that does not exist in the Potential
-
margProdIn
(Potential self, PyObject * varnames)¶ Projection using multiplication as operation.
Parameters: varnames (set) – the set of vars to keep Returns: the projected Potential Return type: pyAgrum.Potential
-
margProdOut
(Potential self, PyObject * varnames)¶ Projection using multiplication as operation.
Parameters: varnames (set) – the set of vars to eliminate Returns: the projected Potential Return type: pyAgrum.Potential Raises: gum.InvalidArgument
– If varnames contains only one variable that does not exist in the Potential
-
margSumIn
(Potential self, PyObject * varnames)¶ Projection using sum as operation.
Parameters: varnames (set) – the set of vars to keep Returns: the projected Potential Return type: pyAgrum.Potential
-
margSumOut
(Potential self, PyObject * varnames)¶ Projection using sum as operation.
Parameters: varnames (set) – the set of vars to eliminate Returns: the projected Potential Return type: pyAgrum.Potential Raises: gum.InvalidArgument
– If varnames contains only one variable that does not exist in the Potential
-
max
(Potential self)¶ Returns: the maximum of all elements in the Potential Return type: double
-
maxNonOne
(Potential self)¶ Returns: the maximum of non one elements in the Potential Return type: double Raises: gum.NotFound
– If all value == 1.0
-
min
(Potential self)¶ Returns: the min of all elements in the Potential Return type: double
-
minNonZero
(Potential self)¶ Returns: the min of non zero elements in the Potential Return type: double Raises: gum.NotFound
– If all value == 0.0
-
nbrDim
(Potential self)¶ Returns: the number of vars in the multidimensional container. Return type: int
-
newFactory
(Potential self)¶ Erase the Potential content and create a new empty one.
Returns: a reference to the new Potential Return type: pyAgrum.Potential
-
normalize
(Potential self)¶ Normalize the Potential (do nothing if sum is 0)
Returns: a reference to the normalized Potential Return type: pyAgrum.Potential
-
normalizeAsCPT
(Potential self)¶ Normalize the Potential as a CPT
Returns: a reference to the normalized Potential Return type: pyAgrum.Potential Raises: gum.FatalError
– If some distribution sums to 0
-
pos
(Potential self, DiscreteVariable v)¶ Parameters: v (pyAgrum.DiscreteVariable) – The variable for which the index is returned. Returns: Return type: Returns the index of a variable. Raises: gum.NotFound
– If v is not in this multidimensional matrix.
-
product
(Potential self)¶ Returns: the product of all elements in the Potential Return type: double
-
putFirst
(Potential self, PyObject * varname)¶ Parameters: v (pyAgrum.DiscreteVariable) – The variable for which the index should be 0. Returns: a reference to the modified potential Return type: pyAgrum.Potential Raises: gum.InvalidArgument
– If the var is not in the potential
-
remove
(Potential self, DiscreteVariable var)¶ Parameters: v (pyAgrum.DiscreteVariable) – The variable to be removed Returns: a reference to the modified potential Return type: pyAgrum.Potential Warning
IndexError raised if the var is not in the potential
-
reorganize
(Potential self, vector< pyAgrum.DiscreteVariable *, allocator< pyAgrum.DiscreteVariable * > > vars)¶ reorganize(Potential self, PyObject * varnames) -> Potential
Create a new Potential with another order.
Returns: varnames – a list of the var names in the new order Return type: list Returns: a reference to the modified potential Return type: pyAgrum.Potential
-
scale
(Potential self, double v)¶ Create a new potential multiplied by v.
Parameters: v (double) – a multiplier Returns: Return type: a reference to the modified potential
-
set
(Potential self, Instantiation i, double value)¶ Change the value pointed by i
Parameters: - i (pyAgrum.Instantiation) – The Instantiation to be changed
- value (double) – The new value of the Instantiation
-
sq
(Potential self)¶ Square all the values in the Potential
-
sum
(Potential self)¶ Returns: the sum of all elements in the Potential Return type: double
-
thisown
¶ The membership flag
-
toarray
()¶ Returns: the potential as an array Return type: array
-
tolist
()¶ Returns: the potential as a list Return type: list
-
translate
(Potential self, double v)¶ Create a new potential added with v.
Parameters: v (double) – The value to be added Returns: Return type: a reference to the modified potential
-
var_dims
¶ Returns: a list containing the dimensions of each variables in the potential Return type: list
-
var_names
¶ Returns: a list containing the name of each variables in the potential Return type: list Warning
Listed in reverse from the variable enumeration order
-
variable
(Potential self, int i)¶ variable(Potential self, str name) -> DiscreteVariable
Parameters: i (int) – An index of this multidimensional matrix. Returns: Return type: the varible at the ith index Raises: gum.NotFound
– If i does not reference a variable in this multidimensional matrix.
-
variablesSequence
()¶ Returns: a list containing the sequence of variables Return type: list
-
Bayesian Network¶
The Bayesian Network is the main object of pyAgrum. A Bayesian network is a probabilistic graphical model. It represents a joint distribution over a set of random variables. In pyAgrum, the variables are (for now) only discrete. A Bayesian network uses a directed acyclic graph (DAG) to represent conditional indepencies in the joint distribution. These conditional indepencies allow to factorize the joint distribution, thereby allowing to compactly represent very large ones. Moreover, inference algorithms can also use this graph to speed up the computations. Finally, the Bayesian networks can be learnt from data.
Model¶
-
class
pyAgrum.
BayesNet
(*args)¶ BayesNet represents a Bayesian Network.
- Available ructors:
BayesNet(name='') -> BayesNet
BayesNet(source) -> BayesNet
Parameters: - name (str) – the name of the Bayes Net (optional)
- source (pyAgrum.BayesNet) – the Bayesian network to copy
-
add
(BayesNet self, DiscreteVariable var)¶ add(BayesNet self, str name, unsigned int nbrmod) -> int add(BayesNet self, DiscreteVariable var, pyAgrum.MultiDimImplementation aContent) -> int add(BayesNet self, DiscreteVariable var, int id) -> int add(BayesNet self, DiscreteVariable var, pyAgrum.MultiDimImplementation aContent, int id) -> int
Add a variable to the pyAgrum.BayesNet.
Parameters: - variable (pyAgrum.DiscreteVariable) – the variable added
- name (str) – the variable name
- nbrmod (int) – the numbre of modalities for the new variable
- id (int) – the variable forced id in the pyAgrum.BayesNet
Returns: the id of the new node
Return type: int
Raises: gum.DuplicateLabel
– If variable.name() is already used in this pyAgrum.BayesNet.gum.NotAllowed
– If nbrmod<2gum.DuplicateElement
– If id is already used.
-
addAMPLITUDE
(BayesNet self, DiscreteVariable var)¶ Others aggregators
Parameters: variable (pyAgrum.DiscreteVariable) – the variable to be added Returns: the id of the added value Return type: int
-
addAND
(BayesNet self, DiscreteVariable var)¶ Add a variable, it’s associate node and an AND implementation.
The id of the new variable is automatically generated.
Parameters: variable (pyAgrum.DiscreteVariable) – The variable added by copy. Returns: the id of the added variable. Return type: int Raises: gum.SizeError
– If variable.domainSize()>2
-
addArc
(BayesNet self, int tail, int head)¶ addArc(BayesNet self, str tail, str head)
Add an arc in the BN, and update arc.head’s CPT.
Parameters: - head – a variable’s id (int)
- tail – a variable’s id (int)
- head – a variable’s name (str)
- tail – a variable’s name (str)
Raises: gum.InvalidEdge
– If arc.tail and/or arc.head are not in the BN.
-
addCOUNT
(BayesNet self, DiscreteVariable var, int value=1)¶ Others aggregators
Parameters: variable (pyAgrum.DiscreteVariable) – the variable to be added Returns: the id of the added value Return type: int
-
addEXISTS
(BayesNet self, DiscreteVariable var, int value=1)¶ Others aggregators
Parameters: variable (pyAgrum.DiscreteVariable) – the variable to be added Returns: the id of the added value Return type: int
-
addFORALL
(BayesNet self, DiscreteVariable var, int value=1)¶ Others aggregators
Parameters: variable (pyAgrum.DiscreteVariable) – the variable to be added Returns: the id of the added variable. Return type: int
-
addLogit
(BayesNet self, DiscreteVariable var, double external_weight, int id)¶ addLogit(BayesNet self, DiscreteVariable var, double external_weight) -> int
Add a variable, its associate node and a Logit implementation.
(The id of the new variable can be automatically generated.)
Parameters: - variable (pyAgrum.DiscreteVariable) – The variable added by copy
- externalWeight (double) – the added external weight
- id (int) – The proposed id for the variable.
Returns: the id of the added variable.
Return type: int
Raises: gum.DuplicateElement
– If id is already used
-
addMAX
(BayesNet self, DiscreteVariable var)¶ Others aggregators
Parameters: variable (pyAgrum.DiscreteVariable) – the variable to be added Returns: the id of the added value Return type: int
-
addMEDIAN
(BayesNet self, DiscreteVariable var)¶ Others aggregators
Parameters: variable (pyAgrum.DiscreteVariable) – the variable to be added Returns: the id of the added value Return type: int
-
addMIN
(BayesNet self, DiscreteVariable var)¶ Others aggregators
Parameters: variable (pyAgrum.DiscreteVariable) – the variable to be added Returns: the id of the added value Return type: int
-
addNoisyAND
(BayesNet self, DiscreteVariable var, double external_weight, int id)¶ addNoisyAND(BayesNet self, DiscreteVariable var, double external_weight) -> int
Add a variable, its associate node and a noisyAND implementation.
(The id of the new variable can be automatically generated.)
Parameters: - variable (pyAgrum.DiscreteVariable) – The variable added by copy
- externalWeight (double) – the added external weight
- id (int) – The proposed id for the variable.
Returns: the id of the added variable.
Return type: int
Raises: gum.DuplicateElement
– If id is already used
-
addNoisyOR
(BayesNet self, DiscreteVariable var, double external_weight)¶ addNoisyOR(BayesNet self, DiscreteVariable var, double external_weight, int id) -> int
Add a variable, it’s 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.
(The id of the new variable can be automatically generated.)
Parameters: - variable (pyAgrum.DiscreteVariable) – The variable added by copy
- externalWeight (double) – the added external weight
- id (int) – The proposed id for the variable.
Returns: the id of the added variable.
Return type: int
Raises: gum.DuplicateElement
– If id is already used
-
addNoisyORCompound
(BayesNet self, DiscreteVariable var, double external_weight)¶ addNoisyORCompound(BayesNet self, DiscreteVariable var, double external_weight, int id) -> int
Add a variable, it’s 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.
(The id of the new variable can be automatically generated.)
Parameters: - variable (pyAgrum.DiscreteVariable) – The variable added by copy
- externalWeight (double) – the added external weight
- id (int) – The proposed id for the variable.
Returns: the id of the added variable.
Return type: int
Raises: gum.DuplicateElement
– If id is already used
-
addNoisyORNet
(BayesNet self, DiscreteVariable var, double external_weight)¶ addNoisyORNet(BayesNet self, DiscreteVariable var, double external_weight, int id) -> int
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.
(The id of the new variable can be automatically generated.)
Parameters: - variable (pyAgrum.DiscreteVariable) – The variable added by copy
- externalWeight (double) – the added external weight
- id (int) – The proposed id for the variable.
Returns: the id of the added variable.
Return type: int
-
addOR
(BayesNet self, DiscreteVariable var)¶ Add a variable, it’s associate node and an OR implementation.
The id of the new variable is automatically generated.
Warning
If parents are not boolean, all value>1 is True
Parameters: variable (pyAgrum.DiscreteVariable) – The variable added by copy Returns: the id of the added variable. Return type: int Raises: gum.SizeError
– If variable.domainSize()>2
-
addStructureListener
(whenNodeAdded=None, whenNodeDeleted=None, whenArcAdded=None, whenArcDeleted=None)¶ Add the listeners in parameters to the list of existing ones.
Parameters: - whenNodeAdded (lambda expression) – a function for when a node is added
- whenNodeDeleted (lambda expression) – a function for when a node is removed
- whenArcAdded (lambda expression) – a function for when an arc is added
- whenArcDeleted (lambda expression) – a function for when an arc is removed
-
addWeightedArc
(BayesNet self, int tail, int head, double causalWeight)¶ addWeightedArc(BayesNet self, str tail, str head, double causalWeight)
Add an arc in the BN, and update arc.head’s CPT.
Parameters: - head – a variable’s id (int)
- tail – a variable’s id (int)
- head – a variable’s name (str)
- tail – a variable’s name (str)
- causalWeight (double) – the added causal weight
Raises: gum.InvalidArc
– If arc.tail and/or arc.head are not in the BN.gum.InvalidArc
– If variable in arc.head is not a NoisyOR variable.
-
arcs
(IBayesNet self)¶ Returns: The lisf of arcs in the IBayesNet Return type: list
-
beginTopologyTransformation
(BayesNet self)¶ 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.
-
changePotential
(BayesNet self, int id, Potential newPot)¶ changePotential(BayesNet self, str name, Potential newPot)
change the CPT associated to nodeId to newPot delete the old CPT associated to nodeId.
Parameters: - newPot (pyAgrum.Potential) – the new potential
- NodeId (int) – the id of the node
- name (str) – the name of the variable
Raises: gum.NotAllowed
– If newPot has not the same signature as __probaMap[NodeId]
-
changeVariableLabel
(BayesNet self, int id, str old_label, str new_label)¶ changeVariableLabel(BayesNet self, str name, str old_label, str new_label)
change the label of the variable associated to nodeId to the new value.
Parameters: - id (int) – the id of the node
- name (str) – the name of the variable
- old_label (str) – the new label
- new_label (str) – the new label
Raises: gum.NotFound
– if id/name is not a variable or if old_label does not exist.
-
changeVariableName
(BayesNet self, int id, str new_name)¶ changeVariableName(BayesNet self, str name, str new_name)
Changes a variable’s name in the pyAgrum.BayesNet.
This will change the pyAgrum.DiscreteVariable names in the pyAgrum.BayesNet.
Parameters: - new_name (str) – the new name of the variable
- NodeId (int) – the id of the node
- name (str) – the name of the variable
Raises: gum.DuplicateLabel
– If new_name is already used in this BayesNet.gum.NotFound
– If no variable matches id.
-
children
(IBayesNet self, int id)¶ Parameters: id (int) – the id of the parent Returns: the set of all the children Return type: Set
-
completeInstantiation
(DAGmodel self)¶ Get an instantiation over all the variables of the model.
Returns: the complete instantiation Return type: pyAgrum.instantiation
-
cpt
(BayesNet self, int varId)¶ cpt(BayesNet self, str name) -> Potential
Returns the CPT of a variable.
Parameters: - VarId (int) – A variable’s id in the pyAgrum.BayesNet.
- name (str) – A variable’s name in the pyAgrum.BayesNet.
Returns: The variable’s CPT.
Return type: Raises: gum.NotFound
– If no variable’s id matches varId.
-
dag
(BayesNet self)¶ Returns: a ant reference to the dag of this BayesNet. Return type: pyAgrum.DAG
-
dim
(IBayesNet self)¶ Returns the dimension (the number of free parameters) in this BayesNet.
Returns: the dimension of the BayesNet Return type: int
-
empty
(DAGmodel self)¶ Returns: True if the model is empty Return type: bool
-
endTopologyTransformation
(BayesNet self)¶ Terminates a sequence of insertions/deletions of arcs by adjusting all CPTs dimensions. End Multiple Change for all CPTs.
Returns: Return type: pyAgrum.BayesNet
-
erase
(BayesNet self, int varId)¶ erase(BayesNet self, str name) erase(BayesNet self, DiscreteVariable var)
Remove a variable from the pyAgrum.BayesNet.
Removes the corresponding variable from the pyAgrum.BayesNet and from all of it’s children pyAgrum.Potential.
If no variable matches the given id, then nothing is done.
Parameters: - id (int) – The variable’s id to remove.
- name (str) – The variable’s name to remove.
- var (pyAgrum.DiscreteVariable) – A reference on the variable to remove.
-
eraseArc
(BayesNet self, Arc arc)¶ eraseArc(BayesNet self, int tail, int head) eraseArc(BayesNet self, str tail, str head)
Removes an arc in the BN, and update head’s CTP.
If (tail, head) doesn’t exist, the nothing happens.
Parameters: - arc (pyAgrum.Arc) – The arc to be removed.
- head – a variable’s id (int)
- tail – a variable’s id (int)
- head – a variable’s name (str)
- tail – a variable’s name (str)
-
static
fastPrototype
(str dotlike, int domainSize=2)¶ Create a bn with a dotlike syntax : ‘a->b->c;b->d;’.
The domain size maybe specified using ‘a[10]’.
Note that if the dotlike string contains such a specification for an already defined variable, the first specification will be used.
Parameters: - dotlike (str) – the string containing the specification
- domainSize (int) – the default domain size for variables
Returns: the resulting bayesian network
Return type:
-
generateCPT
(BayesNet self, int node)¶ generateCPT(BayesNet self, str name)
Randomly generate CPT for a given node in a given structure.
Parameters: - node (int) – The variable’s id.
- name (str) – The variable’s name.
-
generateCPTs
(BayesNet self)¶ Randomly generates CPTs for a given structure.
-
hasSameStructure
(DAGmodel self, DAGmodel other)¶ Parameters: pyAgrum.DAGmodel – a direct acyclic model Returns: True if all the named node are the same and all the named arcs are the same Return type: bool
-
idFromName
(BayesNet self, str name)¶ Returns a variable’s id given its name in the graph.
Parameters: name (str) – The variable’s name from which the id is returned. Returns: The variable’s node id. Return type: int Raises: gum.NotFound
– If name does not match a variable in the graph
-
ids
()¶ Deprecated method in pyAgrum>0.12.0. See nodes instead.
-
jointProbability
(IBayesNet self, Instantiation i)¶ Parameters: i (pyAgrum.instantiation) – an instantiation of the variables Returns: a parameter of the joint probability for the BayesNet Return type: double Warning
a variable not present in the instantiation is assumed to be instantiated to 0
-
loadBIF
(BayesNet self, str name, PyObject * l=(PyObject *) 0)¶ Load a BIF file.
Parameters: - name (str) – the file’s name
- l (list) – list of functions to execute
Raises: gum.IOError
– If file not foundgum.FatalError
– If file is not valid
-
loadBIFXML
(BayesNet self, str name, PyObject * l=(PyObject *) 0)¶ Load a BIFXML file.
Parameters: - name (str) – the name’s file
- l (list) – list of functions to execute
Raises: gum.IOError
– If file not foundgum.FatalError
– If file is not valid
-
loadDSL
(BayesNet self, str name, PyObject * l=(PyObject *) 0)¶ Load a DSL file.
Parameters: - name (str) – the file’s name
- l (list) – list of functions to execute
Raises: gum.IOError
– If file not foundgum.FatalError
– If file is not valid
-
loadNET
(BayesNet self, str name, PyObject * l=(PyObject *) 0)¶ Load a NET file.
Parameters: - name (str) – the name’s file
- l (list) – list of functions to execute
Raises: gum.IOError
– If file not foundgum.FatalError
– If file is not valid
-
loadO3PRM
(BayesNet self, str name, str system="", str classpath="", PyObject * l=(PyObject *) 0)¶ Load an O3PRM file.
Warning
The O3PRM language is the only language allowing to manipulate not only DiscretizedVariable but also RangeVariable and LabelizedVariable.
Parameters: - name (str) – the file’s name
- system (str) – the system’s name
- classpath (str) – the classpath
- l (list) – list of functions to execute
Raises: gum.IOError
– If file not foundgum.FatalError
– If file is not valid
-
loadUAI
(BayesNet self, str name, PyObject * l=(PyObject *) 0)¶ Load an UAI file.
Parameters: - name (str) – the name’s file
- l (list) – list of functions to execute
Raises: gum.IOError
– If file not foundgum.FatalError
– If file is not valid
-
log10DomainSize
(BayesNet self)¶ Returns: The log10 domain size of the joint probability for the model. Return type: double
-
log2JointProbability
(IBayesNet self, Instantiation i)¶ Parameters: i (pyAgrum.instantiation) – an instantiation of the variables Returns: a parameter of the log joint probability for the BayesNet Return type: double Warning
a variable not present in the instantiation is assumed to be instantiated to 0
-
maxNonOneParam
(IBayesNet self)¶ Returns: The biggest value (not equal to 1) in the CPTs of the BayesNet Return type: double
-
maxParam
(IBayesNet self)¶ Returns: the biggest value in the CPTs of the BayesNet Return type: double
-
maxVarDomainSize
(IBayesNet self)¶ Returns: the biggest domain size among the variables of the BayesNet Return type: int
-
minNonZeroParam
(IBayesNet self)¶ Returns: the smallest value (not equal to 0) in the CPTs of the IBayesNet Return type: double
-
minParam
(IBayesNet self)¶ Returns: the smallest value in the CPTs of the IBayesNet Return type: double
-
minimalCondSet
(IBayesNet self, int target, Set soids)¶ minimalCondSet(IBayesNet self, Set targets, Set soids) -> Set minimalCondSet(IBayesNet self, int target, PyObject * list) -> PyObject minimalCondSet(IBayesNet self, PyObject * targets, PyObject * list) -> PyObject *
Returns, given one or many targets and a list of variables, the minimal set of those needed to calculate the target/targets.
Parameters: - target (int) – The id of the target
- targets (list) – The ids of the targets
- list (list) – The list of available variables
Returns: The minimal set of variables
Return type: Set
-
moralGraph
(DAGmodel self, bool clear=True)¶ Returns the moral graph of the BayesNet, formed by adding edges between all pairs of nodes that have a common child, and then making all edges in the graph undirected.
Returns: The moral graph Return type: pyAgrum.UndiGraph
-
names
(IBayesNet self)¶ Returns: The names of the graph variables Return type: list
-
nodeId
(BayesNet self, DiscreteVariable var)¶ Parameters: var (pyAgrum.DiscreteVariable) – a variable Returns: the id of the variable Return type: int Raises: gum.IndexError
– If the graph does not contain the variable
-
nodes
(BayesNet self)¶ Returns: the set of ids Return type: set
-
parents
(IBayesNet self, int id)¶ Parameters: id – The id of the child node Returns: the set of the parents ids. Return type: Set
-
reverseArc
(BayesNet self, int tail, int head)¶ reverseArc(BayesNet self, str tail, str head) reverseArc(BayesNet self, Arc arc)
Reverses an arc while preserving the same joint distribution.
Parameters: - tail – (int) the id of the tail variable
- head – (int) the id of the head variable
- tail – (str) the name of the tail variable
- head – (str) the name of the head variable
- arc (pyAgrum.Arc) – an arc
Raises: gum.InvalidArc
– If the arc does not exsit or if its reversal would induce a directed cycle.
-
saveBIF
(BayesNet self, str name)¶ Save the BayesNet in a BIF file.
Parameters: name (str) – the file’s name
-
saveBIFXML
(BayesNet self, str name)¶ Save the BayesNet in a BIFXML file.
Parameters: name (str) – the file’s name
-
saveDSL
(BayesNet self, str name)¶ Save the BayesNet in a DSL file.
Parameters: name (str) – the file’s name
-
saveNET
(BayesNet self, str name)¶ Save the BayesNet in a NET file.
Parameters: name (str) – the file’s name
-
saveO3PRM
(BayesNet self, str name)¶ Save the BayesNet in an O3PRM file.
Warning
The O3PRM language is the only language allowing to manipulate not only DiscretizedVariable but also RangeVariable and LabelizedVariable.
Parameters: name (str) – the file’s name
-
saveUAI
(BayesNet self, str name)¶ Save the BayesNet in an UAI file.
Parameters: name (str) – the file’s name
-
size
(BayesNet self)¶ Returns: the number of nodes in the graph Return type: int
-
sizeArcs
(DAGmodel self)¶ Returns: the number of arcs in the graph Return type: int
-
thisown
¶ The membership flag
-
toDot
(IBayesNet self)¶ Returns: a friendly display of the graph in DOT format Return type: str
-
topologicalOrder
(DAGmodel self, bool clear=True)¶ Returns: the list of the nodes Ids in a topological order Return type: List Raises: gum.InvalidDirectedCycle
– If this graph contains cycles
-
variable
(BayesNet self, int id)¶ variable(BayesNet self, str name) -> DiscreteVariable
Parameters: - id (int) – a variable’s id
- name (str) – a variable’s name
Returns: the variable
Return type: Raises: gum.IndexError
– If the graph does not contain the variable
-
variableFromName
(BayesNet self, str name)¶ Parameters: name (str) – a variable’s name Returns: the variable Return type: pyAgrum.DiscreteVariable Raises: gum.IndexError
– If the graph does not contain the variable
-
variableNodeMap
(BayesNet self)¶ Returns: the variable node map Return type: pyAgrum.variableNodeMap
Exact Inference¶
Lazy Propagation¶
-
class
pyAgrum.
LazyPropagation
(*args)¶ Class used for Lazy Propagation
- Available ructors:
LazyPropagation(bn) -> LazyPropagation
Parameters: bn (pyAgrum.BayesNet) – a Bayesian network -
BN
(LazyPropagation self)¶ Returns: A ant reference over the IBayesNet referenced by this class. Return type: pyAgrum.IBayesNet Raises: gum.UndefinedElement
– If no Bayes net has been assigned to the inference.
-
H
(LazyPropagation self, int X)¶ H(LazyPropagation self, str nodeName) -> double
Parameters: - X (int) – a node Id
- nodeName (str) – a node name
Returns: the computed Shanon’s entropy of a node given the observation
Return type: double
-
I
(LazyPropagation self, int X, int Y)¶ Parameters: - X (int) – a node Id
- Y (int) – another node Id
Returns: the computed Shanon’s entropy of a node given the observation
Return type: double
-
VI
(LazyPropagation self, int X, int Y)¶ Parameters: - X (int) – a node Id
- Y (int) – another node Id
Returns: variation of information between X and Y
Return type: double
-
addAllTargets
(LazyPropagation self)¶ Add all the nodes as targets.
-
addEvidence
(LazyPropagation self, int id, int val)¶ addEvidence(LazyPropagation self, str nodeName, int val) addEvidence(LazyPropagation self, int id, str val) addEvidence(LazyPropagation self, str nodeName, str val) addEvidence(LazyPropagation self, int id, Vector vals) addEvidence(LazyPropagation self, str nodeName, Vector vals)
Adds a new evidence on a node (might be soft or hard).
Parameters: - id (int) – a node Id
- nodeName (int) – a node name
- val – (int) a node value
- val – (str) the label of the node value
- vals (list) – a list of values
Raises: gum.InvalidArgument
– If the node already has an evidencegum.InvalidArgument
– If val is not a value for the nodegum.InvalidArgument
– If the size of vals is different from the domain side of the nodegum.FatalError
– If vals is a vector of 0sgum.UndefinedElement
– If the node does not belong to the Bayesian network
-
addJointTarget
(LazyPropagation self, PyObject * list)¶ Add a list of nodes as a new joint target. As a collateral effect, every node is added as a marginal target.
Parameters: list – a list of names of nodes Raises: gum.UndefinedElement
– If some node(s) do not belong to the Bayesian network
-
addTarget
(LazyPropagation self, int target)¶ addTarget(LazyPropagation self, str nodeName)
Add a marginal target to the list of targets.
Parameters: - target (int) – a node Id
- nodeName (str) – a node name
Raises: gum.UndefinedElement
– If target is not a NodeId in the Bayes net
-
chgEvidence
(LazyPropagation self, int id, int val)¶ chgEvidence(LazyPropagation self, str nodeName, int val) chgEvidence(LazyPropagation self, int id, str val) chgEvidence(LazyPropagation self, str nodeName, str val) chgEvidence(LazyPropagation self, int id, Vector vals) chgEvidence(LazyPropagation self, str nodeName, Vector vals)
Change the value of an already existing evidence on a node (might be soft or hard).
Parameters: - id (int) – a node Id
- nodeName (int) – a node name
- val – (int) a node value
- val – (str) the label of the node value
- vals (list) – a list of values
Raises: gum.InvalidArgument
– If the node does not already have an evidencegum.InvalidArgument
– If val is not a value for the nodegum.InvalidArgument
– If the size of vals is different from the domain side of the nodegum.FatalError
– If vals is a vector of 0sgum.UndefinedElement
– If the node does not belong to the Bayesian network
-
eraseAllEvidence
(LazyPropagation self)¶ Removes all the evidence entered into the network.
-
eraseAllJointTargets
(LazyPropagation self)¶ Clear all previously defined joint targets.
-
eraseAllMarginalTargets
(LazyPropagation self)¶ Clear all the previously defined marginal targets.
-
eraseAllTargets
(LazyPropagation self)¶ Clear all previously defined targets (marginal and joint targets).
As a result, no posterior can be computed (since we can only compute the posteriors of the marginal or joint targets that have been added by the user).
-
eraseEvidence
(LazyPropagation self, int id)¶ eraseEvidence(LazyPropagation self, str nodeName)
Remove the evidence, if any, corresponding to the node Id or name.
Parameters: - id (int) – a node Id
- nodeName (int) – a node name
Raises: gum.IndexError
– If the node does not belong to the Bayesian network
-
eraseJointTarget
(LazyPropagation self, PyObject * list)¶ Remove, if existing, the joint target.
Parameters: list – a list of names or Ids of nodes
Raises: gum.IndexError
– If one of the node does not belong to the Bayesian networkgum.UndefinedElement
– If node Id is not in the Bayesian network
-
eraseTarget
(LazyPropagation self, int target)¶ eraseTarget(LazyPropagation self, str nodeName)
Remove, if existing, the marginal target.
Parameters: - target (int) – a node Id
- nodeName (int) – a node name
Raises: gum.IndexError
– If one of the node does not belong to the Bayesian networkgum.UndefinedElement
– If node Id is not in the Bayesian network
-
evidenceImpact
(LazyPropagation self, int target, PyObject * evs)¶ evidenceImpact(LazyPropagation self, str target, Vector_string evs) -> Potential
Create a pyAgrum.Potential for P(target|evs) (for all instanciation of target and evs)
Parameters: - target (set) – a set of targets ids or names.
- evs (set) – a set of nodes ids or names.
Warning
if some evs are d-separated, they are not included in the Potential.
Returns: a Potential for P(targets|evs) Return type: pyAgrum.Potential
-
evidenceJointImpact
(LazyPropagation self, PyObject * targets, PyObject * evs)¶ evidenceJointImpact(LazyPropagation self, Vector_string targets, Vector_string evs) -> Potential
Create a pyAgrum.Potential for P(joint targets|evs) (for all instanciation of targets and evs)
Parameters: - targets – (int) a node Id
- targets – (str) a node name
- evs (set) – a set of nodes ids or names.
Returns: a Potential for P(target|evs)
Return type: Raises: gum.Exception
– If some evidene entered into the Bayes net are incompatible (their joint proba = 0)
-
evidenceProbability
(LazyPropagation self)¶ Returns: the probability of evidence Return type: double
-
hardEvidenceNodes
(LazyPropagation self)¶ Returns: the set of nodes with hard evidence Return type: set
-
hasEvidence
(LazyPropagation self, int id)¶ hasEvidence(LazyPropagation self, str nodeName) -> bool
Parameters: - id (int) – a node Id
- nodeName (str) – a node name
Returns: True if some node(s) (or the one in parameters) have received evidence
Return type: bool
Raises: gum.IndexError
– If the node does not belong to the Bayesian network
-
hasHardEvidence
(LazyPropagation self, str nodeName)¶ Parameters: - id (int) – a node Id
- nodeName (str) – a node name
Returns: True if node has received a hard evidence
Return type: bool
Raises: gum.IndexError
– If the node does not belong to the Bayesian network
-
hasSoftEvidence
(LazyPropagation self, int id)¶ hasSoftEvidence(LazyPropagation self, str nodeName) -> bool
Parameters: - id (int) – a node Id
- nodeName (str) – a node name
Returns: True if node has received a soft evidence
Return type: bool
Raises: gum.IndexError
– If the node does not belong to the Bayesian network
-
isJointTarget
(LazyPropagation self, PyObject * list)¶ Parameters: list – a list of nodes ids or names.
Returns: True if target is a joint target.
Return type: bool
Raises: gum.IndexError
– If the node does not belong to the Bayesian networkgum.UndefinedElement
– If node Id is not in the Bayesian network
-
isTarget
(LazyPropagation self, int variable)¶ isTarget(LazyPropagation self, str nodeName) -> bool
Parameters: - variable (int) – a node Id
- nodeName (str) – a node name
Returns: True if variable is a (marginal) target
Return type: bool
Raises: gum.IndexError
– If the node does not belong to the Bayesian networkgum.UndefinedElement
– If node Id is not in the Bayesian network
-
joinTree
(LazyPropagation self)¶ Returns: the current join tree used Return type: pyAgrum.CliqueGraph
-
jointMutualInformation
(LazyPropagation self, PyObject * targets)¶
-
jointPosterior
(LazyPropagation self, PyObject * list)¶ Compute the joint posterior of a set of nodes.
Parameters: list – the list of nodes whose posterior joint probability is wanted Warning
The order of the variables given by the list here or when the jointTarget is declared can not be assumed to be used bu the Potential.
Returns: a ref to the posterior joint probability of the set of nodes. Return type: pyAgrum.Potential Raises: gum.UndefinedElement
– If an element of nodes is not in targets
-
jointTargets
(LazyPropagation self)¶ Returns: the list of target sets Return type: list
-
junctionTree
(LazyPropagation self)¶ Returns: the current junction tree Return type: pyAgrum.CliqueGraph
-
makeInference
(LazyPropagation self)¶ Perform the heavy computations needed to compute the targets’ posteriors
In a Junction tree propagation scheme, for instance, the heavy computations are those of the messages sent in the JT. This is precisely what makeInference should compute. Later, the computations of the posteriors can be done ‘lightly’ by multiplying and projecting those messages.
-
nbrEvidence
(LazyPropagation self)¶ Returns: the number of evidence entered into the Bayesian network Return type: int
-
nbrHardEvidence
(LazyPropagation self)¶ Returns: the number of hard evidence entered into the Bayesian network Return type: int
-
nbrJointTargets
(LazyPropagation self)¶ Returns: the number of joint targets Return type: int
-
nbrSoftEvidence
(LazyPropagation self)¶ Returns: the number of soft evidence entered into the Bayesian network Return type: int
-
nbrTargets
(LazyPropagation self)¶ Returns: the number of marginal targets Return type: int
-
posterior
(LazyPropagation self, int var)¶ posterior(LazyPropagation self, str nodeName) -> Potential
Computes and returns the posterior of a node.
Parameters: - var (int) – the node Id of the node for which we need a posterior probability
- nodeName (str) – the node name of the node for which we need a posterior probability
Returns: a ref to the posterior probability of the node
Return type: Raises: gum.UndefinedElement
– If an element of nodes is not in targets
-
setEvidence
(evidces)¶ Erase all the evidences and apply addEvidence(key,value) for every pairs in evidces.
Parameters: evidces (dict) – a dict of evidences
Raises: gum.InvalidArgument
– If one value is not a value for the nodegum.InvalidArgument
– If the size of a value is different from the domain side of the nodegum.FatalError
– If one value is a vector of 0sgum.UndefinedElement
– If one node does not belong to the Bayesian network
-
setTargets
(targets)¶ Remove all the targets and add the ones in parameter.
Parameters: targets (set) – a set of targets Raises: gum.UndefinedElement
– If one target is not in the Bayes net
-
softEvidenceNodes
(LazyPropagation self)¶ Returns: the set of nodes with soft evidence Return type: set
-
targets
(LazyPropagation self)¶ Returns: the list of marginal targets Return type: list
-
thisown
¶ The membership flag
-
updateEvidence
(evidces)¶ Apply chgEvidence(key,value) for every pairs in evidces (or addEvidence).
Parameters: evidces (dict) – a dict of evidences
Raises: gum.InvalidArgument
– If one value is not a value for the nodegum.InvalidArgument
– If the size of a value is different from the domain side of the nodegum.FatalError
– If one value is a vector of 0sgum.UndefinedElement
– If one node does not belong to the Bayesian network
Shafer Shenoy Inference¶
-
class
pyAgrum.
ShaferShenoyInference
(*args)¶ Class used for Shafer-Shenoy inferences.
- Available ructors:
ShaferShenoyInference(bn) -> ShaferShenoyInference
Parameters: bn (pyAgrum.BayesNet) – a Bayesian network -
BN
(ShaferShenoyInference self)¶ Returns: A ant reference over the IBayesNet referenced by this class. Return type: pyAgrum.IBayesNet Raises: gum.UndefinedElement
– If no Bayes net has been assigned to the inference.
-
H
(ShaferShenoyInference self, int X)¶ H(ShaferShenoyInference self, str nodeName) -> double
Parameters: - X (int) – a node Id
- nodeName (str) – a node name
Returns: the computed Shanon’s entropy of a node given the observation
Return type: double
-
I
(ShaferShenoyInference self, int X, int Y)¶ Parameters: - X (int) – a node Id
- Y (int) – another node Id
Returns: the computed Shanon’s entropy of a node given the observation
Return type: double
-
VI
(ShaferShenoyInference self, int X, int Y)¶ Parameters: - X (int) – a node Id
- Y (int) – another node Id
Returns: variation of information between X and Y
Return type: double
-
addAllTargets
(ShaferShenoyInference self)¶ Add all the nodes as targets.
-
addEvidence
(ShaferShenoyInference self, int id, int val)¶ addEvidence(ShaferShenoyInference self, str nodeName, int val) addEvidence(ShaferShenoyInference self, int id, str val) addEvidence(ShaferShenoyInference self, str nodeName, str val) addEvidence(ShaferShenoyInference self, int id, Vector vals) addEvidence(ShaferShenoyInference self, str nodeName, Vector vals)
Adds a new evidence on a node (might be soft or hard).
Parameters: - id (int) – a node Id
- nodeName (int) – a node name
- val – (int) a node value
- val – (str) the label of the node value
- vals (list) – a list of values
Raises: gum.InvalidArgument
– If the node already has an evidencegum.InvalidArgument
– If val is not a value for the nodegum.InvalidArgument
– If the size of vals is different from the domain side of the nodegum.FatalError
– If vals is a vector of 0sgum.UndefinedElement
– If the node does not belong to the Bayesian network
-
addJointTarget
(ShaferShenoyInference self, PyObject * list)¶ Add a list of nodes as a new joint target. As a collateral effect, every node is added as a marginal target.
Parameters: list – a list of names of nodes Raises: gum.UndefinedElement
– If some node(s) do not belong to the Bayesian network
-
addTarget
(ShaferShenoyInference self, int target)¶ addTarget(ShaferShenoyInference self, str nodeName)
Add a marginal target to the list of targets.
Parameters: - target (int) – a node Id
- nodeName (str) – a node name
Raises: gum.UndefinedElement
– If target is not a NodeId in the Bayes net
-
chgEvidence
(ShaferShenoyInference self, int id, int val)¶ chgEvidence(ShaferShenoyInference self, str nodeName, int val) chgEvidence(ShaferShenoyInference self, int id, str val) chgEvidence(ShaferShenoyInference self, str nodeName, str val) chgEvidence(ShaferShenoyInference self, int id, Vector vals) chgEvidence(ShaferShenoyInference self, str nodeName, Vector vals)
Change the value of an already existing evidence on a node (might be soft or hard).
Parameters: - id (int) – a node Id
- nodeName (int) – a node name
- val – (int) a node value
- val – (str) the label of the node value
- vals (list) – a list of values
Raises: gum.InvalidArgument
– If the node does not already have an evidencegum.InvalidArgument
– If val is not a value for the nodegum.InvalidArgument
– If the size of vals is different from the domain side of the nodegum.FatalError
– If vals is a vector of 0sgum.UndefinedElement
– If the node does not belong to the Bayesian network
-
eraseAllEvidence
(ShaferShenoyInference self)¶ Removes all the evidence entered into the network.
-
eraseAllJointTargets
(ShaferShenoyInference self)¶ Clear all previously defined joint targets.
-
eraseAllMarginalTargets
(ShaferShenoyInference self)¶ Clear all the previously defined marginal targets.
-
eraseAllTargets
(ShaferShenoyInference self)¶ Clear all previously defined targets (marginal and joint targets).
As a result, no posterior can be computed (since we can only compute the posteriors of the marginal or joint targets that have been added by the user).
-
eraseEvidence
(ShaferShenoyInference self, int id)¶ eraseEvidence(ShaferShenoyInference self, str nodeName)
Remove the evidence, if any, corresponding to the node Id or name.
Parameters: - id (int) – a node Id
- nodeName (int) – a node name
Raises: gum.IndexError
– If the node does not belong to the Bayesian network
-
eraseJointTarget
(ShaferShenoyInference self, PyObject * list)¶ Remove, if existing, the joint target.
Parameters: list – a list of names or Ids of nodes
Raises: gum.IndexError
– If one of the node does not belong to the Bayesian networkgum.UndefinedElement
– If node Id is not in the Bayesian network
-
eraseTarget
(ShaferShenoyInference self, int target)¶ eraseTarget(ShaferShenoyInference self, str nodeName)
Remove, if existing, the marginal target.
Parameters: - target (int) – a node Id
- nodeName (int) – a node name
Raises: gum.IndexError
– If one of the node does not belong to the Bayesian networkgum.UndefinedElement
– If node Id is not in the Bayesian network
-
evidenceImpact
(ShaferShenoyInference self, int target, PyObject * evs)¶ evidenceImpact(ShaferShenoyInference self, str target, Vector_string evs) -> Potential
Create a pyAgrum.Potential for P(target|evs) (for all instanciation of target and evs)
Parameters: - target (set) – a set of targets ids or names.
- evs (set) – a set of nodes ids or names.
Warning
if some evs are d-separated, they are not included in the Potential.
Returns: a Potential for P(targets|evs) Return type: pyAgrum.Potential
-
evidenceJointImpact
(ShaferShenoyInference self, PyObject * targets, PyObject * evs)¶ evidenceJointImpact(ShaferShenoyInference self, Vector_string targets, Vector_string evs) -> Potential
Create a pyAgrum.Potential for P(joint targets|evs) (for all instanciation of targets and evs)
Parameters: - targets – (int) a node Id
- targets – (str) a node name
- evs (set) – a set of nodes ids or names.
Returns: a Potential for P(target|evs)
Return type: Raises: gum.Exception
– If some evidene entered into the Bayes net are incompatible (their joint proba = 0)
-
evidenceProbability
(ShaferShenoyInference self)¶ Returns: the probability of evidence Return type: double
-
hardEvidenceNodes
(ShaferShenoyInference self)¶ Returns: the set of nodes with hard evidence Return type: set
-
hasEvidence
(ShaferShenoyInference self, int id)¶ hasEvidence(ShaferShenoyInference self, str nodeName) -> bool
Parameters: - id (int) – a node Id
- nodeName (str) – a node name
Returns: True if some node(s) (or the one in parameters) have received evidence
Return type: bool
Raises: gum.IndexError
– If the node does not belong to the Bayesian network
-
hasHardEvidence
(ShaferShenoyInference self, str nodeName)¶ Parameters: - id (int) – a node Id
- nodeName (str) – a node name
Returns: True if node has received a hard evidence
Return type: bool
Raises: gum.IndexError
– If the node does not belong to the Bayesian network
-
hasSoftEvidence
(ShaferShenoyInference self, int id)¶ hasSoftEvidence(ShaferShenoyInference self, str nodeName) -> bool
Parameters: - id (int) – a node Id
- nodeName (str) – a node name
Returns: True if node has received a soft evidence
Return type: bool
Raises: gum.IndexError
– If the node does not belong to the Bayesian network
-
isJointTarget
(ShaferShenoyInference self, PyObject * list)¶ Parameters: list – a list of nodes ids or names.
Returns: True if target is a joint target.
Return type: bool
Raises: gum.IndexError
– If the node does not belong to the Bayesian networkgum.UndefinedElement
– If node Id is not in the Bayesian network
-
isTarget
(ShaferShenoyInference self, int variable)¶ isTarget(ShaferShenoyInference self, str nodeName) -> bool
Parameters: - variable (int) – a node Id
- nodeName (str) – a node name
Returns: True if variable is a (marginal) target
Return type: bool
Raises: gum.IndexError
– If the node does not belong to the Bayesian networkgum.UndefinedElement
– If node Id is not in the Bayesian network
-
joinTree
(ShaferShenoyInference self)¶ Returns: the current join tree used Return type: pyAgrum.CliqueGraph
-
jointMutualInformation
(ShaferShenoyInference self, PyObject * targets)¶
-
jointPosterior
(ShaferShenoyInference self, PyObject * list)¶ Compute the joint posterior of a set of nodes.
Parameters: list – the list of nodes whose posterior joint probability is wanted Warning
The order of the variables given by the list here or when the jointTarget is declared can not be assumed to be used bu the Potential.
Returns: a ref to the posterior joint probability of the set of nodes. Return type: pyAgrum.Potential Raises: gum.UndefinedElement
– If an element of nodes is not in targets
-
jointTargets
(ShaferShenoyInference self)¶ Returns: the list of target sets Return type: list
-
junctionTree
(ShaferShenoyInference self)¶ Returns: the current junction tree Return type: pyAgrum.CliqueGraph
-
makeInference
(ShaferShenoyInference self)¶ Perform the heavy computations needed to compute the targets’ posteriors
In a Junction tree propagation scheme, for instance, the heavy computations are those of the messages sent in the JT. This is precisely what makeInference should compute. Later, the computations of the posteriors can be done ‘lightly’ by multiplying and projecting those messages.
-
nbrEvidence
(ShaferShenoyInference self)¶ Returns: the number of evidence entered into the Bayesian network Return type: int
-
nbrHardEvidence
(ShaferShenoyInference self)¶ Returns: the number of hard evidence entered into the Bayesian network Return type: int
-
nbrJointTargets
(ShaferShenoyInference self)¶ Returns: the number of joint targets Return type: int
-
nbrSoftEvidence
(ShaferShenoyInference self)¶ Returns: the number of soft evidence entered into the Bayesian network Return type: int
-
nbrTargets
(ShaferShenoyInference self)¶ Returns: the number of marginal targets Return type: int
-
posterior
(ShaferShenoyInference self, int var)¶ posterior(ShaferShenoyInference self, str nodeName) -> Potential
Computes and returns the posterior of a node.
Parameters: - var (int) – the node Id of the node for which we need a posterior probability
- nodeName (str) – the node name of the node for which we need a posterior probability
Returns: a ref to the posterior probability of the node
Return type: Raises: gum.UndefinedElement
– If an element of nodes is not in targets
-
setEvidence
(evidces)¶ Erase all the evidences and apply addEvidence(key,value) for every pairs in evidces.
Parameters: evidces (dict) – a dict of evidences
Raises: gum.InvalidArgument
– If one value is not a value for the nodegum.InvalidArgument
– If the size of a value is different from the domain side of the nodegum.FatalError
– If one value is a vector of 0sgum.UndefinedElement
– If one node does not belong to the Bayesian network
-
setTargets
(targets)¶ Remove all the targets and add the ones in parameter.
Parameters: targets (set) – a set of targets Raises: gum.UndefinedElement
– If one target is not in the Bayes net
-
softEvidenceNodes
(ShaferShenoyInference self)¶ Returns: the set of nodes with soft evidence Return type: set
-
targets
(ShaferShenoyInference self)¶ Returns: the list of marginal targets Return type: list
-
thisown
¶ The membership flag
-
updateEvidence
(evidces)¶ Apply chgEvidence(key,value) for every pairs in evidces (or addEvidence).
Parameters: evidces (dict) – a dict of evidences
Raises: gum.InvalidArgument
– If one value is not a value for the nodegum.InvalidArgument
– If the size of a value is different from the domain side of the nodegum.FatalError
– If one value is a vector of 0sgum.UndefinedElement
– If one node does not belong to the Bayesian network
Variable Elimination¶
-
class
pyAgrum.
VariableElimination
(*args)¶ Class used for Variable Elimination inference algorithm.
- Available ructors:
VariableElimination(bn) -> VariableElimination
Parameters: bn (pyAgrum.BayesNet) – a Bayesian network -
BN
(VariableElimination self)¶ Returns: A ant reference over the IBayesNet referenced by this class. Return type: pyAgrum.IBayesNet Raises: gum.UndefinedElement
– If no Bayes net has been assigned to the inference.
-
H
(VariableElimination self, int X)¶ H(VariableElimination self, str nodeName) -> double
Parameters: - X (int) – a node Id
- nodeName (str) – a node name
Returns: the computed Shanon’s entropy of a node given the observation
Return type: double
-
addAllTargets
(VariableElimination self)¶ Add all the nodes as targets.
-
addEvidence
(VariableElimination self, int id, int val)¶ addEvidence(VariableElimination self, str nodeName, int val) addEvidence(VariableElimination self, int id, str val) addEvidence(VariableElimination self, str nodeName, str val) addEvidence(VariableElimination self, int id, Vector vals) addEvidence(VariableElimination self, str nodeName, Vector vals)
Adds a new evidence on a node (might be soft or hard).
Parameters: - id (int) – a node Id
- nodeName (int) – a node name
- val – (int) a node value
- val – (str) the label of the node value
- vals (list) – a list of values
Raises: gum.InvalidArgument
– If the node already has an evidencegum.InvalidArgument
– If val is not a value for the nodegum.InvalidArgument
– If the size of vals is different from the domain side of the nodegum.FatalError
– If vals is a vector of 0sgum.UndefinedElement
– If the node does not belong to the Bayesian network
-
addJointTarget
(VariableElimination self, PyObject * list)¶ Add a list of nodes as a new joint target. As a collateral effect, every node is added as a marginal target.
Parameters: list – a list of names of nodes Raises: gum.UndefinedElement
– If some node(s) do not belong to the Bayesian network
-
addTarget
(VariableElimination self, int target)¶ addTarget(VariableElimination self, str nodeName)
Add a marginal target to the list of targets.
Parameters: - target (int) – a node Id
- nodeName (str) – a node name
Raises: gum.UndefinedElement
– If target is not a NodeId in the Bayes net
-
chgEvidence
(VariableElimination self, int id, int val)¶ chgEvidence(VariableElimination self, str nodeName, int val) chgEvidence(VariableElimination self, int id, str val) chgEvidence(VariableElimination self, str nodeName, str val) chgEvidence(VariableElimination self, int id, Vector vals) chgEvidence(VariableElimination self, str nodeName, Vector vals)
Change the value of an already existing evidence on a node (might be soft or hard).
Parameters: - id (int) – a node Id
- nodeName (int) – a node name
- val – (int) a node value
- val – (str) the label of the node value
- vals (list) – a list of values
Raises: gum.InvalidArgument
– If the node does not already have an evidencegum.InvalidArgument
– If val is not a value for the nodegum.InvalidArgument
– If the size of vals is different from the domain side of the nodegum.FatalError
– If vals is a vector of 0sgum.UndefinedElement
– If the node does not belong to the Bayesian network
-
eraseAllEvidence
(VariableElimination self)¶ Removes all the evidence entered into the network.
-
eraseAllTargets
(VariableElimination self)¶ Clear all previously defined targets (marginal and joint targets).
As a result, no posterior can be computed (since we can only compute the posteriors of the marginal or joint targets that have been added by the user).
-
eraseEvidence
(VariableElimination self, int id)¶ eraseEvidence(VariableElimination self, str nodeName)
Remove the evidence, if any, corresponding to the node Id or name.
Parameters: - id (int) – a node Id
- nodeName (int) – a node name
Raises: gum.IndexError
– If the node does not belong to the Bayesian network
-
eraseJointTarget
(VariableElimination self, PyObject * list)¶ Remove, if existing, the joint target.
Parameters: list – a list of names or Ids of nodes
Raises: gum.IndexError
– If one of the node does not belong to the Bayesian networkgum.UndefinedElement
– If node Id is not in the Bayesian network
-
eraseTarget
(VariableElimination self, int target)¶ eraseTarget(VariableElimination self, str nodeName)
Remove, if existing, the marginal target.
Parameters: - target (int) – a node Id
- nodeName (int) – a node name
Raises: gum.IndexError
– If one of the node does not belong to the Bayesian networkgum.UndefinedElement
– If node Id is not in the Bayesian network
-
evidenceImpact
(VariableElimination self, int target, PyObject * evs)¶ evidenceImpact(VariableElimination self, str target, Vector_string evs) -> Potential
Create a pyAgrum.Potential for P(target|evs) (for all instanciation of target and evs)
Parameters: - target (set) – a set of targets ids or names.
- evs (set) – a set of nodes ids or names.
Warning
if some evs are d-separated, they are not included in the Potential.
Returns: a Potential for P(targets|evs) Return type: pyAgrum.Potential
-
evidenceJointImpact
(VariableElimination self, PyObject * targets, PyObject * evs)¶ Create a pyAgrum.Potential for P(joint targets|evs) (for all instanciation of targets and evs)
Parameters: - targets – (int) a node Id
- targets – (str) a node name
- evs (set) – a set of nodes ids or names.
Returns: a Potential for P(target|evs)
Return type: Raises: gum.Exception
– If some evidene entered into the Bayes net are incompatible (their joint proba = 0)
-
hardEvidenceNodes
(VariableElimination self)¶ Returns: the set of nodes with hard evidence Return type: set
-
hasEvidence
(VariableElimination self, int id)¶ hasEvidence(VariableElimination self, str nodeName) -> bool
Parameters: - id (int) – a node Id
- nodeName (str) – a node name
Returns: True if some node(s) (or the one in parameters) have received evidence
Return type: bool
Raises: gum.IndexError
– If the node does not belong to the Bayesian network
-
hasHardEvidence
(VariableElimination self, str nodeName)¶ Parameters: - id (int) – a node Id
- nodeName (str) – a node name
Returns: True if node has received a hard evidence
Return type: bool
Raises: gum.IndexError
– If the node does not belong to the Bayesian network
-
hasSoftEvidence
(VariableElimination self, int id)¶ hasSoftEvidence(VariableElimination self, str nodeName) -> bool
Parameters: - id (int) – a node Id
- nodeName (str) – a node name
Returns: True if node has received a soft evidence
Return type: bool
Raises: gum.IndexError
– If the node does not belong to the Bayesian network
-
isJointTarget
(VariableElimination self, PyObject * list)¶ Parameters: list – a list of nodes ids or names.
Returns: True if target is a joint target.
Return type: bool
Raises: gum.IndexError
– If the node does not belong to the Bayesian networkgum.UndefinedElement
– If node Id is not in the Bayesian network
-
isTarget
(VariableElimination self, int variable)¶ isTarget(VariableElimination self, str nodeName) -> bool
Parameters: - variable (int) – a node Id
- nodeName (str) – a node name
Returns: True if variable is a (marginal) target
Return type: bool
Raises: gum.IndexError
– If the node does not belong to the Bayesian networkgum.UndefinedElement
– If node Id is not in the Bayesian network
-
jointMutualInformation
(VariableElimination self, PyObject * targets)¶
-
jointPosterior
(VariableElimination self, PyObject * list)¶ Compute the joint posterior of a set of nodes.
Parameters: list – the list of nodes whose posterior joint probability is wanted Warning
The order of the variables given by the list here or when the jointTarget is declared can not be assumed to be used bu the Potential.
Returns: a ref to the posterior joint probability of the set of nodes. Return type: pyAgrum.Potential Raises: gum.UndefinedElement
– If an element of nodes is not in targets
-
jointTargets
(VariableElimination self)¶ Returns: the list of target sets Return type: list
-
junctionTree
(VariableElimination self, int id)¶ Returns: the current junction tree Return type: pyAgrum.CliqueGraph
-
makeInference
(VariableElimination self)¶ Perform the heavy computations needed to compute the targets’ posteriors
In a Junction tree propagation scheme, for instance, the heavy computations are those of the messages sent in the JT. This is precisely what makeInference should compute. Later, the computations of the posteriors can be done ‘lightly’ by multiplying and projecting those messages.
-
nbrEvidence
(VariableElimination self)¶ Returns: the number of evidence entered into the Bayesian network Return type: int
-
nbrHardEvidence
(VariableElimination self)¶ Returns: the number of hard evidence entered into the Bayesian network Return type: int
-
nbrSoftEvidence
(VariableElimination self)¶ Returns: the number of soft evidence entered into the Bayesian network Return type: int
-
nbrTargets
(VariableElimination self)¶ Returns: the number of marginal targets Return type: int
-
posterior
(VariableElimination self, int var)¶ posterior(VariableElimination self, str nodeName) -> Potential
Computes and returns the posterior of a node.
Parameters: - var (int) – the node Id of the node for which we need a posterior probability
- nodeName (str) – the node name of the node for which we need a posterior probability
Returns: a ref to the posterior probability of the node
Return type: Raises: gum.UndefinedElement
– If an element of nodes is not in targets
-
setEvidence
(evidces)¶ Erase all the evidences and apply addEvidence(key,value) for every pairs in evidces.
Parameters: evidces (dict) – a dict of evidences
Raises: gum.InvalidArgument
– If one value is not a value for the nodegum.InvalidArgument
– If the size of a value is different from the domain side of the nodegum.FatalError
– If one value is a vector of 0sgum.UndefinedElement
– If one node does not belong to the Bayesian network
-
setTargets
(targets)¶ Remove all the targets and add the ones in parameter.
Parameters: targets (set) – a set of targets Raises: gum.UndefinedElement
– If one target is not in the Bayes net
-
softEvidenceNodes
(VariableElimination self)¶ Returns: the set of nodes with soft evidence Return type: set
-
targets
(VariableElimination self)¶ Returns: the list of marginal targets Return type: list
-
thisown
¶ The membership flag
-
updateEvidence
(evidces)¶ Apply chgEvidence(key,value) for every pairs in evidces (or addEvidence).
Parameters: evidces (dict) – a dict of evidences
Raises: gum.InvalidArgument
– If one value is not a value for the nodegum.InvalidArgument
– If the size of a value is different from the domain side of the nodegum.FatalError
– If one value is a vector of 0sgum.UndefinedElement
– If one node does not belong to the Bayesian network
Approximate Inference¶
Loopy Belief Propagation¶
-
class
pyAgrum.
LoopyBeliefPropagation
(bn: pyAgrum.pyAgrum.IBayesNet)¶ Class used for inferences using loopy belief propagation algorithm.
- Available ructors:
LoopyBeliefPropagation(bn) -> LoopyBeliefPropagation
Parameters: bn (pyAgrum.BayesNet) – a Bayesian network -
BN
(LoopyBeliefPropagation self)¶ Returns: A ant reference over the IBayesNet referenced by this class. Return type: pyAgrum.IBayesNet Raises: gum.UndefinedElement
– If no Bayes net has been assigned to the inference.
-
H
(LoopyBeliefPropagation self, int X)¶ H(LoopyBeliefPropagation self, str nodeName) -> double
Parameters: - X (int) – a node Id
- nodeName (str) – a node name
Returns: the computed Shanon’s entropy of a node given the observation
Return type: double
-
addAllTargets
(LoopyBeliefPropagation self)¶ Add all the nodes as targets.
-
addEvidence
(LoopyBeliefPropagation self, int id, int val)¶ addEvidence(LoopyBeliefPropagation self, str nodeName, int val) addEvidence(LoopyBeliefPropagation self, int id, str val) addEvidence(LoopyBeliefPropagation self, str nodeName, str val) addEvidence(LoopyBeliefPropagation self, int id, Vector vals) addEvidence(LoopyBeliefPropagation self, str nodeName, Vector vals)
Adds a new evidence on a node (might be soft or hard).
Parameters: - id (int) – a node Id
- nodeName (int) – a node name
- val – (int) a node value
- val – (str) the label of the node value
- vals (list) – a list of values
Raises: gum.InvalidArgument
– If the node already has an evidencegum.InvalidArgument
– If val is not a value for the nodegum.InvalidArgument
– If the size of vals is different from the domain side of the nodegum.FatalError
– If vals is a vector of 0sgum.UndefinedElement
– If the node does not belong to the Bayesian network
-
addTarget
(LoopyBeliefPropagation self, int target)¶ addTarget(LoopyBeliefPropagation self, str nodeName)
Add a marginal target to the list of targets.
Parameters: - target (int) – a node Id
- nodeName (str) – a node name
Raises: gum.UndefinedElement
– If target is not a NodeId in the Bayes net
-
chgEvidence
(LoopyBeliefPropagation self, int id, int val)¶ chgEvidence(LoopyBeliefPropagation self, str nodeName, int val) chgEvidence(LoopyBeliefPropagation self, int id, str val) chgEvidence(LoopyBeliefPropagation self, str nodeName, str val) chgEvidence(LoopyBeliefPropagation self, int id, Vector vals) chgEvidence(LoopyBeliefPropagation self, str nodeName, Vector vals)
Change the value of an already existing evidence on a node (might be soft or hard).
Parameters: - id (int) – a node Id
- nodeName (int) – a node name
- val – (int) a node value
- val – (str) the label of the node value
- vals (list) – a list of values
Raises: gum.InvalidArgument
– If the node does not already have an evidencegum.InvalidArgument
– If val is not a value for the nodegum.InvalidArgument
– If the size of vals is different from the domain side of the nodegum.FatalError
– If vals is a vector of 0sgum.UndefinedElement
– If the node does not belong to the Bayesian network
-
currentTime
(LoopyBeliefPropagation self)¶ Returns: get the current running time in second (double) Return type: double
-
epsilon
(LoopyBeliefPropagation self)¶ Returns: the value of epsilon Return type: double
-
eraseAllEvidence
(LoopyBeliefPropagation self)¶ Removes all the evidence entered into the network.
-
eraseAllTargets
(LoopyBeliefPropagation self)¶ Clear all previously defined targets (marginal and joint targets).
As a result, no posterior can be computed (since we can only compute the posteriors of the marginal or joint targets that have been added by the user).
-
eraseEvidence
(LoopyBeliefPropagation self, int id)¶ eraseEvidence(LoopyBeliefPropagation self, str nodeName)
Remove the evidence, if any, corresponding to the node Id or name.
Parameters: - id (int) – a node Id
- nodeName (int) – a node name
Raises: gum.IndexError
– If the node does not belong to the Bayesian network
-
eraseTarget
(LoopyBeliefPropagation self, int target)¶ eraseTarget(LoopyBeliefPropagation self, str nodeName)
Remove, if existing, the marginal target.
Parameters: - target (int) – a node Id
- nodeName (int) – a node name
Raises: gum.IndexError
– If one of the node does not belong to the Bayesian networkgum.UndefinedElement
– If node Id is not in the Bayesian network
-
evidenceImpact
(LoopyBeliefPropagation self, int target, PyObject * evs)¶ evidenceImpact(LoopyBeliefPropagation self, str target, Vector_string evs) -> Potential
Create a pyAgrum.Potential for P(target|evs) (for all instanciation of target and evs)
Parameters: - target (set) – a set of targets ids or names.
- evs (set) – a set of nodes ids or names.
Warning
if some evs are d-separated, they are not included in the Potential.
Returns: a Potential for P(targets|evs) Return type: pyAgrum.Potential
-
hardEvidenceNodes
(LoopyBeliefPropagation self)¶ Returns: the set of nodes with hard evidence Return type: set
-
hasEvidence
(LoopyBeliefPropagation self, int id)¶ hasEvidence(LoopyBeliefPropagation self, str nodeName) -> bool
Parameters: - id (int) – a node Id
- nodeName (str) – a node name
Returns: True if some node(s) (or the one in parameters) have received evidence
Return type: bool
Raises: gum.IndexError
– If the node does not belong to the Bayesian network
-
hasHardEvidence
(LoopyBeliefPropagation self, str nodeName)¶ Parameters: - id (int) – a node Id
- nodeName (str) – a node name
Returns: True if node has received a hard evidence
Return type: bool
Raises: gum.IndexError
– If the node does not belong to the Bayesian network
-
hasSoftEvidence
(LoopyBeliefPropagation self, int id)¶ hasSoftEvidence(LoopyBeliefPropagation self, str nodeName) -> bool
Parameters: - id (int) – a node Id
- nodeName (str) – a node name
Returns: True if node has received a soft evidence
Return type: bool
Raises: gum.IndexError
– If the node does not belong to the Bayesian network
-
history
(LoopyBeliefPropagation self)¶ Returns: the scheme history Return type: tuple Raises: gum.OperationNotAllowed
– If the scheme did not performed or if verbosity is set to false
-
isTarget
(LoopyBeliefPropagation self, int variable)¶ isTarget(LoopyBeliefPropagation self, str nodeName) -> bool
Parameters: - variable (int) – a node Id
- nodeName (str) – a node name
Returns: True if variable is a (marginal) target
Return type: bool
Raises: gum.IndexError
– If the node does not belong to the Bayesian networkgum.UndefinedElement
– If node Id is not in the Bayesian network
-
makeInference
(LoopyBeliefPropagation self)¶ Perform the heavy computations needed to compute the targets’ posteriors
In a Junction tree propagation scheme, for instance, the heavy computations are those of the messages sent in the JT. This is precisely what makeInference should compute. Later, the computations of the posteriors can be done ‘lightly’ by multiplying and projecting those messages.
-
maxIter
(LoopyBeliefPropagation self)¶ Returns: the criterion on number of iterations Return type: int
-
maxTime
(LoopyBeliefPropagation self)¶ Returns: the timeout(in seconds) Return type: double
-
messageApproximationScheme
(LoopyBeliefPropagation self)¶ Returns: the approximation scheme message Return type: str
-
minEpsilonRate
(LoopyBeliefPropagation self)¶ Returns: the value of the minimal epsilon rate Return type: double
-
nbrEvidence
(LoopyBeliefPropagation self)¶ Returns: the number of evidence entered into the Bayesian network Return type: int
-
nbrHardEvidence
(LoopyBeliefPropagation self)¶ Returns: the number of hard evidence entered into the Bayesian network Return type: int
-
nbrIterations
(LoopyBeliefPropagation self)¶ Returns: the number of iterations Return type: int
-
nbrSoftEvidence
(LoopyBeliefPropagation self)¶ Returns: the number of soft evidence entered into the Bayesian network Return type: int
-
nbrTargets
(LoopyBeliefPropagation self)¶ Returns: the number of marginal targets Return type: int
-
periodSize
(LoopyBeliefPropagation self)¶ Returns: the number of samples between 2 stopping Return type: int Raises: gum.OutOfLowerBound
– If p<1
-
posterior
(LoopyBeliefPropagation self, int var)¶ posterior(LoopyBeliefPropagation self, str nodeName) -> Potential
Computes and returns the posterior of a node.
Parameters: - var (int) – the node Id of the node for which we need a posterior probability
- nodeName (str) – the node name of the node for which we need a posterior probability
Returns: a ref to the posterior probability of the node
Return type: Raises: gum.UndefinedElement
– If an element of nodes is not in targets
-
setEpsilon
(LoopyBeliefPropagation self, double eps)¶ Parameters: eps (double) – the epsilon we want to use Raises: gum.OutOfLowerBound
– If eps<0
-
setEvidence
(evidces)¶ Erase all the evidences and apply addEvidence(key,value) for every pairs in evidces.
Parameters: evidces (dict) – a dict of evidences
Raises: gum.InvalidArgument
– If one value is not a value for the nodegum.InvalidArgument
– If the size of a value is different from the domain side of the nodegum.FatalError
– If one value is a vector of 0sgum.UndefinedElement
– If one node does not belong to the Bayesian network
-
setMaxIter
(LoopyBeliefPropagation self, int max)¶ Parameters: max (int) – the maximum number of iteration Raises: gum.OutOfLowerBound
– If max <= 1
-
setMaxTime
(LoopyBeliefPropagation self, double timeout)¶ Parameters: tiemout (double) – stopping criterion on timeout (in seconds) Raises: gum.OutOfLowerBound
– If timeout<=0.0
-
setMinEpsilonRate
(LoopyBeliefPropagation self, double rate)¶ Parameters: rate (double) – the minimal epsilon rate
-
setPeriodSize
(LoopyBeliefPropagation self, int p)¶ Parameters: p (int) – number of samples between 2 stopping Raises: gum.OutOfLowerBound
– If p<1
-
setTargets
(targets)¶ Remove all the targets and add the ones in parameter.
Parameters: targets (set) – a set of targets Raises: gum.UndefinedElement
– If one target is not in the Bayes net
-
setVerbosity
(LoopyBeliefPropagation self, bool v)¶ Parameters: v (bool) – verbosity
-
softEvidenceNodes
(LoopyBeliefPropagation self)¶ Returns: the set of nodes with soft evidence Return type: set
-
targets
(LoopyBeliefPropagation self)¶ Returns: the list of marginal targets Return type: list
-
thisown
¶ The membership flag
-
updateEvidence
(evidces)¶ Apply chgEvidence(key,value) for every pairs in evidces (or addEvidence).
Parameters: evidces (dict) – a dict of evidences
Raises: gum.InvalidArgument
– If one value is not a value for the nodegum.InvalidArgument
– If the size of a value is different from the domain side of the nodegum.FatalError
– If one value is a vector of 0sgum.UndefinedElement
– If one node does not belong to the Bayesian network
-
verbosity
(LoopyBeliefPropagation self)¶ Returns: True if the verbosity is enabled Return type: bool
Sampling¶
Gibbs Sampling¶
-
class
pyAgrum.
GibbsSampling
(bn: pyAgrum.pyAgrum.IBayesNet)¶ Class for making Gibbs sampling inference in bayesian networks.
- Available ructors:
GibbsSampling(bn) -> GibbsSampling
Parameters: bn (pyAgrum.BayesNet) – a Bayesian network -
BN
(GibbsSampling self)¶ Returns: A ant reference over the IBayesNet referenced by this class. Return type: pyAgrum.IBayesNet Raises: gum.UndefinedElement
– If no Bayes net has been assigned to the inference.
-
H
(GibbsSampling self, int X)¶ H(GibbsSampling self, str nodeName) -> double
Parameters: - X (int) – a node Id
- nodeName (str) – a node name
Returns: the computed Shanon’s entropy of a node given the observation
Return type: double
-
addAllTargets
(GibbsSampling self)¶ Add all the nodes as targets.
-
addEvidence
(GibbsSampling self, int id, int val)¶ addEvidence(GibbsSampling self, str nodeName, int val) addEvidence(GibbsSampling self, int id, str val) addEvidence(GibbsSampling self, str nodeName, str val) addEvidence(GibbsSampling self, int id, Vector vals) addEvidence(GibbsSampling self, str nodeName, Vector vals)
Adds a new evidence on a node (might be soft or hard).
Parameters: - id (int) – a node Id
- nodeName (int) – a node name
- val – (int) a node value
- val – (str) the label of the node value
- vals (list) – a list of values
Raises: gum.InvalidArgument
– If the node already has an evidencegum.InvalidArgument
– If val is not a value for the nodegum.InvalidArgument
– If the size of vals is different from the domain side of the nodegum.FatalError
– If vals is a vector of 0sgum.UndefinedElement
– If the node does not belong to the Bayesian network
-
addTarget
(GibbsSampling self, int target)¶ addTarget(GibbsSampling self, str nodeName)
Add a marginal target to the list of targets.
Parameters: - target (int) – a node Id
- nodeName (str) – a node name
Raises: gum.UndefinedElement
– If target is not a NodeId in the Bayes net
-
burnIn
(GibbsSampling self)¶ Returns: size of burn in on number of iteration Return type: int
-
chgEvidence
(GibbsSampling self, int id, int val)¶ chgEvidence(GibbsSampling self, str nodeName, int val) chgEvidence(GibbsSampling self, int id, str val) chgEvidence(GibbsSampling self, str nodeName, str val) chgEvidence(GibbsSampling self, int id, Vector vals) chgEvidence(GibbsSampling self, str nodeName, Vector vals)
Change the value of an already existing evidence on a node (might be soft or hard).
Parameters: - id (int) – a node Id
- nodeName (int) – a node name
- val – (int) a node value
- val – (str) the label of the node value
- vals (list) – a list of values
Raises: gum.InvalidArgument
– If the node does not already have an evidencegum.InvalidArgument
– If val is not a value for the nodegum.InvalidArgument
– If the size of vals is different from the domain side of the nodegum.FatalError
– If vals is a vector of 0sgum.UndefinedElement
– If the node does not belong to the Bayesian network
-
currentPosterior
(GibbsSampling self, int id)¶ currentPosterior(GibbsSampling self, str name) -> Potential
Computes and returns the current posterior of a node.
Parameters: - var (int) – the node Id of the node for which we need a posterior probability
- nodeName (str) – the node name of the node for which we need a posterior probability
Returns: a ref to the current posterior probability of the node
Return type: Raises: UndefinedElement
– If an element of nodes is not in targets
-
currentTime
(GibbsSampling self)¶ Returns: get the current running time in second (double) Return type: double
-
epsilon
(GibbsSampling self)¶ Returns: the value of epsilon Return type: double
-
eraseAllEvidence
(GibbsSampling self)¶ Removes all the evidence entered into the network.
-
eraseAllTargets
(GibbsSampling self)¶ Clear all previously defined targets (marginal and joint targets).
As a result, no posterior can be computed (since we can only compute the posteriors of the marginal or joint targets that have been added by the user).
-
eraseEvidence
(GibbsSampling self, int id)¶ eraseEvidence(GibbsSampling self, str nodeName)
Remove the evidence, if any, corresponding to the node Id or name.
Parameters: - id (int) – a node Id
- nodeName (int) – a node name
Raises: gum.IndexError
– If the node does not belong to the Bayesian network
-
eraseTarget
(GibbsSampling self, int target)¶ eraseTarget(GibbsSampling self, str nodeName)
Remove, if existing, the marginal target.
Parameters: - target (int) – a node Id
- nodeName (int) – a node name
Raises: gum.IndexError
– If one of the node does not belong to the Bayesian networkgum.UndefinedElement
– If node Id is not in the Bayesian network
-
evidenceImpact
(GibbsSampling self, int target, PyObject * evs)¶ evidenceImpact(GibbsSampling self, str target, Vector_string evs) -> Potential
Create a pyAgrum.Potential for P(target|evs) (for all instanciation of target and evs)
Parameters: - target (set) – a set of targets ids or names.
- evs (set) – a set of nodes ids or names.
Warning
if some evs are d-separated, they are not included in the Potential.
Returns: a Potential for P(targets|evs) Return type: pyAgrum.Potential
-
hardEvidenceNodes
(GibbsSampling self)¶ Returns: the set of nodes with hard evidence Return type: set
-
hasEvidence
(GibbsSampling self, int id)¶ hasEvidence(GibbsSampling self, str nodeName) -> bool
Parameters: - id (int) – a node Id
- nodeName (str) – a node name
Returns: True if some node(s) (or the one in parameters) have received evidence
Return type: bool
Raises: gum.IndexError
– If the node does not belong to the Bayesian network
-
hasHardEvidence
(GibbsSampling self, str nodeName)¶ Parameters: - id (int) – a node Id
- nodeName (str) – a node name
Returns: True if node has received a hard evidence
Return type: bool
Raises: gum.IndexError
– If the node does not belong to the Bayesian network
-
hasSoftEvidence
(GibbsSampling self, int id)¶ hasSoftEvidence(GibbsSampling self, str nodeName) -> bool
Parameters: - id (int) – a node Id
- nodeName (str) – a node name
Returns: True if node has received a soft evidence
Return type: bool
Raises: gum.IndexError
– If the node does not belong to the Bayesian network
-
history
(GibbsSampling self)¶ Returns: the scheme history Return type: tuple Raises: gum.OperationNotAllowed
– If the scheme did not performed or if verbosity is set to false
-
isDrawnAtRandom
(GibbsSampling self)¶ Returns: True if variables are drawn at random Return type: bool
-
isTarget
(GibbsSampling self, int variable)¶ isTarget(GibbsSampling self, str nodeName) -> bool
Parameters: - variable (int) – a node Id
- nodeName (str) – a node name
Returns: True if variable is a (marginal) target
Return type: bool
Raises: gum.IndexError
– If the node does not belong to the Bayesian networkgum.UndefinedElement
– If node Id is not in the Bayesian network
-
makeInference
(GibbsSampling self)¶ Perform the heavy computations needed to compute the targets’ posteriors
In a Junction tree propagation scheme, for instance, the heavy computations are those of the messages sent in the JT. This is precisely what makeInference should compute. Later, the computations of the posteriors can be done ‘lightly’ by multiplying and projecting those messages.
-
maxIter
(GibbsSampling self)¶ Returns: the criterion on number of iterations Return type: int
-
maxTime
(GibbsSampling self)¶ Returns: the timeout(in seconds) Return type: double
-
messageApproximationScheme
(GibbsSampling self)¶ Returns: the approximation scheme message Return type: str
-
minEpsilonRate
(GibbsSampling self)¶ Returns: the value of the minimal epsilon rate Return type: double
-
nbrDrawnVar
(GibbsSampling self)¶ Returns: the number of variable drawn at each iteration Return type: int
-
nbrEvidence
(GibbsSampling self)¶ Returns: the number of evidence entered into the Bayesian network Return type: int
-
nbrHardEvidence
(GibbsSampling self)¶ Returns: the number of hard evidence entered into the Bayesian network Return type: int
-
nbrIterations
(GibbsSampling self)¶ Returns: the number of iterations Return type: int
-
nbrSoftEvidence
(GibbsSampling self)¶ Returns: the number of soft evidence entered into the Bayesian network Return type: int
-
nbrTargets
(GibbsSampling self)¶ Returns: the number of marginal targets Return type: int
-
periodSize
(GibbsSampling self)¶ Returns: the number of samples between 2 stopping Return type: int Raises: gum.OutOfLowerBound
– If p<1
-
posterior
(GibbsSampling self, int var)¶ posterior(GibbsSampling self, str nodeName) -> Potential
Computes and returns the posterior of a node.
Parameters: - var (int) – the node Id of the node for which we need a posterior probability
- nodeName (str) – the node name of the node for which we need a posterior probability
Returns: a ref to the posterior probability of the node
Return type: Raises: gum.UndefinedElement
– If an element of nodes is not in targets
-
setBurnIn
(GibbsSampling self, int b)¶ Parameters: b (int) – size of burn in on number of iteration
-
setDrawnAtRandom
(GibbsSampling self, bool _atRandom)¶ Parameters: _atRandom (bool) – indicates if variables should be drawn at random
-
setEpsilon
(GibbsSampling self, double eps)¶ Parameters: eps (double) – the epsilon we want to use Raises: gum.OutOfLowerBound
– If eps<0
-
setEvidence
(evidces)¶ Erase all the evidences and apply addEvidence(key,value) for every pairs in evidces.
Parameters: evidces (dict) – a dict of evidences
Raises: gum.InvalidArgument
– If one value is not a value for the nodegum.InvalidArgument
– If the size of a value is different from the domain side of the nodegum.FatalError
– If one value is a vector of 0sgum.UndefinedElement
– If one node does not belong to the Bayesian network
-
setMaxIter
(GibbsSampling self, int max)¶ Parameters: max (int) – the maximum number of iteration Raises: gum.OutOfLowerBound
– If max <= 1
-
setMaxTime
(GibbsSampling self, double timeout)¶ Parameters: tiemout (double) – stopping criterion on timeout (in seconds) Raises: gum.OutOfLowerBound
– If timeout<=0.0
-
setMinEpsilonRate
(GibbsSampling self, double rate)¶ Parameters: rate (double) – the minimal epsilon rate
-
setNbrDrawnVar
(GibbsSampling self, int _nbr)¶ Parameters: _nbr (int) – the number of variables to be drawn at each iteration
-
setPeriodSize
(GibbsSampling self, int p)¶ Parameters: p (int) – number of samples between 2 stopping Raises: gum.OutOfLowerBound
– If p<1
-
setTargets
(targets)¶ Remove all the targets and add the ones in parameter.
Parameters: targets (set) – a set of targets Raises: gum.UndefinedElement
– If one target is not in the Bayes net
-
setVerbosity
(GibbsSampling self, bool v)¶ Parameters: v (bool) – verbosity
-
softEvidenceNodes
(GibbsSampling self)¶ Returns: the set of nodes with soft evidence Return type: set
-
targets
(GibbsSampling self)¶ Returns: the list of marginal targets Return type: list
-
thisown
¶ The membership flag
-
updateEvidence
(evidces)¶ Apply chgEvidence(key,value) for every pairs in evidces (or addEvidence).
Parameters: evidces (dict) – a dict of evidences
Raises: gum.InvalidArgument
– If one value is not a value for the nodegum.InvalidArgument
– If the size of a value is different from the domain side of the nodegum.FatalError
– If one value is a vector of 0sgum.UndefinedElement
– If one node does not belong to the Bayesian network
-
verbosity
(GibbsSampling self)¶ Returns: True if the verbosity is enabled Return type: bool
Monte Carlo Sampling¶
-
class
pyAgrum.
MonteCarloSampling
(bn: pyAgrum.pyAgrum.IBayesNet)¶ Class used for Monte Carlo sampling inference algorithm.
- Available ructors:
MonteCarloSampling(bn) -> MonteCarloSampling
Parameters: bn (pyAgrum.BayesNet) – a Bayesian network -
BN
(MonteCarloSampling self)¶ Returns: A ant reference over the IBayesNet referenced by this class. Return type: pyAgrum.IBayesNet Raises: gum.UndefinedElement
– If no Bayes net has been assigned to the inference.
-
H
(MonteCarloSampling self, int X)¶ H(MonteCarloSampling self, str nodeName) -> double
Parameters: - X (int) – a node Id
- nodeName (str) – a node name
Returns: the computed Shanon’s entropy of a node given the observation
Return type: double
-
addAllTargets
(MonteCarloSampling self)¶ Add all the nodes as targets.
-
addEvidence
(MonteCarloSampling self, int id, int val)¶ addEvidence(MonteCarloSampling self, str nodeName, int val) addEvidence(MonteCarloSampling self, int id, str val) addEvidence(MonteCarloSampling self, str nodeName, str val) addEvidence(MonteCarloSampling self, int id, Vector vals) addEvidence(MonteCarloSampling self, str nodeName, Vector vals)
Adds a new evidence on a node (might be soft or hard).
Parameters: - id (int) – a node Id
- nodeName (int) – a node name
- val – (int) a node value
- val – (str) the label of the node value
- vals (list) – a list of values
Raises: gum.InvalidArgument
– If the node already has an evidencegum.InvalidArgument
– If val is not a value for the nodegum.InvalidArgument
– If the size of vals is different from the domain side of the nodegum.FatalError
– If vals is a vector of 0sgum.UndefinedElement
– If the node does not belong to the Bayesian network
-
addTarget
(MonteCarloSampling self, int target)¶ addTarget(MonteCarloSampling self, str nodeName)
Add a marginal target to the list of targets.
Parameters: - target (int) – a node Id
- nodeName (str) – a node name
Raises: gum.UndefinedElement
– If target is not a NodeId in the Bayes net
-
chgEvidence
(MonteCarloSampling self, int id, int val)¶ chgEvidence(MonteCarloSampling self, str nodeName, int val) chgEvidence(MonteCarloSampling self, int id, str val) chgEvidence(MonteCarloSampling self, str nodeName, str val) chgEvidence(MonteCarloSampling self, int id, Vector vals) chgEvidence(MonteCarloSampling self, str nodeName, Vector vals)
Change the value of an already existing evidence on a node (might be soft or hard).
Parameters: - id (int) – a node Id
- nodeName (int) – a node name
- val – (int) a node value
- val – (str) the label of the node value
- vals (list) – a list of values
Raises: gum.InvalidArgument
– If the node does not already have an evidencegum.InvalidArgument
– If val is not a value for the nodegum.InvalidArgument
– If the size of vals is different from the domain side of the nodegum.FatalError
– If vals is a vector of 0sgum.UndefinedElement
– If the node does not belong to the Bayesian network
-
currentPosterior
(MonteCarloSampling self, int id)¶ currentPosterior(MonteCarloSampling self, str name) -> Potential
Computes and returns the current posterior of a node.
Parameters: - var (int) – the node Id of the node for which we need a posterior probability
- nodeName (str) – the node name of the node for which we need a posterior probability
Returns: a ref to the current posterior probability of the node
Return type: Raises: UndefinedElement
– If an element of nodes is not in targets
-
currentTime
(MonteCarloSampling self)¶ Returns: get the current running time in second (double) Return type: double
-
epsilon
(MonteCarloSampling self)¶ Returns: the value of epsilon Return type: double
-
eraseAllEvidence
(MonteCarloSampling self)¶ Removes all the evidence entered into the network.
-
eraseAllTargets
(MonteCarloSampling self)¶ Clear all previously defined targets (marginal and joint targets).
As a result, no posterior can be computed (since we can only compute the posteriors of the marginal or joint targets that have been added by the user).
-
eraseEvidence
(MonteCarloSampling self, int id)¶ eraseEvidence(MonteCarloSampling self, str nodeName)
Remove the evidence, if any, corresponding to the node Id or name.
Parameters: - id (int) – a node Id
- nodeName (int) – a node name
Raises: gum.IndexError
– If the node does not belong to the Bayesian network
-
eraseTarget
(MonteCarloSampling self, int target)¶ eraseTarget(MonteCarloSampling self, str nodeName)
Remove, if existing, the marginal target.
Parameters: - target (int) – a node Id
- nodeName (int) – a node name
Raises: gum.IndexError
– If one of the node does not belong to the Bayesian networkgum.UndefinedElement
– If node Id is not in the Bayesian network
-
evidenceImpact
(MonteCarloSampling self, int target, PyObject * evs)¶ evidenceImpact(MonteCarloSampling self, str target, Vector_string evs) -> Potential
Create a pyAgrum.Potential for P(target|evs) (for all instanciation of target and evs)
Parameters: - target (set) – a set of targets ids or names.
- evs (set) – a set of nodes ids or names.
Warning
if some evs are d-separated, they are not included in the Potential.
Returns: a Potential for P(targets|evs) Return type: pyAgrum.Potential
-
hardEvidenceNodes
(MonteCarloSampling self)¶ Returns: the set of nodes with hard evidence Return type: set
-
hasEvidence
(MonteCarloSampling self, int id)¶ hasEvidence(MonteCarloSampling self, str nodeName) -> bool
Parameters: - id (int) – a node Id
- nodeName (str) – a node name
Returns: True if some node(s) (or the one in parameters) have received evidence
Return type: bool
Raises: gum.IndexError
– If the node does not belong to the Bayesian network
-
hasHardEvidence
(MonteCarloSampling self, str nodeName)¶ Parameters: - id (int) – a node Id
- nodeName (str) – a node name
Returns: True if node has received a hard evidence
Return type: bool
Raises: gum.IndexError
– If the node does not belong to the Bayesian network
-
hasSoftEvidence
(MonteCarloSampling self, int id)¶ hasSoftEvidence(MonteCarloSampling self, str nodeName) -> bool
Parameters: - id (int) – a node Id
- nodeName (str) – a node name
Returns: True if node has received a soft evidence
Return type: bool
Raises: gum.IndexError
– If the node does not belong to the Bayesian network
-
history
(MonteCarloSampling self)¶ Returns: the scheme history Return type: tuple Raises: gum.OperationNotAllowed
– If the scheme did not performed or if verbosity is set to false
-
isTarget
(MonteCarloSampling self, int variable)¶ isTarget(MonteCarloSampling self, str nodeName) -> bool
Parameters: - variable (int) – a node Id
- nodeName (str) – a node name
Returns: True if variable is a (marginal) target
Return type: bool
Raises: gum.IndexError
– If the node does not belong to the Bayesian networkgum.UndefinedElement
– If node Id is not in the Bayesian network
-
makeInference
(MonteCarloSampling self)¶ Perform the heavy computations needed to compute the targets’ posteriors
In a Junction tree propagation scheme, for instance, the heavy computations are those of the messages sent in the JT. This is precisely what makeInference should compute. Later, the computations of the posteriors can be done ‘lightly’ by multiplying and projecting those messages.
-
maxIter
(MonteCarloSampling self)¶ Returns: the criterion on number of iterations Return type: int
-
maxTime
(MonteCarloSampling self)¶ Returns: the timeout(in seconds) Return type: double
-
messageApproximationScheme
(MonteCarloSampling self)¶ Returns: the approximation scheme message Return type: str
-
minEpsilonRate
(MonteCarloSampling self)¶ Returns: the value of the minimal epsilon rate Return type: double
-
nbrEvidence
(MonteCarloSampling self)¶ Returns: the number of evidence entered into the Bayesian network Return type: int
-
nbrHardEvidence
(MonteCarloSampling self)¶ Returns: the number of hard evidence entered into the Bayesian network Return type: int
-
nbrIterations
(MonteCarloSampling self)¶ Returns: the number of iterations Return type: int
-
nbrSoftEvidence
(MonteCarloSampling self)¶ Returns: the number of soft evidence entered into the Bayesian network Return type: int
-
nbrTargets
(MonteCarloSampling self)¶ Returns: the number of marginal targets Return type: int
-
periodSize
(MonteCarloSampling self)¶ Returns: the number of samples between 2 stopping Return type: int Raises: gum.OutOfLowerBound
– If p<1
-
posterior
(MonteCarloSampling self, int var)¶ posterior(MonteCarloSampling self, str nodeName) -> Potential
Computes and returns the posterior of a node.
Parameters: - var (int) – the node Id of the node for which we need a posterior probability
- nodeName (str) – the node name of the node for which we need a posterior probability
Returns: a ref to the posterior probability of the node
Return type: Raises: gum.UndefinedElement
– If an element of nodes is not in targets
-
setEpsilon
(MonteCarloSampling self, double eps)¶ Parameters: eps (double) – the epsilon we want to use Raises: gum.OutOfLowerBound
– If eps<0
-
setEvidence
(evidces)¶ Erase all the evidences and apply addEvidence(key,value) for every pairs in evidces.
Parameters: evidces (dict) – a dict of evidences
Raises: gum.InvalidArgument
– If one value is not a value for the nodegum.InvalidArgument
– If the size of a value is different from the domain side of the nodegum.FatalError
– If one value is a vector of 0sgum.UndefinedElement
– If one node does not belong to the Bayesian network
-
setMaxIter
(MonteCarloSampling self, int max)¶ Parameters: max (int) – the maximum number of iteration Raises: gum.OutOfLowerBound
– If max <= 1
-
setMaxTime
(MonteCarloSampling self, double timeout)¶ Parameters: tiemout (double) – stopping criterion on timeout (in seconds) Raises: gum.OutOfLowerBound
– If timeout<=0.0
-
setMinEpsilonRate
(MonteCarloSampling self, double rate)¶ Parameters: rate (double) – the minimal epsilon rate
-
setPeriodSize
(MonteCarloSampling self, int p)¶ Parameters: p (int) – number of samples between 2 stopping Raises: gum.OutOfLowerBound
– If p<1
-
setTargets
(targets)¶ Remove all the targets and add the ones in parameter.
Parameters: targets (set) – a set of targets Raises: gum.UndefinedElement
– If one target is not in the Bayes net
-
setVerbosity
(MonteCarloSampling self, bool v)¶ Parameters: v (bool) – verbosity
-
softEvidenceNodes
(MonteCarloSampling self)¶ Returns: the set of nodes with soft evidence Return type: set
-
targets
(MonteCarloSampling self)¶ Returns: the list of marginal targets Return type: list
-
thisown
¶ The membership flag
-
updateEvidence
(evidces)¶ Apply chgEvidence(key,value) for every pairs in evidces (or addEvidence).
Parameters: evidces (dict) – a dict of evidences
Raises: gum.InvalidArgument
– If one value is not a value for the nodegum.InvalidArgument
– If the size of a value is different from the domain side of the nodegum.FatalError
– If one value is a vector of 0sgum.UndefinedElement
– If one node does not belong to the Bayesian network
-
verbosity
(MonteCarloSampling self)¶ Returns: True if the verbosity is enabled Return type: bool
Weighted Sampling¶
-
class
pyAgrum.
WeightedSampling
(bn: pyAgrum.pyAgrum.IBayesNet)¶ Class used for Weighted sampling inference algorithm.
- Available ructors:
WeightedSampling(bn) -> WeightedSampling
Parameters: bn (pyAgrum.BayesNet) – a Bayesian network -
BN
(WeightedSampling self)¶ Returns: A ant reference over the IBayesNet referenced by this class. Return type: pyAgrum.IBayesNet Raises: gum.UndefinedElement
– If no Bayes net has been assigned to the inference.
-
H
(WeightedSampling self, int X)¶ H(WeightedSampling self, str nodeName) -> double
Parameters: - X (int) – a node Id
- nodeName (str) – a node name
Returns: the computed Shanon’s entropy of a node given the observation
Return type: double
-
addAllTargets
(WeightedSampling self)¶ Add all the nodes as targets.
-
addEvidence
(WeightedSampling self, int id, int val)¶ addEvidence(WeightedSampling self, str nodeName, int val) addEvidence(WeightedSampling self, int id, str val) addEvidence(WeightedSampling self, str nodeName, str val) addEvidence(WeightedSampling self, int id, Vector vals) addEvidence(WeightedSampling self, str nodeName, Vector vals)
Adds a new evidence on a node (might be soft or hard).
Parameters: - id (int) – a node Id
- nodeName (int) – a node name
- val – (int) a node value
- val – (str) the label of the node value
- vals (list) – a list of values
Raises: gum.InvalidArgument
– If the node already has an evidencegum.InvalidArgument
– If val is not a value for the nodegum.InvalidArgument
– If the size of vals is different from the domain side of the nodegum.FatalError
– If vals is a vector of 0sgum.UndefinedElement
– If the node does not belong to the Bayesian network
-
addTarget
(WeightedSampling self, int target)¶ addTarget(WeightedSampling self, str nodeName)
Add a marginal target to the list of targets.
Parameters: - target (int) – a node Id
- nodeName (str) – a node name
Raises: gum.UndefinedElement
– If target is not a NodeId in the Bayes net
-
chgEvidence
(WeightedSampling self, int id, int val)¶ chgEvidence(WeightedSampling self, str nodeName, int val) chgEvidence(WeightedSampling self, int id, str val) chgEvidence(WeightedSampling self, str nodeName, str val) chgEvidence(WeightedSampling self, int id, Vector vals) chgEvidence(WeightedSampling self, str nodeName, Vector vals)
Change the value of an already existing evidence on a node (might be soft or hard).
Parameters: - id (int) – a node Id
- nodeName (int) – a node name
- val – (int) a node value
- val – (str) the label of the node value
- vals (list) – a list of values
Raises: gum.InvalidArgument
– If the node does not already have an evidencegum.InvalidArgument
– If val is not a value for the nodegum.InvalidArgument
– If the size of vals is different from the domain side of the nodegum.FatalError
– If vals is a vector of 0sgum.UndefinedElement
– If the node does not belong to the Bayesian network
-
currentPosterior
(WeightedSampling self, int id)¶ currentPosterior(WeightedSampling self, str name) -> Potential
Computes and returns the current posterior of a node.
Parameters: - var (int) – the node Id of the node for which we need a posterior probability
- nodeName (str) – the node name of the node for which we need a posterior probability
Returns: a ref to the current posterior probability of the node
Return type: Raises: UndefinedElement
– If an element of nodes is not in targets
-
currentTime
(WeightedSampling self)¶ Returns: get the current running time in second (double) Return type: double
-
epsilon
(WeightedSampling self)¶ Returns: the value of epsilon Return type: double
-
eraseAllEvidence
(WeightedSampling self)¶ Removes all the evidence entered into the network.
-
eraseAllTargets
(WeightedSampling self)¶ Clear all previously defined targets (marginal and joint targets).
As a result, no posterior can be computed (since we can only compute the posteriors of the marginal or joint targets that have been added by the user).
-
eraseEvidence
(WeightedSampling self, int id)¶ eraseEvidence(WeightedSampling self, str nodeName)
Remove the evidence, if any, corresponding to the node Id or name.
Parameters: - id (int) – a node Id
- nodeName (int) – a node name
Raises: gum.IndexError
– If the node does not belong to the Bayesian network
-
eraseTarget
(WeightedSampling self, int target)¶ eraseTarget(WeightedSampling self, str nodeName)
Remove, if existing, the marginal target.
Parameters: - target (int) – a node Id
- nodeName (int) – a node name
Raises: gum.IndexError
– If one of the node does not belong to the Bayesian networkgum.UndefinedElement
– If node Id is not in the Bayesian network
-
evidenceImpact
(WeightedSampling self, int target, PyObject * evs)¶ evidenceImpact(WeightedSampling self, str target, Vector_string evs) -> Potential
Create a pyAgrum.Potential for P(target|evs) (for all instanciation of target and evs)
Parameters: - target (set) – a set of targets ids or names.
- evs (set) – a set of nodes ids or names.
Warning
if some evs are d-separated, they are not included in the Potential.
Returns: a Potential for P(targets|evs) Return type: pyAgrum.Potential
-
hardEvidenceNodes
(WeightedSampling self)¶ Returns: the set of nodes with hard evidence Return type: set
-
hasEvidence
(WeightedSampling self, int id)¶ hasEvidence(WeightedSampling self, str nodeName) -> bool
Parameters: - id (int) – a node Id
- nodeName (str) – a node name
Returns: True if some node(s) (or the one in parameters) have received evidence
Return type: bool
Raises: gum.IndexError
– If the node does not belong to the Bayesian network
-
hasHardEvidence
(WeightedSampling self, str nodeName)¶ Parameters: - id (int) – a node Id
- nodeName (str) – a node name
Returns: True if node has received a hard evidence
Return type: bool
Raises: gum.IndexError
– If the node does not belong to the Bayesian network
-
hasSoftEvidence
(WeightedSampling self, int id)¶ hasSoftEvidence(WeightedSampling self, str nodeName) -> bool
Parameters: - id (int) – a node Id
- nodeName (str) – a node name
Returns: True if node has received a soft evidence
Return type: bool
Raises: gum.IndexError
– If the node does not belong to the Bayesian network
-
history
(WeightedSampling self)¶ Returns: the scheme history Return type: tuple Raises: gum.OperationNotAllowed
– If the scheme did not performed or if verbosity is set to false
-
isTarget
(WeightedSampling self, int variable)¶ isTarget(WeightedSampling self, str nodeName) -> bool
Parameters: - variable (int) – a node Id
- nodeName (str) – a node name
Returns: True if variable is a (marginal) target
Return type: bool
Raises: gum.IndexError
– If the node does not belong to the Bayesian networkgum.UndefinedElement
– If node Id is not in the Bayesian network
-
makeInference
(WeightedSampling self)¶ Perform the heavy computations needed to compute the targets’ posteriors
In a Junction tree propagation scheme, for instance, the heavy computations are those of the messages sent in the JT. This is precisely what makeInference should compute. Later, the computations of the posteriors can be done ‘lightly’ by multiplying and projecting those messages.
-
maxIter
(WeightedSampling self)¶ Returns: the criterion on number of iterations Return type: int
-
maxTime
(WeightedSampling self)¶ Returns: the timeout(in seconds) Return type: double
-
messageApproximationScheme
(WeightedSampling self)¶ Returns: the approximation scheme message Return type: str
-
minEpsilonRate
(WeightedSampling self)¶ Returns: the value of the minimal epsilon rate Return type: double
-
nbrEvidence
(WeightedSampling self)¶ Returns: the number of evidence entered into the Bayesian network Return type: int
-
nbrHardEvidence
(WeightedSampling self)¶ Returns: the number of hard evidence entered into the Bayesian network Return type: int
-
nbrIterations
(WeightedSampling self)¶ Returns: the number of iterations Return type: int
-
nbrSoftEvidence
(WeightedSampling self)¶ Returns: the number of soft evidence entered into the Bayesian network Return type: int
-
nbrTargets
(WeightedSampling self)¶ Returns: the number of marginal targets Return type: int
-
periodSize
(WeightedSampling self)¶ Returns: the number of samples between 2 stopping Return type: int Raises: gum.OutOfLowerBound
– If p<1
-
posterior
(WeightedSampling self, int var)¶ posterior(WeightedSampling self, str nodeName) -> Potential
Computes and returns the posterior of a node.
Parameters: - var (int) – the node Id of the node for which we need a posterior probability
- nodeName (str) – the node name of the node for which we need a posterior probability
Returns: a ref to the posterior probability of the node
Return type: Raises: gum.UndefinedElement
– If an element of nodes is not in targets
-
setEpsilon
(WeightedSampling self, double eps)¶ Parameters: eps (double) – the epsilon we want to use Raises: gum.OutOfLowerBound
– If eps<0
-
setEvidence
(evidces)¶ Erase all the evidences and apply addEvidence(key,value) for every pairs in evidces.
Parameters: evidces (dict) – a dict of evidences
Raises: gum.InvalidArgument
– If one value is not a value for the nodegum.InvalidArgument
– If the size of a value is different from the domain side of the nodegum.FatalError
– If one value is a vector of 0sgum.UndefinedElement
– If one node does not belong to the Bayesian network
-
setMaxIter
(WeightedSampling self, int max)¶ Parameters: max (int) – the maximum number of iteration Raises: gum.OutOfLowerBound
– If max <= 1
-
setMaxTime
(WeightedSampling self, double timeout)¶ Parameters: tiemout (double) – stopping criterion on timeout (in seconds) Raises: gum.OutOfLowerBound
– If timeout<=0.0
-
setMinEpsilonRate
(WeightedSampling self, double rate)¶ Parameters: rate (double) – the minimal epsilon rate
-
setPeriodSize
(WeightedSampling self, int p)¶ Parameters: p (int) – number of samples between 2 stopping Raises: gum.OutOfLowerBound
– If p<1
-
setTargets
(targets)¶ Remove all the targets and add the ones in parameter.
Parameters: targets (set) – a set of targets Raises: gum.UndefinedElement
– If one target is not in the Bayes net
-
setVerbosity
(WeightedSampling self, bool v)¶ Parameters: v (bool) – verbosity
-
softEvidenceNodes
(WeightedSampling self)¶ Returns: the set of nodes with soft evidence Return type: set
-
targets
(WeightedSampling self)¶ Returns: the list of marginal targets Return type: list
-
thisown
¶ The membership flag
-
updateEvidence
(evidces)¶ Apply chgEvidence(key,value) for every pairs in evidces (or addEvidence).
Parameters: evidces (dict) – a dict of evidences
Raises: gum.InvalidArgument
– If one value is not a value for the nodegum.InvalidArgument
– If the size of a value is different from the domain side of the nodegum.FatalError
– If one value is a vector of 0sgum.UndefinedElement
– If one node does not belong to the Bayesian network
-
verbosity
(WeightedSampling self)¶ Returns: True if the verbosity is enabled Return type: bool
Importance Sampling¶
-
class
pyAgrum.
ImportanceSampling
(bn: pyAgrum.pyAgrum.IBayesNet)¶ Class used for inferences using the Importance Sampling algorithm.
- Available ructors:
ImportanceSampling(bn) -> ImportanceSampling
Parameters: bn (pyAgrum.BayesNet) – a Bayesian network -
BN
(ImportanceSampling self)¶ Returns: A ant reference over the IBayesNet referenced by this class. Return type: pyAgrum.IBayesNet Raises: gum.UndefinedElement
– If no Bayes net has been assigned to the inference.
-
H
(ImportanceSampling self, int X)¶ H(ImportanceSampling self, str nodeName) -> double
Parameters: - X (int) – a node Id
- nodeName (str) – a node name
Returns: the computed Shanon’s entropy of a node given the observation
Return type: double
-
addAllTargets
(ImportanceSampling self)¶ Add all the nodes as targets.
-
addEvidence
(ImportanceSampling self, int id, int val)¶ addEvidence(ImportanceSampling self, str nodeName, int val) addEvidence(ImportanceSampling self, int id, str val) addEvidence(ImportanceSampling self, str nodeName, str val) addEvidence(ImportanceSampling self, int id, Vector vals) addEvidence(ImportanceSampling self, str nodeName, Vector vals)
Adds a new evidence on a node (might be soft or hard).
Parameters: - id (int) – a node Id
- nodeName (int) – a node name
- val – (int) a node value
- val – (str) the label of the node value
- vals (list) – a list of values
Raises: gum.InvalidArgument
– If the node already has an evidencegum.InvalidArgument
– If val is not a value for the nodegum.InvalidArgument
– If the size of vals is different from the domain side of the nodegum.FatalError
– If vals is a vector of 0sgum.UndefinedElement
– If the node does not belong to the Bayesian network
-
addTarget
(ImportanceSampling self, int target)¶ addTarget(ImportanceSampling self, str nodeName)
Add a marginal target to the list of targets.
Parameters: - target (int) – a node Id
- nodeName (str) – a node name
Raises: gum.UndefinedElement
– If target is not a NodeId in the Bayes net
-
chgEvidence
(ImportanceSampling self, int id, int val)¶ chgEvidence(ImportanceSampling self, str nodeName, int val) chgEvidence(ImportanceSampling self, int id, str val) chgEvidence(ImportanceSampling self, str nodeName, str val) chgEvidence(ImportanceSampling self, int id, Vector vals) chgEvidence(ImportanceSampling self, str nodeName, Vector vals)
Change the value of an already existing evidence on a node (might be soft or hard).
Parameters: - id (int) – a node Id
- nodeName (int) – a node name
- val – (int) a node value
- val – (str) the label of the node value
- vals (list) – a list of values
Raises: gum.InvalidArgument
– If the node does not already have an evidencegum.InvalidArgument
– If val is not a value for the nodegum.InvalidArgument
– If the size of vals is different from the domain side of the nodegum.FatalError
– If vals is a vector of 0sgum.UndefinedElement
– If the node does not belong to the Bayesian network
-
currentPosterior
(ImportanceSampling self, int id)¶ currentPosterior(ImportanceSampling self, str name) -> Potential
Computes and returns the current posterior of a node.
Parameters: - var (int) – the node Id of the node for which we need a posterior probability
- nodeName (str) – the node name of the node for which we need a posterior probability
Returns: a ref to the current posterior probability of the node
Return type: Raises: UndefinedElement
– If an element of nodes is not in targets
-
currentTime
(ImportanceSampling self)¶ Returns: get the current running time in second (double) Return type: double
-
epsilon
(ImportanceSampling self)¶ Returns: the value of epsilon Return type: double
-
eraseAllEvidence
(ImportanceSampling self)¶ Removes all the evidence entered into the network.
-
eraseAllTargets
(ImportanceSampling self)¶ Clear all previously defined targets (marginal and joint targets).
As a result, no posterior can be computed (since we can only compute the posteriors of the marginal or joint targets that have been added by the user).
-
eraseEvidence
(ImportanceSampling self, int id)¶ eraseEvidence(ImportanceSampling self, str nodeName)
Remove the evidence, if any, corresponding to the node Id or name.
Parameters: - id (int) – a node Id
- nodeName (int) – a node name
Raises: gum.IndexError
– If the node does not belong to the Bayesian network
-
eraseTarget
(ImportanceSampling self, int target)¶ eraseTarget(ImportanceSampling self, str nodeName)
Remove, if existing, the marginal target.
Parameters: - target (int) – a node Id
- nodeName (int) – a node name
Raises: gum.IndexError
– If one of the node does not belong to the Bayesian networkgum.UndefinedElement
– If node Id is not in the Bayesian network
-
evidenceImpact
(ImportanceSampling self, int target, PyObject * evs)¶ evidenceImpact(ImportanceSampling self, str target, Vector_string evs) -> Potential
Create a pyAgrum.Potential for P(target|evs) (for all instanciation of target and evs)
Parameters: - target (set) – a set of targets ids or names.
- evs (set) – a set of nodes ids or names.
Warning
if some evs are d-separated, they are not included in the Potential.
Returns: a Potential for P(targets|evs) Return type: pyAgrum.Potential
-
hardEvidenceNodes
(ImportanceSampling self)¶ Returns: the set of nodes with hard evidence Return type: set
-
hasEvidence
(ImportanceSampling self, int id)¶ hasEvidence(ImportanceSampling self, str nodeName) -> bool
Parameters: - id (int) – a node Id
- nodeName (str) – a node name
Returns: True if some node(s) (or the one in parameters) have received evidence
Return type: bool
Raises: gum.IndexError
– If the node does not belong to the Bayesian network
-
hasHardEvidence
(ImportanceSampling self, str nodeName)¶ Parameters: - id (int) – a node Id
- nodeName (str) – a node name
Returns: True if node has received a hard evidence
Return type: bool
Raises: gum.IndexError
– If the node does not belong to the Bayesian network
-
hasSoftEvidence
(ImportanceSampling self, int id)¶ hasSoftEvidence(ImportanceSampling self, str nodeName) -> bool
Parameters: - id (int) – a node Id
- nodeName (str) – a node name
Returns: True if node has received a soft evidence
Return type: bool
Raises: gum.IndexError
– If the node does not belong to the Bayesian network
-
history
(ImportanceSampling self)¶ Returns: the scheme history Return type: tuple Raises: gum.OperationNotAllowed
– If the scheme did not performed or if verbosity is set to false
-
isTarget
(ImportanceSampling self, int variable)¶ isTarget(ImportanceSampling self, str nodeName) -> bool
Parameters: - variable (int) – a node Id
- nodeName (str) – a node name
Returns: True if variable is a (marginal) target
Return type: bool
Raises: gum.IndexError
– If the node does not belong to the Bayesian networkgum.UndefinedElement
– If node Id is not in the Bayesian network
-
makeInference
(ImportanceSampling self)¶ Perform the heavy computations needed to compute the targets’ posteriors
In a Junction tree propagation scheme, for instance, the heavy computations are those of the messages sent in the JT. This is precisely what makeInference should compute. Later, the computations of the posteriors can be done ‘lightly’ by multiplying and projecting those messages.
-
maxIter
(ImportanceSampling self)¶ Returns: the criterion on number of iterations Return type: int
-
maxTime
(ImportanceSampling self)¶ Returns: the timeout(in seconds) Return type: double
-
messageApproximationScheme
(ImportanceSampling self)¶ Returns: the approximation scheme message Return type: str
-
minEpsilonRate
(ImportanceSampling self)¶ Returns: the value of the minimal epsilon rate Return type: double
-
nbrEvidence
(ImportanceSampling self)¶ Returns: the number of evidence entered into the Bayesian network Return type: int
-
nbrHardEvidence
(ImportanceSampling self)¶ Returns: the number of hard evidence entered into the Bayesian network Return type: int
-
nbrIterations
(ImportanceSampling self)¶ Returns: the number of iterations Return type: int
-
nbrSoftEvidence
(ImportanceSampling self)¶ Returns: the number of soft evidence entered into the Bayesian network Return type: int
-
nbrTargets
(ImportanceSampling self)¶ Returns: the number of marginal targets Return type: int
-
periodSize
(ImportanceSampling self)¶ Returns: the number of samples between 2 stopping Return type: int Raises: gum.OutOfLowerBound
– If p<1
-
posterior
(ImportanceSampling self, int var)¶ posterior(ImportanceSampling self, str nodeName) -> Potential
Computes and returns the posterior of a node.
Parameters: - var (int) – the node Id of the node for which we need a posterior probability
- nodeName (str) – the node name of the node for which we need a posterior probability
Returns: a ref to the posterior probability of the node
Return type: Raises: gum.UndefinedElement
– If an element of nodes is not in targets
-
setEpsilon
(ImportanceSampling self, double eps)¶ Parameters: eps (double) – the epsilon we want to use Raises: gum.OutOfLowerBound
– If eps<0
-
setEvidence
(evidces)¶ Erase all the evidences and apply addEvidence(key,value) for every pairs in evidces.
Parameters: evidces (dict) – a dict of evidences
Raises: gum.InvalidArgument
– If one value is not a value for the nodegum.InvalidArgument
– If the size of a value is different from the domain side of the nodegum.FatalError
– If one value is a vector of 0sgum.UndefinedElement
– If one node does not belong to the Bayesian network
-
setMaxIter
(ImportanceSampling self, int max)¶ Parameters: max (int) – the maximum number of iteration Raises: gum.OutOfLowerBound
– If max <= 1
-
setMaxTime
(ImportanceSampling self, double timeout)¶ Parameters: tiemout (double) – stopping criterion on timeout (in seconds) Raises: gum.OutOfLowerBound
– If timeout<=0.0
-
setMinEpsilonRate
(ImportanceSampling self, double rate)¶ Parameters: rate (double) – the minimal epsilon rate
-
setPeriodSize
(ImportanceSampling self, int p)¶ Parameters: p (int) – number of samples between 2 stopping Raises: gum.OutOfLowerBound
– If p<1
-
setTargets
(targets)¶ Remove all the targets and add the ones in parameter.
Parameters: targets (set) – a set of targets Raises: gum.UndefinedElement
– If one target is not in the Bayes net
-
setVerbosity
(ImportanceSampling self, bool v)¶ Parameters: v (bool) – verbosity
-
softEvidenceNodes
(ImportanceSampling self)¶ Returns: the set of nodes with soft evidence Return type: set
-
targets
(ImportanceSampling self)¶ Returns: the list of marginal targets Return type: list
-
thisown
¶ The membership flag
-
updateEvidence
(evidces)¶ Apply chgEvidence(key,value) for every pairs in evidces (or addEvidence).
Parameters: evidces (dict) – a dict of evidences
Raises: gum.InvalidArgument
– If one value is not a value for the nodegum.InvalidArgument
– If the size of a value is different from the domain side of the nodegum.FatalError
– If one value is a vector of 0sgum.UndefinedElement
– If one node does not belong to the Bayesian network
-
verbosity
(ImportanceSampling self)¶ Returns: True if the verbosity is enabled Return type: bool
Loopy sampling¶
Loopy Gibbs Sampling¶
-
class
pyAgrum.
LoopyGibbsSampling
(bn: pyAgrum.pyAgrum.IBayesNet)¶ Class used for inferences using a loopy version of Gibbs sampling.
- Available ructors:
LoopyGibbsSampling(bn) -> LoopyGibbsSampling
Parameters: bn (pyAgrum.BayesNet) – a Bayesian network -
BN
(LoopyGibbsSampling self)¶ Returns: A ant reference over the IBayesNet referenced by this class. Return type: pyAgrum.IBayesNet Raises: gum.UndefinedElement
– If no Bayes net has been assigned to the inference.
-
H
(LoopyGibbsSampling self, int X)¶ H(LoopyGibbsSampling self, str nodeName) -> double
Parameters: - X (int) – a node Id
- nodeName (str) – a node name
Returns: the computed Shanon’s entropy of a node given the observation
Return type: double
-
addAllTargets
(LoopyGibbsSampling self)¶ Add all the nodes as targets.
-
addEvidence
(LoopyGibbsSampling self, int id, int val)¶ addEvidence(LoopyGibbsSampling self, str nodeName, int val) addEvidence(LoopyGibbsSampling self, int id, str val) addEvidence(LoopyGibbsSampling self, str nodeName, str val) addEvidence(LoopyGibbsSampling self, int id, Vector vals) addEvidence(LoopyGibbsSampling self, str nodeName, Vector vals)
Adds a new evidence on a node (might be soft or hard).
Parameters: - id (int) – a node Id
- nodeName (int) – a node name
- val – (int) a node value
- val – (str) the label of the node value
- vals (list) – a list of values
Raises: gum.InvalidArgument
– If the node already has an evidencegum.InvalidArgument
– If val is not a value for the nodegum.InvalidArgument
– If the size of vals is different from the domain side of the nodegum.FatalError
– If vals is a vector of 0sgum.UndefinedElement
– If the node does not belong to the Bayesian network
-
addTarget
(LoopyGibbsSampling self, int target)¶ addTarget(LoopyGibbsSampling self, str nodeName)
Add a marginal target to the list of targets.
Parameters: - target (int) – a node Id
- nodeName (str) – a node name
Raises: gum.UndefinedElement
– If target is not a NodeId in the Bayes net
-
burnIn
(LoopyGibbsSampling self)¶ Returns: size of burn in on number of iteration Return type: int
-
chgEvidence
(LoopyGibbsSampling self, int id, int val)¶ chgEvidence(LoopyGibbsSampling self, str nodeName, int val) chgEvidence(LoopyGibbsSampling self, int id, str val) chgEvidence(LoopyGibbsSampling self, str nodeName, str val) chgEvidence(LoopyGibbsSampling self, int id, Vector vals) chgEvidence(LoopyGibbsSampling self, str nodeName, Vector vals)
Change the value of an already existing evidence on a node (might be soft or hard).
Parameters: - id (int) – a node Id
- nodeName (int) – a node name
- val – (int) a node value
- val – (str) the label of the node value
- vals (list) – a list of values
Raises: gum.InvalidArgument
– If the node does not already have an evidencegum.InvalidArgument
– If val is not a value for the nodegum.InvalidArgument
– If the size of vals is different from the domain side of the nodegum.FatalError
– If vals is a vector of 0sgum.UndefinedElement
– If the node does not belong to the Bayesian network
-
currentPosterior
(LoopyGibbsSampling self, int id)¶ currentPosterior(LoopyGibbsSampling self, str name) -> Potential
Computes and returns the current posterior of a node.
Parameters: - var (int) – the node Id of the node for which we need a posterior probability
- nodeName (str) – the node name of the node for which we need a posterior probability
Returns: a ref to the current posterior probability of the node
Return type: Raises: UndefinedElement
– If an element of nodes is not in targets
-
currentTime
(LoopyGibbsSampling self)¶ Returns: get the current running time in second (double) Return type: double
-
epsilon
(LoopyGibbsSampling self)¶ Returns: the value of epsilon Return type: double
-
eraseAllEvidence
(LoopyGibbsSampling self)¶ Removes all the evidence entered into the network.
-
eraseAllTargets
(LoopyGibbsSampling self)¶ Clear all previously defined targets (marginal and joint targets).
As a result, no posterior can be computed (since we can only compute the posteriors of the marginal or joint targets that have been added by the user).
-
eraseEvidence
(LoopyGibbsSampling self, int id)¶ eraseEvidence(LoopyGibbsSampling self, str nodeName)
Remove the evidence, if any, corresponding to the node Id or name.
Parameters: - id (int) – a node Id
- nodeName (int) – a node name
Raises: gum.IndexError
– If the node does not belong to the Bayesian network
-
eraseTarget
(LoopyGibbsSampling self, int target)¶ eraseTarget(LoopyGibbsSampling self, str nodeName)
Remove, if existing, the marginal target.
Parameters: - target (int) – a node Id
- nodeName (int) – a node name
Raises: gum.IndexError
– If one of the node does not belong to the Bayesian networkgum.UndefinedElement
– If node Id is not in the Bayesian network
-
evidenceImpact
(LoopyGibbsSampling self, int target, PyObject * evs)¶ evidenceImpact(LoopyGibbsSampling self, str target, Vector_string evs) -> Potential
Create a pyAgrum.Potential for P(target|evs) (for all instanciation of target and evs)
Parameters: - target (set) – a set of targets ids or names.
- evs (set) – a set of nodes ids or names.
Warning
if some evs are d-separated, they are not included in the Potential.
Returns: a Potential for P(targets|evs) Return type: pyAgrum.Potential
-
hardEvidenceNodes
(LoopyGibbsSampling self)¶ Returns: the set of nodes with hard evidence Return type: set
-
hasEvidence
(LoopyGibbsSampling self, int id)¶ hasEvidence(LoopyGibbsSampling self, str nodeName) -> bool
Parameters: - id (int) – a node Id
- nodeName (str) – a node name
Returns: True if some node(s) (or the one in parameters) have received evidence
Return type: bool
Raises: gum.IndexError
– If the node does not belong to the Bayesian network
-
hasHardEvidence
(LoopyGibbsSampling self, str nodeName)¶ Parameters: - id (int) – a node Id
- nodeName (str) – a node name
Returns: True if node has received a hard evidence
Return type: bool
Raises: gum.IndexError
– If the node does not belong to the Bayesian network
-
hasSoftEvidence
(LoopyGibbsSampling self, int id)¶ hasSoftEvidence(LoopyGibbsSampling self, str nodeName) -> bool
Parameters: - id (int) – a node Id
- nodeName (str) – a node name
Returns: True if node has received a soft evidence
Return type: bool
Raises: gum.IndexError
– If the node does not belong to the Bayesian network
-
history
(LoopyGibbsSampling self)¶ Returns: the scheme history Return type: tuple Raises: gum.OperationNotAllowed
– If the scheme did not performed or if verbosity is set to false
-
isDrawnAtRandom
(LoopyGibbsSampling self)¶ Returns: True if variables are drawn at random Return type: bool
-
isTarget
(LoopyGibbsSampling self, int variable)¶ isTarget(LoopyGibbsSampling self, str nodeName) -> bool
Parameters: - variable (int) – a node Id
- nodeName (str) – a node name
Returns: True if variable is a (marginal) target
Return type: bool
Raises: gum.IndexError
– If the node does not belong to the Bayesian networkgum.UndefinedElement
– If node Id is not in the Bayesian network
-
makeInference
(LoopyGibbsSampling self)¶ Perform the heavy computations needed to compute the targets’ posteriors
In a Junction tree propagation scheme, for instance, the heavy computations are those of the messages sent in the JT. This is precisely what makeInference should compute. Later, the computations of the posteriors can be done ‘lightly’ by multiplying and projecting those messages.
-
maxIter
(LoopyGibbsSampling self)¶ Returns: the criterion on number of iterations Return type: int
-
maxTime
(LoopyGibbsSampling self)¶ Returns: the timeout(in seconds) Return type: double
-
messageApproximationScheme
(LoopyGibbsSampling self)¶ Returns: the approximation scheme message Return type: str
-
minEpsilonRate
(LoopyGibbsSampling self)¶ Returns: the value of the minimal epsilon rate Return type: double
-
nbrDrawnVar
(LoopyGibbsSampling self)¶ Returns: the number of variable drawn at each iteration Return type: int
-
nbrEvidence
(LoopyGibbsSampling self)¶ Returns: the number of evidence entered into the Bayesian network Return type: int
-
nbrHardEvidence
(LoopyGibbsSampling self)¶ Returns: the number of hard evidence entered into the Bayesian network Return type: int
-
nbrIterations
(LoopyGibbsSampling self)¶ Returns: the number of iterations Return type: int
-
nbrSoftEvidence
(LoopyGibbsSampling self)¶ Returns: the number of soft evidence entered into the Bayesian network Return type: int
-
nbrTargets
(LoopyGibbsSampling self)¶ Returns: the number of marginal targets Return type: int
-
periodSize
(LoopyGibbsSampling self)¶ Returns: the number of samples between 2 stopping Return type: int Raises: gum.OutOfLowerBound
– If p<1
-
posterior
(LoopyGibbsSampling self, int var)¶ posterior(LoopyGibbsSampling self, str nodeName) -> Potential
Computes and returns the posterior of a node.
Parameters: - var (int) – the node Id of the node for which we need a posterior probability
- nodeName (str) – the node name of the node for which we need a posterior probability
Returns: a ref to the posterior probability of the node
Return type: Raises: gum.UndefinedElement
– If an element of nodes is not in targets
-
setBurnIn
(LoopyGibbsSampling self, int b)¶ Parameters: b (int) – size of burn in on number of iteration
-
setDrawnAtRandom
(LoopyGibbsSampling self, bool _atRandom)¶ Parameters: _atRandom (bool) – indicates if variables should be drawn at random
-
setEpsilon
(LoopyGibbsSampling self, double eps)¶ Parameters: eps (double) – the epsilon we want to use Raises: gum.OutOfLowerBound
– If eps<0
-
setEvidence
(evidces)¶ Erase all the evidences and apply addEvidence(key,value) for every pairs in evidces.
Parameters: evidces (dict) – a dict of evidences
Raises: gum.InvalidArgument
– If one value is not a value for the nodegum.InvalidArgument
– If the size of a value is different from the domain side of the nodegum.FatalError
– If one value is a vector of 0sgum.UndefinedElement
– If one node does not belong to the Bayesian network
-
setMaxIter
(LoopyGibbsSampling self, int max)¶ Parameters: max (int) – the maximum number of iteration Raises: gum.OutOfLowerBound
– If max <= 1
-
setMaxTime
(LoopyGibbsSampling self, double timeout)¶ Parameters: tiemout (double) – stopping criterion on timeout (in seconds) Raises: gum.OutOfLowerBound
– If timeout<=0.0
-
setMinEpsilonRate
(LoopyGibbsSampling self, double rate)¶ Parameters: rate (double) – the minimal epsilon rate
-
setNbrDrawnVar
(LoopyGibbsSampling self, int _nbr)¶ Parameters: _nbr (int) – the number of variables to be drawn at each iteration
-
setPeriodSize
(LoopyGibbsSampling self, int p)¶ Parameters: p (int) – number of samples between 2 stopping Raises: gum.OutOfLowerBound
– If p<1
-
setTargets
(targets)¶ Remove all the targets and add the ones in parameter.
Parameters: targets (set) – a set of targets Raises: gum.UndefinedElement
– If one target is not in the Bayes net
-
setVerbosity
(LoopyGibbsSampling self, bool v)¶ Parameters: v (bool) – verbosity
-
setVirtualLBPSize
(LoopyGibbsSampling self, double vlbpsize)¶ Parameters: vlbpsize (double) – the size of the virtual LBP
-
softEvidenceNodes
(LoopyGibbsSampling self)¶ Returns: the set of nodes with soft evidence Return type: set
-
targets
(LoopyGibbsSampling self)¶ Returns: the list of marginal targets Return type: list
-
thisown
¶ The membership flag
-
updateEvidence
(evidces)¶ Apply chgEvidence(key,value) for every pairs in evidces (or addEvidence).
Parameters: evidces (dict) – a dict of evidences
Raises: gum.InvalidArgument
– If one value is not a value for the nodegum.InvalidArgument
– If the size of a value is different from the domain side of the nodegum.FatalError
– If one value is a vector of 0sgum.UndefinedElement
– If one node does not belong to the Bayesian network
-
verbosity
(LoopyGibbsSampling self)¶ Returns: True if the verbosity is enabled Return type: bool
Loopy Monte Carlo Sampling¶
-
class
pyAgrum.
LoopyMonteCarloSampling
(bn: pyAgrum.pyAgrum.IBayesNet)¶ Proxy of C++ pyAgrum.LoopySamplingInference< double,pyAgrum.MonteCarloSampling > class.
-
BN
(LoopyMonteCarloSampling self)¶ Returns: A ant reference over the IBayesNet referenced by this class. Return type: pyAgrum.IBayesNet Raises: gum.UndefinedElement
– If no Bayes net has been assigned to the inference.
-
H
(LoopyMonteCarloSampling self, int X)¶ H(LoopyMonteCarloSampling self, str nodeName) -> double
Parameters: - X (int) – a node Id
- nodeName (str) – a node name
Returns: the computed Shanon’s entropy of a node given the observation
Return type: double
-
addAllTargets
(LoopyMonteCarloSampling self)¶ Add all the nodes as targets.
-
addEvidence
(LoopyMonteCarloSampling self, int id, int val)¶ addEvidence(LoopyMonteCarloSampling self, str nodeName, int val) addEvidence(LoopyMonteCarloSampling self, int id, str val) addEvidence(LoopyMonteCarloSampling self, str nodeName, str val) addEvidence(LoopyMonteCarloSampling self, int id, Vector vals) addEvidence(LoopyMonteCarloSampling self, str nodeName, Vector vals)
Adds a new evidence on a node (might be soft or hard).
Parameters: - id (int) – a node Id
- nodeName (int) – a node name
- val – (int) a node value
- val – (str) the label of the node value
- vals (list) – a list of values
Raises: gum.InvalidArgument
– If the node already has an evidencegum.InvalidArgument
– If val is not a value for the nodegum.InvalidArgument
– If the size of vals is different from the domain side of the nodegum.FatalError
– If vals is a vector of 0sgum.UndefinedElement
– If the node does not belong to the Bayesian network
-
addTarget
(LoopyMonteCarloSampling self, int target)¶ addTarget(LoopyMonteCarloSampling self, str nodeName)
Add a marginal target to the list of targets.
Parameters: - target (int) – a node Id
- nodeName (str) – a node name
Raises: gum.UndefinedElement
– If target is not a NodeId in the Bayes net
-
chgEvidence
(LoopyMonteCarloSampling self, int id, int val)¶ chgEvidence(LoopyMonteCarloSampling self, str nodeName, int val) chgEvidence(LoopyMonteCarloSampling self, int id, str val) chgEvidence(LoopyMonteCarloSampling self, str nodeName, str val) chgEvidence(LoopyMonteCarloSampling self, int id, Vector vals) chgEvidence(LoopyMonteCarloSampling self, str nodeName, Vector vals)
Change the value of an already existing evidence on a node (might be soft or hard).
Parameters: - id (int) – a node Id
- nodeName (int) – a node name
- val – (int) a node value
- val – (str) the label of the node value
- vals (list) – a list of values
Raises: gum.InvalidArgument
– If the node does not already have an evidencegum.InvalidArgument
– If val is not a value for the nodegum.InvalidArgument
– If the size of vals is different from the domain side of the nodegum.FatalError
– If vals is a vector of 0sgum.UndefinedElement
– If the node does not belong to the Bayesian network
-
currentPosterior
(LoopyMonteCarloSampling self, int id)¶ currentPosterior(LoopyMonteCarloSampling self, str name) -> Potential
Computes and returns the current posterior of a node.
Parameters: - var (int) – the node Id of the node for which we need a posterior probability
- nodeName (str) – the node name of the node for which we need a posterior probability
Returns: a ref to the current posterior probability of the node
Return type: Raises: UndefinedElement
– If an element of nodes is not in targets
-
currentTime
(LoopyMonteCarloSampling self)¶ Returns: get the current running time in second (double) Return type: double
-
epsilon
(LoopyMonteCarloSampling self)¶ Returns: the value of epsilon Return type: double
-
eraseAllEvidence
(LoopyMonteCarloSampling self)¶ Removes all the evidence entered into the network.
-
eraseAllTargets
(LoopyMonteCarloSampling self)¶ Clear all previously defined targets (marginal and joint targets).
As a result, no posterior can be computed (since we can only compute the posteriors of the marginal or joint targets that have been added by the user).
-
eraseEvidence
(LoopyMonteCarloSampling self, int id)¶ eraseEvidence(LoopyMonteCarloSampling self, str nodeName)
Remove the evidence, if any, corresponding to the node Id or name.
Parameters: - id (int) – a node Id
- nodeName (int) – a node name
Raises: gum.IndexError
– If the node does not belong to the Bayesian network
-
eraseTarget
(LoopyMonteCarloSampling self, int target)¶ eraseTarget(LoopyMonteCarloSampling self, str nodeName)
Remove, if existing, the marginal target.
Parameters: - target (int) – a node Id
- nodeName (int) – a node name
Raises: gum.IndexError
– If one of the node does not belong to the Bayesian networkgum.UndefinedElement
– If node Id is not in the Bayesian network
-
evidenceImpact
(LoopyMonteCarloSampling self, int target, PyObject * evs)¶ evidenceImpact(LoopyMonteCarloSampling self, str target, Vector_string evs) -> Potential
Create a pyAgrum.Potential for P(target|evs) (for all instanciation of target and evs)
Parameters: - target (set) – a set of targets ids or names.
- evs (set) – a set of nodes ids or names.
Warning
if some evs are d-separated, they are not included in the Potential.
Returns: a Potential for P(targets|evs) Return type: pyAgrum.Potential
-
hardEvidenceNodes
(LoopyMonteCarloSampling self)¶ Returns: the set of nodes with hard evidence Return type: set
-
hasEvidence
(LoopyMonteCarloSampling self, int id)¶ hasEvidence(LoopyMonteCarloSampling self, str nodeName) -> bool
Parameters: - id (int) – a node Id
- nodeName (str) – a node name
Returns: True if some node(s) (or the one in parameters) have received evidence
Return type: bool
Raises: gum.IndexError
– If the node does not belong to the Bayesian network
-
hasHardEvidence
(LoopyMonteCarloSampling self, str nodeName)¶ Parameters: - id (int) – a node Id
- nodeName (str) – a node name
Returns: True if node has received a hard evidence
Return type: bool
Raises: gum.IndexError
– If the node does not belong to the Bayesian network
-
hasSoftEvidence
(LoopyMonteCarloSampling self, int id)¶ hasSoftEvidence(LoopyMonteCarloSampling self, str nodeName) -> bool
Parameters: - id (int) – a node Id
- nodeName (str) – a node name
Returns: True if node has received a soft evidence
Return type: bool
Raises: gum.IndexError
– If the node does not belong to the Bayesian network
-
history
(LoopyMonteCarloSampling self)¶ Returns: the scheme history Return type: tuple Raises: gum.OperationNotAllowed
– If the scheme did not performed or if verbosity is set to false
-
isTarget
(LoopyMonteCarloSampling self, int variable)¶ isTarget(LoopyMonteCarloSampling self, str nodeName) -> bool
Parameters: - variable (int) – a node Id
- nodeName (str) – a node name
Returns: True if variable is a (marginal) target
Return type: bool
Raises: gum.IndexError
– If the node does not belong to the Bayesian networkgum.UndefinedElement
– If node Id is not in the Bayesian network
-
makeInference
(LoopyMonteCarloSampling self)¶ Perform the heavy computations needed to compute the targets’ posteriors
In a Junction tree propagation scheme, for instance, the heavy computations are those of the messages sent in the JT. This is precisely what makeInference should compute. Later, the computations of the posteriors can be done ‘lightly’ by multiplying and projecting those messages.
-
maxIter
(LoopyMonteCarloSampling self)¶ Returns: the criterion on number of iterations Return type: int
-
maxTime
(LoopyMonteCarloSampling self)¶ Returns: the timeout(in seconds) Return type: double
-
messageApproximationScheme
(LoopyMonteCarloSampling self)¶ Returns: the approximation scheme message Return type: str
-
minEpsilonRate
(LoopyMonteCarloSampling self)¶ Returns: the value of the minimal epsilon rate Return type: double
-
nbrEvidence
(LoopyMonteCarloSampling self)¶ Returns: the number of evidence entered into the Bayesian network Return type: int
-
nbrHardEvidence
(LoopyMonteCarloSampling self)¶ Returns: the number of hard evidence entered into the Bayesian network Return type: int
-
nbrIterations
(LoopyMonteCarloSampling self)¶ Returns: the number of iterations Return type: int
-
nbrSoftEvidence
(LoopyMonteCarloSampling self)¶ Returns: the number of soft evidence entered into the Bayesian network Return type: int
-
nbrTargets
(LoopyMonteCarloSampling self)¶ Returns: the number of marginal targets Return type: int
-
periodSize
(LoopyMonteCarloSampling self)¶ Returns: the number of samples between 2 stopping Return type: int Raises: gum.OutOfLowerBound
– If p<1
-
posterior
(LoopyMonteCarloSampling self, int var)¶ posterior(LoopyMonteCarloSampling self, str nodeName) -> Potential
Computes and returns the posterior of a node.
Parameters: - var (int) – the node Id of the node for which we need a posterior probability
- nodeName (str) – the node name of the node for which we need a posterior probability
Returns: a ref to the posterior probability of the node
Return type: Raises: gum.UndefinedElement
– If an element of nodes is not in targets
-
setEpsilon
(LoopyMonteCarloSampling self, double eps)¶ Parameters: eps (double) – the epsilon we want to use Raises: gum.OutOfLowerBound
– If eps<0
-
setEvidence
(evidces)¶ Erase all the evidences and apply addEvidence(key,value) for every pairs in evidces.
Parameters: evidces (dict) – a dict of evidences
Raises: gum.InvalidArgument
– If one value is not a value for the nodegum.InvalidArgument
– If the size of a value is different from the domain side of the nodegum.FatalError
– If one value is a vector of 0sgum.UndefinedElement
– If one node does not belong to the Bayesian network
-
setMaxIter
(LoopyMonteCarloSampling self, int max)¶ Parameters: max (int) – the maximum number of iteration Raises: gum.OutOfLowerBound
– If max <= 1
-
setMaxTime
(LoopyMonteCarloSampling self, double timeout)¶ Parameters: tiemout (double) – stopping criterion on timeout (in seconds) Raises: gum.OutOfLowerBound
– If timeout<=0.0
-
setMinEpsilonRate
(LoopyMonteCarloSampling self, double rate)¶ Parameters: rate (double) – the minimal epsilon rate
-
setPeriodSize
(LoopyMonteCarloSampling self, int p)¶ Parameters: p (int) – number of samples between 2 stopping Raises: gum.OutOfLowerBound
– If p<1
-
setTargets
(targets)¶ Remove all the targets and add the ones in parameter.
Parameters: targets (set) – a set of targets Raises: gum.UndefinedElement
– If one target is not in the Bayes net
-
setVerbosity
(LoopyMonteCarloSampling self, bool v)¶ Parameters: v (bool) – verbosity
-
setVirtualLBPSize
(LoopyMonteCarloSampling self, double vlbpsize)¶ Parameters: vlbpsize (double) – the size of the virtual LBP
-
softEvidenceNodes
(LoopyMonteCarloSampling self)¶ Returns: the set of nodes with soft evidence Return type: set
-
targets
(LoopyMonteCarloSampling self)¶ Returns: the list of marginal targets Return type: list
-
thisown
¶ The membership flag
-
updateEvidence
(evidces)¶ Apply chgEvidence(key,value) for every pairs in evidces (or addEvidence).
Parameters: evidces (dict) – a dict of evidences
Raises: gum.InvalidArgument
– If one value is not a value for the nodegum.InvalidArgument
– If the size of a value is different from the domain side of the nodegum.FatalError
– If one value is a vector of 0sgum.UndefinedElement
– If one node does not belong to the Bayesian network
-
verbosity
(LoopyMonteCarloSampling self)¶ Returns: True if the verbosity is enabled Return type: bool
-
Loopy Weighted Sampling¶
-
class
pyAgrum.
LoopyWeightedSampling
(bn: pyAgrum.pyAgrum.IBayesNet)¶ Class used for inferences using a loopy version of weighted sampling.
- Available ructors:
LoopyWeightedSampling(bn) -> LoopyWeightedSampling
Parameters: bn (pyAgrum.BayesNet) – a Bayesian network -
BN
(LoopyWeightedSampling self)¶ Returns: A ant reference over the IBayesNet referenced by this class. Return type: pyAgrum.IBayesNet Raises: gum.UndefinedElement
– If no Bayes net has been assigned to the inference.
-
H
(LoopyWeightedSampling self, int X)¶ H(LoopyWeightedSampling self, str nodeName) -> double
Parameters: - X (int) – a node Id
- nodeName (str) – a node name
Returns: the computed Shanon’s entropy of a node given the observation
Return type: double
-
addAllTargets
(LoopyWeightedSampling self)¶ Add all the nodes as targets.
-
addEvidence
(LoopyWeightedSampling self, int id, int val)¶ addEvidence(LoopyWeightedSampling self, str nodeName, int val) addEvidence(LoopyWeightedSampling self, int id, str val) addEvidence(LoopyWeightedSampling self, str nodeName, str val) addEvidence(LoopyWeightedSampling self, int id, Vector vals) addEvidence(LoopyWeightedSampling self, str nodeName, Vector vals)
Adds a new evidence on a node (might be soft or hard).
Parameters: - id (int) – a node Id
- nodeName (int) – a node name
- val – (int) a node value
- val – (str) the label of the node value
- vals (list) – a list of values
Raises: gum.InvalidArgument
– If the node already has an evidencegum.InvalidArgument
– If val is not a value for the nodegum.InvalidArgument
– If the size of vals is different from the domain side of the nodegum.FatalError
– If vals is a vector of 0sgum.UndefinedElement
– If the node does not belong to the Bayesian network
-
addTarget
(LoopyWeightedSampling self, int target)¶ addTarget(LoopyWeightedSampling self, str nodeName)
Add a marginal target to the list of targets.
Parameters: - target (int) – a node Id
- nodeName (str) – a node name
Raises: gum.UndefinedElement
– If target is not a NodeId in the Bayes net
-
chgEvidence
(LoopyWeightedSampling self, int id, int val)¶ chgEvidence(LoopyWeightedSampling self, str nodeName, int val) chgEvidence(LoopyWeightedSampling self, int id, str val) chgEvidence(LoopyWeightedSampling self, str nodeName, str val) chgEvidence(LoopyWeightedSampling self, int id, Vector vals) chgEvidence(LoopyWeightedSampling self, str nodeName, Vector vals)
Change the value of an already existing evidence on a node (might be soft or hard).
Parameters: - id (int) – a node Id
- nodeName (int) – a node name
- val – (int) a node value
- val – (str) the label of the node value
- vals (list) – a list of values
Raises: gum.InvalidArgument
– If the node does not already have an evidencegum.InvalidArgument
– If val is not a value for the nodegum.InvalidArgument
– If the size of vals is different from the domain side of the nodegum.FatalError
– If vals is a vector of 0sgum.UndefinedElement
– If the node does not belong to the Bayesian network
-
currentPosterior
(LoopyWeightedSampling self, int id)¶ currentPosterior(LoopyWeightedSampling self, str name) -> Potential
Computes and returns the current posterior of a node.
Parameters: - var (int) – the node Id of the node for which we need a posterior probability
- nodeName (str) – the node name of the node for which we need a posterior probability
Returns: a ref to the current posterior probability of the node
Return type: Raises: UndefinedElement
– If an element of nodes is not in targets
-
currentTime
(LoopyWeightedSampling self)¶ Returns: get the current running time in second (double) Return type: double
-
epsilon
(LoopyWeightedSampling self)¶ Returns: the value of epsilon Return type: double
-
eraseAllEvidence
(LoopyWeightedSampling self)¶ Removes all the evidence entered into the network.
-
eraseAllTargets
(LoopyWeightedSampling self)¶ Clear all previously defined targets (marginal and joint targets).
As a result, no posterior can be computed (since we can only compute the posteriors of the marginal or joint targets that have been added by the user).
-
eraseEvidence
(LoopyWeightedSampling self, int id)¶ eraseEvidence(LoopyWeightedSampling self, str nodeName)
Remove the evidence, if any, corresponding to the node Id or name.
Parameters: - id (int) – a node Id
- nodeName (int) – a node name
Raises: gum.IndexError
– If the node does not belong to the Bayesian network
-
eraseTarget
(LoopyWeightedSampling self, int target)¶ eraseTarget(LoopyWeightedSampling self, str nodeName)
Remove, if existing, the marginal target.
Parameters: - target (int) – a node Id
- nodeName (int) – a node name
Raises: gum.IndexError
– If one of the node does not belong to the Bayesian networkgum.UndefinedElement
– If node Id is not in the Bayesian network
-
evidenceImpact
(LoopyWeightedSampling self, int target, PyObject * evs)¶ evidenceImpact(LoopyWeightedSampling self, str target, Vector_string evs) -> Potential
Create a pyAgrum.Potential for P(target|evs) (for all instanciation of target and evs)
Parameters: - target (set) – a set of targets ids or names.
- evs (set) – a set of nodes ids or names.
Warning
if some evs are d-separated, they are not included in the Potential.
Returns: a Potential for P(targets|evs) Return type: pyAgrum.Potential
-
hardEvidenceNodes
(LoopyWeightedSampling self)¶ Returns: the set of nodes with hard evidence Return type: set
-
hasEvidence
(LoopyWeightedSampling self, int id)¶ hasEvidence(LoopyWeightedSampling self, str nodeName) -> bool
Parameters: - id (int) – a node Id
- nodeName (str) – a node name
Returns: True if some node(s) (or the one in parameters) have received evidence
Return type: bool
Raises: gum.IndexError
– If the node does not belong to the Bayesian network
-
hasHardEvidence
(LoopyWeightedSampling self, str nodeName)¶ Parameters: - id (int) – a node Id
- nodeName (str) – a node name
Returns: True if node has received a hard evidence
Return type: bool
Raises: gum.IndexError
– If the node does not belong to the Bayesian network
-
hasSoftEvidence
(LoopyWeightedSampling self, int id)¶ hasSoftEvidence(LoopyWeightedSampling self, str nodeName) -> bool
Parameters: - id (int) – a node Id
- nodeName (str) – a node name
Returns: True if node has received a soft evidence
Return type: bool
Raises: gum.IndexError
– If the node does not belong to the Bayesian network
-
history
(LoopyWeightedSampling self)¶ Returns: the scheme history Return type: tuple Raises: gum.OperationNotAllowed
– If the scheme did not performed or if verbosity is set to false
-
isTarget
(LoopyWeightedSampling self, int variable)¶ isTarget(LoopyWeightedSampling self, str nodeName) -> bool
Parameters: - variable (int) – a node Id
- nodeName (str) – a node name
Returns: True if variable is a (marginal) target
Return type: bool
Raises: gum.IndexError
– If the node does not belong to the Bayesian networkgum.UndefinedElement
– If node Id is not in the Bayesian network
-
makeInference
(LoopyWeightedSampling self)¶ Perform the heavy computations needed to compute the targets’ posteriors
In a Junction tree propagation scheme, for instance, the heavy computations are those of the messages sent in the JT. This is precisely what makeInference should compute. Later, the computations of the posteriors can be done ‘lightly’ by multiplying and projecting those messages.
-
maxIter
(LoopyWeightedSampling self)¶ Returns: the criterion on number of iterations Return type: int
-
maxTime
(LoopyWeightedSampling self)¶ Returns: the timeout(in seconds) Return type: double
-
messageApproximationScheme
(LoopyWeightedSampling self)¶ Returns: the approximation scheme message Return type: str
-
minEpsilonRate
(LoopyWeightedSampling self)¶ Returns: the value of the minimal epsilon rate Return type: double
-
nbrEvidence
(LoopyWeightedSampling self)¶ Returns: the number of evidence entered into the Bayesian network Return type: int
-
nbrHardEvidence
(LoopyWeightedSampling self)¶ Returns: the number of hard evidence entered into the Bayesian network Return type: int
-
nbrIterations
(LoopyWeightedSampling self)¶ Returns: the number of iterations Return type: int
-
nbrSoftEvidence
(LoopyWeightedSampling self)¶ Returns: the number of soft evidence entered into the Bayesian network Return type: int
-
nbrTargets
(LoopyWeightedSampling self)¶ Returns: the number of marginal targets Return type: int
-
periodSize
(LoopyWeightedSampling self)¶ Returns: the number of samples between 2 stopping Return type: int Raises: gum.OutOfLowerBound
– If p<1
-
posterior
(LoopyWeightedSampling self, int var)¶ posterior(LoopyWeightedSampling self, str nodeName) -> Potential
Computes and returns the posterior of a node.
Parameters: - var (int) – the node Id of the node for which we need a posterior probability
- nodeName (str) – the node name of the node for which we need a posterior probability
Returns: a ref to the posterior probability of the node
Return type: Raises: gum.UndefinedElement
– If an element of nodes is not in targets
-
setEpsilon
(LoopyWeightedSampling self, double eps)¶ Parameters: eps (double) – the epsilon we want to use Raises: gum.OutOfLowerBound
– If eps<0
-
setEvidence
(evidces)¶ Erase all the evidences and apply addEvidence(key,value) for every pairs in evidces.
Parameters: evidces (dict) – a dict of evidences
Raises: gum.InvalidArgument
– If one value is not a value for the nodegum.InvalidArgument
– If the size of a value is different from the domain side of the nodegum.FatalError
– If one value is a vector of 0sgum.UndefinedElement
– If one node does not belong to the Bayesian network
-
setMaxIter
(LoopyWeightedSampling self, int max)¶ Parameters: max (int) – the maximum number of iteration Raises: gum.OutOfLowerBound
– If max <= 1
-
setMaxTime
(LoopyWeightedSampling self, double timeout)¶ Parameters: tiemout (double) – stopping criterion on timeout (in seconds) Raises: gum.OutOfLowerBound
– If timeout<=0.0
-
setMinEpsilonRate
(LoopyWeightedSampling self, double rate)¶ Parameters: rate (double) – the minimal epsilon rate
-
setPeriodSize
(LoopyWeightedSampling self, int p)¶ Parameters: p (int) – number of samples between 2 stopping Raises: gum.OutOfLowerBound
– If p<1
-
setTargets
(targets)¶ Remove all the targets and add the ones in parameter.
Parameters: targets (set) – a set of targets Raises: gum.UndefinedElement
– If one target is not in the Bayes net
-
setVerbosity
(LoopyWeightedSampling self, bool v)¶ Parameters: v (bool) – verbosity
-
setVirtualLBPSize
(LoopyWeightedSampling self, double vlbpsize)¶ Parameters: vlbpsize (double) – the size of the virtual LBP
-
softEvidenceNodes
(LoopyWeightedSampling self)¶ Returns: the set of nodes with soft evidence Return type: set
-
targets
(LoopyWeightedSampling self)¶ Returns: the list of marginal targets Return type: list
-
thisown
¶ The membership flag
-
updateEvidence
(evidces)¶ Apply chgEvidence(key,value) for every pairs in evidces (or addEvidence).
Parameters: evidces (dict) – a dict of evidences
Raises: gum.InvalidArgument
– If one value is not a value for the nodegum.InvalidArgument
– If the size of a value is different from the domain side of the nodegum.FatalError
– If one value is a vector of 0sgum.UndefinedElement
– If one node does not belong to the Bayesian network
-
verbosity
(LoopyWeightedSampling self)¶ Returns: True if the verbosity is enabled Return type: bool
Loopy Importance Sampling¶
-
class
pyAgrum.
LoopyImportanceSampling
(bn: pyAgrum.pyAgrum.IBayesNet)¶ Class used for inferences using a loopy version of importance sampling.
- Available ructors:
LoopyImportanceSampling(bn) -> LoopyImportanceSampling
Parameters: bn (pyAgrum.BayesNet) – a Bayesian network -
BN
(LoopyImportanceSampling self)¶ Returns: A ant reference over the IBayesNet referenced by this class. Return type: pyAgrum.IBayesNet Raises: gum.UndefinedElement
– If no Bayes net has been assigned to the inference.
-
H
(LoopyImportanceSampling self, int X)¶ H(LoopyImportanceSampling self, str nodeName) -> double
Parameters: - X (int) – a node Id
- nodeName (str) – a node name
Returns: the computed Shanon’s entropy of a node given the observation
Return type: double
-
addAllTargets
(LoopyImportanceSampling self)¶ Add all the nodes as targets.
-
addEvidence
(LoopyImportanceSampling self, int id, int val)¶ addEvidence(LoopyImportanceSampling self, str nodeName, int val) addEvidence(LoopyImportanceSampling self, int id, str val) addEvidence(LoopyImportanceSampling self, str nodeName, str val) addEvidence(LoopyImportanceSampling self, int id, Vector vals) addEvidence(LoopyImportanceSampling self, str nodeName, Vector vals)
Adds a new evidence on a node (might be soft or hard).
Parameters: - id (int) – a node Id
- nodeName (int) – a node name
- val – (int) a node value
- val – (str) the label of the node value
- vals (list) – a list of values
Raises: gum.InvalidArgument
– If the node already has an evidencegum.InvalidArgument
– If val is not a value for the nodegum.InvalidArgument
– If the size of vals is different from the domain side of the nodegum.FatalError
– If vals is a vector of 0sgum.UndefinedElement
– If the node does not belong to the Bayesian network
-
addTarget
(LoopyImportanceSampling self, int target)¶ addTarget(LoopyImportanceSampling self, str nodeName)
Add a marginal target to the list of targets.
Parameters: - target (int) – a node Id
- nodeName (str) – a node name
Raises: gum.UndefinedElement
– If target is not a NodeId in the Bayes net
-
chgEvidence
(LoopyImportanceSampling self, int id, int val)¶ chgEvidence(LoopyImportanceSampling self, str nodeName, int val) chgEvidence(LoopyImportanceSampling self, int id, str val) chgEvidence(LoopyImportanceSampling self, str nodeName, str val) chgEvidence(LoopyImportanceSampling self, int id, Vector vals) chgEvidence(LoopyImportanceSampling self, str nodeName, Vector vals)
Change the value of an already existing evidence on a node (might be soft or hard).
Parameters: - id (int) – a node Id
- nodeName (int) – a node name
- val – (int) a node value
- val – (str) the label of the node value
- vals (list) – a list of values
Raises: gum.InvalidArgument
– If the node does not already have an evidencegum.InvalidArgument
– If val is not a value for the nodegum.InvalidArgument
– If the size of vals is different from the domain side of the nodegum.FatalError
– If vals is a vector of 0sgum.UndefinedElement
– If the node does not belong to the Bayesian network
-
currentPosterior
(LoopyImportanceSampling self, int id)¶ currentPosterior(LoopyImportanceSampling self, str name) -> Potential
Computes and returns the current posterior of a node.
Parameters: - var (int) – the node Id of the node for which we need a posterior probability
- nodeName (str) – the node name of the node for which we need a posterior probability
Returns: a ref to the current posterior probability of the node
Return type: Raises: UndefinedElement
– If an element of nodes is not in targets
-
currentTime
(LoopyImportanceSampling self)¶ Returns: get the current running time in second (double) Return type: double
-
epsilon
(LoopyImportanceSampling self)¶ Returns: the value of epsilon Return type: double
-
eraseAllEvidence
(LoopyImportanceSampling self)¶ Removes all the evidence entered into the network.
-
eraseAllTargets
(LoopyImportanceSampling self)¶ Clear all previously defined targets (marginal and joint targets).
As a result, no posterior can be computed (since we can only compute the posteriors of the marginal or joint targets that have been added by the user).
-
eraseEvidence
(LoopyImportanceSampling self, int id)¶ eraseEvidence(LoopyImportanceSampling self, str nodeName)
Remove the evidence, if any, corresponding to the node Id or name.
Parameters: - id (int) – a node Id
- nodeName (int) – a node name
Raises: gum.IndexError
– If the node does not belong to the Bayesian network
-
eraseTarget
(LoopyImportanceSampling self, int target)¶ eraseTarget(LoopyImportanceSampling self, str nodeName)
Remove, if existing, the marginal target.
Parameters: - target (int) – a node Id
- nodeName (int) – a node name
Raises: gum.IndexError
– If one of the node does not belong to the Bayesian networkgum.UndefinedElement
– If node Id is not in the Bayesian network
-
evidenceImpact
(LoopyImportanceSampling self, int target, PyObject * evs)¶ evidenceImpact(LoopyImportanceSampling self, str target, Vector_string evs) -> Potential
Create a pyAgrum.Potential for P(target|evs) (for all instanciation of target and evs)
Parameters: - target (set) – a set of targets ids or names.
- evs (set) – a set of nodes ids or names.
Warning
if some evs are d-separated, they are not included in the Potential.
Returns: a Potential for P(targets|evs) Return type: pyAgrum.Potential
-
hardEvidenceNodes
(LoopyImportanceSampling self)¶ Returns: the set of nodes with hard evidence Return type: set
-
hasEvidence
(LoopyImportanceSampling self, int id)¶ hasEvidence(LoopyImportanceSampling self, str nodeName) -> bool
Parameters: - id (int) – a node Id
- nodeName (str) – a node name
Returns: True if some node(s) (or the one in parameters) have received evidence
Return type: bool
Raises: gum.IndexError
– If the node does not belong to the Bayesian network
-
hasHardEvidence
(LoopyImportanceSampling self, str nodeName)¶ Parameters: - id (int) – a node Id
- nodeName (str) – a node name
Returns: True if node has received a hard evidence
Return type: bool
Raises: gum.IndexError
– If the node does not belong to the Bayesian network
-
hasSoftEvidence
(LoopyImportanceSampling self, int id)¶ hasSoftEvidence(LoopyImportanceSampling self, str nodeName) -> bool
Parameters: - id (int) – a node Id
- nodeName (str) – a node name
Returns: True if node has received a soft evidence
Return type: bool
Raises: gum.IndexError
– If the node does not belong to the Bayesian network
-
history
(LoopyImportanceSampling self)¶ Returns: the scheme history Return type: tuple Raises: gum.OperationNotAllowed
– If the scheme did not performed or if verbosity is set to false
-
isTarget
(LoopyImportanceSampling self, int variable)¶ isTarget(LoopyImportanceSampling self, str nodeName) -> bool
Parameters: - variable (int) – a node Id
- nodeName (str) – a node name
Returns: True if variable is a (marginal) target
Return type: bool
Raises: gum.IndexError
– If the node does not belong to the Bayesian networkgum.UndefinedElement
– If node Id is not in the Bayesian network
-
makeInference
(LoopyImportanceSampling self)¶ Perform the heavy computations needed to compute the targets’ posteriors
In a Junction tree propagation scheme, for instance, the heavy computations are those of the messages sent in the JT. This is precisely what makeInference should compute. Later, the computations of the posteriors can be done ‘lightly’ by multiplying and projecting those messages.
-
maxIter
(LoopyImportanceSampling self)¶ Returns: the criterion on number of iterations Return type: int
-
maxTime
(LoopyImportanceSampling self)¶ Returns: the timeout(in seconds) Return type: double
-
messageApproximationScheme
(LoopyImportanceSampling self)¶ Returns: the approximation scheme message Return type: str
-
minEpsilonRate
(LoopyImportanceSampling self)¶ Returns: the value of the minimal epsilon rate Return type: double
-
nbrEvidence
(LoopyImportanceSampling self)¶ Returns: the number of evidence entered into the Bayesian network Return type: int
-
nbrHardEvidence
(LoopyImportanceSampling self)¶ Returns: the number of hard evidence entered into the Bayesian network Return type: int
-
nbrIterations
(LoopyImportanceSampling self)¶ Returns: the number of iterations Return type: int
-
nbrSoftEvidence
(LoopyImportanceSampling self)¶ Returns: the number of soft evidence entered into the Bayesian network Return type: int
-
nbrTargets
(LoopyImportanceSampling self)¶ Returns: the number of marginal targets Return type: int
-
periodSize
(LoopyImportanceSampling self)¶ Returns: the number of samples between 2 stopping Return type: int Raises: gum.OutOfLowerBound
– If p<1
-
posterior
(LoopyImportanceSampling self, int var)¶ posterior(LoopyImportanceSampling self, str nodeName) -> Potential
Computes and returns the posterior of a node.
Parameters: - var (int) – the node Id of the node for which we need a posterior probability
- nodeName (str) – the node name of the node for which we need a posterior probability
Returns: a ref to the posterior probability of the node
Return type: Raises: gum.UndefinedElement
– If an element of nodes is not in targets
-
setEpsilon
(LoopyImportanceSampling self, double eps)¶ Parameters: eps (double) – the epsilon we want to use Raises: gum.OutOfLowerBound
– If eps<0
-
setEvidence
(evidces)¶ Erase all the evidences and apply addEvidence(key,value) for every pairs in evidces.
Parameters: evidces (dict) – a dict of evidences
Raises: gum.InvalidArgument
– If one value is not a value for the nodegum.InvalidArgument
– If the size of a value is different from the domain side of the nodegum.FatalError
– If one value is a vector of 0sgum.UndefinedElement
– If one node does not belong to the Bayesian network
-
setMaxIter
(LoopyImportanceSampling self, int max)¶ Parameters: max (int) – the maximum number of iteration Raises: gum.OutOfLowerBound
– If max <= 1
-
setMaxTime
(LoopyImportanceSampling self, double timeout)¶ Parameters: tiemout (double) – stopping criterion on timeout (in seconds) Raises: gum.OutOfLowerBound
– If timeout<=0.0
-
setMinEpsilonRate
(LoopyImportanceSampling self, double rate)¶ Parameters: rate (double) – the minimal epsilon rate
-
setPeriodSize
(LoopyImportanceSampling self, int p)¶ Parameters: p (int) – number of samples between 2 stopping Raises: gum.OutOfLowerBound
– If p<1
-
setTargets
(targets)¶ Remove all the targets and add the ones in parameter.
Parameters: targets (set) – a set of targets Raises: gum.UndefinedElement
– If one target is not in the Bayes net
-
setVerbosity
(LoopyImportanceSampling self, bool v)¶ Parameters: v (bool) – verbosity
-
setVirtualLBPSize
(LoopyImportanceSampling self, double vlbpsize)¶ Parameters: vlbpsize (double) – the size of the virtual LBP
-
softEvidenceNodes
(LoopyImportanceSampling self)¶ Returns: the set of nodes with soft evidence Return type: set
-
targets
(LoopyImportanceSampling self)¶ Returns: the list of marginal targets Return type: list
-
thisown
¶ The membership flag
-
updateEvidence
(evidces)¶ Apply chgEvidence(key,value) for every pairs in evidces (or addEvidence).
Parameters: evidces (dict) – a dict of evidences
Raises: gum.InvalidArgument
– If one value is not a value for the nodegum.InvalidArgument
– If the size of a value is different from the domain side of the nodegum.FatalError
– If one value is a vector of 0sgum.UndefinedElement
– If one node does not belong to the Bayesian network
-
verbosity
(LoopyImportanceSampling self)¶ Returns: True if the verbosity is enabled Return type: bool
Learning¶
-
class
pyAgrum.
BNLearner
(*args)¶ - Available ructors:
BNLearner(filename) -> BNLearner
BNLearner(filename,src,parse_database=false) -> BNLearner
BNLearner(learner) -> BNLearner
Parameters: - filename (str) – the file to learn from
- src (pyAgrum.BayesNet) – the Bayesian network used to find those modalities
- parse_database (bool) – if true, the modalities specified by the user will be considered as a superset of the modalities of the variables.
- learner (pyAgrum.BNLearner) – the BNLearner to copy
-
G2
(BNLearner self, str var1, str var2, Vector_string knw={})¶ G2 computes the G2 statistic and pvalue for two columns, given a list of other columns.
Parameters: - name1 (str) – the name of the first column
- name2 (str) – the name of the second column
- knowing ([str]) – the list of names of conditioning columns
Returns: the G2 statistic and the associated p-value as a Tuple
Return type: statistic,pvalue
-
addForbiddenArc
(BNLearner self, Arc arc)¶ addForbiddenArc(BNLearner self, int tail, int head) addForbiddenArc(BNLearner self, str tail, str head)
The arc in parameters won’t be added.
Parameters: - arc (pyAgrum.Arc) – an arc
- head – a variable’s id (int)
- tail – a variable’s id (int)
- head – a variable’s name (str)
- tail – a variable’s name (str)
-
addMandatoryArc
(BNLearner self, Arc arc)¶ addMandatoryArc(BNLearner self, int tail, int head) addMandatoryArc(BNLearner self, str tail, str head)
Allow to add prior structural knowledge.
Parameters: - arc (pyAgrum.Arc) – an arc
- head – a variable’s id (int)
- tail – a variable’s id (int)
- head – a variable’s name (str)
- tail – a variable’s name (str)
Raises: gum.InvalidDirectedCycle
– If the added arc creates a directed cycle in the DAG
-
addPossibleEdge
(BNLearner self, Edge edge)¶ addPossibleEdge(BNLearner self, int tail, int head) addPossibleEdge(BNLearner self, str tail, str head)
-
chi2
(BNLearner self, str var1, str var2, Vector_string knw={})¶ chi2 computes the chi2 statistic and pvalue for two columns, given a list of other columns.
Parameters: - name1 (str) – the name of the first column
- name2 (str) – the name of the second column
- knowing ([str]) – the list of names of conditioning columns
Returns: the chi2 statistic and the associated p-value as a Tuple
Return type: statistic,pvalue
-
currentTime
(BNLearner self)¶ Returns: get the current running time in second (double) Return type: double
-
databaseWeight
(BNLearner self)¶
-
epsilon
(BNLearner self)¶ Returns: the value of epsilon Return type: double
-
eraseForbiddenArc
(BNLearner self, Arc arc)¶ eraseForbiddenArc(BNLearner self, int tail, int head) eraseForbiddenArc(BNLearner self, str tail, str head)
Allow the arc to be added if necessary.
Parameters: - arc (pyAgrum) – an arc
- head – a variable’s id (int)
- tail – a variable’s id (int)
- head – a variable’s name (str)
- tail – a variable’s name (str)
-
eraseMandatoryArc
(BNLearner self, Arc arc)¶ eraseMandatoryArc(BNLearner self, int tail, int head) eraseMandatoryArc(BNLearner self, str tail, str head)
Parameters: - arc (pyAgrum) – an arc
- head – a variable’s id (int)
- tail – a variable’s id (int)
- head – a variable’s name (str)
- tail – a variable’s name (str)
-
erasePossibleEdge
(BNLearner self, Edge edge)¶ erasePossibleEdge(BNLearner self, int tail, int head) erasePossibleEdge(BNLearner self, str tail, str head)
Allow the 2 arcs to be added if necessary.
Parameters: - arc (pyAgrum) – an arc
- head – a variable’s id (int)
- tail – a variable’s id (int)
- head – a variable’s name (str)
- tail – a variable’s name (str)
-
hasMissingValues
(BNLearner self)¶ Indicates whether there are missing values in the database.
Returns: True if there are some missing values in the database. Return type: bool
-
history
(BNLearner self)¶ Returns: the scheme history Return type: tuple Raises: gum.OperationNotAllowed
– If the scheme did not performed or if verbosity is set to false
-
idFromName
(BNLearner self, str var_name)¶ Parameters: var_names (str) – a variable’s name Returns: the column id corresponding to a variable name Return type: int Raises: gum.MissingVariableInDatabase
– If a variable of the BN is not found in the database.
-
latentVariables
(BNLearner self)¶ latentVariables(BNLearner self) -> vector< pyAgrum.Arc,allocator< pyAgrum.Arc > >
Warning
learner must be using 3off2 or MIIC algorithm
Returns: the list of latent variables Return type: list
-
learnBN
(BNLearner self)¶ learn a BayesNet from a file (must have read the db before)
Returns: the learned BayesNet Return type: pyAgrum.BayesNet
-
learnDAG
(BNLearner self)¶ learn a structure from a file
Returns: the learned DAG Return type: pyAgrum.DAG
-
learnMixedStructure
(BNLearner self)¶ Warning
learner must be using 3off2 or MIIC algorithm
Returns: the learned structure as an EssentialGraph Return type: pyAgrum.EssentialGraph
-
learnParameters
(BNLearner self, DAG dag, bool take_into_account_score=True)¶ learnParameters(BNLearner self, bool take_into_account_score=True) -> BayesNet
learns a BN (its parameters) when its structure is known.
Parameters: - dag (pyAgrum.DAG) –
- bn (pyAgrum.BayesNet) –
- take_into_account_score (bool) – The dag passed in argument may have been learnt from a structure learning. In this case, if the score used to learn the structure has an implicit apriori (like K2 which has a 1-smoothing apriori), it is important to also take into account this implicit apriori for parameter learning. By default, if a score exists, we will learn parameters by taking into account the apriori specified by methods useAprioriXXX () + the implicit apriori of the score, else we just take into account the apriori specified by useAprioriXXX ()
Returns: the learned BayesNet
Return type: Raises: gum.MissingVariableInDatabase
– If a variable of the BN is not found in the databasegum.UnknownLabelInDatabase
– If a label is found in the database that do not correspond to the variable
-
logLikelihood
(BNLearner self, vector< int, allocator< int > > vars, vector< int, allocator< int > > knowing={})¶ logLikelihood(BNLearner self, vector< int,allocator< int > > vars) -> double logLikelihood(BNLearner self, Vector_string vars, Vector_string knowing={}) -> double logLikelihood(BNLearner self, Vector_string vars) -> double
logLikelihood computes the log-likelihood for the columns in vars, given the columns in the list knowing (optional)
Parameters: - vars (List[str]) – the name of the columns of interest
- knowing (List[str]) – the (optional) list of names of conditioning columns
Returns: the log-likelihood (base 2)
Return type: double
-
maxIter
(BNLearner self)¶ Returns: the criterion on number of iterations Return type: int
-
maxTime
(BNLearner self)¶ Returns: the timeout(in seconds) Return type: double
-
messageApproximationScheme
(BNLearner self)¶ Returns: the approximation scheme message Return type: str
-
minEpsilonRate
(BNLearner self)¶ Returns: the value of the minimal epsilon rate Return type: double
-
nameFromId
(BNLearner self, int id)¶ Parameters: id – a node id Returns: the variable’s name Return type: str
-
names
(BNLearner self)¶ Returns: the names of the variables in the database Return type: List[str]
-
nbCols
(BNLearner self)¶ Return the nimber of columns in the database
Returns: the number of columns in the database Return type: int
-
nbRows
(BNLearner self)¶ Return the number of row in the database
Returns: the number of rows in the database Return type: int
-
nbrIterations
(BNLearner self)¶ Returns: the number of iterations Return type: int
-
periodSize
(BNLearner self)¶ Returns: the number of samples between 2 stopping Return type: int Raises: gum.OutOfLowerBound
– If p<1
-
recordWeight
(BNLearner self, size_t i)¶
-
setAprioriWeight
(weight)¶ Deprecated methods in BNLearner for pyAgrum>0.14.0
-
setDatabaseWeight
(BNLearner self, double new_weight)¶ Set the database weight.
Parameters: weight (double) – the database weight
-
setEpsilon
(BNLearner self, double eps)¶ Parameters: eps (double) – the epsilon we want to use Raises: gum.OutOfLowerBound
– If eps<0
-
setInitialDAG
(BNLearner self, DAG g)¶ Parameters: dag (pyAgrum.DAG) – an initial DAG structure
-
setMaxIndegree
(BNLearner self, int max_indegree)¶
-
setMaxIter
(BNLearner self, int max)¶ Parameters: max (int) – the maximum number of iteration Raises: gum.OutOfLowerBound
– If max <= 1
-
setMaxTime
(BNLearner self, double timeout)¶ Parameters: tiemout (double) – stopping criterion on timeout (in seconds) Raises: gum.OutOfLowerBound
– If timeout<=0.0
-
setMinEpsilonRate
(BNLearner self, double rate)¶ Parameters: rate (double) – the minimal epsilon rate
-
setPeriodSize
(BNLearner self, int p)¶ Parameters: p (int) – number of samples between 2 stopping Raises: gum.OutOfLowerBound
– If p<1
-
setPossibleSkeleton
(BNLearner self, UndiGraph skeleton)¶
-
setRecordWeight
(BNLearner self, size_t i, double weight)¶
-
setSliceOrder
(BNLearner self, PyObject * l)¶ setSliceOrder(BNLearner self, pyAgrum.NodeProperty< int > slice_order) setSliceOrder(BNLearner self, vector< vector< str,allocator< str > >,allocator< vector< str,allocator< str > > > > slices)
Set a partial order on the nodes.
Parameters: l (list) – a list of sequences (composed of ids of rows or string)
-
setVerbosity
(BNLearner self, bool v)¶ Parameters: v (bool) – verbosity
-
thisown
¶ The membership flag
-
use3off2
(BNLearner self)¶ Indicate that we wish to use 3off2.
-
useAprioriBDeu
(BNLearner self, double weight=1)¶ useAprioriBDeu(BNLearner self)
The BDeu apriori adds weight to all the cells of the counting tables. In other words, it adds weight rows in the database with equally probable values.
Parameters: weight (double) – the apriori weight
-
useAprioriDirichlet
(BNLearner self, str filename, double weight=1)¶ useAprioriDirichlet(BNLearner self, str filename)
-
useAprioriSmoothing
(BNLearner self, double weight=1)¶ useAprioriSmoothing(BNLearner self)
-
useEM
(BNLearner self, double epsilon)¶ Indicates if we use EM for parameter learning.
Parameters: epsilon (double) – if epsilon=0.0 then EM is not used if epsilon>0 then EM is used and stops when the sum of the cumulative squared error on parameters is les than epsilon.
-
useGreedyHillClimbing
(BNLearner self)¶
-
useK2
(BNLearner self, PyObject * l)¶ useK2(BNLearner self, pyAgrum.Sequence< int > order) useK2(BNLearner self, vector< int,allocator< int > > order)
Indicate that we wish to use K2.
Parameters: order (list) – a list of ids
-
useLocalSearchWithTabuList
(BNLearner self, int tabu_size=100, int nb_decrease=2)¶ useLocalSearchWithTabuList(BNLearner self, int tabu_size=100) useLocalSearchWithTabuList(BNLearner self)
Indicate that we wish to use a local search with tabu list
Parameters: - tabu_size (int) – The size of the tabu list
- nb_decrease (int) – The max number of changes decreasing the score consecutively that we allow to apply
-
useMDL
(BNLearner self)¶ Indicate that we wish to use the MDL correction for 3off2 or MIIC
-
useMIIC
(BNLearner self)¶ Indicate that we wish to use MIIC.
-
useNML
(BNLearner self)¶ Indicate that we wish to use the NML correction for 3off2 or MIIC
-
useNoApriori
(BNLearner self)¶
-
useNoCorr
(BNLearner self)¶ Indicate that we wish to use the NoCorr correction for 3off2 or MIIC
-
useScoreAIC
(BNLearner self)¶
-
useScoreBD
(BNLearner self)¶
-
useScoreBDeu
(BNLearner self)¶
-
useScoreBIC
(BNLearner self)¶
-
useScoreK2
(BNLearner self)¶
-
useScoreLog2Likelihood
(BNLearner self)¶
-
verbosity
(BNLearner self)¶ Returns: True if the verbosity is enabled Return type: bool
Probabilistic Relational Models¶
For now, pyAgrum only allows to explore Probabilistic Relational Models written with o3prm syntax.
-
class
pyAgrum.
PRMexplorer
¶ PRMexplorer helps navigate through probabilistic relational models.
- Available ructors:
PRMexplorer() -> PRMexplorer
-
aggType
¶ a(9).str
min/max/count/exists/forall/or/and/amplitude/median
Type: aggType
-
classAggregates
(PRMexplorer self, str class_name)¶ Parameters: class_name (str) – a class name Returns: the list of aggregates in the class Return type: list Raises: gum.IndexError
– If the class is not in the PRM
-
classAttributes
(PRMexplorer self, str class_name)¶ Parameters: class_name (str) – a class name Returns: the list of attributes Return type: list Raises: gum.IndexError
– If the class is not in the PRM
-
classDag
(PRMexplorer self, str class_name)¶ Parameters: class_name (str) – a class name Returns: a description of the DAG Return type: tuple Raises: gum.IndexError
– If the class is not in the PRM
-
classImplements
(PRMexplorer self, str class_name)¶ Parameters: class_name (str) – a class name Returns: the list of interfaces implemented by the class Return type: list
-
classParameters
(PRMexplorer self, str class_name)¶ Parameters: class_name (str) – a class name Returns: the list of parameters Return type: list Raises: gum.IndexError
– If the class is not in the PRM
-
classReferences
(PRMexplorer self, str class_name)¶ Parameters: class_name (str) – a class name Returns: the list of references Return type: list Raises: gum.IndexError
– If the class is not in the PRM
-
classSlotChains
(PRMexplorer self, str class_name)¶ Parameters: class_name (str) – a class name Returns: the list of class slot chains Return type: list Raises: gum.IndexError
– if the class is not in the PRM
-
classes
(PRMexplorer self)¶ Returns: the list of classes Return type: list
-
cpf
(PRMexplorer self, str class_name, str attribute)¶ Parameters: - class_name (str) – a class name
- attribute (str) – an attribute
Returns: the potential of the attribute
Return type: Raises: gum.OperationNotAllowed
– If the class element doesn’t have any pyAgrum.Potential (like a pyAgrum.PRMReferenceSlot).gum.IndexError
– If the class is not in the PRMgum.IndexError
– If the attribute in parameters does not exist
-
getDirectSubClass
(PRMexplorer self, str class_name)¶ Parameters: class_name (str) – a class name Returns: the list of direct subclasses Return type: list Raises: gum.IndexError
– If the class is not in the PRM
-
getDirectSubInterfaces
(PRMexplorer self, str interface_name)¶ Parameters: interface_name (str) – an interface name Returns: the list of direct subinterfaces Return type: list Raises: gum.IndexError
– If the interface is not in the PRM
-
getDirectSubTypes
(PRMexplorer self, str type_name)¶ Parameters: type_name (str) – a type name Returns: the list of direct subtypes Return type: list Raises: gum.IndexError
– If the type is not in the PRM
-
getImplementations
(PRMexplorer self, str interface_name)¶ Parameters: interface_name (str) – an interface name Returns: the list of classes implementing the interface Return type: str Raises: gum.IndexError
– If the interface is not in the PRM
-
getLabelMap
(PRMexplorer self, str type_name)¶ Parameters: type_name (str) – a type name Returns: a dict containing pairs of label and their values Return type: dict Raises: gum.IndexError
– If the type is not in the PRM
-
getLabels
(PRMexplorer self, str type_name)¶ Parameters: type_name (str) – a type name Returns: the list of type labels Return type: list Raises: gum.IndexError
– If the type is not in the PRM
-
getSuperClass
(PRMexplorer self, str class_name)¶ Parameters: class_name (str) – a class name Returns: the class extended by class_name Return type: str Raises: gum.IndexError
– If the class is not in the PRM
-
getSuperInterface
(PRMexplorer self, str interface_name)¶ Parameters: interface_name (str) – an interface name Returns: the interace extended by interface_name Return type: str Raises: gum.IndexError
– If the interface is not in the PRM
-
getSuperType
(PRMexplorer self, str type_name)¶ Parameters: type_name (str) – a type name Returns: the type extended by type_name Return type: str Raises: gum.IndexError
– If the type is not in the PRM
-
getalltheSystems
(PRMexplorer self)¶ Returns: the list of all the systems and their components Return type: list
-
interAttributes
(PRMexplorer self, str interface_name, bool allAttributes=False)¶ Parameters: - interface_name (str) – an interface
- allAttributes (bool) – True if supertypes of a custom type should be indicated
Returns: the list of (<type>,<attribute_name>) for the given interface
Return type: list
Raises: gum.IndexError
– If the type is not in the PRM
-
interReferences
(PRMexplorer self, str interface_name)¶ Parameters: interface_name (str) – an interface Returns: the list of (<reference_type>,<reference_name>,<True if the reference is an array>) for the given interface Return type: list Raises: gum.IndexError
– If the type is not in the PRM
-
interfaces
(PRMexplorer self)¶ Returns: the list of interfaces in the PRM Return type: list
-
isAttribute
(PRMexplorer self, str class_name, str att_name)¶ Parameters: - class_name (str) – a class name
- att_name (str) – the name of the attribute to be tested
Returns: True if att_name is an attribute of class_name
Return type: bool
Raises: gum.IndexError
– If the class is not in the PRMgum.IndexError
– If att_name is not an element of class_name
-
isClass
(PRMexplorer self, str name)¶ Parameters: name (str) – an element name Returns: True if the parameter correspond to a class in the PRM Return type: bool
-
isInterface
(PRMexplorer self, str name)¶ Parameters: name (str) – an element name Returns: True if the parameter correspond to an interface in the PRM Return type: bool
-
isType
(PRMexplorer self, str name)¶ Parameters: name (str) – an element name Returns: True if the parameter correspond to a type in the PRM Return type: bool
-
load
(PRMexplorer self, str filename, str classpath="", bool verbose=False)¶ Load a PRM into the explorer.
Parameters: - filename (str) – the name of the o3prm file
- classpath (str) – the classpath of the PRM
Raises: gum.FatalError
– If file not found
-
thisown
¶ The membership flag
-
types
(PRMexplorer self)¶ Returns: the list of the custom types in the PRM Return type: list
Credal Networks¶
Model¶
-
class
pyAgrum.
CredalNet
(*args)¶ Constructor used to create a CredalNet (step by step or with two BayesNet)
- Available ructors:
CredalNet() -> CredalNet
CredalNet(src_min_num,src_max_den) -> CredalNet
CredalNet(src_min_num,src_max_den) -> CredalNet
Parameters: - src_min_num – (str) the path to a BayesNet which contains lower probabilities.
- src_max_den – (str) the (optional) path to a BayesNet which contains upper probabilities.
- src_min_num – (pyAgrum.BayesNet) the BayesNet which contains lower probabilities.
- src_max_den – (pyAgrum.BayesNet) the (optional) BayesNet which contains upper probabilities.
-
addArc
(CredalNet self, int tail, int head)¶ Adds an arc between two nodes
Parameters: - tail – the id of the tail node
- head (int) – the id of the head node
Raises: gum.InvalidDirectedCircle
– If any (directed) cycle is created by this arcgum.InvalidNode
– If head or tail does not belong to the graph nodesgum.DuplicateElement
– If one of the arc already exists
-
addVariable
(CredalNet self, str name, int card)¶ Parameters: - name (str) – the name of the new variable
- card (int) – the domainSize of the new variable
Returns: the id of the new node
Return type: int
-
approximatedBinarization
(CredalNet self)¶ Approximate binarization.
Each bit has a lower and upper probability which is the lowest - resp. highest - over all vertices of the credal set. Enlarge the orignal credal sets and may induce huge imprecision.
Warning
Enlarge the orignal credal sets and therefor induce huge imprecision by propagation. Not recommended, use MCSampling or something else instead
-
bnToCredal
(CredalNet self, double beta, bool oneNet, bool keepZeroes=False)¶ Perturbates the BayesNet provided as input for this CredalNet by generating intervals instead of point probabilities and then computes each vertex of each credal set.
Parameters: - beta (double) – The beta used to perturbate the network
- oneNet (bool) – used as a flag. Set to True if one BayesNet if provided with counts, to False if two BayesNet are provided; one with probabilities (the lower net) and one with denominators over the first modalities (the upper net)
- keepZeroes (bool) – used as a flag as whether or not - respectively True or False - we keep zeroes as zeroes. Default is False, i.e. zeroes are not kept
-
computeCPTMinMax
(CredalNet self)¶ Used with binary networks to speed-up L2U inference.
Store the lower and upper probabilities of each node X over the ‘True’ modality.
-
credalNet_currentCpt
(CredalNet self)¶ Warning
Experimental function - Return type to be wrapped
Returns: a ant reference to the (up-to-date) CredalNet CPTs. Return type: tbw
-
credalNet_srcCpt
(CredalNet self)¶ Warning
Experimental function - Return type to be wrapped
Returns: a ant reference to the (up-to-date) CredalNet CPTs. Return type: tbw
-
currentNodeType
(CredalNet self, int id)¶ Parameters: id (int) – The ant reference to the choosen NodeId Returns: the type of the choosen node in the (up-to-date) CredalNet __current_bn if any, __src_bn otherwise. Return type: pyAgrum.CredalNet
-
current_bn
(CredalNet self)¶ Returns: Returs a ant reference to the actual BayesNet (used as a DAG, it’s CPTs does not matter). Return type: pyAgrum.BayesNet
-
domainSize
(CredalNet self, int id)¶ Parameters: id (int) – The id of the node Returns: The cardinality of the node Return type: int
-
epsilonMax
(CredalNet self)¶ Returns: a ant reference to the highest perturbation of the BayesNet provided as input for this CredalNet. Return type: double
-
epsilonMean
(CredalNet self)¶ Returns: a ant reference to the average perturbation of the BayesNet provided as input for this CredalNet. Return type: double
-
epsilonMin
(CredalNet self)¶ Returns: a ant reference to the lowest perturbation of the BayesNet provided as input for this CredalNet. Return type: double
-
fillConstraint
(CredalNet self, int id, int entry, Vector lower, Vector upper)¶ fillConstraint(CredalNet self, int id, Instantiation ins, Vector lower, Vector upper)
Set the interval raints of a credal set of a given node (from an instantiation index)
Parameters: - id (int) – The id of the node
- entry (int) – The index of the instantiation excluding the given node (only the parents are used to compute the index of the credal set)
- ins (pyAgrum.Instantiation) – The Instantiation
- lower (list) – The lower value for each probability in correct order
- upper (list) – The upper value for each probability in correct order
Warning
You need to call intervalToCredal when done filling all raints.
Warning
DOES change the BayesNet (s) associated to this credal net !
-
fillConstraints
(CredalNet self, int id, Vector lower, Vector upper)¶ Set the interval raints of the credal sets of a given node (all instantiations)
Parameters: - id (int) – The id of the node
- lower (list) – The lower value for each probability in correct order
- upper (list) – The upper value for each probability in correct order
Warning
You need to call intervalToCredal when done filling all raints.
Warning
DOES change the BayesNet (s) associated to this credal net !
-
get_CPT_max
(CredalNet self)¶ Warning
Experimental function - Return type to be wrapped
Returns: a ant reference to the upper probabilities of each node X over the ‘True’ modality Return type: tbw
-
get_CPT_min
(CredalNet self)¶ Warning
Experimental function - Return type to be wrapped
Returns: a ant reference to the lower probabilities of each node X over the ‘True’ modality Return type: tbw
-
hasComputedCPTMinMax
(CredalNet self)¶ Returns: True this CredalNet has called computeCPTMinMax() to speed-up inference with binary networks and L2U. Return type: bool
-
idmLearning
(CredalNet self, int s=0, bool keepZeroes=False)¶ Learns parameters from a BayesNet storing counts of events.
Use this method when using a single BayesNet storing counts of events. IDM model if s > 0, standard point probability if s = 0 (default value if none precised).
Parameters: - s (int) – the IDM parameter.
- keepZeroes (bool) – used as a flag as whether or not - respectively True or False - we keep zeroes as zeroes. Default is False, i.e. zeroes are not kept.
-
instantiation
(CredalNet self, int id)¶ Get an Instantiation from a node id, usefull to fill the raints of the network.
bnet accessors / shortcuts.
Parameters: id (int) – the id of the node we want an instantiation from Returns: the instantiation Return type: pyAgrum.Instantiation
-
intervalToCredal
(CredalNet self)¶ Computes the vertices of each credal set according to their interval definition (uses lrs).
Use this method when using two BayesNet, one with lower probabilities and one with upper probabilities.
-
intervalToCredalWithFiles
(CredalNet self)¶ Warning
Deprecated : use intervalToCredal (lrsWrapper with no input / output files needed).
Computes the vertices of each credal set according to their interval definition (uses lrs).
Use this method when using a single BayesNet storing counts of events.
-
isSeparatelySpecified
(CredalNet self)¶ Returns: True if this CredalNet is separately and interval specified, False otherwise. Return type: bool
-
lagrangeNormalization
(CredalNet self)¶ Normalize counts of a BayesNet storing counts of each events such that no probability is 0.
Use this method when using a single BayesNet storing counts of events. Lagrange normalization. This call is irreversible and modify counts stored by __src_bn.
Doest not performs computations of the parameters but keeps normalized counts of events only. Call idmLearning to compute the probabilities (with any parameter value).
-
nodeType
(CredalNet self, int id)¶ Parameters: id (int) – the ant reference to the choosen NodeId Returns: the type of the choosen node in the (up-to-date) CredalNet in __src_bn. Return type: pyAgrum.CredalNet
-
saveBNsMinMax
(CredalNet self, str min_path, str max_path)¶ If this CredalNet was built over a perturbed BayesNet, one can save the intervals as two BayesNet.
to call after bnToCredal(GUM_SCALAR beta) save a BN with lower probabilities and a BN with upper ones
Parameters: - min_path (str) – the path to save the BayesNet which contains the lower probabilities of each node X.
- max_path (str) – the path to save the BayesNet which contains the upper probabilities of each node X.
-
setCPT
(CredalNet self, int id, int entry, vector< vector< double, allocator >, allocator< vector< double, allocator > > > cpt)¶ setCPT(CredalNet self, int id, Instantiation ins, vector< vector< double,allocator >,allocator< vector< double,allocator > > > cpt)
Warning
(experimental function) - Parameters to be wrapped
Set the vertices of one credal set of a given node (any instantiation index)
Parameters: - id (int) – the Id of the node
- entry (int) – the index of the instantiation (from 0 to K - 1) excluding the given node (only the parents are used to compute the index of the credal set)
- ins (pyAgrum.Instantiation) – the Instantiation (only the parents matter to find the credal set index)
- cpt (tbw) – the vertices of every credal set (for each instantiation of the parents)
Warning
DOES not change the BayesNet(s) associated to this credal net !
-
setCPTs
(CredalNet self, int id, vector< vector< vector< double, allocator >, allocator< vector< double, allocator > > >, allocator< vector< vector< double, allocator >, allocator< vector< double, allocator > > > > > cpt)¶ Warning
(experimental function) - Parameters to be wrapped
Set the vertices of the credal sets (all of the conditionals) of a given node
Parameters: - id (int) – the NodeId of the node
- cpt (tbw) – the vertices of every credal set (for each instantiation of the parents)
Warning
DOES not change the BayesNet (s) associated to this credal net !
-
src_bn
(CredalNet self)¶ Returns: Returns a ant reference to the original BayesNet (used as a DAG, it’s CPTs does not matter). Return type: pyAgrum.BayesNet
-
thisown
¶ The membership flag
Inference¶
-
class
pyAgrum.
CNMonteCarloSampling
(credalNet: pyAgrum.pyAgrum.CredalNet)¶ Class used for inferences in credal networks with Monte Carlo sampling algorithm.
Available ructors:
CNMonteCarloSampling(cn) -> CNMonteCarloSampling
Parameters: cn (pyAgrum.CredalNet) – a Credal network -
currentTime
(CNMonteCarloSampling self)¶ Returns: get the current running time in second (double) Return type: double
-
dynamicExpMax
(CNMonteCarloSampling self, str varName)¶ Get the upper dynamic expectation of a given variable prefix.
Parameters: varName (str) – the variable name prefix which upper expectation we want. Returns: a ant reference to the variable upper expectation over all time steps. Return type: double
-
dynamicExpMin
(CNMonteCarloSampling self, str varName)¶ Get the lower dynamic expectation of a given variable prefix.
Parameters: varName (str) – the variable name prefix which lower expectation we want. Returns: a ant reference to the variable lower expectation over all time steps. Return type: double
-
epsilon
(CNMonteCarloSampling self)¶ Returns: the value of epsilon Return type: double
-
history
(CNMonteCarloSampling self)¶ Returns: the scheme history Return type: tuple Raises: gum.OperationNotAllowed
– If the scheme did not performed or if verbosity is set to false
-
insertEvidenceFile
(CNMonteCarloSampling self, str path)¶ Insert evidence from file.
Parameters: path (str) – the path to the evidence file.
-
insertModalsFile
(CNMonteCarloSampling self, str path)¶ Insert variables modalities from file to compute expectations.
Parameters: path (str) – The path to the modalities file.
-
makeInference
(CNMonteCarloSampling self)¶ Starts the inference.
-
marginalMax
(CNMonteCarloSampling self, int id)¶ marginalMax(CNMonteCarloSampling self, str name) -> Vector
Get the upper marginals of a given node id.
Parameters: - id (int) – the node id which upper marginals we want.
- varName (str) – the variable name which upper marginals we want.
Returns: a ant reference to this node upper marginals.
Return type: list
Raises: gum.IndexError
– If the node does not belong to the Credal network
-
marginalMin
(CNMonteCarloSampling self, int id)¶ marginalMin(CNMonteCarloSampling self, str name) -> Vector
Get the lower marginals of a given node id.
Parameters: - id (int) – the node id which lower marginals we want.
- varName (str) – the variable name which lower marginals we want.
Returns: a ant reference to this node lower marginals.
Return type: list
Raises: gum.IndexError
– If the node does not belong to the Credal network
-
maxIter
(CNMonteCarloSampling self)¶ Returns: the criterion on number of iterations Return type: int
-
maxTime
(CNMonteCarloSampling self)¶ Returns: the timeout(in seconds) Return type: double
-
messageApproximationScheme
(CNMonteCarloSampling self)¶ Returns: the approximation scheme message Return type: str
-
minEpsilonRate
(CNMonteCarloSampling self)¶ Returns: the value of the minimal epsilon rate Return type: double
-
nbrIterations
(CNMonteCarloSampling self)¶ Returns: the number of iterations Return type: int
-
periodSize
(CNMonteCarloSampling self)¶ Returns: the number of samples between 2 stopping Return type: int Raises: gum.OutOfLowerBound
– If p<1
-
setEpsilon
(CNMonteCarloSampling self, double eps)¶ Parameters: eps (double) – the epsilon we want to use Raises: gum.OutOfLowerBound
– If eps<0
-
setMaxIter
(CNMonteCarloSampling self, int max)¶ Parameters: max (int) – the maximum number of iteration Raises: gum.OutOfLowerBound
– If max <= 1
-
setMaxTime
(CNMonteCarloSampling self, double timeout)¶ Parameters: tiemout (double) – stopping criterion on timeout (in seconds) Raises: gum.OutOfLowerBound
– If timeout<=0.0
-
setMinEpsilonRate
(CNMonteCarloSampling self, double rate)¶ Parameters: rate (double) – the minimal epsilon rate
-
setPeriodSize
(CNMonteCarloSampling self, int p)¶ Parameters: p (int) – number of samples between 2 stopping Raises: gum.OutOfLowerBound
– If p<1
-
setRepetitiveInd
(CNMonteCarloSampling self, bool flag)¶ Parameters: flag (bool) – True if repetitive independence is to be used, false otherwise. Only usefull with dynamic networks.
-
setVerbosity
(CNMonteCarloSampling self, bool v)¶ Parameters: v (bool) – verbosity
-
thisown
¶ The membership flag
-
verbosity
(CNMonteCarloSampling self)¶ Returns: True if the verbosity is enabled Return type: bool
-
-
class
pyAgrum.
CNLoopyPropagation
(cnet: pyAgrum.pyAgrum.CredalNet)¶ Class used for inferences in credal networks with Loopy Propagation algorithm.
Available ructors:
CNLoopyPropagation(cn) -> CNLoopyPropagation
Parameters: cn (pyAgrum.CredalNet) – a Credal network -
currentTime
(CNLoopyPropagation self)¶ Returns: get the current running time in second (double) Return type: double
-
dynamicExpMax
(CNLoopyPropagation self, str varName)¶ Get the upper dynamic expectation of a given variable prefix.
Parameters: varName (str) – the variable name prefix which upper expectation we want. Returns: a ant reference to the variable upper expectation over all time steps. Return type: double
-
dynamicExpMin
(CNLoopyPropagation self, str varName)¶ Get the lower dynamic expectation of a given variable prefix.
Parameters: varName (str) – the variable name prefix which lower expectation we want. Returns: a ant reference to the variable lower expectation over all time steps. Return type: double
-
epsilon
(CNLoopyPropagation self)¶ Returns: the value of epsilon Return type: double
-
eraseAllEvidence
(CNLoopyPropagation self)¶ Erase all inference related data to perform another one.
You need to insert evidence again if needed but modalities are kept. You can insert new ones by using the appropriate method which will delete the old ones.
-
history
(CNLoopyPropagation self)¶ Returns: the scheme history Return type: tuple Raises: gum.OperationNotAllowed
– If the scheme did not performed or if verbosity is set to false
-
inferenceType
(CNLoopyPropagation self, pyAgrum.credal::CNLoopyPropagation ::InferenceType inft)¶ inferenceType(CNLoopyPropagation self) -> pyAgrum.credal::CNLoopyPropagation ::InferenceType
Returns: the inference type Return type: int
-
insertEvidenceFile
(CNLoopyPropagation self, str path)¶ Insert evidence from file.
Parameters: path (str) – the path to the evidence file.
-
insertModalsFile
(CNLoopyPropagation self, str path)¶ Insert variables modalities from file to compute expectations.
Parameters: path (str) – The path to the modalities file.
-
makeInference
(CNLoopyPropagation self)¶ Starts the inference.
-
marginalMax
(CNLoopyPropagation self, int id)¶ marginalMax(CNLoopyPropagation self, str name) -> Vector
Get the upper marginals of a given node id.
Parameters: - id (int) – the node id which upper marginals we want.
- varName (str) – the variable name which upper marginals we want.
Returns: a ant reference to this node upper marginals.
Return type: list
Raises: gum.IndexError
– If the node does not belong to the Credal network
-
marginalMin
(CNLoopyPropagation self, int id)¶ marginalMin(CNLoopyPropagation self, str name) -> Vector
Get the lower marginals of a given node id.
Parameters: - id (int) – the node id which lower marginals we want.
- varName (str) – the variable name which lower marginals we want.
Returns: a ant reference to this node lower marginals.
Return type: list
Raises: gum.IndexError
– If the node does not belong to the Credal network
-
maxIter
(CNLoopyPropagation self)¶ Returns: the criterion on number of iterations Return type: int
-
maxTime
(CNLoopyPropagation self)¶ Returns: the timeout(in seconds) Return type: double
-
messageApproximationScheme
(CNLoopyPropagation self)¶ Returns: the approximation scheme message Return type: str
-
minEpsilonRate
(CNLoopyPropagation self)¶ Returns: the value of the minimal epsilon rate Return type: double
-
nbrIterations
(CNLoopyPropagation self)¶ Returns: the number of iterations Return type: int
-
periodSize
(CNLoopyPropagation self)¶ Returns: the number of samples between 2 stopping Return type: int Raises: gum.OutOfLowerBound
– If p<1
-
saveInference
(CNLoopyPropagation self, str path)¶ Saves marginals.
Parameters: path (str) – The path to the file to save marginals.
-
setEpsilon
(CNLoopyPropagation self, double eps)¶ Parameters: eps (double) – the epsilon we want to use Raises: gum.OutOfLowerBound
– If eps<0
-
setMaxIter
(CNLoopyPropagation self, int max)¶ Parameters: max (int) – the maximum number of iteration Raises: gum.OutOfLowerBound
– If max <= 1
-
setMaxTime
(CNLoopyPropagation self, double timeout)¶ Parameters: tiemout (double) – stopping criterion on timeout (in seconds) Raises: gum.OutOfLowerBound
– If timeout<=0.0
-
setMinEpsilonRate
(CNLoopyPropagation self, double rate)¶ Parameters: rate (double) – the minimal epsilon rate
-
setPeriodSize
(CNLoopyPropagation self, int p)¶ Parameters: p (int) – number of samples between 2 stopping Raises: gum.OutOfLowerBound
– If p<1
-
setRepetitiveInd
(CNLoopyPropagation self, bool flag)¶ Parameters: flag (bool) – True if repetitive independence is to be used, false otherwise. Only usefull with dynamic networks.
-
setVerbosity
(CNLoopyPropagation self, bool v)¶ Parameters: v (bool) – verbosity
-
thisown
¶ The membership flag
-
verbosity
(CNLoopyPropagation self)¶ Returns: True if the verbosity is enabled Return type: bool
-
Influence Diagram¶
Model¶
-
class
pyAgrum.
InfluenceDiagram
(*args)¶ InfluenceDiagram represents an Influence Diagram.
- Available ructors:
InfluenceDiagram() -> InfluenceDiagram
InfluenceDiagram(source) -> InfluenceDiagram
Parameters: source (pyAgrum.InfluenceDiagram) – the InfluenceDiagram to copy -
add
(InfluenceDiagram self, DiscreteVariable variable, int id=0)¶ Add a chance variable, it’s associate node and it’s CPT.
The id of the new variable is automatically generated.
Parameters: - variable (pyAgrum.DiscreteVariable) – The variable added by copy.
- id (int) – The chosen id. If 0, the NodeGraphPart will choose.
Warning
give an id (not 0) should be reserved for rare and specific situations !!!
Returns: the id of the added variable. Return type: int Raises: gum.DuplicateElement
– If id(<>0) is already used
-
addArc
(InfluenceDiagram self, int tail, int head)¶ Add an arc in the ID, and update diagram’s potential nodes cpt if necessary.
Parameters: - tail (int) – the id of the tail node
- head (int) – the id of the head node
Raises: gum.InvalidEdge
– If arc.tail and/or arc.head are not in the ID.gum.InvalidEdge
– If tail is a utility node
-
addChanceNode
(InfluenceDiagram self, DiscreteVariable variable, int id=0)¶ addChanceNode(InfluenceDiagram self, DiscreteVariable variable, pyAgrum.MultiDimImplementation aContent, int id=0) -> int
Add a chance variable, it’s associate node and it’s CPT.
The id of the new variable is automatically generated.
Parameters: - variable (pyAgrum.DiscreteVariable) – the variable added by copy.
- id (int) – the chosen id. If 0, the NodeGraphPart will choose.
Warning
give an id (not 0) should be reserved for rare and specific situations !!!
Returns: the id of the added variable. Return type: int Raises: gum.DuplicateElement
– If id(<>0) is already used
-
addDecisionNode
(InfluenceDiagram self, DiscreteVariable variable, int id=0)¶ Add a decision variable.
The id of the new variable is automatically generated.
Parameters: - variable (pyAgrum.DiscreteVariable) – the variable added by copy.
- id (int) – the chosen id. If 0, the NodeGraphPart will choose.
Warning
give an id (not 0) should be reserved for rare and specific situations !!!
Returns: the id of the added variable. Return type: int Raises: gum.DuplicateElement
– If id(<>0) is already used
-
addUtilityNode
(InfluenceDiagram self, DiscreteVariable variable, int id=0)¶ addUtilityNode(InfluenceDiagram self, DiscreteVariable variable, pyAgrum.MultiDimImplementation aContent, int id=0) -> int
Add a utility variable, it’s associate node and it’s UT.
The id of the new variable is automatically generated.
Parameters: - variable (pyAgrum.DiscreteVariable) – the variable added by copy
- id (int) – the chosen id. If 0, the NodeGraphPart will choose
Warning
give an id (not 0) should be reserved for rare and specific situations !!!
Returns: the id of the added variable.
Return type: int
Raises: gum.InvalidArgument
– If variable has more than one labelgum.DuplicateElement
– If id(<>0) is already used
-
arcs
(InfluenceDiagram self)¶ Returns: the list of all the arcs in the Influence Diagram. Return type: list
-
chanceNodeSize
(InfluenceDiagram self)¶ Returns: the number of chance nodes. Return type: int
-
changeVariableName
(InfluenceDiagram self, int id, str new_name)¶ Parameters: - id (int) – the node Id
- new_name (str) – the name of the variable
Raises: gum.DuplicateLabel
– If this name already existsgum.NotFound
– If no nodes matches id.
-
children
(InfluenceDiagram self, int id)¶ Parameters: id (int) – the id of the parent Returns: the set of all the children Return type: Set
-
completeInstantiation
(DAGmodel self)¶ Get an instantiation over all the variables of the model.
Returns: the complete instantiation Return type: pyAgrum.instantiation
-
cpt
(InfluenceDiagram self, int varId)¶ Returns the CPT of a variable.
Parameters: VarId (int) – A variable’s id in the pyAgrum.BayesNet. Returns: The variable’s CPT. Return type: pyAgrum.Potential Raises: gum.NotFound
– If no variable’s id matches varId.
-
dag
(DAGmodel self)¶ Returns: a ant reference to the dag of this BayesNet. Return type: pyAgrum.DAG
-
decisionNodeSize
(InfluenceDiagram self)¶ Returns: the number of decision nodes Return type: int
-
decisionOrderExists
(InfluenceDiagram self)¶ Returns: True if a directed path exist with all decision node Return type: bool
-
empty
(DAGmodel self)¶ Returns: True if the model is empty Return type: bool
-
erase
(InfluenceDiagram self, int id)¶ erase(InfluenceDiagram self, DiscreteVariable var)
Erase a Variable from the network and remove the variable from all his childs.
If no variable matches the id, then nothing is done.
Parameters: - id (int) – The id of the variable to erase.
- var (pyAgrum.DiscreteVariable) – The reference on the variable to remove.
-
eraseArc
(InfluenceDiagram self, Arc arc)¶ eraseArc(InfluenceDiagram self, int tail, int head)
Removes an arc in the ID, and update diagram’s potential nodes cpt if necessary.
If (tail, head) doesn’t exist, the nothing happens.
Parameters: - arc (pyAgrum.Arc) – The arc to be removed.
- tail (int) – the id of the tail node
- head (int) – the id of the head node
-
existsPathBetween
(InfluenceDiagram self, int src, int dest)¶ Returns: true if a path exists between two nodes. Return type: bool
-
getDecisionGraph
(InfluenceDiagram self)¶ Returns: the temporal Graph. Return type: pyAgrum.DAG
-
getDecisionOrder
(InfluenceDiagram self)¶ Returns: the sequence of decision nodes in the directed path. Return type: list Raises: NotFound
– If such a path does not exist
-
hasSameStructure
(DAGmodel self, DAGmodel other)¶ Parameters: pyAgrum.DAGmodel – a direct acyclic model Returns: True if all the named node are the same and all the named arcs are the same Return type: bool
-
idFromName
(InfluenceDiagram self, str name)¶ Returns a variable’s id given its name.
Parameters: name (str) – the variable’s name from which the id is returned. Returns: the variable’s node id. Return type: int Raises: gum.NotFound
– If no such name exists in the graph.
-
ids
(InfluenceDiagram self)¶ Note
Deprecated in pyAgrum>0.13.0 Please use nodes() instead
-
isChanceNode
(InfluenceDiagram self, int varId)¶ Parameters: varId (int) – the tested node id. Returns: true if node is a chance node Return type: bool
-
isDecisionNode
(InfluenceDiagram self, int varId)¶ Parameters: varId (int) – the tested node id. Returns: true if node is a decision node Return type: bool
-
isUtilityNode
(InfluenceDiagram self, int varId)¶ Parameters: varId (int) – the tested node id. Returns: true if node is an utility node Return type: bool
-
loadBIFXML
(InfluenceDiagram self, str name, PyObject * l=(PyObject *) 0)¶ Load a BIFXML file.
Parameters: name (str) – the name’s file
Raises: gum.IOError
– If file not foundgum.FatalError
– If file is not valid
-
log10DomainSize
(DAGmodel self)¶ Returns: The log10 domain size of the joint probability for the model. Return type: double
-
moralGraph
(DAGmodel self, bool clear=True)¶ Returns the moral graph of the BayesNet, formed by adding edges between all pairs of nodes that have a common child, and then making all edges in the graph undirected.
Returns: The moral graph Return type: pyAgrum.UndiGraph
-
names
(InfluenceDiagram self)¶ Returns: The names of the InfluenceDiagram variables Return type: list
-
nodeId
(InfluenceDiagram self, DiscreteVariable var)¶ Parameters: var (pyAgrum.DiscreteVariable) – a variable Returns: the id of the variable Return type: int Raises: gum.IndexError
– If the InfluenceDiagram does not contain the variable
-
nodes
(DAGmodel self)¶ Returns: the set of ids Return type: set
-
parents
(InfluenceDiagram self, int id)¶ Parameters: id – The id of the child node Returns: the set of the parents ids. Return type: set
-
saveBIFXML
(InfluenceDiagram self, str name)¶ Save the BayesNet in a BIFXML file.
Parameters: name (str) – the file’s name
-
size
(DAGmodel self)¶ Returns: the number of nodes in the graph Return type: int
-
sizeArcs
(DAGmodel self)¶ Returns: the number of arcs in the graph Return type: int
-
thisown
¶ The membership flag
-
toDot
(InfluenceDiagram self)¶ Returns: a friendly display of the graph in DOT format Return type: str
-
topologicalOrder
(DAGmodel self, bool clear=True)¶ Returns: the list of the nodes Ids in a topological order Return type: List Raises: gum.InvalidDirectedCycle
– If this graph contains cycles
-
utility
(InfluenceDiagram self, int varId)¶ Parameters: varId (int) – the tested node id. Returns: the utility table of the node Return type: pyAgrum.Potential Raises: gum.IndexError
– If the InfluenceDiagram does not contain the variable
-
utilityNodeSize
(InfluenceDiagram self)¶ Returns: the number of utility nodes Return type: int
-
variable
(InfluenceDiagram self, int id)¶ Parameters: id (int) – the node id Returns: a ant reference over a variabe given it’s node id Return type: pyAgrum.DiscreteVariable Raises: gum.NotFound
– If no variable’s id matches the parameter
-
variableFromName
(InfluenceDiagram self, str name)¶ Parameters: name (str) – a variable’s name Returns: the variable Return type: pyAgrum.DiscreteVariable Raises: gum.IndexError
– If the InfluenceDiagram does not contain the variable
-
variableNodeMap
(DAGmodel self)¶ Returns: the variable node map Return type: pyAgrum.variableNodeMap
Inference¶
-
class
pyAgrum.
InfluenceDiagramInference
(infDiag: pyAgrum.pyAgrum.InfluenceDiagram)¶ Proxy of C++ pyAgrum.InfluenceDiagramInference class. Proxy of C++ pyAgrum.InfluenceDiagramInference class.
-
displayResult
(InfluenceDiagramInference self)¶ Displays the result of an inference.
-
displayStrongJunctionTree
(InfluenceDiagramInference self, ostream stream=cout)¶ Displays on terminal the result of strong junction tree computation for test purpose only.
Parameters: args (TBW) –
-
eraseAllEvidence
(InfluenceDiagramInference self)¶ Removes all the evidence entered into the diagram.
-
eraseEvidence
(InfluenceDiagramInference self, Potential evidence)¶ Parameters: evidence (pyAgrum.Potential) – the evidence to remove Raises: gum.IndexError
– If the evidence does not belong to the influence diagram
-
getBestDecisionChoice
(InfluenceDiagramInference self, int decisionId)¶ Returns best choice for decision variable given in parameter ( based upon MEU criteria )
Parameters: decisionId (int) – the id of the decision variable
Raises: gum.OperationNotAllowed
– If no inference have yet been madegum.InvalidNode
– If node given in parmaeter is not a decision node
-
getMEU
(InfluenceDiagramInference self)¶ Returns maximum expected utility obtained from inference.
Raises: gum.OperationNotAllowed
– If no inference have yet been made
-
influenceDiagram
(InfluenceDiagramInference self)¶ Returns a ant reference over the InfluenceDiagram on which this class work.
Returns: the InfluenceDiagram on which this class work Return type: pyAgrum.InfluenceDiagram
-
insertEvidence
(InfluenceDiagramInference self, pyAgrum.List< pyAgrum.Potential * > evidenceList)¶ Insert new evidence in the graph.
Parameters: evidenceList (list) – a list of potentials as evidences Warning
If an evidence already w.r.t. a given node and a new evidence w.r.t. this node is onserted, the old evidence is removed
Raises: gum.OperationNotAllowed
– If an evidence is over more than one variable
-
junctionTreeToDot
(InfluenceDiagramInference self)¶ Returns: the result of strong junction tree computation for test purpose only. Return type: str
-
makeInference
(InfluenceDiagramInference self)¶ Makes the inference.
-
setEvidence
(evidces)¶ Erase all the evidences and apply addEvidence(key,value) for every pairs in evidces.
Parameters: evidces (dict) – a dict of evidences
Raises: gum.InvalidArgument
– If one value is not a value for the nodegum.InvalidArgument
– If the size of a value is different from the domain side of the nodegum.FatalError
– If one value is a vector of 0sgum.UndefinedElement
– If one node does not belong to the Bayesian network
-
thisown
¶ The membership flag
-
Other functions from aGrUM¶
Listeners¶
aGrUM includes a mechanism for listening to actions (close to QT signal/slot). Some of them have been ported to pyAgrum :
LoadListener¶
Listeners could be added in order to monitor the progress when loading a pyAgrum.BayesNet
>>> import pyAgrum as gum
>>>
>>> # creating a new liseners
>>> def foo(progress):
>>> if progress==200:
>>> print(' BN loaded ')
>>> return
>>> elif progress==100:
>>> car='%'
>>> elif progress%10==0:
>>> car='#'
>>> else:
>>> car='.'
>>> print(car,end='',flush=True)
>>>
>>> def bar(progress):
>>> if progress==50:
>>> print('50%')
>>>
>>>
>>> gum.loadBN('./bn.bif',listeners=[foo,bar])
>>> # .........#.........#.........#.........#..50%
>>> # .......#.........#.........#.........#.........#.........% | bn loaded
StructuralListener¶
Listeners could also be added when structural modification are made in a pyAgrum.BayesNet:
>>> import pyAgrum as gum
>>>
>>> ## creating a BayesNet
>>> bn=gum.BayesNet()
>>>
>>> ## adding structural listeners
>>> bn.addStructureListener(whenNodeAdded=lambda n,s:print('adding {}:{}'.format(n,s)),
>>> whenArcAdded=lambda i,j: print('adding {}->{}'.format(i,j)),
>>> whenNodeDeleted=lambda n:print('deleting {}'.format(n)),
>>> whenArcDeleted=lambda i,j: print('deleting {}->{}'.format(i,j)))
>>>
>>> ## adding another listener for when a node is deleted
>>> bn.addStructureListener(whenNodeDeleted=lambda n: print('yes, really deleting '+str(n)))
>>>
>>> ## adding nodes to the BN
>>> l=[bn.add(item,3) for item in 'ABCDE']
>>> # adding 0:A
>>> # adding 1:B
>>> # adding 2:C
>>> # adding 3:D
>>> # adding 4:E
>>>
>>> ## adding arc to the BN
>>> bn.addArc(1,3)
>>> # adding 1->3
>>>
>>> ## removing a node from the BN
>>> bn.erase('C')
>>> # deleting 2
>>> # yes, really deleting 2
ApproximationSchemeListener¶
DatabaseGenerationListener¶
Random functions¶
-
pyAgrum.
initRandom
(unsigned int seed=0)¶ Initialize random generator seed.
Parameters: seed (int) – the seed used to initialize the random generator
-
pyAgrum.
randomProba
()¶ Returns: a random number between 0 and 1 included (i.e. a proba). Return type: double
-
pyAgrum.
randomDistribution
(int n)¶ Parameters: n (int) – The number of modalities for the ditribution. Returns: Return type: a random discrete distribution.
OMP functions¶
-
pyAgrum.
isOMP
()¶ Returns: True if OMP has been set at compilation, False otherwise Return type: bool
-
pyAgrum.
setNumberOfThreads
(unsigned int number)¶ To avoid spare cycles (less then 100% CPU occupied), use more threads than logical processors (x2 is a good all-around value).
Returns: number – the number of threads to be used Return type: int
-
pyAgrum.
getNumberOfLogicalProcessors
()¶ Returns: the number of logical processors Return type: int
-
pyAgrum.
getMaxNumberOfThreads
()¶ Returns: the max number of threads Return type: int
Exceptions from aGrUM¶
All the classes inherit GumException’s functions errorType, errorCallStack and errorContent.
-
exception
pyAgrum.
DefaultInLabel
(*args)¶ Proxy of C++ pyAgrum.DefaultInLabel class.
-
thisown
¶ The membership flag
-
what
(GumException self)¶
-
-
exception
pyAgrum.
DuplicateElement
(*args)¶ Proxy of C++ pyAgrum.DuplicateElement class.
-
thisown
¶ The membership flag
-
what
(GumException self)¶
-
-
exception
pyAgrum.
DuplicateLabel
(*args)¶ Proxy of C++ pyAgrum.DuplicateLabel class.
-
thisown
¶ The membership flag
-
what
(GumException self)¶
-
-
exception
pyAgrum.
EmptyBSTree
(*args)¶ Proxy of C++ pyAgrum.EmptyBSTree class.
-
thisown
¶ The membership flag
-
what
(GumException self)¶
-
-
exception
pyAgrum.
EmptySet
(*args)¶ Proxy of C++ pyAgrum.EmptySet class.
-
thisown
¶ The membership flag
-
what
(GumException self)¶
-
-
exception
pyAgrum.
GumException
(*args)¶ Proxy of C++ pyAgrum.Exception class.
-
errorCallStack
(GumException self)¶ Returns: the error call stack Return type: str
-
errorContent
(GumException self)¶ Returns: the error content Return type: str
-
errorType
(GumException self)¶ Returns: the error type Return type: str
-
thisown
¶ The membership flag
-
what
(GumException self)¶
-
-
exception
pyAgrum.
FatalError
(*args)¶ Proxy of C++ pyAgrum.FatalError class.
-
thisown
¶ The membership flag
-
what
(GumException self)¶
-
-
exception
pyAgrum.
FormatNotFound
(*args)¶ Proxy of C++ pyAgrum.FormatNotFound class.
-
thisown
¶ The membership flag
-
what
(GumException self)¶
-
-
exception
pyAgrum.
GraphError
(*args)¶ Proxy of C++ pyAgrum.GraphError class.
-
thisown
¶ The membership flag
-
what
(GumException self)¶
-
-
exception
pyAgrum.
IOError
(*args)¶ Proxy of C++ pyAgrum.IOError class.
-
thisown
¶ The membership flag
-
what
(GumException self)¶
-
-
exception
pyAgrum.
IdError
(*args)¶ Proxy of C++ pyAgrum.IdError class.
-
thisown
¶ The membership flag
-
what
(GumException self)¶
-
-
exception
pyAgrum.
InvalidArc
(*args)¶ Proxy of C++ pyAgrum.InvalidArc class.
-
thisown
¶ The membership flag
-
what
(GumException self)¶
-
-
exception
pyAgrum.
InvalidArgument
(*args)¶ Proxy of C++ pyAgrum.InvalidArgument class.
-
thisown
¶ The membership flag
-
what
(GumException self)¶
-
-
exception
pyAgrum.
InvalidArgumentsNumber
(*args)¶ Proxy of C++ pyAgrum.InvalidArgumentsNumber class.
-
thisown
¶ The membership flag
-
what
(GumException self)¶
-
-
exception
pyAgrum.
InvalidDirectedCycle
(*args)¶ Proxy of C++ pyAgrum.InvalidDirectedCycle class.
-
thisown
¶ The membership flag
-
what
(GumException self)¶
-
-
exception
pyAgrum.
InvalidEdge
(*args)¶ Proxy of C++ pyAgrum.InvalidEdge class.
-
thisown
¶ The membership flag
-
what
(GumException self)¶
-
-
exception
pyAgrum.
InvalidNode
(*args)¶ Proxy of C++ pyAgrum.InvalidNode class.
-
thisown
¶ The membership flag
-
what
(GumException self)¶
-
-
exception
pyAgrum.
NoChild
(*args)¶ Proxy of C++ pyAgrum.NoChild class.
-
thisown
¶ The membership flag
-
what
(GumException self)¶
-
-
exception
pyAgrum.
NoNeighbour
(*args)¶ Proxy of C++ pyAgrum.NoNeighbour class.
-
thisown
¶ The membership flag
-
what
(GumException self)¶
-
-
exception
pyAgrum.
NoParent
(*args)¶ Proxy of C++ pyAgrum.NoParent class.
-
thisown
¶ The membership flag
-
what
(GumException self)¶
-
-
exception
pyAgrum.
NotFound
(*args)¶ Proxy of C++ pyAgrum.NotFound class.
-
thisown
¶ The membership flag
-
what
(GumException self)¶
-
-
exception
pyAgrum.
NullElement
(*args)¶ Proxy of C++ pyAgrum.NullElement class.
-
thisown
¶ The membership flag
-
what
(GumException self)¶
-
-
exception
pyAgrum.
OperationNotAllowed
(*args)¶ Proxy of C++ pyAgrum.OperationNotAllowed class.
-
thisown
¶ The membership flag
-
what
(GumException self)¶
-
-
exception
pyAgrum.
OutOfBounds
(*args)¶ Proxy of C++ pyAgrum.OutOfBounds class.
-
thisown
¶ The membership flag
-
what
(GumException self)¶
-
-
exception
pyAgrum.
OutOfLowerBound
(*args)¶ Proxy of C++ pyAgrum.OutOfLowerBound class.
-
thisown
¶ The membership flag
-
what
(GumException self)¶
-
-
exception
pyAgrum.
OutOfUpperBound
(*args)¶ Proxy of C++ pyAgrum.OutOfUpperBound class.
-
thisown
¶ The membership flag
-
what
(GumException self)¶
-
-
exception
pyAgrum.
ReferenceError
(*args)¶ Proxy of C++ pyAgrum.ReferenceError class.
-
thisown
¶ The membership flag
-
what
(GumException self)¶
-
-
exception
pyAgrum.
SizeError
(*args)¶ Proxy of C++ intError class.
-
thisown
¶ The membership flag
-
what
(GumException self)¶
-
-
exception
pyAgrum.
SyntaxError
(*args)¶ Proxy of C++ pyAgrum.SyntaxError class.
-
col
(SyntaxError self)¶ Returns: the indice of the colonne of the error Return type: int
-
line
(SyntaxError self)¶ Returns: the indice of the line of the error Return type: int
-
thisown
¶ The membership flag
-
what
(GumException self)¶
-
-
exception
pyAgrum.
UndefinedElement
(*args)¶ Proxy of C++ pyAgrum.UndefinedElement class.
-
thisown
¶ The membership flag
-
what
(GumException self)¶
-
-
exception
pyAgrum.
UndefinedIteratorKey
(*args)¶ Proxy of C++ pyAgrum.UndefinedIteratorKey class.
-
thisown
¶ The membership flag
-
what
(GumException self)¶
-
Python helpers : pyAgrum.lib¶
pyAgrum.lib is a set of python tools.
Module notebook¶

Helpers¶
Visualization of Potentials¶
Visualization of graphs¶
Visualization of graphical models¶
Visualization of approximation algorithm¶
Module bn2graph¶
-
pyAgrum.lib.bn2graph.
BN2dot
(bn, size='4', nodeColor=None, arcWidth=None, arcColor=None, cmapNode=None, cmapArc=None, showMsg=None)¶ create a pydotplus representation of the BN
Parameters: - bn (pyAgrum.BayesNet) –
- size (string) – size of the rendered graph
- nodeColor – a nodeMap of values (between 0 and 1) to be shown as color of nodes (with special colors for 0
and 1) :param arcWidth: a arcMap of values to be shown as width of arcs :param arcColor: a arcMap of values (between 0 and 1) to be shown as color of arcs :param cmapNode: color map to show the vals of Nodes :param cmapArc: color map to show the vals of Arcs. :param showMsg: a nodeMap of values to be shown as tooltip
Returns: the desired representation of the BN as a dot graph
-
pyAgrum.lib.bn2graph.
BNinference2dot
(bn, size='4', engine=None, evs={}, targets={}, format='png', nodeColor=None, arcWidth=None, cmap=None)¶ create a pydotplus representation of an inference in a BN
Parameters: - bn (pyAgrum.BayesNet) –
- size (string) – size of the rendered graph
- Inference engine (pyAgrum) – inference algorithm used. If None, LazyPropagation will be used
- evs (dictionnary) – map of evidence
- targets (set) – set of targets. If targets={} then each node is a target
- format (string) – render as “png” or “svg”
- nodeColor – a nodeMap of values to be shown as color nodes (with special color for 0 and 1)
- arcWidth – a arcMap of values to be shown as bold arcs
- cmap – color map to show the vals
Returns: the desired representation of the inference
-
pyAgrum.lib.bn2graph.
dotize
(aBN, name, format='pdf')¶ From a bn, creates an image of the BN
Parameters: - bn (pyAgrum.BayesNet) – the bayes net to show
- name (string) – the filename (without extension) for the image
- format (string) – format in [‘pdf’,’png’,’fig’,’jpg’,’svg’]
-
pyAgrum.lib.bn2graph.
pdfize
(aBN, name)¶ From a bn, creates a pdf of the BN
Parameters: - bn (pyAgrum.BayesNet) – the bayes net to show
- name (string) – the filename (without extension) for the image
-
pyAgrum.lib.bn2graph.
pngize
(aBN, name)¶ From a bn, creates a png of the BN
Parameters: - bn (pyAgrum.BayesNet) – the bayes net to show
- name (string) – the filename (without extension) for the image
-
pyAgrum.lib.bn2graph.
proba2histo
(p, scale=1.0)¶ compute the representation of an histogram for a mono-dim Potential
Parameters: p (pyAgrum.Potential) – the mono-dim Potential Returns: a matplotlib histogram for a Potential p.
1 2 3 4 5 6 7 8 9 10 11 12 | bn = gum.fastBN("a->b->d;a->c->d->e;f->b")
g = BNinference2dot(bn,
targets=['f', 'd'],
vals={'a': 1,
'b': 0.3,
'c': 0.3,
'd': 0.1,
'e': 0.1,
'f': 0.3},
arcvals={(0, 1): 2,
(0, 2): 0.5})
g.write("test.png", format='png')
|
Visualization of Potentials¶
-
pyAgrum.lib.bn2graph.
proba2histo
(p, scale=1.0) compute the representation of an histogram for a mono-dim Potential
Parameters: p (pyAgrum.Potential) – the mono-dim Potential Returns: a matplotlib histogram for a Potential p.
Visualization of Bayesian Networks¶
-
pyAgrum.lib.bn2graph.
BN2dot
(bn, size='4', nodeColor=None, arcWidth=None, arcColor=None, cmapNode=None, cmapArc=None, showMsg=None) create a pydotplus representation of the BN
Parameters: - bn (pyAgrum.BayesNet) –
- size (string) – size of the rendered graph
- nodeColor – a nodeMap of values (between 0 and 1) to be shown as color of nodes (with special colors for 0
and 1) :param arcWidth: a arcMap of values to be shown as width of arcs :param arcColor: a arcMap of values (between 0 and 1) to be shown as color of arcs :param cmapNode: color map to show the vals of Nodes :param cmapArc: color map to show the vals of Arcs. :param showMsg: a nodeMap of values to be shown as tooltip
Returns: the desired representation of the BN as a dot graph
-
pyAgrum.lib.bn2graph.
BNinference2dot
(bn, size='4', engine=None, evs={}, targets={}, format='png', nodeColor=None, arcWidth=None, cmap=None) create a pydotplus representation of an inference in a BN
Parameters: - bn (pyAgrum.BayesNet) –
- size (string) – size of the rendered graph
- Inference engine (pyAgrum) – inference algorithm used. If None, LazyPropagation will be used
- evs (dictionnary) – map of evidence
- targets (set) – set of targets. If targets={} then each node is a target
- format (string) – render as “png” or “svg”
- nodeColor – a nodeMap of values to be shown as color nodes (with special color for 0 and 1)
- arcWidth – a arcMap of values to be shown as bold arcs
- cmap – color map to show the vals
Returns: the desired representation of the inference
Hi-level functions¶
-
pyAgrum.lib.bn2graph.
dotize
(aBN, name, format='pdf') From a bn, creates an image of the BN
Parameters: - bn (pyAgrum.BayesNet) – the bayes net to show
- name (string) – the filename (without extension) for the image
- format (string) – format in [‘pdf’,’png’,’fig’,’jpg’,’svg’]
-
pyAgrum.lib.bn2graph.
pngize
(aBN, name) From a bn, creates a png of the BN
Parameters: - bn (pyAgrum.BayesNet) – the bayes net to show
- name (string) – the filename (without extension) for the image
-
pyAgrum.lib.bn2graph.
pdfize
(aBN, name) From a bn, creates a pdf of the BN
Parameters: - bn (pyAgrum.BayesNet) – the bayes net to show
- name (string) – the filename (without extension) for the image
Module dynamic bayesian network¶

other pyAgrum.lib modules¶
bn2roc¶
-
pyAgrum.lib.bn2roc.
module_help
(exit_value=1, message='') defines help viewed if args are not OK on command line, and exit with exit_value
-
pyAgrum.lib.bn2roc.
showROC
(bn, csv_name, variable, label, visible=True, show_fig=False, with_labels=True) Compute the ROC curve and save the result in the folder of the csv file.
Parameters: - bn (pyAgrum.BayesNet) – a bayesian network
- csv_name (str) – a csv filename
- target (str) – the target
- label (str) – the target label
- visible (bool) – indicates if the resulting curve must be printed
bn2csv¶
Samples generation w.r.t to a probability distribution represented by a Bayesian network.
-
class
pyAgrum.lib.bn2csv.
CSVGenerator
Bases:
object
Class for samples generation w.r.t to a probability distribution represented by a Bayesian network.
-
caching_probas
(bn, node_id, n, par) Parameters: - bn (pyAgrum.BayesNet) – a Bayesian network
- node_id (int) – a node id
- n (int) – a node id
- par (list) – the node’s parents
Returns: the node’s probabilities
Return type: list
-
cachingnameAndParents
(bn, n) Compute a list of parents for node n in BN bn.
Parameters: - bn (pyAgrum.BayesNet) – a Bayesian network
- n – (int) a node id
- n – (str) a node name
Returns: a couple of name of n and list of parents names
Return type: tuple
-
static
draw
(tab) draw a value using tab as probability table.
Parameters: tab (list) – a probability table Returns: the couple (i,proba) Return type: tuple
-
static
nameAndParents
(bn, n) Compute a list of parents for node n in BN bn.
Parameters: - bn (pyAgrum.BayesNet) – a Bayesian network
- n – (int) a node id
- n – (str) a node name
Returns: a couple of name of n and list of parents names
Return type: tuple
Raises: gum.IndexError
– If the node is not in the Bayesian network
-
newSample
(bn, seq) Generate a sample w.r.t to the bn using the variable sequence seq (topological order)
Parameters: - bn (pyAgrum.BayesNet) – a Bayesian network
- seq (list) – a variable sequence
Returns: the coule (sample,log2-likelihood)
Return type: tuple
-
proceed
(name_in, name_out, n, visible, with_labels) From the file name_in (BN file), generate n samples and save them in name_out
Parameters: - name_in (str) – a file name
- name_out (str) – the output file
- n (int) – the number of samples
- visible (bool) – indicate if a progress bar should be displayed
- with_labels (bool) – indicate if values should be labelled or not
Returns: the log2-likelihood of the n samples database
Return type: double
-
-
pyAgrum.lib.bn2csv.
generateCSV
(name_in, name_out, n, visible=False, with_labels=True) From the file name_in (BN file), generate n samples and save them in name_out
Parameters: - name_in (str) – a file name
- name_out (str) – the output file
- n (int) – the number of samples
- visible (bool) – indicate if a progress bar should be displayed
- with_labels (bool) – indicate if values should be labelled or not
Returns: the log2-likelihood of the n samples database
Return type: double
-
pyAgrum.lib.bn2csv.
module_help
(exit_value=1) defines help viewed if args are not OK on command line, and exit with exit_value
bn2scores¶
-
pyAgrum.lib.bn2scores.
checkCompatibility
(bn, fields, csv_name) check if variables of the bn are in the fields
if not : return None if compatibilty : return a list of position for variables in fields
-
pyAgrum.lib.bn2scores.
computeScores
(bn_name, csv_name, visible=False, transforme_label=None)
-
pyAgrum.lib.bn2scores.
getNumLabel
(inst, i, label, transforme_label)
-
pyAgrum.lib.bn2scores.
lines_count
(filename) count lines in a file
-
pyAgrum.lib.bn2scores.
module_help
(exit_value=1) defines help viewed if args are not OK on command line, and exit with exit_value
-
pyAgrum.lib.bn2scores.
stringify
(s)
bn_vs_bn¶
-
class
pyAgrum.lib.bn_vs_bn.
GraphicalBNComparator
(name1, name2, delta=1e-06) Bases:
object
BNGraphicalComparator allows to compare in multiple way 2 BNs…The smallest assumption is that the names of the variables are the same in the 2 BNs. But some comparisons will have also to check the type and domainSize of the variables. The bns have not exactly the same role : _bn1 is rather the referent model for the comparison whereas _bn2 is the compared one to the referent model
Parameters: - name1 (str or pyAgrum.BayesNet) – a BN or a filename for reference
- name2 (str or pyAgrum.BayesNet) – another BN or antoher filename for comparison
-
dotDiff
() Return a pydotplus graph that compares the arcs of _bn1 (reference) with those of self._bn2. full black line: the arc is common for both full red line: the arc is common but inverted in _bn2 dotted black line: the arc is added in _bn2 dotted red line: the arc is removed in _bn2
Returns: the result dot graph Return type: pydotplus.Dot
-
equivalentBNs
() Check if the 2 BNs are equivalent :
- same variables
- same graphical structure
- same parmaeters
Returns: “OK” if bn are the same, a description of the error otherwise Return type: str
-
scores
() Compute Precision, Recall, F-score for self._bn2 compared to self._bn1
precision and recall are computed considering BN1 as the reference
Fscor is 2*(recall* precision)/(recall+precision) and is the weighted average of Precision and Recall.
dist2opt=square root of (1-precision)^2+(1-recall)^2 and represents the euclidian distance to the ideal point (precision=1, recall=1)
Returns: A dictionnary containing ‘precision’, ‘recall’, ‘fscore’, ‘dist2opt’ and so on. Return type: dict[str,double]
-
pyAgrum.lib.bn_vs_bn.
module_help
(exit_value=1) defines help viewed if args are not OK on command line, and exit with exit_value
pretty_print¶
-
pyAgrum.lib.pretty_print.
bn2txt
(aBN) Representation of all CPTs of a gum.BayesNet
Parameters: aBN – the bayes net or the name of the file Returns:
-
pyAgrum.lib.pretty_print.
cpt2txt
(cpt, digits=4) string representation of a gum.Potential
Parameters: cpt – the Potential to represent Returns: the string representation
-
pyAgrum.lib.pretty_print.
max_length
(v)
-
pyAgrum.lib.pretty_print.
module_help
(exit_value=1) defines help viewed if args are not OK on command line, and exit with exit_value
Indices and tables¶
Documentation tools¶
Read me/To do¶
Read me¶
The following command is used in order to check the completion of the documentation :
python act guideline
- OPTIONS
- –correction to display the undocumented methods
Lists of methods and classes to skip are defined in the missingDocs python script (in acttools).
To do¶
Type issues¶
CredalNet.credalNet_currentCpt (issue with return type)
CredalNet.credalNet_srcCPt (issue with return type)
CredalNet.get_CPT_max (issue with return type)
CredalNet.get_CPT_min (issue with return type)
CredalNet.setCPT (issue with parameter type)
CredalNet.setCPTs (issue with parameter type)
InfluenceDiagramInference.displayStrongJunctionTree (issue with parameter type)
LazyPropagation.setTriangulation (issue with parameter type, Triangulation is not a wrapped object)
BayesNet.variableNodeMap (issue with return type, VariableNodeMap is not a wrapped object)
Exception issues¶
RangeVar.setMinVal(new_minval) (resp. setMaxVal(new_maxval)) should raise an exception if new_minval>maxval (resp. new_maxval<minval)
Potential.add should raise an exception when a DiscretizedVariable is added without any tick.
Methods to add¶
- gum::LabelizedVariable::addLabels
- gum::DiscretizedVariable::addTicks
Methods to overload¶
hasHardEvidence with a node id in parameter (instead of a node name)
Other issues¶
gum.CredalNet.dynamicExceptations needed in order to make dynamicExpMax and dynamicExpMin work.
Can’t document MarkovBlanket and EssentialGraph for unknown reason.
Version of addChanceNode and addUtilityNode with a multiDimImplementation as parameter should be disabled as the object isn’t wrapped.