Skip to content

[v3] Makes data contiguous in v2 codec #2515

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Dec 2, 2024
Merged
Show file tree
Hide file tree
Changes from 3 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
12 changes: 11 additions & 1 deletion src/zarr/codecs/_v2.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from typing import TYPE_CHECKING

import numcodecs
import numpy as np
from numcodecs.compat import ensure_ndarray_like

from zarr.abc.codec import ArrayBytesCodec
Expand All @@ -14,7 +15,15 @@
import numcodecs.abc

from zarr.core.array_spec import ArraySpec
from zarr.core.buffer import Buffer, NDBuffer
from zarr.core.buffer import Buffer, NDArrayLike, NDBuffer


def ensure_contiguous(arr: NDArrayLike) -> NDArrayLike:
flags = getattr(arr, "flags", None)
if flags is not None and flags.c_contiguous:
return arr
else:
return np.ascontiguousarray(arr)


@dataclass(frozen=True)
Expand Down Expand Up @@ -83,6 +92,7 @@ async def _encode_single(
else:
cdata = chunk

cdata = ensure_contiguous(ensure_ndarray_like(cdata))
return chunk_spec.prototype.buffer.from_bytes(cdata)

def compute_encoded_size(self, _input_byte_length: int, _chunk_spec: ArraySpec) -> int:
Expand Down
24 changes: 24 additions & 0 deletions tests/test_v2.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,3 +132,27 @@ def test_v2_filters_codecs(filters: Any) -> None:
arr[:] = array_fixture
result = arr[:]
np.testing.assert_array_equal(result, array_fixture)


def test_v2_non_contiguous() -> None:
arr = zarr.Array.create(
MemoryStore({}),
shape=(10, 8),
chunks=(3, 3),
fill_value=np.nan,
dtype="float64",
zarr_format=2,
exists_ok=True,
)
a = np.ones(arr.shape)
arr[slice(6, 9, None), slice(3, 6, None)] = a[
slice(6, 9, None), slice(3, 6, None)
] # The slice on the RHS is important

a = np.ones((3, 3), order="F")
assert a.flags.f_contiguous
arr[slice(6, 9, None), slice(3, 6, None)] = a

a = np.ones((3, 3), order="C")
assert a.flags.c_contiguous
arr[slice(6, 9, None), slice(3, 6, None)] = a