From e1aabf9b8124832c23de3900875953ef86415c79 Mon Sep 17 00:00:00 2001 From: juliettelavoie Date: Thu, 4 Apr 2024 13:54:20 -0400 Subject: [PATCH 1/2] handle all nan case --- xclim/sdba/loess.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/xclim/sdba/loess.py b/xclim/sdba/loess.py index d98c4ff68..2a527d993 100644 --- a/xclim/sdba/loess.py +++ b/xclim/sdba/loess.py @@ -95,6 +95,8 @@ def _loess_nb( out = np.full(x.size, np.NaN) y = y[~nan] x = x[~nan] + if x.size == 0: + return out n = x.size yest = np.zeros(n) From f7acea38c1d529505c834f83318fb2074075085e Mon Sep 17 00:00:00 2001 From: juliettelavoie Date: Thu, 4 Apr 2024 14:16:17 -0400 Subject: [PATCH 2/2] add test --- CHANGES.rst | 3 ++- tests/test_sdba/test_loess.py | 21 +++++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/CHANGES.rst b/CHANGES.rst index fd17a8049..8fe365690 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -4,7 +4,7 @@ Changelog v0.49.0 (unreleased) -------------------- -Contributors to this version: Trevor James Smith (:user:`Zeitsperre`), Pascal Bourgault (:user:`aulemahal`). +Contributors to this version: Trevor James Smith (:user:`Zeitsperre`), Pascal Bourgault (:user:`aulemahal`), Juliette Lavoie (:user:`juliettelavoie`). Announcements ^^^^^^^^^^^^^ @@ -14,6 +14,7 @@ Bug fixes ^^^^^^^^^ * Fixed an bug in sdba's ``map_groups`` that prevented passing DataArrays with cftime coordinates if the ``sdba_encode_cf`` option was True. (:issue:`1673`, :pull:`1674`). * Fixed bug (:issue:`1678`, :pull:`1679`) in sdba where a loaded training dataset could not be used for adjustment +* Fixed bug with loess smoothing for an array full of NaNs. (:pull:`1699`). Internal changes ^^^^^^^^^^^^^^^^ diff --git a/tests/test_sdba/test_loess.py b/tests/test_sdba/test_loess.py index 189bf6cb0..15835014e 100644 --- a/tests/test_sdba/test_loess.py +++ b/tests/test_sdba/test_loess.py @@ -1,7 +1,9 @@ from __future__ import annotations import numpy as np +import pandas as pd import pytest +import xarray as xr from xclim.sdba.loess import _constant_regression # noqa from xclim.sdba.loess import _gaussian_weighting # noqa @@ -62,3 +64,22 @@ def test_loess_smoothing(use_dask, open_dataset): # Same but we force not to use the optimization tasmooth3 = loess_smoothing(tas, f=0.1, equal_spacing=False) np.testing.assert_allclose(tasmooth, tasmooth3, rtol=1e-3, atol=1e-3) + + +@pytest.mark.slow +@pytest.mark.parametrize("use_dask", [True, False]) +def test_loess_smoothing_nan(use_dask): + # create data with one axis full of nan + data = np.random.randn(2, 2, 10) + data[0, 0] = [np.nan] * 10 + da = xr.DataArray( + data, + dims=["scenario", "model", "time"], + coords={"time": pd.date_range("2000-01-01", periods=10, freq="YS")}, + ).chunk({"time": -1}) + + out = loess_smoothing(da) + + assert out.dims == da.dims + # check that the output is all nan on the axis with nan in the input + assert np.isnan(out.values[0, 0]).all()