Skip to main content

dima_core/
position.rs

1//! Turns the counts of one position into its result: support class, entropy estimate, sample
2//! coverage, diversity motifs, incidences and per-variant metadata.
3
4use crate::config::Estimator;
5use crate::engine::PositionCounts;
6use crate::entropy::{self, CountProfile};
7use crate::error::Result;
8use crate::model::{FieldCounts, Metadata, PositionResult, Variant};
9use crate::stats;
10
11/// Everything needed to finalise positions, shared by all of them.
12#[derive(Debug)]
13pub struct Finaliser<'a> {
14    /// Support threshold *T*.
15    pub threshold: u64,
16    /// Entropy estimator.
17    pub estimator: Estimator,
18    /// `--min-coverage`, if given.
19    pub min_coverage: Option<f64>,
20    /// Stratified field names, in header order (empty without metadata).
21    pub fields: &'a [String],
22    /// For each header value id: (stratified field index, value).
23    pub values: &'a [(usize, String)],
24}
25
26impl Finaliser<'_> {
27    /// The result of position `position` (1-based).
28    ///
29    /// # Errors
30    /// Internal errors from the estimators (non-finite values).
31    pub fn finalise(&self, position: u64, counts: &PositionCounts) -> Result<PositionResult> {
32        let ids = counts.ordered_ids();
33        let ordered: Vec<u64> = ids.iter().map(|&id| counts.count(id)).collect();
34        let support: u64 = ordered.iter().sum();
35        let motifs = stats::classify_motifs(&ordered);
36        let diversity = stats::diversity(&ordered, &motifs);
37        let profile = CountProfile::from_counts(ordered.iter().copied())?;
38        let estimate = entropy::estimate(&profile, self.estimator, self.threshold)?;
39        let coverage = entropy::sample_coverage(&profile);
40        let diversity_motifs = ids
41            .iter()
42            .zip(&ordered)
43            .zip(&motifs)
44            .map(|((&id, &count), &motif)| Variant {
45                // Canonical bytes are upper-case ASCII letters.
46                sequence: String::from_utf8_lossy(counts.kmer(id)).into_owned(),
47                count,
48                incidence: stats::incidence(count, support),
49                motif,
50                metadata: (!self.fields.is_empty()).then(|| self.metadata(counts, id)),
51            })
52            .collect();
53        Ok(PositionResult {
54            position,
55            low_support: stats::support_label(support, self.threshold),
56            support,
57            distinct_variants_count: diversity.distinct_variants_count,
58            entropy: estimate.entropy,
59            observed_entropy: estimate.observed,
60            entropy_method: estimate.method,
61            entropy_fallback: estimate.fallback,
62            distinct_variants_incidence: diversity.distinct_variants_incidence,
63            total_variants_incidence: diversity.total_variants_incidence,
64            sample_coverage: coverage,
65            below_min_coverage: self.min_coverage.and_then(|m| coverage.map(|c| c < m)),
66            diversity_motifs,
67        })
68    }
69
70    fn metadata(&self, counts: &PositionCounts, id: u32) -> Metadata {
71        let mut per_field: Vec<Vec<(String, u64)>> = vec![Vec::new(); self.fields.len()];
72        for (value_id, n) in counts.cells(id) {
73            let (field, value) = &self.values[value_id as usize];
74            per_field[*field].push((value.clone(), n));
75        }
76        Metadata(
77            per_field
78                .into_iter()
79                .zip(self.fields)
80                .map(|(mut values, field)| {
81                    values.sort_unstable_by(|a, b| a.0.as_bytes().cmp(b.0.as_bytes()));
82                    FieldCounts {
83                        field: field.clone(),
84                        values,
85                    }
86                })
87                .collect(),
88        )
89    }
90}