Skip to content

Building 70 Projects ranging from beginner to advanced so anyone can — learn from, build upon, use as a reference, or even copy directly. Owned by my cybersecurity company 👇

9.3 KB
Raw Blame
// ©AngelaMos | 2026
// stats.rs

pub const RECOMMENDED_TRIALS: usize = 30;
pub const MIN_TRIALS_FOR_POWER: usize = 20;
pub const SIGNIFICANCE: f64 = 0.05;

const Q1: f64 = 0.25;
const Q2: f64 = 0.50;
const Q3: f64 = 0.75;
const CONTINUITY: f64 = 0.5;

const ERFC_COEFFICIENTS: [f64; 10] = [
    -1.265_512_23,
    1.000_023_68,
    0.374_091_96,
    0.096_784_18,
    -0.186_288_06,
    0.278_868_07,
    -1.135_203_98,
    1.488_515_87,
    -0.822_152_23,
    0.170_872_77,
];

#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Summary {
    pub n: usize,
    pub min: f64,
    pub q1: f64,
    pub median: f64,
    pub q3: f64,
    pub max: f64,
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Comparison {
    pub u: f64,
    pub z: f64,
    pub p_value: f64,
    pub a12: f64,
}

impl Comparison {
    #[must_use]
    pub fn is_significant(&self) -> bool {
        self.p_value < SIGNIFICANCE
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Underpowered {
    TooFewTrials { smallest: usize, needed: usize },
    Empty,
}

impl std::fmt::Display for Underpowered {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Underpowered::Empty => write!(formatter, "an arm produced no trials"),
            Underpowered::TooFewTrials { smallest, needed } => write!(
                formatter,
                "the smallest arm has {smallest} trial(s) and a Mann-Whitney U test at alpha={SIGNIFICANCE} cannot reject below {needed}, so no comparative claim is available at this trial count"
            ),
        }
    }
}

#[must_use]
#[allow(
    clippy::cast_precision_loss,
    clippy::cast_possible_truncation,
    clippy::cast_sign_loss
)]
pub fn quantile(sorted: &[f64], q: f64) -> f64 {
    if sorted.is_empty() {
        return f64::NAN;
    }
    if sorted.len() == 1 {
        return sorted[0];
    }
    let position = q * ((sorted.len() - 1) as f64);
    let lower = position.floor();
    let fraction = position - lower;
    let index = lower as usize;
    if index + 1 >= sorted.len() {
        return sorted[sorted.len() - 1];
    }
    sorted[index] + fraction * (sorted[index + 1] - sorted[index])
}

#[must_use]
pub fn summarize(samples: &[f64]) -> Option<Summary> {
    if samples.is_empty() {
        return None;
    }
    let mut sorted = samples.to_vec();
    sorted.sort_by(f64::total_cmp);
    Some(Summary {
        n: sorted.len(),
        min: sorted[0],
        q1: quantile(&sorted, Q1),
        median: quantile(&sorted, Q2),
        q3: quantile(&sorted, Q3),
        max: sorted[sorted.len() - 1],
    })
}

// Exact equality is the definition of a tie: two trials that measured the same value share
// a rank. An epsilon margin here would invent ties the data does not contain and shrink the
// variance for runs that are merely close.
#[must_use]
#[allow(clippy::cast_precision_loss, clippy::float_cmp)]
fn ranks(combined: &[f64]) -> (Vec<f64>, f64) {
    let mut order: Vec<usize> = (0..combined.len()).collect();
    order.sort_by(|left, right| combined[*left].total_cmp(&combined[*right]));

    let mut assigned = vec![0.0_f64; combined.len()];
    let mut tie_correction = 0.0_f64;
    let mut start = 0;
    while start < order.len() {
        let mut end = start + 1;
        while end < order.len() && combined[order[end]] == combined[order[start]] {
            end += 1;
        }
        let group = (end - start) as f64;
        let average = ((start + end + 1) as f64) / 2.0;
        for slot in &order[start..end] {
            assigned[*slot] = average;
        }
        tie_correction += group * group * group - group;
        start = end;
    }
    (assigned, tie_correction)
}

#[must_use]
pub fn normal_sf(z: f64) -> f64 {
    erfc(z / std::f64::consts::SQRT_2) / 2.0
}

#[must_use]
fn erfc(x: f64) -> f64 {
    let z = x.abs();
    let t = 1.0 / (1.0 + 0.5 * z);

    let mut polynomial = ERFC_COEFFICIENTS[ERFC_COEFFICIENTS.len() - 1];
    for coefficient in ERFC_COEFFICIENTS[1..ERFC_COEFFICIENTS.len() - 1]
        .iter()
        .rev()
    {
        polynomial = coefficient + t * polynomial;
    }
    let value = t * (-z * z + ERFC_COEFFICIENTS[0] + t * polynomial).exp();
    if x >= 0.0 { value } else { 2.0 - value }
}

#[allow(clippy::cast_precision_loss)]
pub fn mann_whitney(a: &[f64], b: &[f64]) -> Result<Comparison, Underpowered> {
    if a.is_empty() || b.is_empty() {
        return Err(Underpowered::Empty);
    }
    let smallest = a.len().min(b.len());
    if smallest < MIN_TRIALS_FOR_POWER {
        return Err(Underpowered::TooFewTrials {
            smallest,
            needed: MIN_TRIALS_FOR_POWER,
        });
    }

    let mut combined = Vec::with_capacity(a.len() + b.len());
    combined.extend_from_slice(a);
    combined.extend_from_slice(b);
    let (assigned, tie_correction) = ranks(&combined);

    let n1 = a.len() as f64;
    let n2 = b.len() as f64;
    let total = n1 + n2;
    let rank_sum: f64 = assigned[..a.len()].iter().sum();
    let u1 = rank_sum - n1 * (n1 + 1.0) / 2.0;

    let mean = n1 * n2 / 2.0;
    let variance = (n1 * n2 / 12.0) * ((total + 1.0) - tie_correction / (total * (total - 1.0)));
    let z = if variance <= 0.0 {
        0.0
    } else {
        let deviation = u1 - mean;
        let corrected = if deviation.abs() <= CONTINUITY {
            0.0
        } else {
            deviation.abs() - CONTINUITY
        };
        corrected.copysign(deviation) / variance.sqrt()
    };
    let p_value = (2.0 * normal_sf(z.abs())).min(1.0);

    Ok(Comparison {
        u: u1,
        z,
        p_value,
        a12: u1 / (n1 * n2),
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    fn approx(left: f64, right: f64, tolerance: f64) -> bool {
        (left - right).abs() <= tolerance
    }

    #[test]
    fn quantiles_interpolate_the_way_numpy_does() {
        let sorted = [1.0, 2.0, 3.0, 4.0];
        assert!(approx(quantile(&sorted, 0.25), 1.75, 1e-12));
        assert!(approx(quantile(&sorted, 0.50), 2.5, 1e-12));
        assert!(approx(quantile(&sorted, 0.75), 3.25, 1e-12));
    }

    #[test]
    fn a_summary_reports_quartiles_and_not_mean_and_deviation() {
        let summary = summarize(&[5.0, 1.0, 3.0, 2.0, 4.0]).unwrap();
        assert_eq!(summary.n, 5);
        assert!(approx(summary.min, 1.0, 1e-12));
        assert!(approx(summary.q1, 2.0, 1e-12));
        assert!(approx(summary.median, 3.0, 1e-12));
        assert!(approx(summary.q3, 4.0, 1e-12));
        assert!(approx(summary.max, 5.0, 1e-12));
    }

    #[test]
    fn an_empty_sample_has_no_summary() {
        assert!(summarize(&[]).is_none());
    }

    // scipy.stats.norm.sf reference values.
    #[test]
    fn the_normal_survival_function_matches_published_values() {
        for (z, expected) in [
            (0.0, 0.5),
            (1.0, 0.158_655_253_931_457_05),
            (1.959_963_984_540_054, 0.025),
            (2.575_829_303_548_901, 0.005),
            (3.0, 0.001_349_898_031_630_095),
            (4.0, 0.000_031_671_241_833_119_9),
        ] {
            assert!(
                approx(normal_sf(z), expected, 1.5e-7),
                "sf({z}) = {} want {expected}",
                normal_sf(z)
            );
        }
    }

    // Fewer trials than Schloegel et al.'s mathematical floor cannot reject at
    // alpha=0.05 whatever the data, so no comparison is offered at all.
    #[test]
    fn a_trial_count_below_the_power_floor_refuses_to_compare() {
        let a: Vec<f64> = (0..19).map(f64::from).collect();
        let b: Vec<f64> = (0..19).map(|value| f64::from(value) + 1000.0).collect();
        assert_eq!(
            mann_whitney(&a, &b),
            Err(Underpowered::TooFewTrials {
                smallest: 19,
                needed: MIN_TRIALS_FOR_POWER
            })
        );
    }

    #[test]
    fn an_empty_arm_is_refused_before_the_trial_floor_is_considered() {
        let a: Vec<f64> = (0..30).map(f64::from).collect();
        assert_eq!(mann_whitney(&a, &[]), Err(Underpowered::Empty));
    }

    // Known-answer vectors taken from scipy.stats.mannwhitneyu with
    // alternative="two-sided", method="asymptotic", use_continuity=True.
    #[test]
    fn separated_distributions_match_the_scipy_reference() {
        let a: Vec<f64> = (0..30).map(f64::from).collect();
        let b: Vec<f64> = (0..30).map(|value| f64::from(value) + 100.0).collect();
        let result = mann_whitney(&a, &b).unwrap();
        assert!(approx(result.u, 0.0, 1e-9), "u = {}", result.u);
        assert!(approx(result.a12, 0.0, 1e-12), "a12 = {}", result.a12);
        assert!(result.is_significant(), "p = {}", result.p_value);
    }

    #[test]
    fn identical_distributions_are_not_significant_and_score_a_half() {
        let a: Vec<f64> = (0..30).map(f64::from).collect();
        let b: Vec<f64> = (0..30).map(f64::from).collect();
        let result = mann_whitney(&a, &b).unwrap();
        assert!(approx(result.a12, 0.5, 1e-12), "a12 = {}", result.a12);
        assert!(approx(result.p_value, 1.0, 1e-9), "p = {}", result.p_value);
        assert!(!result.is_significant());
    }

    #[test]
    fn ties_shrink_the_variance_rather_than_being_ignored() {
        let tied_a = vec![1.0; 30];
        let mut tied_b = vec![1.0; 29];
        tied_b.push(2.0);
        let tied = mann_whitney(&tied_a, &tied_b).unwrap();
        assert!(tied.p_value.is_finite());
        assert!(!tied.is_significant(), "p = {}", tied.p_value);
    }
}