1use std::hash::Hash;
5
6use arrow_buffer::BooleanBuffer;
7use num_traits::PrimInt;
8use rustc_hash::FxBuildHasher;
9use vortex_array::ToCanonical;
10use vortex_array::arrays::{NativeValue, PrimitiveArray, PrimitiveVTable};
11use vortex_array::stats::Stat;
12use vortex_dtype::{NativePType, match_each_integer_ptype};
13use vortex_error::{VortexError, VortexExpect, VortexUnwrap};
14use vortex_mask::AllOr;
15use vortex_scalar::{PValue, Scalar};
16use vortex_utils::aliases::hash_map::HashMap;
17
18use crate::sample::sample;
19use crate::{CompressorStats, GenerateStatsOptions};
20
21#[derive(Clone, Debug)]
22pub struct TypedStats<T> {
23 pub min: T,
24 pub max: T,
25 pub top_value: T,
26 pub top_count: u32,
27 pub distinct_values: HashMap<NativeValue<T>, u32, FxBuildHasher>,
28}
29
30#[derive(Clone, Debug)]
35pub enum ErasedStats {
36 U8(TypedStats<u8>),
37 U16(TypedStats<u16>),
38 U32(TypedStats<u32>),
39 U64(TypedStats<u64>),
40 I8(TypedStats<i8>),
41 I16(TypedStats<i16>),
42 I32(TypedStats<i32>),
43 I64(TypedStats<i64>),
44}
45
46impl ErasedStats {
47 pub fn min_is_zero(&self) -> bool {
48 match &self {
49 ErasedStats::U8(x) => x.min == 0,
50 ErasedStats::U16(x) => x.min == 0,
51 ErasedStats::U32(x) => x.min == 0,
52 ErasedStats::U64(x) => x.min == 0,
53 ErasedStats::I8(x) => x.min == 0,
54 ErasedStats::I16(x) => x.min == 0,
55 ErasedStats::I32(x) => x.min == 0,
56 ErasedStats::I64(x) => x.min == 0,
57 }
58 }
59
60 pub fn min_is_negative(&self) -> bool {
61 match &self {
62 ErasedStats::U8(_)
63 | ErasedStats::U16(_)
64 | ErasedStats::U32(_)
65 | ErasedStats::U64(_) => false,
66 ErasedStats::I8(x) => x.min < 0,
67 ErasedStats::I16(x) => x.min < 0,
68 ErasedStats::I32(x) => x.min < 0,
69 ErasedStats::I64(x) => x.min < 0,
70 }
71 }
72
73 pub fn max_minus_min(&self) -> u64 {
75 match &self {
76 ErasedStats::U8(x) => (x.max - x.min) as u64,
77 ErasedStats::U16(x) => (x.max - x.min) as u64,
78 ErasedStats::U32(x) => (x.max - x.min) as u64,
79 ErasedStats::U64(x) => x.max - x.min,
80 ErasedStats::I8(x) => (x.max as i16 - x.min as i16) as u64,
81 ErasedStats::I16(x) => (x.max as i32 - x.min as i32) as u64,
82 ErasedStats::I32(x) => (x.max as i64 - x.min as i64) as u64,
83 ErasedStats::I64(x) => u64::try_from(x.max as i128 - x.min as i128)
84 .vortex_expect("max minus min result bigger than u64"),
85 }
86 }
87
88 pub fn top_value_and_count(&self) -> (PValue, u32) {
90 match &self {
91 ErasedStats::U8(x) => (x.top_value.into(), x.top_count),
92 ErasedStats::U16(x) => (x.top_value.into(), x.top_count),
93 ErasedStats::U32(x) => (x.top_value.into(), x.top_count),
94 ErasedStats::U64(x) => (x.top_value.into(), x.top_count),
95 ErasedStats::I8(x) => (x.top_value.into(), x.top_count),
96 ErasedStats::I16(x) => (x.top_value.into(), x.top_count),
97 ErasedStats::I32(x) => (x.top_value.into(), x.top_count),
98 ErasedStats::I64(x) => (x.top_value.into(), x.top_count),
99 }
100 }
101}
102
103macro_rules! impl_from_typed {
104 ($T:ty, $variant:path) => {
105 impl From<TypedStats<$T>> for ErasedStats {
106 fn from(typed: TypedStats<$T>) -> Self {
107 $variant(typed)
108 }
109 }
110 };
111}
112
113impl_from_typed!(u8, ErasedStats::U8);
114impl_from_typed!(u16, ErasedStats::U16);
115impl_from_typed!(u32, ErasedStats::U32);
116impl_from_typed!(u64, ErasedStats::U64);
117impl_from_typed!(i8, ErasedStats::I8);
118impl_from_typed!(i16, ErasedStats::I16);
119impl_from_typed!(i32, ErasedStats::I32);
120impl_from_typed!(i64, ErasedStats::I64);
121
122#[derive(Clone, Debug)]
124pub struct IntegerStats {
125 pub(super) src: PrimitiveArray,
126 pub(super) null_count: u32,
128 pub(super) value_count: u32,
130 pub(super) average_run_length: u32,
131 pub(super) distinct_values_count: u32,
132 pub(crate) typed: ErasedStats,
133}
134
135impl CompressorStats for IntegerStats {
136 type ArrayVTable = PrimitiveVTable;
137
138 fn generate_opts(input: &PrimitiveArray, opts: GenerateStatsOptions) -> Self {
139 match_each_integer_ptype!(input.ptype(), |T| {
140 typed_int_stats::<T>(input, opts.count_distinct_values)
141 })
142 }
143
144 fn source(&self) -> &PrimitiveArray {
145 &self.src
146 }
147
148 fn sample_opts(&self, sample_size: u32, sample_count: u32, opts: GenerateStatsOptions) -> Self {
149 let sampled = sample(self.src.as_ref(), sample_size, sample_count).to_primitive();
150
151 Self::generate_opts(&sampled, opts)
152 }
153}
154
155fn typed_int_stats<T>(array: &PrimitiveArray, count_distinct_values: bool) -> IntegerStats
156where
157 T: NativePType + PrimInt + for<'a> TryFrom<&'a Scalar, Error = VortexError>,
158 TypedStats<T>: Into<ErasedStats>,
159 NativeValue<T>: Eq + Hash,
160{
161 if array.is_empty() {
163 return IntegerStats {
164 src: array.clone(),
165 null_count: 0,
166 value_count: 0,
167 average_run_length: 0,
168 distinct_values_count: 0,
169 typed: TypedStats {
170 min: T::max_value(),
171 max: T::min_value(),
172 top_value: T::default(),
173 top_count: 0,
174 distinct_values: HashMap::with_hasher(FxBuildHasher),
175 }
176 .into(),
177 };
178 } else if array.all_invalid() {
179 return IntegerStats {
180 src: array.clone(),
181 null_count: array.len().try_into().vortex_expect("null_count"),
182 value_count: 0,
183 average_run_length: 0,
184 distinct_values_count: 0,
185 typed: TypedStats {
186 min: T::max_value(),
187 max: T::min_value(),
188 top_value: T::default(),
189 top_count: 0,
190 distinct_values: HashMap::with_hasher(FxBuildHasher),
191 }
192 .into(),
193 };
194 }
195
196 let validity = array.validity_mask();
197 let null_count = validity.false_count();
198 let value_count = validity.true_count();
199
200 let head_idx = validity
202 .first()
203 .vortex_expect("All null masks have been handled before");
204 let buffer = array.buffer::<T>();
205 let head = buffer[head_idx];
206
207 let mut loop_state = LoopState {
208 distinct_values: if count_distinct_values {
209 HashMap::with_capacity_and_hasher(array.len() / 2, FxBuildHasher)
210 } else {
211 HashMap::with_hasher(FxBuildHasher)
212 },
213 prev: head,
214 runs: 1,
215 };
216
217 let sliced = buffer.slice(head_idx..array.len());
218 let mut chunks = sliced.as_slice().chunks_exact(64);
219 match validity.boolean_buffer() {
220 AllOr::All => {
221 for chunk in &mut chunks {
222 inner_loop_nonnull(
223 chunk.try_into().vortex_unwrap(),
224 count_distinct_values,
225 &mut loop_state,
226 )
227 }
228 let remainder = chunks.remainder();
229 inner_loop_naive(
230 remainder,
231 count_distinct_values,
232 &BooleanBuffer::new_set(remainder.len()),
233 &mut loop_state,
234 );
235 }
236 AllOr::None => unreachable!("All invalid arrays have been handled before"),
237 AllOr::Some(v) => {
238 let mask = v.slice(head_idx, array.len() - head_idx);
239 let mut offset = 0;
240 for chunk in &mut chunks {
241 let validity = mask.slice(offset, 64);
242 offset += 64;
243
244 match validity.count_set_bits() {
245 0 => continue,
247 64 => inner_loop_nonnull(
249 chunk.try_into().vortex_unwrap(),
250 count_distinct_values,
251 &mut loop_state,
252 ),
253 _ => inner_loop_nullable(
255 chunk.try_into().vortex_unwrap(),
256 count_distinct_values,
257 &validity,
258 &mut loop_state,
259 ),
260 }
261 }
262 let remainder = chunks.remainder();
264 inner_loop_naive(
265 remainder,
266 count_distinct_values,
267 &mask.slice(offset, remainder.len()),
268 &mut loop_state,
269 );
270 }
271 }
272
273 let (top_value, top_count) = if count_distinct_values {
274 let (&top_value, &top_count) = loop_state
275 .distinct_values
276 .iter()
277 .max_by_key(|&(_, &count)| count)
278 .vortex_expect("non-empty");
279 (top_value.0, top_count)
280 } else {
281 (T::default(), 0)
282 };
283
284 let runs = loop_state.runs;
285 let distinct_values_count = if count_distinct_values {
286 loop_state.distinct_values.len().try_into().vortex_unwrap()
287 } else {
288 u32::MAX
289 };
290
291 let min = array
292 .statistics()
293 .compute_as::<T>(Stat::Min)
294 .vortex_expect("min should be computed");
295
296 let max = array
297 .statistics()
298 .compute_as::<T>(Stat::Max)
299 .vortex_expect("max should be computed");
300
301 let typed = TypedStats {
302 min,
303 max,
304 distinct_values: loop_state.distinct_values,
305 top_value,
306 top_count,
307 };
308
309 let null_count = null_count
310 .try_into()
311 .vortex_expect("null_count must fit in u32");
312 let value_count = value_count
313 .try_into()
314 .vortex_expect("value_count must fit in u32");
315
316 IntegerStats {
317 src: array.clone(),
318 null_count,
319 value_count,
320 average_run_length: value_count / runs,
321 distinct_values_count,
322 typed: typed.into(),
323 }
324}
325
326struct LoopState<T> {
327 prev: T,
328 runs: u32,
329 distinct_values: HashMap<NativeValue<T>, u32, FxBuildHasher>,
330}
331
332#[inline(always)]
333fn inner_loop_nonnull<T: NativePType>(
334 values: &[T; 64],
335 count_distinct_values: bool,
336 state: &mut LoopState<T>,
337) where
338 NativeValue<T>: Eq + Hash,
339{
340 for &value in values {
341 if count_distinct_values {
342 *state.distinct_values.entry(NativeValue(value)).or_insert(0) += 1;
343 }
344
345 if value != state.prev {
346 state.prev = value;
347 state.runs += 1;
348 }
349 }
350}
351
352#[inline(always)]
353fn inner_loop_nullable<T: NativePType>(
354 values: &[T; 64],
355 count_distinct_values: bool,
356 is_valid: &BooleanBuffer,
357 state: &mut LoopState<T>,
358) where
359 NativeValue<T>: Eq + Hash,
360{
361 for (idx, &value) in values.iter().enumerate() {
362 if is_valid.value(idx) {
363 if count_distinct_values {
364 *state.distinct_values.entry(NativeValue(value)).or_insert(0) += 1;
365 }
366
367 if value != state.prev {
368 state.prev = value;
369 state.runs += 1;
370 }
371 }
372 }
373}
374
375#[inline(always)]
376fn inner_loop_naive<T: NativePType>(
377 values: &[T],
378 count_distinct_values: bool,
379 is_valid: &BooleanBuffer,
380 state: &mut LoopState<T>,
381) where
382 NativeValue<T>: Eq + Hash,
383{
384 for (idx, &value) in values.iter().enumerate() {
385 if is_valid.value(idx) {
386 if count_distinct_values {
387 *state.distinct_values.entry(NativeValue(value)).or_insert(0) += 1;
388 }
389
390 if value != state.prev {
391 state.prev = value;
392 state.runs += 1;
393 }
394 }
395 }
396}
397
398#[cfg(test)]
399mod tests {
400 use std::iter;
401
402 use arrow_buffer::BooleanBuffer;
403 use vortex_array::arrays::PrimitiveArray;
404 use vortex_array::validity::Validity;
405 use vortex_buffer::{Buffer, buffer};
406
407 use crate::CompressorStats;
408 use crate::integer::IntegerStats;
409 use crate::integer::stats::typed_int_stats;
410
411 #[test]
412 fn test_naive_count_distinct_values() {
413 let array = PrimitiveArray::new(buffer![217u8, 0], Validity::NonNullable);
414 let stats = typed_int_stats::<u8>(&array, true);
415 assert_eq!(stats.distinct_values_count, 2);
416 }
417
418 #[test]
419 fn test_naive_count_distinct_values_nullable() {
420 let array = PrimitiveArray::new(
421 buffer![217u8, 0],
422 Validity::from(BooleanBuffer::from(vec![true, false])),
423 );
424 let stats = typed_int_stats::<u8>(&array, true);
425 assert_eq!(stats.distinct_values_count, 1);
426 }
427
428 #[test]
429 fn test_count_distinct_values() {
430 let array = PrimitiveArray::new((0..128u8).collect::<Buffer<u8>>(), Validity::NonNullable);
431 let stats = typed_int_stats::<u8>(&array, true);
432 assert_eq!(stats.distinct_values_count, 128);
433 }
434
435 #[test]
436 fn test_count_distinct_values_nullable() {
437 let array = PrimitiveArray::new(
438 (0..128u8).collect::<Buffer<u8>>(),
439 Validity::from(BooleanBuffer::from_iter(
440 iter::repeat_n(vec![true, false], 64).flatten(),
441 )),
442 );
443 let stats = typed_int_stats::<u8>(&array, true);
444 assert_eq!(stats.distinct_values_count, 64);
445 }
446
447 #[test]
448 fn test_integer_stats_leading_nulls() {
449 let ints = PrimitiveArray::new(buffer![0, 1, 2], Validity::from_iter([false, true, true]));
450
451 let stats = IntegerStats::generate(&ints);
452
453 assert_eq!(stats.value_count, 2);
454 assert_eq!(stats.null_count, 1);
455 assert_eq!(stats.average_run_length, 1);
456 assert_eq!(stats.distinct_values_count, 2);
457 }
458}