Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
60 changes: 35 additions & 25 deletions src/xarray_regrid/regrid.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -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.

Expand All @@ -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.

Expand All @@ -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,
Expand All @@ -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".
Expand Down Expand Up @@ -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,
Expand All @@ -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.
Expand Down Expand Up @@ -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,
Expand All @@ -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.
Expand Down Expand Up @@ -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,
Expand All @@ -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
Expand All @@ -273,43 +273,53 @@ 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: ...


@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()

if len(set(data.dims).intersection(set(ds_target_grid.dims))) == 0:
# 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()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

.coords.to_dataset() causes dims without coords to be dropped. This can cause users to get an incorrect error later. Maybe it would be good to check that ds_target_grid has no dims without coords 🤔

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch. A target with dims but no coordinates got "None of the target dims are in the data … Target dims: []" here, where main (and the same grid as a Dataset) reports the missing coords. The dims check now reads the dims from the target before the conversion, so those errors are the same as on main, with a test.

I didn't add a hard check, because DataArray targets with a dim without a coordinate (an extra bnds-like dim, or time without a coordinate) regrid fine on main today, the same as the Dataset holding them, and DataArray.interp_like skips such dims too. Happy to add the check if you prefer it.

if isinstance(ds_target_grid, xr.DataArray)
else ds_target_grid
)

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_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: {target_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
123 changes: 123 additions & 0 deletions tests/test_dataarray_target.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
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()
# 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"),
coords={"y": [0.5, 2.5, 4.5], "x": [0.5, 2.5, 4.5]},
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})
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(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():
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]})
)