deepbiop_core/encoder.rs
1//! Unified sequence encoding interface for FASTA and FASTQ formats
2//!
3//! This module provides a common trait for encoding biological sequences into
4//! numerical representations suitable for machine learning. The trait uses
5//! zero-cost abstractions to handle both FASTA (sequence-only) and FASTQ
6//! (sequence + quality scores) formats efficiently.
7
8use anyhow::Result;
9
10/// Unified trait for encoding biological sequences
11///
12/// This trait provides a common interface for sequence encoders that work with
13/// both FASTA and FASTQ formats. The key innovation is using `Option<&[u8]>` for
14/// quality scores, which allows FASTA encoders to pass `None` and FASTQ encoders
15/// to pass `Some(qual)`, all with zero runtime cost through monomorphization.
16///
17/// # Type Parameters
18///
19/// * `EncodeOutput` - The output type of the encoding (e.g., `Vec<f32>`, `Array2<u8>`)
20///
21/// # Design Rationale
22///
23/// Using `Option<&[u8]>` for quality scores provides several benefits:
24/// - Zero-cost abstraction: The compiler optimizes away the Option for FASTA
25/// - Unified interface: Same trait works for both FASTA and FASTQ
26/// - Type safety: Encoders must explicitly handle the quality score case
27/// - Memory efficiency: No allocation overhead for FASTA files
28///
29/// # Examples
30///
31/// ## Implementing for a simple encoder
32///
33/// ```
34/// use deepbiop_core::encoder::SequenceEncoder;
35/// use anyhow::Result;
36///
37/// struct SimpleEncoder;
38///
39/// impl SequenceEncoder for SimpleEncoder {
40/// type EncodeOutput = Vec<u8>;
41///
42/// fn encode_sequence(&self, seq: &[u8], qual: Option<&[u8]>) -> Result<Self::EncodeOutput> {
43/// // For FASTA files, qual will be None
44/// // For FASTQ files, qual will be Some(quality_scores)
45/// Ok(seq.to_vec())
46/// }
47///
48/// fn expected_output_size(&self, seq_len: usize) -> usize {
49/// seq_len
50/// }
51/// }
52///
53/// let encoder = SimpleEncoder;
54///
55/// // FASTA-style encoding (no quality scores)
56/// let fasta_encoded = encoder.encode_sequence(b"ACGT", None).unwrap();
57/// assert_eq!(fasta_encoded, b"ACGT");
58///
59/// // FASTQ-style encoding (with quality scores)
60/// let fastq_encoded = encoder.encode_sequence(b"ACGT", Some(b"IIII")).unwrap();
61/// assert_eq!(fastq_encoded, b"ACGT");
62/// ```
63///
64/// ## Implementing an encoder that uses quality scores
65///
66/// ```
67/// use deepbiop_core::encoder::SequenceEncoder;
68/// use anyhow::Result;
69///
70/// struct QualityAwareEncoder;
71///
72/// impl SequenceEncoder for QualityAwareEncoder {
73/// type EncodeOutput = Vec<f32>;
74///
75/// fn encode_sequence(&self, seq: &[u8], qual: Option<&[u8]>) -> Result<Self::EncodeOutput> {
76/// let mut output = Vec::with_capacity(seq.len());
77///
78/// match qual {
79/// Some(quality_scores) => {
80/// // Use quality scores to weight the encoding
81/// for (base, &q) in seq.iter().zip(quality_scores.iter()) {
82/// let weight = q.saturating_sub(33) as f32 / 40.0; // Phred+33 to [0, 1]
83/// output.push(weight);
84/// }
85/// }
86/// None => {
87/// // No quality scores, use uniform weights
88/// output.extend(std::iter::repeat(1.0).take(seq.len()));
89/// }
90/// }
91///
92/// Ok(output)
93/// }
94///
95/// fn expected_output_size(&self, seq_len: usize) -> usize {
96/// seq_len
97/// }
98/// }
99/// ```
100pub trait SequenceEncoder {
101 /// The type of the encoded output
102 ///
103 /// Common choices include:
104 /// - `Vec<u8>` for integer encoding
105 /// - `Vec<f32>` for one-hot or weighted encoding
106 /// - `Array2<f32>` for 2D representations
107 type EncodeOutput;
108
109 /// Encodes a biological sequence into a numerical representation
110 ///
111 /// # Arguments
112 ///
113 /// * `seq` - The nucleotide sequence as a byte slice (e.g., b"ACGT")
114 /// * `qual` - Optional quality scores for FASTQ files. Pass `None` for FASTA.
115 ///
116 /// # Returns
117 ///
118 /// Returns the encoded representation wrapped in a Result.
119 ///
120 /// # Errors
121 ///
122 /// May return an error if:
123 /// - The sequence contains invalid nucleotides
124 /// - Quality scores length doesn't match sequence length
125 /// - Encoding computation fails
126 ///
127 /// # Implementation Notes
128 ///
129 /// For FASTA-only encoders, you can ignore the `qual` parameter:
130 /// ```ignore
131 /// fn encode_sequence(&self, seq: &[u8], _qual: Option<&[u8]>) -> Result<Self::EncodeOutput> {
132 /// // Implement encoding using only seq
133 /// }
134 /// ```
135 ///
136 /// For FASTQ-aware encoders, match on `qual`:
137 /// ```ignore
138 /// fn encode_sequence(&self, seq: &[u8], qual: Option<&[u8]>) -> Result<Self::EncodeOutput> {
139 /// match qual {
140 /// Some(q) => { /* use quality scores */ },
141 /// None => { /* fallback encoding */ },
142 /// }
143 /// }
144 /// ```
145 fn encode_sequence(&self, seq: &[u8], qual: Option<&[u8]>) -> Result<Self::EncodeOutput>;
146
147 /// Encodes multiple sequences in batch for potential performance optimization
148 ///
149 /// Default implementation processes sequences sequentially. Implementations can override
150 /// this method to add optimizations such as:
151 /// - Parallel processing with `rayon`
152 /// - SIMD operations for vectorized encoding
153 /// - Memory pool reuse to reduce allocations
154 ///
155 /// # Arguments
156 ///
157 /// * `sequences` - Slice of tuples containing (sequence, optional_quality_scores)
158 ///
159 /// # Returns
160 ///
161 /// Returns a Vec of encoded outputs, one per input sequence, in the same order.
162 ///
163 /// # Example
164 ///
165 /// ```ignore
166 /// // Default sequential processing (automatically provided)
167 /// let results = encoder.batch_encode(&[(b"ACGT", None), (b"TGCA", None)])?;
168 ///
169 /// // Custom parallel implementation (optional override):
170 /// fn batch_encode(&self, sequences: &[(&[u8], Option<&[u8]>)]) -> Result<Vec<Self::EncodeOutput>> {
171 /// use rayon::prelude::*;
172 /// sequences
173 /// .par_iter()
174 /// .map(|(seq, qual)| self.encode_sequence(seq, *qual))
175 /// .collect()
176 /// }
177 /// ```
178 fn batch_encode(
179 &self,
180 sequences: &[(&[u8], Option<&[u8]>)],
181 ) -> Result<Vec<Self::EncodeOutput>> {
182 sequences
183 .iter()
184 .map(|(seq, qual)| self.encode_sequence(seq, *qual))
185 .collect()
186 }
187
188 /// Returns the expected size of the encoded output
189 ///
190 /// This helps with pre-allocation and validation. The return value
191 /// should represent the number of elements in the output, not bytes.
192 ///
193 /// # Arguments
194 ///
195 /// * `seq_len` - The length of the input sequence
196 ///
197 /// # Examples
198 ///
199 /// For an integer encoder: `seq_len`
200 /// For a one-hot encoder (4 channels): `seq_len * 4`
201 /// For a k-mer encoder (k=3): `seq_len - k + 1`
202 fn expected_output_size(&self, seq_len: usize) -> usize;
203
204 /// Validates that a sequence and quality scores are compatible
205 ///
206 /// Default implementation checks that quality scores (if present) have
207 /// the same length as the sequence. Override this method if you need
208 /// additional validation logic.
209 ///
210 /// # Arguments
211 ///
212 /// * `seq` - The nucleotide sequence
213 /// * `qual` - Optional quality scores
214 ///
215 /// # Returns
216 ///
217 /// Returns `Ok(())` if valid, or an error describing the validation failure.
218 fn validate_input(&self, seq: &[u8], qual: Option<&[u8]>) -> Result<()> {
219 if let Some(q) = qual {
220 if seq.len() != q.len() {
221 return Err(anyhow::anyhow!(
222 "Sequence length ({}) doesn't match quality scores length ({})",
223 seq.len(),
224 q.len()
225 ));
226 }
227 }
228 Ok(())
229 }
230}
231
232#[cfg(test)]
233mod tests {
234 use super::*;
235
236 // Test encoder that simply counts bases
237 struct CountEncoder;
238
239 impl SequenceEncoder for CountEncoder {
240 type EncodeOutput = usize;
241
242 fn encode_sequence(&self, seq: &[u8], _qual: Option<&[u8]>) -> Result<Self::EncodeOutput> {
243 Ok(seq.len())
244 }
245
246 fn expected_output_size(&self, seq_len: usize) -> usize {
247 seq_len
248 }
249 }
250
251 #[test]
252 fn test_encoder_with_fasta() {
253 let encoder = CountEncoder;
254 let result = encoder.encode_sequence(b"ACGTACGT", None).unwrap();
255 assert_eq!(result, 8);
256 }
257
258 #[test]
259 fn test_encoder_with_fastq() {
260 let encoder = CountEncoder;
261 let result = encoder.encode_sequence(b"ACGT", Some(b"IIII")).unwrap();
262 assert_eq!(result, 4);
263 }
264
265 #[test]
266 fn test_validate_input_success() {
267 let encoder = CountEncoder;
268 assert!(encoder.validate_input(b"ACGT", Some(b"IIII")).is_ok());
269 assert!(encoder.validate_input(b"ACGT", None).is_ok());
270 }
271
272 #[test]
273 fn test_validate_input_length_mismatch() {
274 let encoder = CountEncoder;
275 let result = encoder.validate_input(b"ACGT", Some(b"III"));
276 assert!(result.is_err());
277 assert!(result.unwrap_err().to_string().contains("doesn't match"));
278 }
279
280 #[test]
281 fn test_expected_output_size() {
282 let encoder = CountEncoder;
283 assert_eq!(encoder.expected_output_size(100), 100);
284 }
285
286 // Quality-aware encoder for more comprehensive testing
287 struct WeightedEncoder;
288
289 impl SequenceEncoder for WeightedEncoder {
290 type EncodeOutput = Vec<f32>;
291
292 fn encode_sequence(&self, seq: &[u8], qual: Option<&[u8]>) -> Result<Self::EncodeOutput> {
293 self.validate_input(seq, qual)?;
294
295 let output = match qual {
296 Some(q) => seq
297 .iter()
298 .zip(q.iter())
299 .map(|(_, &quality)| (quality - 33) as f32 / 40.0)
300 .collect(),
301 None => vec![1.0; seq.len()],
302 };
303
304 Ok(output)
305 }
306
307 fn expected_output_size(&self, seq_len: usize) -> usize {
308 seq_len
309 }
310 }
311
312 #[test]
313 fn test_weighted_encoder_with_quality() {
314 let encoder = WeightedEncoder;
315 let result = encoder.encode_sequence(b"ACGT", Some(b"IIII")).unwrap();
316 assert_eq!(result.len(), 4);
317 // 'I' has ASCII 73, Phred+33 score of 40
318 let expected = 40.0 / 40.0;
319 for &weight in &result {
320 assert!((weight - expected).abs() < 0.001);
321 }
322 }
323
324 #[test]
325 fn test_weighted_encoder_without_quality() {
326 let encoder = WeightedEncoder;
327 let result = encoder.encode_sequence(b"ACGT", None).unwrap();
328 assert_eq!(result.len(), 4);
329 for &weight in &result {
330 assert!((weight - 1.0).abs() < 0.001);
331 }
332 }
333}