|
| 1 | +"""Codec interface definitions (v1). |
| 2 | +
|
| 3 | +This module defines the abstract interfaces for zarr codecs. |
| 4 | +External codec implementations should subclass ``ArrayArrayCodec``, |
| 5 | +``ArrayBytesCodec``, or ``BytesBytesCodec`` from this module. |
| 6 | +
|
| 7 | +The ``Buffer`` and ``NDBuffer`` types here are protocols — they define |
| 8 | +the structural interface that zarr's concrete buffer types implement. |
| 9 | +Codec authors should type against these protocols, not zarr's concrete |
| 10 | +buffer classes. |
| 11 | +""" |
| 12 | + |
| 13 | +from __future__ import annotations |
| 14 | + |
| 15 | +from abc import ABC, abstractmethod |
| 16 | +from dataclasses import dataclass |
| 17 | +from typing import TYPE_CHECKING, ClassVar, Protocol, Self, runtime_checkable |
| 18 | + |
| 19 | +if TYPE_CHECKING: |
| 20 | + import numpy as np |
| 21 | + import numpy.typing as npt |
| 22 | + |
| 23 | + from zarr_interfaces.data_type.v1 import JSON, TBaseDType, TBaseScalar, ZDType |
| 24 | + |
| 25 | + |
| 26 | +# --------------------------------------------------------------------------- |
| 27 | +# Buffer protocols |
| 28 | +# --------------------------------------------------------------------------- |
| 29 | + |
| 30 | + |
| 31 | +class Buffer(Protocol): |
| 32 | + """Protocol for a flat contiguous memory block (bytes-like).""" |
| 33 | + |
| 34 | + def __len__(self) -> int: ... |
| 35 | + def __getitem__(self, key: slice) -> Buffer: ... |
| 36 | + |
| 37 | + |
| 38 | +class NDBuffer(Protocol): |
| 39 | + """Protocol for an N-dimensional array buffer.""" |
| 40 | + |
| 41 | + @property |
| 42 | + def dtype(self) -> np.dtype[np.generic]: ... |
| 43 | + |
| 44 | + @property |
| 45 | + def shape(self) -> tuple[int, ...]: ... |
| 46 | + |
| 47 | + def as_ndarray_like(self) -> npt.NDArray[np.generic]: ... |
| 48 | + |
| 49 | + @classmethod |
| 50 | + def from_ndarray_like(cls, data: npt.NDArray[np.generic]) -> NDBuffer: ... |
| 51 | + |
| 52 | + def transpose(self, axes: tuple[int, ...]) -> NDBuffer: ... |
| 53 | + |
| 54 | + def __getitem__(self, key: object) -> NDBuffer: ... |
| 55 | + |
| 56 | + def __setitem__(self, key: object, value: object) -> None: ... |
| 57 | + |
| 58 | + |
| 59 | +# --------------------------------------------------------------------------- |
| 60 | +# ArraySpec protocol |
| 61 | +# --------------------------------------------------------------------------- |
| 62 | + |
| 63 | + |
| 64 | +class ArraySpec(Protocol): |
| 65 | + """Protocol for the specification of a chunk's metadata.""" |
| 66 | + |
| 67 | + @property |
| 68 | + def shape(self) -> tuple[int, ...]: ... |
| 69 | + |
| 70 | + @property |
| 71 | + def dtype(self) -> ZDType[TBaseDType, TBaseScalar]: ... |
| 72 | + |
| 73 | + @property |
| 74 | + def fill_value(self) -> object: ... |
| 75 | + |
| 76 | + @property |
| 77 | + def ndim(self) -> int: ... |
| 78 | + |
| 79 | + |
| 80 | +# --------------------------------------------------------------------------- |
| 81 | +# Codec input/output type aliases |
| 82 | +# --------------------------------------------------------------------------- |
| 83 | + |
| 84 | +type CodecInput = NDBuffer | Buffer |
| 85 | +type CodecOutput = NDBuffer | Buffer |
| 86 | + |
| 87 | + |
| 88 | +# --------------------------------------------------------------------------- |
| 89 | +# Sync codec protocol |
| 90 | +# --------------------------------------------------------------------------- |
| 91 | + |
| 92 | + |
| 93 | +@runtime_checkable |
| 94 | +class SupportsSyncCodec[CI: CodecInput, CO: CodecOutput](Protocol): |
| 95 | + """Protocol for codecs that support synchronous encode/decode. |
| 96 | +
|
| 97 | + The type parameters mirror ``BaseCodec``: ``CI`` is the decoded type |
| 98 | + and ``CO`` is the encoded type. |
| 99 | + """ |
| 100 | + |
| 101 | + def _decode_sync(self, chunk_data: CO, chunk_spec: ArraySpec) -> CI: ... |
| 102 | + |
| 103 | + def _encode_sync(self, chunk_data: CI, chunk_spec: ArraySpec) -> CO | None: ... |
| 104 | + |
| 105 | + |
| 106 | +# --------------------------------------------------------------------------- |
| 107 | +# Codec ABCs |
| 108 | +# --------------------------------------------------------------------------- |
| 109 | + |
| 110 | + |
| 111 | +@dataclass(frozen=True) |
| 112 | +class BaseCodec[CI: CodecInput, CO: CodecOutput](ABC): |
| 113 | + """Generic base class for codecs. |
| 114 | +
|
| 115 | + Subclass ``ArrayArrayCodec``, ``ArrayBytesCodec``, or |
| 116 | + ``BytesBytesCodec`` instead of this class directly. |
| 117 | + """ |
| 118 | + |
| 119 | + is_fixed_size: ClassVar[bool] |
| 120 | + |
| 121 | + @classmethod |
| 122 | + def from_dict(cls, data: dict[str, JSON]) -> Self: |
| 123 | + """Create an instance from a JSON dictionary.""" |
| 124 | + return cls(**data) # type: ignore[arg-type] |
| 125 | + |
| 126 | + def to_dict(self) -> dict[str, JSON]: |
| 127 | + """Serialize this codec to a JSON dictionary.""" |
| 128 | + raise NotImplementedError |
| 129 | + |
| 130 | + @abstractmethod |
| 131 | + def compute_encoded_size(self, input_byte_length: int, chunk_spec: ArraySpec) -> int: |
| 132 | + """Return the encoded byte length for a given input byte length.""" |
| 133 | + ... |
| 134 | + |
| 135 | + def resolve_metadata(self, chunk_spec: ArraySpec) -> ArraySpec: |
| 136 | + """Return the chunk spec after encoding by this codec. |
| 137 | +
|
| 138 | + Override this for codecs that change shape, dtype, or fill value. |
| 139 | + """ |
| 140 | + return chunk_spec |
| 141 | + |
| 142 | + def evolve_from_array_spec(self, array_spec: ArraySpec) -> Self: |
| 143 | + """Fill in codec parameters that can be inferred from array metadata.""" |
| 144 | + return self |
| 145 | + |
| 146 | + def validate( |
| 147 | + self, |
| 148 | + *, |
| 149 | + shape: tuple[int, ...], |
| 150 | + dtype: ZDType[TBaseDType, TBaseScalar], |
| 151 | + chunk_grid: object, |
| 152 | + ) -> None: |
| 153 | + """Validate that this codec is compatible with the array metadata. |
| 154 | +
|
| 155 | + The default implementation does nothing. Override to add checks. |
| 156 | + """ |
| 157 | + |
| 158 | + async def _decode_single(self, chunk_data: CO, chunk_spec: ArraySpec) -> CI: |
| 159 | + """Decode a single chunk. Override this or ``_decode_sync``.""" |
| 160 | + raise NotImplementedError |
| 161 | + |
| 162 | + async def decode( |
| 163 | + self, |
| 164 | + chunks_and_specs: Iterable[tuple[CO | None, ArraySpec]], |
| 165 | + ) -> Iterable[CI | None]: |
| 166 | + """Decode a batch of chunks.""" |
| 167 | + results: list[CI | None] = [] |
| 168 | + for chunk_data, chunk_spec in chunks_and_specs: |
| 169 | + if chunk_data is not None: |
| 170 | + results.append(await self._decode_single(chunk_data, chunk_spec)) |
| 171 | + else: |
| 172 | + results.append(None) |
| 173 | + return results |
| 174 | + |
| 175 | + async def _encode_single(self, chunk_data: CI, chunk_spec: ArraySpec) -> CO | None: |
| 176 | + """Encode a single chunk. Override this or ``_encode_sync``.""" |
| 177 | + raise NotImplementedError |
| 178 | + |
| 179 | + async def encode( |
| 180 | + self, |
| 181 | + chunks_and_specs: Iterable[tuple[CI | None, ArraySpec]], |
| 182 | + ) -> Iterable[CO | None]: |
| 183 | + """Encode a batch of chunks.""" |
| 184 | + results: list[CO | None] = [] |
| 185 | + for chunk_data, chunk_spec in chunks_and_specs: |
| 186 | + if chunk_data is not None: |
| 187 | + results.append(await self._encode_single(chunk_data, chunk_spec)) |
| 188 | + else: |
| 189 | + results.append(None) |
| 190 | + return results |
| 191 | + |
| 192 | + |
| 193 | +class ArrayArrayCodec(BaseCodec[NDBuffer, NDBuffer]): |
| 194 | + """Base class for array-to-array codecs (e.g. transpose, scale_offset).""" |
| 195 | + |
| 196 | + |
| 197 | +class ArrayBytesCodec(BaseCodec[NDBuffer, Buffer]): |
| 198 | + """Base class for array-to-bytes codecs (e.g. bytes, sharding).""" |
| 199 | + |
| 200 | + |
| 201 | +class BytesBytesCodec(BaseCodec[Buffer, Buffer]): |
| 202 | + """Base class for bytes-to-bytes codecs (e.g. gzip, zstd).""" |
0 commit comments