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:
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
56
57
58
59
60
61
62
63
64
65 | def __init__(
self,
array: NDArray[Any],
dims: Sequence[Union[AxisId, AxisLike]],
) -> None:
super().__init__()
axes = tuple(
a if isinstance(a, AxisId) else AxisInfo.create(a).id for a in dims
)
self._data = xr.DataArray(array, dims=axes)
|
__hash__
instance-attribute
__slots__
class-attribute
instance-attribute
dims
property
Tuple of dimension names associated with this tensor.
ndim
property
Number of tensor dimensions.
shape
property
Tuple of tensor axes lengths
shape_tuple
property
Tuple of tensor axes lengths
size
property
Number of elements in the tensor.
Equal to math.prod(tensor.shape), i.e., the product of the tensors’ dimensions.
sizes
property
Ordered, immutable mapping from axis ids to axis lengths.
tagged_shape
property
(alias for sizes) Ordered, immutable mapping from axis ids to lengths.
__abs__
Source code in src/bioimageio/core/_magic_tensor_ops.py
| 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
| 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
| def __and__(self, other: _Compatible) -> Self:
return self._binary_op(other, operator.and_)
|
__array__
__array__(dtype: DTypeLike = None)
Source code in src/bioimageio/core/tensor.py
| 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
| 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
| def __floordiv__(self, other: _Compatible) -> Self:
return self._binary_op(other, operator.floordiv)
|
__ge__
__ge__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
| def __ge__(self, other: _Compatible) -> Self:
return self._binary_op(other, operator.ge)
|
__getitem__
Source code in src/bioimageio/core/tensor.py
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91 | 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
| 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
| def __iadd__(self, other: _Compatible) -> Self:
return self._inplace_binary_op(other, operator.iadd)
|
__iand__
__iand__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
| def __iand__(self, other: _Compatible) -> Self:
return self._inplace_binary_op(other, operator.iand)
|
__ifloordiv__
__ifloordiv__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
| def __ifloordiv__(self, other: _Compatible) -> Self:
return self._inplace_binary_op(other, operator.ifloordiv)
|
__ilshift__
__ilshift__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
| def __ilshift__(self, other: _Compatible) -> Self:
return self._inplace_binary_op(other, operator.ilshift)
|
__imod__
__imod__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
| def __imod__(self, other: _Compatible) -> Self:
return self._inplace_binary_op(other, operator.imod)
|
__imul__
__imul__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
| def __imul__(self, other: _Compatible) -> Self:
return self._inplace_binary_op(other, operator.imul)
|
__invert__
Source code in src/bioimageio/core/_magic_tensor_ops.py
| 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
| def __ior__(self, other: _Compatible) -> Self:
return self._inplace_binary_op(other, operator.ior)
|
__ipow__
__ipow__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
| def __ipow__(self, other: _Compatible) -> Self:
return self._inplace_binary_op(other, operator.ipow)
|
__irshift__
__irshift__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
| def __irshift__(self, other: _Compatible) -> Self:
return self._inplace_binary_op(other, operator.irshift)
|
__isub__
__isub__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
| def __isub__(self, other: _Compatible) -> Self:
return self._inplace_binary_op(other, operator.isub)
|
__iter__
__iter__() -> Iterator[Any]
Source code in src/bioimageio/core/tensor.py
| 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
| def __itruediv__(self, other: _Compatible) -> Self:
return self._inplace_binary_op(other, operator.itruediv)
|
__ixor__
__ixor__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
| def __ixor__(self, other: _Compatible) -> Self:
return self._inplace_binary_op(other, operator.ixor)
|
__le__
__le__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
| def __le__(self, other: _Compatible) -> Self:
return self._binary_op(other, operator.le)
|
__len__
Source code in src/bioimageio/core/tensor.py
| def __len__(self) -> int:
return len(self.data)
|
__lshift__
__lshift__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
| def __lshift__(self, other: _Compatible) -> Self:
return self._binary_op(other, operator.lshift)
|
__lt__
__lt__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
| 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
| 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
| 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
| def __ne__(self, other: _Compatible) -> Self: # type: ignore[override]
return self._binary_op(
other,
nputils.array_ne, # pyright: ignore[reportUnknownArgumentType]
)
|
__neg__
Source code in src/bioimageio/core/_magic_tensor_ops.py
| 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
| def __or__(self, other: _Compatible) -> Self:
return self._binary_op(other, operator.or_)
|
__pos__
Source code in src/bioimageio/core/_magic_tensor_ops.py
| 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
| def __pow__(self, other: _Compatible) -> Self:
return self._binary_op(other, operator.pow)
|
__radd__
__radd__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
| 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
| def __rand__(self, other: _Compatible) -> Self:
return self._binary_op(other, operator.and_, reflexive=True)
|
__rfloordiv__
__rfloordiv__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
| def __rfloordiv__(self, other: _Compatible) -> Self:
return self._binary_op(other, operator.floordiv, reflexive=True)
|
__rmod__
__rmod__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
| 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
| 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
| def __ror__(self, other: _Compatible) -> Self:
return self._binary_op(other, operator.or_, reflexive=True)
|
__rpow__
__rpow__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
| def __rpow__(self, other: _Compatible) -> Self:
return self._binary_op(other, operator.pow, reflexive=True)
|
__rshift__
__rshift__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
| def __rshift__(self, other: _Compatible) -> Self:
return self._binary_op(other, operator.rshift)
|
__rsub__
__rsub__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
| 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
| def __rtruediv__(self, other: _Compatible) -> Self:
return self._binary_op(other, operator.truediv, reflexive=True)
|
__rxor__
__rxor__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
| def __rxor__(self, other: _Compatible) -> Self:
return self._binary_op(other, operator.xor, reflexive=True)
|
__setitem__
Source code in src/bioimageio/core/tensor.py
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108 | 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
| 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
| def __truediv__(self, other: _Compatible) -> Self:
return self._binary_op(other, operator.truediv)
|
__xor__
__xor__(other: _Compatible) -> Self
Source code in src/bioimageio/core/_magic_tensor_ops.py
| def __xor__(self, other: _Compatible) -> Self:
return self._binary_op(other, operator.xor)
|
argmax
argmax() -> Mapping[AxisId, int]
Source code in src/bioimageio/core/tensor.py
| 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
| def argsort(self, *args: Any, **kwargs: Any) -> Self:
return self._unary_op(
ops.argsort, # pyright: ignore[reportUnknownArgumentType]
*args,
**kwargs,
)
|
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
| 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
| 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
| 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
| def conjugate(self, *args: Any, **kwargs: Any) -> Self:
return self._unary_op(
ops.conjugate, # pyright: ignore[reportUnknownArgumentType]
*args,
**kwargs,
)
|
crop_to
crop to match sizes
Source code in src/bioimageio/core/tensor.py
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314 | 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
Source code in src/bioimageio/core/tensor.py
| 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
create a Tensor from a numpy array
Parameters:
| Name |
Type |
Description |
Default |
array
|
NDArray[Any]
|
|
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.)
|
required
|
Raises:
| Type |
Description |
ValueError
|
if dims is None and dims guessing fails.
|
Source code in src/bioimageio/core/tensor.py
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205 | @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.)
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
160
161
162
163
164
165
166
167
168
169 | @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.data, dims=tuple(AxisId(d) for d in data_array.dims)
)
|
item
Copy a tensor element to a standard Python scalar and return it.
Source code in src/bioimageio/core/tensor.py
319
320
321
322
323
324
325
326
327
328
329
330
331
332 | 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
| def mean(self, dim: Optional[Union[AxisId, Sequence[AxisId]]] = None) -> Self:
return self.__class__.from_xarray(self._data.mean(dim=dim))
|
pad
Source code in src/bioimageio/core/tensor.py
337
338
339
340
341
342
343
344
345 | def pad(
self,
pad_width: PerAxis[PadWidthLike],
mode: PadMode = "symmetric",
) -> Self:
pad_width = {a: PadWidth.create(p) for a, p in pad_width.items()}
return self.__class__.from_xarray(
self._data.pad(pad_width=pad_width, mode=mode)
)
|
pad_to
pad tensor to match sizes
Source code in src/bioimageio/core/tensor.py
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387 | 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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412 | 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
return cropped/padded tensor with sizes
Source code in src/bioimageio/core/tensor.py
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452 | 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
| 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
| 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
| 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))
|
transpose
return a transposed tensor
Parameters:
| Name |
Type |
Description |
Default |
axes
|
Sequence[AxisId]
|
|
required
|
Source code in src/bioimageio/core/tensor.py
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477 | def transpose(
self,
axes: Sequence[AxisId],
) -> Self:
"""return a transposed tensor
Args:
axes: the desired tensor axes
"""
# expand missing tensor axes
missing_axes = tuple(a for a in axes if a not in self.dims)
array = self._data
if missing_axes:
array = array.expand_dims(missing_axes)
# transpose to the correct axis order
return self.__class__.from_xarray(array.transpose(*axes))
|
var
var(dim: Optional[Union[AxisId, Sequence[AxisId]]] = None) -> Self
Source code in src/bioimageio/core/tensor.py
| def var(self, dim: Optional[Union[AxisId, Sequence[AxisId]]] = None) -> Self:
return self.__class__.from_xarray(self._data.var(dim=dim))
|