File: test_coordinates.py

package info (click to toggle)
python-xarray 2025.10.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 11,652 kB
  • sloc: python: 117,125; makefile: 260; sh: 47
file content (298 lines) | stat: -rw-r--r-- 10,999 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
from __future__ import annotations

from collections.abc import Mapping

import numpy as np
import pandas as pd
import pytest

from xarray.core.coordinates import Coordinates
from xarray.core.dataarray import DataArray
from xarray.core.dataset import Dataset
from xarray.core.indexes import Index, PandasIndex, PandasMultiIndex
from xarray.core.variable import IndexVariable, Variable
from xarray.structure.alignment import align
from xarray.tests import assert_identical, source_ndarray


class TestCoordinates:
    def test_init_noindex(self) -> None:
        coords = Coordinates(coords={"foo": ("x", [0, 1, 2])})
        expected = Dataset(coords={"foo": ("x", [0, 1, 2])})
        assert_identical(coords.to_dataset(), expected)

    def test_init_default_index(self) -> None:
        coords = Coordinates(coords={"x": [1, 2]})
        expected = Dataset(coords={"x": [1, 2]})
        assert_identical(coords.to_dataset(), expected)
        assert "x" in coords.xindexes

    @pytest.mark.filterwarnings("error:IndexVariable")
    def test_init_no_default_index(self) -> None:
        # dimension coordinate with no default index (explicit)
        coords = Coordinates(coords={"x": [1, 2]}, indexes={})
        assert "x" not in coords.xindexes
        assert not isinstance(coords["x"], IndexVariable)

    def test_init_from_coords(self) -> None:
        expected = Dataset(coords={"foo": ("x", [0, 1, 2])})
        coords = Coordinates(coords=expected.coords)
        assert_identical(coords.to_dataset(), expected)

        # test variables copied
        assert coords.variables["foo"] is not expected.variables["foo"]

        # test indexes are extracted
        expected = Dataset(coords={"x": [0, 1, 2]})
        coords = Coordinates(coords=expected.coords)
        assert_identical(coords.to_dataset(), expected)
        assert expected.xindexes == coords.xindexes

        # coords + indexes not supported
        with pytest.raises(
            ValueError, match=r"passing both.*Coordinates.*indexes.*not allowed"
        ):
            coords = Coordinates(
                coords=expected.coords, indexes={"x": PandasIndex([0, 1, 2], "x")}
            )

    def test_init_empty(self) -> None:
        coords = Coordinates()
        assert len(coords) == 0

    def test_init_index_error(self) -> None:
        idx = PandasIndex([1, 2, 3], "x")
        with pytest.raises(ValueError, match="no coordinate variables found"):
            Coordinates(indexes={"x": idx})

        with pytest.raises(TypeError, match=r".* is not an `xarray.indexes.Index`"):
            Coordinates(
                coords={"x": ("x", [1, 2, 3])},
                indexes={"x": "not_an_xarray_index"},  # type: ignore[dict-item]
            )

    def test_init_dim_sizes_conflict(self) -> None:
        with pytest.raises(ValueError):
            Coordinates(coords={"foo": ("x", [1, 2]), "bar": ("x", [1, 2, 3, 4])})

    def test_from_xindex(self) -> None:
        idx = PandasIndex([1, 2, 3], "x")
        coords = Coordinates.from_xindex(idx)

        assert isinstance(coords.xindexes["x"], PandasIndex)
        assert coords.xindexes["x"].equals(idx)

        expected = PandasIndex(idx, "x").create_variables()
        assert list(coords.variables) == list(expected)
        assert_identical(expected["x"], coords.variables["x"])

    def test_from_xindex_error(self) -> None:
        class CustomIndexNoCoordsGenerated(Index):
            def create_variables(self, variables: Mapping | None = None):
                return {}

        idx = CustomIndexNoCoordsGenerated()

        with pytest.raises(ValueError, match=r".*index.*did not create any coordinate"):
            Coordinates.from_xindex(idx)

    def test_from_pandas_multiindex(self) -> None:
        midx = pd.MultiIndex.from_product([["a", "b"], [1, 2]], names=("one", "two"))
        coords = Coordinates.from_pandas_multiindex(midx, "x")

        assert isinstance(coords.xindexes["x"], PandasMultiIndex)
        assert coords.xindexes["x"].index.equals(midx)
        assert coords.xindexes["x"].dim == "x"

        expected = PandasMultiIndex(midx, "x").create_variables()
        assert list(coords.variables) == list(expected)
        for name in ("x", "one", "two"):
            assert_identical(expected[name], coords.variables[name])

    @pytest.mark.filterwarnings("ignore:return type")
    def test_dims(self) -> None:
        coords = Coordinates(coords={"x": [0, 1, 2]})
        assert set(coords.dims) == {"x"}

    def test_sizes(self) -> None:
        coords = Coordinates(coords={"x": [0, 1, 2]})
        assert coords.sizes == {"x": 3}

    def test_dtypes(self) -> None:
        coords = Coordinates(coords={"x": [0, 1, 2]})
        assert coords.dtypes == {"x": int}

    def test_getitem(self) -> None:
        coords = Coordinates(coords={"x": [0, 1, 2]})
        assert_identical(
            coords["x"],
            DataArray([0, 1, 2], coords={"x": [0, 1, 2]}, name="x"),
        )

    def test_delitem(self) -> None:
        coords = Coordinates(coords={"x": [0, 1, 2]})
        del coords["x"]
        assert "x" not in coords

        with pytest.raises(
            KeyError, match="'nonexistent' is not in coordinate variables"
        ):
            del coords["nonexistent"]

    def test_update(self) -> None:
        coords = Coordinates(coords={"x": [0, 1, 2]})

        coords.update({"y": ("y", [4, 5, 6])})
        assert "y" in coords
        assert "y" in coords.xindexes
        expected = DataArray([4, 5, 6], coords={"y": [4, 5, 6]}, name="y")
        assert_identical(coords["y"], expected)

    def test_equals(self):
        coords = Coordinates(coords={"x": [0, 1, 2]})

        assert coords.equals(coords)
        # Test with a different Coordinates object instead of a string
        other_coords = Coordinates(coords={"x": [3, 4, 5]})
        assert not coords.equals(other_coords)

    def test_identical(self):
        coords = Coordinates(coords={"x": [0, 1, 2]})

        assert coords.identical(coords)
        # Test with a different Coordinates object instead of a string
        other_coords = Coordinates(coords={"x": [3, 4, 5]})
        assert not coords.identical(other_coords)

    def test_assign(self) -> None:
        coords = Coordinates(coords={"x": [0, 1, 2]})
        expected = Coordinates(coords={"x": [0, 1, 2], "y": [3, 4]})

        actual = coords.assign(y=[3, 4])
        assert_identical(actual, expected)

        actual = coords.assign({"y": [3, 4]})
        assert_identical(actual, expected)

    def test_copy(self) -> None:
        no_index_coords = Coordinates({"foo": ("x", [1, 2, 3])})
        copied = no_index_coords.copy()
        assert_identical(no_index_coords, copied)
        v0 = no_index_coords.variables["foo"]
        v1 = copied.variables["foo"]
        assert v0 is not v1
        assert source_ndarray(v0.data) is source_ndarray(v1.data)

        deep_copied = no_index_coords.copy(deep=True)
        assert_identical(no_index_coords.to_dataset(), deep_copied.to_dataset())
        v0 = no_index_coords.variables["foo"]
        v1 = deep_copied.variables["foo"]
        assert v0 is not v1
        assert source_ndarray(v0.data) is not source_ndarray(v1.data)

    def test_align(self) -> None:
        coords = Coordinates(coords={"x": [0, 1, 2]})

        left = coords

        # test Coordinates._reindex_callback
        right = coords.to_dataset().isel(x=[0, 1]).coords
        left2, right2 = align(left, right, join="inner")
        assert_identical(left2, right2)

        # test Coordinates._overwrite_indexes
        right.update({"x": ("x", [4, 5, 6])})
        left2, right2 = align(left, right, join="override")
        assert_identical(left2, left)
        assert_identical(left2, right2)

    def test_dataset_from_coords_with_multidim_var_same_name(self):
        # regression test for GH #8883
        var = Variable(data=np.arange(6).reshape(2, 3), dims=["x", "y"])
        coords = Coordinates(coords={"x": var}, indexes={})
        ds = Dataset(coords=coords)
        assert ds.coords["x"].dims == ("x", "y")

    def test_drop_vars(self):
        coords = Coordinates(
            coords={
                "x": Variable("x", range(3)),
                "y": Variable("y", list("ab")),
                "a": Variable(["x", "y"], np.arange(6).reshape(3, 2)),
            },
            indexes={},
        )

        actual = coords.drop_vars("x")
        assert isinstance(actual, Coordinates)
        assert set(actual.variables) == {"a", "y"}

        actual = coords.drop_vars(["x", "y"])
        assert isinstance(actual, Coordinates)
        assert set(actual.variables) == {"a"}

    def test_drop_dims(self) -> None:
        coords = Coordinates(
            coords={
                "x": Variable("x", range(3)),
                "y": Variable("y", list("ab")),
                "a": Variable(["x", "y"], np.arange(6).reshape(3, 2)),
            },
            indexes={},
        )

        actual = coords.drop_dims("x")
        assert isinstance(actual, Coordinates)
        assert set(actual.variables) == {"y"}

        actual = coords.drop_dims(["x", "y"])
        assert isinstance(actual, Coordinates)
        assert set(actual.variables) == set()

    def test_rename_dims(self) -> None:
        coords = Coordinates(
            coords={
                "x": Variable("x", range(3)),
                "y": Variable("y", list("ab")),
                "a": Variable(["x", "y"], np.arange(6).reshape(3, 2)),
            },
            indexes={},
        )

        actual = coords.rename_dims({"x": "X"})
        assert isinstance(actual, Coordinates)
        assert set(actual.dims) == {"X", "y"}
        assert set(actual.variables) == {"a", "x", "y"}

        actual = coords.rename_dims({"x": "u", "y": "v"})
        assert isinstance(actual, Coordinates)
        assert set(actual.dims) == {"u", "v"}
        assert set(actual.variables) == {"a", "x", "y"}

    def test_rename_vars(self) -> None:
        coords = Coordinates(
            coords={
                "x": Variable("x", range(3)),
                "y": Variable("y", list("ab")),
                "a": Variable(["x", "y"], np.arange(6).reshape(3, 2)),
            },
            indexes={},
        )

        actual = coords.rename_vars({"x": "X"})
        assert isinstance(actual, Coordinates)
        assert set(actual.dims) == {"x", "y"}
        assert set(actual.variables) == {"a", "X", "y"}

        actual = coords.rename_vars({"x": "u", "y": "v"})
        assert isinstance(actual, Coordinates)
        assert set(actual.dims) == {"x", "y"}
        assert set(actual.variables) == {"a", "u", "v"}

    def test_operator_merge(self) -> None:
        coords1 = Coordinates({"x": ("x", [0, 1, 2])})
        coords2 = Coordinates({"y": ("y", [3, 4, 5])})
        expected = Dataset(coords={"x": [0, 1, 2], "y": [3, 4, 5]})

        actual = coords1 | coords2
        assert_identical(Dataset(coords=actual), expected)