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:
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 bothself
andvar.type
, if possible.A compatible
Variable
is aVariable
with aType
that’s the “narrower” ofself
andvar.type
.If a compatible
Type
cannot be found, this method will returnNone
.
- 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
isFalse
, andallow_downcast
isTrue
, the data may be cast to an appropriate type. Ifallow_downcast
isFalse
, it may only be up-cast and not lose precision. Ifallow_downcast
isNone
(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 aVariable
with aType
that’s compatible withself
.If the involved
Type
s are not compatible, aTypeError
will be raised.
- is_super(otype)[source]#
Determine if
self
is a supertype ofotype
.This method effectively implements the type relation
>
.In general,
t1.is_super(t2) == True
implies thatt1
can be replaced witht2
.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.
- copy(name=None)[source]#
Create a copy of the variable.
This is just an identity operation, as XTensorVariables are immutable.
- 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 ifdim
is None.
- Returns:
A tensor with additional dimensions inserted at the front.
- Return type:
- 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).
- 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]]
- 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:
- 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:
- 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]]