Skip to content

Commit

Permalink
Error when attempt to set with an array of incompatible shape.
Browse files Browse the repository at this point in the history
Closes #2469
  • Loading branch information
dcherian committed Nov 22, 2024
1 parent 3dd04ce commit f50daa1
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 4 deletions.
18 changes: 14 additions & 4 deletions src/zarr/core/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -2842,14 +2842,24 @@ def set_coordinate_selection(
try:
from numcodecs.compat import ensure_ndarray_like

value = ensure_ndarray_like(value) # TODO replace with agnostic
value_array = ensure_ndarray_like(value) # TODO replace with agnostic
except TypeError:
# Handle types like `list` or `tuple`
value = np.array(value) # TODO replace with agnostic
value_array = np.array(value) # TODO replace with agnostic
if hasattr(value, "shape") and len(value.shape) > 1:
value = np.array(value).reshape(-1)
value_array = np.array(value).reshape(-1)

sync(self._async_array._set_selection(indexer, value, fields=fields, prototype=prototype))
if indexer.sel_shape != value_array.shape:
raise ValueError(
f"Attempting to set a selection of {indexer.sel_shape[0]} "
f"elements with an array of {value_array.shape[0]} elements."
)

sync(
self._async_array._set_selection(
indexer, value_array, fields=fields, prototype=prototype
)
)

@_deprecate_positional_args
def get_block_selection(
Expand Down
18 changes: 18 additions & 0 deletions tests/test_indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -1936,3 +1936,21 @@ def test_zero_sized_chunks(store: StorePath, shape: list[int]) -> None:
z = Array.create(store=store, shape=shape, chunk_shape=shape, zarr_format=3, dtype="f8")
z[...] = 42
assert_array_equal(z[...], np.zeros(shape, dtype="f8"))


@pytest.mark.parametrize("store", ["memory"], indirect=["store"])
def test_vectorized_indexing_incompatible_shape(store) -> None:
# GH2469
shape = (4, 4)
chunks = (2, 2)
fill_value = 32767
arr = zarr.create(
shape,
store=store,
chunks=chunks,
dtype=np.int16,
fill_value=fill_value,
codecs=[zarr.codecs.BytesCodec(), zarr.codecs.BloscCodec()],
)
with pytest.raises(ValueError, match="Attempting to set"):
arr[np.array([1, 2]), np.array([1, 2])] = np.array([[-1, -2], [-3, -4]])

0 comments on commit f50daa1

Please sign in to comment.