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
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
//! The startup banner and the `Command:` line.
//!
//! Every line whittle prints before processing starts is built here, as a pure
//! `String` from resolved config, so each one is unit-testable without a run.
//! `obs` owns the end-of-run counterparts; both use the same `output_desc`
//! text.

use crate::config::AdapterInfer;
use crate::{config, filter, io, trim};

/// The startup banner's operation line, also the wording of bar mode's single
/// start line: `Trimming FASTQ` when input and output share a `Format::family`
/// (a FASTQ to FASTQ.gz run is a compression change, not a conversion), else
/// `Converting {in_label} to {out_label}` for a cross-family conversion.
pub(crate) fn operation_line(in_fmt: io::Format, out_fmt: io::Format) -> String {
    if in_fmt.family() == out_fmt.family() {
        format!("Trimming {}", in_fmt.family())
    } else {
        format!("Converting {} to {}", in_fmt.label(), out_fmt.label())
    }
}

/// The startup banner's `Output: ...` line: `Output: <stdout>` when writing to
/// stdout (no compression detail), else `Output: {path}`, with
/// `(bgzf level {level})` appended for the compressed output formats.
pub(crate) fn output_banner_line(
    output: Option<&std::path::Path>,
    out_fmt: io::Format,
    level: u8,
) -> String {
    let Some(path) = output else {
        return "Output: <stdout>".to_string();
    };
    let mut line = format!("Output: {}", path.display());
    match out_fmt {
        io::Format::Bam | io::Format::FastqGz | io::Format::FastqBgzf => {
            line.push_str(&format!(" (bgzf level {level})"));
        },
        io::Format::Fastq => {},
    }
    line
}

/// The startup banner's `Threads: ...` line: the resolved worker count, then
/// the pool that trims and compresses and the decode workers ahead of it, as
/// `Threads: 8 (trim and compress 8, decode 2)`. `threads <= 1` prints
/// `Threads: 1 (sequential)`.
pub(crate) fn threads_banner_line(threads: usize, b: config::ThreadBudget) -> String {
    if threads <= 1 {
        return "Threads: 1 (sequential)".to_string();
    }
    format!(
        "Threads: {threads} (trim and compress {}, decode {})",
        b.render, b.decode
    )
}

/// The startup banner's `Filters: ...; trim: ...` line. Only active clauses
/// appear, so an all-defaults run reads `Filters: none; trim: none` rather than
/// every no-op threshold. A bound appears only when it differs from its default:
/// length from `min_length > 1` or `max_length != usize::MAX`, quality from
/// `min_qual > 0.0` or `max_qual < 1000.0`, GC from either bound being set.
pub(crate) fn filters_and_trim_line(
    filter: &filter::FilterConfig,
    trim: &trim::TrimPlan,
) -> String {
    let mut filters = Vec::new();

    let length_active = filter.min_length > 1 || filter.max_length != usize::MAX;
    if length_active {
        let mut length = String::new();
        if filter.min_length > 1 {
            length.push_str(&format!(">={}", filter.min_length));
        }
        if filter.max_length != usize::MAX {
            if !length.is_empty() {
                length.push(' ');
            }
            length.push_str(&format!("<={}", filter.max_length));
        }
        filters.push(format!("length {length}"));
    }

    let qual_active = filter.min_qual > 0.0 || filter.max_qual < 1000.0;
    if qual_active {
        let mut quality = format!("{} quality", filter.qual_mode.label());
        if filter.min_qual > 0.0 {
            quality.push_str(&format!(" >={}", filter.min_qual));
        }
        if filter.max_qual < 1000.0 {
            quality.push_str(&format!(" <={}", filter.max_qual));
        }
        filters.push(quality);
    }

    if let Some(max) = filter.max_expected_errors {
        filters.push(format!("expected errors <={max}"));
    }

    if filter.min_gc.is_some() || filter.max_gc.is_some() {
        filters.push(format!(
            "GC {}-{}",
            filter.min_gc.unwrap_or(0.0),
            filter.max_gc.unwrap_or(1.0)
        ));
    }

    let filters_str = if filters.is_empty() {
        "none".to_string()
    } else {
        filters.join("; ")
    };

    let mut trim_parts = Vec::new();
    if trim.head > 0 || trim.tail > 0 {
        trim_parts.push(format!("head {}, tail {}", trim.head, trim.tail));
    }
    if let Some(op) = &trim.quality {
        let mut part = format!("quality {} Q{}", op.method.label(), op.cutoff);
        if op.method == trim::QualityMethod::Runs {
            part.push_str(&format!(" run {}", op.min_low_quality_run));
        }
        if op.end_cutoff > op.cutoff {
            part.push_str(&format!(" ends Q{}", op.end_cutoff));
        }
        trim_parts.push(part);
    }
    let trim_str = if trim_parts.is_empty() {
        "none".to_string()
    } else {
        trim_parts.join(", ")
    };

    format!("Filters: {filters_str}; trim: {trim_str}")
}

/// The startup banner's `Adapters: ...` line: sequence count with its role
/// breakdown, `trim + split` or `ends-only`, error rate, end-zone size, and
/// whether presence detection samples. `None` when adapter trimming is off,
/// so the caller skips the line.
///
/// Under inference the count covers the known sequences that are trimmed
/// before discovery; discoveries are logged once the sample has been read.
pub(crate) fn adapter_banner_line(
    adapters: Option<&crate::adapter::AdapterConfig>,
    adapter_sample: usize,
    adapter_infer: AdapterInfer,
) -> Option<String> {
    let a = adapters?;
    let mode = if a.split { "trim + split" } else { "ends-only" };
    let sample = if adapter_sample > 0 {
        format!("sample {adapter_sample}")
    } else {
        "sample off".to_string()
    };
    let infer_suffix = match adapter_infer {
        AdapterInfer::Off => String::new(),
        mode => format!(" \u{b7} {}", mode.label()),
    };
    let (n_adapters, roles) = (a.adapters.len(), role_breakdown(&a.adapters));
    Some(format!(
        "Adapters: {n_adapters} sequences{roles} · {mode} · error {:.2} · end-zone {} bp · {sample}{infer_suffix}",
        a.error_rate, a.end_size
    ))
}

/// Returns ` (N adapter, M primer, K barcode)` for a mixed set, or an empty
/// string when every entry has the same role.
fn role_breakdown(adapters: &[crate::adapter::Adapter]) -> String {
    use crate::adapter::Role;
    let counts: Vec<(Role, usize)> = [Role::Adapter, Role::Primer, Role::Barcode]
        .into_iter()
        .map(|role| (role, adapters.iter().filter(|a| a.role == role).count()))
        .filter(|(_, n)| *n > 0)
        .collect();
    if counts.len() < 2 {
        return String::new();
    }
    let parts: Vec<String> = counts
        .iter()
        .map(|(role, n)| format!("{n} {}", role.label()))
        .collect();
    format!(" ({})", parts.join(", "))
}

/// Shell-quotes a single argument: bare when non-empty and every character is
/// in the POSIX-shell-safe set (`[A-Za-z0-9_@%+=:,./-]`); otherwise wrapped in
/// single quotes, with an embedded single quote escaped as `'\''` (close the
/// quote, an escaped literal quote, reopen the quote). An empty argument renders
/// as `''`, since a bare empty argument would vanish on re-run.
pub(crate) fn shell_quote(arg: &str) -> String {
    let is_safe = |c: char| c.is_ascii_alphanumeric() || "_@%+=:,./-".contains(c);
    if !arg.is_empty() && arg.chars().all(is_safe) {
        arg.to_string()
    } else {
        format!("'{}'", arg.replace('\'', r"'\''"))
    }
}

/// Joins the process argv into one shell-quoted line that can be copied and
/// re-run. Takes `OsStr`-like items (`args_os()`, not `args()`, which panics on
/// non-UTF-8 argv) and converts them lossily here, the one seam that must not
/// panic on a malformed argv. Generic over the iterator so tests supply their
/// own argv.
///
/// The value carries no label: the banner prefixes its own `Command: `, while
/// `--summary-json` stores the bare line under its `command` key.
pub fn command_line<I, S>(args: I) -> String
where
    I: IntoIterator<Item = S>,
    S: AsRef<std::ffi::OsStr>,
{
    args.into_iter()
        .map(|a| shell_quote(&a.as_ref().to_string_lossy()))
        .collect::<Vec<_>>()
        .join(" ")
}

/// The output path (or `<stdout>`) shown in both the startup banner's `Output:`
/// line and the end-of-run `Completed` line; the two use the same text.
pub(crate) fn output_desc(output: Option<&std::path::Path>) -> String {
    match output {
        Some(p) => p.display().to_string(),
        None => "<stdout>".to_string(),
    }
}
#[cfg(test)]
mod tests {
    use super::*;

    fn base_filter() -> filter::FilterConfig {
        filter::FilterConfig {
            min_length: 1,
            max_length: usize::MAX,
            min_qual: 0.0,
            max_qual: 1000.0,
            max_expected_errors: None,
            min_gc: None,
            max_gc: None,
            qual_mode: crate::qual::QualMode::Mean,
        }
    }

    fn base_trim() -> trim::TrimPlan {
        trim::TrimPlan {
            head: 0,
            tail: 0,
            quality: None,
        }
    }
    use crate::adapter::{Adapter, AdapterConfig, Role};

    #[test]
    fn operation_line_collapses_matching_families() {
        assert_eq!(
            operation_line(io::Format::Fastq, io::Format::Fastq),
            "Trimming FASTQ"
        );
        // FASTQ to FASTQ.gz shares the FASTQ family (a compression change, not
        // a format conversion), so it collapses as well rather than reading as
        // an `X to X` conversion.
        assert_eq!(
            operation_line(io::Format::Fastq, io::Format::FastqGz),
            "Trimming FASTQ"
        );
    }

    #[test]
    fn operation_line_converting_wording_for_cross_family() {
        assert_eq!(
            operation_line(io::Format::Bam, io::Format::Fastq),
            "Converting BAM to FASTQ"
        );
    }

    #[test]
    fn output_banner_line_plain_fastq_has_no_suffix() {
        let p = std::path::Path::new("/tmp/out.fastq");
        assert_eq!(
            output_banner_line(Some(p), io::Format::Fastq, 6),
            "Output: /tmp/out.fastq"
        );
    }

    #[test]
    fn output_banner_line_appends_compression_detail() {
        let p = std::path::Path::new("/tmp/out.fastq.gz");
        assert_eq!(
            output_banner_line(Some(p), io::Format::FastqGz, 6),
            "Output: /tmp/out.fastq.gz (bgzf level 6)"
        );
        let p = std::path::Path::new("/tmp/out.bam");
        assert_eq!(
            output_banner_line(Some(p), io::Format::Bam, 3),
            "Output: /tmp/out.bam (bgzf level 3)"
        );
    }

    #[test]
    fn output_banner_line_stdout_has_no_compression_detail() {
        // Even for a format that would otherwise show a compression suffix.
        assert_eq!(
            output_banner_line(None, io::Format::Bam, 6),
            "Output: <stdout>"
        );
    }

    #[test]
    fn threads_banner_line_names_the_pool_and_the_decoders() {
        let b = config::thread_budget(8, config::Decode::Blocks);
        assert_eq!(
            threads_banner_line(8, b),
            "Threads: 8 (trim and compress 6, decode 2)"
        );
        // A single-threaded run collapses to a plain `sequential` label.
        let b = config::thread_budget(1, config::Decode::Blocks);
        assert_eq!(threads_banner_line(1, b), "Threads: 1 (sequential)");
    }

    #[test]
    fn filters_and_trim_line_defaults() {
        // All-default filter and trim: no active clause, so it reads `none`
        // rather than no-op thresholds such as `mean quality >=0`.
        assert_eq!(
            filters_and_trim_line(&base_filter(), &base_trim()),
            "Filters: none; trim: none"
        );
    }

    #[test]
    fn filters_and_trim_line_only_min_length_active() {
        let mut f = base_filter();
        f.min_length = 500;
        assert_eq!(
            filters_and_trim_line(&f, &base_trim()),
            "Filters: length >=500; trim: none"
        );
    }

    #[test]
    fn filters_and_trim_line_only_max_length_active() {
        let mut f = base_filter();
        f.max_length = 10_000;
        assert_eq!(
            filters_and_trim_line(&f, &base_trim()),
            "Filters: length <=10000; trim: none"
        );
    }

    #[test]
    fn filters_and_trim_line_only_min_qual_active() {
        let mut f = base_filter();
        f.min_qual = 10.0;
        assert_eq!(
            filters_and_trim_line(&f, &base_trim()),
            "Filters: mean quality >=10; trim: none"
        );
    }

    #[test]
    fn filters_and_trim_line_only_max_qual_active() {
        let mut f = base_filter();
        f.max_qual = 40.0;
        assert_eq!(
            filters_and_trim_line(&f, &base_trim()),
            "Filters: mean quality <=40; trim: none"
        );
    }

    #[test]
    fn filters_and_trim_line_only_gc_active() {
        let mut f = base_filter();
        f.min_gc = Some(0.3);
        assert_eq!(
            filters_and_trim_line(&f, &base_trim()),
            "Filters: GC 0.3-1; trim: none"
        );
    }

    #[test]
    fn filters_and_trim_line_only_trim_active() {
        let mut t = base_trim();
        t.head = 5;
        assert_eq!(
            filters_and_trim_line(&base_filter(), &t),
            "Filters: none; trim: head 5, tail 0"
        );
    }

    #[test]
    fn filters_and_trim_line_quality_ops() {
        let f = base_filter();
        let mut t = base_trim();

        t.quality = Some(trim::QualityOp::new(trim::QualityMethod::Best, 20));
        assert!(filters_and_trim_line(&f, &t).ends_with("trim: quality best Q20"));

        t.quality = Some(trim::QualityOp::new(trim::QualityMethod::Segments, 10));
        assert!(filters_and_trim_line(&f, &t).ends_with("trim: quality segments Q10"));

        t.quality = Some(trim::QualityOp::runs(15, 50));
        assert!(filters_and_trim_line(&f, &t).ends_with("trim: quality runs Q15 run 50"));

        t.quality = Some(trim::QualityOp {
            end_cutoff: 20,
            ..trim::QualityOp::new(trim::QualityMethod::Segments, 10)
        });
        assert!(filters_and_trim_line(&f, &t).ends_with("trim: quality segments Q10 ends Q20"));

        // Head and tail only (no quality op): no trailing quality-op clause.
        t.quality = None;
        t.head = 3;
        t.tail = 0;
        assert!(filters_and_trim_line(&f, &t).ends_with("trim: head 3, tail 0"));
    }

    #[test]
    fn filters_and_trim_line_all_bounds_set() {
        let mut f = base_filter();
        f.min_length = 200;
        f.max_length = 10_000;
        f.min_qual = 8.0;
        f.max_qual = 30.0;
        f.min_gc = Some(0.4);
        f.max_gc = Some(0.6);
        f.max_expected_errors = Some(2.5);
        f.qual_mode = crate::qual::QualMode::Median;

        let mut t = base_trim();
        t.head = 10;
        t.tail = 5;
        t.quality = Some(trim::QualityOp::new(trim::QualityMethod::Ends, 12));

        assert_eq!(
            filters_and_trim_line(&f, &t),
            "Filters: length >=200 <=10000; median quality >=8 <=30; expected errors <=2.5; \
             GC 0.4-0.6; \
             trim: head 10, tail 5, quality ends Q12"
        );
    }

    #[test]
    fn adapter_banner_line_none_when_off_and_describes_when_on() {
        assert!(adapter_banner_line(None, 10000, AdapterInfer::Off).is_none());
        let cfg = AdapterConfig {
            adapters: vec![Adapter {
                name: "a".into(),
                seq: b"ACGTACGTACGT".to_vec(),
                role: Role::Adapter,
            }],
            error_rate: 0.2,
            end_size: 150,
            split: true,
            min_piece: 1,
            candidate_index: std::sync::OnceLock::new(),
            amplicon: false,
        };
        let line = adapter_banner_line(Some(&cfg), 10000, AdapterInfer::Off).unwrap();
        assert!(line.contains("1 sequences"));
        assert!(line.contains("trim + split"));
        assert!(line.contains("error 0.20"));
        assert!(line.contains("end-zone 150 bp"));
        assert!(line.contains("sample 10000"));
        assert!(!line.contains("infer"), "No infer suffix when off: {line}");

        let off_line = adapter_banner_line(Some(&cfg), 0, AdapterInfer::Off).unwrap();
        assert!(off_line.contains("sample off"));
    }

    #[test]
    fn adapter_banner_line_ends_only_when_split_disabled() {
        let cfg = AdapterConfig {
            adapters: vec![Adapter {
                name: "a".into(),
                seq: b"ACGTACGTACGT".to_vec(),
                role: Role::Adapter,
            }],
            error_rate: 0.2,
            end_size: 150,
            split: false,
            min_piece: 1,
            candidate_index: std::sync::OnceLock::new(),
            amplicon: false,
        };
        assert!(
            adapter_banner_line(Some(&cfg), 10000, AdapterInfer::Off)
                .unwrap()
                .contains("ends-only")
        );
    }

    #[test]
    fn adapter_banner_line_notes_infer_mode() {
        let cfg = AdapterConfig {
            adapters: vec![],
            error_rate: 0.2,
            end_size: 150,
            split: true,
            min_piece: 1,
            candidate_index: std::sync::OnceLock::new(),
            amplicon: false,
        };
        let trim_line = adapter_banner_line(Some(&cfg), 40000, AdapterInfer::Discover).unwrap();
        assert!(trim_line.ends_with("\u{b7} discover"), "{trim_line}");

        let report_line = adapter_banner_line(Some(&cfg), 40000, AdapterInfer::Report).unwrap();
        assert!(report_line.ends_with("\u{b7} report"), "{report_line}");
    }

    #[test]
    fn command_line_quotes_only_unsafe_args() {
        assert_eq!(
            command_line(["whittle", "-i", "in.fastq", "-o", "out.fastq"]),
            "whittle -i in.fastq -o out.fastq"
        );
        assert_eq!(
            command_line(["whittle", "-i", "my reads.fastq"]),
            "whittle -i 'my reads.fastq'"
        );
    }

    #[test]
    fn shell_quote_leaves_plain_args_bare() {
        assert_eq!(shell_quote("whittle"), "whittle");
        assert_eq!(shell_quote("-i"), "-i");
        assert_eq!(shell_quote("in.fastq"), "in.fastq");
        assert_eq!(
            shell_quote("path/to/file_1.0.fq.gz"),
            "path/to/file_1.0.fq.gz"
        );
    }

    #[test]
    fn shell_quote_wraps_args_with_spaces() {
        assert_eq!(shell_quote("my reads.fastq"), "'my reads.fastq'");
    }

    #[test]
    fn shell_quote_escapes_embedded_single_quotes() {
        assert_eq!(shell_quote("it's here.fastq"), r"'it'\''s here.fastq'");
    }

    #[test]
    fn shell_quote_wraps_shell_metacharacters() {
        assert_eq!(shell_quote("$HOME"), "'$HOME'");
        assert_eq!(shell_quote("a;b"), "'a;b'");
    }

    #[test]
    fn shell_quote_wraps_empty_string() {
        // A bare empty argument would vanish when the line is re-run.
        assert_eq!(shell_quote(""), "''");
    }

    #[test]
    fn output_desc_stdout_vs_path() {
        assert_eq!(output_desc(None), "<stdout>");
        assert_eq!(
            output_desc(Some(std::path::Path::new("/tmp/out.fastq"))),
            "/tmp/out.fastq"
        );
    }
}