Skip to main content

rsomics_seq/operations/
kmers.rs

1use std::io::Write;
2
3use rsomics_common::{Result, RsomicsError};
4use rsomics_kmer::{KmerCounts, decode};
5use rsomics_seqio::Format;
6use serde::Serialize;
7
8use crate::input::scan_records;
9
10/// Options controlling exact DNA k-mer counting.
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub struct KmerOptions {
13    /// K-mer length in `1..=32`.
14    pub k: usize,
15    /// Collapse a k-mer and its reverse complement.
16    pub canonical: bool,
17    /// Emit only k-mers with at least this count.
18    pub min_count: u64,
19}
20
21/// One deterministic k-mer output row.
22#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
23pub struct KmerRow {
24    /// Uppercase A/C/G/T k-mer.
25    pub kmer: String,
26    /// Number of observed windows.
27    pub count: u64,
28}
29
30/// Result of the `kmers` operation.
31#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
32pub struct KmerReport {
33    /// Input path as supplied by the caller, or `-` for stdin.
34    pub input: String,
35    /// Detected input format.
36    pub format: &'static str,
37    /// K-mer length.
38    pub k: usize,
39    /// Whether reverse complements were collapsed.
40    pub canonical: bool,
41    /// Minimum count required for an emitted row.
42    pub min_count: u64,
43    /// Complete fixed-width windows before ambiguity filtering.
44    pub candidate_windows: u64,
45    /// Windows containing only A/C/G/T.
46    pub valid_windows: u64,
47    /// Windows skipped because at least one byte was not A/C/G/T.
48    pub skipped_windows: u64,
49    /// Number of distinct valid k-mers before `min_count` filtering.
50    pub distinct_kmers: u64,
51    /// Rows retained after `min_count` filtering.
52    pub emitted_kmers: u64,
53    /// Deterministically sorted counts.
54    pub counts: Vec<KmerRow>,
55}
56
57/// Counts exact DNA k-mers across one FASTA or FASTQ stream.
58///
59/// Windows containing a non-ACGT byte are skipped. Rows are ordered by
60/// descending count and then lexicographically by k-mer.
61///
62/// # Errors
63///
64/// Returns an error for invalid options, unreadable or malformed input, or
65/// counts that cannot be represented by the report types.
66pub fn count_kmers(input: &str, options: KmerOptions) -> Result<KmerReport> {
67    if options.min_count == 0 {
68        return Err(RsomicsError::InvalidInput(
69            "minimum count must be at least 1".into(),
70        ));
71    }
72
73    let mut accumulator = KmerCounts::try_new(options.k, options.canonical)
74        .map_err(|error| RsomicsError::InvalidInput(error.to_string()))?;
75
76    let mut candidate_windows = 0u64;
77    let format = scan_records(input, |record| {
78        let windows = if record.seq.len() >= options.k {
79            record.seq.len() - options.k + 1
80        } else {
81            0
82        };
83        candidate_windows = candidate_windows
84            .checked_add(u64::try_from(windows).map_err(|_| {
85                RsomicsError::InvalidInput("k-mer window count cannot fit in u64".into())
86            })?)
87            .ok_or_else(|| {
88                RsomicsError::InvalidInput("k-mer window count exceeds u64 capacity".into())
89            })?;
90        accumulator
91            .count_seq(record.seq)
92            .map_err(|error| RsomicsError::InvalidInput(error.to_string()))
93    })?;
94
95    let valid_windows = accumulator.total();
96    let skipped_windows = candidate_windows
97        .checked_sub(valid_windows)
98        .ok_or_else(|| {
99            RsomicsError::InvalidInput("valid k-mer count exceeds candidate windows".into())
100        })?;
101    let distinct_kmers = u64::try_from(accumulator.len())
102        .map_err(|_| RsomicsError::InvalidInput("distinct count cannot fit in u64".into()))?;
103
104    let mut encoded: Vec<_> = accumulator
105        .counts
106        .into_iter()
107        .filter(|(_, count)| *count >= options.min_count)
108        .collect();
109    encoded.sort_unstable_by(|(left_kmer, left_count), (right_kmer, right_count)| {
110        right_count
111            .cmp(left_count)
112            .then_with(|| left_kmer.cmp(right_kmer))
113    });
114
115    let mut counts = Vec::with_capacity(encoded.len());
116    for (encoded_kmer, count) in encoded {
117        let bytes = decode(encoded_kmer, options.k);
118        let kmer = String::from_utf8(bytes)
119            .map_err(|error| RsomicsError::InvalidInput(error.to_string()))?;
120        counts.push(KmerRow { kmer, count });
121    }
122    let emitted_kmers = u64::try_from(counts.len())
123        .map_err(|_| RsomicsError::InvalidInput("emitted count cannot fit in u64".into()))?;
124
125    Ok(KmerReport {
126        input: input.to_owned(),
127        format: match format {
128            Format::Fasta => "FASTA",
129            Format::Fastq => "FASTQ",
130        },
131        k: options.k,
132        canonical: options.canonical,
133        min_count: options.min_count,
134        candidate_windows,
135        valid_windows,
136        skipped_windows,
137        distinct_kmers,
138        emitted_kmers,
139        counts,
140    })
141}
142
143/// Writes a stable two-column TSV count table.
144///
145/// # Errors
146///
147/// Returns an error when the output cannot be written or flushed.
148pub fn write_kmer_tsv(report: &KmerReport, output: &mut dyn Write) -> Result<()> {
149    writeln!(output, "kmer\tcount").map_err(RsomicsError::Io)?;
150    for row in &report.counts {
151        writeln!(output, "{}\t{}", row.kmer, row.count).map_err(RsomicsError::Io)?;
152    }
153    output.flush().map_err(RsomicsError::Io)
154}
155
156#[cfg(test)]
157mod tests {
158    use super::*;
159    use rsomics_kmer::KmerError;
160
161    #[test]
162    fn foundation_constructor_rejects_invalid_user_k() {
163        for k in [0, 33, usize::MAX] {
164            let error = KmerCounts::try_new(k, false).unwrap_err();
165            assert!(matches!(error, KmerError::KOutOfRange(actual) if actual == k));
166            assert_eq!(error.to_string(), format!("k must be in 1..=32 (got {k})"));
167        }
168    }
169
170    #[test]
171    fn fallible_constructor_accepts_codec_boundaries() {
172        assert!(KmerCounts::try_new(1, false).is_ok());
173        assert!(KmerCounts::try_new(32, true).is_ok());
174    }
175}