From a640deb48a227ffe9bf516ac6274b5d358b25cd4 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Fri, 4 Dec 2026 16:05:42 +0100 Subject: [PATCH 1/7] refactor(zarr-indexing): move basic decomposition into transform The cover-and-residual factorization is a property of a transform, not of a reader: `reader.py` and `iteration.py` both consume it. Move `_decompose_basic`, `_decompose_unit_step` and their helpers into `transform.py` unchanged, so the next commit can give them a public owner. Assisted-by: ClaudeCode:claude-opus-5-5 --- .../src/zarr_indexing/iteration.py | 7 +- .../zarr-indexing/src/zarr_indexing/reader.py | 110 +----------------- .../src/zarr_indexing/transform.py | 108 ++++++++++++++++- 3 files changed, 113 insertions(+), 112 deletions(-) diff --git a/packages/zarr-indexing/src/zarr_indexing/iteration.py b/packages/zarr-indexing/src/zarr_indexing/iteration.py index 53cb2c81cd..e79d23f59b 100644 --- a/packages/zarr-indexing/src/zarr_indexing/iteration.py +++ b/packages/zarr-indexing/src/zarr_indexing/iteration.py @@ -64,11 +64,8 @@ from zarr_indexing.chunk_resolution import plan_chunks from zarr_indexing.lazy_array import LazyArray -from zarr_indexing.reader import ( - _decompose_basic, - _lower, -) -from zarr_indexing.transform import IndexTransform +from zarr_indexing.reader import _lower +from zarr_indexing.transform import IndexTransform, _decompose_basic if TYPE_CHECKING: from collections.abc import Generator, Hashable, Iterable, Iterator, Sequence diff --git a/packages/zarr-indexing/src/zarr_indexing/reader.py b/packages/zarr-indexing/src/zarr_indexing/reader.py index 9e14d59c10..403d0c2e1c 100644 --- a/packages/zarr-indexing/src/zarr_indexing/reader.py +++ b/packages/zarr-indexing/src/zarr_indexing/reader.py @@ -4,18 +4,17 @@ import math from dataclasses import dataclass -from typing import TYPE_CHECKING, Any, Final, Protocol - -if TYPE_CHECKING: - from collections.abc import Callable +from typing import Any, Final, Protocol import numpy as np from zarr_indexing._affine import checked_affine from zarr_indexing.chunk_resolution import ChunkProjection # noqa: TC001 (runtime annotation) -from zarr_indexing.output_map import ArrayMap, ConstantMap, DimensionMap, OutputIndexMap +from zarr_indexing.output_map import ArrayMap, ConstantMap, DimensionMap from zarr_indexing.transform import ( IndexTransform, + _decompose_basic, + _decompose_unit_step, ) __all__ = [ @@ -496,104 +495,3 @@ def _lower_general(array: Any, transform: IndexTransform) -> Any: return _restore_domain_axis_order( result, list(broadcast_axes) + residual_axis_dims, transform.domain.shape ) - - -def _push_slice_for_dimension_map( - m: DimensionMap, transform: IndexTransform -) -> tuple[slice, DimensionMap]: - """The positive-step slice covering a `DimensionMap`, and its block-local map. - - A negative step is read forwards and reversed by the residual: a source is - only asked for positive-stride slices. Supporting those slices is part of - this reader's source contract. - """ - d = m.input_dimension - lo = transform.domain.inclusive_min[d] - hi = max(transform.domain.exclusive_max[d], lo) - if hi == lo: - return slice(0, 0, 1), DimensionMap(input_dimension=d, offset=-lo, stride=1) - first = checked_affine(m.offset, m.stride, lo) - last = checked_affine(m.offset, m.stride, hi - 1) - if m.stride > 0: - return ( - slice(first, last + 1, m.stride), - DimensionMap(input_dimension=d, offset=-lo, stride=1), - ) - if m.stride == 0: - return ( - slice(first, first + 1, 1), - DimensionMap(input_dimension=d, offset=0, stride=0), - ) - # Descending: the block holds the same coordinates in ascending order, so - # the residual walks it backwards from the last block position. - return ( - slice(last, first + 1, -m.stride), - DimensionMap(input_dimension=d, offset=hi - 1, stride=-1), - ) - - -def _push_unit_slice_for_dimension_map( - m: DimensionMap, transform: IndexTransform -) -> tuple[slice, DimensionMap]: - """The unit-step slice covering a `DimensionMap`, and its block-local map. - - Strides and reversals stay in the residual: the source is only ever asked - for a contiguous ascending slice, and the original stride is replayed - against the in-memory block. The cover may include unselected elements; - for n distinct points at spacing k it has (n - 1) * k + 1 elements. - """ - d = m.input_dimension - lo = transform.domain.inclusive_min[d] - hi = max(transform.domain.exclusive_max[d], lo) - if hi == lo: - return slice(0, 0, 1), DimensionMap(input_dimension=d, offset=-lo, stride=1) - first = checked_affine(m.offset, m.stride, lo) - if m.stride == 0: - return ( - slice(first, first + 1, 1), - DimensionMap(input_dimension=d, offset=0, stride=0), - ) - last = checked_affine(m.offset, m.stride, hi - 1) - origin = min(first, last) - return ( - slice(origin, max(first, last) + 1, 1), - DimensionMap(input_dimension=d, offset=m.offset - origin, stride=m.stride), - ) - - -def _decompose_basic(transform: IndexTransform) -> tuple[tuple[slice, ...], IndexTransform]: - return _decompose(transform, _push_slice_for_dimension_map) - - -def _decompose_unit_step(transform: IndexTransform) -> tuple[tuple[slice, ...], IndexTransform]: - return _decompose(transform, _push_unit_slice_for_dimension_map) - - -def _decompose( - transform: IndexTransform, - push_dimension_map: Callable[[DimensionMap, IndexTransform], tuple[slice, DimensionMap]], -) -> tuple[tuple[slice, ...], IndexTransform]: - key: list[slice] = [] - residual: list[OutputIndexMap] = [] - for output_map in transform.output: - if isinstance(output_map, ConstantMap): - coordinate = checked_affine(output_map.offset, 0, 0) - key.append(slice(coordinate, coordinate + 1, 1)) - residual.append(ConstantMap(offset=0)) - elif isinstance(output_map, DimensionMap): - pushed, local = push_dimension_map(output_map, transform) - key.append(pushed) - residual.append(local) - else: - coordinates = checked_affine( - output_map.offset, output_map.stride, output_map.index_array - ) - if coordinates.size == 0: - key.append(slice(0, 0, 1)) - local_index = coordinates - else: - origin = int(coordinates.min()) - key.append(slice(origin, int(coordinates.max()) + 1, 1)) - local_index = checked_affine(-origin, 1, coordinates) - residual.append(ArrayMap(index_array=local_index)) - return tuple(key), IndexTransform(domain=transform.domain, output=tuple(residual)) diff --git a/packages/zarr-indexing/src/zarr_indexing/transform.py b/packages/zarr-indexing/src/zarr_indexing/transform.py index 97d1060ff2..3fbc4b8544 100644 --- a/packages/zarr-indexing/src/zarr_indexing/transform.py +++ b/packages/zarr-indexing/src/zarr_indexing/transform.py @@ -50,7 +50,7 @@ ) if TYPE_CHECKING: - from collections.abc import Sequence + from collections.abc import Callable, Sequence import numpy.typing as npt @@ -1537,6 +1537,112 @@ def _reshape_to_axis( return flat.reshape(shape) +# --------------------------------------------------------------------------- # +# Cover-and-residual decomposition +# --------------------------------------------------------------------------- # + + +def _push_slice_for_dimension_map( + m: DimensionMap, transform: IndexTransform +) -> tuple[slice, DimensionMap]: + """The positive-step slice covering a `DimensionMap`, and its block-local map. + + A negative step is read forwards and reversed by the residual: a source is + only asked for positive-stride slices. Supporting those slices is part of + this reader's source contract. + """ + d = m.input_dimension + lo = transform.domain.inclusive_min[d] + hi = max(transform.domain.exclusive_max[d], lo) + if hi == lo: + return slice(0, 0, 1), DimensionMap(input_dimension=d, offset=-lo, stride=1) + first = checked_affine(m.offset, m.stride, lo) + last = checked_affine(m.offset, m.stride, hi - 1) + if m.stride > 0: + return ( + slice(first, last + 1, m.stride), + DimensionMap(input_dimension=d, offset=-lo, stride=1), + ) + if m.stride == 0: + return ( + slice(first, first + 1, 1), + DimensionMap(input_dimension=d, offset=0, stride=0), + ) + # Descending: the block holds the same coordinates in ascending order, so + # the residual walks it backwards from the last block position. + return ( + slice(last, first + 1, -m.stride), + DimensionMap(input_dimension=d, offset=hi - 1, stride=-1), + ) + + +def _push_unit_slice_for_dimension_map( + m: DimensionMap, transform: IndexTransform +) -> tuple[slice, DimensionMap]: + """The unit-step slice covering a `DimensionMap`, and its block-local map. + + Strides and reversals stay in the residual: the source is only ever asked + for a contiguous ascending slice, and the original stride is replayed + against the in-memory block. The cover may include unselected elements; + for n distinct points at spacing k it has (n - 1) * k + 1 elements. + """ + d = m.input_dimension + lo = transform.domain.inclusive_min[d] + hi = max(transform.domain.exclusive_max[d], lo) + if hi == lo: + return slice(0, 0, 1), DimensionMap(input_dimension=d, offset=-lo, stride=1) + first = checked_affine(m.offset, m.stride, lo) + if m.stride == 0: + return ( + slice(first, first + 1, 1), + DimensionMap(input_dimension=d, offset=0, stride=0), + ) + last = checked_affine(m.offset, m.stride, hi - 1) + origin = min(first, last) + return ( + slice(origin, max(first, last) + 1, 1), + DimensionMap(input_dimension=d, offset=m.offset - origin, stride=m.stride), + ) + + +def _decompose_basic(transform: IndexTransform) -> tuple[tuple[slice, ...], IndexTransform]: + return _decompose(transform, _push_slice_for_dimension_map) + + +def _decompose_unit_step(transform: IndexTransform) -> tuple[tuple[slice, ...], IndexTransform]: + return _decompose(transform, _push_unit_slice_for_dimension_map) + + +def _decompose( + transform: IndexTransform, + push_dimension_map: Callable[[DimensionMap, IndexTransform], tuple[slice, DimensionMap]], +) -> tuple[tuple[slice, ...], IndexTransform]: + key: list[slice] = [] + residual: list[OutputIndexMap] = [] + for output_map in transform.output: + if isinstance(output_map, ConstantMap): + coordinate = checked_affine(output_map.offset, 0, 0) + key.append(slice(coordinate, coordinate + 1, 1)) + residual.append(ConstantMap(offset=0)) + elif isinstance(output_map, DimensionMap): + pushed, local = push_dimension_map(output_map, transform) + key.append(pushed) + residual.append(local) + else: + coordinates = checked_affine( + output_map.offset, output_map.stride, output_map.index_array + ) + if coordinates.size == 0: + key.append(slice(0, 0, 1)) + local_index = coordinates + else: + origin = int(coordinates.min()) + key.append(slice(origin, int(coordinates.max()) + 1, 1)) + local_index = checked_affine(-origin, 1, coordinates) + residual.append(ArrayMap(index_array=local_index)) + return tuple(key), IndexTransform(domain=transform.domain, output=tuple(residual)) + + class _OIndexHelper: """Helper that provides orthogonal (outer) indexing via `transform.oindex[...]`.""" From 2daa2476a7332768b235c039dbe806a7e1417f6d Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Fri, 4 Dec 2026 16:09:32 +0100 Subject: [PATCH 2/7] feat(zarr-indexing): lower transforms to NumPy basic selections Add `IndexTransform.as_basic_selection`, which spells a box transform as the tuple of ints, slices and `None` that reads the same cells under NumPy basic indexing, and refuses everything else with the new `NoBasicSelectionError` (a `ValueError`). Fabricated axes lower back to the `None` that made them. Add `IndexTransform.decompose` and `decompose_unit_step`, the total counterparts: every transform factors into ascending cover slices plus an in-memory residual. They are the former private `_decompose_basic` and `_decompose_unit_step`, now the one implementation behind the built-in readers and `iteration`. Both refuse a negative output coordinate, which NumPy would count from the end of the source. `BasicSelection` names the lowering's output type. Assisted-by: ClaudeCode:claude-opus-5-5 --- packages/zarr-indexing/docs/api/index.md | 12 +- .../src/zarr_indexing/__init__.py | 9 +- .../zarr-indexing/src/zarr_indexing/errors.py | 43 ++- .../src/zarr_indexing/iteration.py | 4 +- .../zarr-indexing/src/zarr_indexing/reader.py | 12 +- .../src/zarr_indexing/transform.py | 343 +++++++++++++++++- .../zarr-indexing/tests/test_transform.py | 189 +++++++++- 7 files changed, 570 insertions(+), 42 deletions(-) diff --git a/packages/zarr-indexing/docs/api/index.md b/packages/zarr-indexing/docs/api/index.md index 28e252f186..7c6f4edc12 100644 --- a/packages/zarr-indexing/docs/api/index.md +++ b/packages/zarr-indexing/docs/api/index.md @@ -32,7 +32,9 @@ and the wire format built on top of it. one per storage dimension - [`zarr_indexing.transform`](transform.md) — `IndexTransform`, which pairs a domain with output maps, plus the indexing (`[...]`, `.oindex`, `.vindex`), - `intersect`, `translate`, and `compose` operations, and `selection_to_transform` + `intersect`, `translate`, and `compose` operations, and `selection_to_transform`; + `as_basic_selection` lowers a box transform to a NumPy `BasicSelection`, and + `decompose` factors any transform into a basic cover and an in-memory residual **Chunk resolution** @@ -77,9 +79,11 @@ and the wire format built on top of it. **Errors** -- [`zarr_indexing.errors`](errors.md) — the index-error types this package - raises, also exported at the top level. `zarr.errors` defines classes of the - same names, which are different objects; both subclass `IndexError` +- [`zarr_indexing.errors`](errors.md) — the error types this package + raises, also exported at the top level. `zarr.errors` defines index errors of + the same names, which are different objects; both subclass `IndexError`. + `NoBasicSelectionError`, a `ValueError`, refuses a transform that has no + basic-selection spelling **Test support** (needs the `testing` extra) diff --git a/packages/zarr-indexing/src/zarr_indexing/__init__.py b/packages/zarr-indexing/src/zarr_indexing/__init__.py index 85e794bd6f..e855b9a3e4 100644 --- a/packages/zarr-indexing/src/zarr_indexing/__init__.py +++ b/packages/zarr-indexing/src/zarr_indexing/__init__.py @@ -43,7 +43,11 @@ ) from zarr_indexing.domain import IndexDomain from zarr_indexing.eager import EagerArrayAdapter -from zarr_indexing.errors import BoundsCheckError, VindexInvalidSelectionError +from zarr_indexing.errors import ( + BoundsCheckError, + NoBasicSelectionError, + VindexInvalidSelectionError, +) from zarr_indexing.grid import ( ChunkGrid, ChunkSpec, @@ -89,6 +93,7 @@ unit_step_reader, ) from zarr_indexing.transform import ( + BasicSelection, IndexTransform, ) @@ -97,6 +102,7 @@ __all__ = [ "ArrayMap", "BasicReader", + "BasicSelection", "BoundsCheckError", "ChunkCoverage", "ChunkGrid", @@ -119,6 +125,7 @@ "JointSet", "LazyArray", "NdselError", + "NoBasicSelectionError", "NumPyReader", "OutputIndexMap", "OutputIndexMapJSON", diff --git a/packages/zarr-indexing/src/zarr_indexing/errors.py b/packages/zarr-indexing/src/zarr_indexing/errors.py index 24fc6c6ba6..4f785ebbb1 100644 --- a/packages/zarr-indexing/src/zarr_indexing/errors.py +++ b/packages/zarr-indexing/src/zarr_indexing/errors.py @@ -1,22 +1,51 @@ -"""Canonical index-error types raised by the transform algebra. +"""Canonical error types raised by the transform algebra. -Both subclass the built-in `IndexError`, so an `except IndexError` catch site -keeps working unchanged whichever library raised. +The two index errors subclass the built-in `IndexError`, so an +`except IndexError` catch site keeps working unchanged whichever library +raised. `zarr.errors` defines classes of the same names, and they are *not* +these objects: `zarr.errors.BoundsCheckError is BoundsCheckError` is false. +Catching zarr's class does not catch this package's errors. Import these from +here, or catch their shared built-in `IndexError` base to handle both +libraries. -`zarr.errors` defines classes of the same names, and they are *not* these -objects: `zarr.errors.BoundsCheckError is BoundsCheckError` is false. Catching -zarr's class does not catch this package's errors. Import these from here, -or catch their shared built-in `IndexError` base to handle both libraries. +`NoBasicSelectionError`, the refusal to lower a transform to a basic +selection, subclasses `ValueError` and has no `zarr.errors` counterpart. """ from __future__ import annotations __all__ = [ "BoundsCheckError", + "NoBasicSelectionError", "VindexInvalidSelectionError", ] +class NoBasicSelectionError(ValueError): + """The transform has no basic-selection spelling. + + `IndexTransform.as_basic_selection` is a partial function: integers, + slices, and `None` spell exactly the reads that take one source axis per + result axis, in increasing order, each an arithmetic progression of + nonnegative coordinates. A transform outside that set (a query's lookup + table, a stride-0 broadcast, transposed or repeated axes, a negative + coordinate) is refused with this error rather than approximated. + `IndexTransform.decompose` refuses only the negative coordinate. + + A dedicated subclass, so a consumer's fallback + (`except NoBasicSelectionError: read through a reader instead`) cannot + silently absorb a defect that raises a plain `ValueError`. + + Examples + -------- + >>> from zarr_indexing import IndexTransform + >>> IndexTransform.from_shape((10,)).oindex[[3, 1, 1]].as_basic_selection() + Traceback (most recent call last): + ... + zarr_indexing.errors.NoBasicSelectionError: ... + """ + + class VindexInvalidSelectionError(IndexError): """A wrapper `vindex` selection contained a slice. diff --git a/packages/zarr-indexing/src/zarr_indexing/iteration.py b/packages/zarr-indexing/src/zarr_indexing/iteration.py index e79d23f59b..7ae102519a 100644 --- a/packages/zarr-indexing/src/zarr_indexing/iteration.py +++ b/packages/zarr-indexing/src/zarr_indexing/iteration.py @@ -65,7 +65,7 @@ from zarr_indexing.chunk_resolution import plan_chunks from zarr_indexing.lazy_array import LazyArray from zarr_indexing.reader import _lower -from zarr_indexing.transform import IndexTransform, _decompose_basic +from zarr_indexing.transform import IndexTransform if TYPE_CHECKING: from collections.abc import Generator, Hashable, Iterable, Iterator, Sequence @@ -326,7 +326,7 @@ def _pieces(view: LazyArray) -> list[_Piece]: source = _Source.of(view) pieces: list[_Piece] = [] for part in view.parts(): - crop, residual = _decompose_basic(part.projection.chunk_transform) + crop, residual = part.projection.chunk_transform.decompose() domain = part.projection.chunk_domain pieces.append(_Piece(source, part.base_coords, domain, crop, residual, part.out_selection)) return pieces diff --git a/packages/zarr-indexing/src/zarr_indexing/reader.py b/packages/zarr-indexing/src/zarr_indexing/reader.py index 403d0c2e1c..1f5bea2872 100644 --- a/packages/zarr-indexing/src/zarr_indexing/reader.py +++ b/packages/zarr-indexing/src/zarr_indexing/reader.py @@ -11,11 +11,7 @@ from zarr_indexing._affine import checked_affine from zarr_indexing.chunk_resolution import ChunkProjection # noqa: TC001 (runtime annotation) from zarr_indexing.output_map import ArrayMap, ConstantMap, DimensionMap -from zarr_indexing.transform import ( - IndexTransform, - _decompose_basic, - _decompose_unit_step, -) +from zarr_indexing.transform import IndexTransform # noqa: TC001 (doctest runtime) __all__ = [ "BasicReader", @@ -142,7 +138,7 @@ class BasicReader: def read_into(self, source: Any, context: ReadContext, out: Any, /) -> None: """Read one transform through a positive-slice slab and residual lowering.""" transform = context.transform - key, residual = _decompose_basic(transform) + key, residual = transform.decompose() block = np.asanyarray(source[key]) out[...] = _lower(block, residual) @@ -171,7 +167,7 @@ class NumPyReader: def read_into(self, source: Any, context: ReadContext, out: Any, /) -> None: """Read one transform through a narrowed slab into `out`.""" transform = context.transform - key, residual = _decompose_basic(transform) + key, residual = transform.decompose() block = np.asanyarray(source[key]) out[...] = _lower(block, residual) @@ -214,7 +210,7 @@ class UnitStepReader: def read_into(self, source: Any, context: ReadContext, out: Any, /) -> None: """Read one transform through an ascending unit-step slab into `out`.""" transform = context.transform - key, residual = _decompose_unit_step(transform) + key, residual = transform.decompose_unit_step() block = np.asanyarray(source[key]) out[...] = _lower(block, residual) diff --git a/packages/zarr-indexing/src/zarr_indexing/transform.py b/packages/zarr-indexing/src/zarr_indexing/transform.py index 3fbc4b8544..ee6e850c92 100644 --- a/packages/zarr-indexing/src/zarr_indexing/transform.py +++ b/packages/zarr-indexing/src/zarr_indexing/transform.py @@ -40,7 +40,11 @@ from zarr_indexing._selector import as_scalar_index, require_index from zarr_indexing.boundary import validate_advanced_selection from zarr_indexing.domain import IndexDomain -from zarr_indexing.errors import BoundsCheckError, VindexInvalidSelectionError +from zarr_indexing.errors import ( + BoundsCheckError, + NoBasicSelectionError, + VindexInvalidSelectionError, +) from zarr_indexing.output_map import ( ArrayMap, ConstantMap, @@ -57,6 +61,20 @@ from zarr_indexing.json import IndexTransformJSON +type BasicSelection = tuple[int | slice | None, ...] +"""A selection in NumPy's basic-indexing dialect: one selector per axis. + +The request vocabulary of `source[selection]` under NumPy basic indexing: an +`int` reads one coordinate and drops its axis, a `slice` reads an arithmetic +progression, and `None` fabricates an axis no source axis backs. It is +deliberately wider than `zarr.AsyncArray.getitem`'s selection type: Zarr +rejects `None` and negative-step slices, so an integration with that backend +must normalize those two forms before making the request. Produced by +[`IndexTransform.as_basic_selection`][zarr_indexing.transform.IndexTransform.as_basic_selection]; +which cells a value denotes is relative to the array it is applied to. +""" + + @dataclass(frozen=True, slots=True) class _PointOutOfBounds(Exception): """Internal signal from the shared point kernel: one coordinate left the domain. @@ -462,6 +480,278 @@ def inverted(self) -> IndexTransform: output=tuple(inverse_output[dimension] for dimension in range(self.input_rank)), ) + def as_basic_selection(self) -> BasicSelection: + """Lower a box transform to the NumPy basic selection it describes. + + Returns one selector per output dimension, plus a `None` for each + domain axis no output map reads and no constant stands in for, such + that `source[transform.as_basic_selection()]` under NumPy indexing + semantics reads exactly the cells this transform addresses, in domain + order: the result has shape `domain.shape` exactly, and its element at + position `p` holds the source value at + `apply(domain.inclusive_min + p)`. + + A `DimensionMap` lowers to a `slice`. A `ConstantMap` usually lowers + to an `int`, which drops its axis exactly as the constant map carries + no input dimension. A singleton domain axis that no output map + references (a single-coordinate fancy index collapses to a constant at + construction, leaving its axis behind: `oindex[:, [2]]`) is instead + produced by lowering a constant to a length-1 slice, so the result + keeps the domain's shape. An unreferenced axis with no constant to + stand in for it is one nothing reads, a `None`/newaxis in the + selection that made it, and lowers back to `None`. + + [`decompose`][zarr_indexing.transform.IndexTransform.decompose] is + the total counterpart: every transform factors into a basic cover + plus an in-memory residual, so a refusal here is not a dead end. + + This is the boundary for consumers that plan reads here but perform + them through their own I/O layer, such as an async store or an HTTP + range request, whose request vocabulary is a basic selection rather + than a transform. Such a backend may accept less than NumPy does: a + reversing map lowers to a negative-step slice and a fabricated axis to + `None`, neither of which Zarr's own basic selections take, so a + consumer whose backend is stricter should inspect the lowered + selectors or use `decompose`, whose cover is ascending slices only. + + Returns + ------- + tuple of int or slice or None + One selector per output dimension, interleaved with a `None` for + each domain axis that neither an output map reads nor a constant + stands in for. + + Raises + ------ + NoBasicSelectionError + If the transform cannot be expressed as a basic selection: an + output map is an `ArrayMap` (a query is a lookup table, not a + slab), a `DimensionMap` has stride 0 (a broadcast repeats one + source cell, which no slice spells), the selectors cannot produce + the domain's axes in increasing order and exactly once (basic + indexing never transposes or repeats axes), an unreferenced domain + axis has extent other than 1 (an axis restored by repetition, + where a newaxis would give extent 1), or a selected coordinate is + negative (NumPy would count it from the end of the source). + + Examples + -------- + >>> IndexTransform.from_shape((10, 20))[2:8, ::2].as_basic_selection() + (slice(2, 8, 1), slice(0, 19, 2)) + >>> IndexTransform.from_shape((10, 20))[3, 4:6].as_basic_selection() + (3, slice(4, 6, 1)) + + The collapsed single-coordinate gather keeps its axis: + + >>> IndexTransform.from_shape((10, 20)).oindex[slice(None), [2]].as_basic_selection() + (slice(0, 10, 1), slice(2, 3, 1)) + + An axis the selection fabricated lowers back to the newaxis that made it: + + >>> IndexTransform.from_shape((10, 20))[:, None].as_basic_selection() + (slice(0, 10, 1), None, slice(0, 20, 1)) + + unless a constant is due where the axis is, in which case that + constant keeps it and no newaxis is needed: + + >>> IndexTransform.from_shape((10, 20))[None, 3].as_basic_selection() + (slice(3, 4, 1), slice(0, 20, 1)) + + A query has no basic-selection spelling: + + >>> IndexTransform.from_shape((10,)).oindex[[3, 1, 1]].as_basic_selection() + Traceback (most recent call last): + ... + zarr_indexing.errors.NoBasicSelectionError: cannot lower to a basic \ +selection: output[0] is an ArrayMap; a query selection is a lookup table, not a slab + """ + box_maps: list[ConstantMap | DimensionMap] = [] + for output_dimension, output_map in enumerate(self.output): + # Refused before the axis bookkeeping below, which would otherwise + # blame a query's gathered axis for being unreferenced. + if isinstance(output_map, ArrayMap): + raise NoBasicSelectionError( + f"cannot lower to a basic selection: output[{output_dimension}] " + "is an ArrayMap; a query selection is a lookup table, not a slab" + ) + box_maps.append(output_map) + referenced = {m.input_dimension for m in box_maps if isinstance(m, DimensionMap)} + for axis, extent in enumerate(self.domain.shape): + if axis not in referenced and extent != 1: + raise NoBasicSelectionError( + f"cannot lower to a basic selection: no output map references " + f"input dimension {axis}, whose extent is {extent}; only a " + "singleton axis can be produced without reading a source axis, " + "by an integer-indexed output dimension or a newaxis" + ) + selection: list[int | slice | None] = [] + # The next domain axis a selector has to produce. Slices and newaxes + # produce axes in selector order, so walking the outputs left to right + # must meet the domain axes in increasing order. + next_axis = 0 + for output_dimension, output_map in enumerate(box_maps): + if isinstance(output_map, ConstantMap): + if output_map.offset < 0: + raise NoBasicSelectionError( + f"cannot lower to a basic selection: output[{output_dimension}] " + f"addresses coordinate {output_map.offset}, which NumPy would " + "count from the end of the source" + ) + if next_axis < self.input_rank and next_axis not in referenced: + # This constant stands in for the singleton axis: a + # length-1 slice keeps the axis where an int would drop it. + selection.append(slice(output_map.offset, output_map.offset + 1, 1)) + next_axis += 1 + else: + selection.append(output_map.offset) + continue + if output_map.stride == 0: + raise NoBasicSelectionError( + f"cannot lower to a basic selection: output[{output_dimension}] " + "has stride 0, which repeats one source cell along an axis; " + "no slice spells a broadcast" + ) + d = output_map.input_dimension + if d < next_axis or not referenced.isdisjoint(range(next_axis, d)): + raise NoBasicSelectionError( + "cannot lower to a basic selection: the selectors must produce " + "the domain's axes in increasing order and exactly once, but " + f"output[{output_dimension}] produces input dimension {d} out of " + "that order; basic indexing never transposes or repeats axes" + ) + # Every axis skipped here is unreferenced, hence a proven singleton + # that nothing reads: NumPy inserts it, which is what `None` does. + selection.extend([None] * (d - next_axis)) + next_axis = d + 1 + endpoints = _dimension_map_endpoints( + output_map, self.domain.inclusive_min[d], self.domain.exclusive_max[d] + ) + if endpoints is None: + selection.append(slice(0, 0, 1)) + continue + first, last = endpoints + if min(first, last) < 0: + raise NoBasicSelectionError( + f"cannot lower to a basic selection: output[{output_dimension}] " + f"addresses coordinate {min(first, last)}, which NumPy would " + "count from the end of the source" + ) + if output_map.stride > 0: + selection.append(slice(first, last + 1, output_map.stride)) + else: + # Descending: the stop sits one step past the final coordinate, + # and a stop below 0 has no literal spelling; None walks to + # the front edge instead of wrapping. + stop = last + output_map.stride + selection.append(slice(first, stop if stop >= 0 else None, output_map.stride)) + # Every referenced axis was produced by the map that references it, + # which moved `next_axis` past it, so the axes left over are all + # unreferenced singletons that trail the last selector. + selection.extend([None] * (self.input_rank - next_axis)) + return tuple(selection) + + def decompose(self) -> tuple[tuple[slice, ...], IndexTransform]: + """Factor this transform into a basic cover and an in-memory residual. + + The total counterpart of + [`as_basic_selection`][zarr_indexing.transform.IndexTransform.as_basic_selection]: + where that method is defined only for reads that *are* a basic + selection, every transform factors as one basic read followed by an + in-memory rearrangement. Returns `(cover, residual)` such that + resolving `residual` against the block `source[cover]` reads exactly + the cells this transform addresses, at exactly its domain shape. A + consumer whose I/O layer speaks basic selections can therefore fetch + the cover through it and finish any gather, reversal, or broadcast in + memory. + + The cover is one ascending slice per output dimension: a + `DimensionMap` covers its arithmetic progression (a descending map is + read forwards and reversed by the residual), a `ConstantMap` covers + its single coordinate, and an `ArrayMap` covers the range from its + smallest to its largest coordinate. The price of a slab vocabulary is + over-reading a sparse gather's bounding interval. The residual keeps + this transform's domain and rewrites each output map to block-local + coordinates, so the factorization inverts by composition: the cover, + read as the diagonal transform it denotes, chained onto the residual, + reads cell for cell as `self` (the maps may spell offsets + differently; the reads are identical). + + Returns + ------- + tuple + `(cover, residual)`: a tuple of ascending slices to request from + the source, and the `IndexTransform` to resolve against the + returned block. + + Raises + ------ + NoBasicSelectionError + If an output coordinate is negative: NumPy would count it from + the end of the source, so no cover slice can spell it. This is + the one transform shape with no factorization; every other + transform, including queries and broadcasts, decomposes. + + Examples + -------- + A descending strided read: the cover walks forward, the residual + reverses. + + >>> import numpy as np + >>> source = np.arange(10) + >>> cover, residual = IndexTransform.from_shape((10,))[::-3].decompose() + >>> cover + (slice(0, 10, 3),) + >>> block = source[cover] + >>> lo, hi = residual.domain.inclusive_min[0], residual.domain.exclusive_max[0] + >>> [int(block[residual.apply((p,))]) for p in range(lo, hi)] + [9, 6, 3, 0] + + A query decomposes into its bounding interval and a block-local + lookup, where `as_basic_selection` refuses: + + >>> cover, residual = IndexTransform.from_shape((10,)).oindex[[7, 2, 2]].decompose() + >>> cover + (slice(2, 8, 1),) + >>> block = source[cover] + >>> [int(block[residual.apply((p,))]) for p in range(3)] + [7, 2, 2] + """ + return _decompose(self, _push_slice_for_dimension_map) + + def decompose_unit_step(self) -> tuple[tuple[slice, ...], IndexTransform]: + """Factor as `decompose` does, with a contiguous ascending cover. + + The variant of + [`decompose`][zarr_indexing.transform.IndexTransform.decompose] for a + source that accepts nothing but `slice(start, stop, 1)`; compare + [`UnitStepReader`][zarr_indexing.reader.UnitStepReader], which reads + through exactly this factorization. Strides and reversals stay in the + residual, so the cover over-reads a strided selection by its stride + factor: the price of a unit-step request vocabulary. The cover is the + box bounding the coordinates this transform reads, the bound + TensorStore's `GetOutputRange` computes for a transform's output range. + + Returns + ------- + tuple + `(cover, residual)` exactly as `decompose` returns them, with + every cover slice contiguous and ascending. + + Raises + ------ + NoBasicSelectionError + If an output coordinate is negative, exactly as for `decompose`. + + Examples + -------- + >>> cover, residual = IndexTransform.from_shape((10,))[1:9:3].decompose_unit_step() + >>> cover + (slice(1, 8, 1),) + >>> residual.output + (DimensionMap(input_dimension=0, offset=0, stride=3),) + """ + return _decompose(self, _push_unit_slice_for_dimension_map) + @property def selection_repr(self) -> str: """Compact domain string, e.g. `'{ [2, 8), [0, 10) }'`. @@ -1278,7 +1568,7 @@ def _intersect_general( return (result, out_indices.astype(np.intp)) -def _normalize_basic_selection(selection: Any, ndim: int) -> tuple[int | slice | None, ...]: +def _normalize_basic_selection(selection: Any, ndim: int) -> BasicSelection: """Normalize a selection to a tuple of int, slice, or None (newaxis), expanding ellipsis and padding with slice(None) as needed. """ @@ -1338,7 +1628,7 @@ def _positional_slice(pos: int, size: int, step: int) -> slice: def _reindex_array( m: ArrayMap, - normalized: tuple[int | slice | None, ...], + normalized: BasicSelection, domain: IndexDomain, ) -> np.ndarray[Any, np.dtype[np.intp]]: """Apply basic indexing operations to an ArrayMap's index_array. @@ -1542,6 +1832,23 @@ def _reshape_to_axis( # --------------------------------------------------------------------------- # +def _dimension_map_endpoints( + m: DimensionMap, inclusive_min: int, exclusive_max: int +) -> tuple[int, int] | None: + """The first and last output coordinates `m` reaches over a domain interval. + + `None` for an empty interval, which reaches no coordinate at all. A + descending map reports them in the order it walks them, so `first` may + exceed `last`. + """ + if exclusive_max <= inclusive_min: + return None + return ( + checked_affine(m.offset, m.stride, inclusive_min), + checked_affine(m.offset, m.stride, exclusive_max - 1), + ) + + def _push_slice_for_dimension_map( m: DimensionMap, transform: IndexTransform ) -> tuple[slice, DimensionMap]: @@ -1553,11 +1860,11 @@ def _push_slice_for_dimension_map( """ d = m.input_dimension lo = transform.domain.inclusive_min[d] - hi = max(transform.domain.exclusive_max[d], lo) - if hi == lo: + hi = transform.domain.exclusive_max[d] + endpoints = _dimension_map_endpoints(m, lo, hi) + if endpoints is None: return slice(0, 0, 1), DimensionMap(input_dimension=d, offset=-lo, stride=1) - first = checked_affine(m.offset, m.stride, lo) - last = checked_affine(m.offset, m.stride, hi - 1) + first, last = endpoints if m.stride > 0: return ( slice(first, last + 1, m.stride), @@ -1588,16 +1895,15 @@ def _push_unit_slice_for_dimension_map( """ d = m.input_dimension lo = transform.domain.inclusive_min[d] - hi = max(transform.domain.exclusive_max[d], lo) - if hi == lo: + endpoints = _dimension_map_endpoints(m, lo, transform.domain.exclusive_max[d]) + if endpoints is None: return slice(0, 0, 1), DimensionMap(input_dimension=d, offset=-lo, stride=1) - first = checked_affine(m.offset, m.stride, lo) + first, last = endpoints if m.stride == 0: return ( slice(first, first + 1, 1), DimensionMap(input_dimension=d, offset=0, stride=0), ) - last = checked_affine(m.offset, m.stride, hi - 1) origin = min(first, last) return ( slice(origin, max(first, last) + 1, 1), @@ -1605,14 +1911,6 @@ def _push_unit_slice_for_dimension_map( ) -def _decompose_basic(transform: IndexTransform) -> tuple[tuple[slice, ...], IndexTransform]: - return _decompose(transform, _push_slice_for_dimension_map) - - -def _decompose_unit_step(transform: IndexTransform) -> tuple[tuple[slice, ...], IndexTransform]: - return _decompose(transform, _push_unit_slice_for_dimension_map) - - def _decompose( transform: IndexTransform, push_dimension_map: Callable[[DimensionMap, IndexTransform], tuple[slice, DimensionMap]], @@ -1640,6 +1938,13 @@ def _decompose( key.append(slice(origin, int(coordinates.max()) + 1, 1)) local_index = checked_affine(-origin, 1, coordinates) residual.append(ArrayMap(index_array=local_index)) + for output_dimension, entry in enumerate(key): + if entry.start < 0: + raise NoBasicSelectionError( + f"cannot cover with a basic selection: output[{output_dimension}] " + f"addresses coordinate {entry.start}, which NumPy would count " + "from the end of the source" + ) return tuple(key), IndexTransform(domain=transform.domain, output=tuple(residual)) diff --git a/packages/zarr-indexing/tests/test_transform.py b/packages/zarr-indexing/tests/test_transform.py index 8ae555c46e..85f9ef9cd6 100644 --- a/packages/zarr-indexing/tests/test_transform.py +++ b/packages/zarr-indexing/tests/test_transform.py @@ -6,7 +6,7 @@ import pytest from zarr_indexing.domain import IndexDomain -from zarr_indexing.errors import BoundsCheckError +from zarr_indexing.errors import BoundsCheckError, NoBasicSelectionError from zarr_indexing.lazy_array import LazyArray from zarr_indexing.output_map import ArrayMap, ConstantMap, DimensionMap from zarr_indexing.transform import ( @@ -395,6 +395,193 @@ def test_inverted_rejects_input_labels_that_cannot_be_preserved(self) -> None: transform.inverted() +def _pointwise_read(transform: IndexTransform, source: np.ndarray) -> np.ndarray: + """Read through `transform` one point at a time — the oracle.""" + domain = transform.domain + if transform.input_rank == 0: + return np.asarray(source[transform.apply(())]) + axes = [ + np.arange(lo, hi) for lo, hi in zip(domain.inclusive_min, domain.exclusive_max, strict=True) + ] + if any(axis.size == 0 for axis in axes): + return np.empty(domain.shape, dtype=source.dtype) + mesh = np.meshgrid(*axes, indexing="ij") + points = np.stack([m.ravel() for m in mesh], axis=1) + coordinates = transform.apply_many(points) + return source[tuple(coordinates.T)].reshape(domain.shape) + + +class TestAsBasicSelection: + @pytest.mark.parametrize( + "transform", + [ + pytest.param(IndexTransform.from_shape((10,)), id="identity"), + pytest.param(IndexTransform.from_shape((10,))[2:8], id="slice"), + pytest.param(IndexTransform.from_shape((10,))[1:9:3], id="strided"), + pytest.param(IndexTransform.from_shape((6,))[::-1], id="reversed"), + pytest.param(IndexTransform.from_shape((10,))[::-3], id="reversed-strided"), + pytest.param(IndexTransform.from_shape((10,))[4:4], id="empty"), + pytest.param(IndexTransform.from_shape((5, 7))[3, 1:6:2], id="int-and-slice"), + pytest.param(IndexTransform.from_shape((5, 7))[2:5][3:5], id="composed-literal"), + pytest.param(IndexTransform.from_shape((5, 7))[3, 2], id="rank-zero"), + pytest.param( + # The single-coordinate gather collapses to a constant at + # construction, leaving a singleton domain axis no map + # references; the constant lowers to a length-1 slice. + IndexTransform.from_shape((5, 7)).oindex[slice(None), [2]], + id="collapsed-single-gather", + ), + pytest.param( + IndexTransform.from_shape((5, 7)).oindex[[3], [2]], + id="two-collapsed-gathers", + ), + # An axis nothing reads is one the selection fabricated, in every + # position it can hold relative to the axes that are read. + pytest.param(IndexTransform.from_shape((5, 7))[None], id="leading-newaxis"), + pytest.param(IndexTransform.from_shape((5, 7))[:, None], id="interior-newaxis"), + pytest.param(IndexTransform.from_shape((10,))[:, None], id="trailing-newaxis"), + pytest.param(IndexTransform.from_shape((10,))[None, None], id="stacked-newaxis"), + pytest.param(IndexTransform.from_shape((5, 7))[None, 3], id="newaxis-and-int"), + pytest.param( + IndexTransform.from_shape((5, 7)).oindex[slice(None), [2]][None], + id="newaxis-and-collapsed-gather", + ), + ], + ) + def test_selection_reproduces_the_transform(self, transform: IndexTransform) -> None: + """`source[selection]` has the domain's shape and its exact values.""" + source = np.arange(35).reshape(5, 7) if transform.output_rank == 2 else np.arange(10) + selection = transform.as_basic_selection() + # One selector per output dimension, plus one per fabricated axis. + assert len(selection) - sum(item is None for item in selection) == transform.output_rank + read = np.asarray(source[selection]) + assert read.shape == transform.domain.shape + np.testing.assert_array_equal(read, _pointwise_read(transform, source)) + + def test_rejects_an_array_map(self) -> None: + transform = IndexTransform.from_shape((10,)).oindex[[3, 1, 1]] + with pytest.raises(NoBasicSelectionError, match="is an ArrayMap"): + transform.as_basic_selection() + + def test_rejects_a_zero_stride(self) -> None: + transform = IndexTransform( + IndexDomain.from_shape((3,)), (DimensionMap(0, offset=2, stride=0),) + ) + with pytest.raises(NoBasicSelectionError, match="stride 0"): + transform.as_basic_selection() + + def test_rejects_a_transposed_dimension_order(self) -> None: + transform = IndexTransform( + IndexDomain.from_shape((2, 3)), (DimensionMap(1), DimensionMap(0)) + ) + with pytest.raises(NoBasicSelectionError, match="increasing order"): + transform.as_basic_selection() + + def test_rejects_a_repeated_input_dimension(self) -> None: + transform = IndexTransform( + IndexDomain.from_shape((2,)), (DimensionMap(0), DimensionMap(0, offset=1)) + ) + with pytest.raises(NoBasicSelectionError, match="increasing order"): + transform.as_basic_selection() + + def test_rejects_an_unreferenced_non_singleton_dimension(self) -> None: + """An axis restored by repetition — a duplicate gather of a constant.""" + transform = IndexTransform.from_shape((5,)).oindex[[3]].oindex[np.array([0, 0])] + with pytest.raises(NoBasicSelectionError, match="only a singleton axis"): + transform.as_basic_selection() + + def test_a_trailing_singleton_axis_lowers_to_a_newaxis(self) -> None: + """No output map reads it, so nothing but a newaxis can produce it.""" + transform = IndexTransform(IndexDomain.from_shape((2, 1)), (DimensionMap(0),)) + assert transform.as_basic_selection() == (slice(0, 2, 1), None) + + def test_rejects_a_negative_constant_coordinate(self) -> None: + transform = IndexTransform(IndexDomain.from_shape(()), (ConstantMap(-1),)) + with pytest.raises(NoBasicSelectionError, match="count from the end"): + transform.as_basic_selection() + + def test_rejects_a_negative_slice_coordinate(self) -> None: + transform = IndexTransform(IndexDomain.from_shape((2,)), (DimensionMap(0, offset=-3),)) + with pytest.raises(NoBasicSelectionError, match="count from the end"): + transform.as_basic_selection() + + +class TestDecompose: + @pytest.mark.parametrize( + "transform", + [ + pytest.param(IndexTransform.from_shape((10,)), id="identity"), + pytest.param(IndexTransform.from_shape((10,))[1:9:3], id="strided"), + pytest.param(IndexTransform.from_shape((6,))[::-1], id="reversed"), + pytest.param(IndexTransform.from_shape((10,))[4:4], id="empty"), + pytest.param(IndexTransform.from_shape((5, 7))[3, 1:6:2], id="int-and-slice"), + pytest.param(IndexTransform.from_shape((5, 7))[3, 2], id="rank-zero"), + pytest.param(IndexTransform.from_shape((10,)).oindex[[7, 2, 2]], id="query-gather"), + pytest.param( + IndexTransform.from_shape((5, 7)).oindex[slice(None), [2]], + id="collapsed-single-gather", + ), + pytest.param( + IndexTransform( + IndexDomain.from_shape((3,)), (DimensionMap(0, offset=2, stride=0),) + ), + id="broadcast", + ), + pytest.param( + IndexTransform(IndexDomain.from_shape((2, 3)), (DimensionMap(1), DimensionMap(0))), + id="transposed", + ), + pytest.param(IndexTransform.from_shape((5,))[None], id="newaxis"), + pytest.param( + IndexTransform.from_shape((5,)).oindex[[3]].oindex[np.array([0, 0])], + id="axis-restored-by-repetition", + ), + ], + ) + @pytest.mark.parametrize("unit_step", [False, True], ids=["decompose", "decompose_unit_step"]) + def test_cover_and_residual_reproduce_the_transform( + self, transform: IndexTransform, unit_step: bool + ) -> None: + """The factorization law, checked both ways. + + Value law: resolving the residual against `source[cover]` reads + exactly what the transform reads. Composition law: the cover, read as + the diagonal transform it denotes, chained onto the residual, is the + original transform — `decompose` is inverted by `compose`. Every + transform decomposes, including the shapes `as_basic_selection` + refuses. The unit-step variant obeys the same laws with a contiguous + cover. + """ + source = np.arange(35).reshape(5, 7) if transform.output_rank == 2 else np.arange(10) + cover, residual = transform.decompose_unit_step() if unit_step else transform.decompose() + assert len(cover) == transform.output_rank + assert all(entry.step == 1 if unit_step else entry.step >= 1 for entry in cover) + block = np.asarray(source[cover]) + np.testing.assert_array_equal( + _pointwise_read(residual, block), _pointwise_read(transform, source) + ) + cover_transform = IndexTransform( + IndexDomain.from_shape(block.shape), + tuple( + DimensionMap(axis, offset=entry.start, stride=entry.step) + for axis, entry in enumerate(cover) + ), + ) + composed = residual.compose(cover_transform) + assert composed.domain == transform.domain + np.testing.assert_array_equal( + _pointwise_read(composed, source), _pointwise_read(transform, source) + ) + + @pytest.mark.parametrize("unit_step", [False, True], ids=["decompose", "decompose_unit_step"]) + def test_rejects_a_negative_coordinate(self, unit_step: bool) -> None: + """The one shape with no cover: NumPy would wrap the coordinate.""" + transform = IndexTransform(IndexDomain.from_shape((2,)), (DimensionMap(0, offset=-3),)) + factor = transform.decompose_unit_step if unit_step else transform.decompose + with pytest.raises(NoBasicSelectionError, match="count from the end"): + factor() + + class TestIndexTransformBasicIndexing: def test_slice_identity(self) -> None: """slice(None) on identity transform is a no-op.""" From 7ed138da5ebd11d0b112e9f0847e38f588e4aedf Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Fri, 4 Dec 2026 16:11:11 +0100 Subject: [PATCH 3/7] feat(zarr-indexing): lower partition parts to basic selections Add `Partition.source_selection`, the basic selection on the raw wrapped array that reads a part, and `Partition.chunk_local_selection`, the same read relative to the part's grid cell. A consumer that plans with `parts()` but fetches through its own I/O layer can assemble a view as `out[part.out_selection] = source[part.source_selection]`, or read a cached decoded cell with `cell[part.chunk_local_selection]`. Query parts, and boxes with no basic spelling, raise `NoBasicSelectionError`. Both are thin lowerings of `part.view.transform` and `part.projection.chunk_transform`, which already address the source and the cell in global and cell-local coordinates respectively. Assisted-by: ClaudeCode:claude-opus-5-5 --- .../src/zarr_indexing/lazy_array.py | 72 +++++++++++++++++++ .../zarr-indexing/tests/test_lazy_array.py | 61 ++++++++++++++++ 2 files changed, 133 insertions(+) diff --git a/packages/zarr-indexing/src/zarr_indexing/lazy_array.py b/packages/zarr-indexing/src/zarr_indexing/lazy_array.py index 0cdbbfa488..fce532a28a 100644 --- a/packages/zarr-indexing/src/zarr_indexing/lazy_array.py +++ b/packages/zarr-indexing/src/zarr_indexing/lazy_array.py @@ -190,6 +190,8 @@ import numpy.typing as npt + from zarr_indexing.transform import BasicSelection + SelectFn = Callable[[Any, SelectionMode], "LazyArray"] __all__ = ["LazyArray", "Partition"] @@ -560,6 +562,76 @@ def is_complete(self) -> bool: """Whether the projection proves it covers the entire selected cell.""" return self.projection.coverage == "full" + @property + def source_selection(self) -> BasicSelection: + """The basic selection on the raw wrapped array that reads this part. + + Lowered from `view.transform` by + [`IndexTransform.as_basic_selection`][zarr_indexing.transform.IndexTransform.as_basic_selection], + so the coordinates are global to `view.array` and + `view.array[part.source_selection]` reads the same block + `view.result()` reads, in the same order. This is the request to hand + to a consumer-owned I/O layer whose vocabulary is a basic selection + rather than a transform. When that backend accepts NumPy's complete + basic-selection dialect, assembly is one line per part: + + ```python + out[part.out_selection] = await source.getitem(part.source_selection) + ``` + + A query part has no slab to request and raises + [`NoBasicSelectionError`][zarr_indexing.errors.NoBasicSelectionError], + as do the two degenerate boxes with no basic-selection spelling: an + axis restored by repetition (reached by gathering a collapsed constant + with duplicates) and an axis broadcast from one cell. `view.is_box` is + therefore necessary but not sufficient; catching the error is what + decides it, and a consumer mixing selection kinds falls back to + `view.result()` for the parts that refuse. A consumer that must stay + on its own I/O path even for query parts can instead fetch the cover + half of + [`view.transform.decompose()`][zarr_indexing.transform.IndexTransform.decompose] + and finish the gather in memory. A reversing view lowers to a + negative-step slice and a fabricated axis to `None`, which a backend + narrower than NumPy may not accept. + + Examples + -------- + >>> import numpy as np + >>> view = LazyArray.from_numpy(np.arange(12).reshape(3, 4)).with_parts((2, 2)) + >>> [part.source_selection for part in view[1:, ::2].parts()] + [(slice(1, 2, 1), slice(0, 1, 2)), (slice(1, 2, 1), slice(2, 3, 2)), \ +(slice(2, 3, 1), slice(0, 1, 2)), (slice(2, 3, 1), slice(2, 3, 2))] + """ + return self.view.transform.as_basic_selection() + + @property + def chunk_local_selection(self) -> BasicSelection: + """The same read as `source_selection`, relative to the part's grid cell. + + Lowered from `projection.chunk_transform`, so coordinate 0 per axis is + `projection.chunk_domain`'s origin. For a consumer that caches decoded + cells, this is the selection to apply to a cached cell: with `cell` + holding `view.array[projection.chunk_domain]`, + `cell[part.chunk_local_selection]` yields the same values as + `view.array[part.source_selection]`, and both land at `out_selection` + in the result buffer. + + Defined exactly when `source_selection` is: the two lower the same + maps, so a part that refuses one spelling refuses both. + + Examples + -------- + >>> import numpy as np + >>> view = LazyArray.from_numpy(np.arange(12).reshape(3, 4)).with_parts((2, 2)) + >>> part = next(view[1:, :2].parts()) + >>> (part.base_coords, part.source_selection, part.chunk_local_selection) + ((0, 0), (slice(1, 2, 1), slice(0, 2, 1)), (slice(1, 2, 1), slice(0, 2, 1))) + >>> part = next(view[2:, :2].parts()) + >>> (part.base_coords, part.source_selection, part.chunk_local_selection) + ((1, 0), (slice(2, 3, 1), slice(0, 2, 1)), (slice(0, 1, 1), slice(0, 2, 1))) + """ + return self.projection.chunk_transform.as_basic_selection() + def _validate_prepared_parts(parts: Sequence[Partition], out_shape: tuple[int, ...]) -> None: """Require `parts` to address every output cell exactly once. diff --git a/packages/zarr-indexing/tests/test_lazy_array.py b/packages/zarr-indexing/tests/test_lazy_array.py index cb91a88c08..9cde99b82a 100644 --- a/packages/zarr-indexing/tests/test_lazy_array.py +++ b/packages/zarr-indexing/tests/test_lazy_array.py @@ -32,6 +32,7 @@ IndexDomain, IndexTransform, LazyArray, + NoBasicSelectionError, ReadContext, VaryingDimension, dimension_grids_from_chunks, @@ -2620,3 +2621,63 @@ def test_dask_is_only_required_for_tokenization(monkeypatch: pytest.MonkeyPatch) np.testing.assert_array_equal(view.result(), data[1:]) with pytest.raises(ModuleNotFoundError): view.__dask_tokenize__() + + +# --------------------------------------------------------------------------- +# Backend-native selection lowering +# --------------------------------------------------------------------------- + + +def test_part_selections_carry_the_read() -> None: + """The lowered selections agree with the documented assemblies. + + `out[part.out_selection] = data[part.source_selection]` reproduces the + view (the loop a consumer runs when it plans here but fetches through its + own I/O layer), and `chunk_local_selection` reads the same values from the + part's grid cell (the loop a decoded-chunk cache runs). + """ + data = reference() + view = LazyArray.from_numpy(data).with_parts((3, 2, 3)) + cases = ( + view, + view[1:6, ::2, 1:], + view[::-1, 2, 1::2], + # The single-coordinate gather collapses to a constant and keeps its + # axis through a length-1 slice. + view.oindex[:, [2], :], + view[5, 1, 2], + view.unpartitioned()[2:6, :, ::2], + # Fabricated axes lower back to the newaxis that made them. + view[None, 1:6, :, None, ::2], + # A part's view, repartitioned, still plans over the source's own + # coordinates, so its cells are the source's cells. + next(view[1:6, 1:4, :].parts()).view.with_parts((2, 1, 2)), + ) + for case in cases: + expected = np.asarray(case.result()) + out = np.full(case.shape, -1, dtype=case.dtype) + for part in case.parts(): + slab = data[part.source_selection] + chunk_domain = part.projection.chunk_domain + cell = data[ + tuple( + slice(lo, hi) + for lo, hi in zip( + chunk_domain.inclusive_min, chunk_domain.exclusive_max, strict=True + ) + ) + ] + np.testing.assert_array_equal(cell[part.chunk_local_selection], slab) + out[part.out_selection] = slab + np.testing.assert_array_equal(out, expected) + + +def test_query_part_selections_refuse_to_lower() -> None: + """A query part has no slab; both spellings must say so, not guess.""" + view = LazyArray.from_numpy(reference()).with_parts((3, 2, 3)).oindex[[6, 1, 1], :, :] + part = next(view.parts()) + assert not part.view.is_box + with pytest.raises(NoBasicSelectionError, match="ArrayMap"): + _ = part.source_selection + with pytest.raises(NoBasicSelectionError, match="ArrayMap"): + _ = part.chunk_local_selection From c2ede25bddfffeaf710a65c10d159a847e975f95 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Fri, 4 Dec 2026 16:14:06 +0100 Subject: [PATCH 4/7] test(zarr-indexing): check part lowering and projections in the state machine `ChainedIndexingStateMachine` gains a `fabricates_an_axis` rule, drawing from the new `newaxis_selections` strategy, so views with axes no source axis backs are reached at full weight. A new invariant runs the consumer-owned-I/O assembly literally: every part's `source_selection` and `chunk_local_selection` must reproduce the model under plain NumPy, query and degenerate parts must refuse both spellings, and every part must obey the `decompose` factorization law. `ProjectionReader` reads through a part's projection instead of its transform, gathering from the whole grid cell; the machine always draws it alongside `basic_reader`, so both halves of a `ReadContext` are checked. Assisted-by: ClaudeCode:claude-opus-5-5 --- .../src/zarr_indexing/testing/__init__.py | 4 + .../src/zarr_indexing/testing/stateful.py | 192 +++++++++++++++++- .../src/zarr_indexing/testing/strategies.py | 22 ++ .../tests/test_lazy_array_stateful.py | 28 ++- 4 files changed, 235 insertions(+), 11 deletions(-) diff --git a/packages/zarr-indexing/src/zarr_indexing/testing/__init__.py b/packages/zarr-indexing/src/zarr_indexing/testing/__init__.py index e98d051900..81726da547 100644 --- a/packages/zarr-indexing/src/zarr_indexing/testing/__init__.py +++ b/packages/zarr-indexing/src/zarr_indexing/testing/__init__.py @@ -27,6 +27,7 @@ def make_source(self, data): DEFAULT_PARTITIONINGS, DEFAULT_SETTINGS, ChainedIndexingStateMachine, + ProjectionReader, apply_selection, outer_selection, repartition, @@ -35,6 +36,7 @@ def make_source(self, data): from zarr_indexing.testing.strategies import ( basic_selections, masks, + newaxis_selections, orthogonal_selections, slice_selections, vectorized_selections, @@ -45,9 +47,11 @@ def make_source(self, data): "DEFAULT_PARTITIONINGS", "DEFAULT_SETTINGS", "ChainedIndexingStateMachine", + "ProjectionReader", "apply_selection", "basic_selections", "masks", + "newaxis_selections", "orthogonal_selections", "outer_selection", "repartition", diff --git a/packages/zarr-indexing/src/zarr_indexing/testing/stateful.py b/packages/zarr-indexing/src/zarr_indexing/testing/stateful.py index 00dce58bb9..e6fab579ca 100644 --- a/packages/zarr-indexing/src/zarr_indexing/testing/stateful.py +++ b/packages/zarr-indexing/src/zarr_indexing/testing/stateful.py @@ -38,9 +38,20 @@ def make_source(self, data): The `choose_reader` rule draws a reader and applies it to the view, so the execution strategy becomes part of the chain. Every reader listed by a subclass -must preserve the NumPy model for its source. The universal `basic_reader` is -always eligible to be drawn, even when a subclass lists only specialized readers; with no -declared readers it is the sole strategy drawn. +must preserve the NumPy model for its source. Two universal readers are always +eligible to be drawn, even when a subclass lists only specialized ones: +`basic_reader`, which answers from the read's transform, and +`ProjectionReader`, which answers from its projection instead, fetching whole +grid cells and gathering out of them the way a decoded-chunk cache does. +Between them both halves of a `ReadContext` are checked against the model. A +projection describing a different read than the transform it arrives with is +invisible to every reader that ignores it, which is how such a pairing can be +wrong while every value assertion passes. + +The lowering invariant runs the consumer-owned-I/O assembly literally: every +part's `source_selection` and `chunk_local_selection`, applied with plain NumPy +to the values the source holds, must reproduce the model, and every part, +query parts included, must satisfy the `decompose` factorization law. Requires the `testing` extra (`pip install zarr-indexing[testing]`). """ @@ -56,10 +67,13 @@ def make_source(self, data): from hypothesis import strategies as st from hypothesis.stateful import RuleBasedStateMachine, initialize, invariant, precondition, rule +from zarr_indexing.errors import NoBasicSelectionError from zarr_indexing.lazy_array import LazyArray -from zarr_indexing.reader import Reader, basic_reader +from zarr_indexing.output_map import DimensionMap +from zarr_indexing.reader import ReadContext, Reader, basic_reader from zarr_indexing.testing.strategies import ( basic_selections, + newaxis_selections, orthogonal_selections, slice_selections, vectorized_selections, @@ -67,12 +81,15 @@ def make_source(self, data): if TYPE_CHECKING: from zarr_indexing.boundary import SelectionMode + from zarr_indexing.domain import IndexDomain + from zarr_indexing.transform import IndexTransform __all__ = [ "DEFAULT_DATA", "DEFAULT_PARTITIONINGS", "DEFAULT_SETTINGS", "ChainedIndexingStateMachine", + "ProjectionReader", "apply_selection", "outer_selection", "repartition", @@ -207,8 +224,10 @@ class ChainedIndexingStateMachine(RuleBasedStateMachine): mid-chain does, and spends the whole step budget on indexing. readers Execution strategies `choose_reader` may draw. Every listed reader must - preserve the model for the source. `basic_reader` is always included; - `None` means the reader already carried by the constructed view. + preserve the model for the source. `basic_reader` and a + `ProjectionReader` are always included, since between them they check + both halves of a `ReadContext`; `None` means the reader already carried + by the constructed view. """ data: ClassVar[Any] = DEFAULT_DATA @@ -295,6 +314,19 @@ def slices_only(self, data: st.DataObject) -> None: """ self._step("orthogonal", data.draw(slice_selections(self.model.shape))) + @precondition(lambda self: self._indexable()) + @rule(data=st.data()) + def fabricates_an_axis(self, data: st.DataObject) -> None: + """A basic step carrying `None`, which adds an axis no source axis backs. + + Its own rule for the reason `slices_only` is: a domain axis that no + output map reads is a distinct shape for everything downstream (the + lowering to a basic selection most of all, which has to produce that + axis without reading one), and folding the spelling into `basic` would + leave it drawn a fraction of the time. + """ + self._step("basic", data.draw(newaxis_selections(self.model.shape))) + @rule(data=st.data()) def choose_reader(self, data: st.DataObject) -> None: """Read the rest of the chain through another conforming strategy.""" @@ -365,12 +397,158 @@ def parts_tile_the_view(self) -> None: hits, np.ones(self.view.shape, dtype=np.int64), err_msg=str(self.chain) ) + @invariant() + def box_parts_lower_to_basic_selections(self) -> None: + """The consumer-owned-I/O assembly, run literally. + + [`Partition`][zarr_indexing.lazy_array.Partition] documents + `out[part.out_selection] = source[part.source_selection]` as the + assembly for a consumer fetching box parts through its own I/O layer, + and `cell[part.chunk_local_selection]` as the equivalent read from a + cached grid cell. Both selections are applied here under plain NumPy + semantics to the values the source holds and checked against the + model; a query part must refuse to lower instead of guessing a slab. + + Every part, query parts included, must also satisfy the factorization + law: `transform.decompose()` yields a cover and a residual whose + resolution against `data[cover]` reproduces the model, the read a + consumer performs when it fetches a bounding slab through its own I/O + layer and finishes the gather in memory. + """ + data = np.asarray(type(self).data) + for part in self.view.parts(): + expected_block = self.model[part.out_selection] + cover, residual = part.view.transform.decompose() + decomposed = np.empty(expected_block.shape, dtype=data.dtype) + basic_reader.read_into(data[cover], ReadContext(residual), decomposed) + np.testing.assert_array_equal(decomposed, expected_block, err_msg=str(self.chain)) + try: + source_selection = part.source_selection + except NoBasicSelectionError: + # Refusal is the documented answer for a query part and for + # the two degenerate boxes: an axis restored by repetition + # (gathering a collapsed constant with duplicates) and an axis + # broadcast from one cell. Every other box must lower, an + # integer-indexed one included, which is the shape a laxer + # check would quietly excuse. + assert not part.view.is_box or _is_degenerate_box(part.view.transform), ( + f"a plain box part refused to lower: {self.chain}" + ) + # The paired spellings lower the same maps, so refusing one + # and answering the other would leave a consumer holding a + # cell selection that no source selection matches. + cell_lowered = True + try: + _ = part.chunk_local_selection + except NoBasicSelectionError: + cell_lowered = False + assert not cell_lowered, ( + f"chunk_local_selection lowered a part whose source_selection " + f"refused to: {self.chain}" + ) + continue + np.testing.assert_array_equal( + data[source_selection], expected_block, err_msg=str(self.chain) + ) + np.testing.assert_array_equal( + _cell(data, part.projection.chunk_domain)[part.chunk_local_selection], + expected_block, + err_msg=str(self.chain), + ) + + +def _is_degenerate_box(transform: IndexTransform) -> bool: + """Whether `transform` is one of the boxes with no basic-selection spelling. + + Either an axis no output map reads but that a length-1 slice or a newaxis + cannot produce because its extent is not 1 (an axis restored by + repetition), or an axis broadcast from a single source cell by a stride-0 + map. Both name more values than the cells they read, which no slab does. + """ + referenced = {m.input_dimension for m in transform.output if isinstance(m, DimensionMap)} + return any( + axis not in referenced and extent != 1 for axis, extent in enumerate(transform.domain.shape) + ) or any(isinstance(m, DimensionMap) and m.stride == 0 for m in transform.output) + + +def _cell(source: Any, domain: IndexDomain) -> Any: + """The block of `source` that `domain` names, read with plain slices.""" + return source[ + tuple( + slice(lo, hi) for lo, hi in zip(domain.inclusive_min, domain.exclusive_max, strict=True) + ) + ] + + +def _domain_points(domain: IndexDomain) -> np.ndarray[Any, np.dtype[np.intp]]: + """Every coordinate in `domain`, one row per point, in C order.""" + axes = [ + np.arange(lo, hi, dtype=np.intp) + for lo, hi in zip(domain.inclusive_min, domain.exclusive_max, strict=True) + ] + if not axes: + # A rank-zero domain holds exactly one point, which has no coordinates. + return np.zeros((1, 0), dtype=np.intp) + mesh = np.meshgrid(*axes, indexing="ij") + return np.stack([axis.ravel() for axis in mesh], axis=1) + + +class ProjectionReader: + """Read each part by gathering it out of the whole grid cell it lives in. + + The built-in readers answer from `context.transform` alone, so a + projection describing a different read than the transform it arrives with + cannot change what they return, and no assertion about values can see it. + This one fetches the cell `projection.chunk_domain` names and gathers the + request out of it with `projection.chunk_transform`, as a decoded-chunk + cache does, which puts the pairing of the two under the same NumPy model + as everything else. + + Deliberately naive: whole cells, gathered pointwise. It is a contract + check, not a strategy to copy for performance. + """ + + def read_into(self, source: Any, context: ReadContext, out: np.ndarray[Any, Any], /) -> None: + """Fill `out` through the projection rather than the transform. + + Raises + ------ + ValueError + If `context` carries no projection. `LazyArray` always supplies + one; only a direct caller can omit it. + """ + projection = context.projection + if projection is None: + raise ValueError("ProjectionReader reads through a projection; this context has none") + cell = np.asanyarray(_cell(source, projection.chunk_domain)) + chunk_points = projection.chunk_transform.apply_many( + _domain_points(projection.chunk_transform.domain) + ) + values = cell[tuple(chunk_points.T)] + # The projection's synthetic domain and the buffer's domain enumerate + # the same cells in the same order and at the same shape, which is the + # pairing `ChunkProjection` documents; a reshape that fails has caught + # that promise breaking. + out[...] = values.reshape(out.shape) + + +_PROJECTION_READER = ProjectionReader() +"""The `ProjectionReader` `choose_reader` draws when a subclass declares none.""" + def _reader_set(view: LazyArray, declared: Sequence[Reader] | None) -> tuple[Reader, ...]: - """The readers `choose_reader` draws from, `basic_reader` always among them.""" + """The readers `choose_reader` draws from. + + `basic_reader` and a `ProjectionReader` are always among them: neither + knows anything about a particular source beyond the slab reads every + source already serves, and between them they check both halves of a + `ReadContext` against the model. + """ readers = list(declared) if declared is not None else [view.reader] if all(reader is not basic_reader for reader in readers): readers.insert(0, basic_reader) + if all(not isinstance(reader, ProjectionReader) for reader in readers): + readers.insert(1, _PROJECTION_READER) unique: list[Reader] = [] for reader in readers: if all(reader is not existing for existing in unique): diff --git a/packages/zarr-indexing/src/zarr_indexing/testing/strategies.py b/packages/zarr-indexing/src/zarr_indexing/testing/strategies.py index 3b9970e8b2..9d23fb3a70 100644 --- a/packages/zarr-indexing/src/zarr_indexing/testing/strategies.py +++ b/packages/zarr-indexing/src/zarr_indexing/testing/strategies.py @@ -38,6 +38,7 @@ def test_my_array_slices_like_numpy(selection): "basic_selections", "empty_masks", "masks", + "newaxis_selections", "orthogonal_selections", "slice_selections", "vectorized_selections", @@ -131,6 +132,27 @@ def basic_selections(shape: tuple[int, ...]) -> st.SearchStrategy[tuple[Any, ... return _entries(shape, _basic_entry) +@st.composite +def newaxis_selections(draw: st.DrawFn, shape: tuple[int, ...]) -> tuple[Any, ...]: + """Basic selections carrying `None`, the selector that fabricates an axis. + + NumPy's `None` belongs to basic indexing and `LazyArray` admits it, but it + is the one basic selector that adds an axis of the view no axis of the + source backs: a domain axis no output map reads, which everything + downstream must then produce without reading one. `basic_selections` + promises one entry per axis, so the spelling that breaks that count is + drawn here instead of widening it. + + A selection carries one or two of them, in any position: leading, between + two axes, or trailing, each of which lands the fabricated axis somewhere + different in the result. + """ + entries = list(draw(basic_selections(shape))) + for _ in range(draw(st.integers(1, 2))): + entries.insert(draw(st.integers(0, len(entries))), None) + return tuple(entries) + + def orthogonal_selections(shape: tuple[int, ...]) -> st.SearchStrategy[tuple[Any, ...]]: """Orthogonal (`oindex`) selections: an outer product of per-axis choices. diff --git a/packages/zarr-indexing/tests/test_lazy_array_stateful.py b/packages/zarr-indexing/tests/test_lazy_array_stateful.py index de0d422b0e..228c040527 100644 --- a/packages/zarr-indexing/tests/test_lazy_array_stateful.py +++ b/packages/zarr-indexing/tests/test_lazy_array_stateful.py @@ -22,11 +22,12 @@ import pytest from hypothesis import settings -from zarr_indexing import LazyArray, ReadContext +from zarr_indexing import IndexTransform, LazyArray, ReadContext from zarr_indexing.reader import basic_reader, numpy_reader from zarr_indexing.testing import ( DEFAULT_SETTINGS, ChainedIndexingStateMachine, + ProjectionReader, state_machine_test, stateful, ) @@ -56,9 +57,28 @@ def test_reader_set_deduplicates_by_identity_without_hashing() -> None: readers = stateful._reader_set(LazyArray(np.arange(3)), (first, first, second)) assert readers[0] is basic_reader - assert readers[1] is first - assert readers[2] is second - assert len(readers) == 3 + assert isinstance(readers[1], ProjectionReader) + assert readers[2] is first + assert readers[3] is second + assert len(readers) == 4 + + +def test_reader_set_keeps_a_declared_projection_reader() -> None: + """The universal pair is added, not duplicated over a subclass's own.""" + declared = ProjectionReader() + + readers = stateful._reader_set(LazyArray(np.arange(3)), (declared,)) + + assert readers == (basic_reader, declared) + + +def test_projection_reader_rejects_an_unplanned_read() -> None: + """Without a projection there is no cell to gather from.""" + out = np.empty(3, dtype=np.int64) + with pytest.raises(ValueError, match="has none"): + ProjectionReader().read_into( + np.arange(3), ReadContext(IndexTransform.from_shape((3,))), out + ) class OneDimensionalIndexing(ChainedIndexingStateMachine): From 07e69ecd7010974a53bb23e8b7cd30f217a9dfa7 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Fri, 4 Dec 2026 16:22:23 +0100 Subject: [PATCH 5/7] fix(zarr-indexing): gather rank-0 cells per point in ProjectionReader Indexing a rank-0 cell with the empty tuple returns its one value however many points repeat it, so a broadcast of a 0-d source failed to reshape. Broadcast to one value per point. Also list transform-key transposes among the boxes `Partition.source_selection` refuses. Found by the adversarial review of this branch. Assisted-by: ClaudeCode:claude-opus-5-5 --- .../src/zarr_indexing/lazy_array.py | 7 ++++--- .../src/zarr_indexing/testing/stateful.py | 5 ++++- .../tests/test_lazy_array_stateful.py | 17 +++++++++++++++++ 3 files changed, 25 insertions(+), 4 deletions(-) diff --git a/packages/zarr-indexing/src/zarr_indexing/lazy_array.py b/packages/zarr-indexing/src/zarr_indexing/lazy_array.py index fce532a28a..8ae7db14bd 100644 --- a/packages/zarr-indexing/src/zarr_indexing/lazy_array.py +++ b/packages/zarr-indexing/src/zarr_indexing/lazy_array.py @@ -581,9 +581,10 @@ def source_selection(self) -> BasicSelection: A query part has no slab to request and raises [`NoBasicSelectionError`][zarr_indexing.errors.NoBasicSelectionError], - as do the two degenerate boxes with no basic-selection spelling: an - axis restored by repetition (reached by gathering a collapsed constant - with duplicates) and an axis broadcast from one cell. `view.is_box` is + as do boxes with no basic-selection spelling: an axis restored by + repetition (reached by gathering a collapsed constant with + duplicates), an axis broadcast from one cell, and axes transposed or + repeated by an `IndexTransform` key. `view.is_box` is therefore necessary but not sufficient; catching the error is what decides it, and a consumer mixing selection kinds falls back to `view.result()` for the parts that refuse. A consumer that must stay diff --git a/packages/zarr-indexing/src/zarr_indexing/testing/stateful.py b/packages/zarr-indexing/src/zarr_indexing/testing/stateful.py index e6fab579ca..b9e6328708 100644 --- a/packages/zarr-indexing/src/zarr_indexing/testing/stateful.py +++ b/packages/zarr-indexing/src/zarr_indexing/testing/stateful.py @@ -524,7 +524,10 @@ def read_into(self, source: Any, context: ReadContext, out: np.ndarray[Any, Any] chunk_points = projection.chunk_transform.apply_many( _domain_points(projection.chunk_transform.domain) ) - values = cell[tuple(chunk_points.T)] + # One value per point. A rank-0 cell is indexed by the empty tuple, + # which NumPy answers with the single value however many points + # repeat it, so the broadcast restores one entry per point. + values = np.broadcast_to(cell[tuple(chunk_points.T)], (len(chunk_points),)) # The projection's synthetic domain and the buffer's domain enumerate # the same cells in the same order and at the same shape, which is the # pairing `ChunkProjection` documents; a reshape that fails has caught diff --git a/packages/zarr-indexing/tests/test_lazy_array_stateful.py b/packages/zarr-indexing/tests/test_lazy_array_stateful.py index 228c040527..6e4c44cd14 100644 --- a/packages/zarr-indexing/tests/test_lazy_array_stateful.py +++ b/packages/zarr-indexing/tests/test_lazy_array_stateful.py @@ -72,6 +72,23 @@ def test_reader_set_keeps_a_declared_projection_reader() -> None: assert readers == (basic_reader, declared) +def test_projection_reader_reads_like_the_basic_reader() -> None: + """Gathering from the cell matches the transform's read, a rank-0 cell included.""" + data = np.arange(24).reshape(4, 6) + views = ( + LazyArray(data).with_parts((3, 4))[1:, ::-2], + LazyArray(data).with_parts((3, 4)).oindex[[3, 0, 0], 1:5], + LazyArray(data).with_parts((3, 4))[None, 2], + # Every point of a rank-0 cell repeats its one value. + LazyArray(np.array(7))[None].oindex[[0, 0, 0]], + ) + for view in views: + np.testing.assert_array_equal( + np.asarray(view.with_reader(ProjectionReader()).result()), + np.asarray(view.with_reader(basic_reader).result()), + ) + + def test_projection_reader_rejects_an_unplanned_read() -> None: """Without a projection there is no cell to gather from.""" out = np.empty(3, dtype=np.int64) From bc4eb48c9fd694a21823ae2a2cca9837d22856ef Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Fri, 4 Dec 2026 16:36:53 +0100 Subject: [PATCH 6/7] docs(zarr-indexing): describe the lowering's refusals as conservative Review follow-ups: say that as_basic_selection also refuses some degenerate transforms NumPy could spell, that decompose checks negative coordinates even on empty domains, how to apply a decompose residual with public API, and that BasicSelection differs from zarr's type of the same name. Pin the empty fabricated-axis refusal with a test. Assisted-by: ClaudeCode:claude-opus-5-5 --- .../zarr-indexing/src/zarr_indexing/errors.py | 15 +++++++++------ .../zarr-indexing/src/zarr_indexing/lazy_array.py | 5 ++++- .../zarr-indexing/src/zarr_indexing/transform.py | 12 +++++++----- packages/zarr-indexing/tests/test_transform.py | 6 ++++++ 4 files changed, 26 insertions(+), 12 deletions(-) diff --git a/packages/zarr-indexing/src/zarr_indexing/errors.py b/packages/zarr-indexing/src/zarr_indexing/errors.py index 4f785ebbb1..d0670bbff7 100644 --- a/packages/zarr-indexing/src/zarr_indexing/errors.py +++ b/packages/zarr-indexing/src/zarr_indexing/errors.py @@ -24,12 +24,15 @@ class NoBasicSelectionError(ValueError): """The transform has no basic-selection spelling. - `IndexTransform.as_basic_selection` is a partial function: integers, - slices, and `None` spell exactly the reads that take one source axis per - result axis, in increasing order, each an arithmetic progression of - nonnegative coordinates. A transform outside that set (a query's lookup - table, a stride-0 broadcast, transposed or repeated axes, a negative - coordinate) is refused with this error rather than approximated. + `IndexTransform.as_basic_selection` is a conservative partial function. + It lowers the reads that take one source axis per result axis, in + increasing order, each an arithmetic progression of nonnegative + coordinates, and refuses everything else with this error rather than + approximating: a query's lookup table, a stride-0 broadcast, transposed + or repeated axes, a negative coordinate. It also refuses a few + degenerate transforms NumPy could spell, such as a transposed or + broadcast axis of extent 0 or 1. A refusal never means the read is + impossible, only that it needs `IndexTransform.decompose` or a reader. `IndexTransform.decompose` refuses only the negative coordinate. A dedicated subclass, so a consumer's fallback diff --git a/packages/zarr-indexing/src/zarr_indexing/lazy_array.py b/packages/zarr-indexing/src/zarr_indexing/lazy_array.py index 8ae7db14bd..2e543bcdb5 100644 --- a/packages/zarr-indexing/src/zarr_indexing/lazy_array.py +++ b/packages/zarr-indexing/src/zarr_indexing/lazy_array.py @@ -591,7 +591,10 @@ def source_selection(self) -> BasicSelection: on its own I/O path even for query parts can instead fetch the cover half of [`view.transform.decompose()`][zarr_indexing.transform.IndexTransform.decompose] - and finish the gather in memory. A reversing view lowers to a + and finish the gather in memory by reading the residual half from the + fetched block, for example + `numpy_reader.read_into(block, ReadContext(residual), out)`. A + reversing view lowers to a negative-step slice and a fabricated axis to `None`, which a backend narrower than NumPy may not accept. diff --git a/packages/zarr-indexing/src/zarr_indexing/transform.py b/packages/zarr-indexing/src/zarr_indexing/transform.py index ee6e850c92..0cc63bd84a 100644 --- a/packages/zarr-indexing/src/zarr_indexing/transform.py +++ b/packages/zarr-indexing/src/zarr_indexing/transform.py @@ -67,8 +67,9 @@ The request vocabulary of `source[selection]` under NumPy basic indexing: an `int` reads one coordinate and drops its axis, a `slice` reads an arithmetic progression, and `None` fabricates an axis no source axis backs. It is -deliberately wider than `zarr.AsyncArray.getitem`'s selection type: Zarr -rejects `None` and negative-step slices, so an integration with that backend +deliberately wider than `zarr.AsyncArray.getitem`'s selection type, and a +different object from `zarr.core.indexing.BasicSelection`, which admits +`Ellipsis`: Zarr rejects `None` and negative-step slices, so an integration with that backend must normalize those two forms before making the request. Produced by [`IndexTransform.as_basic_selection`][zarr_indexing.transform.IndexTransform.as_basic_selection]; which cells a value denotes is relative to the array it is applied to. @@ -687,9 +688,10 @@ def decompose(self) -> tuple[tuple[slice, ...], IndexTransform]: ------ NoBasicSelectionError If an output coordinate is negative: NumPy would count it from - the end of the source, so no cover slice can spell it. This is - the one transform shape with no factorization; every other - transform, including queries and broadcasts, decomposes. + the end of the source, so no cover slice can spell it. The check + applies even when the domain is empty and nothing would be read. + Every other transform, including queries and broadcasts, + decomposes. Examples -------- diff --git a/packages/zarr-indexing/tests/test_transform.py b/packages/zarr-indexing/tests/test_transform.py index 85f9ef9cd6..8274377dfc 100644 --- a/packages/zarr-indexing/tests/test_transform.py +++ b/packages/zarr-indexing/tests/test_transform.py @@ -490,6 +490,12 @@ def test_rejects_an_unreferenced_non_singleton_dimension(self) -> None: with pytest.raises(NoBasicSelectionError, match="only a singleton axis"): transform.as_basic_selection() + def test_rejects_an_empty_fabricated_dimension(self) -> None: + """A newaxis sliced to extent 0: `None` would read extent 1, the wrong shape.""" + transform = IndexTransform.from_shape((5,))[None][0:0] + with pytest.raises(NoBasicSelectionError, match="only a singleton axis"): + transform.as_basic_selection() + def test_a_trailing_singleton_axis_lowers_to_a_newaxis(self) -> None: """No output map reads it, so nothing but a newaxis can produce it.""" transform = IndexTransform(IndexDomain.from_shape((2, 1)), (DimensionMap(0),)) From 1cf23a7411bba08f360644889bd3f95bac54abb3 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Fri, 4 Dec 2026 16:37:31 +0100 Subject: [PATCH 7/7] docs(zarr-indexing): add changelog fragment for #496 Assisted-by: ClaudeCode:claude-opus-5-5 --- packages/zarr-indexing/changes/496.feature.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 packages/zarr-indexing/changes/496.feature.md diff --git a/packages/zarr-indexing/changes/496.feature.md b/packages/zarr-indexing/changes/496.feature.md new file mode 100644 index 0000000000..c536567007 --- /dev/null +++ b/packages/zarr-indexing/changes/496.feature.md @@ -0,0 +1 @@ +`IndexTransform.as_basic_selection()` converts a transform to the NumPy basic selection (ints, slices and `None`) that reads the same cells, and raises the new `NoBasicSelectionError` when it can't. `IndexTransform.decompose()` and `decompose_unit_step()` split any transform into ascending slices to fetch plus an in-memory remainder, and `Partition.source_selection` / `Partition.chunk_local_selection` give each part's read as a basic selection, so code that plans with `parts()` can fetch through its own I/O layer.