Skip to content

Commit a6f6c93

Browse files
committed
Draft
1 parent 03d4d28 commit a6f6c93

File tree

2 files changed

+163
-0
lines changed

2 files changed

+163
-0
lines changed

src/array_api_extra/_delegation.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -836,3 +836,40 @@ def argpartition(
836836
# kth is not small compared to x.size
837837

838838
return _funcs.argpartition(a, kth, axis=axis, xp=xp)
839+
840+
841+
def quantile(
842+
a: Array,
843+
q: float | Array,
844+
/,
845+
axis: int | None = None,
846+
method: str = "linear",
847+
keepdims: bool = False,
848+
*,
849+
xp: ModuleType | None = None,
850+
) -> Array:
851+
"""
852+
TODO
853+
"""
854+
855+
methods = {"linear"}
856+
if method not in methods:
857+
message = f"`method` must be one of {methods}"
858+
raise ValueError(message)
859+
if xp is None:
860+
xp = array_namespace(a)
861+
if a.ndim < 1:
862+
msg = "`a` must be at least 1-dimensional"
863+
raise TypeError(msg)
864+
865+
# Delegate where possible.
866+
if is_numpy_namespace(xp) or is_dask_namespace(xp):
867+
return xp.quantile(a, q, axis=axis, method=method, keepdims=keepdims)
868+
is_linear = method == "linear"
869+
if is_linear and is_jax_namespace(xp) or is_cupy_namespace(xp):
870+
return xp.quantile(a, q, axis=axis, method=method, keepdims=keepdims)
871+
if is_linear and is_torch_namespace(xp):
872+
return xp.quantile(a, q, dim=axis, interpolation=method, keepdim=keepdims)
873+
874+
# Otherwise call our implementation (will sort data)
875+
return _funcs.quantile(a, q, axis=axis, method=method, keepdims=keepdims, xp=xp)
Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
1+
from types import ModuleType
2+
3+
import numpy as np
4+
from scipy.stats._axis_nan_policy import _broadcast_arrays
5+
6+
from ._at import at
7+
from ._utils._compat import device as get_device
8+
from ._utils._helpers import eager_shape
9+
from ._utils._typing import Array
10+
11+
12+
def quantile( # numpydoc ignore=PR01,RT01
13+
x,
14+
p,
15+
/,
16+
method: str = 'linear', # noqa: ARG001
17+
axis: int | None = None,
18+
keepdims: bool = False,
19+
*,
20+
xp: ModuleType,
21+
):
22+
"""See docstring in `array_api_extra._delegation.py`."""
23+
# Input validation / standardization
24+
temp = _quantile_iv(x, p, axis, keepdims)
25+
y, p, axis, keepdims, n, axis_none, ndim = temp
26+
27+
res = _quantile_hf(y, p, n, xp)
28+
29+
# Reshape per axis/keepdims
30+
if axis_none and keepdims:
31+
shape = (1,)*(ndim - 1) + res.shape
32+
res = xp.reshape(res, shape)
33+
axis = -1
34+
35+
res = xp.moveaxis(res, -1, axis)
36+
37+
if not keepdims:
38+
res = xp.squeeze(res, axis=axis)
39+
40+
return res[()] if res.ndim == 0 else res
41+
42+
43+
def _quantile_iv(
44+
x: Array,
45+
p: Array,
46+
axis: int | None,
47+
keepdims: bool,
48+
xp: ModuleType
49+
):
50+
51+
if not xp.isdtype(xp.asarray(x).dtype, ('integral', 'real floating')):
52+
raise ValueError("`x` must have real dtype.")
53+
54+
if not xp.isdtype(xp.asarray(p).dtype, 'real floating'):
55+
raise ValueError("`p` must have real floating dtype.")
56+
57+
p_mask = (p > 1) | (p < 0) | xp.isnan(p)
58+
if xp.any(p_mask):
59+
raise ValueError("`p` values must be in the range [0, 1]")
60+
61+
device = get_device(x)
62+
floating_dtype = xp.result_type(x, p)
63+
x = xp.asarray(x, dtype=floating_dtype, device=device)
64+
p = xp.asarray(p, dtype=floating_dtype, device=device)
65+
dtype = x.dtype
66+
67+
axis_none = axis is None
68+
ndim = max(x.ndim, p.ndim)
69+
if axis_none:
70+
x = xp.reshape(x, (-1,))
71+
p = xp.reshape(p, (-1,))
72+
axis = 0
73+
elif np.iterable(axis) or int(axis) != axis:
74+
message = "`axis` must be an integer or None."
75+
raise ValueError(message)
76+
elif (axis >= ndim) or (axis < -ndim):
77+
message = "`axis` is not compatible with the shapes of the inputs."
78+
raise ValueError(message)
79+
axis = int(axis)
80+
81+
if keepdims not in {None, True, False}:
82+
message = "If specified, `keepdims` must be True or False."
83+
raise ValueError(message)
84+
85+
# If data has length zero along `axis`, the result will be an array of NaNs just
86+
# as if the data had length 1 along axis and were filled with NaNs.
87+
n = eager_shape(x, axis)
88+
if n == 0:
89+
shape = eager_shape(x)
90+
shape[axis] = 1
91+
n = 1
92+
x = xp.full(shape, xp.nan, dtype=dtype, device=device)
93+
94+
y = xp.sort(x, axis=axis, stable=False)
95+
# FIXME: I still need to look into the broacasting:
96+
y, p = _broadcast_arrays((y, p), axis=axis)
97+
98+
p_shape = eager_shape(p)
99+
if (keepdims is False) and (p_shape[axis] != 1):
100+
message = "`keepdims` may be False only if the length of `p` along `axis` is 1."
101+
raise ValueError(message)
102+
keepdims = (p_shape[axis] != 1) if keepdims is None else keepdims
103+
104+
y = xp.moveaxis(y, axis, -1)
105+
p = xp.moveaxis(p, axis, -1)
106+
107+
nans = xp.isnan(y)
108+
nan_out = xp.any(nans, axis=-1)
109+
if xp.any(nan_out):
110+
y = xp.asarray(y, copy=True) # ensure writable
111+
y = at(y, nan_out).set(xp.nan)
112+
113+
return y, p, axis, keepdims, n, axis_none, ndim, xp
114+
115+
116+
def _quantile_hf(y, p, n, xp):
117+
m = 1 - p
118+
jg = p*n + m - 1
119+
j = jg // 1
120+
g = jg % 1
121+
g[j < 0] = 0
122+
j = xp.clip(j, 0., n - 1)
123+
jp1 = xp.clip(j + 1, 0., n - 1)
124+
125+
return ((1 - g) * xp.take_along_axis(y, xp.astype(j, xp.int64), axis=-1)
126+
+ g * xp.take_along_axis(y, xp.astype(jp1, xp.int64), axis=-1))

0 commit comments

Comments
 (0)