vyre 0.4.0

GPU compute intermediate representation with a standard operation library
Documentation


//! WGSL spelling note for `stats.chi_square`.

/// WGSL helper body used by conform to identify chi-square lowering.
pub const WGSL_SPELLING: &str = r"
pub fn stats_chi_square_term(count: u32, expected: f32) -> f32 {
    let delta = f32(count) - expected;
    return (delta * delta) / expected;
}
";

/// Compute Pearson chi-square deviation from a uniform byte distribution.
///
/// Empty input returns `0.0`.
#[must_use]
pub fn chi_square(input: &[u8]) -> f32 {
    if input.is_empty() {
        return 0.0;
    }
    let mut counts = [0_u32; 256];
    for &byte in input {
        counts[usize::from(byte)] = counts[usize::from(byte)].wrapping_add(1);
    }
    let expected = input.len() as f64 / 256.0;
    counts
        .iter()
        .map(|&count| {
            let delta = f64::from(count) - expected;
            delta * delta / expected
        })
        .sum::<f64>() as f32
}

/// Compute chi-square and return its IEEE-754 binary32 bit pattern.
#[must_use]
pub fn chi_square_bits(input: &[u8]) -> u32 {
    chi_square(input).to_bits()
}