Skip to content
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
13 changes: 9 additions & 4 deletions numpy/lib/_function_base_impl.py
Original file line number Diff line number Diff line change
Expand Up @@ -4528,7 +4528,8 @@ def _quantile_unchecked(a,
method="linear",
keepdims=False,
weights=None,
weak_q=False):
weak_q=False,
ignore_nans=False):
"""Assumes that q is in [0, 1], and is an ndarray"""
return _ureduce(a,
func=_quantile_ureduce_func,
Expand All @@ -4539,7 +4540,8 @@ def _quantile_unchecked(a,
out=out,
overwrite_input=overwrite_input,
method=method,
weak_q=weak_q)
weak_q=weak_q,
ignore_nans=ignore_nans)


def _quantile_is_valid(q):
Expand Down Expand Up @@ -4672,6 +4674,7 @@ def _quantile_ureduce_func(
overwrite_input: bool = False,
method: str = "linear",
weak_q: bool = False,
ignore_nans: bool = False,
) -> np.ndarray:
if q.ndim > 2:
# The code below works fine for nd, but it might not have useful
Expand Down Expand Up @@ -4699,7 +4702,8 @@ def _quantile_ureduce_func(
method=method,
out=out,
weights=wgt,
weak_q=weak_q)
weak_q=weak_q,
ignore_nans=ignore_nans)
return result


Expand Down Expand Up @@ -4746,6 +4750,7 @@ def _quantile(
out: np.ndarray | None = None,
weights: "np.typing.ArrayLike | None" = None,
weak_q: bool = False,
ignore_nans: bool = False,
) -> np.ndarray:
"""
Private function that doesn't support extended axis or keepdims.
Expand All @@ -4766,7 +4771,7 @@ def _quantile(
# axis being sampled from `arr` to be last.
if axis != 0: # But moveaxis is slow, so only call it if necessary.
arr = np.moveaxis(arr, axis, destination=0)
supports_nans = (
supports_nans = (not ignore_nans) and (
np.issubdtype(arr.dtype, np.inexact) or arr.dtype.kind in 'Mm'
)

Expand Down
73 changes: 37 additions & 36 deletions numpy/lib/_nanfunctions_impl.py
Original file line number Diff line number Diff line change
Expand Up @@ -1590,10 +1590,39 @@ def _nanquantile_unchecked(
# so deal them upfront
if a.size == 0:
return np.nanmean(a, axis, out=out, keepdims=keepdims)
if weights is not None:
# Give a zero weight to the NaNs and use the weighted quantile, which
# then ignores them.
if a.dtype == object:
# object arrays do not support `isnan` (gh-9009), so make a guess
isnan = np.not_equal(a, a, dtype=bool)
else:
isnan = np.isnan(a)
if isnan.any():
weights = np.where(isnan, 0, weights)

# A slice with only NaNs or zero weights has no quantile: the result
# is NaN, as for an all-NaN slice without weights.
empty_slices = np.all(weights == 0, axis=axis, keepdims=True)
if empty_slices.any():
warnings.warn("Slice encountered with all NaN or 0-weight samples",
RuntimeWarning, stacklevel=3)
# set the values to NaN and the weights to 1 for those slices
weights = weights + empty_slices
if a.dtype.kind in "mM":
nan = np.array("NaT", dtype=a.dtype)
else:
nan = np.nan
a = np.where(empty_slices, nan, a)

return fnb._quantile_unchecked(
a, q, axis, out, overwrite_input, method, keepdims,
weights=weights, weak_q=weak_q, ignore_nans=True,
)

return fnb._ureduce(a,
func=_nanquantile_ureduce_func,
q=q,
weights=weights,
keepdims=keepdims,
axis=axis,
out=out,
Expand All @@ -1605,7 +1634,6 @@ def _nanquantile_unchecked(
def _nanquantile_ureduce_func(
a: np.ndarray,
q: np.ndarray,
weights: np.ndarray,
axis: int | None = None,
out=None,
overwrite_input: bool = False,
Expand All @@ -1619,68 +1647,41 @@ def _nanquantile_ureduce_func(
"""
if axis is None or a.ndim == 1:
part = a.ravel()
wgt = None if weights is None else weights.ravel()
result = _nanquantile_1d(part, q, overwrite_input, method,
weights=wgt, weak_q=weak_q)
# Note that this code could try to fill in `out` right away
elif weights is None:
result = _nanquantile_1d(part, q, overwrite_input, method, weak_q)
else:
# Note that this code could try to fill in `out` right away
result = np.apply_along_axis(_nanquantile_1d, axis, a, q,
overwrite_input, method, weights, weak_q)
overwrite_input, method, weak_q)
# apply_along_axis fills in collapsed axis with results.
# Move those axes to the beginning to match percentile's
# convention.
if q.ndim != 0:
from_ax = [axis + i for i in range(q.ndim)]
result = np.moveaxis(result, from_ax, list(range(q.ndim)))
else:
# We need to apply along axis over 2 arrays, a and weights.
# move operation axes to end for simplicity:
a = np.moveaxis(a, axis, -1)
if weights is not None:
weights = np.moveaxis(weights, axis, -1)
if out is not None:
result = out
else:
# weights are limited to `inverted_cdf` so the result dtype
# is known to be identical to that of `a` here:
result = np.empty_like(a, shape=q.shape + a.shape[:-1])

for ii in np.ndindex(a.shape[:-1]):
result[(...,) + ii] = _nanquantile_1d(
a[ii], q, weights=weights[ii],
overwrite_input=overwrite_input, method=method,
weak_q=weak_q,
)
# This path dealt with `out` already...
return result

if out is not None:
out[...] = result
return result


def _nanquantile_1d(
arr1d, q, overwrite_input=False, method="linear", weights=None,
weak_q=False,
arr1d, q, overwrite_input=False, method="linear", weak_q=False,
):
"""
Private function for rank 1 arrays. Compute quantile ignoring NaNs.
See nanpercentile for parameter usage
"""
# TODO: What to do when arr1d = [1, np.nan] and weights = [0, 1]?
arr1d, weights, overwrite_input = _remove_nan_1d(arr1d,
second_arr1d=weights, overwrite_input=overwrite_input)
arr1d, _, overwrite_input = _remove_nan_1d(
arr1d, overwrite_input=overwrite_input)
if arr1d.size == 0:
# Use the quantile implementation to preserve its output dtype.
arr1d = np.full(1, np.nan, dtype=arr1d.dtype)
weights = None

return fnb._quantile_unchecked(
arr1d,
q,
overwrite_input=overwrite_input,
method=method,
weights=weights,
weak_q=weak_q,
)

Expand Down
110 changes: 90 additions & 20 deletions numpy/lib/tests/test_nanfunctions.py
Original file line number Diff line number Diff line change
Expand Up @@ -1108,19 +1108,37 @@ def test_float_special(self):

class TestNanFunctions_Percentile:

@staticmethod
def _get_w_args(mat, weighted, axis):
if weighted is False:
return {}
if weighted == "1d" and not isinstance(axis, int):
return {}
w_args = {"method": "inverted_cdf"}
if weighted == "1d":
w_args["weights"] = np.ones(mat.shape[axis])
else:
w_args["weights"] = np.ones_like(mat)
return w_args

def test_mutation(self):
# Check that passed array is not modified.
ndat = _ndat.copy()
np.nanpercentile(ndat, 30)
assert_equal(ndat, _ndat)

def test_keepdims(self):
mat = np.eye(3)
@pytest.mark.parametrize("weighted", [False, "1d", "2d"])
def test_keepdims(self, weighted):
mat = np.arange(20).reshape((4, 5))
for axis in [None, 0, 1]:
tgt = np.percentile(mat, 70, axis=axis, out=None,
overwrite_input=False)
res = np.nanpercentile(mat, 70, axis=axis, out=None,
overwrite_input=False)
tgt = np.percentile(
mat, 70, axis=axis, out=None, overwrite_input=False,
**self._get_w_args(mat, weighted, axis)
)
res = np.nanpercentile(
mat, 70, axis=axis, out=None, overwrite_input=False,
**self._get_w_args(mat, weighted, axis)
)
assert_(res.ndim == tgt.ndim)

d = np.ones((3, 5, 7, 11))
Expand Down Expand Up @@ -1174,33 +1192,32 @@ def test_keepdims_out(self, q, axis):
assert result is out
assert_equal(result.shape, shape_out)

@pytest.mark.parametrize("weighted", [False, True])
@pytest.mark.parametrize("weighted", [False, "1d", "2d"])
def test_out(self, weighted):
mat = np.random.rand(3, 3)
nan_mat = np.insert(mat, [0, 2], np.nan, axis=1)
resout = np.zeros(3)
if weighted:
w_args = {"weights": np.ones_like(mat), "method": "inverted_cdf"}
nan_w_args = {
"weights": np.ones_like(nan_mat), "method": "inverted_cdf"
}
else:
w_args = {}
nan_w_args = {}
tgt = np.percentile(mat, 42, axis=1, **w_args)
res = np.nanpercentile(nan_mat, 42, axis=1, out=resout, **nan_w_args)
tgt = np.percentile(mat, 42, axis=1,
**self._get_w_args(mat, weighted, axis=1))
res = np.nanpercentile(nan_mat, 42, axis=1, out=resout,
**self._get_w_args(nan_mat, weighted, axis=1))
assert_almost_equal(res, resout)
assert_almost_equal(res, tgt)
# 0-d output:
resout = np.zeros(())
tgt = np.percentile(mat, 42, axis=None, **w_args)
tgt = np.percentile(mat, 42, axis=None,
**self._get_w_args(mat, weighted, axis=None))
res = np.nanpercentile(
nan_mat, 42, axis=None, out=resout, **nan_w_args
nan_mat, 42, axis=None, out=resout,
**self._get_w_args(nan_mat, weighted, axis=None)
)
assert_almost_equal(res, resout)
assert_almost_equal(res, tgt)
tgt = np.percentile(mat, 42, axis=(0, 1),
**self._get_w_args(mat, weighted, axis=(0, 1)))
res = np.nanpercentile(
nan_mat, 42, axis=(0, 1), out=resout, **nan_w_args
nan_mat, 42, axis=(0, 1), out=resout,
**self._get_w_args(nan_mat, weighted, axis=(0, 1))
)
assert_almost_equal(res, resout)
assert_almost_equal(res, tgt)
Expand Down Expand Up @@ -1370,6 +1387,59 @@ def test_nan_value_with_weight_ndim(self, axis):
assert res is out
assert_equal(out, p_expected)

@pytest.mark.parametrize("axis", [0, 1])
def test_1d_weights_with_nans(self, axis):
# gh-29709: 1-D weights raised an IndexError
rng = np.random.default_rng(0)
x = rng.random((5, 4))
x[1, 2] = x[3, 0] = np.nan
w = rng.random(x.shape[axis])
q = [100 / 3, 200 / 3]
w_full = np.broadcast_to(w if axis == 1 else w[:, None], x.shape)
expected = np.nanpercentile(
x, q, axis=axis, weights=w_full, method="inverted_cdf")
res = np.nanpercentile(
x, q, axis=axis, weights=w, method="inverted_cdf")
assert_equal(res, expected)
# each slice matches the quantile of its non-NaN values
for i, xi in enumerate(np.moveaxis(x, axis, -1)):
keep = ~np.isnan(xi)
assert_equal(res[:, i], np.percentile(
xi[keep], q, weights=w[keep], method="inverted_cdf"))

@pytest.mark.parametrize("x, w", [
([1., 2.], [0., 0.]),
([1., np.nan], [0., 1.]),
([np.nan, np.nan], [1., 1.]),
])
def test_weights_all_nan_or_zero(self, x, w):
# no value is left: NaN and a warning, as for an all-NaN slice
with pytest.warns(RuntimeWarning, match="all NaN or 0-weight"):
res = np.nanpercentile(x, 50, weights=w, method="inverted_cdf")
assert np.isnan(res)

def test_weights_all_nan_or_zero_ndim(self):
x = np.array([[1., 2., 3.], [4., np.nan, 6.], [np.nan, np.nan, 9.]])
w = np.array([[0., 0., 0.], [1., 1., 0.], [1., 1., 1.]])
with pytest.warns(RuntimeWarning, match="all NaN or 0-weight"):
res = np.nanpercentile(
x, 50, axis=1, weights=w, method="inverted_cdf")
assert_equal(res, [np.nan, 4., 9.])
# the inputs are not modified
assert_equal(x[0], [1., 2., 3.])
assert_equal(w[0], [0., 0., 0.])

def test_weights_all_nat_or_zero(self):
x = np.array(["2020-01-01", "NaT", "2020-01-03"], dtype="M8[D]")
res = np.nanpercentile(
x, 50, weights=[1, 5, 0], method="inverted_cdf")
assert_equal(res, x[0])
with pytest.warns(RuntimeWarning, match="all NaN or 0-weight"):
res = np.nanpercentile(
x, 50, weights=[0, 5, 0], method="inverted_cdf")
assert res.dtype == x.dtype
assert np.isnat(res)


class TestNanFunctions_Quantile:
# most of this is already tested by TestPercentile
Expand Down
Loading