-
-
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
Open
dcherian
wants to merge
5
commits into
pydata:main
Choose a base branch
from
dcherian:fix-coord-transform-indexing
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+450
−2
Open
Changes from all commits
Commits
Show all changes
5 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 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,105 @@ | ||
| """Property tests comparing CoordinateTransformIndex to PandasIndex.""" | ||
|
|
||
| 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_identical | ||
|
|
||
| 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 {name: dim_positions[name] for name in self.coord_names} | ||
|
|
||
| def reverse(self, coord_labels: dict[Hashable, Any]) -> dict[str, Any]: | ||
| return {dim: coord_labels[dim] for dim in self.dims} | ||
|
|
||
| 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)}) | ||
| for dim, size in sizes.items(): | ||
| transform = IdentityTransform([dim], {dim: size}, dtype=np.dtype(np.int64)) | ||
| index = CoordinateTransformIndex(transform) | ||
| ds = ds.assign_coords(xr.Coordinates.from_xindex(index)) | ||
|
Comment on lines
+48
to
+51
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. not sure if this will make this more readable (it does remove the emulated in-place assignment, at least), but it is possible to collect the coordinate objects and then use |
||
|
|
||
| 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) | ||
| 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_identical(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_identical(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
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
not sure if I'm misunderstanding something here, but there appears to be something wrong: why do we use coordinate names to index
dim_positions(which I think map dimension names to positions), and dimension names to indexcoord_labels?(the example at https://xarray-indexes.readthedocs.io/blocks/transform.html#example-astronomy appears to support my mental model of the coordinate transform)