Skip to main content

rsomics_composition/
adjustment.rs

1use crate::{CompositionError, Result};
2
3#[derive(Clone, Copy, Debug, Eq, PartialEq)]
4#[non_exhaustive]
5pub enum PAdjustMethod {
6    None,
7    Bonferroni,
8    Holm,
9    BenjaminiHochberg,
10}
11
12pub(crate) fn adjust_pvalues(
13    pvalues: &[Option<f64>],
14    method: PAdjustMethod,
15) -> Result<Vec<Option<f64>>> {
16    let mut observed = Vec::with_capacity(pvalues.len());
17    let mut positions = Vec::with_capacity(pvalues.len());
18    for (position, value) in pvalues.iter().copied().enumerate() {
19        if let Some(value) = value {
20            if !value.is_finite() || !(0.0..=1.0).contains(&value) {
21                return Err(CompositionError::Statistics(format!(
22                    "p-value must be finite and between zero and one, got {value}"
23                )));
24            }
25            observed.push(value);
26            positions.push(position);
27        }
28    }
29    let adjusted = match method {
30        PAdjustMethod::None => observed,
31        PAdjustMethod::Bonferroni => bonferroni(&observed),
32        PAdjustMethod::Holm => holm(&observed),
33        PAdjustMethod::BenjaminiHochberg => benjamini_hochberg(&observed),
34    };
35    let mut output = vec![None; pvalues.len()];
36    for (position, value) in positions.into_iter().zip(adjusted) {
37        output[position] = Some(value);
38    }
39    Ok(output)
40}
41
42fn bonferroni(pvalues: &[f64]) -> Vec<f64> {
43    let tests = pvalues.len() as f64;
44    pvalues
45        .iter()
46        .map(|value| (value * tests).min(1.0))
47        .collect()
48}
49
50fn holm(pvalues: &[f64]) -> Vec<f64> {
51    let mut order: Vec<usize> = (0..pvalues.len()).collect();
52    order.sort_by(|&left, &right| pvalues[left].total_cmp(&pvalues[right]));
53    let mut adjusted = vec![0.0; pvalues.len()];
54    let mut running = 0.0_f64;
55    for (rank, index) in order.into_iter().enumerate() {
56        running = running.max(((pvalues.len() - rank) as f64 * pvalues[index]).min(1.0));
57        adjusted[index] = running;
58    }
59    adjusted
60}
61
62fn benjamini_hochberg(pvalues: &[f64]) -> Vec<f64> {
63    let mut order: Vec<usize> = (0..pvalues.len()).collect();
64    order.sort_by(|&left, &right| pvalues[left].total_cmp(&pvalues[right]));
65    let mut adjusted = vec![0.0; pvalues.len()];
66    let mut running = 1.0_f64;
67    for (rank, index) in order.into_iter().enumerate().rev() {
68        running = running.min((pvalues[index] * pvalues.len() as f64 / (rank + 1) as f64).min(1.0));
69        adjusted[index] = running;
70    }
71    adjusted
72}
73
74#[cfg(test)]
75mod tests {
76    use super::*;
77
78    #[test]
79    fn missing_tests_do_not_enter_the_family_size() {
80        assert_eq!(
81            adjust_pvalues(
82                &[Some(0.01), None, Some(0.04), Some(0.5)],
83                PAdjustMethod::Holm,
84            )
85            .unwrap(),
86            vec![Some(0.03), None, Some(0.08), Some(0.5)]
87        );
88        assert_eq!(
89            adjust_pvalues(
90                &[Some(0.01), None, Some(0.02)],
91                PAdjustMethod::BenjaminiHochberg,
92            )
93            .unwrap(),
94            vec![Some(0.02), None, Some(0.02)]
95        );
96    }
97
98    #[test]
99    fn invalid_values_are_rejected() {
100        for value in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -0.1, 1.1] {
101            assert!(adjust_pvalues(&[Some(value)], PAdjustMethod::Holm).is_err());
102        }
103    }
104}