From 41d146e9293ea2cc7d750fc2c9dace560f42b7b9 Mon Sep 17 00:00:00 2001 From: Zackary Loevseth <307867630+ZackaryLoevseth@users.noreply.github.com> Date: Tue, 17 Nov 2026 23:21:48 -0800 Subject: [PATCH 1/2] Accept DataArray target grids Closes #64 --- CHANGELOG.md | 5 +++ src/xarray_regrid/regrid.py | 54 +++++++++++++------------ tests/test_dataarray_target.py | 72 ++++++++++++++++++++++++++++++++++ 3 files changed, 107 insertions(+), 24 deletions(-) create mode 100644 tests/test_dataarray_target.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 149c3a2..71b9423 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,11 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/). +## Unreleased + +Fixed: + - Accept DataArray target grids consistently, including unnamed targets with a time coordinate, and reflect this in type annotations and docstrings ([#64](https://github.com/xarray-contrib/xarray-regrid/issues/64)). + ## 0.4.2 (2026-01-28) New contributors: diff --git a/src/xarray_regrid/regrid.py b/src/xarray_regrid/regrid.py index b2ed389..36e7a9d 100644 --- a/src/xarray_regrid/regrid.py +++ b/src/xarray_regrid/regrid.py @@ -27,13 +27,13 @@ def __init__(self, xarray_obj: xr.DataArray | xr.Dataset): def linear( self, - ds_target_grid: xr.Dataset, + ds_target_grid: xr.DataArray | xr.Dataset, time_dim: str | None = "time", ) -> xr.DataArray | xr.Dataset: """Regrid to the coords of the target dataset with linear interpolation. Args: - ds_target_grid: Dataset containing the target coordinates. + ds_target_grid: Dataset or DataArray containing the target coordinates. time_dim: Name of the time dimension. Defaults to "time". Use `None` to force regridding over the time dimension. @@ -46,13 +46,13 @@ def linear( def nearest( self, - ds_target_grid: xr.Dataset, + ds_target_grid: xr.DataArray | xr.Dataset, time_dim: str | None = "time", ) -> xr.DataArray | xr.Dataset: """Regrid to the coords of the target with nearest-neighbor interpolation. Args: - ds_target_grid: Dataset containing the target coordinates. + ds_target_grid: Dataset or DataArray containing the target coordinates. time_dim: Name of the time dimension. Defaults to "time". Use `None` to force regridding over the time dimension. @@ -65,13 +65,13 @@ def nearest( def cubic( self, - ds_target_grid: xr.Dataset, + ds_target_grid: xr.DataArray | xr.Dataset, time_dim: str | None = "time", ) -> xr.DataArray | xr.Dataset: """Regrid to the coords of the target dataset with cubic interpolation. Args: - ds_target_grid: Dataset containing the target coordinates. + ds_target_grid: Dataset or DataArray containing the target coordinates. time_dim: Name of the time dimension. Defaults to "time". Use `None` to force regridding over the time dimension. @@ -84,7 +84,7 @@ def cubic( def conservative( self, - ds_target_grid: xr.Dataset, + ds_target_grid: xr.DataArray | xr.Dataset, latitude_coord: str | None = None, time_dim: str | None = "time", skipna: bool = True, @@ -94,7 +94,7 @@ def conservative( """Regrid to the coords of the target dataset with a conservative scheme. Args: - ds_target_grid: Dataset containing the target coordinates. + ds_target_grid: Dataset or DataArray containing the target coordinates. latitude_coord: Name of the latitude coord, to be used for applying the spherical correction. By default, attempt to infer a latitude coordinate as either "latitude" or "lat". @@ -132,7 +132,7 @@ def conservative( def most_common( self, - ds_target_grid: xr.Dataset, + ds_target_grid: xr.DataArray | xr.Dataset, values: np.ndarray, time_dim: str | None = "time", fill_value: None | Any = None, @@ -147,7 +147,7 @@ def most_common( either of the two. Args: - ds_target_grid: Target grid dataset + ds_target_grid: Dataset or DataArray containing the target coordinates. values: Numpy array containing all labels expected to be in the input data. For example, `np.array([0, 2, 4])`, if the data only contains the values 0, 2 and 4. @@ -184,7 +184,7 @@ def most_common( def least_common( self, - ds_target_grid: xr.Dataset, + ds_target_grid: xr.DataArray | xr.Dataset, values: np.ndarray, time_dim: str | None = "time", fill_value: None | Any = None, @@ -199,7 +199,7 @@ def least_common( either of the two. Args: - ds_target_grid: Target grid dataset + ds_target_grid: Dataset or DataArray containing the target coordinates. values: Numpy array containing all labels expected to be in the input data. For example, `np.array([0, 2, 4])`, if the data only contains the values 0, 2 and 4. @@ -236,7 +236,7 @@ def least_common( def stat( self, - ds_target_grid: xr.Dataset, + ds_target_grid: xr.DataArray | xr.Dataset, method: str, time_dim: str | None = "time", skipna: bool = False, @@ -249,7 +249,7 @@ def stat( https://flox.readthedocs.io/en/latest/aggregations.html Args: - ds_target_grid: Target grid dataset + ds_target_grid: Dataset or DataArray containing the target coordinates. method: One of the following reduction methods: "sum", "mean", "var", "std", "median", "min", or "max". time_dim: Name of the time dimension. Defaults to "time". Use `None` to @@ -273,7 +273,7 @@ def stat( @overload def validate_input( data: xr.Dataset, - ds_target_grid: xr.Dataset, + ds_target_grid: xr.DataArray | xr.Dataset, time_dim: str | None, ) -> xr.Dataset: ... @@ -281,35 +281,41 @@ def validate_input( @overload def validate_input( data: xr.DataArray, - ds_target_grid: xr.Dataset, + ds_target_grid: xr.DataArray | xr.Dataset, time_dim: str | None, ) -> xr.Dataset: ... def validate_input( data: xr.DataArray | xr.Dataset, - ds_target_grid: xr.Dataset, + ds_target_grid: xr.DataArray | xr.Dataset, time_dim: str | None, ) -> xr.Dataset: - if time_dim is not None and time_dim in ds_target_grid.coords: - ds_target_grid = ds_target_grid.isel({time_dim: 0}).reset_coords() + target_grid: xr.Dataset = ( + ds_target_grid.coords.to_dataset() + if isinstance(ds_target_grid, xr.DataArray) + else ds_target_grid + ) - if len(set(data.dims).intersection(set(ds_target_grid.dims))) == 0: + if time_dim is not None and time_dim in target_grid.coords: + target_grid = target_grid.isel({time_dim: 0}).reset_coords() + + if len(set(data.dims).intersection(set(target_grid.dims))) == 0: msg = ( "None of the target dims are in the data:\n" " regridding is not possible.\n" - f"Target dims: {list(ds_target_grid.dims)}\n" + f"Target dims: {list(target_grid.dims)}\n" f"Source dims: {list(data.dims)}" ) raise ValueError(msg) - if len(set(data.coords).intersection(set(ds_target_grid.coords))) == 0: + if len(set(data.coords).intersection(set(target_grid.coords))) == 0: msg = ( "None of the target coords are in the data:\n" " regridding is not possible.\n" - f"Target coords: {ds_target_grid.coords}\n" + f"Target coords: {target_grid.coords}\n" f"Dataset coords: {data.coords}" ) raise ValueError(msg) - return ds_target_grid + return target_grid diff --git a/tests/test_dataarray_target.py b/tests/test_dataarray_target.py new file mode 100644 index 0000000..827cac3 --- /dev/null +++ b/tests/test_dataarray_target.py @@ -0,0 +1,72 @@ +import dask.array as da +import numpy as np +import pytest +import xarray as xr +from dask import delayed + +import xarray_regrid # noqa: F401 + + +@pytest.mark.parametrize( + ("method", "as_dataset"), + [ + (method, as_dataset) + for method in ["linear", "nearest", "cubic", "conservative", "stat"] + for as_dataset in [False, True] + ] + + [("most_common", False), ("least_common", False)], +) +@pytest.mark.parametrize("target_name", [None, "target"]) +@pytest.mark.parametrize("target_has_time", [False, True]) +@pytest.mark.parametrize("chunked", [False, True]) +def test_dataarray_target_matches_dataset( + method, as_dataset, target_name, target_has_time, chunked +): + source = xr.DataArray( + np.tile(np.arange(36).reshape(6, 6) % 3, (2, 1, 1)), + dims=("time", "y", "x"), + coords={"time": [0, 1], "y": np.arange(6), "x": np.arange(6)}, + name="source", + ) + if as_dataset: + source = source.to_dataset() + target = xr.DataArray( + np.full((3, 3), np.nan), + dims=("y", "x"), + coords={"y": [0.5, 2.5, 4.5], "x": [0.5, 2.5, 4.5]}, + name=target_name, + ) + if target_has_time: + target = target.expand_dims(time=[10, 20]) + if chunked: + source = source.chunk({"time": 1}) + target = target.chunk() + original = target.copy(deep=True) + kwargs = {} + if method in ["most_common", "least_common"]: + kwargs["values"] = np.array([0, 1, 2]) + elif method == "stat": + kwargs["method"] = "mean" + regrid = getattr(source.regrid, method) + expected = regrid(target.coords.to_dataset(), **kwargs) + actual = regrid(target, **kwargs) + xr.testing.assert_identical(actual.compute(), expected.compute()) + xr.testing.assert_identical(target, original) + + +def test_dataarray_target_values_are_not_computed(): + @delayed + def unavailable_values(): + msg = "Target data values must not be computed" + raise AssertionError(msg) + + target = xr.DataArray( + da.from_delayed(unavailable_values(), shape=(3,), dtype=float), + dims="x", + coords={"x": [0.5, 2.5, 4.5]}, + ).expand_dims(time=[10, 20]) + source = xr.DataArray(np.ones(6), dims="x", coords={"x": np.arange(6)}) + actual = source.regrid.linear(target).compute() + xr.testing.assert_identical( + actual, xr.DataArray(np.ones(3), dims="x", coords={"x": [0.5, 2.5, 4.5]}) + ) From 6f63fec903a04afbf11fe7ad9dfde241d98e4ee3 Mon Sep 17 00:00:00 2001 From: Zackary Loevseth <307867630+ZackaryLoevseth@users.noreply.github.com> Date: Thu, 19 Nov 2026 09:25:48 -0800 Subject: [PATCH 2/2] Keep target dims without coordinates in validation; test against an independent grid --- src/xarray_regrid/regrid.py | 8 +++-- tests/test_dataarray_target.py | 53 +++++++++++++++++++++++++++++++++- 2 files changed, 58 insertions(+), 3 deletions(-) diff --git a/src/xarray_regrid/regrid.py b/src/xarray_regrid/regrid.py index 36e7a9d..c5e7f40 100644 --- a/src/xarray_regrid/regrid.py +++ b/src/xarray_regrid/regrid.py @@ -291,6 +291,9 @@ def validate_input( ds_target_grid: xr.DataArray | xr.Dataset, time_dim: str | None, ) -> xr.Dataset: + # Read the dims from the target itself: .coords.to_dataset() drops the dims + # of a DataArray that have no coordinate. + target_dims = list(ds_target_grid.dims) target_grid: xr.Dataset = ( ds_target_grid.coords.to_dataset() if isinstance(ds_target_grid, xr.DataArray) @@ -299,12 +302,13 @@ def validate_input( if time_dim is not None and time_dim in target_grid.coords: target_grid = target_grid.isel({time_dim: 0}).reset_coords() + target_dims = [dim for dim in target_dims if dim != time_dim] - if len(set(data.dims).intersection(set(target_grid.dims))) == 0: + if len(set(data.dims).intersection(set(target_dims))) == 0: msg = ( "None of the target dims are in the data:\n" " regridding is not possible.\n" - f"Target dims: {list(target_grid.dims)}\n" + f"Target dims: {target_dims}\n" f"Source dims: {list(data.dims)}" ) raise ValueError(msg) diff --git a/tests/test_dataarray_target.py b/tests/test_dataarray_target.py index 827cac3..ef235c8 100644 --- a/tests/test_dataarray_target.py +++ b/tests/test_dataarray_target.py @@ -30,6 +30,8 @@ def test_dataarray_target_matches_dataset( ) if as_dataset: source = source.to_dataset() + # The same grid, built once as a Dataset and once as a DataArray. + grid = xr.Dataset(coords={"y": [0.5, 2.5, 4.5], "x": [0.5, 2.5, 4.5]}) target = xr.DataArray( np.full((3, 3), np.nan), dims=("y", "x"), @@ -37,6 +39,7 @@ def test_dataarray_target_matches_dataset( name=target_name, ) if target_has_time: + grid = grid.assign_coords(time=[10, 20]) target = target.expand_dims(time=[10, 20]) if chunked: source = source.chunk({"time": 1}) @@ -48,12 +51,60 @@ def test_dataarray_target_matches_dataset( elif method == "stat": kwargs["method"] = "mean" regrid = getattr(source.regrid, method) - expected = regrid(target.coords.to_dataset(), **kwargs) + expected = regrid(grid, **kwargs) actual = regrid(target, **kwargs) xr.testing.assert_identical(actual.compute(), expected.compute()) xr.testing.assert_identical(target, original) +@pytest.mark.parametrize("method", ["linear", "conservative"]) +def test_unnamed_dataarray_target_with_time_values(method): + # The source only varies along x (0, 1, 2, 0, 1, 2), so the values on the + # target grid can be worked out by hand. + source = xr.DataArray( + np.tile(np.arange(6.0) % 3, (2, 6, 1)), + dims=("time", "y", "x"), + coords={"time": [0, 1], "y": np.arange(6), "x": np.arange(6)}, + ) + target = xr.DataArray( + np.full((3, 3), np.nan), + dims=("y", "x"), + coords={"y": [0.5, 2.5, 4.5], "x": [0.5, 2.5, 4.5]}, + ).expand_dims(time=[10, 20]) + expected = xr.DataArray( + np.tile([0.5, 1.0, 1.5], (2, 3, 1)), + dims=("time", "y", "x"), + coords={"time": [0, 1], "y": [0.5, 2.5, 4.5], "x": [0.5, 2.5, 4.5]}, + ) + xr.testing.assert_allclose(getattr(source.regrid, method)(target), expected) + + +def test_dataarray_target_without_coords_reports_missing_coords(): + source = xr.DataArray( + np.ones((6, 6)), + dims=("y", "x"), + coords={"y": np.arange(6), "x": np.arange(6)}, + ) + target = xr.DataArray(np.ones((3, 3)), dims=("y", "x")) + with pytest.raises(ValueError, match="None of the target coords are in the data"): + source.regrid.linear(target) + + +def test_dataarray_target_dim_without_coord_matches_dataset(): + source = xr.DataArray( + np.arange(36.0).reshape(6, 6), + dims=("y", "x"), + coords={"y": np.arange(6), "x": np.arange(6)}, + ) + target = xr.DataArray( + np.ones((3, 3, 2)), + dims=("y", "x", "bnds"), + coords={"y": [0.5, 2.5, 4.5], "x": [0.5, 2.5, 4.5]}, + ) + expected = source.regrid.linear(target.to_dataset(name="target")) + xr.testing.assert_identical(source.regrid.linear(target), expected) + + def test_dataarray_target_values_are_not_computed(): @delayed def unavailable_values():