|
| 1 | +# Copyright 2024 (C) BioVisionCenter, University of Zurich |
| 2 | +# |
| 3 | +# Original authors: |
| 4 | + |
| 5 | +# |
| 6 | +# This file is derived from a Fractal task core task developed by |
| 7 | +# Tommaso Comparin & Marco Franzon |
| 8 | +"""Task to remove singleton T dimension from an OME-Zarr.""" |
| 9 | + |
| 10 | +import logging |
| 11 | +import os |
| 12 | +import shutil |
| 13 | +from typing import Any |
| 14 | + |
| 15 | +import dask.array as da |
| 16 | +import ngio |
| 17 | +from pydantic import validate_call |
| 18 | + |
| 19 | +logger = logging.getLogger(__name__) |
| 20 | + |
| 21 | + |
| 22 | +@validate_call |
| 23 | +def add_z_singleton( |
| 24 | + *, |
| 25 | + zarr_url: str, |
| 26 | + suffix: str = "z_singleton", |
| 27 | + overwrite_input: bool = True, |
| 28 | +) -> dict[str, Any]: |
| 29 | + """Add a singleton Z dimension to a 2D OME-Zarr. |
| 30 | +
|
| 31 | + Args: |
| 32 | + zarr_url: Path or url to the individual OME-Zarr image to be processed. |
| 33 | + (standard argument for Fractal tasks, managed by Fractal server). |
| 34 | + suffix: Suffix to be used for the new Zarr image. If overwrite_input |
| 35 | + is True, this file is only temporary. |
| 36 | + overwrite_input: Whether the existing iamge should be overwritten with |
| 37 | + the new OME-Zarr with the Z singleton dimension. |
| 38 | + """ |
| 39 | + # Normalize zarr_url |
| 40 | + zarr_url_old = zarr_url.rstrip("/") |
| 41 | + zarr_url_new = f"{zarr_url_old}_{suffix}" |
| 42 | + |
| 43 | + logger.info(f"{zarr_url_old=}") |
| 44 | + logger.info(f"{zarr_url_new=}") |
| 45 | + |
| 46 | + old_ome_zarr = ngio.open_ome_zarr_container(zarr_url_old) |
| 47 | + old_ome_zarr_img = old_ome_zarr.get_image() |
| 48 | + if old_ome_zarr_img.has_axis("z"): |
| 49 | + raise ValueError( |
| 50 | + f"The Zarr image {zarr_url_old} already contains a Z axis. " |
| 51 | + "Thus, the add Z singleton dimension task can't be applied to it." |
| 52 | + ) |
| 53 | + image = old_ome_zarr_img.get_array(mode="dask") |
| 54 | + axes_names = old_ome_zarr_img.meta.axes_mapper.on_disk_axes_names |
| 55 | + ndim = image.ndim |
| 56 | + insert_index = ndim - 2 |
| 57 | + if insert_index < 0: |
| 58 | + raise ValueError( |
| 59 | + f"Cannot insert a Z axis at position {insert_index} in an array" |
| 60 | + f" with {ndim} dimensions." |
| 61 | + ) |
| 62 | + # Insert singleton Z dimension |
| 63 | + image_with_z = da.expand_dims(image, axis=insert_index) |
| 64 | + logger.info(f"Original shape: {image.shape}, new shape: {image_with_z.shape}") |
| 65 | + axes_names_with_z = axes_names[:insert_index] + ["z"] + axes_names[insert_index:] |
| 66 | + |
| 67 | + pixel_size = old_ome_zarr_img.pixel_size |
| 68 | + new_pixel_size = ngio.PixelSize(x=pixel_size.x, y=pixel_size.y, z=1.0) |
| 69 | + |
| 70 | + chunk_sizes = old_ome_zarr_img.chunks |
| 71 | + new_chunk_sizes = chunk_sizes[:insert_index] + (1,) + chunk_sizes[insert_index:] |
| 72 | + |
| 73 | + new_ome_zarr_container = old_ome_zarr.derive_image( |
| 74 | + store=zarr_url_new, |
| 75 | + shape=image_with_z.shape, |
| 76 | + chunks=new_chunk_sizes, |
| 77 | + dtype=old_ome_zarr_img.dtype, |
| 78 | + pixel_size=new_pixel_size, |
| 79 | + axes_names=axes_names_with_z, |
| 80 | + copy_tables=True, |
| 81 | + ) |
| 82 | + new_image_container = new_ome_zarr_container.get_image() |
| 83 | + new_image_container.set_array(image_with_z) |
| 84 | + new_image_container.consolidate() |
| 85 | + |
| 86 | + # TODO: Also handle copying over & adding Z dimension to label images? |
| 87 | + |
| 88 | + if overwrite_input: |
| 89 | + image_list_update = dict(zarr_url=zarr_url_old, types=dict(has_t=False)) |
| 90 | + os.rename(zarr_url_old, f"{zarr_url_old}_tmp") |
| 91 | + os.rename(zarr_url_new, zarr_url_old) |
| 92 | + shutil.rmtree(f"{zarr_url}_tmp") |
| 93 | + else: |
| 94 | + image_list_update = dict( |
| 95 | + zarr_url=zarr_url_new, origin=zarr_url_old, types=dict(has_t=False) |
| 96 | + ) |
| 97 | + |
| 98 | + return {"image_list_updates": [image_list_update]} |
| 99 | + |
| 100 | + |
| 101 | +if __name__ == "__main__": |
| 102 | + from fractal_task_tools.task_wrapper import run_fractal_task |
| 103 | + |
| 104 | + run_fractal_task( |
| 105 | + task_function=add_z_singleton, |
| 106 | + logger_name=logger.name, |
| 107 | + ) |
0 commit comments