Skip to main content

rsomics_seq/operations/
stats.rs

1use std::io::Write;
2
3use rsomics_common::{Result, RsomicsError};
4use rsomics_seqio::Format;
5use serde::Serialize;
6
7use crate::input::scan_records;
8
9const ALPHABET_GUESS_BASES: usize = 10_000;
10
11/// SeqKit-compatible first-record alphabet classification.
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
13pub enum SeqType {
14    /// DNA or nucleotide ambiguity alphabet containing thymine.
15    #[serde(rename = "DNA")]
16    Dna,
17    /// Nucleotide alphabet containing uracil and no thymine.
18    #[serde(rename = "RNA")]
19    Rna,
20    /// Protein alphabet.
21    Protein,
22    /// Input outside the recognized biological alphabets.
23    Unlimit,
24}
25
26impl SeqType {
27    /// Returns the stable tabular spelling.
28    #[must_use]
29    pub const fn as_str(self) -> &'static str {
30        match self {
31            Self::Dna => "DNA",
32            Self::Rna => "RNA",
33            Self::Protein => "Protein",
34            Self::Unlimit => "Unlimit",
35        }
36    }
37}
38
39/// Basic statistics for one input stream.
40#[derive(Debug, Clone, PartialEq, Serialize)]
41pub struct StatsRow {
42    /// Input path as supplied by the caller, or `-` for stdin.
43    pub file: String,
44    /// Detected input format.
45    pub format: &'static str,
46    /// Alphabet inferred from the first record.
47    #[serde(rename = "type")]
48    pub seq_type: SeqType,
49    /// Number of records.
50    pub num_seqs: u64,
51    /// Sum of sequence lengths.
52    pub sum_len: u64,
53    /// Minimum sequence length.
54    pub min_len: u64,
55    /// Arithmetic mean sequence length.
56    pub avg_len: f64,
57    /// Maximum sequence length.
58    pub max_len: u64,
59}
60
61/// Result of the `stats` operation.
62#[derive(Debug, Clone, PartialEq, Serialize)]
63pub struct StatsReport {
64    /// One row per input, preserving command-line order.
65    pub rows: Vec<StatsRow>,
66}
67
68#[derive(Default)]
69struct Accumulator {
70    seq_type: Option<SeqType>,
71    num_seqs: u64,
72    sum_len: u64,
73    min_len: u64,
74    max_len: u64,
75}
76
77impl Accumulator {
78    fn push(&mut self, sequence: &[u8]) -> Result<()> {
79        let len = u64::try_from(sequence.len()).map_err(|_| {
80            RsomicsError::InvalidInput("sequence length cannot be represented as u64".into())
81        })?;
82        if self.seq_type.is_none() {
83            self.seq_type = Some(classify_record(sequence));
84            self.min_len = len;
85        } else {
86            self.min_len = self.min_len.min(len);
87        }
88        self.num_seqs = self.num_seqs.checked_add(1).ok_or_else(|| {
89            RsomicsError::InvalidInput("record count exceeds u64 capacity".into())
90        })?;
91        self.sum_len = self.sum_len.checked_add(len).ok_or_else(|| {
92            RsomicsError::InvalidInput("total sequence length exceeds u64 capacity".into())
93        })?;
94        self.max_len = self.max_len.max(len);
95        Ok(())
96    }
97
98    #[allow(clippy::cast_precision_loss)]
99    fn finish(self, file: &str, format: Format) -> Result<StatsRow> {
100        let Some(seq_type) = self.seq_type else {
101            return Err(RsomicsError::InvalidInput(format!(
102                "{file} contains no sequence records"
103            )));
104        };
105        Ok(StatsRow {
106            file: file.to_owned(),
107            format: format_name(format),
108            seq_type,
109            num_seqs: self.num_seqs,
110            sum_len: self.sum_len,
111            min_len: self.min_len,
112            avg_len: self.sum_len as f64 / self.num_seqs as f64,
113            max_len: self.max_len,
114        })
115    }
116}
117
118/// Computes basic SeqKit-compatible statistics for each input.
119///
120/// `-` selects stdin and cannot be combined with another input because stdin
121/// is a single stream.
122///
123/// # Errors
124///
125/// Returns an error when no input is supplied, stdin is combined with another
126/// input, a stream is unreadable or malformed, or an aggregate overflows.
127pub fn compute_stats(inputs: &[String]) -> Result<StatsReport> {
128    if inputs.is_empty() {
129        return Err(RsomicsError::InvalidInput(
130            "stats requires at least one input".into(),
131        ));
132    }
133    if inputs.len() > 1 && inputs.iter().any(|input| input == "-") {
134        return Err(RsomicsError::InvalidInput(
135            "stdin (`-`) cannot be combined with file inputs".into(),
136        ));
137    }
138
139    let mut rows = Vec::with_capacity(inputs.len());
140    for input in inputs {
141        let mut accumulator = Accumulator::default();
142        let format = scan_records(input, |record| accumulator.push(record.seq))?;
143        rows.push(accumulator.finish(input, format)?);
144    }
145    Ok(StatsReport { rows })
146}
147
148/// Writes the stable SeqKit-compatible basic TSV table.
149///
150/// # Errors
151///
152/// Returns an error when the output cannot be written or flushed.
153pub fn write_stats_tsv(report: &StatsReport, output: &mut dyn Write) -> Result<()> {
154    writeln!(
155        output,
156        "file\tformat\ttype\tnum_seqs\tsum_len\tmin_len\tavg_len\tmax_len"
157    )
158    .map_err(RsomicsError::Io)?;
159    for row in &report.rows {
160        writeln!(
161            output,
162            "{}\t{}\t{}\t{}\t{}\t{}\t{:.1}\t{}",
163            row.file,
164            row.format,
165            row.seq_type.as_str(),
166            row.num_seqs,
167            row.sum_len,
168            row.min_len,
169            row.avg_len,
170            row.max_len
171        )
172        .map_err(RsomicsError::Io)?;
173    }
174    output.flush().map_err(RsomicsError::Io)
175}
176
177fn format_name(format: Format) -> &'static str {
178    match format {
179        Format::Fasta => "FASTA",
180        Format::Fastq => "FASTQ",
181    }
182}
183
184pub(crate) fn classify_record(sequence: &[u8]) -> SeqType {
185    classify(&sequence[..sequence.len().min(ALPHABET_GUESS_BASES)])
186}
187
188fn classify(sample: &[u8]) -> SeqType {
189    if sample.is_empty() {
190        return SeqType::Unlimit;
191    }
192    const DNA: &[u8] = b"ACGTN -.";
193    const RNA: &[u8] = b"ACGUN -.";
194    const DNA_REDUNDANT: &[u8] = b"ACGTRYSWKMBDHVN -.";
195    const RNA_REDUNDANT: &[u8] = b"ACGURYSWKMBDHVN -.";
196    const PROTEIN: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ -*_.";
197
198    let is_subset = |alphabet: &[u8]| {
199        sample
200            .iter()
201            .all(|byte| alphabet.contains(&byte.to_ascii_uppercase()))
202    };
203    if is_subset(DNA) || is_subset(DNA_REDUNDANT) {
204        SeqType::Dna
205    } else if is_subset(RNA) || is_subset(RNA_REDUNDANT) {
206        SeqType::Rna
207    } else if is_subset(PROTEIN) {
208        SeqType::Protein
209    } else {
210        SeqType::Unlimit
211    }
212}
213
214#[cfg(test)]
215mod tests {
216    use super::*;
217
218    #[test]
219    fn classification_matches_pinned_seqkit_cases() {
220        assert_eq!(classify(b"ACGTNRYS"), SeqType::Dna);
221        assert_eq!(classify(b"ACGUNRYS"), SeqType::Rna);
222        assert_eq!(classify(b"MEEPSILQ"), SeqType::Protein);
223        assert_eq!(classify(b"TU"), SeqType::Protein);
224        assert_eq!(classify(b"OJ"), SeqType::Protein);
225        assert_eq!(classify(b""), SeqType::Unlimit);
226        assert_eq!(classify(b"ACGT?"), SeqType::Unlimit);
227    }
228}