rsomics_seq/operations/
kmers.rs1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub struct KmerOptions {
13 pub k: usize,
15 pub canonical: bool,
17 pub min_count: u64,
19}
20
21#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
23pub struct KmerRow {
24 pub kmer: String,
26 pub count: u64,
28}
29
30#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
32pub struct KmerReport {
33 pub input: String,
35 pub format: &'static str,
37 pub k: usize,
39 pub canonical: bool,
41 pub min_count: u64,
43 pub candidate_windows: u64,
45 pub valid_windows: u64,
47 pub skipped_windows: u64,
49 pub distinct_kmers: u64,
51 pub emitted_kmers: u64,
53 pub counts: Vec<KmerRow>,
55}
56
57pub 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
143pub 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}