whittle 1.0.0

Coordinate-consistent trimming of long-read uBAM and tagged FASTQ
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
//! Adapter trimming and splitting, barcode restriction, per-segment cropping
//! and quality processing, expressed as intervals in the original read.

pub mod strategies;

use strategies::{best_segment, maximal_segments, split_low_quality, trim_by_quality};

/// The quality trimming method, selected by `--quality-trim`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum QualityMethod {
    /// Trim each end up to the first base at or above the cutoff
    Ends,
    /// Keep the single best segment under the modified Mott score
    Best,
    /// Keep every maximal segment under the modified Mott score
    Segments,
    /// Split at runs of --min-low-quality-run bases below the cutoff
    Runs,
}

impl QualityMethod {
    /// Lowercase label, as the command line, the banner and the summary spell
    /// it.
    pub fn label(self) -> &'static str {
        match self {
            QualityMethod::Ends => "ends",
            QualityMethod::Best => "best",
            QualityMethod::Segments => "segments",
            QualityMethod::Runs => "runs",
        }
    }
}

/// The quality trimming applied within each adapter segment.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct QualityOp {
    /// The trimming method.
    pub method: QualityMethod,
    /// Phred cutoff the method scores or compares each base against.
    pub cutoff: u8,
    /// Minimum run of bases below `cutoff` that splits a read under
    /// `QualityMethod::Runs`; 1 for the other methods.
    pub min_low_quality_run: usize,
    /// Phred cutoff at which each piece of `QualityMethod::Segments` or
    /// `QualityMethod::Runs` has its ends trimmed after the split; equal to
    /// `cutoff` unless set.
    pub end_cutoff: u8,
}

impl QualityOp {
    /// The operation `method` at `cutoff`, splitting at every low-quality base
    /// under `QualityMethod::Runs`.
    pub fn new(method: QualityMethod, cutoff: u8) -> Self {
        QualityOp {
            method,
            cutoff,
            min_low_quality_run: 1,
            end_cutoff: cutoff,
        }
    }

    /// The `QualityMethod::Runs` operation at `cutoff`, splitting at runs of at
    /// least `min_low_quality_run` bases below it.
    pub fn runs(cutoff: u8, min_low_quality_run: usize) -> Self {
        QualityOp {
            min_low_quality_run,
            ..QualityOp::new(QualityMethod::Runs, cutoff)
        }
    }

    /// Returns the intervals of `phred` the operation keeps, in its coordinates.
    ///
    /// Every piece of `Segments` and `Runs` starts and ends at a base at or
    /// above `cutoff`, so the end trim changes a piece only when `end_cutoff`
    /// is higher; a piece with no base at or above it is dropped.
    fn apply(&self, phred: &[u8]) -> Vec<(usize, usize)> {
        let pieces = match self.method {
            QualityMethod::Ends => return trim_by_quality(phred, self.cutoff),
            QualityMethod::Best => return best_segment(phred, self.cutoff),
            QualityMethod::Segments => maximal_segments(phred, self.cutoff),
            QualityMethod::Runs => split_low_quality(phred, self.cutoff, self.min_low_quality_run),
        };
        if self.end_cutoff <= self.cutoff {
            return pieces;
        }
        pieces
            .into_iter()
            .flat_map(|(s, e)| {
                trim_by_quality(&phred[s..e], self.end_cutoff)
                    .into_iter()
                    .map(move |(ts, te)| (s + ts, s + te))
            })
            .collect()
    }
}

/// The per-read trim configuration.
#[derive(Debug, Clone, Default)]
pub struct TrimPlan {
    /// Bases removed from each adapter-derived segment's 5' end after barcode restriction.
    pub head: usize,
    /// Bases removed from each adapter-derived segment's 3' end after barcode restriction.
    pub tail: usize,
    /// Quality operation applied to each cropped segment.
    pub quality: Option<QualityOp>,
}

/// Searches the original read for adapters, intersects each retained segment
/// with `barcode`, crops each intersection once, and applies the quality
/// operation. Quality splitting can produce multiple intervals per adapter
/// segment. The result is flattened in original-coordinate order for final
/// numbering and filtering by length, quality and GC.
///
/// `barcode` is the retained interval resolved from the original record's
/// verified `bi` spans. `None` retains the whole read. An unmatched
/// read enters barcode restriction and cropping as one full-length segment.
pub fn apply(
    seq: &[u8],
    phred: &[u8],
    plan: &TrimPlan,
    adapters: Option<&crate::adapter::AdapterConfig>,
    barcode: Option<(usize, usize)>,
) -> Vec<(usize, usize)> {
    debug_assert_eq!(
        seq.len(),
        phred.len(),
        "Sequence and quality lengths must be equal"
    );
    let seq_len = seq.len();
    let (outer_start, outer_end) = match barcode {
        Some((s, e)) => (s.min(seq_len), e.clamp(s.min(seq_len), seq_len)),
        None => (0, seq_len),
    };
    if outer_start >= outer_end {
        return vec![];
    }

    let process_segment = |s: usize, e: usize, out: &mut Vec<(usize, usize)>| {
        let s = s.max(outer_start);
        let e = e.min(outer_end);
        if s >= e {
            return;
        }
        let s = s.saturating_add(plan.head).min(e);
        let e = e.saturating_sub(plan.tail).max(s);
        if s >= e {
            return;
        }
        let wp = &phred[s..e];
        let offset = |v: Vec<(usize, usize)>, out: &mut Vec<(usize, usize)>| {
            out.extend(v.into_iter().map(|(is, ie)| (is + s, ie + s)));
        };
        match &plan.quality {
            None => out.push((s, e)),
            Some(op) => offset(op.apply(wp), out),
        }
    };

    let mut out = Vec::new();
    match adapters {
        None => {
            process_segment(0, seq_len, &mut out);
        },
        Some(cfg) => {
            for (s, e) in crate::adapter::adapter_segments(seq, cfg) {
                process_segment(s, e, &mut out);
            }
        },
    }
    out
}

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

    fn adapter_config() -> crate::adapter::AdapterConfig {
        crate::adapter::AdapterConfig {
            adapters: vec![crate::adapter::Adapter {
                name: "junction".into(),
                seq: b"GGGGTTTTGGGGTTTT".to_vec(),
                role: crate::adapter::Role::Adapter,
            }],
            error_rate: 0.0,
            end_size: 8,
            split: true,
            min_piece: 1,
            candidate_index: std::sync::OnceLock::new(),
            amplicon: false,
        }
    }

    #[test]
    fn adapter_segments_are_cropped_once_before_quality_processing() {
        let ac = adapter_config();
        let seq = [vec![b'C'; 64], ac.adapters[0].seq.clone(), vec![b'A'; 64]].concat();
        let mut phred = vec![40; seq.len()];
        phred[20..24].fill(2);
        phred[104..108].fill(2);
        let plan = TrimPlan {
            head: 3,
            tail: 5,
            quality: Some(QualityOp::runs(9, 4)),
        };
        assert_eq!(
            apply(&seq, &phred, &plan, Some(&ac), None),
            vec![(3, 20), (24, 59), (83, 104), (108, 139)]
        );
        assert_eq!(
            apply(&seq, &phred, &plan, Some(&ac), Some((10, 135))),
            vec![(13, 20), (24, 59), (83, 104), (108, 130)]
        );
        let end_trim = TrimPlan {
            quality: Some(QualityOp::new(QualityMethod::Ends, 20)),
            ..plan.clone()
        };
        assert_eq!(
            apply(&seq, &phred, &end_trim, Some(&ac), None),
            vec![(3, 59), (83, 139)]
        );
        let best = TrimPlan {
            quality: Some(QualityOp::new(QualityMethod::Best, 20)),
            ..plan
        };
        assert_eq!(
            apply(&seq, &phred, &best, Some(&ac), None),
            vec![(24, 59), (108, 139)]
        );
    }

    /// Each maximal segment of a cropped segment is offset back to read
    /// coordinates.
    #[test]
    fn split_segments_are_offset_to_read_coordinates() {
        let seq = vec![b'C'; 200];
        let mut phred = vec![40; seq.len()];
        phred[80..100].fill(2);
        let plan = TrimPlan {
            head: 3,
            tail: 5,
            quality: Some(QualityOp::new(QualityMethod::Segments, 20)),
        };
        assert_eq!(
            apply(&seq, &phred, &plan, None, None),
            vec![(3, 80), (100, 195)]
        );
    }

    /// A read the method leaves whole has its ends trimmed at the stricter end
    /// cutoff under both splitting methods.
    #[test]
    fn end_cutoff_trims_the_ends_of_an_unsplit_read() {
        let phred = [vec![12u8; 5], vec![30; 100], vec![12; 5]].concat();
        let seq = vec![b'A'; phred.len()];
        for method in [QualityMethod::Segments, QualityMethod::Runs] {
            let op = QualityOp::new(method, 10);
            let plan = |quality| TrimPlan {
                quality: Some(quality),
                ..TrimPlan::default()
            };
            assert_eq!(
                apply(&seq, &phred, &plan(op.clone()), None, None),
                vec![(0, 110)],
                "{method:?}"
            );
            let strict = QualityOp {
                end_cutoff: 20,
                ..op
            };
            assert_eq!(
                apply(&seq, &phred, &plan(strict), None, None),
                vec![(5, 105)],
                "{method:?}"
            );
        }
    }

    /// Every piece of a split read has both of its ends trimmed at the end
    /// cutoff, including the ends facing the low-quality region, and a piece
    /// left with no base at or above the end cutoff is dropped.
    #[test]
    fn end_cutoff_trims_every_piece_of_a_split_read() {
        let phred = [
            vec![12u8; 5],
            vec![30; 80],
            vec![12; 3],
            vec![2; 30],
            vec![14; 4],
            vec![30; 80],
            vec![12; 5],
            vec![2; 30],
            vec![15; 60],
        ]
        .concat();
        let seq = vec![b'A'; phred.len()];
        let runs = TrimPlan {
            quality: Some(QualityOp {
                end_cutoff: 20,
                ..QualityOp::runs(10, 10)
            }),
            ..TrimPlan::default()
        };
        assert_eq!(
            apply(&seq, &phred, &runs, None, None),
            vec![(5, 85), (122, 202)]
        );
        let segments = TrimPlan {
            quality: Some(QualityOp {
                end_cutoff: 20,
                ..QualityOp::new(QualityMethod::Segments, 10)
            }),
            ..TrimPlan::default()
        };
        assert_eq!(
            apply(&seq, &phred, &segments, None, None),
            vec![(5, 85), (122, 202)]
        );
    }

    /// An end cutoff at or below the method cutoff changes nothing: every
    /// piece already starts and ends at a base at or above the method cutoff.
    #[test]
    fn end_cutoff_at_or_below_the_cutoff_keeps_the_method_output() {
        let mut state = 5u64;
        for _ in 0..500 {
            let len = 1 + (lcg(&mut state) % 400) as usize;
            let phred: Vec<u8> = (0..len).map(|_| (lcg(&mut state) % 40) as u8).collect();
            let seq = vec![b'A'; len];
            for op in [
                QualityOp::runs(12, 3),
                QualityOp::new(QualityMethod::Segments, 12),
            ] {
                let plan = |quality| TrimPlan {
                    quality: Some(quality),
                    ..TrimPlan::default()
                };
                let want = apply(&seq, &phred, &plan(op.clone()), None, None);
                for end_cutoff in [0, 7, 12] {
                    let lower = QualityOp {
                        end_cutoff,
                        ..op.clone()
                    };
                    assert_eq!(apply(&seq, &phred, &plan(lower), None, None), want);
                }
            }
        }
    }

    /// A deterministic linear congruential generator for the randomized tests.
    fn lcg(state: &mut u64) -> u64 {
        *state = state
            .wrapping_mul(6_364_136_223_846_793_005)
            .wrapping_add(1_442_695_040_888_963_407);
        *state >> 33
    }

    #[test]
    fn terminal_adapter_is_recognized_before_barcode_restriction_and_crop() {
        let ac = adapter_config();
        let seq = [ac.adapters[0].seq.clone(), vec![b'C'; 64]].concat();
        let phred = vec![40; seq.len()];
        let plan = TrimPlan {
            head: 3,
            tail: 5,
            quality: None,
        };
        assert_eq!(apply(&seq, &phred, &plan, Some(&ac), None), vec![(19, 75)]);
        assert_eq!(
            apply(&seq, &phred, &plan, Some(&ac), Some((12, 70))),
            vec![(19, 65)]
        );
    }

    #[test]
    fn unmatched_read_is_cropped_and_quality_split() {
        let ac = adapter_config();
        let seq = vec![b'C'; 64];
        let mut phred = vec![40; seq.len()];
        phred[20..24].fill(2);
        let plan = TrimPlan {
            head: 3,
            tail: 5,
            quality: Some(QualityOp::runs(9, 4)),
        };
        assert_eq!(
            apply(&seq, &phred, &plan, Some(&ac), None),
            vec![(3, 20), (24, 59)]
        );
    }

    #[test]
    fn crop_can_consume_one_adapter_segment_without_consuming_its_sibling() {
        let ac = adapter_config();
        let seq = [vec![b'C'; 24], ac.adapters[0].seq.clone(), vec![b'A'; 64]].concat();
        let phred = vec![40; seq.len()];
        let plan = TrimPlan {
            head: 20,
            tail: 5,
            quality: None,
        };
        assert_eq!(apply(&seq, &phred, &plan, Some(&ac), None), vec![(60, 99)]);
        assert!(apply(&seq, &phred, &plan, Some(&ac), Some((0, 24))).is_empty());
    }

    #[test]
    fn no_quality_op_is_fixed_crop() {
        let phred = vec![30u8; 20];
        let seq = vec![b'A'; 20];
        let plan = TrimPlan {
            head: 5,
            tail: 3,
            quality: None,
        };
        assert_eq!(apply(&seq, &phred, &plan, None, None), vec![(5, 17)]);
    }

    #[test]
    fn crop_then_quality_offsets_back() {
        // 20 bases, head crop 2, then `TrimQual` on the remaining window. The
        // first two Phred values are low, so the good region starts at 2 after
        // the crop.
        let mut phred = vec![40u8; 20];
        phred[0] = 2;
        phred[1] = 2;
        let seq = vec![b'A'; 20];
        let plan = TrimPlan {
            head: 2,
            tail: 0,
            quality: Some(QualityOp::new(QualityMethod::Ends, 30)),
        };
        assert_eq!(apply(&seq, &phred, &plan, None, None), vec![(2, 20)]);
    }

    /// `apply` applies no length filter; the caller filters per segment after
    /// trimming, so a short segment is returned.
    #[test]
    fn short_segments_are_emitted_not_filtered() {
        let phred = vec![40u8; 4];
        let seq = vec![b'A'; 4];
        let plan = TrimPlan {
            head: 0,
            tail: 0,
            quality: None,
        };
        assert_eq!(apply(&seq, &phred, &plan, None, None), vec![(0, 4)]);
    }

    #[test]
    fn empty_when_crop_exceeds_length() {
        let phred = vec![40u8; 4];
        let seq = vec![b'A'; 4];
        let plan = TrimPlan {
            head: 3,
            tail: 3,
            quality: None,
        };
        assert_eq!(
            apply(&seq, &phred, &plan, None, None),
            Vec::<(usize, usize)>::new()
        );
    }

    #[test]
    fn adapter_stage_runs_before_quality_op() {
        use crate::adapter::{Adapter, AdapterConfig, Role};
        let adapter = b"ACGTACGTACGT";
        let mut seq = adapter.to_vec();
        seq.extend_from_slice(b"GGGGGGGGGGGG");
        let mut phred = vec![40u8; seq.len()];
        phred[12..15].fill(2);
        let plan = TrimPlan {
            head: 2,
            tail: 1,
            quality: Some(QualityOp::new(QualityMethod::Ends, 20)),
        };
        let ac = AdapterConfig {
            adapters: vec![Adapter {
                name: "a".into(),
                seq: adapter.to_vec(),
                role: Role::Adapter,
            }],
            error_rate: 0.2,
            end_size: 20,
            split: false,
            min_piece: 1,
            candidate_index: std::sync::OnceLock::new(),
            amplicon: false,
        };
        assert_eq!(apply(&seq, &phred, &plan, Some(&ac), None), vec![(15, 23)]);
    }

    #[test]
    fn crop_without_adapters_uses_the_full_read() {
        let phred = vec![30u8; 20];
        let seq = vec![b'A'; 20];
        let plan = TrimPlan {
            head: 5,
            tail: 3,
            quality: None,
        };
        assert_eq!(apply(&seq, &phred, &plan, None, None), vec![(5, 17)]);
    }
}

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

    /// Fixed cropping operates within the original-coordinate barcode interval.
    #[test]
    fn barcode_window_precedes_the_crop() {
        let seq = vec![b'A'; 20];
        let phred = vec![40u8; 20];
        let plan = TrimPlan {
            head: 2,
            tail: 1,
            quality: None,
        };
        assert_eq!(
            apply(&seq, &phred, &plan, None, Some((5, 15))),
            vec![(7, 14)]
        );
    }

    /// A crop wider than the barcode window keeps nothing.
    #[test]
    fn crop_beyond_the_barcode_window_keeps_nothing() {
        let seq = vec![b'A'; 20];
        let phred = vec![40u8; 20];
        let plan = TrimPlan {
            head: 6,
            tail: 6,
            quality: None,
        };
        let kept = apply(&seq, &phred, &plan, None, Some((5, 15)));
        assert!(kept.is_empty());
    }
}