Skip to content
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

Fix/quantile wrong errmsg #3635

Merged
merged 3 commits into from
Dec 17, 2019
Merged
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
2 changes: 2 additions & 0 deletions doc/whats-new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ Bug fixes
By `Deepak Cherian <https://github.com/dcherian>`_.
- Fix issue with Dask-backed datasets raising a ``KeyError`` on some computations involving ``map_blocks`` (:pull:`3598`)
By `Tom Augspurger <https://github.com/TomAugspurger>`_.
- Ensure :py:meth:`Dataset.quantile`, :py:meth:`DataArray.quantile` issue the correct error
when ``q`` is out of bounds (:issue:`3634`) by `Mathias Hauser <https://github.com/mathause>`_.

Documentation
~~~~~~~~~~~~~
Expand Down
6 changes: 6 additions & 0 deletions xarray/core/variable.py
Original file line number Diff line number Diff line change
Expand Up @@ -1731,6 +1731,10 @@ def quantile(self, q, dim=None, interpolation="linear", keep_attrs=None):
scalar = utils.is_scalar(q)
q = np.atleast_1d(np.asarray(q, dtype=np.float64))

# TODO: remove once numpy >= 1.15.0 is the minimum requirement
if np.count_nonzero(q < 0.0) or np.count_nonzero(q > 1.0):
raise ValueError("Quantiles must be in the range [0, 1]")

if dim is None:
dim = self.dims

Expand All @@ -1739,6 +1743,8 @@ def quantile(self, q, dim=None, interpolation="linear", keep_attrs=None):

def _wrapper(npa, **kwargs):
# move quantile axis to end. required for apply_ufunc

# TODO: use np.nanquantile once numpy >= 1.15.0 is the minimum requirement
return np.moveaxis(np.nanpercentile(npa, **kwargs), 0, -1)

axis = np.arange(-1, -1 * len(dim) - 1, -1)
Expand Down
8 changes: 8 additions & 0 deletions xarray/tests/test_variable.py
Original file line number Diff line number Diff line change
Expand Up @@ -1542,6 +1542,14 @@ def test_quantile_chunked_dim_error(self):
with raises_regex(ValueError, "dimension 'x'"):
v.quantile(0.5, dim="x")

@pytest.mark.parametrize("q", [-0.1, 1.1, [2], [0.25, 2]])
def test_quantile_out_of_bounds(self, q):
v = Variable(["x", "y"], self.d)

# escape special characters
with raises_regex(ValueError, r"Quantiles must be in the range \[0, 1\]"):
v.quantile(q, dim="x")

@requires_dask
@requires_bottleneck
def test_rank_dask_raises(self):
Expand Down