Skip to main content

polars_core/chunked_array/ops/aggregate/
mod.rs

1//! Implementations of the ChunkAgg trait.
2pub(crate) mod quantile;
3mod var;
4
5use num_traits::{AsPrimitive, Float, One, ToPrimitive, Zero};
6use polars_arrow::types::NativeType;
7#[cfg(feature = "dtype-decimal")]
8use polars_compute::decimal::DEC128_MAX_PREC;
9use polars_compute::float_sum;
10use polars_compute::min_max::MinMaxKernel;
11use polars_compute::rolling::QuantileMethod;
12use polars_compute::sum::{WrappingAdd, WrappingSum, wrapping_sum_arr, wrapping_sum_arr_upcast};
13use polars_utils::float::IsFloat;
14use polars_utils::float16::pf16;
15use polars_utils::min_max::MinMax;
16pub use quantile::{
17    QuantileAggSeries, QuantileFractionDtypes, cast_quantile_fractions, check_quantile_dtype,
18    check_quantiles, extract_non_null_quantiles, extract_quantiles, quantile_indices,
19    quantile_reduce_fraction,
20};
21pub(crate) use quantile::{quantile_of_nonnull, quantile_with, sorted_quantile};
22pub use var::*;
23
24use super::float_sorted_arg_max::{
25    float_arg_max_sorted_ascending, float_arg_max_sorted_descending,
26};
27use crate::chunked_array::{ChunkedArray, arg_max_binary, arg_min_binary};
28use crate::datatypes::{BooleanChunked, PolarsNumericType};
29use crate::prelude::*;
30use crate::series::IsSorted;
31
32pub trait SumCast: Sized {
33    type Sum: NumericNative + From<Self>;
34}
35
36macro_rules! impl_sum_cast {
37    ($($x:ty),*) => {
38        $(impl SumCast for $x { type Sum = $x; })*
39    };
40    ($($from:ty as $to:ty),*) => {
41        $(impl SumCast for $from { type Sum = $to; })*
42    };
43}
44
45impl_sum_cast!(
46    bool as IdxSize,
47    u8 as i64,
48    u16 as i64,
49    i8 as i64,
50    i16 as i64
51);
52impl_sum_cast!(u32, u64, i32, i64, f32, f64);
53#[cfg(feature = "dtype-f16")]
54impl_sum_cast!(pf16);
55#[cfg(feature = "dtype-i128")]
56impl_sum_cast!(i128);
57#[cfg(feature = "dtype-u128")]
58impl_sum_cast!(u128);
59
60pub fn sum_output_dtype(in_dtype: &DataType) -> DataType {
61    use DataType::*;
62    match in_dtype {
63        Boolean => IDX_DTYPE,
64        Int8 | UInt8 | Int16 | UInt16 => Int64,
65        #[cfg(feature = "dtype-decimal")]
66        Decimal(_, scale) => Decimal(DEC128_MAX_PREC, *scale),
67        dt => dt.clone(),
68    }
69}
70
71/// Aggregations that return [`Series`] of unit length. Those can be used in broadcasting operations.
72pub trait ChunkAggSeries {
73    /// Get the sum of the [`ChunkedArray`] as a new [`Series`] of length 1.
74    fn sum_reduce(&self) -> Scalar {
75        unimplemented!()
76    }
77    /// Get the max of the [`ChunkedArray`] as a new [`Series`] of length 1.
78    fn max_reduce(&self) -> Scalar {
79        unimplemented!()
80    }
81    /// Get the min of the [`ChunkedArray`] as a new [`Series`] of length 1.
82    fn min_reduce(&self) -> Scalar {
83        unimplemented!()
84    }
85    /// Get the product of the [`ChunkedArray`] as a new [`Series`] of length 1.
86    fn prod_reduce(&self) -> Scalar {
87        unimplemented!()
88    }
89}
90
91fn sum<T>(array: &PrimitiveArray<T>) -> T
92where
93    T: NumericNative + NativeType + WrappingSum,
94{
95    if array.null_count() == array.len() {
96        return T::default();
97    }
98
99    if T::is_float() {
100        unsafe {
101            if T::is_f16() {
102                let f16_arr =
103                    std::mem::transmute::<&PrimitiveArray<T>, &PrimitiveArray<pf16>>(array);
104                // We do not trust the numerical accuracy of f16 summation
105                let sum: pf16 = float_sum::sum_arr_as_f32(f16_arr).as_();
106                std::mem::transmute_copy::<pf16, T>(&sum)
107            } else if T::is_f32() {
108                let f32_arr =
109                    std::mem::transmute::<&PrimitiveArray<T>, &PrimitiveArray<f32>>(array);
110                let sum = float_sum::sum_arr_as_f32(f32_arr);
111                std::mem::transmute_copy::<f32, T>(&sum)
112            } else if T::is_f64() {
113                let f64_arr =
114                    std::mem::transmute::<&PrimitiveArray<T>, &PrimitiveArray<f64>>(array);
115                let sum = float_sum::sum_arr_as_f64(f64_arr);
116                std::mem::transmute_copy::<f64, T>(&sum)
117            } else {
118                unreachable!("only supported float types are f16, f32 and f64");
119            }
120        }
121    } else {
122        wrapping_sum_arr(array)
123    }
124}
125
126impl<T> ChunkAgg<T::Native> for ChunkedArray<T>
127where
128    T: PolarsNumericType,
129    T::Native: WrappingSum,
130    PrimitiveArray<T::Native>: for<'a> MinMaxKernel<Scalar<'a> = T::Native>,
131{
132    fn sum(&self) -> Option<T::Native> {
133        Some(
134            self.downcast_iter()
135                .map(sum)
136                .fold(T::Native::zero(), |acc, v| acc + v),
137        )
138    }
139
140    fn _sum_as_f64(&self) -> f64 {
141        self.downcast_iter().map(float_sum::sum_arr_as_f64).sum()
142    }
143
144    fn min(&self) -> Option<T::Native> {
145        if self.null_count() == self.len() {
146            return None;
147        }
148
149        // There is at least one non-null value.
150
151        match self.is_sorted_flag() {
152            IsSorted::Ascending => {
153                let idx = self.first_non_null().unwrap();
154                unsafe { self.get_unchecked(idx) }
155            },
156            IsSorted::Descending => {
157                let idx = self.last_non_null().unwrap();
158                unsafe { self.get_unchecked(idx) }
159            },
160            IsSorted::Not => self
161                .downcast_iter()
162                .filter_map(MinMaxKernel::min_ignore_nan_kernel)
163                .reduce(MinMax::min_ignore_nan),
164        }
165    }
166
167    fn max(&self) -> Option<T::Native> {
168        if self.null_count() == self.len() {
169            return None;
170        }
171        // There is at least one non-null value.
172
173        match self.is_sorted_flag() {
174            IsSorted::Ascending => {
175                let idx = if T::get_static_dtype().is_float() {
176                    float_arg_max_sorted_ascending(self)
177                } else {
178                    self.last_non_null().unwrap()
179                };
180
181                unsafe { self.get_unchecked(idx) }
182            },
183            IsSorted::Descending => {
184                let idx = if T::get_static_dtype().is_float() {
185                    float_arg_max_sorted_descending(self)
186                } else {
187                    self.first_non_null().unwrap()
188                };
189
190                unsafe { self.get_unchecked(idx) }
191            },
192            IsSorted::Not => self
193                .downcast_iter()
194                .filter_map(MinMaxKernel::max_ignore_nan_kernel)
195                .reduce(MinMax::max_ignore_nan),
196        }
197    }
198
199    fn min_max(&self) -> Option<(T::Native, T::Native)> {
200        if self.null_count() == self.len() {
201            return None;
202        }
203        // There is at least one non-null value.
204
205        match self.is_sorted_flag() {
206            IsSorted::Ascending => {
207                let min = unsafe { self.get_unchecked(self.first_non_null().unwrap()) };
208                let max = {
209                    let idx = if T::get_static_dtype().is_float() {
210                        float_arg_max_sorted_ascending(self)
211                    } else {
212                        self.last_non_null().unwrap()
213                    };
214
215                    unsafe { self.get_unchecked(idx) }
216                };
217                min.zip(max)
218            },
219            IsSorted::Descending => {
220                let min = unsafe { self.get_unchecked(self.last_non_null().unwrap()) };
221                let max = {
222                    let idx = if T::get_static_dtype().is_float() {
223                        float_arg_max_sorted_descending(self)
224                    } else {
225                        self.first_non_null().unwrap()
226                    };
227
228                    unsafe { self.get_unchecked(idx) }
229                };
230
231                min.zip(max)
232            },
233            IsSorted::Not => self
234                .downcast_iter()
235                .filter_map(MinMaxKernel::min_max_ignore_nan_kernel)
236                .reduce(|(min1, max1), (min2, max2)| {
237                    (
238                        MinMax::min_ignore_nan(min1, min2),
239                        MinMax::max_ignore_nan(max1, max2),
240                    )
241                }),
242        }
243    }
244
245    fn mean(&self) -> Option<f64> {
246        let count = self.len() - self.null_count();
247        if count == 0 {
248            return None;
249        }
250        Some(self._sum_as_f64() / count as f64)
251    }
252}
253
254/// Booleans are cast to 1 or 0.
255impl BooleanChunked {
256    pub fn sum(&self) -> Option<IdxSize> {
257        Some(if self.is_empty() {
258            0
259        } else {
260            self.downcast_iter()
261                .map(|arr| match arr.validity() {
262                    Some(validity) => {
263                        (arr.len() - (validity & arr.values()).unset_bits()) as IdxSize
264                    },
265                    None => (arr.len() - arr.values().unset_bits()) as IdxSize,
266                })
267                .sum()
268        })
269    }
270
271    pub fn min(&self) -> Option<bool> {
272        let nc = self.null_count();
273        let len = self.len();
274        if self.is_empty() || nc == len {
275            return None;
276        }
277        if nc == 0 {
278            if self.all() { Some(true) } else { Some(false) }
279        } else {
280            // we can unwrap as we already checked empty and all null above
281            if (self.sum().unwrap() + nc as IdxSize) == len as IdxSize {
282                Some(true)
283            } else {
284                Some(false)
285            }
286        }
287    }
288
289    pub fn max(&self) -> Option<bool> {
290        if self.is_empty() || self.null_count() == self.len() {
291            return None;
292        }
293        if self.any() { Some(true) } else { Some(false) }
294    }
295    pub fn mean(&self) -> Option<f64> {
296        if self.is_empty() || self.null_count() == self.len() {
297            return None;
298        }
299        self.sum()
300            .map(|sum| sum as f64 / (self.len() - self.null_count()) as f64)
301    }
302}
303
304// Needs the same trait bounds as the implementation of ChunkedArray<T> of dyn Series.
305impl<T> ChunkAggSeries for ChunkedArray<T>
306where
307    T: PolarsNumericType,
308    T::Native: WrappingSum + SumCast,
309    <T::Native as SumCast>::Sum: WrappingAdd,
310    PrimitiveArray<T::Native>: for<'a> MinMaxKernel<Scalar<'a> = T::Native>,
311{
312    fn sum_reduce(&self) -> Scalar {
313        let v: <T::Native as SumCast>::Sum = if T::Native::is_float() {
314            self.sum().map(Into::into).unwrap_or_else(Zero::zero)
315        } else {
316            self.downcast_iter()
317                .map(wrapping_sum_arr_upcast)
318                .fold(Zero::zero(), |a, b| a.wrapping_add(&b))
319        };
320        Scalar::new(sum_output_dtype(&T::get_static_dtype()), v.into())
321    }
322
323    fn max_reduce(&self) -> Scalar {
324        let v = ChunkAgg::max(self);
325        Scalar::new(T::get_static_dtype(), v.into())
326    }
327
328    fn min_reduce(&self) -> Scalar {
329        let v = ChunkAgg::min(self);
330        Scalar::new(T::get_static_dtype(), v.into())
331    }
332
333    fn prod_reduce(&self) -> Scalar {
334        let mut prod = T::Native::one();
335
336        for arr in self.downcast_iter() {
337            for v in arr.into_iter().flatten() {
338                prod = prod * *v
339            }
340        }
341        Scalar::new(T::get_static_dtype(), prod.into())
342    }
343}
344
345impl<T> VarAggSeries for ChunkedArray<T>
346where
347    T: PolarsIntegerType,
348    ChunkedArray<T>: ChunkVar,
349{
350    fn var_reduce(&self, ddof: u8) -> Scalar {
351        let v = self.var(ddof);
352        Scalar::new(DataType::Float64, v.into())
353    }
354
355    fn std_reduce(&self, ddof: u8) -> Scalar {
356        let v = self.std(ddof);
357        Scalar::new(DataType::Float64, v.into())
358    }
359}
360
361#[cfg(feature = "dtype-f16")]
362impl VarAggSeries for Float16Chunked {
363    fn var_reduce(&self, ddof: u8) -> Scalar {
364        let v = self.var(ddof).map(AsPrimitive::<pf16>::as_);
365        Scalar::new(DataType::Float16, v.into())
366    }
367
368    fn std_reduce(&self, ddof: u8) -> Scalar {
369        let v = self.std(ddof).map(AsPrimitive::<pf16>::as_);
370        Scalar::new(DataType::Float16, v.into())
371    }
372}
373
374impl VarAggSeries for Float32Chunked {
375    fn var_reduce(&self, ddof: u8) -> Scalar {
376        let v = self.var(ddof).map(|v| v as f32);
377        Scalar::new(DataType::Float32, v.into())
378    }
379
380    fn std_reduce(&self, ddof: u8) -> Scalar {
381        let v = self.std(ddof).map(|v| v as f32);
382        Scalar::new(DataType::Float32, v.into())
383    }
384}
385
386impl VarAggSeries for Float64Chunked {
387    fn var_reduce(&self, ddof: u8) -> Scalar {
388        let v = self.var(ddof);
389        Scalar::new(DataType::Float64, v.into())
390    }
391
392    fn std_reduce(&self, ddof: u8) -> Scalar {
393        let v = self.std(ddof);
394        Scalar::new(DataType::Float64, v.into())
395    }
396}
397
398impl<T> QuantileAggSeries for ChunkedArray<T>
399where
400    T: PolarsIntegerType,
401    T::Native: Ord + WrappingSum,
402{
403    fn quantile_reduce(&self, quantile: f64, method: QuantileMethod) -> PolarsResult<Scalar> {
404        let v = self.quantile(quantile, method)?;
405        Ok(Scalar::new(DataType::Float64, v.into()))
406    }
407
408    fn quantiles_reduce(&self, quantiles: &[f64], method: QuantileMethod) -> PolarsResult<Scalar> {
409        let v = self.quantiles(quantiles, method)?;
410        let s =
411            Float64Chunked::from_iter_options(PlSmallStr::from_static("quantiles"), v.into_iter())
412                .into_series();
413        let dtype = DataType::List(Box::new(s.dtype().clone()));
414        Ok(Scalar::new(dtype, AnyValue::List(s)))
415    }
416
417    fn median_reduce(&self) -> Scalar {
418        let v = self.median();
419        Scalar::new(DataType::Float64, v.into())
420    }
421}
422
423#[cfg(feature = "dtype-f16")]
424impl QuantileAggSeries for Float16Chunked {
425    fn quantile_reduce(&self, quantile: f64, method: QuantileMethod) -> PolarsResult<Scalar> {
426        let v = self.quantile(quantile, method)?;
427        Ok(Scalar::new(DataType::Float16, v.into()))
428    }
429
430    fn quantiles_reduce(&self, quantiles: &[f64], method: QuantileMethod) -> PolarsResult<Scalar> {
431        let v = self.quantiles(quantiles, method)?;
432        let s =
433            Float16Chunked::from_iter_options(PlSmallStr::from_static("quantiles"), v.into_iter())
434                .into_series();
435        let dtype = DataType::List(Box::new(s.dtype().clone()));
436        Ok(Scalar::new(dtype, AnyValue::List(s)))
437    }
438
439    fn median_reduce(&self) -> Scalar {
440        let v = self.median();
441        Scalar::new(DataType::Float16, v.into())
442    }
443}
444
445impl QuantileAggSeries for Float32Chunked {
446    fn quantile_reduce(&self, quantile: f64, method: QuantileMethod) -> PolarsResult<Scalar> {
447        let v = self.quantile(quantile, method)?;
448        Ok(Scalar::new(DataType::Float32, v.into()))
449    }
450
451    fn quantiles_reduce(&self, quantiles: &[f64], method: QuantileMethod) -> PolarsResult<Scalar> {
452        let v = self.quantiles(quantiles, method)?;
453        let s =
454            Float32Chunked::from_iter_options(PlSmallStr::from_static("quantiles"), v.into_iter())
455                .into_series();
456        let dtype = DataType::List(Box::new(s.dtype().clone()));
457        Ok(Scalar::new(dtype, AnyValue::List(s)))
458    }
459
460    fn median_reduce(&self) -> Scalar {
461        let v = self.median();
462        Scalar::new(DataType::Float32, v.into())
463    }
464}
465
466impl QuantileAggSeries for Float64Chunked {
467    fn quantile_reduce(&self, quantile: f64, method: QuantileMethod) -> PolarsResult<Scalar> {
468        let v = self.quantile(quantile, method)?;
469        Ok(Scalar::new(DataType::Float64, v.into()))
470    }
471
472    fn quantiles_reduce(&self, quantiles: &[f64], method: QuantileMethod) -> PolarsResult<Scalar> {
473        let v = self.quantiles(quantiles, method)?;
474        let s =
475            Float64Chunked::from_iter_options(PlSmallStr::from_static("quantiles"), v.into_iter())
476                .into_series();
477        let dtype = DataType::List(Box::new(s.dtype().clone()));
478        Ok(Scalar::new(dtype, AnyValue::List(s)))
479    }
480
481    fn median_reduce(&self) -> Scalar {
482        let v = self.median();
483        Scalar::new(DataType::Float64, v.into())
484    }
485}
486
487impl ChunkAggSeries for BooleanChunked {
488    fn sum_reduce(&self) -> Scalar {
489        let v = self.sum();
490        Scalar::new(IDX_DTYPE, v.into())
491    }
492    fn max_reduce(&self) -> Scalar {
493        let v = self.max();
494        Scalar::new(DataType::Boolean, v.into())
495    }
496    fn min_reduce(&self) -> Scalar {
497        let v = self.min();
498        Scalar::new(DataType::Boolean, v.into())
499    }
500}
501
502impl StringChunked {
503    pub(crate) fn max_str(&self) -> Option<&str> {
504        if self.is_empty() {
505            return None;
506        }
507        match self.is_sorted_flag() {
508            IsSorted::Ascending => {
509                self.last_non_null().and_then(|idx| {
510                    // SAFETY: last_non_null returns in bound index
511                    unsafe { self.get_unchecked(idx) }
512                })
513            },
514            IsSorted::Descending => {
515                self.first_non_null().and_then(|idx| {
516                    // SAFETY: first_non_null returns in bound index
517                    unsafe { self.get_unchecked(idx) }
518                })
519            },
520            IsSorted::Not => self
521                .downcast_iter()
522                .filter_map(MinMaxKernel::max_ignore_nan_kernel)
523                .reduce(MinMax::max_ignore_nan),
524        }
525    }
526    pub(crate) fn min_str(&self) -> Option<&str> {
527        if self.is_empty() {
528            return None;
529        }
530        match self.is_sorted_flag() {
531            IsSorted::Ascending => {
532                self.first_non_null().and_then(|idx| {
533                    // SAFETY: first_non_null returns in bound index
534                    unsafe { self.get_unchecked(idx) }
535                })
536            },
537            IsSorted::Descending => {
538                self.last_non_null().and_then(|idx| {
539                    // SAFETY: last_non_null returns in bound index
540                    unsafe { self.get_unchecked(idx) }
541                })
542            },
543            IsSorted::Not => self
544                .downcast_iter()
545                .filter_map(MinMaxKernel::min_ignore_nan_kernel)
546                .reduce(MinMax::min_ignore_nan),
547        }
548    }
549}
550
551impl ChunkAggSeries for StringChunked {
552    fn max_reduce(&self) -> Scalar {
553        let av: AnyValue = self.max_str().into();
554        Scalar::new(DataType::String, av.into_static())
555    }
556    fn min_reduce(&self) -> Scalar {
557        let av: AnyValue = self.min_str().into();
558        Scalar::new(DataType::String, av.into_static())
559    }
560}
561
562#[cfg(feature = "dtype-categorical")]
563impl<T: PolarsCategoricalType> CategoricalChunked<T>
564where
565    ChunkedArray<T::PolarsPhysical>: ChunkAgg<T::Native>,
566{
567    pub fn min_categorical(&self) -> Option<CatSize> {
568        if self.is_empty() || self.null_count() == self.len() {
569            return None;
570        }
571        if self.uses_lexical_ordering() {
572            let mapping = self.get_mapping();
573            let s = self
574                .physical()
575                .iter()
576                .flat_map(|opt_cat| {
577                    Some(unsafe { mapping.cat_to_str_unchecked(opt_cat?.as_cat()) })
578                })
579                .min();
580            mapping.get_cat(s.unwrap())
581        } else {
582            Some(self.physical().min()?.as_cat())
583        }
584    }
585
586    pub fn max_categorical(&self) -> Option<CatSize> {
587        if self.is_empty() || self.null_count() == self.len() {
588            return None;
589        }
590        if self.uses_lexical_ordering() {
591            let mapping = self.get_mapping();
592            let s = self
593                .physical()
594                .iter()
595                .flat_map(|opt_cat| {
596                    Some(unsafe { mapping.cat_to_str_unchecked(opt_cat?.as_cat()) })
597                })
598                .max();
599            mapping.get_cat(s.unwrap())
600        } else {
601            Some(self.physical().max()?.as_cat())
602        }
603    }
604}
605
606#[cfg(feature = "dtype-categorical")]
607impl<T: PolarsCategoricalType> ChunkAggSeries for CategoricalChunked<T>
608where
609    ChunkedArray<T::PolarsPhysical>: ChunkAgg<T::Native>,
610{
611    fn min_reduce(&self) -> Scalar {
612        let Some(min) = self.min_categorical() else {
613            return Scalar::new(self.dtype().clone(), AnyValue::Null);
614        };
615        let av = match self.dtype() {
616            DataType::Enum(_, mapping) => AnyValue::EnumOwned(min, mapping.clone()),
617            DataType::Categorical(_, mapping) => AnyValue::CategoricalOwned(min, mapping.clone()),
618            _ => unreachable!(),
619        };
620        Scalar::new(self.dtype().clone(), av)
621    }
622
623    fn max_reduce(&self) -> Scalar {
624        let Some(max) = self.max_categorical() else {
625            return Scalar::new(self.dtype().clone(), AnyValue::Null);
626        };
627        let av = match self.dtype() {
628            DataType::Enum(_, mapping) => AnyValue::EnumOwned(max, mapping.clone()),
629            DataType::Categorical(_, mapping) => AnyValue::CategoricalOwned(max, mapping.clone()),
630            _ => unreachable!(),
631        };
632        Scalar::new(self.dtype().clone(), av)
633    }
634}
635
636impl BinaryChunked {
637    pub fn max_binary(&self) -> Option<&[u8]> {
638        if self.is_empty() {
639            return None;
640        }
641        match self.is_sorted_flag() {
642            IsSorted::Ascending => {
643                self.last_non_null().and_then(|idx| {
644                    // SAFETY: last_non_null returns in bound index.
645                    unsafe { self.get_unchecked(idx) }
646                })
647            },
648            IsSorted::Descending => {
649                self.first_non_null().and_then(|idx| {
650                    // SAFETY: first_non_null returns in bound index.
651                    unsafe { self.get_unchecked(idx) }
652                })
653            },
654            IsSorted::Not => self
655                .downcast_iter()
656                .filter_map(MinMaxKernel::max_ignore_nan_kernel)
657                .reduce(MinMax::max_ignore_nan),
658        }
659    }
660
661    pub fn min_binary(&self) -> Option<&[u8]> {
662        if self.is_empty() {
663            return None;
664        }
665        match self.is_sorted_flag() {
666            IsSorted::Ascending => {
667                self.first_non_null().and_then(|idx| {
668                    // SAFETY: first_non_null returns in bound index.
669                    unsafe { self.get_unchecked(idx) }
670                })
671            },
672            IsSorted::Descending => {
673                self.last_non_null().and_then(|idx| {
674                    // SAFETY: last_non_null returns in bound index.
675                    unsafe { self.get_unchecked(idx) }
676                })
677            },
678            IsSorted::Not => self
679                .downcast_iter()
680                .filter_map(MinMaxKernel::min_ignore_nan_kernel)
681                .reduce(MinMax::min_ignore_nan),
682        }
683    }
684    pub fn arg_min_binary(&self) -> Option<usize> {
685        if self.is_empty() || self.null_count() == self.len() {
686            return None;
687        }
688
689        match self.is_sorted_flag() {
690            IsSorted::Ascending => self.first_non_null(),
691            IsSorted::Descending => self.last_non_null(),
692            IsSorted::Not => arg_min_binary(self),
693        }
694    }
695
696    pub fn arg_max_binary(&self) -> Option<usize> {
697        if self.is_empty() || self.null_count() == self.len() {
698            return None;
699        }
700
701        match self.is_sorted_flag() {
702            IsSorted::Ascending => self.last_non_null(),
703            IsSorted::Descending => self.first_non_null(),
704            IsSorted::Not => arg_max_binary(self),
705        }
706    }
707}
708
709impl ChunkAggSeries for BinaryChunked {
710    fn sum_reduce(&self) -> Scalar {
711        unimplemented!()
712    }
713    fn max_reduce(&self) -> Scalar {
714        let av: AnyValue = self.max_binary().into();
715        Scalar::new(self.dtype().clone(), av.into_static())
716    }
717    fn min_reduce(&self) -> Scalar {
718        let av: AnyValue = self.min_binary().into();
719        Scalar::new(self.dtype().clone(), av.into_static())
720    }
721}
722
723#[cfg(feature = "object")]
724impl<T: PolarsObject> ChunkAggSeries for ObjectChunked<T> {}
725
726#[cfg(test)]
727mod test {
728    use polars_compute::rolling::QuantileMethod;
729
730    use crate::prelude::*;
731
732    #[test]
733    #[cfg(not(miri))]
734    fn test_var() {
735        // Validated with numpy. Note that numpy uses ddof as an argument which
736        // influences results. The default ddof=0, we chose ddof=1, which is
737        // standard in statistics.
738        let ca1 = Int32Chunked::new(PlSmallStr::EMPTY, &[5, 8, 9, 5, 0]);
739        let ca2 = Int32Chunked::new(
740            PlSmallStr::EMPTY,
741            &[
742                Some(5),
743                None,
744                Some(8),
745                Some(9),
746                None,
747                Some(5),
748                Some(0),
749                None,
750            ],
751        );
752        for ca in &[ca1, ca2] {
753            let out = ca.var(1);
754            assert_eq!(out, Some(12.3));
755            let out = ca.std(1).unwrap();
756            assert!((3.5071355833500366 - out).abs() < 0.000000001);
757        }
758    }
759
760    #[test]
761    fn test_agg_float() {
762        let ca1 = Float32Chunked::new(PlSmallStr::from_static("a"), &[1.0, f32::NAN]);
763        let ca2 = Float32Chunked::new(PlSmallStr::from_static("b"), &[f32::NAN, 1.0]);
764        assert_eq!(ca1.min(), ca2.min());
765        let ca1 = Float64Chunked::new(PlSmallStr::from_static("a"), &[1.0, f64::NAN]);
766        let ca2 = Float64Chunked::from_slice(PlSmallStr::from_static("b"), &[f64::NAN, 1.0]);
767        assert_eq!(ca1.min(), ca2.min());
768        println!("{:?}", (ca1.min(), ca2.min()))
769    }
770
771    #[test]
772    fn test_median() {
773        let ca = UInt32Chunked::new(
774            PlSmallStr::from_static("a"),
775            &[Some(2), Some(1), None, Some(3), Some(5), None, Some(4)],
776        );
777        assert_eq!(ca.median(), Some(3.0));
778        let ca = UInt32Chunked::new(
779            PlSmallStr::from_static("a"),
780            &[
781                None,
782                Some(7),
783                Some(6),
784                Some(2),
785                Some(1),
786                None,
787                Some(3),
788                Some(5),
789                None,
790                Some(4),
791            ],
792        );
793        assert_eq!(ca.median(), Some(4.0));
794
795        let ca = Float32Chunked::from_slice(
796            PlSmallStr::EMPTY,
797            &[
798                0.166189, 0.166559, 0.168517, 0.169393, 0.175272, 0.233167, 0.238787, 0.266562,
799                0.26903, 0.285792, 0.292801, 0.293429, 0.301706, 0.308534, 0.331489, 0.346095,
800                0.367644, 0.369939, 0.372074, 0.41014, 0.415789, 0.421781, 0.427725, 0.465363,
801                0.500208, 2.621727, 2.803311, 3.868526,
802            ],
803        );
804        assert!((ca.median().unwrap() - 0.3200115).abs() < 0.0001)
805    }
806
807    #[test]
808    fn test_mean() {
809        let ca = Float32Chunked::new(PlSmallStr::EMPTY, &[Some(1.0), Some(2.0), None]);
810        assert_eq!(ca.mean().unwrap(), 1.5);
811        assert_eq!(
812            ca.into_series()
813                .mean_reduce()
814                .unwrap()
815                .value()
816                .extract::<f32>()
817                .unwrap(),
818            1.5
819        );
820        // all null values case
821        let ca = Float32Chunked::full_null(PlSmallStr::EMPTY, 3);
822        assert_eq!(ca.mean(), None);
823        assert_eq!(
824            ca.into_series()
825                .mean_reduce()
826                .unwrap()
827                .value()
828                .extract::<f32>(),
829            None
830        );
831    }
832
833    #[test]
834    fn test_quantile_all_null() {
835        let test_f32 = Float32Chunked::from_slice_options(PlSmallStr::EMPTY, &[None, None, None]);
836        let test_i32 = Int32Chunked::from_slice_options(PlSmallStr::EMPTY, &[None, None, None]);
837        let test_f64 = Float64Chunked::from_slice_options(PlSmallStr::EMPTY, &[None, None, None]);
838        let test_i64 = Int64Chunked::from_slice_options(PlSmallStr::EMPTY, &[None, None, None]);
839
840        let methods = vec![
841            QuantileMethod::Nearest,
842            QuantileMethod::Lower,
843            QuantileMethod::Higher,
844            QuantileMethod::Midpoint,
845            QuantileMethod::Linear,
846            QuantileMethod::Equiprobable,
847        ];
848
849        for method in methods {
850            assert_eq!(test_f32.quantile(0.9, method).unwrap(), None);
851            assert_eq!(test_i32.quantile(0.9, method).unwrap(), None);
852            assert_eq!(test_f64.quantile(0.9, method).unwrap(), None);
853            assert_eq!(test_i64.quantile(0.9, method).unwrap(), None);
854        }
855    }
856
857    #[test]
858    fn test_quantile_single_value() {
859        let test_f32 = Float32Chunked::from_slice_options(PlSmallStr::EMPTY, &[Some(1.0)]);
860        let test_i32 = Int32Chunked::from_slice_options(PlSmallStr::EMPTY, &[Some(1)]);
861        let test_f64 = Float64Chunked::from_slice_options(PlSmallStr::EMPTY, &[Some(1.0)]);
862        let test_i64 = Int64Chunked::from_slice_options(PlSmallStr::EMPTY, &[Some(1)]);
863
864        let methods = vec![
865            QuantileMethod::Nearest,
866            QuantileMethod::Lower,
867            QuantileMethod::Higher,
868            QuantileMethod::Midpoint,
869            QuantileMethod::Linear,
870            QuantileMethod::Equiprobable,
871        ];
872
873        for method in methods {
874            assert_eq!(test_f32.quantile(0.5, method).unwrap(), Some(1.0));
875            assert_eq!(test_i32.quantile(0.5, method).unwrap(), Some(1.0));
876            assert_eq!(test_f64.quantile(0.5, method).unwrap(), Some(1.0));
877            assert_eq!(test_i64.quantile(0.5, method).unwrap(), Some(1.0));
878        }
879    }
880
881    #[test]
882    fn test_quantile_min_max() {
883        let test_f32 = Float32Chunked::from_slice_options(
884            PlSmallStr::EMPTY,
885            &[None, Some(1f32), Some(5f32), Some(1f32)],
886        );
887        let test_i32 = Int32Chunked::from_slice_options(
888            PlSmallStr::EMPTY,
889            &[None, Some(1i32), Some(5i32), Some(1i32)],
890        );
891        let test_f64 = Float64Chunked::from_slice_options(
892            PlSmallStr::EMPTY,
893            &[None, Some(1f64), Some(5f64), Some(1f64)],
894        );
895        let test_i64 = Int64Chunked::from_slice_options(
896            PlSmallStr::EMPTY,
897            &[None, Some(1i64), Some(5i64), Some(1i64)],
898        );
899
900        let methods = vec![
901            QuantileMethod::Nearest,
902            QuantileMethod::Lower,
903            QuantileMethod::Higher,
904            QuantileMethod::Midpoint,
905            QuantileMethod::Linear,
906            QuantileMethod::Equiprobable,
907        ];
908
909        for method in methods {
910            assert_eq!(test_f32.quantile(0.0, method).unwrap(), test_f32.min());
911            assert_eq!(test_f32.quantile(1.0, method).unwrap(), test_f32.max());
912
913            assert_eq!(
914                test_i32.quantile(0.0, method).unwrap().unwrap(),
915                test_i32.min().unwrap() as f64
916            );
917            assert_eq!(
918                test_i32.quantile(1.0, method).unwrap().unwrap(),
919                test_i32.max().unwrap() as f64
920            );
921
922            assert_eq!(test_f64.quantile(0.0, method).unwrap(), test_f64.min());
923            assert_eq!(test_f64.quantile(1.0, method).unwrap(), test_f64.max());
924            assert_eq!(test_f64.quantile(0.5, method).unwrap(), test_f64.median());
925
926            assert_eq!(
927                test_i64.quantile(0.0, method).unwrap().unwrap(),
928                test_i64.min().unwrap() as f64
929            );
930            assert_eq!(
931                test_i64.quantile(1.0, method).unwrap().unwrap(),
932                test_i64.max().unwrap() as f64
933            );
934        }
935    }
936
937    #[test]
938    fn test_quantile() {
939        let ca = UInt32Chunked::new(
940            PlSmallStr::from_static("a"),
941            &[Some(2), Some(1), None, Some(3), Some(5), None, Some(4)],
942        );
943
944        assert_eq!(
945            ca.quantile(0.1, QuantileMethod::Nearest).unwrap(),
946            Some(1.0)
947        );
948        assert_eq!(
949            ca.quantile(0.9, QuantileMethod::Nearest).unwrap(),
950            Some(5.0)
951        );
952        assert_eq!(
953            ca.quantile(0.6, QuantileMethod::Nearest).unwrap(),
954            Some(3.0)
955        );
956
957        assert_eq!(ca.quantile(0.1, QuantileMethod::Lower).unwrap(), Some(1.0));
958        assert_eq!(ca.quantile(0.9, QuantileMethod::Lower).unwrap(), Some(4.0));
959        assert_eq!(ca.quantile(0.6, QuantileMethod::Lower).unwrap(), Some(3.0));
960
961        assert_eq!(ca.quantile(0.1, QuantileMethod::Higher).unwrap(), Some(2.0));
962        assert_eq!(ca.quantile(0.9, QuantileMethod::Higher).unwrap(), Some(5.0));
963        assert_eq!(ca.quantile(0.6, QuantileMethod::Higher).unwrap(), Some(4.0));
964
965        assert_eq!(
966            ca.quantile(0.1, QuantileMethod::Midpoint).unwrap(),
967            Some(1.5)
968        );
969        assert_eq!(
970            ca.quantile(0.9, QuantileMethod::Midpoint).unwrap(),
971            Some(4.5)
972        );
973        assert_eq!(
974            ca.quantile(0.6, QuantileMethod::Midpoint).unwrap(),
975            Some(3.5)
976        );
977
978        assert_eq!(ca.quantile(0.1, QuantileMethod::Linear).unwrap(), Some(1.4));
979        assert_eq!(ca.quantile(0.9, QuantileMethod::Linear).unwrap(), Some(4.6));
980        assert!(
981            (ca.quantile(0.6, QuantileMethod::Linear).unwrap().unwrap() - 3.4).abs() < 0.0000001
982        );
983
984        assert_eq!(
985            ca.quantile(0.15, QuantileMethod::Equiprobable).unwrap(),
986            Some(1.0)
987        );
988        assert_eq!(
989            ca.quantile(0.25, QuantileMethod::Equiprobable).unwrap(),
990            Some(2.0)
991        );
992        assert_eq!(
993            ca.quantile(0.6, QuantileMethod::Equiprobable).unwrap(),
994            Some(3.0)
995        );
996
997        let ca = UInt32Chunked::new(
998            PlSmallStr::from_static("a"),
999            &[
1000                None,
1001                Some(7),
1002                Some(6),
1003                Some(2),
1004                Some(1),
1005                None,
1006                Some(3),
1007                Some(5),
1008                None,
1009                Some(4),
1010            ],
1011        );
1012
1013        assert_eq!(
1014            ca.quantile(0.1, QuantileMethod::Nearest).unwrap(),
1015            Some(2.0)
1016        );
1017        assert_eq!(
1018            ca.quantile(0.9, QuantileMethod::Nearest).unwrap(),
1019            Some(6.0)
1020        );
1021        assert_eq!(
1022            ca.quantile(0.6, QuantileMethod::Nearest).unwrap(),
1023            Some(5.0)
1024        );
1025
1026        assert_eq!(ca.quantile(0.1, QuantileMethod::Lower).unwrap(), Some(1.0));
1027        assert_eq!(ca.quantile(0.9, QuantileMethod::Lower).unwrap(), Some(6.0));
1028        assert_eq!(ca.quantile(0.6, QuantileMethod::Lower).unwrap(), Some(4.0));
1029
1030        assert_eq!(ca.quantile(0.1, QuantileMethod::Higher).unwrap(), Some(2.0));
1031        assert_eq!(ca.quantile(0.9, QuantileMethod::Higher).unwrap(), Some(7.0));
1032        assert_eq!(ca.quantile(0.6, QuantileMethod::Higher).unwrap(), Some(5.0));
1033
1034        assert_eq!(
1035            ca.quantile(0.1, QuantileMethod::Midpoint).unwrap(),
1036            Some(1.5)
1037        );
1038        assert_eq!(
1039            ca.quantile(0.9, QuantileMethod::Midpoint).unwrap(),
1040            Some(6.5)
1041        );
1042        assert_eq!(
1043            ca.quantile(0.6, QuantileMethod::Midpoint).unwrap(),
1044            Some(4.5)
1045        );
1046
1047        assert_eq!(ca.quantile(0.1, QuantileMethod::Linear).unwrap(), Some(1.6));
1048        assert_eq!(ca.quantile(0.9, QuantileMethod::Linear).unwrap(), Some(6.4));
1049        assert_eq!(ca.quantile(0.6, QuantileMethod::Linear).unwrap(), Some(4.6));
1050
1051        assert_eq!(
1052            ca.quantile(0.14, QuantileMethod::Equiprobable).unwrap(),
1053            Some(1.0)
1054        );
1055        assert_eq!(
1056            ca.quantile(0.15, QuantileMethod::Equiprobable).unwrap(),
1057            Some(2.0)
1058        );
1059        assert_eq!(
1060            ca.quantile(0.6, QuantileMethod::Equiprobable).unwrap(),
1061            Some(5.0)
1062        );
1063    }
1064}