Repository navigation
MAINT: Avoid repeated validation of percentiles in nanpercentile - #10241
Conversation
Previously, this would check the percentiles were 0 <= q <= 100 on every single slice of non-reduction axes. This also pulls the division by 100 to the top level, which makes things clearer, and also reduces the size of the stack trace
fd57e5c to
b0740b7
Compare
| result = _nanpercentile1d(part, q, overwrite_input, interpolation) | ||
| result = _nanquantile_1d(part, q, overwrite_input, interpolation) | ||
| else: | ||
| result = np.apply_along_axis(_nanpercentile1d, axis, a, q, |
There was a problem hiding this comment.
This would check and divide the percentile arguments in each iteration step, which is just wasteful.
| def _quantile_is_valid(q): | ||
| # avoid expensive reductions, relevant for arrays with < O(1000) elements | ||
| if q.ndim == 1 and q.size < 10: | ||
| for i in range(q.size): |
There was a problem hiding this comment.
While you're at it, would it be an idea to just remove this special casing? The timing does switch at 10 elements, at ~3us on my machine, and for 2 elements the python loop is 1.2us, while the numpy loop is still ~3us. But why do we care if next we are going to sort a whole array? This optimization is just not worth it.
If we do keep the loop, maybe at least make it do:
for _q in q:
if not (0.0 <= _q <= 1.0):
return False
(which is faster both for not getting indices and for doing the combined comparison)
p.s. the count_nonzero is worth it
There was a problem hiding this comment.
Was planning to put that in a separate PR
| return False | ||
| else: | ||
| # faster than any() | ||
| if np.count_nonzero(q < 0.0) or np.count_nonzero(q > 1.0): |
There was a problem hiding this comment.
Could probably use | here, something like np.count_nonzero((q < 0.0) | (q > 1.0)), or even in place. Just a note for the separate PR.
There was a problem hiding this comment.
Doing the or vectorized is algorithmically slower - n or operations vs 1.
|
Thanks Eric. |
Previously, this would check the percentiles were 0 <= q <= 100 on every single slice of non-reduction axes.
This also pulls the division by 100 to the top level, which makes things clearer, and also reduces the depth of the stack trace for invalid values from 5 levels back to 1
This is also pretty blatant groundwork for #10199 (cc @chunweiyuan)