Skip to content
Draft
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
1 change: 1 addition & 0 deletions packages/zarr-metadata/changes/498.bugfix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Array models that describe the same array are now equal in three more cases. A v2 fill value is compared as the value NumPy stores for the dtype: for `<f4`, `0.1` equals `0.10000000149011612`; for `|S3`, `"YQ=="` equals `"YQAA"`, which only adds padding; for `<U2`, `"abc"` equals `"ab"`; and two base64 spellings of the same bytes are equal. A v3 `cast_value` codec with a `rounding` of `nearest-even` equals one without a `rounding`. A `numpy.datetime64` or `numpy.timedelta64` with a unit of `μs` equals one with a unit of `us`. `canonical_of` and `canonical_fill_value` write the one spelling in each case. Which documents are accepted has not changed.
16 changes: 16 additions & 0 deletions packages/zarr-metadata/docs/models.md
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,15 @@ These are each declaration, and the fill value read against its data type.
`endian`, or with none. The codec is compared for the chunk it
receives: after a `cast_value` to `float32`, the two `endian` values
are two codecs.
- A `cast_value` codec with a `rounding` of `nearest-even` is the same
codec without one, because an absent `rounding`
[means `nearest-even`](https://github.com/zarr-developers/zarr-extensions/blob/4da7b37a84f76e660902f6d3de3eaef0e0febae6/codecs/cast_value/README.md?plain=1#L73).
- A `numpy.datetime64` or `numpy.timedelta64` with a unit of `μs` is the
same data type with a unit of `us`. The spec of
[`numpy.datetime64`](https://github.com/zarr-developers/zarr-extensions/blob/4da7b37a84f76e660902f6d3de3eaef0e0febae6/data-types/numpy.datetime64/README.md?plain=1#L87-L88)
and the spec of
[`numpy.timedelta64`](https://github.com/zarr-developers/zarr-extensions/blob/4da7b37a84f76e660902f6d3de3eaef0e0febae6/data-types/numpy.timedelta64/README.md?plain=1#L90-L91)
both say the two are equivalent.

A v2 document's
[dtype](https://zarr-specs.readthedocs.io/en/latest/v2/v2.0.html#data-type-encoding),
Expand All @@ -244,6 +253,13 @@ codecs and fill value are compared the same way:
data. In v3, the
[blosc spec](https://zarr-specs.readthedocs.io/en/v3.1.0/v3/codecs/blosc/index.html#configuration-parameters)
says `noshuffle` ignores `typesize`.
- A v2 fill value is compared as the value NumPy stores for the dtype,
because the v2 spec gives the dtype as a NumPy typestr. So for `<f4`,
`0.1` equals `0.10000000149011612`. For `|S3`, `"YQ=="` equals
`"YQAA"`, which only adds padding. For `<U2`, `"abc"` equals `"ab"`,
because an item of a NumPy array holds no more than its size. This
differs from v3,
where `fixed_length_utf32` refuses a string that is too long.
- A v2 node with no `.zattrs` equals one with an empty `.zattrs`. The
[v2 spec](https://zarr-specs.readthedocs.io/en/latest/v2/v2.0.html#attributes)
says the key "does not have to be present, and if it is absent the
Expand Down
73 changes: 68 additions & 5 deletions packages/zarr-metadata/src/zarr_metadata/_numpy.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,23 @@
"""NumPy encodings that both Zarr formats use in fill values: numpy time ticks and `NaT`, and base64 byte strings.

A v3 data type and a v2 dtype of the same NumPy family write their fill
values the same way, so each encoding is defined once here.
"""What NumPy and base64 fix for both Zarr formats: numpy time units, ticks and `NaT`, base64 byte strings, and the padding of a byte string.

Each Zarr format has its own spec, and each definition states its own
rules and cites its own spec. This module holds what both formats take
from NumPy or from base64: which strings are base64 and which bytes they
hold, that NumPy reads `μs` and `us` as one unit, that NumPy stores
not-a-time as the smallest int64, and that NumPy pads a byte string with
null bytes. Which values a format accepts is in the format's own
definition, as is the reason that the format follows NumPy.
"""

import base64
import re
from typing import Annotated, Final, Literal, NewType
from collections.abc import Iterator, Mapping
from typing import Annotated, Final, Literal, NewType, TypeVar, cast

from annotated_types import Interval

from zarr_metadata._json import ValidationProblem, shown

NUMPY_TIME_UNITS: Final = (
"Y",
"M",
Expand Down Expand Up @@ -51,6 +60,22 @@
"""


_TimeConfiguration = TypeVar("_TimeConfiguration", bound=Mapping[str, object])


def numpy_time_canonical(configuration: _TimeConfiguration) -> _TimeConfiguration:
"""Return the configuration of a numpy time type with the unit `μs` written as `us`, as NumPy writes it.

NumPy reads both as microseconds: `np.dtype("<M8[μs]") ==
np.dtype("<M8[us]")`, and the `str` of both is `<M8[us]`
(https://numpy.org/doc/stable/reference/arrays.datetime.html#datetime-units).
Each format's definition says why it follows NumPy here.
"""
if configuration.get("unit") != "μs":
return configuration
return cast("_TimeConfiguration", {**configuration, "unit": "us"})


def numpy_time_fill_value_canonical(
configuration: object, nested: object, value: NumpyTimeTicks | Literal["NaT"]
) -> NumpyTimeTicks | Literal["NaT"]:
Expand All @@ -76,6 +101,39 @@ def base64_bytes(value: str) -> Base64Bytes:
return Base64Bytes(value)


def base64_problems(value: str) -> Iterator[ValidationProblem]:
"""Check that a fill value written as a string is standard-alphabet base64."""
try:
base64_bytes(value)
except ValueError:
yield ValidationProblem(
(), f"expected standard-alphabet base64, got {shown(value)}", "invalid_value"
)


def base64_decoded(value: str) -> bytes | None:
"""The bytes that `value` encodes in standard-alphabet base64; None when it is not such base64."""
try:
return base64.b64decode(base64_bytes(value))
except ValueError:
return None


def base64_spelling(data: bytes) -> str:
"""`data` in the single spelling of a base64 fill value, standard-alphabet base64: `"QR=="` decodes to the byte that `"QQ=="` spells."""
return base64.b64encode(data).decode("ascii")


def null_padded_bytes_spelling(value: str) -> str:
"""Return the bytes that the base64 `value` holds, without their trailing null bytes, in base64 again: one spelling for each value of NumPy's `S`.

NumPy pads a value of `S` with null bytes to the type's size, and
reads it back without them, so `"QQ=="` and `"QQAA"` are the same
value. `"QR=="` decodes to the same byte as `"QQ=="`.
"""
return base64_spelling(base64.b64decode(value).rstrip(b"\x00"))


__all__ = [
"NOT_A_TIME_TICKS",
"NUMPY_TIME_MAX_SCALE_FACTOR",
Expand All @@ -84,5 +142,10 @@ def base64_bytes(value: str) -> Base64Bytes:
"NumpyTimeScaleFactor",
"NumpyTimeTicks",
"base64_bytes",
"base64_decoded",
"base64_problems",
"base64_spelling",
"null_padded_bytes_spelling",
"numpy_time_canonical",
"numpy_time_fill_value_canonical",
]
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
import dataclasses
import functools
from collections.abc import Callable, Iterable, Iterator, Mapping
from dataclasses import dataclass
from dataclasses import dataclass, field
from types import MappingProxyType
from typing import (
TYPE_CHECKING,
Expand Down Expand Up @@ -175,6 +175,79 @@ def __hash__(self) -> int:
return hash(json_text(self.value))


def _scalar_defaults(
what: str, defaults: Mapping[str, JSONValue]
) -> tuple[tuple[str, JSONValue], ...]:
"""`defaults` as pairs, in the order given, after checking that each default is a JSON scalar. Raises `TypeError` for any other value."""
for key, value in defaults.items():
if not (value is None or type(value) in (str, int, float, bool)):
msg = f"{what} takes a string, a number, a boolean or null for {key!r}, got {value!r}"
raise TypeError(msg)
return tuple(defaults.items())


@dataclass(frozen=True, slots=True)
class _Defaults:
"""What an absent member of a configuration means, by key. It is a value and not a closure, as `ConstantFillValue` is. Two of the same class compare equal, and hash equal, when their defaults are written the same way and in the same order, so `0` and `False` are two defaults. Two equal values therefore give the same result for a configuration, down to the order of its members."""

defaults: tuple[tuple[str, JSONValue], ...] = field(compare=False)
texts: tuple[tuple[str, str], ...] = field(init=False)
"""Each key with its default as JSON text, in the order of `defaults`. It is derived from `defaults` when the value is built, so it always agrees with them, and comparing, hashing or calling the value does not encode a default again."""

def __post_init__(self) -> None:
"""Write each default as JSON text."""
texts = tuple((key, json_text(value)) for key, value in self.defaults)
object.__setattr__(self, "texts", texts)


class _WithoutDefaults(_Defaults):
__slots__ = ()

def __call__(self, configuration: T) -> T:
"""Return `configuration` without each member that is written with its default."""
written = cast("Mapping[str, JSONValue]", configuration)
redundant = [
key for key, text in self.texts if key in written and json_text(written[key]) == text
]
if len(redundant) == 0:
return configuration
return cast("T", {key: value for key, value in written.items() if key not in redundant})


class _WithDefaults(_Defaults):
__slots__ = ()

def __call__(self, configuration: T) -> T:
"""Return `configuration` with each absent member written with its default."""
return cast("T", {**dict(self.defaults), **cast("Mapping[str, JSONValue]", configuration)})


def without_defaults(**defaults: JSONValue) -> Callable[[T], T]:
"""Return a `canonical` that removes each member written with the value its absence means.

Each keyword names a member of the configuration and gives the value
that an absent member means. A configuration that writes that value
and one that leaves the member out describe the same thing, so the
canonical form leaves it out: `without_defaults(checksum=False)` reads
`{"level": 3, "checksum": False}` as `{"level": 3}`. A value is
compared as JSON, so `0` is not `False`. A default is a string, a
number, a boolean or null.
"""
return _WithoutDefaults(_scalar_defaults("without_defaults", defaults))


def with_defaults(**defaults: JSONValue) -> Callable[[T], T]:
"""Return a `canonical` that writes each absent member with the value its absence means.

This is `without_defaults` the other way round, for a format whose
writers write every member: `with_defaults(level=1)` reads `{}` as
`{"level": 1}`. The members that have a default come first, in the
order the defaults are given, and then every other member as written.
A default is a string, a number, a boolean or null.
"""
return _WithDefaults(_scalar_defaults("with_defaults", defaults))


_DECLARATION_KINDS: Final[dict[TypeAliasType, type[Definition[Any]]]] = {}
"""Maps each declaration alias to the kind that a member annotated with it is read as. Each kind adds its aliases when its class is built."""

Expand Down Expand Up @@ -2238,6 +2311,8 @@ def _replaced(value: JSONValue, path: Loc, new: JSONValue) -> JSONValue:
"spelled_canonically",
"typed_document",
"unchanged",
"with_defaults",
"with_problems",
"without_defaults",
"written_json",
]
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ class ZarrV2ScalarConfiguration(TypedDict, closed=True):
# fixed_width

ZarrV2Base64FillValue = str | None
"""A fill value that the v2 spec encodes as base64, for a fixed-length byte string, void, or a structured type (https://github.com/zarr-developers/zarr-specs/blob/fc7dd9c9beb5a50b87f9b08b00bf50fc0048482f/docs/v2/v2.0.rst#L191-L193), or null."""
"""A fill value that the v2 spec encodes as base64, for a fixed-length byte string, void, or a structured type (https://github.com/zarr-developers/zarr-specs/blob/fc7dd9c9beb5a50b87f9b08b00bf50fc0048482f/docs/v2/v2.0.rst#L192-L194), or null."""


# object
Expand Down
53 changes: 15 additions & 38 deletions packages/zarr-metadata/src/zarr_metadata/v2/codec/compression.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,16 @@
Each parameter that numcodecs gives a default is optional. numcodecs
writes the full object with `get_config()`. The canonical form of each
codec fills in those defaults, so a configuration that leaves out a
parameter and one that writes its default are one codec.
parameter and one that writes its default are one codec. The defaults
of each codec but `blosc` are the keywords of its `with_defaults`, as
numcodecs writes them. `blosc` has a canonical form of its own.
"""

from __future__ import annotations

from typing import Final

from zarr_metadata.definition._definition import with_defaults
from zarr_metadata.v2._definition import ZarrV2CodecDefinition
from zarr_metadata.v2._types.codec import (
ZarrV2BloscCName,
Expand All @@ -24,26 +27,6 @@
)


def _zlib_canonical(configuration: ZarrV2ZlibParameters) -> ZarrV2ZlibParameters:
"""Fill in the default `level`, 1, as numcodecs writes it."""
return {"level": 1, **configuration}


def _gzip_canonical(configuration: ZarrV2GzipParameters) -> ZarrV2GzipParameters:
"""Fill in the default `level`, 1, as numcodecs writes it."""
return {"level": 1, **configuration}


def _bz2_canonical(configuration: ZarrV2Bz2Parameters) -> ZarrV2Bz2Parameters:
"""Fill in the default `level`, 1, as numcodecs writes it."""
return {"level": 1, **configuration}


def _lzma_canonical(configuration: ZarrV2LzmaParameters) -> ZarrV2LzmaParameters:
"""Fill in the defaults, as numcodecs writes them: `format` 1 (`lzma.FORMAT_XZ`), `check` -1 (the format's own check), and null `preset` and `filters`."""
return {"format": 1, "check": -1, "preset": None, "filters": None, **configuration}


def _blosc_canonical(configuration: ZarrV2BloscParameters) -> ZarrV2BloscParameters:
"""Fill in the defaults, as numcodecs writes them, and write a `shuffle` of `true` or `false` as 1 or 0, which numcodecs reads it as.

Expand All @@ -66,42 +49,36 @@ def _blosc_canonical(configuration: ZarrV2BloscParameters) -> ZarrV2BloscParamet
return {**filled, "typesize": typesize}


def _zstd_canonical(configuration: ZarrV2ZstdParameters) -> ZarrV2ZstdParameters:
"""Fill in the defaults, `level` 0 and `checksum` false, as numcodecs writes them."""
return {"level": 0, "checksum": False, **configuration}


def _lz4_canonical(configuration: ZarrV2Lz4Parameters) -> ZarrV2Lz4Parameters:
"""Fill in the default `acceleration`, 1, as numcodecs writes it."""
return {"acceleration": 1, **configuration}


ZLIB_CODEC_V2: Final = ZarrV2CodecDefinition(
name="zlib", configuration=ZarrV2ZlibParameters, canonical=_zlib_canonical
name="zlib", configuration=ZarrV2ZlibParameters, canonical=with_defaults(level=1)
)
"""`numcodecs.Zlib`."""
GZIP_CODEC_V2: Final = ZarrV2CodecDefinition(
name="gzip", configuration=ZarrV2GzipParameters, canonical=_gzip_canonical
name="gzip", configuration=ZarrV2GzipParameters, canonical=with_defaults(level=1)
)
"""`numcodecs.GZip`."""
BZ2_CODEC_V2: Final = ZarrV2CodecDefinition(
name="bz2", configuration=ZarrV2Bz2Parameters, canonical=_bz2_canonical
name="bz2", configuration=ZarrV2Bz2Parameters, canonical=with_defaults(level=1)
)
"""`numcodecs.BZ2`."""
LZMA_CODEC_V2: Final = ZarrV2CodecDefinition(
name="lzma", configuration=ZarrV2LzmaParameters, canonical=_lzma_canonical
name="lzma",
configuration=ZarrV2LzmaParameters,
canonical=with_defaults(format=1, check=-1, preset=None, filters=None),
)
"""`numcodecs.LZMA`."""
"""`numcodecs.LZMA`. Its defaults are `format` 1 (`lzma.FORMAT_XZ`), `check` -1 (the format's own check), and null `preset` and `filters`."""
BLOSC_CODEC_V2: Final = ZarrV2CodecDefinition(
name="blosc", configuration=ZarrV2BloscParameters, canonical=_blosc_canonical
)
"""`numcodecs.Blosc`."""
ZSTD_CODEC_V2: Final = ZarrV2CodecDefinition(
name="zstd", configuration=ZarrV2ZstdParameters, canonical=_zstd_canonical
name="zstd",
configuration=ZarrV2ZstdParameters,
canonical=with_defaults(level=0, checksum=False),
)
"""`numcodecs.Zstd`."""
LZ4_CODEC_V2: Final = ZarrV2CodecDefinition(
name="lz4", configuration=ZarrV2Lz4Parameters, canonical=_lz4_canonical
name="lz4", configuration=ZarrV2Lz4Parameters, canonical=with_defaults(acceleration=1)
)
"""`numcodecs.LZ4`."""

Expand Down
8 changes: 2 additions & 6 deletions packages/zarr-metadata/src/zarr_metadata/v2/codec/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from typing import Final

from zarr_metadata._common import EmptyConfiguration
from zarr_metadata.definition._definition import with_defaults
from zarr_metadata.v2._definition import ZarrV2CodecDefinition
from zarr_metadata.v2._types.codec import (
ZarrV2AsTypeParameters,
Expand All @@ -24,11 +25,6 @@
from zarr_metadata.v2.codec._dtype import canonical_typestr, dtype_parameter


def _shuffle_canonical(configuration: ZarrV2ShuffleParameters) -> ZarrV2ShuffleParameters:
"""Fill in the default `elementsize`, 4, as numcodecs writes it."""
return {"elementsize": 4, **configuration}


def _typestrs(dtype: str, astype: str | None) -> tuple[str, str]:
"""`dtype` and `astype` as NumPy spells them, with an `astype` that is omitted or null filled in with the `dtype`, as numcodecs writes them."""
canonical = canonical_typestr(dtype)
Expand Down Expand Up @@ -70,7 +66,7 @@ def _astype_canonical(configuration: ZarrV2AsTypeParameters) -> ZarrV2AsTypePara


SHUFFLE_CODEC_V2: Final = ZarrV2CodecDefinition(
name="shuffle", configuration=ZarrV2ShuffleParameters, canonical=_shuffle_canonical
name="shuffle", configuration=ZarrV2ShuffleParameters, canonical=with_defaults(elementsize=4)
)
"""`numcodecs.Shuffle`."""
DELTA_CODEC_V2: Final = ZarrV2CodecDefinition(
Expand Down
Loading