xtensor.type – Types and Variables#

XTensorVariable creation functions#

pytensor.xtensor.type.as_xtensor(x, dims=None, *, name=None)[source]#

Convert a variable or data to an XTensorVariable.

Parameters:
  • x (Variable or data) –

  • dims (Sequence[str] or None, optional) – If dims are provided, TensorVariable (or data) will be converted to an XTensorVariable with those dims. XTensorVariables will be returned as is, if the dims match. Otherwise, a ValueError is raised. If dims are not provided, and the data is not a scalar, an XTensorVariable or xarray.DataArray, an error is raised.

  • name (str or None, optional) – Name of the resulting XTensorVariable.

pytensor.xtensor.type.xtensor(name=None, *, dims, shape=None, dtype='floatX')[source]#

Create an XTensorVariable.

Parameters:
  • name (str or None, optional) – The name of the variable

  • dims (Sequence[str]) – The names of the dimensions of the tensor

  • shape (Sequence[int | None] or None, optional) – The shape of the tensor. If None, defaults to a shape with None for each dimension.

  • dtype (str or np.dtype, optional) – The data type of the tensor. Defaults to ‘floatX’ (config.floatX).

Returns:

A new XTensorVariable with the specified name, dims, shape, and dtype.

Return type:

XTensorVariable

pytensor.xtensor.type.xtensor_constant(x, name=None, dims=None)[source]#

Convert a constant value to an XTensorConstant.

XTensor Type and Variable classes#

class pytensor.xtensor.type.XTensorConstant(type, data, name=None)[source]#

Constant of XtensorType.

class pytensor.xtensor.type.XTensorType(dtype, *, dims, shape=None, name=None)[source]#

A Type for Xtensors (Xarray-like tensors with dims).

clone(dtype=None, dims=None, shape=None, **kwargs)[source]#

Clone a copy of this type with the given arguments/keyword values, if any.

constant_type[source]#

alias of XTensorConstant

convert_variable(var)[source]#

Produce a Variable that’s compatible with both self and var.type, if possible.

A compatible Variable is a Variable with a Type that’s the “narrower” of self and var.type.

If a compatible Type cannot be found, this method will return None.

filter(value, strict=False, allow_downcast=None)[source]#

Return data or an appropriately wrapped/converted data.

Subclass implementations should raise a TypeError exception if the data is not of an acceptable type.

Parameters:
  • data (array-like) – The data to be filtered/converted.

  • strict (bool (optional)) – If True, the data returned must be the same as the data passed as an argument.

  • allow_downcast (bool (optional)) – If strict is False, and allow_downcast is True, the data may be cast to an appropriate type. If allow_downcast is False, it may only be up-cast and not lose precision. If allow_downcast is None (default), the behaviour can be type-dependent, but for now it means only Python floats can be down-casted, and only to floatX scalars.

filter_variable(other, allow_convert=True)[source]#

Convert a other into a Variable with a Type that’s compatible with self.

If the involved Types are not compatible, a TypeError will be raised.

is_super(otype)[source]#

Determine if self is a supertype of otype.

This method effectively implements the type relation >.

In general, t1.is_super(t2) == True implies that t1 can be replaced with t2.

See Type.in_same_class.

Return type:

None if the type relation cannot be applied/determined.

variable_type[source]#

alias of XTensorVariable

class pytensor.xtensor.type.XTensorVariable(type, owner, index=None, name=None)[source]#

Variable of XTensorType.

property T[source]#

Return the full transpose of the variable.

This is equivalent to calling transpose() with no arguments.

all(dim=None)[source]#

Reduce the variable by applying all along some dimension(s).

any(dim=None)[source]#

Reduce the variable by applying any along some dimension(s).

astype(dtype)[source]#

Convert the variable to a different data type.

broadcast_like(other, exclude=None)[source]#

Broadcast against another XTensorVariable.

clip(min, max)[source]#

Clip the values of the variable to a specified range.

conj()[source]#

Return the complex conjugate of the variable.

property coords[source]#

Not implemented.

copy(name=None)[source]#

Create a copy of the variable.

This is just an identity operation, as XTensorVariables are immutable.

cumprod(dim=None)[source]#

Compute the cumulative product along the given dimension(s).

cumsum(dim=None)[source]#

Compute the cumulative sum along the given dimension(s).

diff(dim, n=1)[source]#

Compute the n-th discrete difference along the given dimension.

property dims[source]#

The names of the dimensions of the variable.

dot(other, dim=None)[source]#

Generalized dot product with another XTensorVariable.

property dtype[source]#

The data type of the variable.

expand_dims(dim=None, create_index_for_new_dim=True, axis=None, **dim_kwargs)[source]#

Add one or more new dimensions to the variable.

Parameters:
  • dim (str | Sequence[str] | dict[str, int | Sequence] | None) –

    If str or sequence of str, new dimensions with size 1. If dict, keys are dimension names and values are either:

    • int: the new size

    • sequence: coordinates (length determines size)

  • create_index_for_new_dim (bool, default: True) – Ignored by PyTensor

  • axis (int | Sequence[int] | None, default: None) – Not implemented yet. In xarray, specifies where to insert the new dimension(s). By default (None), new dimensions are inserted at the beginning (axis=0).

  • **dim_kwargs (int | Sequence) – Alternative to dim dict. Only used if dim is None.

Returns:

A tensor with additional dimensions inserted at the front.

Return type:

XTensorVariable

property imag[source]#

Return the imaginary part of the variable.

inc(value)[source]#

Return a copy of the variable indexed by self with the indexed values incremented by value.

The original variable is not modified.

Raises:

ValueError – If self is not the result of an index operation

Examples

import pytensor.xtensor as ptx

x = ptx.as_xtensor([[1, 1], [1, 1]], dims=("a", "b"))
idx = ptx.as_xtensor([0, 1], dims=("a",))
out = x[:, idx].inc(1)
print(out.eval())
[[2 1]
 [1 2]]
import pytensor.xtensor as ptx

x = ptx.as_xtensor([[1, 1], [1, 1]], dims=("a", "b"))
idx = ptx.as_xtensor([0, 1], dims=("a",))
out = x.isel({"b": idx}).inc(-1)
print(out.eval())
[[0 1]
 [1 0]]
isel(indexers=None, drop=False, missing_dims='raise', **indexers_kwargs)[source]#

Index the variable along the specified dimension(s).

item()[source]#

Not implemented.

property loc[source]#

Not implemented.

max(dim=None)[source]#

Compute the maximum along the given dimension(s).

mean(dim=None)[source]#

Compute the mean along the given dimension(s).

min(dim=None)[source]#

Compute the minimum along the given dimension(s).

property ndim[source]#

The number of dimensions of the variable.

prod(dim=None)[source]#

Compute the product along the given dimension(s).

property real[source]#

Return the real part of the variable.

rename(new_name_or_name_dict=None, **names)[source]#

Rename the variable or its dimension(s).

sel(*args, **kwargs)[source]#

Not implemented.

set(value)[source]#

Return a copy of the variable indexed by self with the indexed values set to y.

The original variable is not modified.

Raises:

ValueError – If self is not the result of an index operation

Examples

import pytensor.xtensor as ptx

x = ptx.as_xtensor([[0, 0], [0, 0]], dims=("a", "b"))
idx = ptx.as_xtensor([0, 1], dims=("a",))
out = x[:, idx].set(1)
print(out.eval())
[[1 0]
 [0 1]]
import pytensor.xtensor as ptx

x = ptx.as_xtensor([[0, 0], [0, 0]], dims=("a", "b"))
idx = ptx.as_xtensor([0, 1], dims=("a",))
out = x.isel({"b": idx}).set(-1)
print(out.eval())
[[-1  0]
 [ 0 -1]]
property shape[source]#

The shape of the variable.

property size[source]#

The total number of elements in the variable.

property sizes[source]#

The sizes of the dimensions of the variable.

squeeze(dim=None, drop=None, axis=None)[source]#

Remove dimensions of size 1.

Parameters:
  • x (XTensorVariable) – The input tensor

  • dim (str or None or iterable of str, optional) – The name(s) of the dimension(s) to remove. If None, all dimensions of size 1 (known statically) will be removed. Dimensions with unknown static shape will be retained, even if they have size 1 at runtime.

  • drop (bool, optional) – If drop=True, drop squeezed coordinates instead of making them scalar.

  • axis (int or iterable of int, optional) – The axis(es) to remove. If None, all dimensions of size 1 will be removed.

Returns:

A new tensor with the specified dimension(s) removed.

Return type:

XTensorVariable

stack(dim, **dims)[source]#

Stack existing dimensions into a single new dimension.

std(dim=None, ddof=0)[source]#

Compute the standard deviation along the given dimension(s).

sum(dim=None)[source]#

Compute the sum along the given dimension(s).

transpose(*dim, missing_dims='raise')[source]#

Transpose the dimensions of the variable.

Parameters:
  • *dim (str | Ellipsis) – Dimensions to transpose. If empty, performs a full transpose. Can use ellipsis (…) to represent remaining dimensions.

  • missing_dims ({"raise", "warn", "ignore"}, default="raise") –

    How to handle dimensions that don’t exist in the tensor:

    • ”raise”: Raise an error if any dimensions don’t exist

    • ”warn”: Warn if any dimensions don’t exist

    • ”ignore”: Silently ignore any dimensions that don’t exist

Returns:

Transposed tensor with reordered dimensions.

Return type:

XTensorVariable

Raises:

ValueError – If missing_dims=”raise” and any dimensions don’t exist. If multiple ellipsis are provided.

unstack(dim, **dims)[source]#

Unstack a dimension into multiple dimensions of a given size.

Because XTensorVariables don’t have coords, this operation requires the sizes of each unstacked dimension to be specified. Also, unstacked dims will follow a C-style order, regardless of the order of the original dimensions.

import pytensor.xtensor as ptx

x = ptx.as_xtensor([[1, 2], [3, 4]], dims=("a", "b"))
stacked_cumsum = x.stack({"c": ["a", "b"]}).cumsum("c")
unstacked_cumsum = stacked_cumsum.unstack({"c": x.sizes})
print(unstacked_cumsum.eval())
[[ 1  3]
 [ 6 10]]
property values[source]#

Convert to a TensorVariable with the same data.

var(dim=None, ddof=0)[source]#

Compute the variance along the given dimension(s).