Skip to content

Commit 033e141

Browse files
authored
better align error (#34)
1 parent 49d61b3 commit 033e141

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

xproj/index.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,10 @@
66
import pyproj
77
import xarray as xr
88
from pyproj.exceptions import CRSError
9+
10+
# TODO: import from xarray.errors when available
11+
# (https://github.com/pydata/xarray/pull/10285)
12+
from xarray import AlignmentError
913
from xarray.indexes import Index
1014

1115

@@ -85,6 +89,15 @@ def equals(self, other: Index, *, exclude: frozenset[Hashable] | None = None) ->
8589
return False
8690
return True
8791

92+
def join(self, other: CRSIndex, how: str = "inner") -> CRSIndex:
93+
# If this method is called during Xarray alignment, it means that the
94+
# equality check failed. Instead of a NotImplementedError we raise a
95+
# ValueError with a nice error message.
96+
raise AlignmentError(
97+
"Objects to align do not have the same CRS\n"
98+
f"first index:\n{self!r}\n\nsecond index:\n{other!r}"
99+
)
100+
88101
def _repr_inline_(self, max_width: int) -> str:
89102
if max_width is None:
90103
max_width = xr.get_options()["display_width"]

xproj/tests/test_index.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,3 +81,19 @@ def test_crsindex_equals() -> None:
8181

8282
idx4 = CRSIndex(pyproj.CRS.from_user_input("epsg:4978"))
8383
assert idx1.equals(idx4) is False
84+
85+
86+
def test_align() -> None:
87+
ds = xr.Dataset(coords={"spatial_ref": 0})
88+
89+
crs1 = pyproj.CRS.from_user_input("epsg:4326")
90+
crs2 = pyproj.CRS.from_user_input("epsg:4978")
91+
92+
ds_crs1 = ds.set_xindex("spatial_ref", CRSIndex, crs=crs1)
93+
ds_crs2 = ds.set_xindex("spatial_ref", CRSIndex, crs=crs2)
94+
95+
with pytest.raises(xr.AlignmentError, match="do not have the same CRS"):
96+
xr.align(ds_crs1, ds_crs2, join="inner")
97+
98+
with pytest.raises(xr.AlignmentError, match="cannot align objects with join='exact'"):
99+
xr.align(ds_crs1, ds_crs2, join="exact")

0 commit comments

Comments
 (0)