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
1 change: 1 addition & 0 deletions changes/351.bugfix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Zarr format 2 arrays whose data type is a single-byte boolean or integer, or raw bytes, written with a `<` or `>` byte order (e.g. `<i1`, `>b1`, `<V4`, as written by netCDF-C, Zarr.jl and jzarr) can be read again, including as fields of structured data types. The byte order of these data types is not relevant, and metadata is written back with the canonical `|` spelling. Also, `datetime64` and `timedelta64` data types no longer accept an object codec in Zarr format 2, and a structured data type with an unrecognized field data type is rejected with `DataTypeValidationError`.
17 changes: 17 additions & 0 deletions changes/4382.bugfix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
Made the `fill_value` check on the write path substantially cheaper.
`NDBuffer.all_equal` runs on every chunk write when `write_empty_chunks` is
false, which is the default, and it dominated the cost of writing chunks.

Two changes. The bit-pattern comparison used for a zero `fill_value`, which
keeps `-0.0` distinct from `0.0`, now views the buffer as an unsigned integer
of the same width instead of as a void dtype; NumPy has vectorised integer
comparison loops but no void one, so the void form fell back to a generic
elementwise path. Separately, the scan now walks slices of the leading axis,
doubling in length, and returns on the first slice that differs, so a buffer
that is not uniformly `fill_value` no longer has to be read in full. The
leading axis is used rather than a flattened view because a chunk is normally
a strided view into a larger array and cannot be flattened without a copy. A
buffer that really is uniform is still covered in the same number of element
comparisons.

Results are unchanged, including for `-0.0`, NaN, and non-contiguous buffers.
1 change: 1 addition & 0 deletions changes/4386.feature.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Added the `NCZarrChar` data type for the netCDF `NC_CHAR` type as NCZarr writes it in Zarr format 2 (`>S1`). Arrays with this data type keep the `>S1` spelling when their metadata is written back, so netCDF readers still see characters rather than strings. Zarr format 2 fixed-length bytes written with a `<` or `>` byte order (e.g. `<S3`, as written by Zarr.jl) can be read again.
1 change: 1 addition & 0 deletions docs/user-guide/data_types.md
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,7 @@ here, it's possible to create it yourself: see [Adding new data types](#adding-n
- [Fixed-length null-terminated bytes][zarr.dtype.NullTerminatedBytes]
- [Fixed-length raw bytes][zarr.dtype.RawBytes]
- [Variable-length bytes][zarr.dtype.VariableLengthBytes]
- [NCZarr character][zarr.dtype.NCZarrChar] (Zarr V2 only)

#### Temporal

Expand Down
6 changes: 2 additions & 4 deletions examples/custom_dtype/custom_dtype.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
import pytest

import zarr
from zarr.dtype import ZDType, check_dtype_spec_v2, data_type_registry
from zarr.dtype import ZDType, check_dtype_spec_no_object_codec_v2, data_type_registry
from zarr.errors import DataTypeValidationError
from zarr.types import JSON, DTypeConfig_V2, DTypeJSON, ZarrFormat

Expand Down Expand Up @@ -79,9 +79,7 @@ def _check_json_v2(cls, data: DTypeJSON) -> TypeGuard[DTypeConfig_V2[Literal["|b

See the Zarr docs for more information about the JSON encoding for data types.
"""
return (
check_dtype_spec_v2(data) and data["name"] == "int2" and data["object_codec_id"] is None
)
return check_dtype_spec_no_object_codec_v2(data) and data["name"] == "int2"

@classmethod
def _check_json_v3(cls, data: DTypeJSON) -> TypeGuard[Literal["int2"]]:
Expand Down
2 changes: 2 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -435,6 +435,8 @@ addopts = [
"-ra",
"--doctest-modules",
"--ignore=tests/test_regression/scripts",
# interoperability reproducers that need other implementations; run by hand, not by pytest
"--ignore=tests/interop",
"--ignore=src/zarr/_cli",
]
filterwarnings = [
Expand Down
79 changes: 61 additions & 18 deletions src/zarr/core/buffer/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,15 @@
__all__: list[str] = []


# Integer dtypes used to compare raw bytes when `fill_value` is zero, keyed by
# itemsize. A view to a dtype of the same width is always permitted by numpy.
_BITWISE_DTYPE = {1: "u1", 2: "u2", 4: "u4", 8: "u8"}

# Elements in the first slice examined by `NDBuffer.all_equal`. Large enough to
# amortise one numpy call, small enough that a mismatch in it is nearly free.
_ALL_EQUAL_BLOCK = 1 << 14


@runtime_checkable
class ArrayLike(Protocol):
"""Protocol for the array-like type that underlie Buffer"""
Expand Down Expand Up @@ -531,32 +540,66 @@ def __len__(self) -> int:
def __repr__(self) -> str:
return f"<NDBuffer shape={self.shape} dtype={self.dtype} {self._data!r}>"

def all_equal(self, other: Any, equal_nan: bool = True) -> bool:
"""Compare to `other` using np.array_equal."""
if other is None:
# Handle None fill_value for Zarr V2
return False
@staticmethod
def _compare_all(data: NDArrayLike, other: Any, equal_nan: bool) -> bool:
"""Whether every element of `data` equals `other`, inspecting all of it."""
# Handle positive and negative zero by comparing bit patterns:
if (
np.asarray(other).dtype.kind == "f"
and other == 0.0
and self._data.dtype.kind not in ("U", "S", "T", "O", "V")
and data.dtype.kind not in ("U", "S", "T", "O", "V")
):
_data, other = np.broadcast_arrays(self._data, np.asarray(other, self._data.dtype))
void_dtype = f"V{_data.dtype.itemsize}"
return np.array_equal(_data.view(void_dtype), other.view(void_dtype))
_data, other = np.broadcast_arrays(data, np.asarray(other, data.dtype))
# Read the bytes as unsigned integers rather than as a void dtype.
# Both compare bit patterns, so both keep -0.0 distinct from 0.0,
# but numpy has vectorised integer comparison loops and no void
# one: the void form falls back to a generic elementwise path that
# is more than an order of magnitude slower. Widths with no integer
# of the same size (longdouble, complex128) keep the void form.
bitwise_dtype = _BITWISE_DTYPE.get(_data.dtype.itemsize, f"V{_data.dtype.itemsize}")
return bool(np.array_equal(_data.view(bitwise_dtype), other.view(bitwise_dtype)))
# use array_equal to obtain equal_nan=True functionality
# Since fill-value is a scalar, isn't there a faster path than allocating a new array for fill value
# every single time we have to write data?
_data, other = np.broadcast_arrays(self._data, other)
return np.array_equal(
_data,
other,
equal_nan=equal_nan
if self._data.dtype.kind not in ("U", "S", "T", "O", "V")
else False,
_data, other = np.broadcast_arrays(data, other)
return bool(
np.array_equal(
_data,
other,
equal_nan=equal_nan if data.dtype.kind not in ("U", "S", "T", "O", "V") else False,
)
)

def all_equal(self, other: Any, equal_nan: bool = True) -> bool:
"""Compare to `other` using np.array_equal."""
if other is None:
# Handle None fill_value for Zarr V2
return False
data = self._data
# A buffer that is not uniformly `other` still has to be read in full
# before a whole-buffer comparison can report the first mismatch, and
# on the write path that is the common case. Walking it in slices of
# the leading axis returns as soon as one slice differs. Slices double
# in length, so a buffer that really is uniform is covered in O(log n)
# comparisons and costs the same as the single scan this replaces.
#
# The leading axis is used rather than a flattened view because a chunk
# is usually a strided view into a larger array, which cannot be
# flattened without copying it. Slicing axis 0 is a view whatever the
# layout.
if data.ndim > 0 and np.ndim(other) == 0 and data.size > _ALL_EQUAL_BLOCK:
leading = data.shape[0]
per_index = data.size // leading if leading else 0
if leading > 1 and per_index:
step = max(1, _ALL_EQUAL_BLOCK // per_index)
start = 0
while start < leading:
stop = min(start + step, leading)
if not self._compare_all(data[start:stop], other, equal_nan):
return False
start = stop
step *= 2
return True
return self._compare_all(data, other, equal_nan)

def fill(self, value: Any) -> None:
self._data.fill(value)

Expand Down
6 changes: 4 additions & 2 deletions src/zarr/core/dtype/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

from zarr.core.dtype.npy.bool import Bool
from zarr.core.dtype.npy.bytes import (
NCZarrChar,
NullTerminatedBytes,
NullterminatedBytesJSON_V2,
NullTerminatedBytesJSON_V3,
Expand Down Expand Up @@ -71,6 +72,7 @@
"Int16",
"Int32",
"Int64",
"NCZarrChar",
"NullTerminatedBytes",
"NullTerminatedBytesJSON_V3",
"NullterminatedBytesJSON_V2",
Expand Down Expand Up @@ -118,8 +120,8 @@
TimeDType = DateTime64 | TimeDelta64
TIME_DTYPE: Final = DateTime64, TimeDelta64

BytesDType = RawBytes | NullTerminatedBytes | VariableLengthBytes
BYTES_DTYPE: Final = RawBytes, NullTerminatedBytes, VariableLengthBytes
BytesDType = RawBytes | NullTerminatedBytes | NCZarrChar | VariableLengthBytes
BYTES_DTYPE: Final = RawBytes, NullTerminatedBytes, NCZarrChar, VariableLengthBytes

AnyDType = (
Bool
Expand Down
13 changes: 13 additions & 0 deletions src/zarr/core/dtype/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,19 @@ def check_dtype_spec_v2(data: object) -> TypeGuard[DTypeSpec_V2]:
return isinstance(data["object_codec_id"], str | None)


def check_dtype_spec_no_object_codec_v2(
data: object,
) -> TypeGuard[DTypeConfig_V2[DTypeName_V2, None]]:
"""
Type guard for narrowing a python object to a Zarr V2 data type without an object codec.

Only the data types stored with the NumPy "O" data type have an object codec, so every other
data type should check its Zarr V2 JSON with this function rather than
[`check_dtype_spec_v2`][zarr.dtype.check_dtype_spec_v2].
"""
return check_dtype_spec_v2(data) and data["object_codec_id"] is None


# By comparison, The JSON representation of a dtype in zarr v3 is much simpler.
# It's either a string, or a structured dict
DTypeSpec_V3 = str | NamedConfig[str, Mapping[str, object]]
Expand Down
8 changes: 2 additions & 6 deletions src/zarr/core/dtype/npy/bool.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
DTypeConfig_V2,
DTypeJSON,
HasItemSize,
check_dtype_spec_v2,
check_dtype_spec_no_object_codec_v2,
)
from zarr.core.dtype.wrapper import TBaseDType, ZDType
from zarr.errors import DataTypeValidationError
Expand Down Expand Up @@ -103,11 +103,7 @@ def _check_json_v2(
``TypeGuard[DTypeConfig_V2[Literal["|b1"], None]]``
True if the input is a valid JSON representation, False otherwise.
"""
return (
check_dtype_spec_v2(data)
and data["name"] == cls._zarr_v2_name
and data["object_codec_id"] is None
)
return check_dtype_spec_no_object_codec_v2(data) and data["name"] == cls._zarr_v2_name

@classmethod
def _check_json_v3(cls, data: DTypeJSON) -> TypeGuard[Literal["bool"]]:
Expand Down
108 changes: 104 additions & 4 deletions src/zarr/core/dtype/npy/bytes.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
HasItemSize,
HasLength,
HasObjectCodec,
check_dtype_spec_no_object_codec_v2,
check_dtype_spec_v2,
v3_unstable_dtype_warning,
)
Expand Down Expand Up @@ -267,10 +268,9 @@ def _check_json_v2(cls, data: DTypeJSON) -> TypeGuard[NullterminatedBytesJSON_V2
"""

return (
check_dtype_spec_v2(data)
check_dtype_spec_no_object_codec_v2(data)
and isinstance(data["name"], str)
and re.match(r"^\|S\d+$", data["name"]) is not None
and data["object_codec_id"] is None
)

@classmethod
Expand Down Expand Up @@ -541,6 +541,107 @@ def item_size(self) -> int:
return self.length


@dataclass(frozen=True, kw_only=True)
class NCZarrChar(NullTerminatedBytes):
"""
The netCDF `NC_CHAR` data type as NCZarr writes it in Zarr V2: a one-byte string named `">S1"`.

In the Zarr V2 specification the byte order of an `"S"` data type is not relevant, so `">S1"`
and `"|S1"` name the same data type, and this data type holds the same values as
`NullTerminatedBytes(length=1)`. NCZarr gives the byte order a meaning of its own: it reads
`">S1"` as `NC_CHAR` and `"|S1"` as `NC_STRING`. This data type keeps the `">S1"` spelling
when array metadata is written back, so netCDF readers see the same type.

It is never inferred from a NumPy data type: arrays with a NumPy `"S1"` data type use
`NullTerminatedBytes`. It has no Zarr V3 representation.

Attributes
----------
length : int
The length of the bytes, which is always 1.

References
----------
See the [NCZarr documentation](https://github.com/Unidata/netcdf-c/blob/main/docs/nczarr.md)
for the NCZarr type mapping.
"""

_zarr_v3_name: ClassVar[Literal["nczarr.char"]] = "nczarr.char" # type: ignore[assignment]
_zarr_v2_name: ClassVar[Literal[">S1"]] = ">S1"
length: int = 1

def __post_init__(self) -> None:
if self.length != 1:
raise ValueError(f"length must be 1, got {self.length}.")

@classmethod
def _check_native_dtype(cls, dtype: TBaseDType) -> TypeGuard[np.dtypes.BytesDType[int]]:
"""
Return False: a NumPy data type does not say whether it holds netCDF characters.
"""
return False

@classmethod
def _check_json_v2(cls, data: DTypeJSON) -> TypeGuard[NullterminatedBytesJSON_V2]:
"""
Check that the input is the NCZarr `NC_CHAR` data type, `{"name": ">S1", "object_codec_id": None}`.
"""
return check_dtype_spec_no_object_codec_v2(data) and data["name"] == cls._zarr_v2_name

@classmethod
def _check_json_v3(cls, data: DTypeJSON) -> TypeGuard[NullTerminatedBytesJSON_V3]:
"""
Return False: this data type has no Zarr V3 representation.
"""
return False

@classmethod
def _from_json_v2(cls, data: DTypeJSON) -> Self:
if cls._check_json_v2(data):
return cls()
msg = f"Invalid JSON representation of {cls.__name__}. Got {data!r}, expected the string {cls._zarr_v2_name!r}"
raise DataTypeValidationError(msg)

@classmethod
def _from_json_v3(cls, data: DTypeJSON) -> Self:
msg = f"{cls.__name__} has no Zarr V3 representation. Got {data!r}"
raise DataTypeValidationError(msg)

@overload
def to_json(self, zarr_format: Literal[2]) -> NullterminatedBytesJSON_V2: ...

@overload
def to_json(self, zarr_format: Literal[3]) -> NullTerminatedBytesJSON_V3: ...

def to_json(
self, zarr_format: ZarrFormat
) -> DTypeConfig_V2[str, None] | NullTerminatedBytesJSON_V3:
"""
Serialize this data type to Zarr V2 JSON.

Parameters
----------
zarr_format : ZarrFormat
The Zarr format version. Only 2 is supported.

Returns
-------
NullterminatedBytesJSON_V2
`{"name": ">S1", "object_codec_id": None}`.

Raises
------
ValueError
If `zarr_format` is 3: this data type has no Zarr V3 representation.
"""
if zarr_format == 2:
return {"name": self._zarr_v2_name, "object_codec_id": None}
raise ValueError(
f"{type(self).__name__} has no Zarr V3 representation. Use NullTerminatedBytes(length=1) "
"to store one-byte strings in a Zarr V3 array."
)


@dataclass(frozen=True, kw_only=True)
class RawBytes(ZDType[np.dtypes.VoidDType[int], np.void], HasLength, HasItemSize):
"""
Expand Down Expand Up @@ -669,10 +770,9 @@ def _check_json_v2(cls, data: DTypeJSON) -> TypeGuard[RawBytesJSON_V2]:

"""
return (
check_dtype_spec_v2(data)
check_dtype_spec_no_object_codec_v2(data)
and isinstance(data["name"], str)
and re.match(r"^\|V\d+$", data["name"]) is not None
and data["object_codec_id"] is None
)

@classmethod
Expand Down
8 changes: 2 additions & 6 deletions src/zarr/core/dtype/npy/complex.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
DTypeJSON,
HasEndianness,
HasItemSize,
check_dtype_spec_v2,
check_dtype_spec_no_object_codec_v2,
)
from zarr.core.dtype.npy.common import (
ComplexLike,
Expand Down Expand Up @@ -106,11 +106,7 @@ def _check_json_v2(cls, data: DTypeJSON) -> TypeGuard[DTypeConfig_V2[str, None]]
bool
True if the input is a valid JSON representation, False otherwise.
"""
return (
check_dtype_spec_v2(data)
and data["name"] in cls._zarr_v2_names
and data["object_codec_id"] is None
)
return check_dtype_spec_no_object_codec_v2(data) and data["name"] in cls._zarr_v2_names

@classmethod
def _check_json_v3(cls, data: DTypeJSON) -> TypeGuard[str]:
Expand Down
Loading
Loading