Skip to main content

vortex_array/aggregate_fn/fns/all_non_nan/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use vortex_error::VortexResult;
5use vortex_session::VortexSession;
6use vortex_session::registry::CachedId;
7
8use crate::ArrayRef;
9use crate::Columnar;
10use crate::ExecutionCtx;
11use crate::IntoArray;
12use crate::aggregate_fn::AggregateFnId;
13use crate::aggregate_fn::AggregateFnVTable;
14use crate::aggregate_fn::EmptyOptions;
15use crate::aggregate_fn::fns::nan_count::nan_count;
16use crate::dtype::DType;
17use crate::dtype::Nullability;
18use crate::scalar::Scalar;
19
20/// Compute whether every value in an array is not NaN.
21///
22/// Like other `all` aggregates, this is vacuously true for empty input.
23///
24/// This is a pruning aggregate, not just a convenience wrapper around
25/// [`NanCount`][crate::aggregate_fn::fns::nan_count::NanCount]. Pruning aggregates must prove a
26/// row-wise fact for every value in the scope, so their partials remain valid when a stats column is
27/// sliced or concatenated alongside the data. [`NanCount`][crate::aggregate_fn::fns::nan_count::NanCount]
28/// carries cross-row count information instead, so it is useful as a legacy storage format but not
29/// as the pruning expression itself.
30#[derive(Clone, Debug)]
31pub struct AllNonNan;
32
33impl AggregateFnVTable for AllNonNan {
34    type Options = EmptyOptions;
35    type Partial = bool;
36
37    fn id(&self) -> AggregateFnId {
38        static ID: CachedId = CachedId::new("vortex.all_non_nan");
39        *ID
40    }
41
42    fn serialize(&self, _options: &Self::Options) -> VortexResult<Option<Vec<u8>>> {
43        Ok(Some(vec![]))
44    }
45
46    fn deserialize(
47        &self,
48        _metadata: &[u8],
49        _session: &VortexSession,
50    ) -> VortexResult<Self::Options> {
51        Ok(EmptyOptions)
52    }
53
54    fn return_dtype(&self, _options: &Self::Options, input_dtype: &DType) -> Option<DType> {
55        matches!(input_dtype, DType::Primitive(ptype, _) if ptype.is_float())
56            .then_some(DType::Bool(Nullability::Nullable))
57    }
58
59    fn partial_dtype(&self, options: &Self::Options, input_dtype: &DType) -> Option<DType> {
60        self.return_dtype(options, input_dtype)
61    }
62
63    fn empty_partial(
64        &self,
65        _options: &Self::Options,
66        _input_dtype: &DType,
67    ) -> VortexResult<Self::Partial> {
68        Ok(true)
69    }
70
71    fn combine_partials(&self, partial: &mut Self::Partial, other: Scalar) -> VortexResult<()> {
72        *partial &= bool::try_from(&other)?;
73        Ok(())
74    }
75
76    fn to_scalar(&self, partial: &Self::Partial) -> VortexResult<Scalar> {
77        Ok(Scalar::bool(*partial, Nullability::Nullable))
78    }
79
80    fn reset(&self, partial: &mut Self::Partial) {
81        *partial = true;
82    }
83
84    fn is_saturated(&self, partial: &Self::Partial) -> bool {
85        !*partial
86    }
87
88    fn try_accumulate(
89        &self,
90        state: &mut Self::Partial,
91        batch: &ArrayRef,
92        ctx: &mut ExecutionCtx,
93    ) -> VortexResult<bool> {
94        *state &= nan_count(batch, ctx)? == 0;
95        Ok(true)
96    }
97
98    fn accumulate(
99        &self,
100        partial: &mut Self::Partial,
101        batch: &Columnar,
102        ctx: &mut ExecutionCtx,
103    ) -> VortexResult<()> {
104        // Normal array dispatch is handled by `try_accumulate`, which always short-circuits.
105        // Keep this fallback in sync for direct Columnar accumulation paths.
106        let array = match batch {
107            Columnar::Constant(c) => c.clone().into_array(),
108            Columnar::Canonical(c) => c.clone().into_array(),
109        };
110        *partial &= nan_count(&array, ctx)? == 0;
111        Ok(())
112    }
113
114    fn finalize(&self, partials: ArrayRef) -> VortexResult<ArrayRef> {
115        Ok(partials)
116    }
117
118    fn finalize_scalar(&self, partial: &Self::Partial) -> VortexResult<Scalar> {
119        self.to_scalar(partial)
120    }
121}
122
123#[cfg(test)]
124mod tests {
125    use vortex_error::VortexResult;
126
127    use crate::IntoArray;
128    use crate::VortexSessionExecute;
129    use crate::aggregate_fn::Accumulator;
130    use crate::aggregate_fn::DynAccumulator;
131    use crate::aggregate_fn::EmptyOptions;
132    use crate::aggregate_fn::fns::all_non_nan::AllNonNan;
133    use crate::array_session;
134    use crate::arrays::PrimitiveArray;
135    use crate::dtype::DType;
136    use crate::dtype::Nullability;
137    use crate::dtype::PType;
138
139    #[test]
140    fn all_non_nan_aggregate_fn() -> VortexResult<()> {
141        let mut ctx = array_session().create_execution_ctx();
142        let dtype = DType::Primitive(PType::F32, Nullability::Nullable);
143        let mut acc = Accumulator::try_new(AllNonNan, EmptyOptions, dtype)?;
144
145        let batch = PrimitiveArray::from_option_iter([Some(1.0f32), None, Some(3.0)]).into_array();
146        acc.accumulate(&batch, &mut ctx)?;
147
148        assert!(bool::try_from(&acc.finish()?)?);
149        Ok(())
150    }
151
152    #[test]
153    fn all_non_nan_false_with_nan() -> VortexResult<()> {
154        let mut ctx = array_session().create_execution_ctx();
155        let dtype = DType::Primitive(PType::F32, Nullability::Nullable);
156        let mut acc = Accumulator::try_new(AllNonNan, EmptyOptions, dtype)?;
157
158        let batch = PrimitiveArray::from_option_iter([Some(1.0f32), Some(f32::NAN)]).into_array();
159        acc.accumulate(&batch, &mut ctx)?;
160
161        assert!(!bool::try_from(&acc.finish()?)?);
162        Ok(())
163    }
164
165    #[test]
166    fn all_non_nan_unsupported_for_non_float() -> VortexResult<()> {
167        let dtype = DType::Primitive(PType::I32, Nullability::Nullable);
168        assert!(Accumulator::try_new(AllNonNan, EmptyOptions, dtype).is_err());
169        Ok(())
170    }
171
172    #[test]
173    fn all_non_nan_true_for_empty_float() -> VortexResult<()> {
174        let dtype = DType::Primitive(PType::F32, Nullability::Nullable);
175        let mut acc = Accumulator::try_new(AllNonNan, EmptyOptions, dtype)?;
176
177        assert!(bool::try_from(&acc.finish()?)?);
178        Ok(())
179    }
180
181    #[test]
182    fn all_non_nan_true_with_nulls() -> VortexResult<()> {
183        let mut ctx = array_session().create_execution_ctx();
184        let dtype = DType::Primitive(PType::F32, Nullability::Nullable);
185        let mut acc = Accumulator::try_new(AllNonNan, EmptyOptions, dtype)?;
186
187        let batch = PrimitiveArray::from_option_iter([Some(1.0f32), None]).into_array();
188        acc.accumulate(&batch, &mut ctx)?;
189
190        assert!(bool::try_from(&acc.finish()?)?);
191        Ok(())
192    }
193}