From 7075e98498ae31d6fe4ec930269f2f94514a0ca3 Mon Sep 17 00:00:00 2001 From: Henrik K M <19748824+Henrik-KM@users.noreply.github.com> Date: Thu, 19 Nov 2026 19:10:53 +0100 Subject: [PATCH] feat: expose the Dask write grid for image regions --- CHANGELOG.md | 6 +++ docs/getting_started/2_images.md | 18 ++++++++ src/ngio/images/_abstract_image.py | 32 +++++++++++++- tests/unit/common/test_dask_io.py | 70 ++++++++++++++++++++++++++++++ 4 files changed, 125 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8dacce07..c3772e1b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # Changelog +## [Unreleased] + +### Features + +- `Image.write_grid(roi)` exposes the Dask writer's chunk- or shard-aligned block sizes in array order for an ROI or the full image ([#278](https://github.com/BioVisionCenter/ngio/issues/278)). + ## [v1.1.5] ### Fixes diff --git a/docs/getting_started/2_images.md b/docs/getting_started/2_images.md index 62b89092..1c772543 100644 --- a/docs/getting_started/2_images.md +++ b/docs/getting_started/2_images.md @@ -234,6 +234,24 @@ that came back: Axis keywords compose with a roi as a hierarchy: `get_roi(roi, z=2)` reads the roi's x/y extent at one absolute z plane. An explicit keyword on an axis the roi already pins replaces the roi-derived selection — coordinates are absolute array indices, not relative to the roi — and drops the pipe's `roi`, so anything needing the region as a `Roi` (a mask transform, world anchoring) refuses rather than misplacing pixels. +### Planning Dask writes + +`image.write_grid(roi)` returns the block lengths the writer uses for a region, +in `image.axes` order. Interior block edges fall on chunk or shard boundaries in +the Zarr array, and each block is written by one Dask task. Call +`image.write_grid()` for the full image. + +If a sliceable source matches the ROI's shape and axis order, use the grid as its +Dask chunks. The writer can use those blocks directly when the block-size +settings and the ROI match. + +```python +import dask.array as da + +patch = da.from_array(source, chunks=image.write_grid(roi)) +image.set_roi(roi, patch, axes_order=image.axes) +``` + ## Labels A label is a segmentation mask that identifies objects in the image. In ngio a [`Label`][ngio.Label] diff --git a/src/ngio/images/_abstract_image.py b/src/ngio/images/_abstract_image.py index eb78bc5d..e6431613 100644 --- a/src/ngio/images/_abstract_image.py +++ b/src/ngio/images/_abstract_image.py @@ -18,7 +18,8 @@ Roi, consolidate_pyramid, ) -from ngio.common._dask_io import RegionType +from ngio.common._dask_io import RegionType, _normalize_region +from ngio.common._dask_io import write_grid as dask_write_grid from ngio.common._pyramid import ( ChunksLike, ConsolidationMode, @@ -233,6 +234,35 @@ def write_granularity(self) -> tuple[int, ...]: """ return self.zarr_array.shards or self.zarr_array.chunks + def write_grid(self, roi: Roi | None = None) -> tuple[tuple[int, ...], ...]: + """Return the Dask block sizes for writing a region of this image. + + Interior block edges fall on chunk or shard boundaries in Zarr array + coordinates. Each block is written by one Dask task. A block at the + edge of the region may cover part of a write unit. + + The grid uses the writer's current Dask block-size settings. Use these + sizes to build a lazy patch in `image.axes` order and write it with the + same ROI and settings to avoid rechunking. + + Args: + roi: The region to write, resolved at this image's pixel size. + `None` selects the full image. + + Returns: + The block lengths along each on-disk axis, in array order. + """ + region = None + if roi is not None: + setter = DaskSetter( + zarr_array=self.zarr_array, + dimensions=self.dimensions, + roi=roi, + ) + region = setter.slicing_ops.normalized_slicing_tuple + slices = _normalize_region(region, self.shape) + return dask_write_grid(self.zarr_array, slices) + @property def is_3d(self) -> bool: """Return True if the image is 3D.""" diff --git a/tests/unit/common/test_dask_io.py b/tests/unit/common/test_dask_io.py index ca698bc9..37f8bc5a 100644 --- a/tests/unit/common/test_dask_io.py +++ b/tests/unit/common/test_dask_io.py @@ -10,6 +10,7 @@ from dask.array.core import _get_zarr_write_chunks from dask.utils import parse_bytes +from ngio import Roi, create_empty_ome_zarr from ngio.common._dask_io import ( _normalize_region, block_budget, @@ -241,6 +242,75 @@ def test_the_cap_bounds_the_block(tmp_path, monkeypatch): # --------------------------------------------------------------------------- +@pytest.mark.parametrize( + ("shards", "expected_grid"), + [ + (None, ((1,), (1, 4, 4, 2), (3, 4, 4, 4, 2))), + ((1, 8, 8), ((1,), (5, 6), (3, 8, 6))), + ], + ids=["chunked", "sharded"], +) +def test_image_write_grid_matches_the_roi_writer(monkeypatch, shards, expected_grid): + """A world-space ROI uses the writer's rounded, clipped on-disk bounds.""" + image = create_empty_ome_zarr( + zarr.storage.MemoryStore(), + shape=(3, 15, 22), + pixelsize=0.5, + axes_names=("c", "y", "x"), + levels=1, + chunks=(1, 4, 4), + shards=shards, + ngff_version="0.5", + ).get_image() + roi = Roi.from_values( + name=None, + slices={"x": (2.6, 10.0), "y": (1.6, 5.2), "c": (1, 1)}, + ) + data = np.arange(1, 188, dtype=image.dtype).reshape(1, 11, 17) + stored = [] + original_store = da.store + + def record_store(sources, *args, **kwargs): + stored.append((sources, kwargs["regions"], kwargs["lock"])) + return original_store(sources, *args, **kwargs) + + monkeypatch.setattr(da, "store", record_store) + with dask.config.set({"array.chunk-size": "1 B"}): + grid = image.write_grid(roi) + assert grid == expected_grid + patch = da.from_array(data, chunks=grid) + image.set_roi(roi, patch, axes_order=image.axes) + + assert len(stored) == 1 + written, regions, lock = stored[0] + selection = (slice(1, 2), slice(3, 14), slice(5, 22)) + assert regions == [selection] + assert not lock + assert written.chunks == grid + assert written.name == patch.name + expected = np.zeros(image.shape, dtype=image.dtype) + expected[selection] = data + np.testing.assert_array_equal(image.get_as_numpy(axes_order=image.axes), expected) + + +def test_image_write_grid_for_full_image_uses_the_block_budget(monkeypatch): + image = create_empty_ome_zarr( + zarr.storage.MemoryStore(), + shape=(2, 9, 21), + pixelsize=1.0, + axes_names=("c", "y", "x"), + levels=1, + chunks=(1, 4, 4), + ).get_image() + + with dask.config.set({"array.chunk-size": "1 MiB"}): + _with_cap(monkeypatch, None) + assert image.write_grid() == ((2,), (9,), (21,)) + _with_cap(monkeypatch, 1) + assert image.write_grid() == ((1, 1), (4, 4, 1), (4, 4, 4, 4, 4, 1)) + assert image.write_grid(image.roi()) == image.write_grid() + + def test_small_units_are_glued_into_one_block(): """Dask's heuristic must still engage: several units per block, not one.