Skip to main content

vortex_array/arrays/primitive/array/
top_value.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::hash::Hash;
5
6use rustc_hash::FxBuildHasher;
7use vortex_error::VortexExpect;
8use vortex_error::VortexResult;
9use vortex_mask::AllOr;
10use vortex_mask::Mask;
11use vortex_utils::aliases::hash_map::HashMap;
12
13use crate::ExecutionCtx;
14use crate::arrays::PrimitiveArray;
15use crate::arrays::primitive::NativeValue;
16use crate::dtype::NativePType;
17use crate::match_each_native_ptype;
18use crate::scalar::PValue;
19
20impl PrimitiveArray {
21    /// Compute most common present value of this array
22    pub fn top_value(&self, ctx: &mut ExecutionCtx) -> VortexResult<Option<(PValue, usize)>> {
23        if self.is_empty() {
24            return Ok(None);
25        }
26
27        if self.validity()?.definitely_all_null() {
28            return Ok(None);
29        }
30
31        match_each_native_ptype!(self.ptype(), |P| {
32            let (top, count) = typed_top_value(
33                self.as_slice::<P>(),
34                self.as_ref()
35                    .validity()?
36                    .execute_mask(self.as_ref().len(), ctx)?,
37            );
38            Ok(Some((top.into(), count)))
39        })
40    }
41}
42
43fn typed_top_value<T>(values: &[T], mask: Mask) -> (T, usize)
44where
45    T: NativePType,
46    NativeValue<T>: Eq + Hash,
47{
48    let mut distinct_values: HashMap<NativeValue<T>, usize, FxBuildHasher> =
49        HashMap::with_hasher(FxBuildHasher);
50    match mask.indices() {
51        AllOr::All => {
52            for value in values.iter().copied() {
53                *distinct_values.entry(NativeValue(value)).or_insert(0) += 1;
54            }
55        }
56        AllOr::None => unreachable!("All invalid arrays should be handled earlier"),
57        AllOr::Some(idxs) => {
58            for &i in idxs {
59                *distinct_values
60                    .entry(NativeValue(unsafe { *values.get_unchecked(i) }))
61                    .or_insert(0) += 1
62            }
63        }
64    }
65
66    let (&top_value, &top_count) = distinct_values
67        .iter()
68        .max_by_key(|&(_, &count)| count)
69        .vortex_expect("non-empty");
70    (top_value.0, top_count)
71}