Skip to content

ngio.common API documentation

ngio.common

Common classes and functions that are used across the package.

ChunksLike module-attribute

ChunksLike = tuple[int, ...] | Literal['auto']

ShardsLike module-attribute

ShardsLike = tuple[int, ...] | Literal['auto']

InterpolationOrder module-attribute

InterpolationOrder = Literal['nearest', 'linear', 'cubic']

Dimensions

Dimensions(
    shape: tuple[int, ...],
    chunks: tuple[int, ...],
    dataset: Dataset,
)

Dimension metadata Handling Class.

This class is used to handle and manipulate dimension metadata. It provides methods to access and validate dimension information, such as shape, axes, and properties like is_2d, is_3d, is_time_series, etc.

Create a Dimension object from a Zarr array.

Parameters:

  • shape (tuple[int, ...]) –

    The shape of the Zarr array.

  • chunks (tuple[int, ...]) –

    The chunks of the Zarr array.

  • dataset (Dataset) –

    The dataset object.

Source code in src/ngio/common/_dimensions.py
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
def __init__(
    self,
    shape: tuple[int, ...],
    chunks: tuple[int, ...],
    dataset: Dataset,
) -> None:
    """Create a Dimension object from a Zarr array.

    Args:
        shape: The shape of the Zarr array.
        chunks: The chunks of the Zarr array.
        dataset: The dataset object.
    """
    self._shape = shape
    self._chunks = chunks
    self._axes_handler = dataset.axes_handler
    self._pixel_size = dataset.pixel_size

    if len(self._shape) != len(self._axes_handler.axes):
        raise NgioValueError(
            "The number of dimensions must match the number of axes. "
            f"Expected Axis {self._axes_handler.axes_names} but got shape "
            f"{self._shape}."
        )
require_axes_match class-attribute instance-attribute
require_axes_match = require_axes_match
check_if_axes_match class-attribute instance-attribute
check_if_axes_match = check_if_axes_match
require_dimensions_match class-attribute instance-attribute
require_dimensions_match = require_dimensions_match
check_if_dimensions_match class-attribute instance-attribute
check_if_dimensions_match = check_if_dimensions_match
require_rescalable class-attribute instance-attribute
require_rescalable = require_rescalable
check_if_rescalable class-attribute instance-attribute
check_if_rescalable = check_if_rescalable
axes_handler property
axes_handler: AxesHandler

Return the axes handler object.

pixel_size property
pixel_size: PixelSize

Return the pixel size object.

shape property
shape: tuple[int, ...]

Return the shape as a tuple.

chunks property
chunks: tuple[int, ...]

Return the chunks as a tuple.

axes property
axes: tuple[str, ...]

Return the axes as a tuple of strings.

is_time_series property
is_time_series: bool

Return whether the image is a time series.

is_2d property
is_2d: bool

Return whether the image is 2D.

is_2d_time_series property
is_2d_time_series: bool

Return whether the image is a 2D time series.

is_3d property
is_3d: bool

Return whether the image is 3D.

is_3d_time_series property
is_3d_time_series: bool

Return whether the image is a 3D time series.

is_multi_channels property
is_multi_channels: bool

Return whether the image has multiple channels.

get
get(axis_name: str, default: None = None) -> int | None
get(axis_name: str, default: int) -> int
get(
    axis_name: str, default: int | None = None
) -> int | None

Return the dimension/shape of the given axis name.

Parameters:

  • axis_name (str) –

    The name of the axis (either canonical or non-canonical).

  • default (int | None, default: None ) –

    The default value to return if the axis does not exist.

Source code in src/ngio/common/_dimensions.py
325
326
327
328
329
330
331
332
333
334
335
def get(self, axis_name: str, default: int | None = None) -> int | None:
    """Return the dimension/shape of the given axis name.

    Args:
        axis_name: The name of the axis (either canonical or non-canonical).
        default: The default value to return if the axis does not exist.
    """
    index = self.axes_handler.get_index(axis_name)
    if index is None:
        return default
    return self._shape[index]

ImagePyramidBuilder

Bases: BaseModel

levels instance-attribute
levels: list[PyramidLevel]
axes instance-attribute
axes: tuple[str, ...]
data_type class-attribute instance-attribute
data_type: str = 'uint16'
dimension_separator class-attribute instance-attribute
dimension_separator: Literal['.', '/'] = '/'
compressors class-attribute instance-attribute
compressors: Any = 'auto'
zarr_format class-attribute instance-attribute
zarr_format: Literal[2, 3] = 2
other_array_kwargs class-attribute instance-attribute
other_array_kwargs: Mapping[str, Any] = {}
model_config class-attribute instance-attribute
model_config = ConfigDict(arbitrary_types_allowed=True)
from_scaling_factors classmethod
from_scaling_factors(
    levels_paths: tuple[str, ...],
    scaling_factors: tuple[float, ...],
    base_shape: tuple[int, ...],
    base_scale: tuple[float, ...],
    axes: tuple[str, ...],
    base_translation: Sequence[float] | None = None,
    chunks: ChunksLike = "auto",
    shards: ShardsLike | None = None,
    data_type: str = "uint16",
    dimension_separator: Literal[".", "/"] = "/",
    compressors: Any = "auto",
    zarr_format: Literal[2, 3] = 2,
    other_array_kwargs: Mapping[str, Any] | None = None,
    precision_scale: bool = True,
) -> ImagePyramidBuilder
Source code in src/ngio/common/_pyramid.py
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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
@classmethod
def from_scaling_factors(
    cls,
    levels_paths: tuple[str, ...],
    scaling_factors: tuple[float, ...],
    base_shape: tuple[int, ...],
    base_scale: tuple[float, ...],
    axes: tuple[str, ...],
    base_translation: Sequence[float] | None = None,
    chunks: ChunksLike = "auto",
    shards: ShardsLike | None = None,
    data_type: str = "uint16",
    dimension_separator: Literal[".", "/"] = "/",
    compressors: Any = "auto",
    zarr_format: Literal[2, 3] = 2,
    other_array_kwargs: Mapping[str, Any] | None = None,
    precision_scale: bool = True,
) -> "ImagePyramidBuilder":
    # Since shapes needs to be rounded to integers, we compute them here
    # and then pass them to from_shapes
    # This ensures that the shapes and scaling factors are consistent
    # and avoids accumulation of rounding errors
    shapes = compute_shapes_from_scaling_factors(
        base_shape=base_shape,
        scaling_factors=scaling_factors,
        num_levels=len(levels_paths),
    )

    if precision_scale:
        # Compute precise scales from shapes
        # Since shapes are rounded to integers, the scaling factors
        # may not be exactly the same as the input scaling factors
        # Thus, we compute the scales from the shapes to ensure consistency
        base_scale_ = compute_scales_from_shapes(
            shapes=shapes,
            base_scale=base_scale,
        )
    else:
        base_scale_ = _compute_scales_from_factors(
            base_scale=base_scale,
            scaling_factors=scaling_factors,
            num_levels=len(levels_paths),
        )

    return cls.from_shapes(
        shapes=shapes,
        base_scale=base_scale_,
        axes=axes,
        base_translation=base_translation,
        levels_paths=levels_paths,
        chunks=chunks,
        shards=shards,
        data_type=data_type,
        dimension_separator=dimension_separator,
        compressors=compressors,
        zarr_format=zarr_format,
        other_array_kwargs=other_array_kwargs,
    )
from_shapes classmethod
from_shapes(
    shapes: Sequence[tuple[int, ...]],
    base_scale: tuple[float, ...] | list[tuple[float, ...]],
    axes: tuple[str, ...],
    base_translation: Sequence[float] | None = None,
    levels_paths: Sequence[str] | None = None,
    chunks: ChunksLike = "auto",
    shards: ShardsLike | None = None,
    data_type: str = "uint16",
    dimension_separator: Literal[".", "/"] = "/",
    compressors: Any = "auto",
    zarr_format: Literal[2, 3] = 2,
    other_array_kwargs: Mapping[str, Any] | None = None,
) -> ImagePyramidBuilder
Source code in src/ngio/common/_pyramid.py
410
411
412
413
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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
@classmethod
def from_shapes(
    cls,
    shapes: Sequence[tuple[int, ...]],
    base_scale: tuple[float, ...] | list[tuple[float, ...]],
    axes: tuple[str, ...],
    base_translation: Sequence[float] | None = None,
    levels_paths: Sequence[str] | None = None,
    chunks: ChunksLike = "auto",
    shards: ShardsLike | None = None,
    data_type: str = "uint16",
    dimension_separator: Literal[".", "/"] = "/",
    compressors: Any = "auto",
    zarr_format: Literal[2, 3] = 2,
    other_array_kwargs: Mapping[str, Any] | None = None,
) -> "ImagePyramidBuilder":
    levels = []
    if levels_paths is None:
        levels_paths = tuple(str(i) for i in range(len(shapes)))

    _check_order(shapes)
    if isinstance(base_scale, tuple) and all(
        isinstance(s, float) for s in base_scale
    ):
        scales = compute_scales_from_shapes(shapes, base_scale)
    elif isinstance(base_scale, list):
        scales = base_scale
        if len(scales) != len(shapes):
            raise NgioValueError(
                "Scales must have the same length as shapes "
                f"({len(shapes)}), got {len(scales)}"
            )
    else:
        raise NgioValueError(
            "base_scale must be either a tuple of floats or a list of tuples "
            " of floats."
        )

    translations = _compute_translations_from_shapes(scales, base_translation)
    for level_path, shape, scale, translation in zip(
        levels_paths,
        shapes,
        scales,
        translations,
        strict=True,
    ):
        level = PyramidLevel(
            path=level_path,
            shape=shape,
            scale=scale,
            translation=translation,
            chunks=chunks,
            shards=shards,
        )
        levels.append(level)
    other_array_kwargs = other_array_kwargs or {}
    return cls(
        levels=levels,
        axes=axes,
        data_type=data_type,
        dimension_separator=dimension_separator,
        compressors=compressors,
        zarr_format=zarr_format,
        other_array_kwargs=other_array_kwargs,
    )
to_zarr
to_zarr(group: Group) -> None

Save the pyramid specification to a Zarr group.

Parameters:

  • group (Group) –

    The Zarr group to save the pyramid specification to.

Source code in src/ngio/common/_pyramid.py
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
def to_zarr(self, group: zarr.Group) -> None:
    """Save the pyramid specification to a Zarr group.

    Args:
        group (zarr.Group): The Zarr group to save the pyramid specification to.
    """
    array_static_kwargs = {
        "dtype": self.data_type,
        "overwrite": True,
        "compressors": self.compressors,
        **self.other_array_kwargs,
    }

    if self.zarr_format == 2:
        array_static_kwargs["chunk_key_encoding"] = {
            "name": "v2",
            "separator": self.dimension_separator,
        }
    else:
        array_static_kwargs["chunk_key_encoding"] = {
            "name": "default",
            "separator": self.dimension_separator,
        }
        array_static_kwargs["dimension_names"] = self.axes
    for p_level in self.levels:
        group.create_array(
            name=p_level.path,
            shape=tuple(p_level.shape),
            chunks=p_level.chunks,
            shards=p_level.shards,
            **array_static_kwargs,
        )

Roi

Bases: BaseModel

A multi-dimensional Region of Interest (ROI).

An Roi groups one RoiSlice per axis into a named, labelled region that can live in either world (physical) or pixel coordinate space.

Attributes:

  • name (str | None) –

    Human-readable name for this ROI, or None.

  • slices (list[RoiSlice]) –

    List of per-axis slices. Must contain at least two entries and each axis name must be unique.

  • label (int | None) –

    Integer label identifying the ROI (e.g. from a label image). Must be non-negative, or None if unlabelled.

  • space (Literal['world', 'pixel']) –

    Coordinate space of the slice values - either "world" for physical units or "pixel" for pixel indices.

name instance-attribute
name: str | None
slices class-attribute instance-attribute
slices: list[RoiSlice] = Field(min_length=2)
label class-attribute instance-attribute
label: int | None = Field(default=None, ge=0)
space class-attribute instance-attribute
space: Literal['world', 'pixel'] = 'world'
model_config class-attribute instance-attribute
model_config = ConfigDict(extra='allow')
validate_no_duplicate_axes classmethod
validate_no_duplicate_axes(
    v: list[RoiSlice],
) -> list[RoiSlice]
Source code in src/ngio/common/_roi.py
279
280
281
282
283
284
285
@field_validator("slices")
@classmethod
def validate_no_duplicate_axes(cls, v: list[RoiSlice]) -> list[RoiSlice]:
    axis_names = [s.axis_name for s in v]
    if len(axis_names) != len(set(axis_names)):
        raise NgioValueError("Roi slices must have unique axis names")
    return v
from_values classmethod
from_values(
    slices: Mapping[str, SliceValueType | RoiSlice],
    name: str | None,
    label: int | None = None,
    space: Literal["world", "pixel"] = "world",
    **kwargs,
) -> Self

Create an Roi from a mapping of axis names to slice values.

Parameters:

  • slices (Mapping[str, SliceValueType | RoiSlice]) –

    Mapping from axis name to a slice value accepted by RoiSlice.from_value (slice, tuple, float, or RoiSlice).

  • name (str | None) –

    Human-readable name for the ROI.

  • label (int | None, default: None ) –

    Integer label, or None if unlabelled.

  • space (Literal['world', 'pixel'], default: 'world' ) –

    Coordinate space of the provided values ("world" or "pixel").

  • **kwargs

    Additional fields stored on the model.

Returns:

  • Self

    A new Roi instance.

Source code in src/ngio/common/_roi.py
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
@classmethod
def from_values(
    cls,
    slices: Mapping[str, SliceValueType | RoiSlice],
    name: str | None,
    label: int | None = None,
    space: Literal["world", "pixel"] = "world",
    **kwargs,
) -> Self:
    """Create an Roi from a mapping of axis names to slice values.

    Args:
        slices: Mapping from axis name to a slice value accepted by
            RoiSlice.from_value (slice, tuple, float, or RoiSlice).
        name: Human-readable name for the ROI.
        label: Integer label, or None if unlabelled.
        space: Coordinate space of the provided values ("world" or
            "pixel").
        **kwargs: Additional fields stored on the model.

    Returns:
        A new Roi instance.
    """
    _slices = []
    for axis, _slice in slices.items():
        _slices.append(RoiSlice.from_value(axis_name=axis, value=_slice))
    return cls.model_construct(
        name=name, slices=_slices, label=label, space=space, **kwargs
    )
get
get(
    axis_name: str, default: RoiSlice | None = None
) -> RoiSlice | None

Return the RoiSlice for a given axis, or None if not present.

Parameters:

  • axis_name (str) –

    Name of the axis to look up.

  • default (RoiSlice | None, default: None ) –

    Value to return if the axis is not found.

Returns:

  • RoiSlice | None

    The matching RoiSlice, or the default value if no slice with

  • RoiSlice | None

    the given axis name exists.

Source code in src/ngio/common/_roi.py
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
def get(self, axis_name: str, default: RoiSlice | None = None) -> RoiSlice | None:
    """Return the RoiSlice for a given axis, or None if not present.

    Args:
        axis_name: Name of the axis to look up.
        default: Value to return if the axis is not found.

    Returns:
        The matching RoiSlice, or the default value if no slice with
        the given axis name exists.
    """
    for roi_slice in self.slices:
        if roi_slice.axis_name == axis_name:
            return roi_slice
    return default
get_name
get_name() -> str

Return a display name for this ROI.

Falls back to the string label, then a full repr, when name is None.

Returns:

  • str

    The ROI name, label as string, or a repr string.

Source code in src/ngio/common/_roi.py
353
354
355
356
357
358
359
360
361
362
363
364
365
def get_name(self) -> str:
    """Return a display name for this ROI.

    Falls back to the string label, then a full repr, when name is None.

    Returns:
        The ROI name, label as string, or a repr string.
    """
    if self.name is not None:
        return self.name
    if self.label is not None:
        return str(self.label)
    return self._nice_repr__()
intersection
intersection(other: Self) -> Self | None

Return the per-axis intersection of this ROI and other, or None.

Axes present in both ROIs are intersected; axes present in only one are kept as-is. Returns None if any shared axis has no overlap.

Parameters:

  • other (Self) –

    Another Roi in the same coordinate space.

Returns:

  • Self | None

    A new Roi representing the intersection, or None if the ROIs

  • Self | None

    do not overlap.

Raises:

  • NgioValueError

    If the two ROIs are in different coordinate spaces, or if the labels conflict.

Source code in src/ngio/common/_roi.py
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
419
420
421
422
423
424
def intersection(self, other: Self) -> Self | None:
    """Return the per-axis intersection of this ROI and other, or None.

    Axes present in both ROIs are intersected; axes present in only one
    are kept as-is. Returns None if any shared axis has no overlap.

    Args:
        other: Another Roi in the same coordinate space.

    Returns:
        A new Roi representing the intersection, or None if the ROIs
        do not overlap.

    Raises:
        NgioValueError: If the two ROIs are in different coordinate
            spaces, or if the labels conflict.
    """
    if self.space != other.space:
        raise NgioValueError(
            "Roi intersection failed: One ROI is in pixel space and the "
            "other in world space"
        )

    out_slices = self._apply_sym_ops(
        self.slices, other.slices, op=lambda a, b: a.intersection(b)
    )
    if out_slices is None:
        return None

    name = _join_roi_names(self.name, other.name)
    label = _join_roi_labels(self.label, other.label)
    return self.model_copy(
        update={"name": name, "slices": out_slices, "label": label}
    )
union
union(other: Self) -> Self

Return the per-axis union (bounding box) of this ROI and other.

Axes present in both ROIs are unioned; axes present in only one are kept as-is.

Parameters:

  • other (Self) –

    Another Roi in the same coordinate space.

Returns:

  • Self

    A new Roi whose slices span the combined extent of both inputs.

Raises:

  • NgioValueError

    If the two ROIs are in different coordinate spaces, or if the labels conflict.

Source code in src/ngio/common/_roi.py
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
453
454
455
456
457
458
def union(self, other: Self) -> Self:
    """Return the per-axis union (bounding box) of this ROI and other.

    Axes present in both ROIs are unioned; axes present in only one are
    kept as-is.

    Args:
        other: Another Roi in the same coordinate space.

    Returns:
        A new Roi whose slices span the combined extent of both inputs.

    Raises:
        NgioValueError: If the two ROIs are in different coordinate
            spaces, or if the labels conflict.
    """
    if self.space != other.space:
        raise NgioValueError(
            "Roi union failed: One ROI is in pixel space and the "
            "other in world space"
        )

    out_slices = self._apply_sym_ops(
        self.slices, other.slices, op=lambda a, b: a.union(b)
    )
    if out_slices is None:
        raise NgioValueError("Roi union failed: could not compute union")

    name = _join_roi_names(self.name, other.name)
    label = _join_roi_labels(self.label, other.label)
    return self.model_copy(
        update={"name": name, "slices": out_slices, "label": label}
    )
zoom
zoom(
    zoom_factor: float = 1.0,
    axes: tuple[str, ...] = ("x", "y"),
) -> Self

Expand or shrink the ROI symmetrically along the specified axes.

Parameters:

  • zoom_factor (float, default: 1.0 ) –

    Multiplicative scale applied to the length of each selected slice. Must be strictly positive.

  • axes (tuple[str, ...], default: ('x', 'y') ) –

    Names of the axes to zoom. Defaults to ("x", "y").

Returns:

  • Self

    A new Roi with the zoom applied to the selected axes.

Source code in src/ngio/common/_roi.py
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
def zoom(
    self, zoom_factor: float = 1.0, axes: tuple[str, ...] = ("x", "y")
) -> Self:
    """Expand or shrink the ROI symmetrically along the specified axes.

    Args:
        zoom_factor: Multiplicative scale applied to the length of each
            selected slice. Must be strictly positive.
        axes: Names of the axes to zoom. Defaults to ("x", "y").

    Returns:
        A new Roi with the zoom applied to the selected axes.
    """
    new_slices = []
    for roi_slice in self.slices:
        if roi_slice.axis_name in axes:
            new_slices.append(roi_slice.zoom(zoom_factor=zoom_factor))
        else:
            new_slices.append(roi_slice)
    return self.model_copy(update={"slices": new_slices})
to_world
to_world(pixel_size: PixelSize | None = None) -> Self

Convert the ROI to world (physical) coordinate space.

If the ROI is already in world space, a copy is returned unchanged.

Parameters:

  • pixel_size (PixelSize | None, default: None ) –

    Per-axis pixel sizes used for the conversion. Required when the ROI is currently in pixel space.

Returns:

  • Self

    A new Roi with all slices expressed in world units.

Raises:

  • NgioValueError

    If the ROI is in pixel space and pixel_size is not provided.

Source code in src/ngio/common/_roi.py
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
def to_world(self, pixel_size: PixelSize | None = None) -> Self:
    """Convert the ROI to world (physical) coordinate space.

    If the ROI is already in world space, a copy is returned unchanged.

    Args:
        pixel_size: Per-axis pixel sizes used for the conversion.
            Required when the ROI is currently in pixel space.

    Returns:
        A new Roi with all slices expressed in world units.

    Raises:
        NgioValueError: If the ROI is in pixel space and pixel_size is
            not provided.
    """
    if self.space == "world":
        return self.model_copy()
    if pixel_size is None:
        raise NgioValueError(
            "Pixel sizes must be provided to convert ROI from pixel to world"
        )
    new_slices = []
    for roi_slice in self.slices:
        pixel_size_ = pixel_size.get(roi_slice.axis_name, default=1.0)
        new_slices.append(roi_slice.to_world(pixel_size=pixel_size_))
    return self.model_copy(update={"slices": new_slices, "space": "world"})
to_pixel
to_pixel(pixel_size: PixelSize | None = None) -> Self

Convert the ROI to pixel coordinate space.

If the ROI is already in pixel space, a copy is returned unchanged.

Parameters:

  • pixel_size (PixelSize | None, default: None ) –

    Per-axis pixel sizes used for the conversion. Required when the ROI is currently in world space.

Returns:

  • Self

    A new Roi with all slices expressed in pixel units.

Raises:

  • NgioValueError

    If the ROI is in world space and pixel_size is not provided.

Source code in src/ngio/common/_roi.py
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
def to_pixel(self, pixel_size: PixelSize | None = None) -> Self:
    """Convert the ROI to pixel coordinate space.

    If the ROI is already in pixel space, a copy is returned unchanged.

    Args:
        pixel_size: Per-axis pixel sizes used for the conversion.
            Required when the ROI is currently in world space.

    Returns:
        A new Roi with all slices expressed in pixel units.

    Raises:
        NgioValueError: If the ROI is in world space and pixel_size is
            not provided.
    """
    if self.space == "pixel":
        return self.model_copy()

    if pixel_size is None:
        raise NgioValueError(
            "Pixel sizes must be provided to convert ROI from world to pixel"
        )

    new_slices = []
    for roi_slice in self.slices:
        pixel_size_ = pixel_size.get(roi_slice.axis_name, default=1.0)
        new_slices.append(roi_slice.to_pixel(pixel_size=pixel_size_))
    return self.model_copy(update={"slices": new_slices, "space": "pixel"})
to_slicing_dict
to_slicing_dict(
    pixel_size: PixelSize | None = None,
) -> dict[str, slice]

Convert the ROI to a dict of axis-name -> slice in pixel space.

Converts to pixel coordinates first if necessary.

Parameters:

  • pixel_size (PixelSize | None, default: None ) –

    Per-axis pixel sizes, required when the ROI is in world space.

Returns:

  • dict[str, slice]

    A dict mapping each axis name to a Python slice object.

Source code in src/ngio/common/_roi.py
539
540
541
542
543
544
545
546
547
548
549
550
551
552
def to_slicing_dict(self, pixel_size: PixelSize | None = None) -> dict[str, slice]:
    """Convert the ROI to a dict of axis-name -> slice in pixel space.

    Converts to pixel coordinates first if necessary.

    Args:
        pixel_size: Per-axis pixel sizes, required when the ROI is in
            world space.

    Returns:
        A dict mapping each axis name to a Python slice object.
    """
    roi = self.to_pixel(pixel_size=pixel_size)
    return {roi_slice.axis_name: roi_slice.to_slice() for roi_slice in roi.slices}
update_slice
update_slice(
    name: str, new_slice: SliceValueType | RoiSlice
) -> Self

Replace or add the slice for a given axis.

If an axis with the given name already exists it is replaced; otherwise the new slice is appended.

Parameters:

  • name (str) –

    Axis name of the slice to update or add.

  • new_slice (SliceValueType | RoiSlice) –

    New slice value, accepted by RoiSlice.from_value.

Returns:

  • Self

    A new Roi with the updated slice list.

Source code in src/ngio/common/_roi.py
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
def update_slice(self, name: str, new_slice: SliceValueType | RoiSlice) -> Self:
    """Replace or add the slice for a given axis.

    If an axis with the given name already exists it is replaced;
    otherwise the new slice is appended.

    Args:
        name: Axis name of the slice to update or add.
        new_slice: New slice value, accepted by RoiSlice.from_value.

    Returns:
        A new Roi with the updated slice list.
    """
    new_roi_slice = RoiSlice.from_value(axis_name=name, value=new_slice)
    slices = []
    found = False
    for roi_slice in self.slices:
        if roi_slice.axis_name == name:
            slices.append(new_roi_slice)
            found = True
        else:
            slices.append(roi_slice)
    if not found:
        slices.append(new_roi_slice)
    return self.model_copy(update={"slices": slices})
remove_slice
remove_slice(name: str) -> Self

Remove the slice for a given axis.

Parameters:

  • name (str) –

    Axis name of the slice to remove.

Returns:

  • Self

    A new Roi with the named slice removed.

Raises:

Source code in src/ngio/common/_roi.py
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
def remove_slice(self, name: str) -> Self:
    """Remove the slice for a given axis.

    Args:
        name: Axis name of the slice to remove.

    Returns:
        A new Roi with the named slice removed.

    Raises:
        NgioValueError: If no slice with the given axis name exists.
    """
    slices = [s for s in self.slices if s.axis_name != name]
    if len(slices) == len(self.slices):
        raise NgioValueError(f"Axis '{name}' not found in ROI slices")
    return self.model_copy(update={"slices": slices})

RoiSlice

Bases: BaseModel

A 1-D slice along a named axis for use within a Region of Interest.

Represents a contiguous interval [start, start + length) along a single named axis. Either bound may be None to indicate an open (unbounded) interval.

Attributes:

  • axis_name (str) –

    Name of the axis this slice applies to (e.g. "x", "y", "z").

  • start (float | None) –

    Start coordinate of the interval (inclusive). None means "from the beginning".

  • length (float | None) –

    Length of the interval. Must be non-negative. None means "to the end".

axis_name instance-attribute
axis_name: str
start class-attribute instance-attribute
start: float | None = Field(default=None)
length class-attribute instance-attribute
length: float | None = Field(default=None, ge=0)
model_config class-attribute instance-attribute
model_config = ConfigDict(extra='forbid')
end property
end: float | None

Exclusive end coordinate of the interval.

Returns:

  • float | None

    start + length, or None if either bound is unset.

from_value classmethod
from_value(
    axis_name: str, value: SliceValueType | RoiSlice
) -> RoiSlice

Create a RoiSlice from a variety of input types.

Parameters:

  • axis_name (str) –

    Name of the axis this slice applies to.

  • value (SliceValueType | RoiSlice) –

    The interval to represent. Accepted types: - slice: converted directly via start / stop. - tuple[float | None, float | None]: interpreted as (start, length). - int | float: a single-unit interval starting at value (length=1). - RoiSlice: returned as-is.

Returns:

Raises:

  • TypeError

    If value is not one of the supported types.

Source code in src/ngio/common/_roi.py
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
@classmethod
def from_value(
    cls,
    axis_name: str,
    value: "SliceValueType | RoiSlice",
) -> "RoiSlice":
    """Create a RoiSlice from a variety of input types.

    Args:
        axis_name: Name of the axis this slice applies to.
        value: The interval to represent. Accepted types:
            - slice: converted directly via start / stop.
            - tuple[float | None, float | None]: interpreted as (start, length).
            - int | float: a single-unit interval starting at value (length=1).
            - RoiSlice: returned as-is.

    Returns:
        A new RoiSlice instance.

    Raises:
        TypeError: If value is not one of the supported types.
    """
    if isinstance(value, slice):
        return cls._from_slice(axis_name=axis_name, selection=value)
    elif isinstance(value, tuple):
        return cls(axis_name=axis_name, start=value[0], length=value[1])
    elif isinstance(value, int | float):
        return cls(axis_name=axis_name, start=value, length=1)
    elif isinstance(value, RoiSlice):
        return value
    else:
        raise TypeError(f"Unsupported type for slice value: {type(value)}")
to_slice
to_slice() -> slice

Convert to a standard Python slice object.

Returns:

  • slice

    A slice(start, end) representing this interval.

Source code in src/ngio/common/_roi.py
134
135
136
137
138
139
140
def to_slice(self) -> slice:
    """Convert to a standard Python slice object.

    Returns:
        A slice(start, end) representing this interval.
    """
    return slice(self.start, self.end)
union
union(other: RoiSlice) -> RoiSlice

Return the smallest interval that contains both slices.

Parameters:

  • other (RoiSlice) –

    Another RoiSlice on the same axis.

Returns:

  • RoiSlice

    A new RoiSlice spanning from the minimum start to the maximum

  • RoiSlice

    end of the two inputs.

Raises:

Source code in src/ngio/common/_roi.py
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
def union(self, other: "RoiSlice") -> "RoiSlice":
    """Return the smallest interval that contains both slices.

    Args:
        other: Another RoiSlice on the same axis.

    Returns:
        A new RoiSlice spanning from the minimum start to the maximum
        end of the two inputs.

    Raises:
        NgioValueError: If the two slices are on different axes.
    """
    self._is_compatible(other, "RoiSlice union failed")
    start = min(self.start or 0, other.start or 0)
    end = max(self.end or float("inf"), other.end or float("inf"))
    length = end - start if end > start else 0
    if length == float("inf"):
        length = None
    return RoiSlice(axis_name=self.axis_name, start=start, length=length)
intersection
intersection(other: RoiSlice) -> RoiSlice | None

Return the overlap between this slice and other, or None.

Parameters:

  • other (RoiSlice) –

    Another RoiSlice on the same axis.

Returns:

  • RoiSlice | None

    A new RoiSlice representing the overlapping interval, or None

  • RoiSlice | None

    if the two slices do not overlap.

Raises:

Source code in src/ngio/common/_roi.py
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
def intersection(self, other: "RoiSlice") -> "RoiSlice | None":
    """Return the overlap between this slice and other, or None.

    Args:
        other: Another RoiSlice on the same axis.

    Returns:
        A new RoiSlice representing the overlapping interval, or None
        if the two slices do not overlap.

    Raises:
        NgioValueError: If the two slices are on different axes.
    """
    self._is_compatible(other, "RoiSlice intersection failed")
    start = max(self.start or 0, other.start or 0)
    end = min(self.end or float("inf"), other.end or float("inf"))
    if end <= start:
        # No intersection
        return None
    length = end - start
    if length == float("inf"):
        length = None
    return RoiSlice(axis_name=self.axis_name, start=start, length=length)
to_world
to_world(pixel_size: float) -> RoiSlice

Convert from pixel coordinates to world (physical) coordinates.

Parameters:

  • pixel_size (float) –

    Physical size of one pixel along this axis.

Returns:

  • RoiSlice

    A new RoiSlice with start and length expressed in world units.

Source code in src/ngio/common/_roi.py
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
def to_world(self, pixel_size: float) -> "RoiSlice":
    """Convert from pixel coordinates to world (physical) coordinates.

    Args:
        pixel_size: Physical size of one pixel along this axis.

    Returns:
        A new RoiSlice with start and length expressed in world units.
    """
    start = (
        pixel_to_world(self.start, pixel_size) if self.start is not None else None
    )
    length = (
        pixel_to_world(self.length, pixel_size) if self.length is not None else None
    )
    return RoiSlice(axis_name=self.axis_name, start=start, length=length)
to_pixel
to_pixel(pixel_size: float) -> RoiSlice

Convert from world (physical) coordinates to pixel coordinates.

Parameters:

  • pixel_size (float) –

    Physical size of one pixel along this axis.

Returns:

  • RoiSlice

    A new RoiSlice with start and length expressed in pixel units.

Source code in src/ngio/common/_roi.py
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
def to_pixel(self, pixel_size: float) -> "RoiSlice":
    """Convert from world (physical) coordinates to pixel coordinates.

    Args:
        pixel_size: Physical size of one pixel along this axis.

    Returns:
        A new RoiSlice with start and length expressed in pixel units.
    """
    start = (
        world_to_pixel(self.start, pixel_size) if self.start is not None else None
    )
    length = (
        world_to_pixel(self.length, pixel_size) if self.length is not None else None
    )
    return RoiSlice(axis_name=self.axis_name, start=start, length=length)
zoom
zoom(zoom_factor: float = 1.0) -> RoiSlice

Expand or shrink the slice symmetrically around its centre.

A zoom_factor greater than 1 enlarges the interval; less than 1 shrinks it. The centre of the interval is preserved, and the start is clamped to 0.

Parameters:

  • zoom_factor (float, default: 1.0 ) –

    Multiplicative scale applied to the length. Must be strictly positive.

Returns:

  • RoiSlice

    A new RoiSlice with the adjusted interval.

Raises:

Source code in src/ngio/common/_roi.py
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
def zoom(self, zoom_factor: float = 1.0) -> "RoiSlice":
    """Expand or shrink the slice symmetrically around its centre.

    A zoom_factor greater than 1 enlarges the interval; less than 1
    shrinks it. The centre of the interval is preserved, and the start
    is clamped to 0.

    Args:
        zoom_factor: Multiplicative scale applied to the length.
            Must be strictly positive.

    Returns:
        A new RoiSlice with the adjusted interval.

    Raises:
        NgioValueError: If zoom_factor is not greater than 0.
    """
    if zoom_factor <= 0:
        raise NgioValueError("Zoom factor must be greater than 0")
    zoom_factor -= 1.0
    if self.length is None:
        return self

    diff_length = self.length * zoom_factor
    length = self.length + diff_length
    start = max((self.start or 0) - (diff_length / 2), 0)
    return RoiSlice(axis_name=self.axis_name, start=start, length=length)

compute_masking_roi

compute_masking_roi(
    segmentation: ndarray | Array,
    pixel_size: PixelSize,
    axes_order: Sequence[str],
) -> list[Roi]

Compute ROIs for each label in a segmentation.

This function expects a 2D, 3D, or 4D segmentation array. The axes order should match the segmentation dimensions.

Parameters:

  • segmentation (ndarray | Array) –

    The segmentation array (2D, 3D, or 4D).

  • pixel_size (PixelSize) –

    The pixel size metadata for coordinate conversion.

  • axes_order (Sequence[str]) –

    The order of axes in the segmentation (e.g., 'zyx' or 'yx').

Returns:

  • list[Roi]

    A list of Roi objects, one for each unique label in the segmentation.

Source code in src/ngio/common/_masking_roi.py
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
def compute_masking_roi(
    segmentation: np.ndarray | da.Array,
    pixel_size: PixelSize,
    axes_order: Sequence[str],
) -> list[Roi]:
    """Compute ROIs for each label in a segmentation.

    This function expects a 2D, 3D, or 4D segmentation array.
    The axes order should match the segmentation dimensions.

    Args:
        segmentation: The segmentation array (2D, 3D, or 4D).
        pixel_size: The pixel size metadata for coordinate conversion.
        axes_order: The order of axes in the segmentation (e.g., 'zyx' or 'yx').

    Returns:
        A list of Roi objects, one for each unique label in the segmentation.
    """
    if segmentation.ndim not in [2, 3, 4]:
        raise NgioValueError("Only 2D, 3D, and 4D segmentations are supported.")

    if len(axes_order) != segmentation.ndim:
        raise NgioValueError(
            "The length of axes_order must match the number of dimensions "
            "of the segmentation."
        )

    if isinstance(segmentation, da.Array):
        slices = lazy_compute_slices(segmentation)
    else:
        slices = compute_slices(segmentation)

    rois = []
    for label, slice_ in slices.items():
        assert len(slice_) == len(axes_order)
        slices = dict(zip(axes_order, slice_, strict=True))
        roi = Roi.from_values(
            name=str(label), slices=slices, label=label, space="pixel"
        )
        roi = roi.to_world(pixel_size=pixel_size)
        rois.append(roi)
    return rois

consolidate_pyramid

consolidate_pyramid(
    source: Array,
    targets: list[Array],
    order: InterpolationOrder = "linear",
    mode: Literal["dask", "numpy", "coarsen"] = "dask",
) -> None

Consolidate the Zarr array.

Source code in src/ngio/common/_pyramid.py
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
def consolidate_pyramid(
    source: zarr.Array,
    targets: list[zarr.Array],
    order: InterpolationOrder = "linear",
    mode: Literal["dask", "numpy", "coarsen"] = "dask",
) -> None:
    """Consolidate the Zarr array."""
    processed = [source]
    to_be_processed = targets

    while to_be_processed:
        source_id, target_id = _find_closest_arrays(processed, to_be_processed)

        source_image = processed[source_id]
        target_image = to_be_processed.pop(target_id)

        on_disk_zoom(
            source=source_image,
            target=target_image,
            mode=mode,
            order=order,
        )
        processed.append(target_image)

on_disk_zoom

on_disk_zoom(
    source: Array,
    target: Array,
    order: InterpolationOrder = "linear",
    mode: Literal["dask", "numpy", "coarsen"] = "dask",
) -> None

Apply a zoom operation from a source zarr array to a target zarr array.

Parameters:

  • source (Array) –

    The source array to zoom.

  • target (Array) –

    The target array to save the zoomed result to.

  • order (InterpolationOrder, default: 'linear' ) –

    The order of interpolation. Defaults to "linear".

  • mode (Literal['dask', 'numpy', 'coarsen'], default: 'dask' ) –

    The mode to use. Defaults to "dask".

Source code in src/ngio/common/_pyramid.py
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
def on_disk_zoom(
    source: zarr.Array,
    target: zarr.Array,
    order: InterpolationOrder = "linear",
    mode: Literal["dask", "numpy", "coarsen"] = "dask",
) -> None:
    """Apply a zoom operation from a source zarr array to a target zarr array.

    Args:
        source (zarr.Array): The source array to zoom.
        target (zarr.Array): The target array to save the zoomed result to.
        order (InterpolationOrder): The order of interpolation. Defaults to "linear".
        mode (Literal["dask", "numpy", "coarsen"]): The mode to use. Defaults to "dask".
    """
    if not isinstance(source, zarr.Array):
        raise NgioValueError("source must be a zarr array")

    if not isinstance(target, zarr.Array):
        raise NgioValueError("target must be a zarr array")

    if source.dtype != target.dtype:
        raise NgioValueError("source and target must have the same dtype")

    match mode:
        case "numpy":
            return _on_disk_numpy_zoom(source, target, order)
        case "dask":
            return _on_disk_dask_zoom(source, target, order)
        case "coarsen":
            return _on_disk_coarsen(
                source,
                target,
            )
        case _:
            raise NgioValueError("mode must be either 'dask', 'numpy' or 'coarsen'")

dask_zoom

dask_zoom(
    source_array: Array,
    scale: tuple[float | int, ...] | None = None,
    target_shape: tuple[int, ...] | None = None,
    order: InterpolationOrder = "linear",
) -> Array

Dask implementation of zooming an array.

Only one of scale or target_shape must be provided.

Parameters:

  • source_array (Array) –

    The source array to zoom.

  • scale (tuple[int, ...] | None, default: None ) –

    The scale factor to zoom by.

  • target_shape ((tuple[int, ...], None), default: None ) –

    The target shape to zoom to.

  • order (Literal['nearest', 'linear', 'cubic'], default: 'linear' ) –

    The order of interpolation. Defaults to "linear".

Returns:

  • Array

    da.Array: The zoomed array.

Source code in src/ngio/common/_zoom.py
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
def dask_zoom(
    source_array: da.Array,
    scale: tuple[float | int, ...] | None = None,
    target_shape: tuple[int, ...] | None = None,
    order: InterpolationOrder = "linear",
) -> da.Array:
    """Dask implementation of zooming an array.

    Only one of scale or target_shape must be provided.

    Args:
        source_array (da.Array): The source array to zoom.
        scale (tuple[int, ...] | None): The scale factor to zoom by.
        target_shape (tuple[int, ...], None): The target shape to zoom to.
        order (Literal["nearest", "linear", "cubic"]): The order of interpolation.
            Defaults to "linear".

    Returns:
        da.Array: The zoomed array.
    """
    # This function follow the implementation from:
    # https://github.com/ome/ome-zarr-py/blob/master/ome_zarr/dask_utils.py
    # The module was contributed by Andreas Eisenbarth @aeisenbarth
    # See https://github.com/toloudis/ome-zarr-py/pull/
    _scale, _target_shape = _zoom_inputs_check(
        source_array=source_array, scale=scale, target_shape=target_shape
    )

    # Rechunk to better match the scaling operation
    source_chunks = np.array(source_array.chunksize)  # type: ignore (da.Array.chunksize is a tuple of ints)
    better_source_chunks = np.maximum(1, np.round(source_chunks * _scale) / _scale)
    better_source_chunks = better_source_chunks.astype(int)
    source_array = source_array.rechunk(better_source_chunks)  # type: ignore (better_source_chunks is a valid input for rechunk)

    # Calculate the block output shape
    block_output_shape = tuple(np.ceil(better_source_chunks * _scale).astype(int))

    zoom_wrapper = partial(
        fast_zoom,
        zoom=_scale,
        order=order_to_int(order),
        mode="grid-constant",
        grid_mode=True,
    )

    out_array = da.map_blocks(
        zoom_wrapper, source_array, chunks=block_output_shape, dtype=source_array.dtype
    )

    # Slice and rechunk to target
    slices = tuple(slice(0, ts, 1) for ts in _target_shape)
    out_array = out_array[slices]
    return out_array

numpy_zoom

numpy_zoom(
    source_array: ndarray,
    scale: tuple[int | float, ...] | None = None,
    target_shape: tuple[int, ...] | None = None,
    order: InterpolationOrder = "linear",
) -> ndarray

Numpy implementation of zooming an array.

Only one of scale or target_shape must be provided.

Parameters:

  • source_array (ndarray) –

    The source array to zoom.

  • scale (tuple[int, ...] | None, default: None ) –

    The scale factor to zoom by.

  • target_shape ((tuple[int, ...], None), default: None ) –

    The target shape to zoom to.

  • order (Literal[0, 1, 2], default: 'linear' ) –

    The order of interpolation. Defaults to 1.

Returns:

  • ndarray

    np.ndarray: The zoomed array

Source code in src/ngio/common/_zoom.py
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
def numpy_zoom(
    source_array: np.ndarray,
    scale: tuple[int | float, ...] | None = None,
    target_shape: tuple[int, ...] | None = None,
    order: InterpolationOrder = "linear",
) -> np.ndarray:
    """Numpy implementation of zooming an array.

    Only one of scale or target_shape must be provided.

    Args:
        source_array (np.ndarray): The source array to zoom.
        scale (tuple[int, ...] | None): The scale factor to zoom by.
        target_shape (tuple[int, ...], None): The target shape to zoom to.
        order (Literal[0, 1, 2]): The order of interpolation. Defaults to 1.

    Returns:
        np.ndarray: The zoomed array
    """
    _scale, _ = _zoom_inputs_check(
        source_array=source_array, scale=scale, target_shape=target_shape
    )

    out_array = fast_zoom(
        source_array,
        zoom=_scale,
        order=order_to_int(order),
        mode="grid-constant",
        grid_mode=True,
    )
    assert isinstance(out_array, np.ndarray)
    return out_array