Skip to main content

legume_numeric/matrix/
robust_band.rs

1//! Robust (median ± MAD) outlier bands, for cell QC and any per-unit metric.
2//!
3//! Moved from data-beans' `qc_lib` (which re-exports it) so crates below
4//! data-beans can use it without depending on data-beans.
5
6/// Which side(s) of the robust band count as outliers.
7#[derive(Clone, Copy, Debug, PartialEq, Eq)]
8pub enum Tail {
9    /// Flag values far *below* the median (e.g. low counts / few genes).
10    Lower,
11    /// Flag values far *above* the median (e.g. high mito fraction).
12    Upper,
13    /// Flag both extremes.
14    Both,
15}
16
17/// Median of a non-empty slice via `O(n)` quickselect (reorders in place).
18fn median_in_place(xs: &mut [f32]) -> f32 {
19    let mid = xs.len() / 2;
20    xs.select_nth_unstable_by(mid, |a, b| a.total_cmp(b));
21    xs[mid]
22}
23
24/// The robust band [`robust_outlier_keep`] tests against: `median ± n_mads ·
25/// MAD · 1.4826`, on the `log1p` scale when asked.
26#[derive(Clone, Copy, Debug)]
27pub struct RobustBand {
28    pub median: f32,
29    pub lo: f32,
30    pub hi: f32,
31}
32
33impl RobustBand {
34    /// The band on the values' own scale, undoing `log1p`.
35    pub fn raw(self, log1p: bool) -> Self {
36        let back = |v: f32| if log1p { v.exp_m1() } else { v };
37        Self {
38            median: back(self.median),
39            lo: back(self.lo),
40            hi: back(self.hi),
41        }
42    }
43}
44
45/// A value on the scale its band is fitted on: `ln(1 + v)` for counts.
46fn band_scale(v: f32, log1p: bool) -> f32 {
47    if log1p {
48        v.max(0.0).ln_1p()
49    } else {
50        v
51    }
52}
53
54/// [`RobustBand`] of `values` (the `consider`ed ones, when given); `None`
55/// when none is finite, or when they have no spread (a MAD of 0).
56pub fn robust_band(
57    values: &[f32],
58    n_mads: f32,
59    log1p: bool,
60    consider: Option<&[bool]>,
61) -> Option<RobustBand> {
62    let xform = |v: f32| band_scale(v, log1p);
63
64    // Band statistics computed over the considered subset only.
65    let mut xs: Vec<f32> = values
66        .iter()
67        .enumerate()
68        .filter(|(i, _)| consider.is_none_or(|c| c[*i]))
69        .map(|(_, &v)| xform(v))
70        .filter(|v| v.is_finite())
71        .collect();
72    if xs.is_empty() {
73        return None;
74    }
75    // O(n) median via quickselect (no full sort).
76    let median = median_in_place(&mut xs);
77
78    let mut dev: Vec<f32> = xs.iter().map(|&v| (v - median).abs()).collect();
79    let mad = median_in_place(&mut dev) * 1.4826;
80    // No spread: more than half the values are one value (a mito fraction
81    // of 0 in most nuclei, say). A band of width 0 would call every other
82    // value an outlier, so there is none.
83    if mad <= 0.0 {
84        return None;
85    }
86
87    Some(RobustBand {
88        median,
89        lo: median - n_mads * mad,
90        hi: median + n_mads * mad,
91    })
92}
93
94/// Robust outlier keep-mask: `keep[i] = false` when `values[i]` falls
95/// outside `median ± n_mads · MAD · 1.4826` on the requested `tail`.
96/// Count-like metrics should pass `log1p = true` so the band is symmetric
97/// on the multiplicative scale. Consolidates the median+MAD idiom used in
98/// `cnv::hmm`.
99/// `consider` (when `Some`) restricts the median/MAD band to the cells it
100/// marks `true` — so e.g. near-empty cells don't contaminate the robust
101/// center — while the keep decision is still returned for every cell.
102pub fn robust_outlier_keep(
103    values: &[f32],
104    n_mads: f32,
105    tail: Tail,
106    log1p: bool,
107    consider: Option<&[bool]>,
108) -> Vec<bool> {
109    let n = values.len();
110    let Some(band) = robust_band(values, n_mads, log1p, consider) else {
111        return vec![true; n];
112    };
113    let xform = |v: f32| band_scale(v, log1p);
114    let (lo, hi) = (band.lo, band.hi);
115    values
116        .iter()
117        .map(|&raw| {
118            let v = xform(raw);
119            if !v.is_finite() {
120                return false;
121            }
122            match tail {
123                Tail::Lower => v >= lo,
124                Tail::Upper => v <= hi,
125                Tail::Both => v >= lo && v <= hi,
126            }
127        })
128        .collect()
129}
130
131#[cfg(test)]
132mod tests {
133    use super::*;
134
135    #[test]
136    fn robust_lower_flags_low_outlier() {
137        let v = vec![100.0, 110.0, 90.0, 105.0, 95.0, 1.0];
138        let keep = robust_outlier_keep(&v, 3.0, Tail::Lower, true, None);
139        assert!(!keep[5], "the value 1.0 should be a lower outlier");
140        assert!(keep[..5].iter().all(|&k| k), "the bulk should be kept");
141        // upper tail must not flag a low value
142        let keep_up = robust_outlier_keep(&v, 3.0, Tail::Upper, true, None);
143        assert!(keep_up[5], "lower outlier kept under Tail::Upper");
144    }
145
146    #[test]
147    fn no_spread_flags_no_one() {
148        // Most cells read no mito at all: the MAD is 0, and a cell with one
149        // mito read is no outlier for it.
150        let mut v = vec![0.0f32; 60];
151        v.extend([0.01, 0.02, 0.05, 0.3]);
152        assert!(robust_band(&v, 5.0, false, None).is_none());
153        let keep = robust_outlier_keep(&v, 5.0, Tail::Upper, false, None);
154        assert!(keep.iter().all(|&k| k));
155    }
156
157    #[test]
158    fn robust_uniform_keeps_all() {
159        let v = vec![7.0; 20];
160        let keep = robust_outlier_keep(&v, 5.0, Tail::Both, true, None);
161        assert!(keep.iter().all(|&k| k));
162    }
163
164    #[test]
165    fn robust_consider_excludes_contaminants_from_band() {
166        // A real cluster around 100 plus a large block of near-empty 0s that
167        // would drag a naive median/MAD down. With `consider` masking the
168        // zeros out of the band, a genuine low real cell (40) is still flagged.
169        let mut v = vec![0.0; 12];
170        v.extend([100.0, 102.0, 98.0, 101.0, 99.0, 40.0]);
171        let mut consider = vec![false; 12];
172        consider.extend([true; 6]);
173        let keep = robust_outlier_keep(&v, 2.0, Tail::Lower, true, Some(&consider));
174        assert!(
175            !keep[17],
176            "40 is a lower outlier of the real cluster (~100)"
177        );
178        // Without `consider`, the zeros dominate the median and 40 survives.
179        let keep_naive = robust_outlier_keep(&v, 2.0, Tail::Lower, true, None);
180        assert!(
181            keep_naive[17],
182            "naive band (contaminated by zeros) keeps 40"
183        );
184    }
185}