Skip to content

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 |

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

Adds a new variable in the Instantiation.

  • Parameters: v (DiscreteVariable) – The new variable added to the Instantiation
  • Raises: DuplicateElement – If the variable is already in this Instantiation
  • Return type: None

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.

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: Instantiation
  • Raises:
    • NotFound – If variable v does not belong to the instantiation.
    • OutOfBounds – If newval is not a possible value for the variable.

Erase all variables from an Instantiation.

  • Return type: None

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

Operator –.

  • Return type: None

Operator – for the variables in i.

  • Parameters: i (Instantiation) – The set of variables to decrement in this Instantiation
  • Return type: None

Operator – for vars which are not v.

  • Parameters: v (DiscreteVariable) – The variable not to decrement in this Instantiation.
  • Return type: None

Operator – for the variables not in i.

  • Parameters: i (Instantiation) – The set of variables to not decrement in this Instantiation.
  • Return type: None

Operator – for variable v only.

  • Parameters: v (DiscreteVariable) – The variable to decrement in this Instantiation.
  • Raises: NotFound – If variable v does not belong to the Instantiation.
  • Return type: None
  • Returns: The product of the variable’s domain size in the Instantiation.
  • Return type: int
  • Returns: True if the instantiation is empty.
  • Return type: bool
  • Returns: True if the Instantiation reached the end.
  • Return type: bool
  • 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

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: None
  • Returns: the hamming distance of this instantiation.
  • Return type: int
  • Returns: True if the current value of the tuple is correct
  • Return type: bool

Operator ++.

  • Return type: None

Operator ++ for the variables in i.

  • Parameters: i (Instantiation) – The set of variables to increment in this Instantiation.
  • Return type: None

Operator ++ for vars which are not v.

  • Parameters: v (DiscreteVariable) – The variable not to increment in this Instantiation.
  • Return type: None

Operator ++ for the variables not in i.

  • Parameters: i (Instantiation) – The set of variable to not increment in this Instantiation.
  • Return type: None

Operator ++ for variable v only.

  • Parameters: v (DiscreteVariable) – The variable to increment in this Instantiation.
  • Raises: NotFound – If variable v does not belong to the Instantiation.
  • Return type: None

Check whether this Instantiation is currently a slave of another object (i.e., not mutable).

  • Returns: True if the Instantiation is a slave (not independently mutable)
  • Return type: bool

Generator to iterate on an Instantiation.

Yield an pyagrum.Instantiation (copy of self) that iterates over all the possible values for the Instantiation.

Examples

>>> import pyagrum as gum
>>> bn=pyagrum.fastBN("A[3]->B[3]<-C[3]")
>>> I=pyagrum.Instantiation(bn.cpt("B"))
>>> for i in I.loopIn():
print(i)
print(bn.cpt("B").get(i))
bn.cpt("B").set(i,0.3)
  • Returns: The number of variables in the Instantiation.
  • Return type: int
  • Returns: the position of the variable v.
  • Return type: int
  • Parameters: v (DiscreteVariable) – the variable for which its position is return.
  • Raises: NotFound – If v does not belong to the instantiation.
  • Returns: True if the Instantiation reached the rend.
  • Return type: bool

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

Assign the first values to the tuple of the Instantiation.

  • Return type: None

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

  • Parameters: i (Instantiation) – The variables to which their first value is assigned in this Instantiation.
  • Return type: None

Assign the first values to variables different of v.

  • Parameters: v (DiscreteVariable) – The variable that will not be set to its first value in this Instantiation.
  • Return type: None

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

  • Parameters: i (Instantiation) – The variable that will not be set to their first value in this Instantiation.
  • Return type: None

Assign the first value in the Instantiation for var v.

  • Parameters: v (DiscreteVariable) – The variable that will be set to its first value in this Instantiation.
  • Return type: None

Assign the last values in the Instantiation.

  • Return type: None

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

  • Parameters: i (Instantiation) – The variables to which their last value is assigned in this Instantiation.
  • Return type: None

Assign the last values to variables different of v.

  • Parameters: v (DiscreteVariable) – The variable that will not be set to its last value in this Instantiation.
  • Return type: None

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

  • Parameters: i (Instantiation) – The variables that will not be set to their last value in this Instantiation.
  • Return type: None

Assign the last value in the Instantiation for var v.

  • Parameters: v (DiscreteVariable) – The variable that will be set to its last value in this Instantiation.
  • Return type: None

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

After this call, the Instantiation is no longer a slave and can be freely modified.

  • Return type: None

Assign the values from i in the Instantiation.

  • Parameters: i (Instantiation) – An Instantiation in which the new values are searched
  • Returns: a reference to the instantiation
  • Return type: Instantiation

Create a dictionary {variable_name:value} from an instantiation

  • Parameters: withLabels (bool) – 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 | str]

Alias for unsetOverflow().

  • Return type: None

Removes the flag overflow.

  • Return type: None
  • 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.
  • Parameters: i (int) – The index of the variable
  • Returns: the variable at position i in the tuple.
  • Return type: DiscreteVariable
  • Raises: NotFound – If the element cannot be found.
  • Returns: a list containing the sequence of variables
  • Return type: list

Class representing a tensor.

Tensor() -> Tensor : default constructor

Tensor(src) -> Tensor : Parameters: : - src (pyagrum.Tensor) – the Tensor to copy

Tensor(v1,v2, …) -> Tensor : Parameters: : - v1,v2… (pyagrum.DiscreteVariable) – the variables to be added to the tensor

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

  • Parameters: p (Tensor) – the tensor from which we want to calculate the divergence.
  • Returns: The value of the divergence
  • Return type: float
  • Raises:

Apply abs on every element of the container

  • Returns: a reference to the modified tensor.
  • Return type: Tensor

Add a discrete variable to the tensor.

  • Returns: the list of positions of the max and the max of all elements in the Tensor
  • Return type: tuple[list[Instantiation], float]
  • Returns: the list of positions of the min and the min of all elements in the Tensor
  • Return type: tuple[list[Instantiation], float]

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

The returned array shares memory with the Tensor: modifying one modifies the other. The Tensor is kept alive as long as the view exists.

The shape follows the same convention as toarray(): tuple(reversed(self.shape)).

  • Returns: float64 view, shape tuple(reversed(self.shape)), C-contiguous.
  • Return type: numpy.ndarray

Examples

>>> t = pyagrum.Tensor().add(pyagrum.LabelizedVariable("a","",2)).add(pyagrum.LabelizedVariable("b","",3))
>>> t.fillWith([1,2,3,4,5,6])
>>> v = t.as_nparray() # shape (3, 2), shares buffer with t
>>> v[0, 0] = 99
>>> t[{"a": 0, "b": 0}] # 99.0
99.0

Check whether a variable is in the tensor.

  • Parameters: v (DiscreteVariable) – the variable to check.
  • Returns: True if the var is in the tensor
  • Return type: bool

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

  • Parameters:
    • var (pyagrum.DiscreteVariable) – the variable to use
    • value (int | str) – the indice or the label of the value for the variable
  • Returns: The representation of the deterministic function as a pyagrum.Tensor.
  • Return type: Tensor

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

  • Returns: the size of the domain of the Tensor (the number of values it can take)
  • Return type: int

draw a value using the tensor as a probability table.

  • Returns: the index of the drawn value
  • Return type: int
  • Returns: Returns true if no variable is in the tensor.
  • Return type: bool
  • Returns: the entropy of the tensor
  • Return type: float

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.

Notes

Examples

>>> A=pyagrum.fastVariable('A[0:10:20]')
>>> p=pyagrum.Tensor.evEq(A,5)
>>> p
(pyagrum.Tensor@000001D7FAB06AD0)
A |
[0;0.5[ |[0.5;1[ |[1;1.5[ |[1.5;2[ |[2;2.5[ |[2.5;3[ |[3;3.5[ |[3.5;4[ |[4;4.5[ |[4.5;5[ |[5;5.5[ |[5.5;6[ |[6;6.5[ |[6.5;7[ |[7;7.5[ |[7.5;8[ |[8;8.5[ |[8.5;9[ |[9;9.5[ |[9.5;10] |
---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|
0.0000 | 0.0000 | 0.0000 | 0.0000 | 0.0000 | 0.0000 | 0.0000 | 0.0000 | 0.0000 | 0.0000 | 1.0000 | 0.0000 | 0.0000 | 0.0000 | 0.0000 | 0.0000 | 0.0000 | 0.0000 | 0.0000 | 0.0000 |

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.

Notes

Examples

>>> A=pyagrum.fastVariable('A[0:10:20]')
>>> p=pyagrum.Tensor.evGt(A,5)
>>> p
(pyagrum.Tensor@000001D7FAB06AD0)
A |
[0;0.5[ |[0.5;1[ |[1;1.5[ |[1.5;2[ |[2;2.5[ |[2.5;3[ |[3;3.5[ |[3.5;4[ |[4;4.5[ |[4.5;5[ |[5;5.5[ |[5.5;6[ |[6;6.5[ |[6.5;7[ |[7;7.5[ |[7.5;8[ |[8;8.5[ |[8.5;9[ |[9;9.5[ |[9.5;10] |
---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|
0.0000 | 0.0000 | 0.0000 | 0.0000 | 0.0000 | 0.0000 | 0.0000 | 0.0000 | 0.0000 | 0.0000 | 1.0000 | 1.0000 | 1.0000 | 1.0000 | 1.0000 | 1.0000 | 1.0000 | 1.0000 | 1.0000 | 1.0000 |

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)

Notes

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.

Notes

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

  • Parameters: func (function *(*dict ) ->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.Tensor 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

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

  • Parameters:
    • inst (pyagrum.instantiation) – a partial instantiation
    • dict (dict) – 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.Tensor, this key is just not used without notification. Then pyagrum.Tensor.extract concerns only the variables that both are in the Tensor and in the dictionnary.

  • Returns: the new Tensor
  • Return type: Tensor

fillFromDistribution(distribution, **s_fns)

Section titled “fillFromDistribution(distribution, **s_fns)”

Automatically fills the tensor 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 scipy.stats as stats
>>> import pyagrum as gum
>>> bn=pyagrum.fastBN('A[10]->B[10]<-C[10]')
>>> bn.cpt("B").fillFromDistribution(stats.norm,loc="(A+C)/2",scale=1)
  • 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 tensor
  • Return type: pyagrum.Tensor
  • Raises: pyagrum.InvalidArgument – If the first variable is Labelized.

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

The symbolic expression s_fn gives a value for each parameters of the Tensor

Examples

>>> import pyagrum as gum
>>> bn=pyagrum.fastBN('A[3]->B[3]<-C[3]')
>>> bn.cpt('B').fillFromFunction('(B+A+C)/2')
  • Parameters: s_fn (str) – a symbolic expression using the name of the variables of the Tensor and giving a value to the first variable of the Tensor. 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 tensor
  • Return type: pyagrum.Tensor

Automatically fills the tensor 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 Tensor and giving a value to the first variable of the Tensor. 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.

Automatically fills the tensor with v.

  • Parameters:
    • v (number or list of values or pyagrum.Tensor or numpy.ndarray) – a value or a list/pyagrum.Tensor/ndarray containing the values to fill the Tensor with.
    • mapping (list *|*tuple *|*dict)

Warning

  • if v is a list, the size of the list must be the size of the tensor
  • if v is a ref:pyagrum.Tensor, 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 tensor source to the variables of the tensor 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.
  • if v is a numpy.ndarray, it must be C-contiguous, dtype float64, and its total size must equal the domain size. If it is N-D, its shape must equal tuple(reversed(self.shape)). Copies the data in a single memcpy.

Find all the position of a value in the Tensor.

  • Parameters: v (float) – the value to find
  • Returns: a list of all the instantiations (as python dictionary) where the value is found
  • Return type: list[dict[str, int]]
  • Parameters: i (Instantiation) – an Instantiation
  • Returns: the value in the Tensor at the position given by the instantiation
  • Return type: float

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

  • Returns: self (in-place modification)
  • Return type: Tensor

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

A tensor is an evidence if it has exactly one variable, all values are in [0, 1], and the sum is positive.

  • Returns: True if the tensor is a valid likelihood vector
  • Return type: bool
  • Returns: a boolean-like tensor using the predicate isNonZero.
  • Return type: Tensor

log2 all the values in the Tensor

Warning

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

Generator to iterate inside a Tensor.

Yield an pyagrum.Instantiation that iterates over all the possible values for the pyagrum.Tensor

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)
  • Returns: the maximum of all elements in the Tensor
  • Return type: float

Projection using max as operation.

  • Parameters: varnames (set) – the set of vars to keep
  • Returns: the projected Tensor
  • Return type: Tensor
  • Returns: the maximum of non one elements in the Tensor
  • Return type: float
  • Raises: pyagrum.NotFound – If all value == 1.0

Projection using max as operation.

  • Parameters: varnames (set) – the set of vars to eliminate
  • Returns: the projected Tensor
  • Return type: Tensor
  • Raises: pyagrum.InvalidArgument – If varnames contains only one variable that does not exist in the Tensor

Compute the mean of a univariate numerical discrete distribution.

  • Raises: pyagrum.ArgumentError – If the tensor is not a 1-dimensional distribution (sum != 1) or if the variable is not numerical.
  • Returns: the mean of the distribution
  • Return type: float

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

  • Returns: the size in byte of the representation of the Tensor in memory.
  • Return type: int
  • Returns: the min of all elements in the Tensor
  • Return type: float

Projection using min as operation.

  • Parameters: varnames (set) – the set of vars to keep
  • Returns: the projected Tensor
  • Return type: Tensor
  • Returns: the min of non zero elements in the Tensor
  • Return type: float
  • Raises: pyagrum.NotFound – If all value == 0.0

Projection using min as operation.

  • Parameters: varnames (set) – the set of vars to eliminate
  • Returns: the projected Tensor
  • Return type: Tensor

Warning

InvalidArgument raised if varnames contains only one variable that does not exist in the Tensor

  • Returns: a list containing the name of each variables in the tensor
  • Return type: list

Warning

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

  • Returns: the number of vars in the multidimensional container.
  • Return type: int

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

  • Returns: new tensor
  • Return type: Tensor

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

  • Returns: new tensor
  • Return type: Tensor

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

  • Returns: new tensor
  • Return type: Tensor

Return a new tensor with each element squared.

  • Returns: new tensor
  • Return type: Tensor

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

  • Parameters: alpha (float) – noise level, must be in [0, 1]
  • Returns: self (in-place modification)
  • Return type: Tensor

Normalize the Tensor (do nothing if sum is 0)

  • Returns: a reference to the normalized Tensor
  • Return type: Tensor

Normalize the Tensor as a CPT

  • Returns: a reference to the normalized Tensor
  • Return type: Tensor
  • Raises: pyagrum.FatalError – If some distribution sums to 0
  • Parameters: varId (int)
  • Parameters: v (DiscreteVariable) – The variable for which the index is returned.
  • Returns: the index of a variable.
  • Return type: int
  • Raises: pyagrum.NotFound – If v is not in this multidimensional matrix.

Projection using multiplication as operation.

  • Parameters: varnames (set) – the set of vars to keep
  • Returns: the projected Tensor
  • Return type: Tensor

Projection using multiplication as operation.

  • Parameters: varnames (set) – the set of vars to eliminate
  • Returns: the projected Tensor
  • Return type: Tensor
  • Raises: pyagrum.InvalidArgument – If varnames contains only one variable that does not exist in the Tensor
  • Returns: the product of all elements in the Tensor
  • Return type: float

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

  • Returns: self (in-place modification)
  • Return type: Tensor

Fill the tensor as a random conditional probability table (each conditional distribution sums to 1).

  • Returns: self (in-place modification)
  • Return type: Tensor

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

  • Returns: self (in-place modification)
  • Return type: Tensor
  • Parameters: v (pyagrum.DiscreteVariable) – The variable to be removed
  • Returns: a reference to the modified tensor
  • Return type: None

Warning

IndexError raised if the var is not in the tensor

Create a new Tensor with another order.

  • Returns: varnames – a list of the var names in the new order
  • Return type: Tensor
  • Returns: a reference to the modified tensor
  • Return type: pyagrum.Tensor

Create a new tensor multiplied by v.

  • Parameters: v (float) – a multiplier
  • Return type: Tensor
  • Returns: a reference to the modified tensor

Change the value pointed by i

  • Parameters:
    • i (Instantiation) – The Instantiation to be changed
    • value (float) – The new value of the Instantiation
  • Return type: None

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

  • Returns: self (in-place modification)
  • Return type: Tensor
  • Returns: a list containing the dimensions of each variables in the tensor
  • Return type: list

Warning

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

Square all the values in the Tensor

Compute the standard deviation of a univariate numerical discrete distribution.

  • Raises: pyagrum.ArgumentError – If the tensor is not a 1-dimensional distribution (sum != 1) or if the variable is not numerical.
  • Returns: the standard deviation of the distribution
  • Return type: float
  • Returns: the sum of all elements in the Tensor
  • Return type: float

Projection using sum as operation.

  • Parameters: varnames (set) – the set of vars to keep
  • Returns: the projected Tensor
  • Return type: Tensor

Projection using sum as operation.

  • Parameters: varnames (set) – the set of vars to eliminate
  • Returns: the projected Tensor
  • Return type: Tensor
  • Raises: pyagrum.InvalidArgument – If varnames contains only one variable that does not exist in the Tensor

The membership flag

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

Warning

p is a pyAgrum’s object that can refer to variables through a method p.variable(name:str). For instance, a Potential, an Instantiation or a Graphical Model (Bayesian Network,…).

Examples

>>> import pyagrum as gum
>>> bn1=pyagrum.fastBN('A[3]->B[3]<-C[3]')
>>> bn2=pyagrum.fastBN('A[3]<-B[3]<-C[3]')
>>> # bn1.cpt('A')+bn2.cpt('A') # does not work since the vars 'A' in bn1 and bn2 are not the same.
>>> bn1.cpt('A').toVars(bn2)+bn2.cpt('A') # OK
  • Returns: pyagrum.Tensor : a copy of the Potential with the same variables as p.

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

The shape follows the Tensor’s variable order: the last variable added varies fastest (C order), so the shape is tuple(reversed(self.shape)).

  • Returns: New float64 array; modifying it does not affect the Tensor.
  • Return type: numpy.ndarray

Examples

>>> t = pyagrum.Tensor().add(pyagrum.LabelizedVariable("a","",2)).add(pyagrum.LabelizedVariable("b","",3))
>>> t.fillWith([1,2,3,4,5,6])
>>> t.toarray() # shape (3, 2)
array([[1., 2.],
[3., 4.],
[5., 6.]])

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

The clipboard content can be pasted into a spreadsheet application.

  • Parameters: **kwargs – Additional keyword arguments passed to pandas.DataFrame.to_clipboard().

Render object to a LaTeX tabular.

Requires to include booktabs package in the LaTeX document.

  • Returns: the tensor as LaTeX string
  • Return type: str
  • Returns: the tensor as a list
  • Return type: list
  • Returns: the tensor as an pandas.DataFrame
  • Return type: pandas.DataFrame

Create a new tensor added with v.

  • Parameters: v (float) – The value to be added
  • Return type: Tensor
  • Returns: a reference to the modified tensor

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

  • Parameters: var (DiscreteVariable) – the variable defining the domain
  • Returns: uniform tensor over var
  • Return type: Tensor
  • Parameters: i (int) – An index of this multidimensional matrix.
  • Return type: DiscreteVariable
  • Returns: the variable at the ith index
  • Raises: pyagrum.NotFound – If i does not reference a variable in this multidimensional matrix.
  • Returns: a list containing the sequence of variables
  • Return type: list

Compute the variance of a univariate numerical discrete distribution.

  • Raises: pyagrum.ArgumentError – If the tensor is not a 1-dimensional distribution (sum != 1) or if the variable is not numerical.
  • Returns: the variance of the distribution
  • Return type: float