Tensor and Instantiation

pyagrum.Tensor 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.Tensor().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  |
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.Tensor().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).sumOut(["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:
Returns:

  • pyagrum.Instantiation – An empty tuple or a copy of the one in parameters

  • Instantiation is subscriptable therefore values can be easily accessed/modified.

Example

import pyagrum as gum

bn = gum.fastBN("A[3]->B[2]")
i = gum.Instantiation(bn.cpt("B"))  # over the variables of the CPT of B
print(i)
# <B:0|A:0>
i["A"] = 2  # an Instantiation is subscriptable by the names of its variables
i["B"] = "1"  # a label can be given instead of an index
i["A"], i["B"]
# (2, 1)
i.todict()
# {'B': 1, 'A': 2}
bn.cpt("B").get(i) == bn.cpt("B")[{"A": 2, "B": 1}]
# True

Methods

add()

Adds a new variable in the Instantiation.

addVarsFromModel()

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

chgVal()

Assign newval to v (or to the variable at position varPos) in the Instantiation.

clear()

Erase all variables from an Instantiation.

contains()

Indicates whether a given variable belongs to the Instantiation.

dec()

Operator –.

decIn()

Operator – for the variables in i.

decNotVar()

Operator – for vars which are not v.

decOut()

Operator – for the variables not in i.

decVar()

Operator – for variable v only.

domainSize()

empty()

end()

erase()

fromdict()

Change the values in an instantiation from a dictionary {variable_name:value} where value can be a position (int) or a label (string).

hamming()

inOverflow()

inc()

Operator ++.

incIn()

Operator ++ for the variables in i.

incNotVar()

Operator ++ for vars which are not v.

incOut()

Operator ++ for the variables not in i.

incVar()

Operator ++ for variable v only.

isMutable()

Check whether this Instantiation is a slave of another object: use isSlave instead.

isSlave()

Check whether this Instantiation is a slave of another object (for instance of the pyagrum.Tensor it was built on): its variables follow those of its master, and pyagrum.Instantiation.setMutable detaches it.

loopIn()

Generator to iterate on an Instantiation.

nbrDim()

pos()

rend()

reorder()

Reorder the variables of this instantiation in the order given by v.

setFirst()

Assign the first values to the tuple of the Instantiation.

setFirstIn()

Assign the first values in the Instantiation for the variables in i.

setFirstNotVar()

Assign the first values to variables different of v.

setFirstOut()

Assign the first values in the Instantiation for the variables not in i.

setFirstVar()

Assign the first value in the Instantiation for var v.

setLast()

Assign the last values in the Instantiation.

setLastIn()

Assign the last values in the Instantiation for the variables in i.

setLastNotVar()

Assign the last values to variables different of v.

setLastOut()

Assign the last values in the Instantiation for the variables not in i.

setLastVar()

Assign the last value in the Instantiation for var v.

setMutable()

Detach this Instantiation from its master, making it independently mutable.

setVals()

Assign the values from i in the Instantiation.

todict()

Create a dictionary {variable_name:value} from an instantiation

unsetEnd()

Alias for unsetOverflow().

unsetOverflow()

Removes the flag overflow.

val()

variable()

variablesSequence()

Tensor

class pyagrum.Tensor(*args)

Class representing a tensor.

Tensor() -> Tensor

default constructor

Tensor(src) -> Tensor
Parameters:
Tensor(v1,v2, …) -> Tensor
Parameters:

Methods

KL()

Check the compatibility and compute the Kullback-Leibler divergence between the tensor and p.

abs()

Apply abs on every element of the container

add()

Add a discrete variable to the tensor.

argmax()

argmin()

as_nparray()

Return a zero-copy numpy view over the Tensor’s internal data buffer.

contains()

Check whether a variable is in the tensor.

deterministicTensor()

This static method generates a Tensor representing a deterministic function of a pyagrum.DiscreteVariable) such as a hard evidence.

domainSize()

Compute the size of the domain of the Tensor, i.e., the product of the domain sizes of the variables in the Tensor.

draw()

draw a value using the tensor as a probability table.

empty()

entropy()

evEq()

This static method generates a Tensor representing an observation where a quasi-continuous variable (a pyagrum.DiscretizedVariable with many ticks) takes a specific given value.

evGt()

This static method generates a Tensor representing an observation where a quasi-continuous variable (a pyagrum.DiscretizedVariable with many ticks) takes a value greater than the parameter.

evIn()

This static method generates a Tensor representing an observation where a quasi-continuous variable (a pyagrum.DiscretizedVariable with many ticks) takes a value between the 2 paramerts (min,max)

evLt()

This static method generates a Tensor representing an observation where a quasi-continuous variable (a pyagrum.DiscretizedVariable with many ticks) takes a value less than the parameter.

expectedValue()

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

extract()

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

fillFromDistribution()

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

fillFromExpression()

Automatically fills the tensor with the evaluation of the expression s_fn (no matter if is a CPT or not).

fillFromFunction()

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

fillWith()

Automatically fills the tensor with v.

findAll()

Find all the position of a value in the Tensor.

get()

inverse()

Invert each value of the tensor in place (replace x by 1/x for each element).

isEvidence()

Check whether the tensor represents a likelihood (soft evidence) over a single variable.

isNonZeroMap()

log2()

log2 all the values in the Tensor

loopIn()

Generator to iterate inside a Tensor.

max()

maxIn()

Projection using max as operation.

maxNonOne()

maxOut()

Projection using max as operation.

mean()

Compute the mean of a univariate numerical discrete distribution.

memoryFootprint()

get the size (in byte) of the Tensor representation in memory

min()

minIn()

Projection using min as operation.

minNonZero()

minOut()

Projection using min as operation.

nbrDim()

new_abs()

Return a new tensor with the absolute value applied to each element.

new_log2()

Return a new tensor with the base-2 logarithm applied to each element.

new_sgn()

Return a new tensor with the sign function applied element-wise: -1 if value < 0, 0 if value == 0, 1 if value > 0.

new_sq()

Return a new tensor with each element squared.

noising()

Add noise to a CPT by mixing it with a random CPT: (1 - alpha) * self + alpha * randomCPT().

normalize()

Normalize the Tensor (do nothing if sum is 0)

normalizeAsCPT()

Normalize the Tensor as a CPT

pos()

prodIn()

Projection using multiplication as operation.

prodOut()

Projection using multiplication as operation.

product()

putFirst()

random()

Fill the tensor with random values uniformly drawn from [0,1].

randomCPT()

Fill the tensor as a random conditional probability table.

randomDistribution()

Fill the tensor as a random probability distribution (values are non-negative and sum to 1).

remove()

reorganize()

Create a new Tensor with another order.

scale()

Create a new tensor multiplied by v.

set()

Change the value pointed by i

sgn()

Apply the sign function element-wise in place: -1 if value < 0, 0 if value == 0, 1 if value > 0.

sq()

Square all the values in the Tensor

stdDev()

Compute the standard deviation of a univariate numerical discrete distribution.

sum()

sumIn()

Projection using sum as operation.

sumOut()

Projection using sum as operation.

toVarsIn()

Create a copy of the Tensor with the same variables as in p.

toarray()

Return a copy of the Tensor’s data as a shaped numpy array.

toclipboard()

Write a text representation of the tensor to the system clipboard.

tolatex()

Render object to a LaTeX tabular.

tolist()

topandas()

translate()

Create a new tensor added with v.

uniformTensor()

Create a uniform tensor over a single discrete variable (all values equal to 1/domainSize).

variable()

variablesSequence()

variance()

Compute the variance of a univariate numerical discrete distribution.

Attributes

names

shape