Skip to main content

vortex_array/stats/
stat.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::fmt::Debug;
5use std::fmt::Display;
6use std::fmt::Formatter;
7
8use enum_iterator::Sequence;
9use enum_iterator::all;
10use num_enum::IntoPrimitive;
11use num_enum::TryFromPrimitive;
12
13use crate::aggregate_fn;
14use crate::aggregate_fn::AggregateFnRef;
15use crate::aggregate_fn::AggregateFnVTable;
16use crate::aggregate_fn::AggregateFnVTableExt;
17use crate::aggregate_fn::EmptyOptions;
18use crate::aggregate_fn::NumericalAggregateOpts;
19use crate::dtype::DType;
20use crate::dtype::Nullability::NonNullable;
21use crate::stats::LowerBound;
22use crate::stats::Precision;
23use crate::stats::StatType;
24use crate::stats::UpperBound;
25
26#[derive(
27    Debug,
28    Clone,
29    Copy,
30    PartialEq,
31    Eq,
32    PartialOrd,
33    Ord,
34    Hash,
35    Sequence,
36    IntoPrimitive,
37    TryFromPrimitive,
38)]
39#[repr(u8)]
40pub enum Stat {
41    /// Whether all values are the same (nulls are not equal to other non-null values,
42    /// so this is true iff all values are null or all values are the same non-null value)
43    IsConstant = 0,
44    /// Whether the non-null values in the array are sorted in ascending order (i.e., we skip nulls)
45    /// This may later be extended to support descending order, but for now we only support ascending order.
46    IsSorted = 1,
47    /// Whether the non-null values in the array are strictly sorted in ascending order (i.e., sorted with no duplicates)
48    /// This may later be extended to support descending order, but for now we only support ascending order.
49    IsStrictSorted = 2,
50    /// The maximum value in the array (ignoring nulls, unless all values are null)
51    Max = 3,
52    /// The minimum value in the array (ignoring nulls, unless all values are null)
53    Min = 4,
54    /// The sum of the non-null values of the array.
55    Sum = 5,
56    /// The number of null values in the array
57    NullCount = 6,
58    /// The uncompressed size of the array in bytes
59    UncompressedSizeInBytes = 7,
60    /// The number of NaN values in the array
61    NaNCount = 8,
62}
63
64/// These structs allow the extraction of the bound from the `Precision` value.
65/// They tie together the Stat and the StatBound, which allows the bound to be extracted.
66pub struct Max;
67
68pub struct Min;
69
70pub struct Sum;
71
72pub struct IsConstant;
73
74pub struct IsSorted;
75
76pub struct IsStrictSorted;
77
78pub struct NullCount;
79
80pub struct UncompressedSizeInBytes;
81
82pub struct NaNCount;
83
84impl StatType<bool> for IsConstant {
85    type Bound = Precision<bool>;
86
87    const STAT: Stat = Stat::IsConstant;
88}
89
90impl StatType<bool> for IsSorted {
91    type Bound = Precision<bool>;
92
93    const STAT: Stat = Stat::IsSorted;
94}
95
96impl StatType<bool> for IsStrictSorted {
97    type Bound = Precision<bool>;
98
99    const STAT: Stat = Stat::IsStrictSorted;
100}
101
102impl<T: PartialOrd + Clone> StatType<T> for NullCount {
103    type Bound = UpperBound<T>;
104
105    const STAT: Stat = Stat::NullCount;
106}
107
108impl<T: PartialOrd + Clone> StatType<T> for UncompressedSizeInBytes {
109    type Bound = UpperBound<T>;
110
111    const STAT: Stat = Stat::UncompressedSizeInBytes;
112}
113
114impl<T: PartialOrd + Clone + Debug> StatType<T> for Max {
115    type Bound = UpperBound<T>;
116
117    const STAT: Stat = Stat::Max;
118}
119
120impl<T: PartialOrd + Clone + Debug> StatType<T> for Min {
121    type Bound = LowerBound<T>;
122
123    const STAT: Stat = Stat::Min;
124}
125
126impl<T: PartialOrd + Clone + Debug> StatType<T> for Sum {
127    type Bound = Precision<T>;
128
129    const STAT: Stat = Stat::Sum;
130}
131
132impl<T: PartialOrd + Clone> StatType<T> for NaNCount {
133    type Bound = UpperBound<T>;
134
135    const STAT: Stat = Stat::NaNCount;
136}
137
138impl Stat {
139    /// Whether the statistic is commutative (i.e., whether merging can be done independently of ordering)
140    /// e.g., min/max are commutative, but is_sorted is not
141    pub fn is_commutative(&self) -> bool {
142        // NOTE: we prefer this syntax to force a compile error if we add a new stat
143        match self {
144            Self::IsConstant
145            | Self::Max
146            | Self::Min
147            | Self::NullCount
148            | Self::Sum
149            | Self::NaNCount
150            | Self::UncompressedSizeInBytes => true,
151            Self::IsSorted | Self::IsStrictSorted => false,
152        }
153    }
154
155    /// Whether the statistic has the same dtype as the array it's computed on
156    pub fn has_same_dtype_as_array(&self) -> bool {
157        matches!(self, Stat::Min | Stat::Max)
158    }
159
160    /// Return the [`DType`] of the statistic scalar assuming the array is of the given [`DType`].
161    pub fn dtype(&self, data_type: &DType) -> Option<DType> {
162        Some(match self {
163            Self::IsConstant => DType::Bool(NonNullable),
164            Self::IsSorted => DType::Bool(NonNullable),
165            Self::IsStrictSorted => DType::Bool(NonNullable),
166            Self::Max if matches!(data_type, DType::Null) => return None,
167            Self::Max => data_type.clone(),
168            Self::Min if matches!(data_type, DType::Null) => return None,
169            Self::Min => data_type.clone(),
170            Self::NullCount => {
171                return aggregate_fn::fns::null_count::NullCount
172                    .return_dtype(&EmptyOptions, data_type);
173            }
174            Self::UncompressedSizeInBytes => {
175                return aggregate_fn::fns::uncompressed_size_in_bytes::UncompressedSizeInBytes
176                    .return_dtype(&EmptyOptions, data_type);
177            }
178            Self::NaNCount => {
179                return aggregate_fn::fns::nan_count::NanCount
180                    .return_dtype(&EmptyOptions, data_type);
181            }
182            Self::Sum => {
183                // Statistics follow NaN-skipping semantics; request it explicitly.
184                return aggregate_fn::fns::sum::Sum
185                    .return_dtype(&NumericalAggregateOpts::skip_nans(), data_type);
186            }
187        })
188    }
189
190    /// Return the built-in aggregate function corresponding to this statistic, if one exists.
191    pub fn aggregate_fn(&self) -> Option<AggregateFnRef> {
192        // Statistics follow NaN-skipping semantics; request it explicitly rather than the default.
193        Some(match self {
194            Self::Max => aggregate_fn::fns::max::Max.bind(NumericalAggregateOpts::skip_nans()),
195            Self::Min => aggregate_fn::fns::min::Min.bind(NumericalAggregateOpts::skip_nans()),
196            Self::Sum => aggregate_fn::fns::sum::Sum.bind(NumericalAggregateOpts::skip_nans()),
197            Self::NullCount => aggregate_fn::fns::null_count::NullCount.bind(EmptyOptions),
198            Self::NaNCount => aggregate_fn::fns::nan_count::NanCount.bind(EmptyOptions),
199            Self::UncompressedSizeInBytes => {
200                aggregate_fn::fns::uncompressed_size_in_bytes::UncompressedSizeInBytes
201                    .bind(EmptyOptions)
202            }
203            Self::IsConstant | Self::IsSorted | Self::IsStrictSorted => return None,
204        })
205    }
206
207    /// Return the statistic represented by `aggregate_fn`, if it has a legacy stat slot.
208    ///
209    /// Min/max/sum statistics skip NaN values, so NaN-including configurations of those
210    /// aggregates have no stat slot.
211    pub fn from_aggregate_fn(aggregate_fn: &AggregateFnRef) -> Option<Self> {
212        if let Some(options) = aggregate_fn.as_opt::<aggregate_fn::fns::sum::Sum>() {
213            return options.skip_nans.then_some(Self::Sum);
214        }
215        if aggregate_fn.is::<aggregate_fn::fns::nan_count::NanCount>() {
216            return Some(Self::NaNCount);
217        }
218        if aggregate_fn.is::<aggregate_fn::fns::null_count::NullCount>() {
219            return Some(Self::NullCount);
220        }
221        if let Some(options) = aggregate_fn.as_opt::<aggregate_fn::fns::min::Min>() {
222            return options.skip_nans.then_some(Self::Min);
223        }
224        if let Some(options) = aggregate_fn.as_opt::<aggregate_fn::fns::max::Max>() {
225            return options.skip_nans.then_some(Self::Max);
226        }
227        if aggregate_fn
228            .is::<aggregate_fn::fns::uncompressed_size_in_bytes::UncompressedSizeInBytes>()
229        {
230            return Some(Self::UncompressedSizeInBytes);
231        }
232        None
233    }
234
235    pub fn name(&self) -> &str {
236        match self {
237            Self::IsConstant => "is_constant",
238            Self::IsSorted => "is_sorted",
239            Self::IsStrictSorted => "is_strict_sorted",
240            Self::Max => "max",
241            Self::Min => "min",
242            Self::NullCount => "null_count",
243            Self::UncompressedSizeInBytes => "uncompressed_size_in_bytes",
244            Self::Sum => "sum",
245            Self::NaNCount => "nan_count",
246        }
247    }
248
249    pub fn all() -> impl Iterator<Item = Stat> {
250        all::<Self>()
251    }
252}
253
254impl Display for Stat {
255    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
256        write!(f, "{}", self.name())
257    }
258}
259
260#[cfg(test)]
261mod test {
262    use std::sync::LazyLock;
263
264    use enum_iterator::all;
265    use vortex_session::VortexSession;
266
267    use crate::VortexSessionExecute;
268    use crate::arrays::PrimitiveArray;
269    use crate::stats::Stat;
270
271    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
272
273    #[test]
274    fn min_of_nulls_is_not_panic() {
275        let min = PrimitiveArray::from_option_iter::<i32, _>([None, None, None, None])
276            .statistics()
277            .compute_as::<i64>(Stat::Min, &mut SESSION.create_execution_ctx());
278
279        assert_eq!(min, None);
280    }
281
282    #[test]
283    fn has_same_dtype_as_array() {
284        assert!(Stat::Min.has_same_dtype_as_array());
285        assert!(Stat::Max.has_same_dtype_as_array());
286        for stat in all::<Stat>().filter(|s| !matches!(s, Stat::Min | Stat::Max)) {
287            assert!(!stat.has_same_dtype_as_array());
288        }
289    }
290}