glubglub 0.0.1-alpha.1

A HyperLogLog and HyperLogLog++ implementation in Rust.
Documentation
/// Computes the harmonic mean given the number of bits in each
/// element of the mean.
///
/// This is the basis for the "raw" estimate in HyperLogLog.
pub fn harmonic_mean_bit_couters(values: &[u8]) -> f64 {
    let sum_of_inverses: f64 = values.iter().map(|&x| 2f64.powi(-(x as i32))).sum();

    1. / sum_of_inverses
}

/// Estimate the cardinality using the Linear Counting algorithm.
/// This is used in HyperLogLog++ for small cardinalities.
/// See "Figure 1: The practical variant of the HyperLogLog algorithm
/// as presented in [original HyperLogLog paper]" in the HyperLogLog++ paper.
pub fn linear_counting(
    // m on Figure 1 of the HyperLogLog++ paper
    // The number of total registers, also referred to as "slots".
    // This is 2^p where p is the precision factor.
    register_count: usize,
    // V in Figure 1 of the HyperLogLog++ paper.
    // The number of registers equal to 0.
    zero_count: usize,
) -> f64 {
    debug_assert!(
        zero_count <= register_count,
        "zero_count must be less than or equal to register_count"
    );
    debug_assert!(
        zero_count > 0,
        "linear_counting is only defined for zero_count > 0"
    );
    let m = register_count as f64;
    let v = zero_count as f64;
    m * (m / v).ln()
}

#[test]
fn test_linear_counting_all_zeros() {
    // An all-zero register set can only happen if no elements have been added.
    // In this case, the estimate should be _exactly_ 0.
    let estimate = linear_counting(1 << 16, 1 << 16);
    assert_eq!(
        estimate, 0.,
        "Estimate for all-zero registers should be 0, got {}",
        estimate
    );
}

#[test]
fn test_linear_counting_for_single_slot() {
    let estimate = linear_counting(1 << 16, (1 << 16) - 1);
    let expected = 1.;
    let error = (estimate - expected).abs();
    assert!(
        error < 1.0,
        "Estimate {} differs from expected {} by more than 1.0",
        estimate,
        expected
    );
}

#[cfg(test)]
pub(crate) fn compare_result(result: u64, expected: u64, error_margin: f64) {
    let error = (expected as f64 * error_margin).ceil() as u64;
    assert!(
        (result as i64 - expected as i64).unsigned_abs() <= error,
        "count {} is not within the error margin of {:.2}% from expected count {}",
        result,
        error_margin * 100.,
        expected,
    );
}

#[cfg(test)]
pub(crate) fn fill_with_n_distinct<S>(set: &mut S, n: u64)
where
    S: crate::RawApproxSet,
{
    let start = rand::random_range(0..(u64::MAX - n));

    for i in start..(start + n) {
        use std::hash::BuildHasher;
        let hash = fasthash::metro::Hash64_1.hash_one(i);
        set.insert_hash(hash);
    }
}