Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down
18 changes: 18 additions & 0 deletions docs/getting_started/2_images.md
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
32 changes: 31 additions & 1 deletion src/ngio/images/_abstract_image.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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."""
Expand Down
70 changes: 70 additions & 0 deletions tests/unit/common/test_dask_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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.

Expand Down