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.

>>> import pyAgrum as gum
>>> 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                          |
B     ||1        |2        |3        |
------||---------|---------|---------|
1     || 1.0000  | 2.0000  | 3.0000  |
2     || 4.0000  | 5.0000  | 6.0000  |
>>> print(p.normalizeAsCPT())
      ||  A                          |
B     ||1        |2        |3        |
------||---------|---------|---------|
1     || 0.1667  | 0.3333  | 0.5000  |
2     || 0.2667  | 0.3333  | 0.4000  |
  • For addressing and looping in a pyAgrum.Potential structure, pyAgrum provides Instantiation 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(f"{I} -> {p.get(I)}")
<A:1|B:1> -> 0.16666666666666666
>>> I["B"]="2";print(f"{I} -> {p.get(I)}")
<A:1|B:2> -> 0.26666666666666666
>>> c=gum.RangeVariable("C","variable C",1,5)
>>> q=gum.Potential().add(a).add(c).fillWith(1)
>>> print(p+q)
             ||  A                          |
C     |B     ||1        |2        |3        |
------|------||---------|---------|---------|
1     |1     || 1.1667  | 1.3333  | 1.5000  |
2     |1     || 1.1667  | 1.3333  | 1.5000  |
3     |1     || 1.1667  | 1.3333  | 1.5000  |
4     |1     || 1.1667  | 1.3333  | 1.5000  |
5     |1     || 1.1667  | 1.3333  | 1.5000  |
1     |2     || 1.2667  | 1.3333  | 1.4000  |
2     |2     || 1.2667  | 1.3333  | 1.4000  |
3     |2     || 1.2667  | 1.3333  | 1.4000  |
4     |2     || 1.2667  | 1.3333  | 1.4000  |
5     |2     || 1.2667  | 1.3333  | 1.4000  |
>>> print((p*q).margSumOut(["B","C"])) # marginalize p*q over B and C(using sum)
  A                          |
1        |2        |3        |
---------|---------|---------|
 2.1667  | 3.3333  | 4.5000  |

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.

Instantiation() -> Instantiation

default constructor

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(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

Return type:

None

addVarsFromModel(model, names)

From a graphical model, add all the variable whose names are in the iterable

Parameters:
  • model (pyAgrum.GraphicalModel) –

  • network (a (discrete) graphical model such as Bayesian) –

  • field (Markov random) –

  • Diagram (Influence) –

  • etc.

  • names (iterable of strings) –

  • string) (a list/set/etc of names of variables (as) –

Returns:

  • pyAgrum.Instantiation

  • the current instantiation (self) in order to chain methods.

chgVal(*args)

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:

pyAgrum.Instantiation

Raises:
  • NotFound – If variable v does not belong to the instantiation.

  • OutOfBounds – If newval is not a possible value for the variable.

clear()

Erase all variables from an Instantiation.

Return type:

None

contains(*args)

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()

Operator –.

Return type:

None

decIn(i)

Operator – for the variables in i.

Parameters:

i (pyAgrum.Instantiation) – The set of variables to decrement in this Instantiation

Return type:

None

decNotVar(v)

Operator – for vars which are not v.

Parameters:

v (pyAgrum.DiscreteVariable) – The variable not to decrement in this Instantiation.

Return type:

None

decOut(i)

Operator – for the variables not in i.

Parameters:

i (pyAgrum.Instantiation) – The set of variables to not decrement in this Instantiation.

Return type:

None

decVar(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.

Return type:

None

domainSize()
Returns:

The product of the variable’s domain size in the Instantiation.

Return type:

int

empty()
Returns:

True if the instantiation is empty.

Return type:

bool

end()
Returns:

True if the Instantiation reached the end.

Return type:

bool

erase(*args)
Parameters:

v (pyAgrum.DiscreteVariable) – The variable to be removed from this Instantiation.

Raises:

NotFound – If v does not belong to this Instantiation.

Return type:

None

fromdict(dict)

Change the values in an instantiation from a dictionary {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.

Parameters:

dict (object) –

Return type:

Instantiation

hamming()
Returns:

the hamming distance of this instantiation.

Return type:

int

inOverflow()
Returns:

True if the current value of the tuple is correct

Return type:

bool

inc()

Operator ++.

Return type:

None

incIn(i)

Operator ++ for the variables in i.

Parameters:

i (pyAgrum.Instantiation) – The set of variables to increment in this Instantiation.

Return type:

None

incNotVar(v)

Operator ++ for vars which are not v.

Parameters:

v (pyAgrum.DiscreteVariable) – The variable not to increment in this Instantiation.

Return type:

None

incOut(i)

Operator ++ for the variables not in i.

Parameters:

i (Instantiation) – The set of variable to not increment in this Instantiation.

Return type:

None

incVar(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.

Return type:

None

isMutable()
Return type:

bool

nbrDim()
Returns:

The number of variables in the Instantiation.

Return type:

int

pos(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()
Returns:

True if the Instantiation reached the rend.

Return type:

bool

reorder(*args)

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.

Return type:

None

setFirst()

Assign the first values to the tuple of the Instantiation.

Return type:

None

setFirstIn(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.

Return type:

None

setFirstNotVar(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.

Return type:

None

setFirstOut(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.

Return type:

None

setFirstVar(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.

Return type:

None

setLast()

Assign the last values in the Instantiation.

Return type:

None

setLastIn(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.

Return type:

None

setLastNotVar(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.

Return type:

None

setLastOut(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.

Return type:

None

setLastVar(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.

Return type:

None

setMutable()
Return type:

None

setVals(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

todict(withLabels=False)

Create a dictionary {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. Default is False

Returns:

The dictionary

Return type:

Dict[str,int]

unsetEnd()

Alias for unsetOverflow().

Return type:

None

unsetOverflow()

Removes the flag overflow.

Return type:

None

val(*args)
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(*args)
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()
Returns:

a list containing the sequence of variables

Return type:

list

Potential

class pyAgrum.Potential(*args)

Class representing a potential.

Potential() -> Potential

default constructor

Potential(src) -> Potential
Parameters:
  • src (pyAgrum.Potential) – the Potential to copy

KL(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:
abs()

Apply abs on every element of the container

Returns:

a reference to the modified potential.

Return type:

pyAgrum.Potential

add(v)

Add a discrete variable to the potential.

Parameters:

v (pyAgrum.DiscreteVariable) – the var to be added

Raises:
Returns:

a reference to the modified potential.

Return type:

pyAgrum.Potential

argmax()
Returns:

the list of positions of the max and the max of all elements in the Potential

Return type:

Tuple[Dict[str,int],float]

argmin()
Returns:

the list of positions of the min and the min of all elements in the Potential

Return type:

Tuple[Dict[str,int],float]

contains(v)
Parameters:

v (pyAgrum.Potential) – a DiscreteVariable.

Returns:

True if the var is in the potential

Return type:

bool

domainSize()
Return type:

int

draw()

draw a value using the potential as a probability table.

Returns:

the index of the drawn value

Return type:

int

empty()
Returns:

Returns true if no variable is in the potential.

Return type:

bool

entropy()
Returns:

the entropy of the potential

Return type:

float

static evEq(v, val)
Parameters:
Return type:

Potential

static evGt(v, val)
Parameters:
Return type:

Potential

static evIn(v, val1, val2)
Parameters:
Return type:

Potential

static evLt(v, val)
Parameters:
Return type:

Potential

expectedValue(*args)

Calculate the mathematical expected value of a (joint) random variable using the given function as an argument.

Parameters:

func (function(Dict[str,int])->float) – A function that takes a single argument, representing the value of a python representation of a pyAgrum.Instantiation (as a dictionary), and returns a float.

Warning

The pyAgrum.Potential is assumed to contain a joint distribution.

Examples

>>> def log2cptA(x):
...   return -math.log2(bn.cpt('A')[x])
>>> entropy_of_A=bn.cpt('A').expectedValue(log2cptA) # OK it A has no parents.
Returns:

The mathematical expected value of the random variable calculated using the given function as an argument.

Return type:

float

extract(*args)

create a new Potential extracted from self given a partial instantiation.

Parameters:
  • inst (pyAgrum.instantiation) – a partial instantiation

  • dict (Dict[str,str|int]) – a dictionnary containing values for some discrete variables.

Warning

if the dictionnary contains a key that is not the name of a variable in the pyAgrum.Potential, this key is just not used without notification. Then pyAgrum.Potential.extract concerns only the variables that both are in the Potential and in the dictionnary.

Returns:

the new Potential

Return type:

pyAgrum.Potential

fillFromDistribution(distribution, **s_fns)

Automatically fills the potential as a familly of distributions whose parameters are found using evaluation of the expressions s_fns.

The symbolic expressions s_fns gives a value for the named parameters of the distributions.

Examples

>>> import pyAgrum as gum
>>> bn=pyAgrum.fastBN('A[3]->B[3]<-C[3]')
>>> bn.cpt('B').fillFromFunction('(A+C)/2')
Parameters:

s_fns (a list of named arguments (str)) – the named arguments with an evaluation of the expressions in s_fns are passed as argument for the chosen distribution.

Returns:

a reference to the modified potential

Return type:

pyAgrum.Potential

Raises:

pyAgrum.InvalidArgument – If the first variable is Labelized.

fillFromFunction(s_fn)

Automatically fills the potential as a deterministic CPT with the evaluation of the expression s_fn.

The symbolic expression s_fn gives a value for the first variable, depending on the following variables. The computed CPT is deterministic.

Examples

>>> import pyAgrum as gum
>>> bn=pyAgrum.fastBN('A[3]->B[3]<-C[3]')
>>> bn.cpt('B').fillFromFunction('(A+C)/2')
Parameters:

s_fn (str) – a symbolic expression using the name of the second and following variables of the Potential and giving a value to the first variable of the Potential. This evaluation is done in a context that inclides ‘math’ module.

Warning

The expression may have any numerical values, but will be then transformed to the closest correct value for the range of the variable.

Returns:

a reference to the modified potential

Return type:

pyAgrum.Potential

Raises:

pyAgrum.InvalidArgument – If the first variable is Labelized.

fillWith(*args)

Automatically fills the potential with v.

Parameters:
  • v (number or list of values or pyAgrum.Potential) – a value or a list/pyAgrum.Potential containing the values to fill the Potential with.

  • mapping (list|tuple|dict) –

Warning

  • if v is a list, the size of the list must be the size of the potential

  • if v is a ref:pyAgrum.Potential, it must contain variables with exactly the same names and labels but not necessarily the same variables. If

  • If the second argument mapping is given, mapping explains how to map the variables of the potential source to the variables of the potential destination.

  • If mapping is a sequence, the order follows the same order as destination.names. If mapping is a dict, the keys are the names in the destination and the values are the names in the source.

Returns:

a reference to the modified potentia

Return type:

pyAgrum.Potential

Raises:
fillWithFunction(s, noise=None)

Automatically fills the potential as a (quasi) deterministic CPT with the evaluation of the expression s.

The expression s gives a value for the first variable using the names of the last variables. The computed CPT is deterministic unless noise is used to add a ‘probabilistic’ noise around the exact value given by the expression.

Examples

>>> import pyAgrum as gum
>>> bn=pyAgrum.fastBN("A[3]->B[3]<-C[3]")
>>> bn.cpt("B").fillWithFunction("(A+C)/2")
Parameters:

s (str) – an expression using the name of the last variables of the Potential and giving a value to the first variable of the Potential

Warning

The expression may have any numerical values, but will be then transformed to the closest correct value for the range of the variable.

Note

Deprecated. Please use pyAgrum.Potential.fillFromFunction instead.

Returns:

a reference to the modified potential

Return type:

pyAgrum.Potential

Raises:

pyAgrum.InvalidArgument – If the first variable is Labelized or Integer, or if the len of the noise is not odd.

findAll(v)
Parameters:

v (float) –

Return type:

List[Dict[str, int]]

get(i)
Parameters:

i (pyAgrum.Instantiation) – an Instantiation

Returns:

the value in the Potential at the position given by the instantiation

Return type:

float

inverse()
Return type:

Potential

isEvidence()
Return type:

bool

isNonZeroMap()
Returns:

a boolean-like potential using the predicate isNonZero.

Return type:

pyAgrum.Potential

log2()

log2 all the values in the Potential :rtype: Potential

Warning

When the Potential contains 0 or negative values, no exception are raised but -inf or nan values are assigned.

loopIn()

Generator to iterate inside a Potential.

Yield an pyAgrum.Instantiation that iterates over all the possible values for the pyAgrum.Potential

Examples

>>> import pyAgrum as gum
>>> bn=pyAgrum.fastBN("A[3]->B[3]<-C[3]")
>>> for i in bn.cpt("B").loopIn():
      print(i)
      print(bn.cpt("B").get(i))
      bn.cpt("B").set(i,0.3)
margMaxIn(*args)

Projection using max as operation.

Parameters:

varnames (set) – the set of vars to keep

Returns:

the projected Potential

Return type:

pyAgrum.Potential

margMaxOut(*args)

Projection using max as operation.

Parameters:

varnames (set) – the set of vars to eliminate

Returns:

the projected Potential

Return type:

pyAgrum.Potential

Raises:

pyAgrum.InvalidArgument – If varnames contains only one variable that does not exist in the Potential

margMinIn(*args)

Projection using min as operation.

Parameters:

varnames (set) – the set of vars to keep

Returns:

the projected Potential

Return type:

pyAgrum.Potential

margMinOut(*args)

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(*args)

Projection using multiplication as operation.

Parameters:

varnames (set) – the set of vars to keep

Returns:

the projected Potential

Return type:

pyAgrum.Potential

margProdOut(*args)

Projection using multiplication as operation.

Parameters:

varnames (set) – the set of vars to eliminate

Returns:

the projected Potential

Return type:

pyAgrum.Potential

Raises:

pyAgrum.InvalidArgument – If varnames contains only one variable that does not exist in the Potential

margSumIn(*args)

Projection using sum as operation.

Parameters:

varnames (set) – the set of vars to keep

Returns:

the projected Potential

Return type:

pyAgrum.Potential

margSumOut(*args)

Projection using sum as operation.

Parameters:

varnames (set) – the set of vars to eliminate

Returns:

the projected Potential

Return type:

pyAgrum.Potential

Raises:

pyAgrum.InvalidArgument – If varnames contains only one variable that does not exist in the Potential

max()
Returns:

the maximum of all elements in the Potential

Return type:

float

maxNonOne()
Returns:

the maximum of non one elements in the Potential

Return type:

float

Raises:

pyAgrum.NotFound – If all value == 1.0

min()
Returns:

the min of all elements in the Potential

Return type:

float

minNonZero()
Returns:

the min of non zero elements in the Potential

Return type:

float

Raises:

pyAgrum.NotFound – If all value == 0.0

property names
Returns:

a list containing the name of each variables in the potential

Return type:

list

Warning

listed in the reverse order of the enumeration order of the variables.

nbrDim(*args)
Returns:

the number of vars in the multidimensional container.

Return type:

int

newFactory()

Erase the Potential content and create a new empty one.

Returns:

a reference to the new Potential

Return type:

pyAgrum.Potential

new_abs()
Return type:

Potential

new_log2()
Return type:

Potential

new_sgn()
Return type:

Potential

new_sq()
Return type:

Potential

noising(alpha)
Parameters:

alpha (float) –

Return type:

Potential

normalize()

Normalize the Potential (do nothing if sum is 0)

Returns:

a reference to the normalized Potential

Return type:

pyAgrum.Potential

normalizeAsCPT(varId=0)

Normalize the Potential as a CPT

Returns:

a reference to the normalized Potential

Return type:

pyAgrum.Potential

Raises:

pyAgrum.FatalError – If some distribution sums to 0

Parameters:

varId (int) –

pos(v)
Parameters:

v (pyAgrum.DiscreteVariable) – The variable for which the index is returned.

Return type:

int

Returns:

Returns the index of a variable.

Raises:

pyAgrum.NotFound – If v is not in this multidimensional matrix.

product()
Returns:

the product of all elements in the Potential

Return type:

float

putFirst(varname)
Parameters:
Returns:

a reference to the modified potential

Return type:

pyAgrum.Potential

Raises:

pyAgrum.InvalidArgument – If the var is not in the potential

random()
Return type:

Potential

randomCPT()
Return type:

Potential

randomDistribution()
Return type:

Potential

remove(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

Parameters:

var (DiscreteVariable) –

reorganize(*args)

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(v)

Create a new potential multiplied by v.

Parameters:

v (float) – a multiplier

Return type:

Potential

Returns:

a reference to the modified potential

set(i, value)

Change the value pointed by i

Parameters:
  • i (pyAgrum.Instantiation) – The Instantiation to be changed

  • value (float) – The new value of the Instantiation

Return type:

None

sgn()
Return type:

Potential

property shape
Returns:

a list containing the dimensions of each variables in the potential

Return type:

list

Warning

p.shape and p[:].shape list the dimensions in different order

sq()

Square all the values in the Potential

Return type:

Potential

sum()
Returns:

the sum of all elements in the Potential

Return type:

float

property thisown

The membership flag

toarray()
Returns:

the potential as an array

Return type:

array

toclipboard(**kwargs)

Write a text representation of object to the system clipboard. This can be pasted into spreadsheet, for instance.

tolatex()

Render object to a LaTeX tabular.

Requires to include booktabs package in the LaTeX document.

Returns:

the potential as LaTeX string

Return type:

str

tolist()
Returns:

the potential as a list

Return type:

list

topandas()
Returns:

the potential as an pandas.DataFrame

Return type:

pandas.DataFrame

translate(v)

Create a new potential added with v.

Parameters:

v (float) – The value to be added

Return type:

Potential

Returns:

a reference to the modified potential

property var_dims
Returns:

a list containing the dimensions of each variables in the potential

Return type:

list

Warning

This methods is deprecated. Please use pyAgrum.Potential.shape and note the change in the order !

var_dims return a list in the reverse order of the enumeration order of the variables.

property var_names
Returns:

a list containing the name of each variables in the potential

Return type:

list

Warning

This methods is deprecated. Please use pyAgrum.Potential.names and note the change in the order !

var_names return a list in the reverse order of the enumeration order of the variables.

variable(*args)
Parameters:

i (int) – An index of this multidimensional matrix.

Return type:

DiscreteVariable

Returns:

the varible at the ith index

Raises:

pyAgrum.NotFound – If i does not reference a variable in this multidimensional matrix.

variablesSequence()
Returns:

a list containing the sequence of variables

Return type:

list