Skip to main content

polars_core/chunked_array/ops/
binning.rs

1use std::hash::{Hash, Hasher};
2use std::num::NonZeroUsize;
3use std::ops::Deref;
4
5#[cfg(feature = "serde")]
6use serde::{Deserialize, Serialize};
7
8pub use super::aggregate::quantile::{order_statistics_physical, quantiles_without_nan};
9use crate::CHEAP_SERIES_HASH_LIMIT;
10use crate::prelude::*;
11use crate::utils::Wrap;
12
13/// Breakpoints delimiting bins by value.
14///
15/// Always free of nulls and non-decreasing.
16#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
17#[derive(Clone, PartialEq, Debug)]
18pub struct Breaks(Series);
19
20impl Breaks {
21    pub fn new(breaks: Series) -> PolarsResult<Self> {
22        polars_ensure!(
23            breaks.null_count() == 0,
24            ComputeError: "breakpoints cannot contain nulls"
25        );
26        let n = breaks.len();
27        if n >= 2 {
28            let non_decreasing = breaks
29                .slice(Slice::head(n - 1))
30                .lt_eq(&breaks.slice((1usize, n - 1)))?;
31            polars_ensure!(
32                non_decreasing.all(),
33                ComputeError: "breakpoints must be non-decreasing"
34            );
35        }
36        Ok(Self(breaks))
37    }
38
39    pub fn into_series(self) -> Series {
40        self.0
41    }
42}
43
44/// Cumulative fractions delimiting bins by proportion.
45///
46/// Always non-decreasing and within `[0, 1]`.
47#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
48#[cfg_attr(feature = "dsl-schema", derive(schemars::JsonSchema))]
49#[derive(Clone, PartialEq, Debug)]
50pub struct Fractions(Vec<f64>);
51
52impl Fractions {
53    pub fn new(fractions: Vec<f64>) -> PolarsResult<Self> {
54        for x in &fractions {
55            polars_ensure!(
56                (0.0..=1.0).contains(x),
57                ComputeError: "fractions must be between 0.0 and 1.0, got {}", x
58            );
59        }
60        polars_ensure!(
61            fractions.is_sorted(),
62            ComputeError: "fractions must be non-decreasing"
63        );
64        Ok(Self(fractions))
65    }
66}
67
68/// How interval binning delimits its bins, with its breakpoints resolved.
69#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
70#[derive(Clone, PartialEq, Debug, Hash)]
71pub enum IntervalSpec {
72    /// Explicit breakpoints.
73    Breaks(Breaks),
74    /// `n` equal-width bins spanning `[min, max]`.
75    Count(NonZeroUsize),
76}
77
78/// How quantile and rank binning delimit their bins.
79#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
80#[cfg_attr(feature = "dsl-schema", derive(schemars::JsonSchema))]
81#[derive(Clone, PartialEq, Debug, Hash)]
82pub enum FractionSpec {
83    /// Explicit fractions.
84    Explicit(Fractions),
85    /// `n` bins of equal probability, or of equal size for rank binning.
86    Count(NonZeroUsize),
87}
88
89fn n_bins(n_bins: usize) -> PolarsResult<NonZeroUsize> {
90    NonZeroUsize::new(n_bins)
91        .ok_or_else(|| polars_err!(ComputeError: "binning requires at least one bin"))
92}
93
94impl IntervalSpec {
95    pub fn from_breaks(breaks: Series) -> PolarsResult<Self> {
96        Ok(Self::Breaks(Breaks::new(breaks)?))
97    }
98
99    pub fn from_count(count: usize) -> PolarsResult<Self> {
100        Ok(Self::Count(n_bins(count)?))
101    }
102
103    pub fn n_bins(&self) -> usize {
104        match self {
105            Self::Breaks(breaks) => breaks.len() + 1,
106            Self::Count(n_bins) => n_bins.get(),
107        }
108    }
109
110    pub fn breaks(&self) -> Option<&Series> {
111        match self {
112            Self::Breaks(breaks) => Some(&breaks.0),
113            Self::Count(_) => None,
114        }
115    }
116}
117
118impl FractionSpec {
119    pub fn from_fractions(fractions: Vec<f64>) -> PolarsResult<Self> {
120        Ok(Self::Explicit(Fractions::new(fractions)?))
121    }
122
123    pub fn from_count(count: usize) -> PolarsResult<Self> {
124        Ok(Self::Count(n_bins(count)?))
125    }
126
127    pub fn n_bins(&self) -> usize {
128        match self {
129            Self::Explicit(fractions) => fractions.len() + 1,
130            Self::Count(n_bins) => n_bins.get(),
131        }
132    }
133}
134
135impl Deref for Breaks {
136    type Target = Series;
137
138    fn deref(&self) -> &Self::Target {
139        &self.0
140    }
141}
142
143impl Deref for Fractions {
144    type Target = [f64];
145
146    fn deref(&self) -> &Self::Target {
147        &self.0
148    }
149}
150
151impl Hash for Breaks {
152    fn hash<H: Hasher>(&self, state: &mut H) {
153        Wrap(self.0.slice(Slice::head(CHEAP_SERIES_HASH_LIMIT))).hash(state)
154    }
155}
156
157impl Hash for Fractions {
158    fn hash<H: Hasher>(&self, state: &mut H) {
159        bytemuck::cast_slice::<_, u64>(&self.0).hash(state)
160    }
161}