From 5e527d44fbd585c6bd9e058d86bf7b17a1ab6144 Mon Sep 17 00:00:00 2001 From: Mattia Almansi Date: Wed, 7 Jun 2023 18:57:54 +0200 Subject: [PATCH 1/3] fix polyfit changing the original object --- xarray/core/dataset.py | 2 +- xarray/tests/test_dataset.py | 7 +++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/xarray/core/dataset.py b/xarray/core/dataset.py index 81860bede95..0f271e9d7e4 100644 --- a/xarray/core/dataset.py +++ b/xarray/core/dataset.py @@ -7972,7 +7972,7 @@ def polyfit( scale_da = scale if w is not None: - rhs *= w[:, np.newaxis] + rhs = rhs * w[:, np.newaxis] with warnings.catch_warnings(): if full: # Copy np.polyfit behavior diff --git a/xarray/tests/test_dataset.py b/xarray/tests/test_dataset.py index cc9220dfe33..a273fb20766 100644 --- a/xarray/tests/test_dataset.py +++ b/xarray/tests/test_dataset.py @@ -6217,6 +6217,13 @@ def test_polyfit_output(self) -> None: out = ds.polyfit("time", 2) assert len(out.data_vars) == 0 + def test_polyfit_weighted(self) -> None: + ds = create_test_data(seed=1) + ds_copy = ds.copy(deep=True) + + ds.polyfit("dim2", 2, w=np.arange(ds.sizes["dim2"])) + xr.testing.assert_identical(ds, ds_copy) + def test_polyfit_warnings(self) -> None: ds = create_test_data(seed=1) From f7885ae37a36a74d7155f3acf1bfd6b3605eacdb Mon Sep 17 00:00:00 2001 From: Mattia Almansi Date: Wed, 7 Jun 2023 19:03:19 +0200 Subject: [PATCH 2/3] what's new --- doc/whats-new.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/doc/whats-new.rst b/doc/whats-new.rst index 990962673b8..5c0d3c3c843 100644 --- a/doc/whats-new.rst +++ b/doc/whats-new.rst @@ -42,6 +42,8 @@ Performance Bug fixes ~~~~~~~~~ +- Fix bug where weighted ``polyfit`` were changing the original object (:issue:`5644`, :pull:`7900`). + By `Mattia Almansi `_. - Don't call ``CachingFileManager.__del__`` on interpreter shutdown (:issue:`7814`, :pull:`7880`). By `Justus Magin `_. From 6f4a857b742355087df6f402b3dfd9377a33856c Mon Sep 17 00:00:00 2001 From: Mattia Almansi Date: Thu, 8 Jun 2023 18:14:52 +0200 Subject: [PATCH 3/3] add test comment --- xarray/tests/test_dataset.py | 1 + 1 file changed, 1 insertion(+) diff --git a/xarray/tests/test_dataset.py b/xarray/tests/test_dataset.py index a273fb20766..01c26ad6104 100644 --- a/xarray/tests/test_dataset.py +++ b/xarray/tests/test_dataset.py @@ -6218,6 +6218,7 @@ def test_polyfit_output(self) -> None: assert len(out.data_vars) == 0 def test_polyfit_weighted(self) -> None: + # Make sure weighted polyfit does not change the original object (issue #5644) ds = create_test_data(seed=1) ds_copy = ds.copy(deep=True)