diff --git a/CHANGELOG.md b/CHANGELOG.md index 8dacce07..f5fbe0c4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # Changelog +## [Unreleased] + +### Changes + +- Preserve pyramid-level coordinate transformations when updating OME-Zarr 0.4 and 0.5 images and labels. Dataset scales, translations, and `pixel_size` now reflect the dataset-level metadata. The pyramid transforms are available on `meta.coordinate_transformations` and apply afterward ([#281](https://github.com/BioVisionCenter/ngio/issues/281)). + ## [v1.1.5] ### Fixes diff --git a/src/ngio/ome_zarr_meta/ngio_specs/_ngio_image.py b/src/ngio/ome_zarr_meta/ngio_specs/_ngio_image.py index 40803cfd..f3ddb049 100644 --- a/src/ngio/ome_zarr_meta/ngio_specs/_ngio_image.py +++ b/src/ngio/ome_zarr_meta/ngio_specs/_ngio_image.py @@ -10,6 +10,7 @@ from typing import Any, Literal, TypeVar import numpy as np +from ome_zarr_models.common.coordinate_transformations import ValidTransform from pydantic import BaseModel from ngio.ome_zarr_meta.ngio_specs._axes import ( @@ -53,7 +54,12 @@ class AbstractNgioImageMeta: """Base class for ImageMeta and LabelMeta.""" def __init__( - self, version: NgffVersions, name: str | None, datasets: list[Dataset] + self, + version: NgffVersions, + name: str | None, + datasets: list[Dataset], + *, + coordinate_transformations: ValidTransform | None = None, ) -> None: """Initialize the ImageMeta object.""" self._version = version @@ -64,6 +70,12 @@ def __init__( self._datasets = datasets self._axes_handler = datasets[0].axes_handler + self._coordinate_transformations = coordinate_transformations + + @property + def coordinate_transformations(self) -> ValidTransform | None: + """Transforms applied to the image pyramid after each dataset's transforms.""" + return self._coordinate_transformations def __repr__(self): class_name = type(self).__name__ @@ -111,6 +123,7 @@ def _rebuild(self, *, name: str | None, datasets: list[Dataset]): version=self.version, name=name, datasets=datasets, + coordinate_transformations=self.coordinate_transformations, ) def to_units( @@ -385,9 +398,16 @@ def __init__( name: str | None, datasets: list[Dataset], image_label: ImageLabelSource | None = None, + *, + coordinate_transformations: ValidTransform | None = None, ) -> None: """Initialize the ImageMeta object.""" - super().__init__(version, name, datasets) + super().__init__( + version, + name, + datasets, + coordinate_transformations=coordinate_transformations, + ) image_label = ( ImageLabelSource.default_init(self.version) if image_label is None @@ -421,6 +441,7 @@ def _rebuild(self, *, name: str | None, datasets: list[Dataset]): name=name, datasets=datasets, image_label=self._image_label, + coordinate_transformations=self.coordinate_transformations, ) @@ -433,9 +454,16 @@ def __init__( name: str | None, datasets: list[Dataset], channels: ChannelsMeta | None = None, + *, + coordinate_transformations: ValidTransform | None = None, ) -> None: """Initialize the ImageMeta object.""" - super().__init__(version=version, name=name, datasets=datasets) + super().__init__( + version=version, + name=name, + datasets=datasets, + coordinate_transformations=coordinate_transformations, + ) self._channels_meta = channels @property @@ -458,6 +486,7 @@ def _rebuild(self, *, name: str | None, datasets: list[Dataset]): name=name, datasets=datasets, channels=self._channels_meta, + coordinate_transformations=self.coordinate_transformations, ) def init_channels( diff --git a/src/ngio/ome_zarr_meta/v04/_v04_spec.py b/src/ngio/ome_zarr_meta/v04/_v04_spec.py index d08a34dd..9ec1f89f 100644 --- a/src/ngio/ome_zarr_meta/v04/_v04_spec.py +++ b/src/ngio/ome_zarr_meta/v04/_v04_spec.py @@ -37,6 +37,7 @@ ChannelVisualisation, Dataset, ImageLabelSource, + NgioImageLabelMeta, NgioImageMeta, NgioLabelMeta, NgioLabelsGroupMeta, @@ -97,9 +98,10 @@ def _v04_omero_to_channels(v04_omero: OmeroV04 | None) -> ChannelsMeta | None: def _compute_scale_translation( v04_transforms: ValidTransformV04, - scale: list[float], - translation: list[float], + ndim: int, ) -> tuple[list[float], list[float]]: + scale = [1.0] * ndim + translation = [0.0] * ndim for v04_transform in v04_transforms: if isinstance(v04_transform, VectorScaleV04): scale = [t1 * t2 for t1, t2 in zip(scale, v04_transform.scale, strict=True)] @@ -123,14 +125,6 @@ def _v04_to_ngio_datasets( """Convert a v04 multiscale to a list of ngio datasets.""" datasets = [] - global_scale = [1.0] * len(v04_multiscale.axes) - global_translation = [0.0] * len(v04_multiscale.axes) - - if v04_multiscale.coordinateTransformations is not None: - global_scale, global_translation = _compute_scale_translation( - v04_multiscale.coordinateTransformations, global_scale, global_translation - ) - # Prepare axes handler axes = [] for v04_axis in v04_multiscale.axes: @@ -153,7 +147,7 @@ def _v04_to_ngio_datasets( for v04_dataset in v04_multiscale.datasets: _scale, _translation = _compute_scale_translation( - v04_dataset.coordinateTransformations, global_scale, global_translation + v04_dataset.coordinateTransformations, len(v04_multiscale.axes) ) datasets.append( Dataset( @@ -187,15 +181,15 @@ def v04_to_ngio_image_meta( "Multiple multiscales in a single image are not supported in ngio." ) - v04_muliscale = v04_image.multiscales[0] + v04_multiscale = v04_image.multiscales[0] channels_meta = _v04_omero_to_channels(v04_image.omero) datasets = _v04_to_ngio_datasets( - v04_muliscale, + v04_multiscale, axes_setup=axes_setup, ) - name = v04_muliscale.name + name = v04_multiscale.name if name is not None and not isinstance(name, str): name = str(name) return NgioImageMeta( @@ -203,6 +197,7 @@ def v04_to_ngio_image_meta( name=name, datasets=datasets, channels=channels_meta, + coordinate_transformations=v04_multiscale.coordinateTransformations, ) @@ -227,9 +222,9 @@ def v04_to_ngio_label_meta( "Multiple multiscales in a single image are not supported in ngio." ) - v04_muliscale = v04_label.multiscales[0] + v04_multiscale = v04_label.multiscales[0] datasets = _v04_to_ngio_datasets( - v04_muliscale, + v04_multiscale, axes_setup=axes_setup, ) @@ -246,7 +241,7 @@ def v04_to_ngio_label_meta( version="0.4", source={"image": image_label_source}, ) - name = v04_muliscale.name + name = v04_multiscale.name if name is not None and not isinstance(name, str): name = str(name) @@ -255,20 +250,13 @@ def v04_to_ngio_label_meta( name=name, datasets=datasets, image_label=image_label_source, + coordinate_transformations=v04_multiscale.coordinateTransformations, ) -def _ngio_to_v04_multiscale(name: str | None, datasets: list[Dataset]) -> MultiscaleV04: - """Convert a ngio multiscale to a v04 multiscale. - - Args: - name (str | None): The name of the multiscale. - datasets (list[Dataset]): The ngio datasets. - - Returns: - MultiscaleV04: The v04 multiscale. - """ - ax_mapper = datasets[0].axes_handler +def _ngio_to_v04_multiscale(metadata: NgioImageLabelMeta) -> MultiscaleV04: + """Convert a ngio multiscale to a v04 multiscale.""" + ax_mapper = metadata.axes_handler v04_axes = [] for axis in ax_mapper.axes: v04_axes.append( @@ -280,7 +268,7 @@ def _ngio_to_v04_multiscale(name: str | None, datasets: list[Dataset]) -> Multis ) v04_datasets = [] - for dataset in datasets: + for dataset in metadata.datasets: transform = [VectorScaleV04(type="scale", scale=list(dataset._scale))] if any(abs(t) > 1e-9 for t in dataset._translation): transform = ( @@ -296,7 +284,11 @@ def _ngio_to_v04_multiscale(name: str | None, datasets: list[Dataset]) -> Multis DatasetV04(path=dataset.path, coordinateTransformations=transform) ) return MultiscaleV04( - axes=v04_axes, datasets=tuple(v04_datasets), version="0.4", name=name + axes=v04_axes, + datasets=tuple(v04_datasets), + version="0.4", + name=metadata.name, + coordinateTransformations=metadata.coordinate_transformations, ) @@ -341,9 +333,7 @@ def ngio_to_v04_image_meta(metadata: NgioImageMeta) -> dict: Returns: dict: The v04 image metadata. """ - v04_muliscale = _ngio_to_v04_multiscale( - name=metadata.name, datasets=metadata.datasets - ) + v04_muliscale = _ngio_to_v04_multiscale(metadata) v04_omero = _ngio_to_v04_omero(metadata._channels_meta) v04_image = ImageAttrsV04(multiscales=[v04_muliscale], omero=v04_omero) @@ -359,9 +349,7 @@ def ngio_to_v04_label_meta(metadata: NgioLabelMeta) -> dict: Returns: dict: The v04 image metadata. """ - v04_muliscale = _ngio_to_v04_multiscale( - name=metadata.name, datasets=metadata.datasets - ) + v04_muliscale = _ngio_to_v04_multiscale(metadata) labels_meta = { "multiscales": [v04_muliscale], "image-label": metadata.image_label.model_dump(), diff --git a/src/ngio/ome_zarr_meta/v05/_v05_spec.py b/src/ngio/ome_zarr_meta/v05/_v05_spec.py index 391f6c5b..574de6f6 100644 --- a/src/ngio/ome_zarr_meta/v05/_v05_spec.py +++ b/src/ngio/ome_zarr_meta/v05/_v05_spec.py @@ -38,6 +38,7 @@ ChannelVisualisation, Dataset, ImageLabelSource, + NgioImageLabelMeta, NgioImageMeta, NgioLabelMeta, NgioLabelsGroupMeta, @@ -110,9 +111,10 @@ def _v05_omero_to_channels(v05_omero: OmeroV05 | None) -> ChannelsMeta | None: def _compute_scale_translation( v05_transforms: ValidTransformV05, - scale: list[float], - translation: list[float], + ndim: int, ) -> tuple[list[float], list[float]]: + scale = [1.0] * ndim + translation = [0.0] * ndim for v05_transform in v05_transforms: if isinstance(v05_transform, VectorScaleV05): scale = [t1 * t2 for t1, t2 in zip(scale, v05_transform.scale, strict=True)] @@ -136,14 +138,6 @@ def _v05_to_ngio_datasets( """Convert a v05 multiscale to a list of ngio datasets.""" datasets = [] - global_scale = [1.0] * len(v05_multiscale.axes) - global_translation = [0.0] * len(v05_multiscale.axes) - - if v05_multiscale.coordinateTransformations is not None: - global_scale, global_translation = _compute_scale_translation( - v05_multiscale.coordinateTransformations, global_scale, global_translation - ) - # Prepare axes handler axes = [] for v05_axis in v05_multiscale.axes: @@ -166,7 +160,7 @@ def _v05_to_ngio_datasets( for v05_dataset in v05_multiscale.datasets: _scale, _translation = _compute_scale_translation( - v05_dataset.coordinateTransformations, global_scale, global_translation + v05_dataset.coordinateTransformations, len(v05_multiscale.axes) ) datasets.append( Dataset( @@ -216,6 +210,7 @@ def v05_to_ngio_image_meta( name=name, datasets=datasets, channels=channels_meta, + coordinate_transformations=v05_multiscale.coordinateTransformations, ) @@ -273,20 +268,13 @@ def v05_to_ngio_label_meta( name=name, datasets=datasets, image_label=image_label_source, + coordinate_transformations=v05_multiscale.coordinateTransformations, ) -def _ngio_to_v05_multiscale(name: str | None, datasets: list[Dataset]) -> MultiscaleV05: - """Convert a ngio multiscale to a v05 multiscale. - - Args: - name (str | None): The name of the multiscale. - datasets (list[Dataset]): The ngio datasets. - - Returns: - MultiscaleV05: The v05 multiscale. - """ - ax_mapper = datasets[0].axes_handler +def _ngio_to_v05_multiscale(metadata: NgioImageLabelMeta) -> MultiscaleV05: + """Convert a ngio multiscale to a v05 multiscale.""" + ax_mapper = metadata.axes_handler v05_axes = [] for axis in ax_mapper.axes: v05_axes.append( @@ -298,7 +286,7 @@ def _ngio_to_v05_multiscale(name: str | None, datasets: list[Dataset]) -> Multis ) v05_datasets = [] - for dataset in datasets: + for dataset in metadata.datasets: transform = [VectorScaleV05(type="scale", scale=list(dataset._scale))] if any(abs(t) > 1e-9 for t in dataset._translation): transform = ( @@ -313,7 +301,12 @@ def _ngio_to_v05_multiscale(name: str | None, datasets: list[Dataset]) -> Multis v05_datasets.append( DatasetV05(path=dataset.path, coordinateTransformations=transform) ) - return MultiscaleV05(axes=v05_axes, datasets=tuple(v05_datasets), name=name) + return MultiscaleV05( + axes=v05_axes, + datasets=tuple(v05_datasets), + name=metadata.name, + coordinateTransformations=metadata.coordinate_transformations, + ) def _ngio_to_v05_omero(channels: ChannelsMeta | None) -> OmeroV05 | None: @@ -357,9 +350,7 @@ def ngio_to_v05_image_meta(metadata: NgioImageMeta) -> dict: Returns: dict: The v05 image metadata. """ - v05_muliscale = _ngio_to_v05_multiscale( - name=metadata.name, datasets=metadata.datasets - ) + v05_muliscale = _ngio_to_v05_multiscale(metadata) v05_omero = _ngio_to_v05_omero(metadata._channels_meta) v05_image_attrs = ImageV05AttrsWithOmero( @@ -380,9 +371,7 @@ def ngio_to_v05_label_meta(metadata: NgioLabelMeta) -> dict: Returns: dict: The v05 image metadata. """ - v05_muliscale = _ngio_to_v05_multiscale( - name=metadata.name, datasets=metadata.datasets - ) + v05_muliscale = _ngio_to_v05_multiscale(metadata) labels_meta = { "multiscales": [v05_muliscale], "image-label": metadata.image_label.model_dump(), diff --git a/tests/unit/images/test_axes_units.py b/tests/unit/images/test_axes_units.py index ecd016e7..57787674 100644 --- a/tests/unit/images/test_axes_units.py +++ b/tests/unit/images/test_axes_units.py @@ -1,8 +1,9 @@ """The units API: split setters, the deprecated batch form, and issue #231/#232.""" import pytest +import zarr -from ngio import create_empty_ome_zarr +from ngio import create_empty_ome_zarr, open_ome_zarr_container from ngio.utils import NgioDeprecationWarning @@ -73,3 +74,53 @@ def test_label_source_survives_metadata_updates(ngff_version): label.set_space_unit("micrometer") after = label._meta_handler.get_meta().image_label assert after == before + + +@pytest.mark.parametrize("ngff_version", ["0.4", "0.5"]) +@pytest.mark.parametrize("is_label", [False, True], ids=["image", "label"]) +def test_metadata_updates_preserve_multiscale_transforms(ngff_version, is_label): + store = zarr.storage.MemoryStore() + container = create_empty_ome_zarr( + store=store, + shape=(2, 16, 24), + axes_names=["c", "y", "x"], + pixelsize=(0.5, 1.0), + levels=2, + ngff_version=ngff_version, + ) + if is_label: + container.derive_label("seg") + group_path = "labels/seg" if is_label else None + group = zarr.open_group(store=store, path=group_path, mode="r+") + attrs = dict(group.attrs) + metadata = attrs if ngff_version == "0.4" else attrs["ome"] + multiscale = metadata["multiscales"][0] + leading_axes = len(multiscale["axes"]) - 2 + pyramid_transforms = [ + {"type": "scale", "scale": [1.0] * leading_axes + [2.0, 3.0]}, + {"type": "translation", "translation": [0.0] * leading_axes + [10.0, 20.0]}, + ] + multiscale["coordinateTransformations"] = pyramid_transforms + local_translation = [0.0] * leading_axes + [4.0, -3.0] + for dataset in multiscale["datasets"]: + dataset["coordinateTransformations"].append( + {"type": "translation", "translation": local_translation} + ) + group.attrs.update(attrs) + + container = open_ome_zarr_container(store, mode="r+") + image = container.get_label("seg") if is_label else container.get_image() + for decoded, raw in zip(image.meta.datasets, multiscale["datasets"], strict=True): + assert decoded.scale == tuple(raw["coordinateTransformations"][0]["scale"]) + assert decoded.translation == tuple(local_translation) + + if not is_label: + container.set_channel_labels(["first", "second"]) + image.set_space_unit("nanometer") + + attrs = dict(zarr.open_group(store=store, path=group_path, mode="r").attrs) + metadata = attrs if ngff_version == "0.4" else attrs["ome"] + written = metadata["multiscales"][0] + assert written["coordinateTransformations"] == pyramid_transforms + assert written["datasets"] == multiscale["datasets"] + assert all(axis["unit"] == "nanometer" for axis in written["axes"][-2:]) diff --git a/tests/unit/ome_zarr_meta/test_unit_v05_utils.py b/tests/unit/ome_zarr_meta/test_unit_v05_utils.py index 343a109b..2ce61977 100644 --- a/tests/unit/ome_zarr_meta/test_unit_v05_utils.py +++ b/tests/unit/ome_zarr_meta/test_unit_v05_utils.py @@ -134,9 +134,13 @@ def test_image_global_coordinate_transformations(): ngio_image = v05_to_ngio_image_meta( _image_attrs(multiscales=[multiscale]), axes_setup=AxesSetup() ) - # the multiscale-level scale multiplies every dataset scale - assert ngio_image.datasets[0].scale == (2.0, 2.0) - assert ngio_image.datasets[1].scale == (4.0, 4.0) + assert ngio_image.datasets[0].scale == (1.0, 1.0) + assert ngio_image.datasets[1].scale == (2.0, 2.0) + transforms = ngio_image.coordinate_transformations + assert transforms is not None + assert [transform.model_dump() for transform in transforms] == multiscale[ + "coordinateTransformations" + ] def _label_attrs() -> dict: