Skip to content
Open
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
3 changes: 3 additions & 0 deletions changes/4238.bugfix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
The codec *cast_value* expects a contiguous numpy array to work properly.
It used to break when place before or after a *transpose* codec, which produces non-contiguous arrays.
This fix resolves the issue.
2 changes: 1 addition & 1 deletion src/zarr/codecs/cast_value.py
Original file line number Diff line number Diff line change
Expand Up @@ -317,7 +317,7 @@ def _do_cast(
to_tgt = int if np.issubdtype(target_dtype, np.integer) else float
scalar_map_entries = {to_src(k): to_tgt(v) for k, v in scalar_map.items()}
return cast_array_rs( # type: ignore[no-any-return]
arr,
np.ascontiguousarray(arr),
target_dtype=target_dtype,
rounding_mode=self.rounding,
out_of_range_mode=self.out_of_range,
Expand Down
45 changes: 45 additions & 0 deletions tests/test_codecs/test_cast_value.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,13 @@

import numpy as np
import pytest
from numpy.testing import assert_array_equal

import zarr
from tests.conftest import Expect, ExpectFail
from zarr.codecs import BytesCodec, TransposeCodec
from zarr.codecs.cast_value import CastValue
from zarr.storage import MemoryStore

try:
import cast_value_rs # noqa: F401
Expand Down Expand Up @@ -477,3 +480,45 @@ def test_parse_scalar_map(case: Expect[Any, Any]) -> None:
from zarr.codecs.cast_value import parse_scalar_map

assert parse_scalar_map(case.input) == case.output


@requires_cast_value_rs
def test_enforce_contiguous_arrays() -> None:
"""
Transpose codec produces non-contiguous arrays.
Ensure cast_value makes them contiguous before processing.
"""
data = np.arange(20, dtype=np.float32).reshape(5, 2, 2)

def make_array(filters: list[Any]) -> Any:
return zarr.create_array(
store=MemoryStore(),
shape=data.shape,
dtype=data.dtype,
chunks=data.shape,
filters=filters,
serializer=BytesCodec(endian="little"),
compressors=None,
zarr_format=3,
)

# Cast before transpose
array = make_array(
[
CastValue(data_type="uint16"),
TransposeCodec(order=(1, 2, 0)),
]
)
array[:] = data
assert_array_equal(array[:], data)

# Cast after transpose
array = make_array(
[
TransposeCodec(order=(1, 2, 0)),
CastValue(data_type="uint16"),
]
)

array[:] = data
assert_array_equal(array[:], data)
Loading