diff --git a/doc/whats-new.rst b/doc/whats-new.rst index 9e31298349f..2f2d65ff569 100644 --- a/doc/whats-new.rst +++ b/doc/whats-new.rst @@ -557,6 +557,12 @@ Bug Fixes - Fix numpy ufuncs and :py:func:`apply_ufunc` raising for a :py:class:`DataArray` with a coordinate or attribute named ``"keys"`` (:pull:`11908`). By `Pieter Eendebak `_. +- :py:meth:`Dataset.interp` and :py:meth:`DataArray.interp` work along + dimensions with a single coordinate value: a new coordinate equal to it gets + the data there, and other new coordinates are out of range. Previously this + often returned NaN with a ``RuntimeWarning`` from SciPy, or raised a + ``ValueError`` (:issue:`10747`). + By `Vanshaj Poonia `_. - :py:meth:`Dataset.to_netcdf` and :py:meth:`DataArray.to_netcdf` accept ``format="NETCDF3_64BIT_DATA"`` (CDF5) without an ``engine`` and use the netCDF4 engine, the only one that writes it. Previously this raised diff --git a/xarray/core/dataarray.py b/xarray/core/dataarray.py index 4cdab7f55a6..c12522700dd 100644 --- a/xarray/core/dataarray.py +++ b/xarray/core/dataarray.py @@ -2538,6 +2538,10 @@ def interp( - When interpolating along multiple dimensions with methods `linear` and `nearest`, the process attempts to decompose the interpolation into independent interpolations along one dimension at a time. + - Along a dimension with a single coordinate value, a new coordinate equal to + that value gets the data there, and any other new coordinate is out of + range. Extrapolating, e.g. with ``fill_value="extrapolate"``, repeats the + data there. - For Dask arrays, the chunks along the interpolated dimensions are merged into a single chunk. With methods `linear` and `nearest`, the data is first subset to the range of the new coordinates, so only the chunks that diff --git a/xarray/core/dataset.py b/xarray/core/dataset.py index 942fd39699c..9817232f211 100644 --- a/xarray/core/dataset.py +++ b/xarray/core/dataset.py @@ -4036,6 +4036,10 @@ def interp( - When interpolating along multiple dimensions with methods `linear` and `nearest`, the process attempts to decompose the interpolation into independent interpolations along one dimension at a time. + - Along a dimension with a single coordinate value, a new coordinate equal to + that value gets the data there, and any other new coordinate is out of + range. Extrapolating, e.g. with ``fill_value="extrapolate"``, repeats the + data there. - For Dask arrays, the chunks along the interpolated dimensions are merged into a single chunk. With methods `linear` and `nearest`, the data is first subset to the range of the new coordinates, so only the chunks that diff --git a/xarray/core/missing.py b/xarray/core/missing.py index 49960e32379..1d58d7e16e7 100644 --- a/xarray/core/missing.py +++ b/xarray/core/missing.py @@ -612,6 +612,68 @@ def _floatize_x( return x, new_x +def _interp_single_point( + var: Variable, + indexes_coords: SourceDest, + method: InterpOptions, + kwargs: dict[str, Any], +) -> Variable: + """Interpolate along the dimensions that have a single source point (GH10747). + + A new coordinate equal to that point gets its data, any other is out of range. + """ + single = [dim for dim, (x, _) in indexes_coords.items() if x.size == 1] + result = interp( + var.isel(dict.fromkeys(single, 0)), + {dim: xs for dim, xs in indexes_coords.items() if dim not in single}, + method, + **kwargs, + ) + if not issubclass(result.dtype.type, np.inexact): + result = result.astype(float) + + fill_value = kwargs.get("fill_value") + # a constant is the only curve through one point + extrapolate = ( + method in ["barycentric", "krogh"] + or bool(kwargs.get("extrapolate")) + or (isinstance(fill_value, str) and fill_value == "extrapolate") + ) + if fill_value is None or isinstance(fill_value, str): + below = above = np.nan + elif isinstance(fill_value, tuple) and len(fill_value) == 2: + below, above = fill_value + else: + below = above = fill_value + # like scipy, an array fill value broadcasts against the other dimensions + other_dims = [d for d in var.dims if d not in indexes_coords] + below_fill, above_fill = ( + Variable(other_dims[len(other_dims) - np.ndim(v) :], v) for v in (below, above) + ) + + for dim in single: + x, new_x = indexes_coords[dim] + point = x.data[0] + if not extrapolate: + off_point = (new_x != point) & new_x.notnull() + if kwargs.get("bounds_error") and bool(off_point.any()): + raise ValueError( + f"A new coordinate of {dim!r} is out of the interpolation " + f"range, which is the single point {x.values[0]}." + ) + fill = below_fill.where(new_x < point, above_fill) + result = result.where(new_x == point, fill) + result = result.where(new_x.notnull()) + + out_dims: OrderedSet = OrderedSet() + for d in var.dims: + if d in indexes_coords: + out_dims.update(indexes_coords[d][1].dims) + else: + out_dims.add(d) + return result.transpose(*out_dims) + + def interp( var: Variable, indexes_coords: SourceDest, @@ -646,6 +708,9 @@ def interp( if not indexes_coords: return var.copy() + if any(x.size == 1 for x, _ in indexes_coords.values()): + return _interp_single_point(var, indexes_coords, method, kwargs) + result = var if method in ["linear", "nearest", "slinear"]: diff --git a/xarray/tests/test_interp.py b/xarray/tests/test_interp.py index 0dfa9ae8d2f..61005953cea 100644 --- a/xarray/tests/test_interp.py +++ b/xarray/tests/test_interp.py @@ -1328,3 +1328,101 @@ def test_interp_vectorized_empty_dim(use_dask: bool) -> None: actual = da.interp(z=new_z) expected = xr.DataArray(np.zeros((0, 3)), dims=("t", "r"), coords={"z": new_z}) assert_identical(actual.compute(), expected) + + +@requires_scipy +@pytest.mark.filterwarnings("error") +@pytest.mark.parametrize("method", ["linear", "nearest", "cubic", "pchip"]) +def test_interp_single_point(method: InterpOptions, use_dask: bool) -> None: + # GH10747: the interpolants need two points or more along each dimension + da = xr.DataArray( + [[4.0, 7.0, 9.0, 12.0, 15.0]], + dims=("x", "y"), + coords={"x": [0.3], "y": [0, 1, 2, 3, 4]}, + ) + if use_dask: + da = da.chunk() + + with raise_if_dask_computes(): + actual = da.interp(x=[-1.0, 0.3, 0.8, np.nan], y=[1, 3], method=method) + expected = xr.DataArray( + [[np.nan, np.nan], [7.0, 12.0], [np.nan, np.nan], [np.nan, np.nan]], + dims=("x", "y"), + coords={"x": [-1.0, 0.3, 0.8, np.nan], "y": [1, 3]}, + ) + # cubic can be off by one ulp + assert_allclose(actual.compute(), expected) + + # the dimension order of the data is kept + actual = da.transpose().interp(x=[0.3], y=[1, 3], method=method) + assert_allclose(actual.compute(), expected.isel(x=[1]).transpose()) + + +@requires_scipy +@pytest.mark.filterwarnings("error") +def test_interp_single_point_scalar() -> None: + # GH10747 + da = xr.DataArray([[4, 7, 9]], dims=("x", "y"), coords={"x": [0.3], "y": [0, 1, 2]}) + actual = da.interp(x=0.3, y=1.5) + assert_identical(actual, xr.DataArray(8.0, coords={"x": 0.3, "y": 1.5})) + + actual = da.interp(x=0.3) + expected = xr.DataArray( + [4.0, 7.0, 9.0], dims="y", coords={"x": 0.3, "y": [0, 1, 2]} + ) + assert_identical(actual, expected) + + actual = da.interp(x=0.8, y=1.5) + assert np.isnan(actual.item()) + + +@requires_scipy +@pytest.mark.parametrize( + "method, kwargs, below, above", + [ + ("linear", {"fill_value": -1.0}, [-1.0, -1.0], [-1.0, -1.0]), + ("linear", {"fill_value": (-1.0, -3.0)}, [-1.0, -1.0], [-3.0, -3.0]), + # array fill values broadcast against y, and only a tuple splits them + ( + "linear", + {"fill_value": (np.array([-1.0, -3.0]), np.array([-2.0, -4.0]))}, + [-1.0, -3.0], + [-2.0, -4.0], + ), + ("linear", {"fill_value": [-1.0, -3.0]}, [-1.0, -3.0], [-1.0, -3.0]), + ("linear", {"fill_value": np.array([-1.0, -3.0])}, [-1.0, -3.0], [-1.0, -3.0]), + ("linear", {"fill_value": "extrapolate"}, [2.0, 5.0], [2.0, 5.0]), + ("pchip", {"extrapolate": True}, [2.0, 5.0], [2.0, 5.0]), + ("krogh", {}, [2.0, 5.0], [2.0, 5.0]), + ], +) +def test_interp_single_point_out_of_range( + method: InterpOptions, + kwargs: dict, + below: list[float], + above: list[float], + use_dask: bool, +) -> None: + # GH10747: other new coordinates are out of range, and the only way to + # extrapolate from one point is a constant + da = xr.DataArray([[2.0, 5.0]], dims=("x", "y"), coords={"x": [6], "y": [0, 1]}) + if use_dask: + da = da.chunk() + new_x = [4.0, 6.0, 8.0, np.nan] + with raise_if_dask_computes(): + actual = da.interp(x=new_x, method=method, kwargs=kwargs) + expected = xr.DataArray( + [below, [2.0, 5.0], above, [np.nan, np.nan]], + dims=("x", "y"), + coords={"x": new_x, "y": [0, 1]}, + ) + assert_identical(actual.compute(), expected) + + +@requires_scipy +def test_interp_single_point_bounds_error() -> None: + da = xr.DataArray([[2.0, 5.0]], dims=("x", "y"), coords={"x": [6], "y": [0, 1]}) + actual = da.interp(x=[6.0], kwargs={"bounds_error": True}) + assert_identical(actual, da.astype(float).assign_coords(x=[6.0])) + with pytest.raises(ValueError, match="single point 6"): + da.interp(x=[6.0, 7.0], kwargs={"bounds_error": True})