1use anyhow::Result;
6use log::warn;
7use ndarray::{Array2, Array3};
8use rand::rngs::SmallRng;
9use rand::{RngExt, SeedableRng};
10use rayon::prelude::*;
11
12use deepbiop_core::error::DPError;
13use deepbiop_core::types::EncodingType;
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum AmbiguousStrategy {
18 Skip,
20 Mask,
22 Random,
24}
25
26pub struct OneHotEncoder {
42 encoding_type: EncodingType,
44 ambiguous_strategy: AmbiguousStrategy,
46 seed: Option<u64>,
48}
49
50impl OneHotEncoder {
51 pub fn new(encoding_type: EncodingType, ambiguous_strategy: AmbiguousStrategy) -> Self {
62 Self {
63 encoding_type,
64 ambiguous_strategy,
65 seed: None,
66 }
67 }
68
69 pub fn with_seed(
77 encoding_type: EncodingType,
78 ambiguous_strategy: AmbiguousStrategy,
79 seed: u64,
80 ) -> Self {
81 Self {
82 encoding_type,
83 ambiguous_strategy,
84 seed: Some(seed),
85 }
86 }
87
88 pub fn encode(&self, sequence: &[u8]) -> Result<Array2<f32>> {
104 let alphabet_size = self.encoding_type.alphabet_size();
105 let seq_len = sequence.len();
106
107 let mut encoded = Array2::<f32>::zeros((seq_len, alphabet_size));
108
109 let mut rng_state: Option<SmallRng> =
111 if matches!(self.ambiguous_strategy, AmbiguousStrategy::Random) {
112 Some(if let Some(seed) = self.seed {
113 SmallRng::seed_from_u64(seed)
114 } else {
115 SmallRng::from_rng(&mut rand::rng())
116 })
117 } else {
118 None
119 };
120
121 for (i, &base) in sequence.iter().enumerate() {
122 let base_upper = base.to_ascii_uppercase();
123
124 if !self.encoding_type.is_valid_char(base_upper) {
126 warn!("unexpected base '{}' at position {}", base as char, i);
127 match self.ambiguous_strategy {
128 AmbiguousStrategy::Skip => {
129 return Err(DPError::InvalidAlphabet {
130 character: base as char,
131 position: i,
132 expected: String::from_utf8_lossy(self.encoding_type.alphabet())
133 .to_string(),
134 }
135 .into());
136 }
137 AmbiguousStrategy::Mask => {
138 continue;
140 }
141 AmbiguousStrategy::Random => {
142 let alphabet = self.encoding_type.alphabet();
144 if let Some(rng_ref) = &mut rng_state {
145 let random_idx = rng_ref.random_range(0..alphabet.len());
146 encoded[[i, random_idx]] = 1.0;
147 }
148 continue;
149 }
150 }
151 }
152
153 if let Some(pos) = self
155 .encoding_type
156 .alphabet()
157 .iter()
158 .position(|&a| a == base_upper)
159 {
160 encoded[[i, pos]] = 1.0;
161 }
162 }
163
164 Ok(encoded)
165 }
166
167 pub fn encode_batch(&self, sequences: &[&[u8]]) -> Result<Array3<f32>> {
183 if sequences.is_empty() {
184 return Ok(Array3::zeros((0, 0, self.encoding_type.alphabet_size())));
185 }
186
187 let max_len = sequences.iter().map(|s| s.len()).max().unwrap_or(0);
189 let alphabet_size = self.encoding_type.alphabet_size();
190
191 let encoded_seqs: Result<Vec<Array2<f32>>> =
193 sequences.par_iter().map(|seq| self.encode(seq)).collect();
194
195 let encoded_seqs = encoded_seqs?;
196
197 let mut batch = Array3::<f32>::zeros((sequences.len(), max_len, alphabet_size));
199
200 for (batch_idx, encoded) in encoded_seqs.iter().enumerate() {
202 let seq_len = encoded.shape()[0];
203 for i in 0..seq_len {
204 for j in 0..alphabet_size {
205 batch[[batch_idx, i, j]] = encoded[[i, j]];
206 }
207 }
208 }
209
210 Ok(batch)
211 }
212
213 pub fn encoding_type(&self) -> EncodingType {
215 self.encoding_type
216 }
217
218 pub fn ambiguous_strategy(&self) -> AmbiguousStrategy {
220 self.ambiguous_strategy
221 }
222}
223
224impl deepbiop_core::encoder::SequenceEncoder for OneHotEncoder {
226 type EncodeOutput = Array2<f32>;
227
228 fn encode_sequence(&self, seq: &[u8], qual: Option<&[u8]>) -> Result<Self::EncodeOutput> {
229 self.validate_input(seq, qual)?;
231
232 self.encode(seq)
234 }
235
236 fn expected_output_size(&self, seq_len: usize) -> usize {
237 seq_len * self.encoding_type.alphabet_size()
238 }
239}
240
241#[cfg(test)]
242mod tests {
243 use super::*;
244
245 #[test]
246 fn test_onehot_encode_dna() {
247 let encoder = OneHotEncoder::new(EncodingType::DNA, AmbiguousStrategy::Skip);
248 let encoded = encoder.encode(b"ACGT").unwrap();
249
250 assert_eq!(encoded.shape(), &[4, 4]);
251
252 assert_eq!(encoded[[0, 0]], 1.0);
254 assert_eq!(encoded[[0, 1]], 0.0);
255
256 assert_eq!(encoded[[1, 1]], 1.0);
258
259 assert_eq!(encoded[[2, 2]], 1.0);
261
262 assert_eq!(encoded[[3, 3]], 1.0);
264 }
265
266 #[test]
267 fn test_onehot_encode_protein() {
268 let encoder = OneHotEncoder::new(EncodingType::Protein, AmbiguousStrategy::Skip);
269 let encoded = encoder.encode(b"ACDE").unwrap();
270
271 assert_eq!(encoded.shape(), &[4, 20]); }
273
274 #[test]
275 fn test_onehot_encode_ambiguous_mask() {
276 let encoder = OneHotEncoder::new(EncodingType::DNA, AmbiguousStrategy::Mask);
277 let encoded = encoder.encode(b"ACGTN").unwrap();
278
279 assert_eq!(encoded.shape(), &[5, 4]);
280 assert_eq!(encoded[[4, 0]], 0.0);
282 assert_eq!(encoded[[4, 1]], 0.0);
283 assert_eq!(encoded[[4, 2]], 0.0);
284 assert_eq!(encoded[[4, 3]], 0.0);
285 }
286
287 #[test]
288 fn test_onehot_encode_batch() {
289 let encoder = OneHotEncoder::new(EncodingType::DNA, AmbiguousStrategy::Skip);
290 let sequences = vec![b"ACGT".as_ref(), b"AC".as_ref(), b"ACGTACGT".as_ref()];
291
292 let batch = encoder.encode_batch(&sequences).unwrap();
293
294 assert_eq!(batch.shape(), &[3, 8, 4]); assert_eq!(batch[[0, 0, 0]], 1.0); assert_eq!(batch[[0, 1, 1]], 1.0); assert_eq!(batch[[1, 0, 0]], 1.0); assert_eq!(batch[[1, 1, 1]], 1.0); assert_eq!(batch[[1, 2, 0]], 0.0); }
305
306 #[test]
307 fn test_onehot_encode_ambiguous_random() {
308 let encoder = OneHotEncoder::with_seed(EncodingType::DNA, AmbiguousStrategy::Random, 42);
309 let encoded = encoder.encode(b"ACGTN").unwrap();
310
311 assert_eq!(encoded.shape(), &[5, 4]);
312
313 assert_eq!(encoded[[0, 0]], 1.0); assert_eq!(encoded[[1, 1]], 1.0); assert_eq!(encoded[[2, 2]], 1.0); assert_eq!(encoded[[3, 3]], 1.0); let n_encoding: Vec<f32> = (0..4).map(|i| encoded[[4, i]]).collect();
321 let sum: f32 = n_encoding.iter().sum();
322 assert_eq!(sum, 1.0);
323 assert!(n_encoding.contains(&1.0));
324
325 let encoder2 = OneHotEncoder::with_seed(EncodingType::DNA, AmbiguousStrategy::Random, 42);
327 let encoded2 = encoder2.encode(b"ACGTN").unwrap();
328 assert_eq!(encoded, encoded2);
329 }
330}