Skip to main content

dima_core/
stats.rs

1//! Support classes, diversity motifs and incidences of a position (Tharanga et al. 2025;
2//! motif definitions after Hu et al. 2013 and Khan et al. 2008).
3
4use crate::model::{Motif, SupportLabel};
5
6/// Low-support class of a position: NS (N = 0), LS (0 < N < T), ELS (N = T); `None` for
7/// eligible positions (N > T).
8#[must_use]
9pub const fn support_label(support: u64, threshold: u64) -> Option<SupportLabel> {
10    if support == 0 {
11        Some(SupportLabel::NoSupport)
12    } else if support < threshold {
13        Some(SupportLabel::Low)
14    } else if support == threshold {
15        Some(SupportLabel::EqualToThreshold)
16    } else {
17        None
18    }
19}
20
21/// `count / support × 100`, rounded once (`support` must be positive).
22#[must_use]
23pub fn incidence(count: u64, support: u64) -> f64 {
24    debug_assert!(support > 0);
25    (u128::from(count) * 100) as f64 / support as f64
26}
27
28/// Classifies the variants of a position, given their counts in descending order:
29///
30/// * **Index**: the highest count, if above 1 (all variants tied at the highest count are Index;
31///   Tharanga et al. 2025: "a position may exhibit more than one index or major variant");
32/// * **Unique**: count 1;
33/// * **Major**: the highest count among the rest (ties are all Major);
34/// * **Minor**: everything else.
35#[must_use]
36pub fn classify_motifs(counts_desc: &[u64]) -> Vec<Motif> {
37    debug_assert!(
38        counts_desc.windows(2).all(|w| w[0] >= w[1]),
39        "counts must be descending"
40    );
41    let Some(&max) = counts_desc.first() else {
42        return Vec::new();
43    };
44    let major = counts_desc.iter().copied().find(|&c| c != max && c > 1);
45    counts_desc
46        .iter()
47        .map(|&c| {
48            if c == 1 {
49                Motif::Unique
50            } else if c == max {
51                Motif::Index
52            } else if Some(c) == major {
53                Motif::Major
54            } else {
55                Motif::Minor
56            }
57        })
58        .collect()
59}
60
61/// Diversity statistics of a position derived from its motifs.
62#[derive(Clone, Copy, Debug, PartialEq)]
63pub struct Diversity {
64    /// Number of distinct non-Index variants (DiMA's `distinct_variants_count`).
65    pub distinct_variants_count: u64,
66    /// Non-Index variant types per 100 non-Index sequences; `None` when every sequence carries
67    /// an Index variant (0/0).
68    pub distinct_variants_incidence: Option<f64>,
69    /// Non-Index sequences per 100 supporting sequences; `None` without support.
70    pub total_variants_incidence: Option<f64>,
71}
72
73/// Computes the diversity statistics from counts and their motifs.
74#[must_use]
75pub fn diversity(counts: &[u64], motifs: &[Motif]) -> Diversity {
76    debug_assert_eq!(counts.len(), motifs.len());
77    let support: u64 = counts.iter().sum();
78    let (mut types, mut reads) = (0u64, 0u64);
79    for (&c, &m) in counts.iter().zip(motifs) {
80        if m != Motif::Index {
81            types += 1;
82            reads += c;
83        }
84    }
85    Diversity {
86        distinct_variants_count: types,
87        distinct_variants_incidence: (reads > 0).then(|| incidence(types, reads)),
88        total_variants_incidence: (support > 0).then(|| incidence(reads, support)),
89    }
90}
91
92#[cfg(test)]
93mod tests {
94    use super::*;
95    use Motif::{Index as I, Major as Ma, Minor as Mi, Unique as U};
96
97    #[test]
98    fn labels_at_threshold_boundaries() {
99        assert_eq!(support_label(0, 100), Some(SupportLabel::NoSupport));
100        assert_eq!(support_label(1, 100), Some(SupportLabel::Low));
101        assert_eq!(support_label(99, 100), Some(SupportLabel::Low));
102        assert_eq!(
103            support_label(100, 100),
104            Some(SupportLabel::EqualToThreshold)
105        );
106        assert_eq!(support_label(101, 100), None);
107        assert_eq!(support_label(0, 1), Some(SupportLabel::NoSupport));
108        assert_eq!(support_label(1, 1), Some(SupportLabel::EqualToThreshold));
109    }
110
111    #[test]
112    fn motifs_position_25() {
113        // MERS-CoV spike position 25 (Tharanga et al. 2025, Fig. 1C).
114        let counts = [129, 14, 9, 6, 4, 4, 1, 1, 1, 1];
115        let m = classify_motifs(&counts);
116        assert_eq!(m, [I, Ma, Mi, Mi, Mi, Mi, U, U, U, U]);
117        let d = diversity(&counts, &m);
118        assert_eq!(d.distinct_variants_count, 9);
119        assert!((d.distinct_variants_incidence.unwrap() - 900.0 / 41.0).abs() < 1e-12);
120        assert!((d.total_variants_incidence.unwrap() - 4100.0 / 170.0).abs() < 1e-12);
121    }
122
123    #[test]
124    fn motif_ties_and_edge_cases() {
125        assert_eq!(classify_motifs(&[]), Vec::<Motif>::new());
126        assert_eq!(classify_motifs(&[5]), [I]);
127        assert_eq!(classify_motifs(&[1]), [U]);
128        assert_eq!(classify_motifs(&[1, 1, 1]), [U, U, U]);
129        assert_eq!(classify_motifs(&[3, 3, 2, 2, 1]), [I, I, Ma, Ma, U]);
130        assert_eq!(classify_motifs(&[2, 2, 1]), [I, I, U]);
131        assert_eq!(classify_motifs(&[5, 2, 1]), [I, Ma, U]);
132        assert_eq!(classify_motifs(&[7, 4, 3, 3]), [I, Ma, Mi, Mi]);
133    }
134
135    #[test]
136    fn diversity_nulls() {
137        // Fully conserved: total 0, distinct undefined (0/0).
138        let d = diversity(&[50], &[I]);
139        assert_eq!(d.distinct_variants_count, 0);
140        assert_eq!(d.total_variants_incidence, Some(0.0));
141        assert_eq!(d.distinct_variants_incidence, None);
142        // No support.
143        let d = diversity(&[], &[]);
144        assert_eq!(d.total_variants_incidence, None);
145        assert_eq!(d.distinct_variants_incidence, None);
146        // All unique: no Index, everything is variation.
147        let d = diversity(&[1, 1, 1, 1], &[U, U, U, U]);
148        assert_eq!(d.distinct_variants_count, 4);
149        assert_eq!(d.total_variants_incidence, Some(100.0));
150        assert_eq!(d.distinct_variants_incidence, Some(100.0));
151    }
152
153    #[test]
154    fn incidence_is_correctly_rounded() {
155        assert_eq!(incidence(1, 3), 100.0 / 3.0);
156        assert_eq!(incidence(129, 170), 12900.0 / 170.0);
157        assert_eq!(incidence(u64::MAX, u64::MAX), 100.0);
158    }
159}