Skip to main content

vortex_array/arrays/primitive/array/
majority_candidate.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use vortex_error::VortexResult;
5use vortex_mask::AllOr;
6
7use crate::ExecutionCtx;
8use crate::IntoArray;
9use crate::arrays::BoolArray;
10use crate::arrays::ConstantArray;
11use crate::arrays::PrimitiveArray;
12use crate::arrays::bool::BoolArrayExt;
13use crate::builtins::ArrayBuiltins;
14use crate::match_each_native_ptype;
15use crate::scalar::PValue;
16use crate::scalar::Scalar;
17use crate::scalar_fn::builtin::operators::CompareOperator;
18use crate::stats::majority::majority_candidate;
19
20impl PrimitiveArray {
21    /// Returns the majority candidate of this array's present values and the exact number of
22    /// times it occurs.
23    ///
24    /// The value is found by a Boyer–Moore majority vote, so it is the most common present value
25    /// whenever that value fills more than half of the present positions. Otherwise it is some
26    /// present value, which callers can judge by its count. Returns `None` if no value is present.
27    pub fn majority_candidate(
28        &self,
29        ctx: &mut ExecutionCtx,
30    ) -> VortexResult<Option<(PValue, usize)>> {
31        if self.is_empty() || self.validity()?.definitely_all_null() {
32            return Ok(None);
33        }
34
35        let mask = self.as_ref().validity()?.execute_mask(self.len(), ctx)?;
36        let top: Option<PValue> = match_each_native_ptype!(self.ptype(), |P| {
37            majority_candidate(self.as_slice::<P>(), &mask).map(PValue::from)
38        });
39        let Some(top) = top else {
40            return Ok(None);
41        };
42
43        let top_array = ConstantArray::new(
44            Scalar::primitive_value(top, top.ptype(), self.dtype().nullability()),
45            self.len(),
46        );
47        let equal = self
48            .clone()
49            .into_array()
50            .compare(top_array.into_array(), CompareOperator::Eq)?
51            .execute::<BoolArray>(ctx)?
52            .to_bit_buffer();
53        let count = match mask.bit_buffer() {
54            AllOr::All => equal.true_count(),
55            AllOr::None => 0,
56            AllOr::Some(validity) => (&equal & validity).true_count(),
57        };
58        Ok(Some((top, count)))
59    }
60}
61
62#[cfg(test)]
63#[expect(clippy::cast_possible_truncation, reason = "test inputs are small")]
64mod tests {
65    use rstest::rstest;
66    use vortex_buffer::Buffer;
67    use vortex_error::VortexExpect;
68    use vortex_error::VortexResult;
69    use vortex_session::VortexSession;
70
71    use super::*;
72    use crate::VortexSessionExecute;
73    use crate::validity::Validity;
74
75    fn candidate(array: &PrimitiveArray) -> VortexResult<Option<(PValue, usize)>> {
76        array.majority_candidate(&mut VortexSession::empty().create_execution_ctx())
77    }
78
79    /// The majority sits at the end of a sorted array, so a prefix of the input never sees it.
80    #[rstest]
81    #[case::shorter_than_lanes(5)]
82    #[case::not_a_multiple_of_64(1_000)]
83    #[case::long(100_003)]
84    fn sorted_majority(#[case] len: usize) -> VortexResult<()> {
85        let minority = len / 3;
86        let values: Buffer<u32> = (0..len)
87            .map(|index| {
88                if index < minority {
89                    index as u32
90                } else {
91                    u32::MAX
92                }
93            })
94            .collect();
95        let array = PrimitiveArray::new(values, Validity::NonNullable);
96        assert_eq!(candidate(&array)?, Some((u32::MAX.into(), len - minority)));
97        Ok(())
98    }
99
100    /// Without a majority, the value is some present value, reported with its exact count.
101    #[test]
102    fn without_majority_counts_the_returned_value() -> VortexResult<()> {
103        let values: Vec<i64> = (0..1_000).map(|index| index % 10).collect();
104        let array = PrimitiveArray::new(
105            values.iter().copied().collect::<Buffer<i64>>(),
106            Validity::NonNullable,
107        );
108        let (top, count) = candidate(&array)?.vortex_expect("array has valid values");
109        let top = i64::try_from(top)?;
110        assert_eq!(count, values.iter().filter(|&&value| value == top).count());
111        Ok(())
112    }
113
114    /// Invalid values must not vote: zero is the most common stored value, but most zeros are null.
115    #[rstest]
116    #[case::short(104)]
117    #[case::long(10_000)]
118    fn nulls_do_not_vote(#[case] len: usize) -> VortexResult<()> {
119        let values: Buffer<u16> = (0..len)
120            .map(|index| if index % 8 < 3 { 9 } else { 0 })
121            .collect();
122        let validity = Validity::from_iter((0..len).map(|index| index % 8 < 4));
123        let array = PrimitiveArray::new(values, validity);
124        assert_eq!(candidate(&array)?, Some((9u16.into(), len / 8 * 3)));
125        Ok(())
126    }
127
128    /// Floats compare by bit pattern, so NaNs are equal and `-0.0` differs from `0.0`.
129    #[test]
130    fn floats_compare_bits() -> VortexResult<()> {
131        let values: Buffer<f64> = [f64::NAN, -0.0, f64::NAN, 0.0, f64::NAN, -0.0, f64::NAN]
132            .into_iter()
133            .collect();
134        let array = PrimitiveArray::new(values, Validity::NonNullable);
135        let (top, count) = candidate(&array)?.vortex_expect("array has valid values");
136        assert!(f64::try_from(top)?.is_nan());
137        assert_eq!(count, 4);
138
139        let values: Buffer<f64> = [0.0, -0.0, -0.0].into_iter().collect();
140        let array = PrimitiveArray::new(values, Validity::NonNullable);
141        let (top, count) = candidate(&array)?.vortex_expect("array has valid values");
142        assert_eq!(f64::try_from(top)?.to_bits(), (-0.0f64).to_bits());
143        assert_eq!(count, 2);
144        Ok(())
145    }
146
147    #[rstest]
148    #[case::all_valid(Validity::NonNullable)]
149    #[case::nullable(Validity::from_iter((0..1_000).map(|index| index % 3 != 0)))]
150    fn bytes(#[case] validity: Validity) -> VortexResult<()> {
151        let values: Buffer<i8> = (0..1_000)
152            .map(|index| {
153                if index % 3 == 0 {
154                    (index % 7) as i8
155                } else {
156                    -5
157                }
158            })
159            .collect();
160        // Every `-5` is valid in both cases.
161        let array = PrimitiveArray::new(values, validity);
162        assert_eq!(candidate(&array)?, Some(((-5i8).into(), 666)));
163        Ok(())
164    }
165
166    #[test]
167    fn all_null() -> VortexResult<()> {
168        let array = PrimitiveArray::new(Buffer::<u32>::zeroed(10), Validity::AllInvalid);
169        assert_eq!(candidate(&array)?, None);
170        Ok(())
171    }
172}