rsomics-composition 0.1.0

Compositional-data geometry, transforms, and differential abundance
Documentation
use crate::{CompositionError, Result};

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum PAdjustMethod {
    None,
    Bonferroni,
    Holm,
    BenjaminiHochberg,
}

pub(crate) fn adjust_pvalues(
    pvalues: &[Option<f64>],
    method: PAdjustMethod,
) -> Result<Vec<Option<f64>>> {
    let mut observed = Vec::with_capacity(pvalues.len());
    let mut positions = Vec::with_capacity(pvalues.len());
    for (position, value) in pvalues.iter().copied().enumerate() {
        if let Some(value) = value {
            if !value.is_finite() || !(0.0..=1.0).contains(&value) {
                return Err(CompositionError::Statistics(format!(
                    "p-value must be finite and between zero and one, got {value}"
                )));
            }
            observed.push(value);
            positions.push(position);
        }
    }
    let adjusted = match method {
        PAdjustMethod::None => observed,
        PAdjustMethod::Bonferroni => bonferroni(&observed),
        PAdjustMethod::Holm => holm(&observed),
        PAdjustMethod::BenjaminiHochberg => benjamini_hochberg(&observed),
    };
    let mut output = vec![None; pvalues.len()];
    for (position, value) in positions.into_iter().zip(adjusted) {
        output[position] = Some(value);
    }
    Ok(output)
}

fn bonferroni(pvalues: &[f64]) -> Vec<f64> {
    let tests = pvalues.len() as f64;
    pvalues
        .iter()
        .map(|value| (value * tests).min(1.0))
        .collect()
}

fn holm(pvalues: &[f64]) -> Vec<f64> {
    let mut order: Vec<usize> = (0..pvalues.len()).collect();
    order.sort_by(|&left, &right| pvalues[left].total_cmp(&pvalues[right]));
    let mut adjusted = vec![0.0; pvalues.len()];
    let mut running = 0.0_f64;
    for (rank, index) in order.into_iter().enumerate() {
        running = running.max(((pvalues.len() - rank) as f64 * pvalues[index]).min(1.0));
        adjusted[index] = running;
    }
    adjusted
}

fn benjamini_hochberg(pvalues: &[f64]) -> Vec<f64> {
    let mut order: Vec<usize> = (0..pvalues.len()).collect();
    order.sort_by(|&left, &right| pvalues[left].total_cmp(&pvalues[right]));
    let mut adjusted = vec![0.0; pvalues.len()];
    let mut running = 1.0_f64;
    for (rank, index) in order.into_iter().enumerate().rev() {
        running = running.min((pvalues[index] * pvalues.len() as f64 / (rank + 1) as f64).min(1.0));
        adjusted[index] = running;
    }
    adjusted
}

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

    #[test]
    fn missing_tests_do_not_enter_the_family_size() {
        assert_eq!(
            adjust_pvalues(
                &[Some(0.01), None, Some(0.04), Some(0.5)],
                PAdjustMethod::Holm,
            )
            .unwrap(),
            vec![Some(0.03), None, Some(0.08), Some(0.5)]
        );
        assert_eq!(
            adjust_pvalues(
                &[Some(0.01), None, Some(0.02)],
                PAdjustMethod::BenjaminiHochberg,
            )
            .unwrap(),
            vec![Some(0.02), None, Some(0.02)]
        );
    }

    #[test]
    fn invalid_values_are_rejected() {
        for value in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -0.1, 1.1] {
            assert!(adjust_pvalues(&[Some(value)], PAdjustMethod::Holm).is_err());
        }
    }
}