Skip to content
This repository has been archived by the owner on Oct 7, 2024. It is now read-only.

Commit

Permalink
Fix/quantile wrong errmsg (pydata#3635)
Browse files Browse the repository at this point in the history
* test correct error is thrown

* quantile: throw out of bounds error

* whats-new
  • Loading branch information
mathause authored and crusaderky committed Dec 17, 2019
1 parent f2b2f9f commit 6295bc6
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 0 deletions.
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

0 comments on commit 6295bc6

Please sign in to comment.