-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Fix indexing bugs in CoordinateTransformIndex
#10980
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
Merged
+487
−2
Merged
Changes from 15 commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
be58818
Fix CoordinateTransformIndexingAdapter
dcherian be580c1
Add strategies
dcherian eae0798
Fix indentation bug in create_transform_da
dcherian b576b0d
Merge branch 'main' into fix-coord-transform-indexing
dcherian 630d010
Add unit test
dcherian eae815d
Merge branch 'main' into fix-coord-transform-indexing
dcherian f2f6f45
fix
dcherian 0913077
Better test
dcherian 8efe0c5
Add label based vectorized indexing
dcherian fadfee4
Add label based orthogonal indexing
dcherian 5de497c
Add commented out label based basic indexing test
dcherian fde34b5
fix docstring
dcherian 3568adf
Merge branch 'main' into fix-coord-transform-indexing
dcherian ff6b725
Merge branch 'main' into fix-coord-transform-indexing
keewis 7e2a0ab
assert_equal instead of assert_identical
dcherian 4b21e29
Update properties/test_coordinate_transform.py
dcherian 69252fe
Merge branch 'main' into fix-coord-transform-indexing
dcherian 25fa47a
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,138 @@ | ||
| """Property tests comparing CoordinateTransformIndex to PandasIndex.""" | ||
|
|
||
| import functools | ||
| import operator | ||
| from collections.abc import Hashable | ||
| from typing import Any | ||
|
|
||
| import numpy as np | ||
| import pytest | ||
|
|
||
| pytest.importorskip("hypothesis") | ||
|
|
||
| import hypothesis.strategies as st | ||
| from hypothesis import given | ||
|
|
||
| import xarray as xr | ||
| import xarray.testing.strategies as xrst | ||
| from xarray.core.coordinate_transform import CoordinateTransform | ||
| from xarray.core.indexes import CoordinateTransformIndex | ||
| from xarray.testing import assert_equal | ||
|
|
||
| DATA_VAR_NAME = "_test_data_" | ||
|
|
||
|
|
||
| class IdentityTransform(CoordinateTransform): | ||
| """Identity transform that returns dimension positions as coordinate labels.""" | ||
|
|
||
| def forward(self, dim_positions: dict[str, Any]) -> dict[Hashable, Any]: | ||
| return dim_positions | ||
|
|
||
| def reverse(self, coord_labels: dict[Hashable, Any]) -> dict[str, Any]: | ||
| return coord_labels | ||
|
|
||
| def equals( | ||
| self, other: CoordinateTransform, exclude: frozenset[Hashable] | None = None | ||
| ) -> bool: | ||
| if not isinstance(other, IdentityTransform): | ||
| return False | ||
| return self.dim_size == other.dim_size | ||
|
|
||
|
|
||
| def create_transform_da(sizes: dict[str, int]) -> xr.DataArray: | ||
| """Create a DataArray with IdentityTransform CoordinateTransformIndex.""" | ||
| dims = list(sizes.keys()) | ||
| shape = tuple(sizes.values()) | ||
| data = np.arange(np.prod(shape)).reshape(shape) | ||
|
|
||
| # Create dataset with transform index for each dimension | ||
| ds = xr.Dataset({DATA_VAR_NAME: (dims, data)}) | ||
| coords = functools.reduce( | ||
| operator.or_, | ||
| [ | ||
| xr.Coordinates.from_xindex( | ||
| CoordinateTransformIndex( | ||
| IdentityTransform((dim,), {dim: size}, dtype=np.dtype(np.int64)) | ||
| ) | ||
| ) | ||
| for dim, size in sizes.items() | ||
| ], | ||
| ) | ||
| ds = ds.assign_coords(coords) | ||
| return ds[DATA_VAR_NAME] | ||
|
|
||
|
|
||
| def create_pandas_da(sizes: dict[str, int]) -> xr.DataArray: | ||
| """Create a DataArray with standard PandasIndex (range index).""" | ||
| shape = tuple(sizes.values()) | ||
| data = np.arange(np.prod(shape)).reshape(shape) | ||
| coords = {dim: np.arange(size) for dim, size in sizes.items()} | ||
| return xr.DataArray( | ||
| data, dims=list(sizes.keys()), coords=coords, name=DATA_VAR_NAME | ||
| ) | ||
|
|
||
|
|
||
| @given( | ||
| st.data(), | ||
| xrst.dimension_sizes(min_dims=1, max_dims=3, min_side=1, max_side=5), | ||
| ) | ||
| def test_basic_indexing(data, sizes): | ||
| """Test basic indexing produces identical results for transform and pandas index.""" | ||
| pandas_da = create_pandas_da(sizes) | ||
| transform_da = create_transform_da(sizes) | ||
| idxr = data.draw(xrst.basic_indexers(sizes=sizes)) | ||
| pandas_result = pandas_da.isel(idxr) | ||
| transform_result = transform_da.isel(idxr) | ||
| # TODO: any indexed dim in pandas_result should be an indexed dim in transform_result | ||
| # This requires us to return a new CoordinateTransformIndex from .isel. | ||
| # for dim in pandas_result.xindexes: | ||
| # assert isinstance(transform_result.xindexes[dim], CoordinateTransformIndex) | ||
| assert_equal(pandas_result, transform_result) | ||
|
|
||
| # not supported today | ||
| # pandas_result = pandas_da.sel(idxr) | ||
| # transform_result = transform_da.sel(idxr) | ||
| # assert_identical(pandas_result, transform_result) | ||
|
|
||
|
|
||
| @given( | ||
| st.data(), | ||
| xrst.dimension_sizes(min_dims=1, max_dims=3, min_side=1, max_side=5), | ||
| ) | ||
| def test_outer_indexing(data, sizes): | ||
| """Test outer indexing produces identical results for transform and pandas index.""" | ||
| pandas_da = create_pandas_da(sizes) | ||
| transform_da = create_transform_da(sizes) | ||
| idxr = data.draw(xrst.outer_array_indexers(sizes=sizes, min_dims=1)) | ||
| pandas_result = pandas_da.isel(idxr) | ||
| transform_result = transform_da.isel(idxr) | ||
| assert_equal(pandas_result, transform_result) | ||
|
|
||
| label_idxr = { | ||
| dim: np.arange(pandas_da.sizes[dim])[ind.data] for dim, ind in idxr.items() | ||
| } | ||
| pandas_result = pandas_da.sel(label_idxr) | ||
| transform_result = transform_da.sel(label_idxr, method="nearest") | ||
| assert_equal(pandas_result, transform_result) | ||
|
|
||
|
|
||
| @given( | ||
| st.data(), | ||
| xrst.dimension_sizes(min_dims=2, max_dims=3, min_side=1, max_side=5), | ||
| ) | ||
| def test_vectorized_indexing(data, sizes): | ||
| """Test vectorized indexing produces identical results for transform and pandas index.""" | ||
| pandas_da = create_pandas_da(sizes) | ||
| transform_da = create_transform_da(sizes) | ||
| idxr = data.draw(xrst.vectorized_indexers(sizes=sizes)) | ||
| pandas_result = pandas_da.isel(idxr) | ||
| transform_result = transform_da.isel(idxr) | ||
| assert_equal(pandas_result, transform_result) | ||
|
|
||
| label_idxr = { | ||
| dim: ind.copy(data=np.arange(pandas_da.sizes[dim])[ind.data]) | ||
| for dim, ind in idxr.items() | ||
| } | ||
| pandas_result = pandas_da.sel(label_idxr, method="nearest") | ||
| transform_result = transform_da.sel(label_idxr, method="nearest") | ||
| assert_equal(pandas_result, transform_result) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,66 @@ | ||
| import pytest | ||
|
|
||
| pytest.importorskip("hypothesis") | ||
|
|
||
| import hypothesis.strategies as st | ||
| from hypothesis import given | ||
|
|
||
| import xarray as xr | ||
| import xarray.testing.strategies as xrst | ||
|
|
||
|
|
||
| def _slice_size(s: slice, dim_size: int) -> int: | ||
| """Compute the size of a slice applied to a dimension.""" | ||
| return len(range(*s.indices(dim_size))) | ||
|
|
||
|
|
||
| @given( | ||
| st.data(), | ||
| xrst.variables(dims=xrst.dimension_sizes(min_dims=1, max_dims=4, min_side=1)), | ||
| ) | ||
| def test_basic_indexing(data, var): | ||
| """Test that basic indexers produce expected output shape.""" | ||
| idxr = data.draw(xrst.basic_indexers(sizes=var.sizes)) | ||
| result = var.isel(idxr) | ||
| expected_shape = tuple( | ||
| _slice_size(idxr[d], var.sizes[d]) if d in idxr else var.sizes[d] | ||
| for d in result.dims | ||
| ) | ||
| assert result.shape == expected_shape | ||
|
|
||
|
|
||
| @given( | ||
| st.data(), | ||
| xrst.variables(dims=xrst.dimension_sizes(min_dims=1, max_dims=4, min_side=1)), | ||
| ) | ||
| def test_outer_indexing(data, var): | ||
| """Test that outer array indexers produce expected output shape.""" | ||
| idxr = data.draw(xrst.outer_array_indexers(sizes=var.sizes, min_dims=1)) | ||
| result = var.isel(idxr) | ||
| expected_shape = tuple( | ||
| len(idxr[d]) if d in idxr else var.sizes[d] for d in result.dims | ||
| ) | ||
| assert result.shape == expected_shape | ||
|
|
||
|
|
||
| @given( | ||
| st.data(), | ||
| xrst.variables(dims=xrst.dimension_sizes(min_dims=2, max_dims=4, min_side=1)), | ||
| ) | ||
| def test_vectorized_indexing(data, var): | ||
| """Test that vectorized indexers produce expected output shape.""" | ||
| da = xr.DataArray(var) | ||
| idxr = data.draw(xrst.vectorized_indexers(sizes=var.sizes)) | ||
| result = da.isel(idxr) | ||
|
|
||
| # TODO: this logic works because the dims in idxr don't overlap with da.dims | ||
| # Compute expected shape from result dims | ||
| # Non-indexed dims keep their original size, indexed dims get broadcast size | ||
| broadcast_result = xr.broadcast(*idxr.values()) | ||
| broadcast_sizes = dict( | ||
| zip(broadcast_result[0].dims, broadcast_result[0].shape, strict=True) | ||
| ) | ||
| expected_shape = tuple( | ||
| var.sizes[d] if d in var.sizes else broadcast_sizes[d] for d in result.dims | ||
| ) | ||
| assert result.shape == expected_shape |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.