Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/zarr-indexing/changes/496.feature.md
Original file line number Diff line number Diff line change
@@ -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.
12 changes: 8 additions & 4 deletions packages/zarr-indexing/docs/api/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -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**

Expand Down Expand Up @@ -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)

Expand Down
9 changes: 8 additions & 1 deletion packages/zarr-indexing/src/zarr_indexing/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -89,6 +93,7 @@
unit_step_reader,
)
from zarr_indexing.transform import (
BasicSelection,
IndexTransform,
)

Expand All @@ -97,6 +102,7 @@
__all__ = [
"ArrayMap",
"BasicReader",
"BasicSelection",
"BoundsCheckError",
"ChunkCoverage",
"ChunkGrid",
Expand All @@ -119,6 +125,7 @@
"JointSet",
"LazyArray",
"NdselError",
"NoBasicSelectionError",
"NumPyReader",
"OutputIndexMap",
"OutputIndexMapJSON",
Expand Down
46 changes: 39 additions & 7 deletions packages/zarr-indexing/src/zarr_indexing/errors.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,54 @@
"""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 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
(`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.

Expand Down
7 changes: 2 additions & 5 deletions packages/zarr-indexing/src/zarr_indexing/iteration.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,10 +64,7 @@

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.reader import _lower
from zarr_indexing.transform import IndexTransform

if TYPE_CHECKING:
Expand Down Expand Up @@ -329,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
Expand Down
76 changes: 76 additions & 0 deletions packages/zarr-indexing/src/zarr_indexing/lazy_array.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,8 @@

import numpy.typing as npt

from zarr_indexing.transform import BasicSelection

SelectFn = Callable[[Any, SelectionMode], "LazyArray"]

__all__ = ["LazyArray", "Partition"]
Expand Down Expand Up @@ -560,6 +562,80 @@ 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 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
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 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.

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.
Expand Down
118 changes: 6 additions & 112 deletions packages/zarr-indexing/src/zarr_indexing/reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,14 @@

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.transform import (
IndexTransform,
)
from zarr_indexing.output_map import ArrayMap, ConstantMap, DimensionMap
from zarr_indexing.transform import IndexTransform # noqa: TC001 (doctest runtime)

__all__ = [
"BasicReader",
Expand Down Expand Up @@ -143,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)

Expand Down Expand Up @@ -172,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)

Expand Down Expand Up @@ -215,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)

Expand Down Expand Up @@ -496,104 +491,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))
Loading
Loading