|
| 1 | +"""Property tests comparing CoordinateTransformIndex to PandasIndex.""" |
| 2 | + |
| 3 | +import functools |
| 4 | +import operator |
| 5 | +from collections.abc import Hashable |
| 6 | +from typing import Any |
| 7 | + |
| 8 | +import numpy as np |
| 9 | +import pytest |
| 10 | + |
| 11 | +pytest.importorskip("hypothesis") |
| 12 | + |
| 13 | +import hypothesis.strategies as st |
| 14 | +from hypothesis import given |
| 15 | + |
| 16 | +import xarray as xr |
| 17 | +import xarray.testing.strategies as xrst |
| 18 | +from xarray.core.coordinate_transform import CoordinateTransform |
| 19 | +from xarray.core.indexes import CoordinateTransformIndex |
| 20 | +from xarray.testing import assert_equal |
| 21 | + |
| 22 | +DATA_VAR_NAME = "_test_data_" |
| 23 | + |
| 24 | + |
| 25 | +class IdentityTransform(CoordinateTransform): |
| 26 | + """Identity transform that returns dimension positions as coordinate labels.""" |
| 27 | + |
| 28 | + def forward(self, dim_positions: dict[str, Any]) -> dict[Hashable, Any]: |
| 29 | + return dim_positions |
| 30 | + |
| 31 | + def reverse(self, coord_labels: dict[Hashable, Any]) -> dict[str, Any]: |
| 32 | + return coord_labels |
| 33 | + |
| 34 | + def equals( |
| 35 | + self, other: CoordinateTransform, exclude: frozenset[Hashable] | None = None |
| 36 | + ) -> bool: |
| 37 | + if not isinstance(other, IdentityTransform): |
| 38 | + return False |
| 39 | + return self.dim_size == other.dim_size |
| 40 | + |
| 41 | + |
| 42 | +def create_transform_da(sizes: dict[str, int]) -> xr.DataArray: |
| 43 | + """Create a DataArray with IdentityTransform CoordinateTransformIndex.""" |
| 44 | + dims = list(sizes.keys()) |
| 45 | + shape = tuple(sizes.values()) |
| 46 | + data = np.arange(np.prod(shape)).reshape(shape) |
| 47 | + |
| 48 | + # Create dataset with transform index for each dimension |
| 49 | + ds = xr.Dataset({DATA_VAR_NAME: (dims, data)}) |
| 50 | + indexes = [ |
| 51 | + xr.Coordinates.from_xindex( |
| 52 | + CoordinateTransformIndex( |
| 53 | + IdentityTransform((dim,), {dim: size}, dtype=np.dtype(np.int64)) |
| 54 | + ) |
| 55 | + ) |
| 56 | + for dim, size in sizes.items() |
| 57 | + ] |
| 58 | + coords = functools.reduce(operator.or_, indexes) |
| 59 | + return ds.assign_coords(coords).get(DATA_VAR_NAME) |
| 60 | + |
| 61 | + |
| 62 | +def create_pandas_da(sizes: dict[str, int]) -> xr.DataArray: |
| 63 | + """Create a DataArray with standard PandasIndex (range index).""" |
| 64 | + shape = tuple(sizes.values()) |
| 65 | + data = np.arange(np.prod(shape)).reshape(shape) |
| 66 | + coords = {dim: np.arange(size) for dim, size in sizes.items()} |
| 67 | + return xr.DataArray( |
| 68 | + data, dims=list(sizes.keys()), coords=coords, name=DATA_VAR_NAME |
| 69 | + ) |
| 70 | + |
| 71 | + |
| 72 | +@given( |
| 73 | + st.data(), |
| 74 | + xrst.dimension_sizes(min_dims=1, max_dims=3, min_side=1, max_side=5), |
| 75 | +) |
| 76 | +def test_basic_indexing(data, sizes): |
| 77 | + """Test basic indexing produces identical results for transform and pandas index.""" |
| 78 | + pandas_da = create_pandas_da(sizes) |
| 79 | + transform_da = create_transform_da(sizes) |
| 80 | + idxr = data.draw(xrst.basic_indexers(sizes=sizes)) |
| 81 | + pandas_result = pandas_da.isel(idxr) |
| 82 | + transform_result = transform_da.isel(idxr) |
| 83 | + # TODO: any indexed dim in pandas_result should be an indexed dim in transform_result |
| 84 | + # This requires us to return a new CoordinateTransformIndex from .isel. |
| 85 | + # for dim in pandas_result.xindexes: |
| 86 | + # assert isinstance(transform_result.xindexes[dim], CoordinateTransformIndex) |
| 87 | + assert_equal(pandas_result, transform_result) |
| 88 | + |
| 89 | + # not supported today |
| 90 | + # pandas_result = pandas_da.sel(idxr) |
| 91 | + # transform_result = transform_da.sel(idxr) |
| 92 | + # assert_identical(pandas_result, transform_result) |
| 93 | + |
| 94 | + |
| 95 | +@given( |
| 96 | + st.data(), |
| 97 | + xrst.dimension_sizes(min_dims=1, max_dims=3, min_side=1, max_side=5), |
| 98 | +) |
| 99 | +def test_outer_indexing(data, sizes): |
| 100 | + """Test outer indexing produces identical results for transform and pandas index.""" |
| 101 | + pandas_da = create_pandas_da(sizes) |
| 102 | + transform_da = create_transform_da(sizes) |
| 103 | + idxr = data.draw(xrst.outer_array_indexers(sizes=sizes, min_dims=1)) |
| 104 | + pandas_result = pandas_da.isel(idxr) |
| 105 | + transform_result = transform_da.isel(idxr) |
| 106 | + assert_equal(pandas_result, transform_result) |
| 107 | + |
| 108 | + label_idxr = { |
| 109 | + dim: np.arange(pandas_da.sizes[dim])[ind.data] for dim, ind in idxr.items() |
| 110 | + } |
| 111 | + pandas_result = pandas_da.sel(label_idxr) |
| 112 | + transform_result = transform_da.sel(label_idxr, method="nearest") |
| 113 | + assert_equal(pandas_result, transform_result) |
| 114 | + |
| 115 | + |
| 116 | +@given( |
| 117 | + st.data(), |
| 118 | + xrst.dimension_sizes(min_dims=2, max_dims=3, min_side=1, max_side=5), |
| 119 | +) |
| 120 | +def test_vectorized_indexing(data, sizes): |
| 121 | + """Test vectorized indexing produces identical results for transform and pandas index.""" |
| 122 | + pandas_da = create_pandas_da(sizes) |
| 123 | + transform_da = create_transform_da(sizes) |
| 124 | + idxr = data.draw(xrst.vectorized_indexers(sizes=sizes)) |
| 125 | + pandas_result = pandas_da.isel(idxr) |
| 126 | + transform_result = transform_da.isel(idxr) |
| 127 | + assert_equal(pandas_result, transform_result) |
| 128 | + |
| 129 | + label_idxr = { |
| 130 | + dim: ind.copy(data=np.arange(pandas_da.sizes[dim])[ind.data]) |
| 131 | + for dim, ind in idxr.items() |
| 132 | + } |
| 133 | + pandas_result = pandas_da.sel(label_idxr, method="nearest") |
| 134 | + transform_result = transform_da.sel(label_idxr, method="nearest") |
| 135 | + assert_equal(pandas_result, transform_result) |
0 commit comments