fastars 0.1.0

Ultra-fast QC and trimming for short and long reads
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
//! Quality-based trimming.
//!
//! This module provides trimming based on quality scores,
//! removing low-quality bases from read ends using a sliding window algorithm.

use super::TrimResult;

/// Configuration for quality-based trimming.
#[derive(Debug, Clone)]
pub struct QualityTrimConfig {
    /// Size of the sliding window for quality calculation.
    pub window_size: usize,
    /// Quality threshold (Phred score). Windows with mean quality below this are trimmed.
    pub threshold: u8,
    /// Whether to trim from the 5' (front) end.
    pub cut_front: bool,
    /// Whether to trim from the 3' (tail) end.
    pub cut_tail: bool,
    /// Whether to trim from the first low-quality position to the end.
    pub cut_right: bool,
    /// Window size for cut_right (if None, uses window_size).
    pub right_window_size: Option<usize>,
    /// Quality threshold for cut_right (if None, uses threshold).
    pub right_threshold: Option<u8>,
    /// Window size for cut_tail (if None, uses window_size).
    pub tail_window_size: Option<usize>,
    /// Quality threshold for cut_tail (if None, uses threshold).
    pub tail_threshold: Option<u8>,
    /// Window size for cut_front (if None, uses window_size).
    pub front_window_size: Option<usize>,
    /// Quality threshold for cut_front (if None, uses threshold).
    pub front_threshold: Option<u8>,
}

impl Default for QualityTrimConfig {
    fn default() -> Self {
        Self {
            window_size: 4,
            threshold: 15,
            cut_front: false,
            cut_tail: true,
            cut_right: false,
            right_window_size: None,
            right_threshold: None,
            tail_window_size: None,
            tail_threshold: None,
            front_window_size: None,
            front_threshold: None,
        }
    }
}

impl QualityTrimConfig {
    /// Create a new quality trim config with default settings.
    pub fn new() -> Self {
        Self::default()
    }

    /// Create config for short read mode.
    pub fn short_read() -> Self {
        Self {
            window_size: 4,
            threshold: 15,
            cut_front: false,
            cut_tail: true,
            cut_right: false,
            right_window_size: None,
            right_threshold: None,
            tail_window_size: None,
            tail_threshold: None,
            front_window_size: None,
            front_threshold: None,
        }
    }

    /// Create config for long read mode.
    pub fn long_read() -> Self {
        Self {
            window_size: 20,
            threshold: 7,
            cut_front: false,
            cut_tail: true,
            cut_right: false,
            right_window_size: None,
            right_threshold: None,
            tail_window_size: None,
            tail_threshold: None,
            front_window_size: None,
            front_threshold: None,
        }
    }

    /// Set window size.
    pub fn with_window_size(mut self, size: usize) -> Self {
        self.window_size = size;
        self
    }

    /// Set quality threshold.
    pub fn with_threshold(mut self, threshold: u8) -> Self {
        self.threshold = threshold;
        self
    }

    /// Enable/disable front trimming.
    pub fn with_cut_front(mut self, enabled: bool) -> Self {
        self.cut_front = enabled;
        self
    }

    /// Enable/disable tail trimming.
    pub fn with_cut_tail(mut self, enabled: bool) -> Self {
        self.cut_tail = enabled;
        self
    }

    /// Enable/disable right trimming.
    pub fn with_cut_right(mut self, enabled: bool) -> Self {
        self.cut_right = enabled;
        self
    }

    /// Set window size for cut_right.
    pub fn with_right_window_size(mut self, size: usize) -> Self {
        self.right_window_size = Some(size);
        self
    }

    /// Set quality threshold for cut_right.
    pub fn with_right_threshold(mut self, threshold: u8) -> Self {
        self.right_threshold = Some(threshold);
        self
    }

    /// Set window size for cut_tail.
    pub fn with_tail_window_size(mut self, size: usize) -> Self {
        self.tail_window_size = Some(size);
        self
    }

    /// Set quality threshold for cut_tail.
    pub fn with_tail_threshold(mut self, threshold: u8) -> Self {
        self.tail_threshold = Some(threshold);
        self
    }

    /// Set window size for cut_front.
    pub fn with_front_window_size(mut self, size: usize) -> Self {
        self.front_window_size = Some(size);
        self
    }

    /// Set quality threshold for cut_front.
    pub fn with_front_threshold(mut self, threshold: u8) -> Self {
        self.front_threshold = Some(threshold);
        self
    }
}

/// Perform sliding window quality trimming.
///
/// Uses a sliding window approach where the window moves along the sequence,
/// calculating mean quality at each position. When the mean quality falls below
/// the threshold, the read is trimmed from that position.
///
/// # Arguments
/// * `qual` - Quality scores (Phred+33 encoded, ASCII 33-126)
/// * `config` - Trimming configuration
///
/// # Returns
/// A `TrimResult` containing the start and end indices of the good-quality region.
///
/// # Example
/// ```
/// use fastars::trim::quality::{sliding_window_trim, QualityTrimConfig};
///
/// let qual = b"IIIIIIIII55555!!!!!"; // High quality followed by low
/// let config = QualityTrimConfig::default();
/// let result = sliding_window_trim(qual, &config);
/// assert!(result.end < qual.len()); // Some trimming occurred
/// ```
pub fn sliding_window_trim(qual: &[u8], config: &QualityTrimConfig) -> TrimResult {
    let len = qual.len();

    // Handle edge cases
    if len == 0 {
        return TrimResult::empty();
    }

    if config.window_size == 0 || config.window_size > len {
        return TrimResult::full(len);
    }

    let mut start = 0;
    let mut end = len;

    // Trim from 3' end (tail)
    if config.cut_tail {
        let window_size = config.tail_window_size.unwrap_or(config.window_size);
        let threshold = config.tail_threshold.unwrap_or(config.threshold);
        end = trim_tail(qual, window_size, threshold);
    }

    // Trim from 5' end (front)
    if config.cut_front && end > 0 {
        let window_size = config.front_window_size.unwrap_or(config.window_size);
        let threshold = config.front_threshold.unwrap_or(config.threshold);
        start = trim_front(qual, end, window_size, threshold);
    }

    // Trim from the first low-quality window to the end (cut_right)
    if config.cut_right && end > 0 {
        let window_size = config.right_window_size.unwrap_or(config.window_size);
        let threshold = config.right_threshold.unwrap_or(config.threshold);
        let right_end = trim_right(qual, window_size, threshold);
        end = end.min(right_end);
    }

    if start >= end {
        return TrimResult::empty();
    }

    TrimResult::new(start, end)
}

/// Trim from the 3' end using sliding window.
///
/// This implements fastp's exact algorithm: when a good window is found,
/// keep only up to the start position of that window + 1.
/// (fastp does post-loop adjustment: t = t - w + 1, then rlen = t + 1)
fn trim_tail(qual: &[u8], window_size: usize, threshold: u8) -> usize {
    let len = qual.len();
    if len < window_size {
        return len;
    }

    // Calculate initial window sum at the end
    let mut window_sum: u32 = qual[len - window_size..]
        .iter()
        .map(|&q| phred_score(q) as u32)
        .sum();

    let threshold_sum = (threshold as u32) * (window_size as u32);

    // If last window is good, no trimming needed
    if window_sum >= threshold_sum {
        return len;
    }

    // Slide window from end towards start
    let mut end = len - window_size;

    for i in (0..len - window_size).rev() {
        // Slide window: add the new base, remove the one that exits
        window_sum = window_sum + phred_score(qual[i]) as u32
                   - phred_score(qual[i + window_size]) as u32;

        if window_sum >= threshold_sum {
            // Found a good window - fastp-compatible: keep up to window start + 1
            // (fastp does post-loop: t = t - w + 1, then rlen = t + 1)
            return i + 1;
        }
        end = i;
    }

    // All windows are bad
    end
}

/// Trim from the 5' end using sliding window.
fn trim_front(qual: &[u8], end: usize, window_size: usize, threshold: u8) -> usize {
    if end < window_size {
        return 0;
    }

    // Calculate initial window sum at the start
    let mut window_sum: u32 = qual[..window_size]
        .iter()
        .map(|&q| phred_score(q) as u32)
        .sum();

    let threshold_sum = (threshold as u32) * (window_size as u32);

    // If first window is good, no trimming needed
    if window_sum >= threshold_sum {
        return 0;
    }

    // Slide window from start towards end
    for i in 1..=end - window_size {
        // Slide window: add the new base, remove the one that exits
        window_sum = window_sum + phred_score(qual[i + window_size - 1]) as u32
                   - phred_score(qual[i - 1]) as u32;

        if window_sum >= threshold_sum {
            return i;
        }
    }

    // All windows are bad
    end
}

/// Trim from the first position where sliding window mean drops below threshold.
/// This scans left to right and trims from the first low-quality window to the end.
fn trim_right(qual: &[u8], window_size: usize, threshold: u8) -> usize {
    let len = qual.len();
    if len < window_size {
        return len;
    }

    // Calculate initial window sum at the start
    let mut window_sum: u32 = qual[..window_size]
        .iter()
        .map(|&q| phred_score(q) as u32)
        .sum();

    let threshold_sum = (threshold as u32) * (window_size as u32);

    // Check first window
    if window_sum < threshold_sum {
        return 0;
    }

    // Slide window from left to right
    for i in 1..=len - window_size {
        // Slide window: add the new base, remove the one that exits
        window_sum = window_sum + phred_score(qual[i + window_size - 1]) as u32
                   - phred_score(qual[i - 1]) as u32;

        if window_sum < threshold_sum {
            // Found low quality window, trim from here
            return i;
        }
    }

    // All windows are good
    len
}

/// Convert Phred+33 ASCII to Phred score.
#[inline]
fn phred_score(ascii: u8) -> u8 {
    ascii.saturating_sub(33)
}

/// Calculate mean quality score for a slice.
#[inline]
pub fn mean_quality(qual: &[u8]) -> f64 {
    if qual.is_empty() {
        return 0.0;
    }
    let sum: u32 = qual.iter().map(|&q| phred_score(q) as u32).sum();
    sum as f64 / qual.len() as f64
}

// Legacy type alias for compatibility
pub type QualityTrimmer = QualityTrimConfig;

/// Configuration for quality masking.
#[derive(Debug, Clone)]
pub struct MaskConfig {
    /// Window size for quality masking.
    pub window_size: usize,
    /// Mean quality threshold for masking.
    pub threshold: u8,
}

impl MaskConfig {
    /// Create a new mask config.
    pub fn new(window_size: usize, threshold: u8) -> Self {
        Self {
            window_size,
            threshold,
        }
    }
}

/// Configuration for read breaking.
#[derive(Debug, Clone)]
pub struct BreakConfig {
    /// Window size for read breaking.
    pub window_size: usize,
    /// Mean quality threshold for breaking.
    pub threshold: u8,
}

impl BreakConfig {
    /// Create a new break config.
    pub fn new(window_size: usize, threshold: u8) -> Self {
        Self {
            window_size,
            threshold,
        }
    }
}

/// Mask low quality regions in sequence and quality strings.
///
/// Detects low quality regions using a sliding window approach and replaces
/// bases in those regions with 'N' and quality with '!' (Phred 0).
///
/// # Arguments
/// * `seq` - Mutable sequence slice
/// * `qual` - Quality scores (Phred+33 encoded)
/// * `config` - Masking configuration
///
/// # Returns
/// Number of bases masked
pub fn mask_low_quality(seq: &mut [u8], qual: &[u8], config: &MaskConfig) -> usize {
    let len = seq.len();
    if len == 0 || len != qual.len() {
        return 0;
    }

    if config.window_size == 0 || config.window_size > len {
        return 0;
    }

    let threshold_sum = (config.threshold as u32) * (config.window_size as u32);
    let mut masked_count = 0;

    // Slide window across the sequence
    let mut window_sum: u32 = qual[..config.window_size]
        .iter()
        .map(|&q| phred_score(q) as u32)
        .sum();

    // Check first window
    if window_sum < threshold_sum {
        for i in 0..config.window_size {
            seq[i] = b'N';
            masked_count += 1;
        }
    }

    // Slide window from left to right
    for i in 1..=len - config.window_size {
        // Update window sum
        window_sum = window_sum + phred_score(qual[i + config.window_size - 1]) as u32
            - phred_score(qual[i - 1]) as u32;

        // If mean quality is below threshold, mask this window
        if window_sum < threshold_sum {
            for j in i..i + config.window_size {
                if seq[j] != b'N' {
                    seq[j] = b'N';
                    masked_count += 1;
                }
            }
        }
    }

    masked_count
}

/// Break a read at low quality regions.
///
/// Detects low quality regions using a sliding window approach and identifies
/// break points where the read should be split.
///
/// # Arguments
/// * `qual` - Quality scores (Phred+33 encoded)
/// * `config` - Breaking configuration
///
/// # Returns
/// Vector of (start, end) pairs representing high-quality segments
pub fn break_at_low_quality(qual: &[u8], config: &BreakConfig) -> Vec<(usize, usize)> {
    let len = qual.len();
    if len == 0 {
        return Vec::new();
    }

    if config.window_size == 0 || config.window_size > len {
        return vec![(0, len)];
    }

    let threshold_sum = (config.threshold as u32) * (config.window_size as u32);
    let mut low_quality_regions = Vec::new();

    // Slide window across the sequence to find low quality regions
    let mut window_sum: u32 = qual[..config.window_size]
        .iter()
        .map(|&q| phred_score(q) as u32)
        .sum();

    // Track low quality regions
    let mut in_low_quality = window_sum < threshold_sum;
    let mut low_quality_start = if in_low_quality { 0 } else { usize::MAX };

    for i in 1..=len - config.window_size {
        // Update window sum
        window_sum = window_sum + phred_score(qual[i + config.window_size - 1]) as u32
            - phred_score(qual[i - 1]) as u32;

        let is_low = window_sum < threshold_sum;

        if is_low && !in_low_quality {
            // Start of low quality region
            low_quality_start = i;
            in_low_quality = true;
        } else if !is_low && in_low_quality {
            // End of low quality region
            low_quality_regions.push((low_quality_start, i + config.window_size - 1));
            in_low_quality = false;
        }
    }

    // Handle case where read ends in low quality region
    if in_low_quality {
        low_quality_regions.push((low_quality_start, len));
    }

    // Convert low quality regions to high quality segments
    if low_quality_regions.is_empty() {
        return vec![(0, len)];
    }

    let mut segments = Vec::new();
    let mut current_pos = 0;

    for (lq_start, lq_end) in low_quality_regions {
        if current_pos < lq_start {
            segments.push((current_pos, lq_start));
        }
        current_pos = lq_end;
    }

    // Add final segment if there's high quality region at the end
    if current_pos < len {
        segments.push((current_pos, len));
    }

    segments
}

#[cfg(test)]
mod tests {
    use super::*;

    fn make_qual(scores: &[u8]) -> Vec<u8> {
        scores.iter().map(|&s| s + 33).collect()
    }

    #[test]
    fn test_quality_trim_config_default() {
        let config = QualityTrimConfig::default();
        assert_eq!(config.window_size, 4);
        assert_eq!(config.threshold, 15);
        assert!(!config.cut_front);
        assert!(config.cut_tail);
    }

    #[test]
    fn test_quality_trim_config_short_read() {
        let config = QualityTrimConfig::short_read();
        assert_eq!(config.window_size, 4);
        assert_eq!(config.threshold, 15);
    }

    #[test]
    fn test_quality_trim_config_long_read() {
        let config = QualityTrimConfig::long_read();
        assert_eq!(config.window_size, 20);
        assert_eq!(config.threshold, 7);
    }

    #[test]
    fn test_sliding_window_empty() {
        let config = QualityTrimConfig::default();
        let result = sliding_window_trim(&[], &config);
        assert!(result.is_empty());
    }

    #[test]
    fn test_sliding_window_all_high_quality() {
        let qual = make_qual(&[30, 30, 30, 30, 30, 30, 30, 30]);
        let config = QualityTrimConfig::default();
        let result = sliding_window_trim(&qual, &config);
        assert_eq!(result.start, 0);
        assert_eq!(result.end, 8);
    }

    #[test]
    fn test_sliding_window_all_low_quality() {
        let qual = make_qual(&[2, 2, 2, 2, 2, 2, 2, 2]);
        let config = QualityTrimConfig::default();
        let result = sliding_window_trim(&qual, &config);
        // All windows are bad, should trim to beginning
        assert!(result.is_empty() || result.len() < qual.len());
    }

    #[test]
    fn test_sliding_window_tail_trim() {
        // High quality at start, low at end
        let qual = make_qual(&[30, 30, 30, 30, 30, 30, 5, 5, 5, 5]);
        let config = QualityTrimConfig::default().with_cut_tail(true).with_cut_front(false);
        let result = sliding_window_trim(&qual, &config);
        assert_eq!(result.start, 0);
        // Tail should be trimmed - the exact position depends on window algorithm
        assert!(result.end < qual.len());
    }

    #[test]
    fn test_sliding_window_front_trim() {
        // Low quality at start, high at end
        let qual = make_qual(&[5, 5, 5, 5, 30, 30, 30, 30, 30, 30]);
        let config = QualityTrimConfig::default().with_cut_front(true).with_cut_tail(false);
        let result = sliding_window_trim(&qual, &config);
        // Front should be trimmed - start should be > 0
        assert!(result.start > 0);
        assert_eq!(result.end, 10);
    }

    #[test]
    fn test_sliding_window_both_ends() {
        // Low quality at both ends
        let qual = make_qual(&[5, 5, 5, 30, 30, 30, 30, 5, 5, 5]);
        let config = QualityTrimConfig::default().with_cut_front(true).with_cut_tail(true);
        let result = sliding_window_trim(&qual, &config);
        // Both ends should be trimmed - result should be shorter
        assert!(result.len() < qual.len());
    }

    #[test]
    fn test_sliding_window_shorter_than_window() {
        let qual = make_qual(&[30, 30]);
        let config = QualityTrimConfig::default().with_window_size(4);
        let result = sliding_window_trim(&qual, &config);
        assert_eq!(result.start, 0);
        assert_eq!(result.end, 2);
    }

    #[test]
    fn test_mean_quality() {
        let qual = make_qual(&[30, 30, 30, 30]);
        let mean = mean_quality(&qual);
        assert!((mean - 30.0).abs() < 0.01);
    }

    #[test]
    fn test_mean_quality_empty() {
        let mean = mean_quality(&[]);
        assert_eq!(mean, 0.0);
    }

    #[test]
    fn test_phred_score() {
        assert_eq!(phred_score(b'!'), 0);  // ASCII 33 = Phred 0
        assert_eq!(phred_score(b'I'), 40); // ASCII 73 = Phred 40
        assert_eq!(phred_score(b'~'), 93); // ASCII 126 = Phred 93
    }

    #[test]
    fn test_config_builder() {
        let config = QualityTrimConfig::new()
            .with_window_size(10)
            .with_threshold(20)
            .with_cut_front(true)
            .with_cut_tail(false);
        assert_eq!(config.window_size, 10);
        assert_eq!(config.threshold, 20);
        assert!(config.cut_front);
        assert!(!config.cut_tail);
    }
}