Path: blob/main/crates/polars-utils/src/cardinality_sketch.rs
6939 views
use crate::algebraic_ops::alg_add_f64;12// Computes 2^-n by directly subtracting from the IEEE754 double exponent.3fn inv_pow2(n: u8) -> f64 {4let base = f64::to_bits(1.0);5f64::from_bits(base - ((n as u64) << 52))6}78/// HyperLogLog in Practice: Algorithmic Engineering of9/// a State of The Art Cardinality Estimation Algorithm10/// Stefan Heule, Marc Nunkesser, Alexander Hall11///12/// We use m = 256 which gives a relative error of ~6.5% of the cardinality13/// estimate. We don't bother with stuffing the counts in 6 bits, byte access is14/// fast.15///16/// The bias correction described in the paper is not implemented, so this is17/// somewhere in between HyperLogLog and HyperLogLog++.18#[derive(Clone)]19pub struct CardinalitySketch {20buckets: Box<[u8; 256]>,21}2223impl Default for CardinalitySketch {24fn default() -> Self {25Self::new()26}27}2829impl CardinalitySketch {30pub fn new() -> Self {31Self {32// This compiles to alloc_zeroed directly.33buckets: vec![0u8; 256].into_boxed_slice().try_into().unwrap(),34}35}3637/// Add a new hash to the sketch.38pub fn insert(&mut self, mut h: u64) {39const ARBITRARY_ODD: u64 = 0x902813a5785dc787;40// We multiply by this arbitrarily chosen odd number and then take the41// top bits to ensure the sketch is influenced by all bits of the hash.42h = h.wrapping_mul(ARBITRARY_ODD);43let idx = (h >> 56) as usize;44let p = 1 + (h << 8).leading_zeros() as u8;45self.buckets[idx] = self.buckets[idx].max(p);46}4748pub fn combine(&mut self, other: &CardinalitySketch) {49*self.buckets = std::array::from_fn(|i| std::cmp::max(self.buckets[i], other.buckets[i]));50}5152pub fn estimate(&self) -> usize {53let m = 256.0;54let alpha_m = 0.7123 / (1.0 + 1.079 / m);5556let mut sum = 0.0;57let mut num_zero = 0;58for x in self.buckets.iter() {59sum = alg_add_f64(sum, inv_pow2(*x));60num_zero += (*x == 0) as usize;61}6263let est = (alpha_m * m * m) / sum;64let corr_est = if est <= 5.0 / 2.0 * m && num_zero != 0 {65// Small cardinality estimate, full 64-bit logarithm is overkill.66m * (m as f32 / num_zero as f32).ln() as f6467} else {68est69};7071corr_est as usize72}73}747576