Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Fix lazy negative slice rewriting. #7586

Merged
merged 9 commits into from
Mar 27, 2023
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion xarray/backends/zarr.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,13 @@ def __getitem__(self, key):
]
else:
assert isinstance(key, indexing.OuterIndexer)
return array.oindex[key.tuple]
# decompose so that negative slices are now positive slices for the zarr library
# Then reverse the in-memory data.
backend_indexer, numpy_indexer = indexing._decompose_outer_indexer(
key, self.shape, indexing.IndexingSupport.OUTER
)
part = array.oindex[backend_indexer.tuple]
return part[numpy_indexer.tuple]
# if self.ndim == 0:
# could possibly have a work-around for 0d data here

Expand Down
20 changes: 16 additions & 4 deletions xarray/core/indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -829,20 +829,32 @@ def decompose_indexer(
raise TypeError(f"unexpected key type: {indexer}")


def _decompose_slice(key, size):
def _decompose_slice(key: slice, size: int) -> tuple[slice, ...]:
dcherian marked this conversation as resolved.
Show resolved Hide resolved
"""convert a slice to successive two slices. The first slice always has
a positive step.

>>> _decompose_slice(slice(2, 98, 2), 99)
(slice(2, 98, 2), slice(None, None, None))

>>> _decompose_slice(slice(98, 2, -2), 99)
(slice(4, 99, 2), slice(None, None, -1))

>>> _decompose_slice(slice(98, 2, -2), 98)
(slice(3, 98, 2), slice(None, None, -1))

>>> _decompose_slice(slice(360, None, -10), 361)
(slice(0, 361, 10), slice(None, None, -1))
"""
start, stop, step = key.indices(size)
if step > 0:
# If key already has a positive step, use it as is in the backend
return key, slice(None)
else:
# determine stop precisely for step > 1 case
# Use the range object to do the calculation
# e.g. [98:2:-2] -> [98:3:-2]
stop = start + int((stop - start - 1) / step) * step + 1
start, stop = stop + 1, start + 1
return slice(start, stop, -step), slice(None, None, -1)
exact_stop = range(start, stop, step)[-1]
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's a nice trick, have to remember that one :)

return slice(exact_stop, start + 1, -step), slice(None, None, -1)


def _decompose_vectorized_indexer(
Expand Down
21 changes: 18 additions & 3 deletions xarray/tests/test_backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -711,9 +711,6 @@ def multiple_indexing(indexers):
]
multiple_indexing(indexers5)

@pytest.mark.xfail(
reason="zarr without dask handles negative steps in slices incorrectly",
)
def test_vectorized_indexing_negative_step(self) -> None:
# use dask explicitly when present
open_kwargs: dict[str, Any] | None
Expand Down Expand Up @@ -753,6 +750,24 @@ def multiple_indexing(indexers):
]
multiple_indexing(indexers)

def test_outer_indexing_reversed(self) -> None:
# regression test for GH6560
ds = xr.Dataset(
dcherian marked this conversation as resolved.
Show resolved Hide resolved
{
"z": (
("time", "isoBaricInhPa", "latitude", "longitude"),
np.ones((1, 5, 721, 1440)),
)
},
coords={"latitude": np.linspace(-90, 90, 721)},
)

with self.roundtrip(ds) as on_disk:
subset = on_disk.isel(time=[0], isoBaricInhPa=1).z[:, ::10, ::10][
:, ::-1, :
]
assert subset.sizes == subset.load().sizes

def test_isel_dataarray(self) -> None:
# Make sure isel works lazily. GH:issue:1688
in_memory = create_test_data()
Expand Down