Skip to content

tensor ¤

Classes:

Name Description
Tensor

A wrapper around an xr.DataArray for better integration with bioimageio.spec

Tensor ¤

Tensor(array: Union[NDArray[Any], xr.DataArray], dims: Sequence[Union[AxisId, AxisLike]])

Bases: MagicTensorOpsMixin


              flowchart TD
              bioimageio.core.tensor.Tensor[Tensor]
              bioimageio.core._magic_tensor_ops.MagicTensorOpsMixin[MagicTensorOpsMixin]

                              bioimageio.core._magic_tensor_ops.MagicTensorOpsMixin --> bioimageio.core.tensor.Tensor
                


              click bioimageio.core.tensor.Tensor href "" "bioimageio.core.tensor.Tensor"
              click bioimageio.core._magic_tensor_ops.MagicTensorOpsMixin href "" "bioimageio.core._magic_tensor_ops.MagicTensorOpsMixin"
            

A wrapper around an xr.DataArray for better integration with bioimageio.spec and improved type annotations.

Methods:

Name Description
__abs__
__add__
__and__
__array__
__eq__
__floordiv__
__ge__
__getitem__
__gt__
__iadd__
__iand__
__ifloordiv__
__ilshift__
__imod__
__imul__
__invert__
__ior__
__ipow__
__irshift__
__isub__
__iter__
__itruediv__
__ixor__
__le__
__len__
__lshift__
__lt__
__mod__
__mul__
__ne__
__neg__
__or__
__pos__
__pow__
__radd__
__rand__
__repr__
__rfloordiv__
__rmod__
__rmul__
__ror__
__rpow__
__rshift__
__rsub__
__rtruediv__
__rxor__
__setitem__
__sub__
__truediv__
__xor__
argmax
argsort
assign_batch_multi_index

Set the batch multi-index for this tensor.

astype

Return tensor cast to dtype

clip

Return a tensor whose values are limited to [min, max].

conj
conjugate
crop_to

crop to match sizes

expand_dims
from_numpy

create a Tensor from a numpy array

from_xarray

create a Tensor from an xarray data array

item

Copy a tensor element to a standard Python scalar and return it.

mean
pad
pad_to

pad tensor to match sizes

quantile
resize_to

return cropped/padded tensor with sizes

round
std
sum

Reduce this Tensor's data by applying sum along some dimension(s).

to_numpy

Return the data of this tensor as a numpy array.

transpose

Return a transposed tensor, missing axes are expanded (if unstack_missing_dims_from_batch is False) or unstacked from batch (if unstack_missing_dims_from_batch is True), extra axes are stacked to batch (if stack_extra_dims_to_batch is True). Additional axes raise (if stack_extra_dims_to_batch is True).

unstack_batch_multi_index

Unstack the batch multi-index of this tensor.

var

Attributes:

Name Type Description
__hash__ None
__slots__
data
dims

Tuple of dimension names associated with this tensor.

dtype DTypeStr
ndim

Number of tensor dimensions.

shape

Tuple of tensor axes lengths

shape_tuple

Tuple of tensor axes lengths

size

Number of elements in the tensor.

sizes

Ordered, immutable mapping from axis ids to axis lengths.

tagged_shape

(alias for sizes) Ordered, immutable mapping from axis ids to lengths.

Source code in src/bioimageio/core/tensor.py
76
77
78
79
80
81
82
83
84
85
86
87
88
def __init__(
    self,
    array: Union[NDArray[Any], xr.DataArray],
    dims: Sequence[Union[AxisId, AxisLike]],
) -> None:
    super().__init__()
    axes = tuple(
        a if isinstance(a, AxisId) else AxisInfo.create(a).id for a in dims
    )
    if isinstance(array, xr.DataArray):
        self._data = array.transpose(*axes)
    else:
        self._data = xr.DataArray(array, dims=axes)

__hash__ instance-attribute ¤

__hash__: None

__slots__ class-attribute instance-attribute ¤

__slots__ = ()

data property ¤

data

dims property ¤

dims

Tuple of dimension names associated with this tensor.

dtype property ¤

dtype: DTypeStr

ndim property ¤

ndim

Number of tensor dimensions.

shape property ¤

shape

Tuple of tensor axes lengths

shape_tuple property ¤

shape_tuple

Tuple of tensor axes lengths

size property ¤

size

Number of elements in the tensor.

Equal to math.prod(tensor.shape), i.e., the product of the tensors’ dimensions.

sizes property ¤

sizes

Ordered, immutable mapping from axis ids to axis lengths.

tagged_shape property ¤

tagged_shape

(alias for sizes) Ordered, immutable mapping from axis ids to lengths.

__abs__ ¤

__abs__() -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
175
176
def __abs__(self) -> Self:
    return self._unary_op(operator.abs)

__add__ ¤

__add__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
31
32
def __add__(self, other: _Compatible) -> Self:
    return self._binary_op(other, operator.add)

__and__ ¤

__and__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
52
53
def __and__(self, other: _Compatible) -> Self:
    return self._binary_op(other, operator.and_)  # pyright: ignore[reportUnknownArgumentType]

__array__ ¤

__array__(dtype: DTypeLike = None)
Source code in src/bioimageio/core/tensor.py
93
94
def __array__(self, dtype: DTypeLike = None):
    return np.asarray(self._data, dtype=dtype)

__eq__ ¤

__eq__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
79
80
81
82
83
def __eq__(self, other: _Compatible) -> Self:  # type: ignore[override]
    return self._binary_op(
        other,
        nputils.array_eq,  # pyright: ignore[reportUnknownArgumentType]
    )

__floordiv__ ¤

__floordiv__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
46
47
def __floordiv__(self, other: _Compatible) -> Self:
    return self._binary_op(other, operator.floordiv)  # pyright: ignore[reportUnknownArgumentType]

__ge__ ¤

__ge__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
76
77
def __ge__(self, other: _Compatible) -> Self:
    return self._binary_op(other, operator.ge)

__getitem__ ¤

__getitem__(key: Union[SliceInfo, slice, int, PerAxis[Union[SliceInfo, slice, int]], Tensor, xr.DataArray]) -> Self
Source code in src/bioimageio/core/tensor.py
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
def __getitem__(
    self,
    key: Union[
        SliceInfo,
        slice,
        int,
        PerAxis[Union[SliceInfo, slice, int]],
        Tensor,
        xr.DataArray,
    ],
) -> Self:
    if isinstance(key, SliceInfo):
        key = slice(*key)
    elif isinstance(key, collections.abc.Mapping):
        key = {
            a: s if isinstance(s, int) else s if isinstance(s, slice) else slice(*s)
            for a, s in key.items()
        }
    elif isinstance(key, Tensor):
        key = key._data

    return self.__class__.from_xarray(self._data[key])

__gt__ ¤

__gt__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
73
74
def __gt__(self, other: _Compatible) -> Self:
    return self._binary_op(other, operator.gt)

__iadd__ ¤

__iadd__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
130
131
def __iadd__(self, other: _Compatible) -> Self:
    return self._inplace_binary_op(other, operator.iadd)  # pyright: ignore[reportUnknownArgumentType]

__iand__ ¤

__iand__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
151
152
def __iand__(self, other: _Compatible) -> Self:
    return self._inplace_binary_op(other, operator.iand)  # pyright: ignore[reportUnknownArgumentType]

__ifloordiv__ ¤

__ifloordiv__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
145
146
def __ifloordiv__(self, other: _Compatible) -> Self:
    return self._inplace_binary_op(other, operator.ifloordiv)  # pyright: ignore[reportUnknownArgumentType]

__ilshift__ ¤

__ilshift__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
160
161
def __ilshift__(self, other: _Compatible) -> Self:
    return self._inplace_binary_op(other, operator.ilshift)  # pyright: ignore[reportUnknownArgumentType]

__imod__ ¤

__imod__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
148
149
def __imod__(self, other: _Compatible) -> Self:
    return self._inplace_binary_op(other, operator.imod)  # pyright: ignore[reportUnknownArgumentType]

__imul__ ¤

__imul__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
136
137
def __imul__(self, other: _Compatible) -> Self:
    return self._inplace_binary_op(other, operator.imul)  # pyright: ignore[reportUnknownArgumentType]

__invert__ ¤

__invert__() -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
178
179
def __invert__(self) -> Self:
    return self._unary_op(operator.invert)

__ior__ ¤

__ior__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
157
158
def __ior__(self, other: _Compatible) -> Self:
    return self._inplace_binary_op(other, operator.ior)  # pyright: ignore[reportUnknownArgumentType]

__ipow__ ¤

__ipow__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
139
140
def __ipow__(self, other: _Compatible) -> Self:
    return self._inplace_binary_op(other, operator.ipow)  # pyright: ignore[reportUnknownArgumentType]

__irshift__ ¤

__irshift__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
163
164
def __irshift__(self, other: _Compatible) -> Self:
    return self._inplace_binary_op(other, operator.irshift)  # pyright: ignore[reportUnknownArgumentType]

__isub__ ¤

__isub__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
133
134
def __isub__(self, other: _Compatible) -> Self:
    return self._inplace_binary_op(other, operator.isub)  # pyright: ignore[reportUnknownArgumentType]

__iter__ ¤

__iter__() -> Iterator[Any]
Source code in src/bioimageio/core/tensor.py
143
144
145
146
def __iter__(self: Any) -> Iterator[Any]:
    if self.ndim == 0:
        raise TypeError("iteration over a 0-d array")
    return self._iter()

__itruediv__ ¤

__itruediv__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
142
143
def __itruediv__(self, other: _Compatible) -> Self:
    return self._inplace_binary_op(other, operator.itruediv)  # pyright: ignore[reportUnknownArgumentType]

__ixor__ ¤

__ixor__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
154
155
def __ixor__(self, other: _Compatible) -> Self:
    return self._inplace_binary_op(other, operator.ixor)  # pyright: ignore[reportUnknownArgumentType]

__le__ ¤

__le__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
70
71
def __le__(self, other: _Compatible) -> Self:
    return self._binary_op(other, operator.le)

__len__ ¤

__len__() -> int
Source code in src/bioimageio/core/tensor.py
136
137
def __len__(self) -> int:
    return len(self.data)

__lshift__ ¤

__lshift__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
61
62
def __lshift__(self, other: _Compatible) -> Self:
    return self._binary_op(other, operator.lshift)  # pyright: ignore[reportUnknownArgumentType]

__lt__ ¤

__lt__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
67
68
def __lt__(self, other: _Compatible) -> Self:
    return self._binary_op(other, operator.lt)

__mod__ ¤

__mod__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
49
50
def __mod__(self, other: _Compatible) -> Self:
    return self._binary_op(other, operator.mod)

__mul__ ¤

__mul__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
37
38
def __mul__(self, other: _Compatible) -> Self:
    return self._binary_op(other, operator.mul)

__ne__ ¤

__ne__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
85
86
87
88
89
def __ne__(self, other: _Compatible) -> Self:  # type: ignore[override]
    return self._binary_op(
        other,
        nputils.array_ne,  # pyright: ignore[reportUnknownArgumentType]
    )

__neg__ ¤

__neg__() -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
169
170
def __neg__(self) -> Self:
    return self._unary_op(operator.neg)

__or__ ¤

__or__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
58
59
def __or__(self, other: _Compatible) -> Self:
    return self._binary_op(other, operator.or_)  # pyright: ignore[reportUnknownArgumentType]

__pos__ ¤

__pos__() -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
172
173
def __pos__(self) -> Self:
    return self._unary_op(operator.pos)

__pow__ ¤

__pow__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
40
41
def __pow__(self, other: _Compatible) -> Self:
    return self._binary_op(other, operator.pow)  # pyright: ignore[reportUnknownArgumentType]

__radd__ ¤

__radd__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
95
96
def __radd__(self, other: _Compatible) -> Self:
    return self._binary_op(other, operator.add, reflexive=True)

__rand__ ¤

__rand__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
116
117
def __rand__(self, other: _Compatible) -> Self:
    return self._binary_op(other, operator.and_, reflexive=True)  # pyright: ignore[reportUnknownArgumentType]

__repr__ ¤

__repr__() -> str
Source code in src/bioimageio/core/tensor.py
90
91
def __repr__(self) -> str:
    return f"<Tensor {repr(self._data)}>"

__rfloordiv__ ¤

__rfloordiv__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
110
111
def __rfloordiv__(self, other: _Compatible) -> Self:
    return self._binary_op(other, operator.floordiv, reflexive=True)  # pyright: ignore[reportUnknownArgumentType]

__rmod__ ¤

__rmod__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
113
114
def __rmod__(self, other: _Compatible) -> Self:
    return self._binary_op(other, operator.mod, reflexive=True)

__rmul__ ¤

__rmul__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
101
102
def __rmul__(self, other: _Compatible) -> Self:
    return self._binary_op(other, operator.mul, reflexive=True)

__ror__ ¤

__ror__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
122
123
def __ror__(self, other: _Compatible) -> Self:
    return self._binary_op(other, operator.or_, reflexive=True)  # pyright: ignore[reportUnknownArgumentType]

__rpow__ ¤

__rpow__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
104
105
def __rpow__(self, other: _Compatible) -> Self:
    return self._binary_op(other, operator.pow, reflexive=True)  # pyright: ignore[reportUnknownArgumentType]

__rshift__ ¤

__rshift__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
64
65
def __rshift__(self, other: _Compatible) -> Self:
    return self._binary_op(other, operator.rshift)  # pyright: ignore[reportUnknownArgumentType]

__rsub__ ¤

__rsub__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
98
99
def __rsub__(self, other: _Compatible) -> Self:
    return self._binary_op(other, operator.sub, reflexive=True)

__rtruediv__ ¤

__rtruediv__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
107
108
def __rtruediv__(self, other: _Compatible) -> Self:
    return self._binary_op(other, operator.truediv, reflexive=True)  # pyright: ignore[reportUnknownArgumentType]

__rxor__ ¤

__rxor__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
119
120
def __rxor__(self, other: _Compatible) -> Self:
    return self._binary_op(other, operator.xor, reflexive=True)  # pyright: ignore[reportUnknownArgumentType]

__setitem__ ¤

__setitem__(key: Union[PerAxis[Union[SliceInfo, slice]], Tensor, xr.DataArray], value: Union[Tensor, xr.DataArray, float, int]) -> None
Source code in src/bioimageio/core/tensor.py
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
def __setitem__(
    self,
    key: Union[PerAxis[Union[SliceInfo, slice]], Tensor, xr.DataArray],
    value: Union[Tensor, xr.DataArray, float, int],
) -> None:
    if isinstance(key, Tensor):
        key = key._data
    elif isinstance(key, xr.DataArray):
        pass
    else:
        key = {a: s if isinstance(s, slice) else slice(*s) for a, s in key.items()}

    if isinstance(value, Tensor):
        value = value._data

    self._data[key] = value

__sub__ ¤

__sub__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
34
35
def __sub__(self, other: _Compatible) -> Self:
    return self._binary_op(other, operator.sub)

__truediv__ ¤

__truediv__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
43
44
def __truediv__(self, other: _Compatible) -> Self:
    return self._binary_op(other, operator.truediv)  # pyright: ignore[reportUnknownArgumentType]

__xor__ ¤

__xor__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
55
56
def __xor__(self, other: _Compatible) -> Self:
    return self._binary_op(other, operator.xor)  # pyright: ignore[reportUnknownArgumentType]

argmax ¤

argmax() -> Mapping[AxisId, int]
Source code in src/bioimageio/core/tensor.py
283
284
285
286
def argmax(self) -> Mapping[AxisId, int]:
    ret = self._data.argmax(...)
    assert isinstance(ret, dict)
    return {cast(AxisId, k): cast(int, v.item()) for k, v in ret.items()}

argsort ¤

argsort(*args: Any, **kwargs: Any) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
188
189
190
191
192
193
def argsort(self, *args: Any, **kwargs: Any) -> Self:
    return self._unary_op(
        ops.argsort,  # pyright: ignore[reportUnknownArgumentType]
        *args,
        **kwargs,
    )

assign_batch_multi_index ¤

assign_batch_multi_index(multi_index: 'pd.MultiIndex') -> Self

Set the batch multi-index for this tensor.

Parameters:

Name Type Description Default

multi_index ¤

'pd.MultiIndex'

The multi-index to set.

required
Source code in src/bioimageio/core/tensor.py
492
493
494
495
496
497
498
499
500
501
502
503
504
505
def assign_batch_multi_index(self, multi_index: "pd.MultiIndex") -> Self:
    """Set the batch multi-index for this tensor.

    Args:
        multi_index: The multi-index to set.
    """
    if AxisId("batch") not in self.dims:
        raise ValueError(
            "Cannot set batch multi-index on a tensor without a 'batch' axis."
        )

    return self.__class__.from_xarray(
        self._data.assign_coords({AxisId("batch"): multi_index})
    )

astype ¤

astype(dtype: DTypeStr, *, copy: bool = False)

Return tensor cast to dtype

note: if dtype is already satisfied copy if copy

Source code in src/bioimageio/core/tensor.py
288
289
290
291
292
def astype(self, dtype: DTypeStr, *, copy: bool = False):
    """Return tensor cast to `dtype`

    note: if dtype is already satisfied copy if `copy`"""
    return self.__class__.from_xarray(self._data.astype(dtype, copy=copy))

clip ¤

clip(min: Optional[float] = None, max: Optional[float] = None)

Return a tensor whose values are limited to [min, max]. At least one of max or min must be given.

Source code in src/bioimageio/core/tensor.py
294
295
296
297
def clip(self, min: Optional[float] = None, max: Optional[float] = None):
    """Return a tensor whose values are limited to [min, max].
    At least one of max or min must be given."""
    return self.__class__.from_xarray(self._data.clip(min, max))

conj ¤

conj(*args: Any, **kwargs: Any) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
195
196
197
198
199
200
def conj(self, *args: Any, **kwargs: Any) -> Self:
    return self._unary_op(
        ops.conj,  # pyright: ignore[reportUnknownArgumentType]
        *args,
        **kwargs,
    )

conjugate ¤

conjugate(*args: Any, **kwargs: Any) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
202
203
204
205
206
207
def conjugate(self, *args: Any, **kwargs: Any) -> Self:
    return self._unary_op(
        ops.conjugate,  # pyright: ignore[reportUnknownArgumentType]
        *args,
        **kwargs,
    )

crop_to ¤

crop_to(sizes: PerAxis[int], crop_where: Union[CropWhere, PerAxis[CropWhere]] = 'left_and_right') -> Self

crop to match sizes

Source code in src/bioimageio/core/tensor.py
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
def crop_to(
    self,
    sizes: PerAxis[int],
    crop_where: Union[
        CropWhere,
        PerAxis[CropWhere],
    ] = "left_and_right",
) -> Self:
    """crop to match `sizes`"""
    if isinstance(crop_where, str):
        crop_axis_where: PerAxis[CropWhere] = {a: crop_where for a in self.dims}
    else:
        crop_axis_where = crop_where

    slices: Dict[AxisId, SliceInfo] = {}

    for a, s_is in self.sizes.items():
        if a not in sizes or sizes[a] == s_is:
            pass
        elif sizes[a] > s_is:
            logger.warning(
                "Cannot crop axis {} of size {} to larger size {}",
                a,
                s_is,
                sizes[a],
            )
        elif a not in crop_axis_where:
            raise ValueError(
                f"Don't know where to crop axis {a}, `crop_where`={crop_where}"
            )
        else:
            crop_this_axis_where = crop_axis_where[a]
            if crop_this_axis_where == "left":
                slices[a] = SliceInfo(s_is - sizes[a], s_is)
            elif crop_this_axis_where == "right":
                slices[a] = SliceInfo(0, sizes[a])
            elif crop_this_axis_where == "left_and_right":
                slices[a] = SliceInfo(
                    start := (s_is - sizes[a]) // 2, sizes[a] + start
                )
            else:
                assert_never(crop_this_axis_where)

    return self[slices]

expand_dims ¤

expand_dims(dims: Union[Sequence[AxisId], PerAxis[int]]) -> Self
Source code in src/bioimageio/core/tensor.py
344
345
def expand_dims(self, dims: Union[Sequence[AxisId], PerAxis[int]]) -> Self:
    return self.__class__.from_xarray(self._data.expand_dims(dims=dims))

from_numpy classmethod ¤

from_numpy(array: NDArray[Any], *, dims: Optional[Union[AxisLike, Sequence[AxisLike]]]) -> Tensor

create a Tensor from a numpy array

Parameters:

Name Type Description Default

array ¤

NDArray[Any]

the nd numpy array

required

dims ¤

Optional[Union[AxisLike, Sequence[AxisLike]]]

A description of the array's axes. If None axes are guessed (which might fail and raise a ValueError.) If dims do not match array shape, permutations and singleton dimensions are tried to find a match.

required

Raises: ValueError: if dims is None and dims guessing fails.

Source code in src/bioimageio/core/tensor.py
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
@classmethod
def from_numpy(
    cls,
    array: NDArray[Any],
    *,
    dims: Optional[Union[AxisLike, Sequence[AxisLike]]],
) -> Tensor:
    """create a `Tensor` from a numpy array

    Args:
        array: the nd numpy array
        dims: A description of the array's axes.
            If None axes are guessed (which might fail and raise a ValueError.)
            If dims do not match array shape, permutations and singleton dimensions are tried to find a match.
    Raises:
        ValueError: if `dims` is None and dims guessing fails.
    """

    if dims is None:
        return cls._interprete_array_wo_known_axes(array)
    elif isinstance(dims, collections.abc.Sequence):
        dim_seq = list(dims)
    else:
        dim_seq = [dims]

    axis_infos = [AxisInfo.create(a) for a in dim_seq]
    original_shape = tuple(array.shape)

    successful_view = _get_array_view(array, axis_infos)
    if successful_view is None:
        raise ValueError(
            f"Array shape {original_shape} does not map to axes {dims}"
        )

    return Tensor(successful_view, dims=tuple(a.id for a in axis_infos))

from_xarray classmethod ¤

from_xarray(data_array: xr.DataArray) -> Self

create a Tensor from an xarray data array

this factory method is round-trip save

for any Tensor's data property (an xarray.DataArray).

Source code in src/bioimageio/core/tensor.py
186
187
188
189
190
191
192
193
@classmethod
def from_xarray(cls, data_array: xr.DataArray) -> Self:
    """create a `Tensor` from an xarray data array

    note for internal use: this factory method is round-trip save
        for any `Tensor`'s  `data` property (an xarray.DataArray).
    """
    return cls(array=data_array, dims=tuple(AxisId(d) for d in data_array.dims))

item ¤

item(key: Union[None, SliceInfo, slice, int, PerAxis[Union[SliceInfo, slice, int]]] = None)

Copy a tensor element to a standard Python scalar and return it.

Source code in src/bioimageio/core/tensor.py
347
348
349
350
351
352
353
354
355
356
357
358
359
360
def item(
    self,
    key: Union[
        None, SliceInfo, slice, int, PerAxis[Union[SliceInfo, slice, int]]
    ] = None,
):
    """Copy a tensor element to a standard Python scalar and return it."""
    if key is None:
        ret = self._data.item()
    else:
        ret = self[key]._data.item()

    assert isinstance(ret, (bool, float, int))
    return ret

mean ¤

mean(dim: Optional[Union[AxisId, Sequence[AxisId]]] = None) -> Self
Source code in src/bioimageio/core/tensor.py
362
363
def mean(self, dim: Optional[Union[AxisId, Sequence[AxisId]]] = None) -> Self:
    return self.__class__.from_xarray(self._data.mean(dim=dim))

pad ¤

pad(pad_width: PerAxis[PadWidthLike], mode: PadMode = 'symmetric') -> Self
Source code in src/bioimageio/core/tensor.py
365
366
367
368
369
370
371
372
373
374
375
376
def pad(
    self,
    pad_width: PerAxis[PadWidthLike],
    mode: PadMode = "symmetric",
) -> Self:
    pad_width = {a: PadWidth.create(p) for a, p in pad_width.items()}
    mode_name, constant_value = _resolve_pad_mode(mode)
    return self.__class__.from_xarray(
        self._data.pad(
            pad_width=pad_width, mode=mode_name, constant_values=constant_value
        )
    )

pad_to ¤

pad_to(sizes: PerAxis[int], pad_where: Union[PadWhere, PerAxis[PadWhere]] = 'left_and_right', mode: PadMode = 'symmetric') -> Self

pad tensor to match sizes

Source code in src/bioimageio/core/tensor.py
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
def pad_to(
    self,
    sizes: PerAxis[int],
    pad_where: Union[PadWhere, PerAxis[PadWhere]] = "left_and_right",
    mode: PadMode = "symmetric",
) -> Self:
    """pad `tensor` to match `sizes`"""
    if isinstance(pad_where, str):
        pad_axis_where: PerAxis[PadWhere] = {a: pad_where for a in self.dims}
    else:
        pad_axis_where = pad_where

    pad_width: Dict[AxisId, PadWidth] = {}
    for a, s_is in self.sizes.items():
        if a not in sizes or sizes[a] == s_is:
            pad_width[a] = PadWidth(0, 0)
        elif s_is > sizes[a]:
            pad_width[a] = PadWidth(0, 0)
            logger.warning(
                "Cannot pad axis {} of size {} to smaller size {}",
                a,
                s_is,
                sizes[a],
            )
        elif a not in pad_axis_where:
            raise ValueError(
                f"Don't know where to pad axis {a}, `pad_where`={pad_where}"
            )
        else:
            pad_this_axis_where = pad_axis_where[a]
            d = sizes[a] - s_is
            if pad_this_axis_where == "left":
                pad_width[a] = PadWidth(d, 0)
            elif pad_this_axis_where == "right":
                pad_width[a] = PadWidth(0, d)
            elif pad_this_axis_where == "left_and_right":
                pad_width[a] = PadWidth(left := d // 2, d - left)
            else:
                assert_never(pad_this_axis_where)

    return self.pad(pad_width, mode)

quantile ¤

quantile(q: Union[float, Sequence[float]], dim: Optional[Union[AxisId, Sequence[AxisId]]] = None, method: QuantileMethod = 'linear') -> Self
Source code in src/bioimageio/core/tensor.py
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
def quantile(
    self,
    q: Union[float, Sequence[float]],
    dim: Optional[Union[AxisId, Sequence[AxisId]]] = None,
    method: QuantileMethod = "linear",
) -> Self:
    assert (
        isinstance(q, (float, int))
        and q >= 0.0
        or not isinstance(q, (float, int))
        and all(qq >= 0.0 for qq in q)
    )
    assert (
        isinstance(q, (float, int))
        and q <= 1.0
        or not isinstance(q, (float, int))
        and all(qq <= 1.0 for qq in q)
    )
    assert dim is None or (
        (quantile_dim := AxisId("quantile")) != dim and quantile_dim not in set(dim)
    )
    return self.__class__.from_xarray(
        self._data.quantile(q, dim=dim, method=method)
    )

resize_to ¤

resize_to(sizes: PerAxis[int], *, pad_where: Union[PadWhere, PerAxis[PadWhere]] = 'left_and_right', crop_where: Union[CropWhere, PerAxis[CropWhere]] = 'left_and_right', pad_mode: PadMode = 'symmetric')

return cropped/padded tensor with sizes

Source code in src/bioimageio/core/tensor.py
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
def resize_to(
    self,
    sizes: PerAxis[int],
    *,
    pad_where: Union[
        PadWhere,
        PerAxis[PadWhere],
    ] = "left_and_right",
    crop_where: Union[
        CropWhere,
        PerAxis[CropWhere],
    ] = "left_and_right",
    pad_mode: PadMode = "symmetric",
):
    """return cropped/padded tensor with `sizes`"""
    crop_to_sizes: Dict[AxisId, int] = {}
    pad_to_sizes: Dict[AxisId, int] = {}
    new_axes = dict(sizes)
    for a, s_is in self.sizes.items():
        a = AxisId(str(a))
        _ = new_axes.pop(a, None)
        if a not in sizes or sizes[a] == s_is:
            pass
        elif s_is > sizes[a]:
            crop_to_sizes[a] = sizes[a]
        else:
            pad_to_sizes[a] = sizes[a]

    tensor = self
    if crop_to_sizes:
        tensor = tensor.crop_to(crop_to_sizes, crop_where=crop_where)

    if pad_to_sizes:
        tensor = tensor.pad_to(pad_to_sizes, pad_where=pad_where, mode=pad_mode)

    if new_axes:
        tensor = tensor.expand_dims(new_axes)

    return tensor

round ¤

round(*args: Any, **kwargs: Any) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
181
182
183
184
185
186
def round(self, *args: Any, **kwargs: Any) -> Self:
    return self._unary_op(
        ops.round_,  # pyright: ignore[reportUnknownArgumentType]
        *args,
        **kwargs,
    )

std ¤

std(dim: Optional[Union[AxisId, Sequence[AxisId]]] = None) -> Self
Source code in src/bioimageio/core/tensor.py
485
486
def std(self, dim: Optional[Union[AxisId, Sequence[AxisId]]] = None) -> Self:
    return self.__class__.from_xarray(self._data.std(dim=dim))

sum ¤

sum(dim: Optional[Union[AxisId, Sequence[AxisId]]] = None) -> Self

Reduce this Tensor's data by applying sum along some dimension(s).

Source code in src/bioimageio/core/tensor.py
488
489
490
def sum(self, dim: Optional[Union[AxisId, Sequence[AxisId]]] = None) -> Self:
    """Reduce this Tensor's data by applying sum along some dimension(s)."""
    return self.__class__.from_xarray(self._data.sum(dim=dim))

to_numpy ¤

to_numpy() -> NDArray[Any]

Return the data of this tensor as a numpy array.

Source code in src/bioimageio/core/tensor.py
279
280
281
def to_numpy(self) -> NDArray[Any]:
    """Return the data of this tensor as a numpy array."""
    return self.data.to_numpy()  # pyright: ignore[reportUnknownVariableType]

transpose ¤

transpose(axes: Sequence[AxisId], *, extra_dims: Literal['raise', 'squeeze', 'stack', 'squeeze_or_stack'] = 'squeeze', missing_dims: Literal['raise', 'expand', 'unstack', 'unstack_or_expand'] = 'unstack_or_expand') -> Self

Return a transposed tensor, missing axes are expanded (if unstack_missing_dims_from_batch is False) or unstacked from batch (if unstack_missing_dims_from_batch is True), extra axes are stacked to batch (if stack_extra_dims_to_batch is True). Additional axes raise (if stack_extra_dims_to_batch is True).

Parameters:

Name Type Description Default

axes ¤

Sequence[AxisId]

The desired tensor axes

required

extra_dims ¤

Literal['raise', 'squeeze', 'stack', 'squeeze_or_stack']

Extra dimensions are any dimensions in the tensor that are not specified in axes. If "raise", any extra dimensions will raise an error. If "squeeze", any extra singleton dimensions will be squeezed, non-singleton dimensions will raise an error. If "stack", any extra dimensions will be stacked to the batch dimension. Such a stacked batch dimension then has a multi-index that can be unstacked using Tensor.unstack_batch_multi_index(). If "squeeze_or_stack", any extra singleton dimensions will be squeezed, non-singleton dimensions will be stacked to the batch dimension.

'squeeze'

missing_dims ¤

Literal['raise', 'expand', 'unstack', 'unstack_or_expand']

Missing dimensions are any dimensions specified in axes that are not present in the tensor. If "raise", any missing dimensions will raise an error. If "expand", any missing dimensions will be added as singleton dimensions. If "unstack", any missing dimensions will be unstacked from the batch dimension. For this option a batch dimension with a multi-index must be present from previous stacking operations or assigned by Tensor.assign_batch_multi_index(). If "unstack_or_expand", any missing dimensions will be unstacked from the batch dimension if it has a multi-index, otherwise they will be added as singleton dimensions.

'unstack_or_expand'
Source code in src/bioimageio/core/tensor.py
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
def transpose(
    self,
    axes: Sequence[AxisId],
    *,
    extra_dims: Literal[
        "raise", "squeeze", "stack", "squeeze_or_stack"
    ] = "squeeze",
    missing_dims: Literal[
        "raise", "expand", "unstack", "unstack_or_expand"
    ] = "unstack_or_expand",
) -> Self:
    """Return a transposed tensor, missing axes are expanded (if `unstack_missing_dims_from_batch` is False) or unstacked from batch (if `unstack_missing_dims_from_batch` is True), extra axes are stacked to batch (if `stack_extra_dims_to_batch` is True). Additional axes raise (if `stack_extra_dims_to_batch` is True).

    Args:
        axes: The desired tensor axes
        extra_dims:
            Extra dimensions are any dimensions in the tensor that are not specified in `axes`.
            If "raise", any extra dimensions will raise an error.
            If "squeeze", any extra singleton dimensions will be squeezed, non-singleton dimensions will raise an error.
            If "stack", any extra dimensions will be stacked to the batch dimension. Such a stacked batch dimension then has a multi-index that can be unstacked using `Tensor.unstack_batch_multi_index()`.
            If "squeeze_or_stack", any extra singleton dimensions will be squeezed, non-singleton dimensions will be stacked to the batch dimension.
        missing_dims:
            Missing dimensions are any dimensions specified in `axes` that are not present in the tensor.
            If "raise", any missing dimensions will raise an error.
            If "expand", any missing dimensions will be added as singleton dimensions.
            If "unstack", any missing dimensions will be unstacked from the batch dimension. For this option a batch dimension with a multi-index must be present from previous stacking operations or assigned by `Tensor.assign_batch_multi_index()`.
            If "unstack_or_expand", any missing dimensions will be unstacked from the batch dimension if it has a multi-index, otherwise they will be added as singleton dimensions.
    """
    array = self._data

    unhandled_missing_dims = [a for a in axes if a not in array.dims]
    if unhandled_missing_dims and missing_dims == "raise":
        raise ValueError(f"Found missing dimensions {unhandled_missing_dims}.")

    unstack_error = None
    if unhandled_missing_dims and missing_dims in ("unstack", "unstack_or_expand"):
        lets_unstack = AxisId("batch") in array.dims
        if not lets_unstack:
            unstack_error = f"Missing dimensions {unhandled_missing_dims} found, but 'batch' axis is not in the tensor. Cannot unstack missing dimensions from batch."
            if missing_dims == "unstack":
                raise ValueError(unstack_error)

        if lets_unstack and not isinstance(
            array.indexes.get(AxisId("batch")), pd.MultiIndex
        ):
            lets_unstack = False
            unstack_error = f"Missing dimensions {unhandled_missing_dims} found, but 'batch' axis does not have a MultiIndex. Cannot unstack missing dimensions from non-multi-index batch."
            if missing_dims == "unstack":
                raise ValueError(unstack_error)
    else:
        lets_unstack = False

    if lets_unstack:
        array = array.unstack(AxisId("batch"))

        if AxisId("original_batch") in array.dims:
            if AxisId("batch") in axes:
                array = array.rename({AxisId("original_batch"): AxisId("batch")})
            else:
                array = array.squeeze(AxisId("original_batch"))

        unhandled_missing_dims = [a for a in axes if a not in array.dims]

    if unhandled_missing_dims and missing_dims in ("expand", "unstack_or_expand"):
        array = array.expand_dims(unhandled_missing_dims)
        unhandled_missing_dims = []

    if unhandled_missing_dims:
        if unstack_error is not None:
            raise ValueError(unstack_error)

        raise ValueError(f"Missing dimensions {unhandled_missing_dims}.")

    unhandled_extra_dims = [a for a in array.dims if a not in axes]

    if unhandled_extra_dims and extra_dims == "raise":
        raise ValueError(f"Found extra dimensions {unhandled_extra_dims}.")

    if unhandled_extra_dims and extra_dims in ("squeeze", "squeeze_or_stack"):
        for d in list(unhandled_extra_dims):
            if array.sizes[d] == 1:
                array = array.squeeze(d)
                unhandled_extra_dims.remove(d)
            elif extra_dims == "squeeze":
                raise ValueError(
                    f"Extra dimension {d} found but stack_extra_dims_to_batch is False and the dimension is not a singleton."
                )

    if unhandled_extra_dims and extra_dims in ("stack", "squeeze_or_stack"):
        if AxisId("batch") not in axes:
            raise ValueError(
                f"Extra dimensions {unhandled_extra_dims} found but 'batch' axis is not in the desired axes {axes}."
                + " Cannot stack extra dimensions to batch."
            )

        if AxisId("batch") in array.dims:
            array = array.rename({AxisId("batch"): AxisId("original_batch")})
            unhandled_extra_dims.insert(0, AxisId("original_batch"))

        array = array.stack({AxisId("batch"): unhandled_extra_dims})
        unhandled_extra_dims = []

    if unhandled_extra_dims:
        raise ValueError(
            f"Non-singleton extra dimensions {unhandled_extra_dims} found, but `extra_dims` not in ('stack', 'squeeze_or_stack')."
        )

    # transpose to the correct axis order
    return self.__class__.from_xarray(array.transpose(*axes))

unstack_batch_multi_index ¤

unstack_batch_multi_index(*, errors: Literal['raise', 'ignore'] = 'raise') -> Self

Unstack the batch multi-index of this tensor.

Returns:

Type Description
Self

A new tensor with the batch multi-index unstacked into separate axes.

Source code in src/bioimageio/core/tensor.py
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
def unstack_batch_multi_index(
    self, *, errors: Literal["raise", "ignore"] = "raise"
) -> Self:
    """Unstack the batch multi-index of this tensor.

    Returns:
        A new tensor with the batch multi-index unstacked into separate axes.
    """
    if AxisId("batch") not in self.dims:
        if errors == "raise":
            raise ValueError(
                "Cannot unstack batch multi-index on a tensor without a 'batch' axis."
            )
        elif errors == "ignore":
            return self
        else:
            assert_never(errors)

    if not isinstance(self._data.indexes.get(AxisId("batch")), pd.MultiIndex):
        if errors == "raise":
            raise ValueError(
                "Cannot unstack batch multi-index on a tensor whose 'batch' axis does not have a MultiIndex."
            )
        elif errors == "ignore":
            return self
        else:
            assert_never(errors)

    old_dims = self.dims
    array = self._data.unstack(AxisId("batch"))
    added_dims = [AxisId(d) for d in array.dims if d not in self._data.dims]

    # restore expected axis order, replace batch dim with added dims
    new_dims: List[AxisId] = []
    for d in old_dims:
        if d in array.dims:
            new_dims.append(d)
        elif d == AxisId("batch"):
            new_dims.extend(added_dims)
        else:
            raise ValueError(f"Expected axis {d} not found in unstacked array.")

    array = array.transpose(*new_dims)
    if AxisId("original_batch") in array.dims:
        array = array.rename({AxisId("original_batch"): AxisId("batch")})

    return self.__class__.from_xarray(array)

var ¤

var(dim: Optional[Union[AxisId, Sequence[AxisId]]] = None) -> Self
Source code in src/bioimageio/core/tensor.py
665
666
def var(self, dim: Optional[Union[AxisId, Sequence[AxisId]]] = None) -> Self:
    return self.__class__.from_xarray(self._data.var(dim=dim))