glubglub 0.0.1-alpha.1

A HyperLogLog and HyperLogLog++ implementation in Rust.
Documentation
/// Minimum precision factor for HyperLogLog++ algorithm.
const MIN_PRECISION_FACTOR: usize = 4;

/// Maximum precision factor for HyperLogLog++ algorithm.
const MAX_PRECISION_FACTOR: usize = 32;

/// A raw HyperLogLog structure that implements the core algorithm.
/// This struct expects hashed values as inputs. Elements should be hashed
/// using the same hash function before insertion in order for the statistical
/// properties of HyperLogLog are maintained.
#[derive(Debug, Clone)]
pub struct RawHLL {
    data: Box<[u8]>,
}

impl Default for RawHLL {
    fn default() -> Self {
        Self {
            // 2^14 = 16384 registers, which corresponds to a precision factor of 14.
            // This is the reference value used in the HyperLogLog++ paper, mentioned as:
            // "For brevity, and since the results are qualitatively similar, we illustrate
            // the behavior of the algorithm by considering only precision 14 here and in
            // the remainder of the paper." (section 5.2 paragraph 4)
            data: Box::new([0; 1 << 14]),
        }
    }
}

impl RawHLL {
    /// Create a new RawHLL with the specified precision factor.
    /// The precision factor must be between 4 and 32, inclusive.
    /// Higher precision factors use more memory but provide better accuracy.
    ///
    /// # Panics
    /// Panics if the precision factor is not between 4 and 32.
    pub fn with_precision(precision: usize) -> Self {
        assert!(
            (MIN_PRECISION_FACTOR..=MAX_PRECISION_FACTOR).contains(&precision),
            "Precision factor must be between {} and {}",
            MIN_PRECISION_FACTOR,
            MAX_PRECISION_FACTOR
        );
        let register_count = 1 << precision;
        Self {
            data: vec![0; register_count].into_boxed_slice(),
        }
    }

    /// Create a new RawHLL with the specified precision factor.
    /// The precision factor must be between 4 and 32, inclusive.
    /// Higher precision factors use more memory but provide better accuracy.
    ///
    /// Returns `None` if the precision factor is not between 4 and 32.
    /// Returns `Some(RawHLL)` if the precision factor is valid.
    pub fn try_with_precision(precision: usize) -> Option<Self> {
        if !(MIN_PRECISION_FACTOR..=MAX_PRECISION_FACTOR).contains(&precision) {
            return None;
        }
        let register_count = 1 << precision;
        Some(Self {
            data: vec![0; register_count].into_boxed_slice(),
        })
    }
}

#[test]
fn precision_validation() {
    assert!(RawHLL::try_with_precision(3).is_none());
    assert!(RawHLL::try_with_precision(4).is_some());
    assert!(RawHLL::try_with_precision(32).is_some());
    assert!(RawHLL::try_with_precision(33).is_none());

    assert!(std::panic::catch_unwind(|| RawHLL::with_precision(3)).is_err());
    assert!(std::panic::catch_unwind(|| RawHLL::with_precision(4)).is_ok());
    assert!(std::panic::catch_unwind(|| RawHLL::with_precision(32)).is_ok());
    assert!(std::panic::catch_unwind(|| RawHLL::with_precision(33)).is_err());
}

impl super::sealed::RawApproxSet for RawHLL {
    fn insert_hash(&mut self, hash: u64) {
        debug_assert!(
            self.data.len().is_power_of_two(),
            "Register count must be a power of two"
        );

        // The algorithm from HyperLogLog extracts the top p bits
        // from the hash to determine the register index, where
        // p = log2(m) and m is the number of registers (self.data.len()).
        // The leading zero bits from the remaining 64 -p bits determine
        // the value to store in the register.
        //
        // Instead of doing the more complex bit fidling to extract the
        // _top_ p bits followed by leading zeros from the middle of the hash,
        // we can use a simpler approach that is equivalent:
        // 1. Use the bottom p bits to determine the register index.
        // 2. Shift the hash right by p bits, and count the trailing zeros
        //    in the remaining bits.
        //
        // This works because the hash is assumed to be uniformly distributed,
        // so all bits are equally random. This approach is the same as reversing
        // the hash bits and then applying the original algorithm.

        let p = self.data.len().ilog2();
        let mask = (self.data.len() - 1) as u64;
        let index = (hash & mask) as usize;
        let w = hash >> p;

        // This cast never truncates because w is at most
        // 56 bits (u64 shifted by one byte), which fits in u8.
        let v = w.trailing_zeros() as u8;
        self.data[index] = u8::max(self.data[index], v + 1);
    }

    fn count(&self) -> u64 {
        let small_range_threshold = (5 * (self.data.len() >> 1)) as f64;

        let estimate = match compute_raw_estimate(&self.data) {
            e if e <= small_range_threshold => {
                // Use linear counting for small cardinalities.
                let zero_count = self.data.iter().filter(|&&x| x == 0).count();
                if zero_count > 0 {
                    crate::common::linear_counting(self.data.len(), zero_count)
                } else {
                    e
                }
            }
            e => e,
        };

        estimate.round() as u64
    }

    fn union(&self, other: &Self) -> Self {
        let mut result = Self::default();
        for i in 0..self.data.len() {
            result.data[i] = u8::max(self.data[i], other.data[i]);
        }
        result
    }
}

/// Computes the raw cardinality estimate from the inner state
/// of a HyperLogLog structure.
///
/// This does not apply any bias correction or small-range
/// correction, it simply computes the raw HyperLogLog estimate.
pub(crate) fn compute_raw_estimate(registers: &[u8]) -> f64 {
    // The number of registers (m in the HyperLogLog paper).
    let m = registers.len();
    // Define a16 = 0.673, α32 = 0.697, α64 = 0.709,
    // αm = 0.7213/(1 + 1.079/m) for m≥128.
    let a_sub_m: f64 = match m {
        16 => 0.673,
        32 => 0.697,
        64 => 0.709,
        _ if m >= 128 => 0.7213 / (1. + (1.079 / m as f64)),
        _ => unreachable!("m must be a power of two and at least 16"),
    };

    let harmonic_mean = crate::common::harmonic_mean_bit_couters(registers);
    let scaling_factor = a_sub_m * (m * m) as f64;
    scaling_factor * harmonic_mean
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::common;
    use crate::sealed::RawApproxSet;

    #[test]
    fn test_zero_entries() {
        let hll = RawHLL::default();
        assert_eq!(hll.count(), 0);
    }

    #[test]
    fn test_single_entry() {
        let mut hll = RawHLL::default();
        common::fill_with_n_distinct(&mut hll, 1);
        assert_eq!(hll.count(), 1);
    }

    #[cfg(feature = "test")]
    #[test]
    fn test_small_sets() {
        for n in [10, 100, 1000, 10_000, 100_000] {
            let mut hll = RawHLL::with_precision(26);
            common::fill_with_n_distinct(&mut hll, n);
            common::compare_result(hll.count(), n, 0.005);
        }
    }

    #[cfg(feature = "test")]
    #[test]
    fn test_large_sets() {
        let mut hll = RawHLL::with_precision(26);
        common::fill_with_n_distinct(&mut hll, 10_000_000);
        common::compare_result(hll.count(), 10_000_000, 0.005);
    }
}