diff --git a/changes/4643.misc.md b/changes/4643.misc.md new file mode 100644 index 0000000000..d5a9a850e9 --- /dev/null +++ b/changes/4643.misc.md @@ -0,0 +1 @@ +When an `oindex`, `vindex` or `__setitem__` index array names an element more than once, the value the element receives is now documented as unspecified, as in NumPy. Remove repeated indices if the result matters. Grouping a fancy selection by chunk is also several times faster. diff --git a/docs/user-guide/arrays.md b/docs/user-guide/arrays.md index 5b025047b6..17f9b82b0d 100644 --- a/docs/user-guide/arrays.md +++ b/docs/user-guide/arrays.md @@ -549,6 +549,13 @@ z[:] = data print(np.all(z.oindex[[0, 2], :] == z[[0, 2], :])) ``` +### Repeated indices + +If an index array used for writing names an element more than once, the element is +set to one of the values given for it, and which one is unspecified, as in NumPy. +This applies to coordinate and orthogonal writes, through `vindex`, `oindex` +or the square bracket operator. Remove repeated indices if the result matters. + ### Block indexing Zarr also supports block indexing, which allows selections of whole chunks based on their diff --git a/src/zarr/core/array.py b/src/zarr/core/array.py index 3735a4da18..e895b74958 100644 --- a/src/zarr/core/array.py +++ b/src/zarr/core/array.py @@ -3313,6 +3313,10 @@ def set_orthogonal_selection( Slices with step > 1 are supported, but slices with negative step are not. + If `selection` names an element more than once, the element is set to one of the + values given for it, and which one is unspecified, as in NumPy. Remove repeated + indices if the result matters. + Related ------- [get_basic_selection][zarr.Array.get_basic_selection], @@ -3668,6 +3672,10 @@ def set_coordinate_selection( Slices are not supported. Coordinate arrays must be provided for all dimensions of the array. + If `selection` names an element more than once, the element is set to one of the + values given for it, and which one is unspecified, as in NumPy. Remove repeated + indices if the result matters. + Related ------- [get_basic_selection][zarr.Array.get_basic_selection], diff --git a/src/zarr/core/indexing.py b/src/zarr/core/indexing.py index ffd4035bb7..7cbd833886 100644 --- a/src/zarr/core/indexing.py +++ b/src/zarr/core/indexing.py @@ -762,6 +762,58 @@ def sorted_run_ends( return a[run_starts].astype(np.intp, copy=False), run_ends +# Below this many items per 16-bit pass, NumPy's stable sort of the full-width indices is +# faster than radix-sorting them. +_RADIX_SORT_MIN_ITEMS_PER_PASS = 128 + + +def argsort_chunk_indices( + chunk_indices: npt.NDArray[np.intp], nchunks: int +) -> npt.NDArray[np.intp]: + """Return the indices that sort `chunk_indices`, each in `range(nchunks)`. + + NumPy sorts integers of at most 16 bits with a radix sort, several times faster than + its default sort, so the indices are sorted 16 bits at a time, lowest bits first. + With more than 2**16 chunks, each index is first offset by the smallest one, so the + number of passes follows the range of chunks the selection touches rather than the + size of the grid. For a few indices the plain stable sort is faster and is used + instead. Either way the sort is stable, so items that share a chunk keep their + order. That order is an implementation detail: the value stored for a repeated index + is unspecified. + """ + lowest = 0 + n_passes = _radix_passes(nchunks - 1) + # finding the range costs a few percent of a pass, so only look when it can save one + # and the radix sort may still run + if n_passes > 1 and chunk_indices.size >= _RADIX_SORT_MIN_ITEMS_PER_PASS: + smallest, largest = int(chunk_indices.min()), int(chunk_indices.max()) + n_passes = _radix_passes(largest) + # offsetting costs a subtraction per pass, so only offset when it saves a pass + if _radix_passes(largest - smallest) < n_passes: + lowest = smallest + n_passes = _radix_passes(largest - smallest) + if chunk_indices.size < _RADIX_SORT_MIN_ITEMS_PER_PASS * n_passes: + return np.argsort(chunk_indices, kind="stable") + low_digit = chunk_indices.astype(np.uint16) + if lowest: + # the low 16 bits of an offset depend only on the low 16 bits of the index and + # of `lowest`, and uint16 subtraction wraps + low_digit -= np.uint16(lowest & 0xFFFF) + order = np.argsort(low_digit, kind="stable") + for shift in range(16, 16 * n_passes, 16): + offsets = chunk_indices[order] + if lowest: + offsets -= lowest + digit = (offsets >> shift).astype(np.uint16) + order = order[np.argsort(digit, kind="stable")] + return order + + +def _radix_passes(largest: int) -> int: + """Return how many 16-bit radix passes sort non-negative integers up to `largest`.""" + return max(1, -(largest.bit_length() // -16)) + + @dataclass(frozen=True) class IntArrayDimIndexer: """Integer array selection against a single dimension.""" @@ -831,7 +883,7 @@ def __init__( dim_sel_chunk_sorted = dim_sel_chunk[::-1] else: # sort indices to group by chunk - dim_out_sel = np.argsort(dim_sel_chunk) + dim_out_sel = argsort_chunk_indices(dim_sel_chunk, nchunks) dim_sel = np.take(dim_sel, dim_out_sel) dim_sel_chunk_sorted = dim_sel_chunk[dim_out_sel] @@ -1346,7 +1398,7 @@ def __init__( # group points by chunk if np.any(np.diff(chunks_raveled_indices) < 0): # optimisation, only sort if needed - sel_sort = np.argsort(chunks_raveled_indices) + sel_sort = argsort_chunk_indices(chunks_raveled_indices, product(cdata_shape)) selection_broadcast = tuple(dim_sel[sel_sort] for dim_sel in selection_broadcast) chunks_raveled_indices = chunks_raveled_indices[sel_sort] else: diff --git a/tests/test_indexing.py b/tests/test_indexing.py index 4ff35563c6..df7ee8d32c 100644 --- a/tests/test_indexing.py +++ b/tests/test_indexing.py @@ -20,7 +20,7 @@ from zarr import Array from zarr.core.buffer import default_buffer_prototype from zarr.core.chunk_grids import ChunkGrid -from zarr.core.common import ceildiv_int +from zarr.core.common import ceildiv_int, product from zarr.core.indexing import ( BasicSelection, CoordinateIndexer, @@ -32,6 +32,7 @@ _ArrayIndexingOrder, _iter_grid, _iter_regions, + argsort_chunk_indices, make_slice_selection, normalize_integer_selection, oindex, @@ -507,17 +508,122 @@ def test_setitem_zarr_array_as_value() -> None: assert_array_equal(dst2[2:7], np.arange(2, 7)) -@pytest.mark.skip(reason="fails on ubuntu, windows; numpy=2.2; in CI") -def test_setitem_repeated_index(): - """oindex assignment with repeated indices writes the last value for each duplicated index position.""" - array = zarr.array(data=np.zeros((4,)), chunks=(1,)) - indexer = np.array([-1, -1, 0, 0]) - array.oindex[(indexer,)] = [0, 1, 2, 3] - np.testing.assert_array_equal(array[:], np.array([3, 0, 0, 1])) +def _reversed_within_chunk_argsort( + chunk_indices: npt.NDArray[np.intp], nchunks: int +) -> npt.NDArray[np.intp]: + """Group `chunk_indices` by chunk, reversing the order of items within each chunk.""" + return np.lexsort((-np.arange(chunk_indices.size), chunk_indices)) - indexer = np.array([-1, 0, 0, -1]) - array.oindex[(indexer,)] = [0, 1, 2, 3] - np.testing.assert_array_equal(array[:], np.array([2, 0, 0, 3])) + +@pytest.mark.parametrize("method", ["oindex", "vindex"]) +@pytest.mark.parametrize("layout", ["unit_chunks", "partial_chunks", "one_chunk", "sharded"]) +@pytest.mark.parametrize( + ("shape", "selection"), + [ + ((24,), ([-1, -1, 0, 0],)), + ((24,), ([-1, 0, 0, -1],)), + ((24,), ([1] + [0] * 23,)), + ((6, 6), ([0, 5, 0, -1, 2] * 4, [1, 1, 4, 4, 2] * 4)), + ], + ids=["adjacent", "interleaved", "many_repeats", "two_dimensions"], +) +@pytest.mark.parametrize("within_chunk_order", ["default", "reversed"]) +def test_setitem_repeated_index( + method: str, + layout: str, + shape: tuple[int, ...], + selection: tuple[list[int], ...], + within_chunk_order: str, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Assignment with repeated indices sets each repeated element to one of its values, whole, and leaves the rest as NumPy would.""" + if within_chunk_order == "reversed": + monkeypatch.setattr( + zarr.core.indexing, "argsort_chunk_indices", _reversed_within_chunk_argsort + ) + chunks = { + "unit_chunks": (1,) * len(shape), + "partial_chunks": (4,) * len(shape), + "one_chunk": shape, + "sharded": (2,) * len(shape), + }[layout] + shards = (6,) * len(shape) if layout == "sharded" else None + array = zarr.create_array(store={}, shape=shape, chunks=chunks, shards=shards, dtype="i8") + flat_ids = np.arange(product(shape)).reshape(shape) + if method == "oindex": + targets = flat_ids[np.ix_(*selection)] + value = np.arange(1, 1 + targets.size).reshape(targets.shape) + array.oindex[selection] = value + else: + targets = flat_ids[selection] + value = np.arange(1, 1 + targets.size) + array.vindex[selection] = value + written = array[:].reshape(-1) + targets = targets.reshape(-1) + value = value.reshape(-1) + assert (np.delete(written, targets) == 0).all() + for target in np.unique(targets): + assert written[target] in value[targets == target] + + +@pytest.mark.parametrize("spread", ["whole_grid", "upper_part", "narrow"]) +@pytest.mark.parametrize("n_items", [100, 2000]) +@pytest.mark.parametrize( + "nchunks", [1, 2**8, 2**16, 2**16 + 1, 2**32, 2**32 + 1, 2**48, 2**48 + 1, 2**62, 2**70] +) +def test_argsort_chunk_indices(nchunks: int, n_items: int, spread: str) -> None: + """The sort matches NumPy's stable sort for any number of chunks, for few or many items, and for indices spread over the whole grid, a range at its top, or a narrow range in its middle.""" + rng = np.random.default_rng(0) + highest = min(nchunks, 2**63) - 1 + if spread == "whole_grid": + low, high = 0, highest + elif spread == "upper_part": + # a range about 2**-16 of the grid wide at its top, so offsetting by its lowest + # index saves a pass on large grids + low, high = max(0, highest - (highest >> 16) - 12345), highest + else: + # a few hundred chunks around a multiple of 2**16, which crosses a 16-bit digit + # on grids of more than 2**17 chunks + middle = highest // 2 // 2**16 * 2**16 + low, high = max(0, middle - 300), min(highest, middle + 300) + chunk_indices = np.concatenate( + [[low, high, high, low], rng.integers(low, high + 1, n_items - 4)] + ).astype(np.intp) + expected = np.argsort(chunk_indices, kind="stable") + assert_array_equal(argsort_chunk_indices(chunk_indices, nchunks), expected) + + +@pytest.mark.parametrize("spread", ["whole_grid", "narrow"]) +@pytest.mark.parametrize("method", ["oindex", "vindex"]) +def test_fancy_selection_visits_each_chunk_once(method: str, spread: str) -> None: + """An unordered selection over more than 2**16 chunks visits each chunk once, in order, and reads what NumPy reads.""" + rng = np.random.default_rng(0) + if method == "oindex": + # one dimension of 2**17 + 5 chunks + shape: tuple[int, ...] = (2**17 + 5,) + low, high = (0, shape[0] - 1) if spread == "whole_grid" else (2**16 - 300, 2**16 + 300) + selection: tuple[npt.NDArray[np.intp], ...] = (rng.integers(low, high + 1, 600),) + else: + # 300 * 300 = 90,000 chunks; rows 217-219 cover chunks 65,100-65,999, around 2**16 + shape = (300, 300) + rows = (0, 299) if spread == "whole_grid" else (217, 219) + selection = (rng.integers(rows[0], rows[1] + 1, 600), rng.integers(0, 300, 600)) + expected = np.zeros(shape, dtype="i8") + points = np.unique(np.ravel_multi_index(selection, shape)) + expected.reshape(-1)[points] = points + 1 + grid = ChunkGrid.from_sizes(shape, (1,) * len(shape)) + array = zarr.create_array(store={}, shape=shape, chunks=(1,) * len(shape), dtype="i8") + # write in increasing order, which needs no sort + array.vindex[np.unravel_index(points, shape)] = points + 1 + + if method == "oindex": + dim_indexer = IntArrayDimIndexer(selection[0], shape[0], grid._dimensions[0]) + visited = dim_indexer.dim_chunk_ixs + assert_array_equal(array.oindex[selection], expected[selection]) + else: + visited = CoordinateIndexer(selection, shape, grid).chunk_rixs + assert_array_equal(array.vindex[selection], expected[selection]) + assert (np.diff(visited) > 0).all() Index = list[int] | tuple[slice | int | list[int], ...]