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
1 change: 1 addition & 0 deletions changes/4342.bugfix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
`DateTime64` and `TimeDelta64` normalize `μs` to `us` and preserve generic-unit scale factors when converting native NumPy dtypes and serializing V2/V3 metadata. V2 writes an explicit suffix such as `[2generic]` to avoid the scale loss in NumPy's `dtype.str` and `dtype.name`. Generic temporal arrays also preserve dtype parameters during CPU buffer allocation and correctly convert byte order; generic datetime fill values can be read back, including in structured fields. The default NaT fill value now carries the scale factor, so missing chunks of a scaled timedelta array such as `m8[2us]` read back as NaT on NumPy < 2.2 instead of an arbitrary count.
42 changes: 38 additions & 4 deletions src/zarr/core/buffer/cpu.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
TYPE_CHECKING,
Any,
Literal,
cast,
)

import numpy as np
Expand Down Expand Up @@ -156,22 +157,55 @@ def create(
order: Literal["C", "F"] = "C",
fill_value: Any | None = None,
) -> Self:
parsed_dtype = np.dtype(dtype)
zero_fill = fill_value is None or (isinstance(fill_value, int) and fill_value == 0)
if parsed_dtype.kind in "mM":
# NumPy allocation can drop a generic time unit's scale factor and byte order
# (`np.zeros(1, ">M8[2generic]").dtype` is `<M8`). A view restores both, and
# must precede assignment so values are encoded in the requested byte order.
data = np.zeros(shape=tuple(shape), dtype=parsed_dtype, order=order).view(parsed_dtype)
if not zero_fill:
data[...] = fill_value
# np.zeros is much faster than np.full, and therefore using it when possible is better.
if fill_value is None or (isinstance(fill_value, int) and fill_value == 0):
return cls(np.zeros(shape=tuple(shape), dtype=dtype, order=order))
elif zero_fill:
data = np.zeros(shape=tuple(shape), dtype=dtype, order=order)
else:
return cls(np.full(shape=tuple(shape), fill_value=fill_value, dtype=dtype, order=order))
data = np.full(shape=tuple(shape), fill_value=fill_value, dtype=dtype, order=order)
return cls(data)

@classmethod
def empty(
cls, shape: tuple[int, ...], dtype: npt.DTypeLike, order: Literal["C", "F"] = "C"
) -> Self:
return cls(np.empty(shape=shape, dtype=dtype, order=order))
data = np.empty(shape=shape, dtype=dtype, order=order)
if data.dtype.kind in "mM":
# See `create`: a view restores what allocation drops from generic time dtypes.
data = data.view(dtype=dtype)
return cls(data)

@classmethod
def from_numpy_array(cls, array_like: npt.ArrayLike) -> Self:
return cls.from_ndarray_like(np.asanyarray(array_like))

def astype(self, dtype: npt.DTypeLike, order: Literal["K", "A", "C", "F"] = "K") -> Self:
target = np.dtype(dtype)
if (
self.dtype.kind in "mM"
and isinstance(target, np.dtypes.DateTime64DType | np.dtypes.TimeDelta64DType)
and target.kind == self.dtype.kind
and np.datetime_data(self.dtype)[0] == "generic"
and np.datetime_data(self.dtype)
== np.datetime_data(
cast("np.dtypes.DateTime64DType | np.dtypes.TimeDelta64DType", target)
)
):
# NumPy's astype between generic time dtypes ignores the target and keeps the
# source byte order. Convert the underlying counts for an endian-only cast.
counts = self.as_numpy_array().view(self.dtype.byteorder + "i8")
converted = counts.astype(target.byteorder + "i8", order=order)
return self.__class__(converted.view(target))
return super().astype(dtype, order=order)

def as_numpy_array(self) -> npt.NDArray[Any]:
"""Returns the buffer as a NumPy array (host memory).

Expand Down
20 changes: 19 additions & 1 deletion src/zarr/core/dtype/npy/structured.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,9 @@ def _unsupported_field_feature(dtype: np.dtype[np.void]) -> str | None:
- field titles, e.g. `np.dtype([(("title", "name"), "i4")])`
- subarray fields, e.g. `np.dtype([("name", "i4", (2,))])`

These are implementation restrictions. In particular, Zarr V2 supports subarray
field descriptors; this implementation does not preserve them.

Returns
-------
str | None
Expand Down Expand Up @@ -563,7 +566,22 @@ def default_scalar(self) -> np.void:
cast to this structured data type.
"""

return self._cast_scalar_unchecked(0)
values: list[object] = []
for _, field in self.fields:
dtype = field.to_native_dtype()
if isinstance(field, Structured):
value = field.default_scalar()
elif (
isinstance(dtype, np.dtypes.DateTime64DType)
and np.datetime_data(cast("np.dtypes.DateTime64DType", dtype))[0] == "generic"
):
# NumPy rejects casting integer zero to generic datetime, but a
# zero count is representable by viewing the integer storage.
value = np.zeros(1, dtype=dtype.byteorder + "i8").view(dtype)[0]
else:
value = np.array([0], dtype=dtype)[0]
values.append(value)
return self._cast_scalar_unchecked(tuple(values))

def from_json_scalar(self, data: JSON, *, zarr_format: ZarrFormat) -> np.void:
"""
Expand Down
32 changes: 22 additions & 10 deletions src/zarr/core/dtype/npy/time.py
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,11 @@ def __post_init__(self) -> None:
raise ValueError(f"scale_factor must be < 2147483648, got {self.scale_factor}.")
if self.unit not in get_args(DateTimeUnit):
raise ValueError(f"unit must be one of {get_args(DateTimeUnit)}, got {self.unit!r}.")
if self.unit == "μs":
# NumPy spells the microsecond unit "us" and resolves "μs" to it, so an
# instance built with "μs" would not round-trip through to_native_dtype().
# Store the NumPy spelling; "μs" stays accepted as input and in stored metadata.
object.__setattr__(self, "unit", "us")

@classmethod
def from_native_dtype(cls, dtype: TBaseDType) -> Self:
Expand All @@ -256,7 +261,7 @@ def from_native_dtype(cls, dtype: TBaseDType) -> Self:
"""

if cls._check_native_dtype(dtype):
unit, scale_factor = np.datetime_data(dtype.name)
unit, scale_factor = np.datetime_data(dtype)
unit = cast("DateTimeUnit", unit)
return cls(
unit=unit,
Expand Down Expand Up @@ -492,7 +497,10 @@ def to_json(self, zarr_format: ZarrFormat) -> TimeDelta64JSON_V2 | TimeDelta64JS
If the zarr_format is not 2 or 3.
"""
if zarr_format == 2:
name = self.to_native_dtype().str
name: str = self.to_native_dtype().str
if self.unit == "generic" and self.scale_factor != 1:
# NumPy omits generic scale from dtype.str; preserve it explicitly.
name += f"[{self.scale_factor}generic]"
return {"name": name, "object_codec_id": None}
elif zarr_format == 3:
return {
Expand Down Expand Up @@ -548,8 +556,7 @@ def cast_scalar(self, data: object) -> np.timedelta64:
"""
if self._check_scalar(data):
if isinstance(data, np.timedelta64) and np.isnat(data):
# numpy 2.x stub: 'generic' is a runtime-valid unit but not in the Literal overload.
return np.timedelta64("NaT", self.unit) # type: ignore[arg-type]
return self._cast_scalar_unchecked("NaT")
return self._cast_scalar_unchecked(data)
msg = (
f"Cannot convert object {data!r} with type {type(data)} to a scalar compatible with the "
Expand All @@ -564,8 +571,9 @@ def default_scalar(self) -> np.timedelta64:
This method provides a default value for the timedelta64 scalar, which is
a 'Not-a-Time' (NaT) value.
"""
# numpy 2.x stub: 'generic' is a runtime-valid unit but not in the Literal overload.
return np.timedelta64("NaT", self.unit) # type: ignore[arg-type]
# Carry the scale factor: NumPy < 2.2 turns a timedelta NaT into a count when
# casting it between scales, e.g. NaT[us] into a [2us] array.
return self._cast_scalar_unchecked("NaT")

def from_json_scalar(self, data: JSON, *, zarr_format: ZarrFormat) -> np.timedelta64:
"""
Expand Down Expand Up @@ -777,7 +785,10 @@ def to_json(self, zarr_format: ZarrFormat) -> DateTime64JSON_V2 | DateTime64JSON
If the zarr_format is not 2 or 3.
"""
if zarr_format == 2:
name = self.to_native_dtype().str
name: str = self.to_native_dtype().str
if self.unit == "generic" and self.scale_factor != 1:
# NumPy omits generic scale from dtype.str; preserve it explicitly.
name += f"[{self.scale_factor}generic]"
return {"name": name, "object_codec_id": None}
elif zarr_format == 3:
return {
Expand Down Expand Up @@ -818,6 +829,9 @@ def _cast_scalar_unchecked(self, data: DateTimeLike) -> np.datetime64:
numpy.datetime64
The input cast to a NumPy datetime scalar.
"""
if isinstance(data, int):
# The scalar constructor rejects integer counts with a generic unit.
return datetime_from_int(data, unit=self.unit, scale_factor=self.scale_factor)
# numpy 2.x stub: datetime64(scalar, formatted_unit_str) is runtime-valid
# but no overload matches the dynamic f-string unit argument.
return self.to_native_dtype().type(data, f"{self.scale_factor}{self.unit}") # type: ignore[call-overload, no-any-return]
Expand Down Expand Up @@ -858,9 +872,7 @@ def default_scalar(self) -> np.datetime64:
numpy.datetime64
The default scalar value, which is a 'Not-a-Time' (NaT) value
"""

# numpy 2.x stub: 'generic' is a runtime-valid unit but not in the Literal overload.
return np.datetime64("NaT", self.unit) # type: ignore[arg-type]
return self._cast_scalar_unchecked("NaT")

def from_json_scalar(self, data: JSON, *, zarr_format: ZarrFormat) -> np.datetime64:
"""
Expand Down
15 changes: 2 additions & 13 deletions src/zarr/testing/strategies.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,23 +95,12 @@ def _leaf_zdtypes(cls: type[ZDType[TBaseDType, TBaseScalar]]) -> SearchStrategy[
if "length" in params:
kwargs["length"] = st.integers(min_value=1, max_value=16)
if "unit" in params:
# NumPy spells the microsecond unit "us", so the "μs" alias never round-trips as-is.
kwargs["unit"] = st.sampled_from([u for u in DATETIME_UNIT if u != "μs"])
# The constructor normalizes the microsecond alias; all units accept a scale.
kwargs["unit"] = st.sampled_from(DATETIME_UNIT)
kwargs["scale_factor"] = st.integers(min_value=1, max_value=2**31 - 1)
return st.builds(cls, **kwargs).map(_normalize_generic_scale_factor)
return st.builds(cls, **kwargs)


def _normalize_generic_scale_factor(zdtype: Any) -> Any:
"""
NumPy retains generic scale factors internally, but its dtype string omits them.
Use `scale_factor=1` so the generated dtype survives Zarr V2 string serialization.
"""
if zdtype.unit == "generic":
return dataclasses.replace(zdtype, scale_factor=1)
return zdtype


def _struct_zdtypes(
children: SearchStrategy[ZDType[Any, Any]],
) -> SearchStrategy[ZDType[Any, Any]]:
Expand Down
29 changes: 29 additions & 0 deletions tests/test_buffer.py
Original file line number Diff line number Diff line change
Expand Up @@ -296,3 +296,32 @@ def test_all_equal_distinguishes_negative_zero(dtype: str) -> None:
assert not cpu.NDBuffer.from_numpy_array(negative).all_equal(0.0)
assert cpu.NDBuffer.from_numpy_array(negative).all_equal(-0.0)
assert not cpu.NDBuffer.from_numpy_array(positive).all_equal(-0.0)


@pytest.mark.parametrize("kind", ["M8", "m8"])
@pytest.mark.parametrize("byteorder", ["<", ">"])
@pytest.mark.parametrize("scale_factor", [2, 2**31 - 1])
@pytest.mark.parametrize("fill_value", [None, 0, "NaT"])
@pytest.mark.parametrize("order", ["C", "F"])
@pytest.mark.filterwarnings(
"ignore:The 'generic' unit for NumPy timedelta is deprecated:DeprecationWarning"
)
def test_cpu_generic_time_allocation(
kind: str,
byteorder: str,
scale_factor: int,
fill_value: int | str | None,
order: Literal["C", "F"],
) -> None:
"""Both allocation paths retain generic scale even when NumPy drops it."""
dtype = np.dtype(f"{byteorder}{kind}[{scale_factor}generic]")
empty = cpu.NDBuffer.empty((2, 3), dtype=dtype, order=order)
filled = cpu.NDBuffer.create(shape=(2, 3), dtype=dtype, order=order, fill_value=fill_value)
for buffer in (empty, filled):
assert buffer.dtype == dtype
array = buffer.as_numpy_array()
assert array.flags.c_contiguous if order == "C" else array.flags.f_contiguous
expected = -(2**63) if fill_value == "NaT" else 0
np.testing.assert_array_equal(
filled.as_numpy_array().view(dtype.byteorder + "i8"), np.full((2, 3), expected)
)
Loading
Loading