Skip to main content

polars_core/chunked_array/ops/aggregate/
quantile.rs

1use num_traits::AsPrimitive;
2use polars_compute::rolling::QuantileMethod;
3use polars_compute::selection::{
4    MaskedSlice, SELECT_MIN_PAR_LEN, select_many_by, select_many_seq_by,
5};
6#[cfg(feature = "dtype-f16")]
7use polars_utils::float16::pf16;
8
9use super::*;
10use crate::runtime::RAYON;
11
12pub trait QuantileAggSeries {
13    /// Get the median of the [`ChunkedArray`] as a new [`Series`] of length 1.
14    fn median_reduce(&self) -> Scalar;
15
16    /// Get the quantile of the [`ChunkedArray`] as a new [`Series`] of length 1.
17    fn quantile_reduce(&self, quantile: f64, method: QuantileMethod) -> PolarsResult<Scalar>;
18
19    /// Get the quantiles of the [`ChunkedArray`] as a new [`Series`] of same length as quantiles
20    fn quantiles_reduce(&self, _quantiles: &[f64], _method: QuantileMethod)
21    -> PolarsResult<Scalar>;
22}
23
24/// Returns the 0-based indices into `n_nonnull` sorted non-null values that `quantile` needs, and
25/// the fraction of the way from the lower to the upper one: `(lower_idx, upper_idx, fraction)`.
26///
27/// `upper_idx == lower_idx` unless `method` combines two distinct values. Only `Linear` uses
28/// `fraction`; `Midpoint` averages the two values.
29pub fn quantile_indices(
30    n_nonnull: usize,
31    quantile: f64,
32    method: QuantileMethod,
33) -> (usize, usize, f64) {
34    assert!(n_nonnull > 0);
35    let float_idx = (n_nonnull as f64 - 1.0) * quantile;
36    let floor_idx = float_idx as usize;
37    let ceil_idx = (float_idx.ceil() as usize).min(n_nonnull - 1);
38    match method {
39        QuantileMethod::Nearest => {
40            let idx = float_idx.round() as usize;
41            (idx, idx, 0.0)
42        },
43        QuantileMethod::Lower => (floor_idx, floor_idx, 0.0),
44        QuantileMethod::Higher => (ceil_idx, ceil_idx, 0.0),
45        QuantileMethod::Midpoint | QuantileMethod::Linear => {
46            (floor_idx, ceil_idx, float_idx - floor_idx as f64)
47        },
48        QuantileMethod::Equiprobable => {
49            let idx = ((n_nonnull as f64 * quantile).ceil() - 1.0).max(0.0) as usize;
50            (idx, idx, 0.0)
51        },
52    }
53}
54
55/// The dtypes a `quantile` fraction may have, which depend on where it is given.
56#[derive(Clone, Copy, Debug, PartialEq, Eq)]
57pub enum QuantileFractionDtypes {
58    /// One number, as in a group-by, where each group takes one fraction.
59    Number,
60    /// One number or a list of numbers.
61    NumberOrList,
62}
63
64/// Returns an error if a `quantile` fraction of `dtype` isn't one of `allowed`. The Null dtype
65/// passes, as a null fraction gives a null result. An unresolved dtype passes too.
66pub fn check_quantile_dtype(dtype: &DataType, allowed: QuantileFractionDtypes) -> PolarsResult<()> {
67    use QuantileFractionDtypes as A;
68    let inner = match dtype {
69        DataType::List(inner) if allowed != A::Number => inner.as_ref(),
70        dtype => dtype,
71    };
72    let ok = inner.is_numeric()
73        || inner.is_null()
74        || matches!(inner, DataType::Unknown(UnknownKind::Any));
75    polars_ensure!(
76        ok,
77        SchemaMismatch: "expected expression of dtype 'numeric' for quantile, got '{}'", dtype
78    );
79    Ok(())
80}
81
82/// Checks a column of `quantile` fractions of any length and casts it to Float64, or to
83/// List(Float64) if it holds lists. A null fraction passes.
84pub fn cast_quantile_fractions(
85    fractions: &Series,
86    allowed: QuantileFractionDtypes,
87) -> PolarsResult<Series> {
88    check_quantile_dtype(fractions.dtype(), allowed)?;
89    let fractions = match fractions.dtype() {
90        DataType::List(_) => {
91            let fractions = fractions.strict_cast(&DataType::List(Box::new(DataType::Float64)))?;
92            check_quantiles(fractions.list()?.get_inner().f64()?.iter())?;
93            fractions
94        },
95        _ => {
96            let fractions = fractions.strict_cast(&DataType::Float64)?;
97            check_quantiles(fractions.f64()?.iter())?;
98            fractions
99        },
100    };
101    Ok(fractions)
102}
103
104/// Checks the fraction given to `quantile` and returns its values. `fraction` holds one row: a
105/// number or a list of numbers. `allowed` gives the dtypes it may have. Returns `None` if the
106/// fraction is a null list; a null number is a `None` element.
107pub fn extract_quantiles(
108    fraction: &Series,
109    allowed: QuantileFractionDtypes,
110) -> PolarsResult<Option<Vec<Option<f64>>>> {
111    polars_ensure!(!fraction.is_empty(), ComputeError:
112        "the 'quantile' expression input should produce a single quantile or a list of quantiles, \
113        got an empty input"
114    );
115    polars_ensure!(fraction.len() == 1, ComputeError:
116        "polars does not support varying quantiles yet, \
117        make sure the 'quantile' expression input produces a single quantile or a list of quantiles"
118    );
119    let fraction = cast_quantile_fractions(fraction, allowed)?;
120    let quantiles = match fraction.dtype() {
121        DataType::List(_) => fraction
122            .list()?
123            .get_as_series(0)
124            .map(|s| s.f64().unwrap().iter().collect()),
125        _ => Some(vec![fraction.f64()?.get(0)]),
126    };
127    Ok(quantiles)
128}
129
130/// Like [`extract_quantiles`], for a fraction that is a constant rather than an expression, which
131/// mustn't be null.
132pub fn extract_non_null_quantiles(
133    fraction: &Series,
134    allowed: QuantileFractionDtypes,
135) -> PolarsResult<Vec<f64>> {
136    extract_quantiles(fraction, allowed)?
137        .and_then(|quantiles| quantiles.into_iter().collect())
138        .ok_or_else(
139            || polars_err!(ComputeError: "`quantile` should be between 0.0 and 1.0, got null"),
140        )
141}
142
143/// The quantile of `s` at `fraction`, or a list of quantiles for a list of fractions, as
144/// `extract_quantiles` reads it. A null fraction gives a null quantile.
145pub fn quantile_reduce_fraction(
146    s: &Series,
147    fraction: &Series,
148    method: QuantileMethod,
149) -> PolarsResult<Scalar> {
150    let quantiles = extract_quantiles(fraction, QuantileFractionDtypes::NumberOrList)?;
151    if !fraction.dtype().is_list() {
152        return match quantiles.and_then(|q| q[0]) {
153            Some(quantile) => s.quantile_reduce(quantile, method),
154            // The quantile of no values is a null of the output dtype.
155            None => s.clear().quantile_reduce(0.5, method),
156        };
157    }
158    let Some(quantiles) = quantiles else {
159        let dtype = s.clear().quantiles_reduce(&[], method)?.dtype().clone();
160        return Ok(Scalar::null(dtype));
161    };
162    let non_null: Vec<f64> = quantiles.iter().flatten().copied().collect();
163    let out = s.quantiles_reduce(&non_null, method)?;
164    if non_null.len() == quantiles.len() {
165        return Ok(out);
166    }
167    // Put the null fractions back as nulls at their positions.
168    let AnyValue::List(values) = out.value() else {
169        return Ok(out);
170    };
171    let mut next: IdxSize = 0;
172    let positions: IdxCa = quantiles
173        .iter()
174        .map(|q| {
175            q.map(|_| {
176                next += 1;
177                next - 1
178            })
179        })
180        .collect();
181    let values = values.take(&positions)?;
182    Ok(Scalar::new(out.dtype().clone(), AnyValue::List(values)))
183}
184
185/// Returns an error if a quantile is NaN or outside `0.0..=1.0`. A null quantile passes, as it
186/// gives a null result.
187pub fn check_quantiles(
188    quantiles: impl IntoIterator<Item = impl Into<Option<f64>>>,
189) -> PolarsResult<()> {
190    for q in quantiles.into_iter().filter_map(Into::into) {
191        polars_ensure!(
192            (0.0..=1.0).contains(&q),
193            ComputeError: "`quantile` should be between 0.0 and 1.0, got {}", q,
194        );
195    }
196    Ok(())
197}
198
199fn linear_interpol<T: Float>(lower: T, upper: T, fraction: f64) -> T {
200    if lower == upper {
201        lower
202    } else {
203        let proportion: T = T::from(fraction).unwrap();
204        proportion * (upper - lower) + lower
205    }
206}
207fn midpoint_interpol<T: Float>(lower: T, upper: T) -> T {
208    if lower == upper {
209        lower
210    } else {
211        (lower + upper) / (T::one() + T::one())
212    }
213}
214
215/// Combines the values at the ranks returned by [`quantile_indices`] into the quantile.
216fn interpolate<T: ToPrimitive>(
217    lower: T,
218    upper: T,
219    fraction: f64,
220    method: QuantileMethod,
221) -> Option<f64> {
222    let lower = lower.to_f64()?;
223    match method {
224        QuantileMethod::Midpoint => Some(midpoint_interpol(lower, upper.to_f64()?)),
225        QuantileMethod::Linear => Some(linear_interpol(lower, upper.to_f64()?, fraction)),
226        _ => Some(lower),
227    }
228}
229
230/// Computes `quantile` of `n_nonnull` values, where `order_stats(ranks, out)` writes the values at
231/// the given ascending ranks of the sorted values to `out`.
232pub(crate) fn quantile_with<T: ToPrimitive + Copy + Default>(
233    n_nonnull: usize,
234    quantile: f64,
235    method: QuantileMethod,
236    order_stats: impl FnOnce(&[usize], &mut [T]),
237) -> Option<f64> {
238    if n_nonnull == 0 {
239        return None;
240    }
241    let (lower, upper, fraction) = quantile_indices(n_nonnull, quantile, method);
242    let k = if lower == upper { 1 } else { 2 };
243    let mut vals = [T::default(); 2];
244    order_stats(&[lower, upper][..k], &mut vals[..k]);
245    interpolate(vals[0], vals[k - 1], fraction, method)
246}
247
248/// [`quantile_with`] for several quantiles, fetching all the order statistics they need at once.
249fn quantiles_with<T: ToPrimitive + Copy + Default>(
250    n_nonnull: usize,
251    quantiles: &[f64],
252    method: QuantileMethod,
253    order_stats: impl FnOnce(&[usize], &mut [T]),
254) -> Vec<Option<f64>> {
255    if n_nonnull == 0 {
256        return vec![None; quantiles.len()];
257    }
258    let indices: Vec<_> = quantiles
259        .iter()
260        .map(|&q| quantile_indices(n_nonnull, q, method))
261        .collect();
262    let mut ranks: Vec<usize> = indices.iter().flat_map(|&(l, u, _)| [l, u]).collect();
263    ranks.sort_unstable();
264    ranks.dedup();
265    let mut vals = vec![T::default(); ranks.len()];
266    order_stats(&ranks, &mut vals);
267    let at = |r| vals[ranks.binary_search(&r).unwrap()];
268    indices
269        .iter()
270        .map(|&(lower, upper, fraction)| interpolate(at(lower), at(upper), fraction, method))
271        .collect()
272}
273
274/// The `quantile` of `vals`, non-null values in any order, which it reorders on the calling
275/// thread, since group-by already runs its groups in parallel.
276pub(crate) fn quantile_of_nonnull<T: ToPrimitive + TotalOrd + Copy + Default>(
277    vals: &mut [T],
278    quantile: f64,
279    method: QuantileMethod,
280) -> Option<f64> {
281    quantile_with(vals.len(), quantile, method, |ranks, out| {
282        select_many_seq_by(vals, ranks, out, TotalOrd::tot_cmp)
283    })
284}
285
286/// Reads the values at the ascending `ranks` of the non-null values of `ca` into `out`, given that
287/// `ca` is flagged sorted (descending if `descending`), which keeps all its nulls at one end.
288fn sorted_order_stats<T: PolarsNumericType>(
289    ca: &ChunkedArray<T>,
290    descending: bool,
291    ranks: &[usize],
292    out: &mut [T::Native],
293) {
294    let n_nonnull = ca.len() - ca.null_count();
295    let start = ca.first_non_null().unwrap_or(0);
296    debug_assert!(ranks.last().is_none_or(|&r| r < n_nonnull));
297
298    // Visit the ranks in ascending row order, so a single pass over the chunks finds them.
299    let mut chunks = ca.downcast_iter();
300    let mut chunk = chunks.next().unwrap();
301    let mut chunk_start = 0;
302    for j in 0..ranks.len() {
303        let (i, idx) = if descending {
304            let i = ranks.len() - 1 - j;
305            (i, start + n_nonnull - 1 - ranks[i])
306        } else {
307            (j, start + ranks[j])
308        };
309        while idx >= chunk_start + chunk.len() {
310            chunk_start += chunk.len();
311            chunk = chunks.next().unwrap();
312        }
313        out[i] = chunk.value(idx - chunk_start);
314    }
315}
316
317/// The `quantile` of `ca`, which is sorted (descending if `descending`) with its nulls at one end.
318pub(crate) fn sorted_quantile<T: PolarsNumericType>(
319    ca: &ChunkedArray<T>,
320    descending: bool,
321    quantile: f64,
322    method: QuantileMethod,
323) -> Option<f64> {
324    let n_nonnull = ca.len() - ca.null_count();
325    quantile_with(n_nonnull, quantile, method, |ranks, out| {
326        sorted_order_stats(ca, descending, ranks, out)
327    })
328}
329
330/// Writes the values at the strictly ascending `ranks` of the sorted non-null values of `ca` to
331/// `out`, reading them directly if `ca` is flagged sorted and selecting them otherwise.
332pub fn order_statistics<T: PolarsNumericType>(
333    ca: &ChunkedArray<T>,
334    ranks: &[usize],
335    out: &mut [T::Native],
336) {
337    if ranks.is_empty() {
338        return;
339    }
340    let n_valid = ca.len() - ca.null_count();
341    match ca.is_sorted_flag() {
342        // Entering the pool costs a thread wake-up, more than a small selection. On one thread,
343        // copying and selecting sequentially beats classifying every value against a sampled
344        // bracket.
345        IsSorted::Not if n_valid < SELECT_MIN_PAR_LEN || RAYON.current_num_threads() == 1 => {
346            select_many_seq_by(&mut ca.to_vec_non_null(), ranks, out, TotalOrd::tot_cmp)
347        },
348        IsSorted::Not => {
349            let chunks: Vec<MaskedSlice<'_, T::Native>> = ca
350                .downcast_iter()
351                .map(|arr| MaskedSlice {
352                    values: arr.values(),
353                    validity: arr.validity().filter(|v| v.unset_bits() > 0).map(|v| {
354                        let (bytes, offset, _) = v.as_slice();
355                        (bytes, offset)
356                    }),
357                })
358                .collect();
359            RAYON.install(|| select_many_by(&chunks, n_valid, ranks, out))
360        },
361        sorted => sorted_order_stats(ca, sorted == IsSorted::Descending, ranks, out),
362    }
363}
364
365/// The values at the strictly ascending `ranks` of the sorted non-null physical values of the
366/// numeric `s`, as a [`Series`] of them.
367pub fn order_statistics_physical(s: &Series, ranks: &[usize]) -> Series {
368    let phys = s.to_physical_repr();
369    with_match_physical_numeric_polars_type!(phys.dtype(), |$T| {
370        let ca: &ChunkedArray<$T> = phys.as_ref().as_ref().as_ref();
371        let mut out = vec![Default::default(); ranks.len()];
372        order_statistics(ca, ranks, &mut out);
373        ChunkedArray::<$T>::from_vec(s.name().clone(), out).into_series()
374    })
375}
376
377/// The `quantile` of `ca`, after validating it.
378fn ca_quantile<T: PolarsNumericType>(
379    ca: &ChunkedArray<T>,
380    quantile: f64,
381    method: QuantileMethod,
382) -> PolarsResult<Option<f64>> {
383    check_quantiles([quantile])?;
384    let n_nonnull = ca.len() - ca.null_count();
385    Ok(quantile_with(n_nonnull, quantile, method, |ranks, out| {
386        order_statistics(ca, ranks, out)
387    }))
388}
389
390/// The `quantiles` of `ca`, after validating them.
391fn ca_quantiles<T: PolarsNumericType>(
392    ca: &ChunkedArray<T>,
393    quantiles: &[f64],
394    method: QuantileMethod,
395) -> PolarsResult<Vec<Option<f64>>> {
396    check_quantiles(quantiles.iter().copied())?;
397    let n_nonnull = ca.len() - ca.null_count();
398    Ok(quantiles_with(
399        n_nonnull,
400        quantiles,
401        method,
402        |ranks, out| order_statistics(ca, ranks, out),
403    ))
404}
405
406/// The `quantiles` of the non-null values of `ca` that are not NaN, after validating them, or
407/// `None` if there are no such values.
408pub fn quantiles_without_nan(
409    ca: &Float64Chunked,
410    quantiles: &[f64],
411    method: QuantileMethod,
412) -> PolarsResult<Option<Vec<f64>>> {
413    check_quantiles(quantiles.iter().copied())?;
414    let n_nan: usize = ca
415        .downcast_iter()
416        .map(|arr| arr.non_null_values_iter().filter(|v| v.is_nan()).count())
417        .sum();
418    // NaN orders above every other value, so the lowest ranks are exactly the values without NaN.
419    let n = ca.len() - ca.null_count() - n_nan;
420    if n == 0 {
421        return Ok(None);
422    }
423    let qs = quantiles_with(n, quantiles, method, |ranks, out| {
424        order_statistics(ca, ranks, out)
425    });
426    Ok(Some(qs.into_iter().map(Option::unwrap).collect()))
427}
428
429impl<T> ChunkQuantile<f64> for ChunkedArray<T>
430where
431    T: PolarsIntegerType,
432{
433    fn quantile(&self, quantile: f64, method: QuantileMethod) -> PolarsResult<Option<f64>> {
434        ca_quantile(self, quantile, method)
435    }
436
437    fn quantiles(
438        &self,
439        quantiles: &[f64],
440        method: QuantileMethod,
441    ) -> PolarsResult<Vec<Option<f64>>> {
442        ca_quantiles(self, quantiles, method)
443    }
444
445    fn median(&self) -> Option<f64> {
446        self.quantile(0.5, QuantileMethod::Linear).unwrap() // unwrap fine since quantile in range
447    }
448}
449
450macro_rules! impl_chunk_quantile_for_float_chunked {
451    ($T:ty, $CA:ty) => {
452        impl ChunkQuantile<$T> for $CA {
453            fn quantile(&self, quantile: f64, method: QuantileMethod) -> PolarsResult<Option<$T>> {
454                Ok(ca_quantile(self, quantile, method)?.map(AsPrimitive::as_))
455            }
456
457            fn quantiles(
458                &self,
459                quantiles: &[f64],
460                method: QuantileMethod,
461            ) -> PolarsResult<Vec<Option<$T>>> {
462                Ok(ca_quantiles(self, quantiles, method)?
463                    .into_iter()
464                    .map(|opt| opt.map(AsPrimitive::as_))
465                    .collect())
466            }
467
468            fn median(&self) -> Option<$T> {
469                self.quantile(0.5, QuantileMethod::Linear).unwrap() // unwrap fine since quantile in range
470            }
471        }
472    };
473}
474
475#[cfg(feature = "dtype-f16")]
476impl_chunk_quantile_for_float_chunked!(pf16, Float16Chunked);
477impl_chunk_quantile_for_float_chunked!(f32, Float32Chunked);
478impl_chunk_quantile_for_float_chunked!(f64, Float64Chunked);
479
480impl ChunkQuantile<String> for StringChunked {}
481impl ChunkQuantile<Series> for ListChunked {}
482#[cfg(feature = "dtype-array")]
483impl ChunkQuantile<Series> for ArrayChunked {}
484#[cfg(feature = "object")]
485impl<T: PolarsObject> ChunkQuantile<Series> for ObjectChunked<T> {}
486impl ChunkQuantile<bool> for BooleanChunked {}