Skip to content
Merged
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
114 changes: 111 additions & 3 deletions src/polystore/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,11 @@ def create(
) -> Codec | None:
"""Create the codec for this compressor variant."""

@abstractmethod
def create_v3(self, compression_level: int, shuffle: bool = True):
"""This compressor as a Zarr v3 codec: the specification's own codec where it has
one, so any v3 reader can open the array."""


class NoZarrCompressorFactory(ZarrCompressorFactory):
"""Factory for disabling Zarr compression."""
Expand All @@ -56,6 +61,9 @@ def create(
) -> None:
return None

def create_v3(self, compression_level: int, shuffle: bool = True) -> None:
return None


class BloscZarrCompressorFactory(ZarrCompressorFactory):
"""Factory for Blosc-backed Zarr compression."""
Expand All @@ -73,6 +81,12 @@ def create(
shuffle=shuffle,
)

def create_v3(self, compression_level: int, shuffle: bool = True):
from zarr.codecs import BloscCodec

return BloscCodec(
cname="lz4", clevel=compression_level, shuffle="shuffle" if shuffle else "noshuffle")


class ZlibZarrCompressorFactory(ZarrCompressorFactory):
"""Factory for zlib-backed Zarr compression."""
Expand All @@ -86,6 +100,12 @@ def create(
) -> Zlib:
return Zlib(level=compression_level)

def create_v3(self, compression_level: int, shuffle: bool = True):
"""Deflate in the v3 specification is the gzip codec; zlib framing has none."""
from zarr.codecs import GzipCodec

return GzipCodec(level=compression_level)


class Lz4ZarrCompressorFactory(ZarrCompressorFactory):
"""Factory for LZ4-backed Zarr compression."""
Expand All @@ -99,6 +119,13 @@ def create(
) -> LZ4:
return LZ4(acceleration=compression_level)

def create_v3(self, compression_level: int, shuffle: bool = True):
"""Standalone LZ4 has no v3 specification codec: numcodecs' wrapper, which only
numcodecs-aware readers open. Blosc carries LZ4 inside the specification."""
from numcodecs.zarr3 import LZ4 as LZ4V3

return LZ4V3(acceleration=compression_level)


class ZstdZarrCompressorFactory(ZarrCompressorFactory):
"""Factory for Zstandard-backed Zarr compression."""
Expand All @@ -112,12 +139,93 @@ def create(
) -> Zstd:
return Zstd(level=compression_level)

def create_v3(self, compression_level: int, shuffle: bool = True):
from zarr.codecs import ZstdCodec

return ZstdCodec(level=compression_level)


class ZarrLayout(ABC):
"""How one stored array is laid out: its chunks, its shards, the NGFF format that can
describe that, and the form its compressor takes in that format."""

@abstractmethod
def chunks(self, shape: tuple[int, ...]) -> tuple[int, ...]:
"""The chunk shape for an array of ``shape`` (leading axes, then ``y, x``)."""

def shards(self, shape: tuple[int, ...], chunks: tuple[int, ...]) -> tuple[int, ...] | None:
"""The shard shape for an array of ``shape`` stored in ``chunks``, or ``None`` when
every chunk is its own object."""
return None

@abstractmethod
def output_format(self):
"""The OME-NGFF format declaration that can describe this layout."""

@abstractmethod
def codec_arguments(self, factory: ZarrCompressorFactory, level: int) -> dict[str, object]:
"""The ``create_array`` compression arguments in this layout's Zarr format."""


class ZarrV2Layout(ZarrLayout):
"""Zarr v2 / OME-NGFF 0.4: one object per chunk, numcodecs compressors."""

def output_format(self):
from ome_zarr.format import FormatV04

return FormatV04()

def codec_arguments(self, factory: ZarrCompressorFactory, level: int) -> dict[str, object]:
return {"compressor": factory.create(level, shuffle=True)}


class WholeWellLayout(ZarrV2Layout):
"""One chunk for the whole well: optimal for batch I/O."""

def chunks(self, shape: tuple[int, ...]) -> tuple[int, ...]:
return shape


class PlaneLayout(ZarrV2Layout):
"""Each original plane is compressed separately, whatever the leading axes."""

def chunks(self, shape: tuple[int, ...]) -> tuple[int, ...]:
return (1,) * (len(shape) - 2) + shape[-2:]


class ShardedPlaneLayout(PlaneLayout):
"""Each plane its own chunk, all of them inside one shard object per array: plane-level
random access with one file per well. Sharding exists only in Zarr v3, so this layout
writes OME-NGFF 0.5 with Zarr v3 codecs."""

def shards(self, shape: tuple[int, ...], chunks: tuple[int, ...]) -> tuple[int, ...]:
"""One shard holding the whole array: the array's extent rounded up to whole chunks,
as a shard must be a multiple of its chunk shape."""
return tuple(-(-extent // chunk) * chunk for extent, chunk in zip(shape, chunks, strict=True))

def output_format(self):
from ome_zarr.format import FormatV05

return FormatV05()

def codec_arguments(self, factory: ZarrCompressorFactory, level: int) -> dict[str, object]:
codec = factory.create_v3(level, shuffle=True)
return {"compressors": (codec,) if codec is not None else None}


class ZarrChunkStrategy(Enum):
"""Chunking strategies supported by :class:`ZarrStorageBackend`."""
"""Chunking strategies supported by :class:`ZarrStorageBackend`; each member owns its
:class:`ZarrLayout`."""

WELL = ("well", WholeWellLayout())
FILE = ("file", PlaneLayout())
SHARDED = ("sharded", ShardedPlaneLayout())

WELL = "well"
FILE = "file"
def __new__(cls, value: str, layout: ZarrLayout):
member = object.__new__(cls)
member._value_ = value
member.layout = layout
return member


class TiffCompression(Enum):
Expand Down
49 changes: 18 additions & 31 deletions src/polystore/zarr.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,12 +119,23 @@ class ZarrStorageBackend(StorageBackend, PicklableBackend):
_backend_type = Backend.ZARR.value
supports_arbitrary_files = False # Class attribute: zarr only handles array data

@cached_property
@property
def output_format(self):
"""Resolve NGFF format only when a Zarr write needs its declaration."""
from ome_zarr.format import FormatV04

return FormatV04()
"""The NGFF format the configured layout writes; resolved only when a write needs it."""
return self.config.chunk_strategy.layout.output_format()

def _array_layout(
self, shape: tuple[int, ...], chunks: tuple[int, ...] | None = None,
) -> dict[str, object]:
"""The configured layout's chunk, shard and compression arguments for ``shape``;
``chunks`` overrides the layout's own chunk shape."""
layout = self.config.chunk_strategy.layout
chunks = layout.chunks(shape) if chunks is None else chunks
return {
"chunks": chunks,
"shards": layout.shards(shape, chunks),
**layout.codec_arguments(self.config.compressor_factory, self.config.compression_level),
}

@staticmethod
def _is_disk_passthrough_path(path: str | Path) -> bool:
Expand Down Expand Up @@ -242,28 +253,6 @@ def set_connection_params(self, params: dict[str, Any] | None) -> None:
def _as_cpu_array(data: Any) -> Any:
return storage_numpy_array(data)

def _calculate_chunks(self, data_shape: tuple[int, ...]) -> tuple[int, ...]:
"""
Calculate chunk shape based on configured strategy.

Args:
data_shape: Array shape with arbitrary leading semantic axes and
trailing ``y, x`` pixel axes.

Returns:
Chunk shape tuple
"""
from .config import ZarrChunkStrategy

match self.config.chunk_strategy:
case ZarrChunkStrategy.WELL:
# Single chunk for entire well (current behavior, optimal for batch I/O)
return data_shape
case ZarrChunkStrategy.FILE:
# Each original plane is compressed separately regardless of
# the number of declared leading axes.
return (1,) * (len(data_shape) - 2) + data_shape[-2:]

def _split_store_and_key(self, path: str | Path) -> tuple[LocalStore, str]:
"""
Split path into zarr store and key.
Expand Down Expand Up @@ -333,10 +322,9 @@ def save(self, data: Any, output_path: str | Path, **kwargs):
name=key,
shape=cpu_data.shape,
dtype=cpu_data.dtype,
chunks=chunks,
compressor=kwargs.get("compressor", self.compressor),
chunk_key_encoding=self.output_format.chunk_key_encoding,
overwrite=False, # 🔒 Must be False by doctrine
**self._array_layout(cpu_data.shape, tuple(chunks)),
)
array[:] = cpu_data
except Exception as e:
Expand Down Expand Up @@ -540,9 +528,8 @@ def save_batch(self, data_list: list[Any], output_paths: list[str | Path], **kwa
"0",
shape=reshaped_data.shape,
dtype=reshaped_data.dtype,
chunks=self._calculate_chunks(reshaped_data.shape),
compressor=self.compressor,
chunk_key_encoding=self.output_format.chunk_key_encoding,
**self._array_layout(reshaped_data.shape),
)
field_array[:] = reshaped_data
transformations = self.output_format.generate_coordinate_transformations(
Expand Down
47 changes: 46 additions & 1 deletion tests/test_zarr_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -811,7 +811,52 @@ def test_every_compressor_has_one_registered_factory(self, compressor):
def test_chunk_strategy_controls_backend_chunks(self, strategy, expected):
backend = ZarrStorageBackend(ZarrConfig(chunk_strategy=strategy))

assert backend._calculate_chunks((2, 3, 4, 10, 20)) == expected
layout = backend._array_layout((2, 3, 4, 10, 20))
assert layout["chunks"] == expected
assert layout["shards"] is None

def test_sharded_strategy_stores_planes_as_chunks_of_one_shard(self):
backend = ZarrStorageBackend(ZarrConfig(chunk_strategy=ZarrChunkStrategy.SHARDED))

layout = backend._array_layout((2, 3, 4, 10, 20))
assert layout["chunks"] == (1, 1, 1, 10, 20)
assert layout["shards"] == (2, 3, 4, 10, 20)
assert backend.output_format.zarr_format == 3

@pytest.mark.parametrize("compressor", tuple(ZarrCompressor))
def test_a_sharded_array_is_one_object_and_round_trips_with_every_codec(self, tmp_path, compressor):
"""Chunks that do not divide the array still fit one shard, rounded up to whole chunks."""
backend = ZarrStorageBackend(
ZarrConfig(compressor=compressor, chunk_strategy=ZarrChunkStrategy.SHARDED))
pixels = np.arange(5 * 7 * 9, dtype=np.uint16).reshape(5, 7, 9)
path = tmp_path / "image.tif"
backend.save(pixels, path, chunks=(2, 7, 9))
array = zarr.open_array(str(path), mode="r")

assert array.metadata.zarr_format == 3
assert array.chunks == (2, 7, 9)
assert array.shards == (6, 7, 9)
stored = [file for file in path.rglob("*") if file.is_file() and file.name != "zarr.json"]
assert len(stored) == 1
# Every compressor the v3 specification covers is written as its specified codec.
inner = [codec.to_dict()["name"] for codec in array.metadata.codecs[0].codecs]
specified = {ZarrCompressor.BLOSC: "blosc", ZarrCompressor.ZLIB: "gzip",
ZarrCompressor.ZSTD: "zstd"}
if compressor in specified:
assert specified[compressor] in inner
np.testing.assert_array_equal(backend.load(path), pixels)

def test_a_sharded_well_batch_round_trips_through_its_filename_mapping(self, tmp_path):
backend = ZarrStorageBackend(ZarrConfig(chunk_strategy=ZarrChunkStrategy.SHARDED))
paths = save_hcs_image_axis_batch(
backend, tmp_path / "plate.zarr", axis_name="channel", values=(1, 2, 3), row="A", col="01")

loaded = backend.load_batch(paths)
assert [int(image[0, 0]) for image in loaded] == [0, 1, 2]
field = zarr.open_array(str(tmp_path / "plate.zarr" / "A" / "01" / "0" / "0"), mode="r")
assert field.metadata.zarr_format == 3
assert field.shards == field.shape
assert field.chunks == (1,) * (field.ndim - 2) + field.shape[-2:]

@pytest.mark.parametrize("compressor", tuple(ZarrCompressor))
@pytest.mark.parametrize("dtype", [np.uint8, np.uint16, np.int32, np.float16, np.float64])
Expand Down
Loading