Undirected Graphical Model
pyagrum.MarkovRandomField is the main class for representing and manipulating Markov random
fields in pyAgrum. It stores the undirected graph structure and the potential functions (tensors) over
its cliques.
- class pyagrum.MarkovRandomField(*args)
MarkovRandomField represents a Markov random field.
- MarkovRandomField(name=’’) -> MarkovRandomField
- Parameters:
name (str) – the name of the Bayes Net
- MarkovRandomField(source) -> MarkovRandomField
- Parameters:
source (pyagrum.MarkovRandomField) – the Markov random field to copy
- add(*args)
Add a variable to the pyagrum.MarkovRandomField.
- Parameters:
variable (pyagrum.DiscreteVariable) – the variable added
name (str) – the variable name
nbrmod (int) – the number of modalities for the new variable
id (int) – the variable forced id in the pyagrum.MarkovRandomField
- Returns:
the id of the new node
- Return type:
int
- Raises:
pyagrum.DuplicateLabel – If variable.name() is already used in this pyagrum.MarkovRandomField.
pyagrum.OperationNotAllowed – If nbrmod is less than 2
pyagrum.DuplicateElement – If id is already used.
- addFactor(*args)
Add a factor from a list or a set of id or str. If the argument is a set, the order is the order of the IDs of the variables
- Parameters:
seq (sequence (list or set) of int or string) – The sequence (ordered or not) of node id or names
- Return type:
- addStructureListener(whenNodeAdded=None, whenNodeDeleted=None, whenEdgeAdded=None, whenedgeDeleted=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
whenEdgeAdded (lambda expression) – a function for when an edge is added
whenEdgeDeleted (lambda expression) – a function for when an edge is removed
- addVariables(listFastVariables, default_nbr_mod=2)
Add a list of variable in the form of ‘fast’ syntax.
- Parameters:
listFastVariables (list[str]) – the list of variables in ‘fast’ syntax.
default_nbr_mod (int) – the number of modalities for the variable if not specified following fast syntax. Note that default_nbr_mod=1 is mandatory to create variables with only one modality (for utility for instance).
- Returns:
the list of created ids.
- Return type:
list[int]
- adjacencyMatrix()
adjacency matrix from a graph/graphical models
Compute the adjacency matrix of a pyAgrum’s graph or graphical models (more generally an object that has nodes, children/parents or neighbours methods)
- Returns:
adjacency matrix (as numpy.ndarray) with nodeId as key.
- Return type:
numpy.ndarray
- beginTopologyTransformation()
Begin a sequence of structural modifications (factor additions/deletions).
Structural changes are batched until endTopologyTransformation is called, which then adjusts all factor dimensions.
- Return type:
None
- changeVariableLabel(*args)
change the label of the variable associated to nodeId to the new value.
- Parameters:
var (int | str) – a variable’s id (int) or name
old_label (str) – the old label
new_label (str) – the new label
- Raises:
pyagrum.NotFound – if id/name is not a variable or if old_label does not exist.
- Return type:
None
- changeVariableName(*args)
Changes a variable’s name in the pyagrum.MarkovRandomField.
This will change the pyagrum.DiscreteVariable names in the pyagrum.MarkovRandomField.
- Parameters:
car (int | str) – a variable’s id (int) or name
new_name (str) – the new name of the variable
- Raises:
pyagrum.DuplicateLabel – If new_name is already used in this MarkovRandomField.
pyagrum.NotFound – If no variable matches id.
- Return type:
None
- clear()
Clear the whole MarkovRandomField
- Return type:
None
- completeInstantiation()
Give an instantiation over all the variables of the model
- Returns:
a complete Instantiation for the model
- Return type:
- connectedComponents()
Return the connected components of the undirected model.
Each node is mapped to the id of its component root.
- Returns:
mapping node id → component root id
- Return type:
dict[int, int]
- connectedComponentsCount()
number of connected components
- Returns:
the number of connected components in the graph.
- Return type:
int
- connectedComponentsList()
connected components as a dict of sets
- Returns:
dict of connected components (as sets of nodeIds) keyed by an arbitrary root nodeId per component.
- Return type:
dict(int, set[int])
- dim()
Return the dimension (total number of free parameters) of the Markov random field.
- Returns:
the number of free parameters
- Return type:
int
- edges()
- Returns:
the set of edges in the Markov random field
- Return type:
set
- empty()
Check if there are some variables in the model.
- Returns:
True if there is no variable in the model.
- Return type:
bool
- endTopologyTransformation()
Terminates a sequence of insertions/deletions of arcs by adjusting all CPTs dimensions. End Multiple Change for all CPTs.
- Return type:
- erase(*args)
Remove a variable from the pyagrum.MarkovRandomField.
Removes the corresponding variable from the pyagrum.MarkovRandomField and from all of it’s children pyagrum.Tensor.
If no variable matches the given id, then nothing is done.
- Parameters:
var (int | str | pyagrum.DiscreteVariable) – a variable’s id (int) or name of variable or a reference of this variable to remove.
- Return type:
None
- eraseFactor(*args)
Remove the factor that covers a given set of variables.
- Parameters:
vars (set[int] | list[str]) – the set of variable ids or names whose factor should be removed
- Return type:
None
- exists(*args)
Check if a node with this name or id exists
- Parameters:
norid (str|int) – name or id of the searched node
- Returns:
True if there is a node with such a name or id
- Return type:
bool
- existsEdge(*args)
Check whether an edge exists between two nodes.
- Parameters:
n1 (int | str) – one endpoint (id or name)
n2 (int | str) – the other endpoint (id or name)
- Returns:
True if the edge exists
- Return type:
bool
- existsProperty(name)
Check whether a property key exists in the model’s metadata.
- Parameters:
name (str) – the property name
- Returns:
True if the property exists
- Return type:
bool
- factor(*args)
Returns the factor of a set of variables (if existing).
- Parameters:
vars (set) – A set of ids or names of variable the pyagrum.MarkovRandomField.
- Returns:
The factor of the set of nodes.
- Return type:
- Raises:
pyagrum.NotFound – If no variable’s id matches varId.
- factors()
Return the table of all factors in the Markov random field.
- Returns:
a dict mapping frozenset[int] (node id sets) to pyagrum.Tensor
- Return type:
dict
- family(*args)
Return the family of a node: the node itself plus all its neighbours.
- Parameters:
id (int) – the node id
- Returns:
the node and all its neighbours
- Return type:
set[int]
- static fastPrototype(*args)
- Create a Markov random field with a modified dot-like syntax which specifies:
the structure
a--b--c;b--d--e;. The substringa--b--cindicates a factor with the scope (a,b,c).the type of the variables with different syntax (cf documentation).
Examples
>>> import pyagrum as gum >>> bn=pyagrum.MarkovRandomField.fastPrototype('A--B[1,3]--C{yes|No}--D[2,4]--E[1,2.5,3.9]',6)
- Parameters:
dotlike (str) – the string containing the specification
domainSize (int or str) – the default domain size or the default domain for variables
- Returns:
the resulting Markov random field
- Return type:
- static fromBN(bn)
Create a Markov random field from a Bayesian network.
- Parameters:
bn (pyagrum.BayesNet) – the Bayesian network to convert
- Returns:
a new MRF with the same variables and moralised structure
- Return type:
- generateFactor(vars)
Randomly generate factor parameters for a given factor in a given structure.
- Parameters:
node (int | str) – a variable’s id (int) or name
vars (
list[int])
- Return type:
None
- generateFactors()
Randomly generates factors parameters for a given structure.
- Return type:
None
- graph()
Return the underlying undirected graph.
- Returns:
the underlying graph
- Return type:
- hasSameStructure(other)
Check whether this model has the same undirected structure as another UGmodel.
- Parameters:
other (pyagrum.MarkovRandomField) – the model to compare with
- Returns:
True if the undirected structures are identical
- Return type:
bool
- idFromName(name)
Return the node id of a variable given its name.
- Parameters:
name (str) – the name of the variable
- Returns:
the node id of the variable
- Return type:
int
- Raises:
pyagrum.NotFound – if no variable with this name exists in the model
- ids(names)
List of ids for a list of names of variables in the model
- Parameters:
lov (list of str) – List of variable names
names (
tuple[str,...])
- Returns:
The ids for the list of names of the graph variables
- Return type:
list of int
- isIndependent(*args)
check if nodes X and nodes Y are independent given nodes Z
- Parameters:
X (str|int|list of str|int) – a list of of nodeIds or names
Y (str|int|list of str|int) – a list of of nodeIds or names
Z (str|int|list of str|int) – a list of of nodeIds or names
- Raises:
InvalidArgument – if X and Y share variables
- Returns:
True if X and Y are independent given Z in the model
- Return type:
bool
- loadGUM(name, binary=False)
Load a jgum (JSON) or bgum (binary/msgpack) file.
- Parameters:
name (str) – the file’s path (extension:
.jgumfor JSON,.bgumfor binary)binary (bool) – if True, read as bgum (msgpack) regardless of extension (default: False)
- Raises:
pyagrum.IOError – If file not found
pyagrum.FatalError – If file content is not valid
- Return type:
None
See also
- JGUM / BGUM Format Reference
complete format reference
- loadGUMstring(content)
Deserialize a MarkovRandomField from a jgum JSON string.
- Parameters:
content (str) – a JSON string in jgum format
- Raises:
pyagrum.FatalError – If the string is not valid jgum JSON or the type field does not match
"MRF"- Return type:
None
See also
- JGUM / BGUM Format Reference
complete format reference
- loadUAI(*args)
Load an UAI file.
- Parameters:
name (str) – the name’s file
l (list) – list of functions to execute
- Raises:
pyagrum.IOError – If file not found
pyagrum.FatalError – If file is not valid
- Return type:
str
- log10DomainSize()
returns the log10 of the domain size of the model defined as the product of the domain sizes of the variables in the model.
- Returns:
the log10 domain size.
- Return type:
float
- maxNonOneParam()
Return the maximum parameter value strictly less than 1 across all factors.
- Returns:
the maximum non-one factor parameter
- Return type:
float
- maxParam()
Return the maximum parameter value across all factors.
- Returns:
the maximum factor parameter
- Return type:
float
- maxVarDomainSize()
Return the maximum domain size among all variables in the model.
- Returns:
the maximum domain size
- Return type:
int
- minNonZeroParam()
Return the minimum non-zero parameter value across all factors.
- Returns:
the minimum non-zero factor parameter
- Return type:
float
- minParam()
Return the minimum parameter value across all factors.
- Returns:
the minimum factor parameter
- Return type:
float
- minimalCondSet(*args)
Return a minimal conditioning set of a target given source nodes in the MRF.
- Parameters:
target (int | str | list[int|str]) – the target node id(s) or name(s)
soids (list[int|str]) – the list of source node ids or names
- Returns:
the minimal conditioning set (as node ids)
- Return type:
set[int]
- names()
Set of names of variables in the model
- Returns:
The names of the graph variables
- Return type:
set
- neighbours(norid)
Return the set of neighbours of a node.
- Parameters:
id (int) – the node id
norid (
object)
- Returns:
the set of neighbour node ids
- Return type:
set[int]
- nodeId(var)
Return the node id of a variable.
- Parameters:
var (pyagrum.DiscreteVariable) – the variable
- Returns:
the node id of the variable
- Return type:
int
- Raises:
pyagrum.NotFound – if the variable does not exist in the model
- nodes()
Return the set of node ids in the model.
- Returns:
the set of node ids
- Return type:
set[int]
- nodeset(names)
Set of ids for a list of names of variables in the model
- Parameters:
lov (list of str) – List of variable names
names (
tuple[str,...])
- Returns:
The set of ids for the list of names of the graph variables
- Return type:
set
- properties()
Return the keys of all metadata properties of the model.
- Returns:
tuple of property names (use
property()to retrieve a value by key)- Return type:
tuple[str, …]
- saveGUM(name, binary=False, indent=2)
Save the MarkovRandomField in a jgum (JSON) or bgum (binary/msgpack) file.
Metadata properties (
software,creation,lastModification) are updated automatically.- Parameters:
name (str) – the file’s path
binary (bool) – if True, write as bgum (msgpack); otherwise write as jgum (JSON) (default: False)
indent (int) – indentation level for JSON output; -1 for compact, 2 for pretty-printed (default: 2)
- Return type:
None
See also
- JGUM / BGUM Format Reference
complete format reference
- saveGUMstring(indent=2)
Serialize the MarkovRandomField to a jgum JSON string.
Metadata properties (
software,creation,lastModification) are updated automatically.- Parameters:
indent (int) – indentation level; -1 for compact, 2 for pretty-printed (default: 2)
- Returns:
a JSON string representing the MarkovRandomField in jgum format
- Return type:
str
See also
- JGUM / BGUM Format Reference
complete format reference
- saveUAI(name)
Save the MarkovRandomField in an UAI file.
- Parameters:
name (str) – the file’s name
- Return type:
None
- size()
Return the number of nodes (variables) in the graphical model.
- Returns:
the number of nodes
- Return type:
int
- sizeEdges()
Return the number of edges in the model.
- Returns:
the number of edges
- Return type:
int
- smallestFactorFromNode(node)
Return the id set of the smallest factor that contains the given node.
- Parameters:
node (int) – the node id
- Returns:
the id set of the smallest factor containing this node
- Return type:
set[int]
- Raises:
pyagrum.NotFound – if no factor contains this node
- static spaceCplxToString(dSize, dim, usedMem)
Return a human-readable string summarising the space complexity of a graphical model.
- Parameters:
dSize (float) – log10 of the joint domain size
dim (int) – number of independent parameters
usedMem (int) – memory footprint in bytes
- Returns:
a string of the form
'domainSize: X, dim: Y, mem: Z'- Return type:
str
- property thisown
The membership flag
- toDot()
Return a Graphviz dot representation of the Markov random field.
- Returns:
a dot-format string
- Return type:
str
- toDotAsFactorGraph()
Return a Graphviz dot representation of the Markov random field as a factor graph.
- Returns:
a dot-format string with variable nodes and factor nodes
- Return type:
str
- toFast(filename=None)
Export the MRF as fast syntax (in a string or in a python file)
- Parameters:
filename (Optional[str]) – the name of the file (including the prefix), if None , use sys.stdout
- Return type:
str
- updateMetaData()
Update the model’s built-in metadata (version, creation date, last modification date).
This method is called automatically by writers before saving the model to a file.
- Return type:
None
- variable(*args)
Return the variable associated with a given node id.
- Parameters:
id (int) – the node id
- Returns:
the variable
- Return type:
- Raises:
pyagrum.NotFound – if the node id does not exist
- variableFromName(name)
Return the variable with the given name.
- Parameters:
name (str) – the name of the variable
- Returns:
the variable
- Return type:
- Raises:
pyagrum.NotFound – if no variable with this name exists in the model
- variableNodeMap()
Return the variable-to-node mapping of the model.
- Returns:
the internal variable-to-node bijection
- Return type:
pyagrum.VariableNodeMap
- variables(*args)
Return the set of variables corresponding to a list of names or a set of node ids.
- Parameters:
args (list[str] or set[int]) – variable names or node ids
- Returns:
the set of corresponding variables
- Return type:
pyagrum.VariableSet