Skip to content

Raise exception when using diff with a non-existent dimension #8962

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
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: 4 additions & 1 deletion doc/whats-new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,10 @@ Breaking changes

Bug fixes
~~~~~~~~~

- Fix for :py:meth:`DataSet.diff` and consequently :py:meth:`DataArray.diff` to
raise a KeyError when `diff` is parameterized with a dimension that does not
exist in callee's DataSet/DataArray. (:issue:`7748`)
Comment on lines +39 to +41
Copy link
Collaborator

Choose a reason for hiding this comment

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

This is fine, though we can also simplify the language a bit — cut words like consequently / parameterized with!

By `Nathan Redmond <https://github.com/nathanredmond>`_.

Internal Changes
~~~~~~~~~~~~~~~~
Expand Down
14 changes: 13 additions & 1 deletion xarray/core/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -7726,6 +7726,7 @@ def diff(
n: int = 1,
*,
label: Literal["upper", "lower"] = "upper",
dims_found=False,
Copy link
Collaborator

Choose a reason for hiding this comment

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

Do we need this? I think it can be defined inside the function

) -> Self:
"""Calculate the n-th order discrete difference along given axis.

Expand Down Expand Up @@ -7798,14 +7799,25 @@ def diff(
variables[name] = var.isel(slice_end) - var.isel(slice_start)
else:
variables[name] = var.isel(slice_new)
dims_found = True
else:
variables[name] = var

difference = self._replace_with_new_dims(variables, indexes=indexes)

if n > 1:
return difference.diff(dim, n - 1)
return difference.diff(dim, n - 1, dims_found=dims_found)
else:
if dims_found:
return difference
else:
from warnings import warn
Comment on lines +7811 to +7814
Copy link
Collaborator

Choose a reason for hiding this comment

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

(these can be reduced to a single if not dims_found, and then it'll fall through to the return difference below)


warn(
"Expected dim to be present in at least one DataArray found in DataSet, "
"dim provided not present. This will raise a KeyError in the future.",
DeprecationWarning,
)
return difference

def shift(
Expand Down
6 changes: 6 additions & 0 deletions xarray/tests/test_dataarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -3861,6 +3861,12 @@ def test_dataarray_diff_n1(self) -> None:
expected = DataArray(np.diff(da.values, axis=1), dims=["x", "y"])
assert_equal(expected, actual)

def test_dataarray_diff_dim_nonexist(self) -> None:
# uncomment this code for test corresponding to pushed changes
# with pytest.raises(KeyError, match=r"dim provided not present"):
Copy link
Collaborator

Choose a reason for hiding this comment

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

This can use pytest.warns

# DataArray(np.random.randn(3, 4), dims=["x", "y"]).diff("z")
pass

def test_coordinate_diff(self) -> None:
# regression test for GH634
arr = DataArray(range(0, 20, 2), dims=["lon"], coords=[range(10)])
Expand Down
7 changes: 7 additions & 0 deletions xarray/tests/test_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -6040,6 +6040,13 @@ def test_dataset_diff_n2(self) -> None:
expected.coords["numbers"] = ("dim3", ds["numbers"].values)
assert_equal(expected, actual)

def test_dataset_diff_dim_nonexist(self) -> None:
# uncomment this code for test corresponding to pushed changes
# ds = create_test_data(seed=1)
# with pytest.raises(KeyError, match=r"dim provided not present"):
# ds.diff("dim4")
pass

def test_dataset_diff_exception_n_neg(self) -> None:
ds = create_test_data(seed=1)
with pytest.raises(ValueError, match=r"must be non-negative"):
Expand Down