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
//! Machine-readable run summary (`--summary-json`).
//!
//! One JSON object per run: the resolved settings (`params`), what was consumed
//! and produced (`reads`, `bases`), and why anything was dropped
//! (`segments_dropped`). Written regardless of `--quiet` or the log level. The
//! field names are interface: `schema_version` is bumped when an existing field
//! changes meaning or disappears, but not when one is added.

use std::path::Path;

use serde::Serialize;

use crate::config::{Config, FastqTags};
use crate::trim::QualityMethod;
use crate::workflow::Stats;

/// Incremented only when an existing field changes meaning or is removed.
const SCHEMA_VERSION: u32 = 2;

/// The `--summary-json` document for one run.
#[derive(Debug, Serialize)]
pub struct Summary {
    schema_version: u32,
    tool: &'static str,
    version: &'static str,
    /// The invocation, shell-quoted so it can be copied back out and re-run.
    command: String,
    /// Input path, or `<stdin>`.
    input: String,
    /// Output path, or `<stdout>`.
    output: String,
    /// Wall-clock processing time.
    elapsed_seconds: f64,
    params: Params,
    reads: Reads,
    bases: Bases,
    segments_dropped: SegmentsDropped,
    warnings: Warnings,
}

/// The run's resolved settings, after defaults and clamping. Reading these back,
/// rather than re-deriving them from `command`, makes the file a self-contained
/// provenance record.
#[derive(Debug, Serialize)]
struct Params {
    threads: usize,
    compression_level: u8,
    min_length: usize,
    /// `None` when `--max-length` was not given.
    max_length: Option<usize>,
    min_qual: f64,
    max_qual: f64,
    max_expected_errors: Option<f64>,
    min_gc: Option<f64>,
    max_gc: Option<f64>,
    qual_mode: &'static str,
    head_crop: usize,
    tail_crop: usize,
    /// `None` without `--quality-trim`.
    quality_trim: Option<QualityTrimParams>,
    update_moves: bool,
    ordered: bool,
    /// Aux tags removed from every output record, sorted, with every
    /// `--remove-tag` group expanded.
    remove_tags: Vec<String>,
    /// The `--tag-filter` expressions as written; empty when unset.
    tag_filter: Vec<String>,
    /// The `--rejected-output` path, or `None`.
    rejected_output: Option<String>,
    /// `all`, `none`, or the comma-joined tag list.
    fastq_tags: String,
    /// `None` when adapter trimming is off.
    adapters: Option<AdapterParams>,
}

/// The `--quality-trim` method and its settings.
#[derive(Debug, Serialize)]
struct QualityTrimParams {
    /// `ends`, `best`, `segments`, or `runs`.
    method: &'static str,
    cutoff: u8,
    /// Only meaningful for `runs`; `None` otherwise.
    min_low_quality_run: Option<usize>,
    /// The resolved `--quality-end-cutoff` of `segments` and `runs`; `None`
    /// otherwise.
    end_cutoff: Option<u8>,
}

/// The adapter-trimming settings and the configured and resolved set sizes.
#[derive(Debug, Serialize)]
struct AdapterParams {
    /// Adapters configured before resolution: the preset, the FASTA, or both.
    /// This is the figure the startup banner prints, since it is all that is
    /// known before reads have been sampled. `0` under inference, where the set
    /// is discovered rather than configured.
    configured: usize,
    /// Adapters trimmed against, after presence detection narrowed the
    /// configured set or inference replaced it. Equal to `configured` when
    /// neither ran.
    count: usize,
    error_rate: f64,
    end_size: usize,
    /// False under `--adapter-ends-only`.
    split: bool,
    /// Reads sampled for presence detection or inference; `0` disables detection.
    sample: usize,
    /// `off`, `trim`, or `report`.
    infer: &'static str,
}

/// Read-level counts: input, output, and the four-way split of the input.
#[derive(Debug, Serialize)]
struct Reads {
    input: u64,
    /// Output segments written. A quality-split read can contribute several,
    /// so this can exceed `input`.
    output: u64,
    /// Input reads that produced at least one surviving segment.
    with_output: u64,
    /// Input reads that produced no segments at all (empty, fully consumed by
    /// adapter trimming, or over-cropped).
    trimmed_to_nothing: u64,
    /// Input reads that produced segments, all of which the filters rejected.
    all_filtered: u64,
    /// Input reads rejected by `--tag-filter` before trimming.
    tag_filtered: u64,
}

/// Base-level counts for input and output.
#[derive(Debug, Serialize)]
struct Bases {
    input: u64,
    output: u64,
}

/// Segment-level filter rejections, by reason. One input read can contribute to
/// more than one of these when it splits, so these do not sum to a read count.
#[derive(Debug, Serialize)]
struct SegmentsDropped {
    too_short: u64,
    too_long: u64,
    low_quality: u64,
    high_quality: u64,
    expected_errors: u64,
    gc_out_of_range: u64,
}

/// Per-read anomalies the run tolerated.
#[derive(Debug, Serialize)]
struct Warnings {
    /// Reads whose per-base kinetics tag length disagreed with the sequence and
    /// was left untouched.
    malformed_tag_reads: u64,
    /// Reads whose `MM`/`ML`/`MN` block was malformed and removed.
    malformed_mod_reads: u64,
    undo_tags_dropped_reads: u64,
    /// Trimmed or split reads whose fibertools footprint arrays (`ns`, `nl`,
    /// `as`, `al`) were removed.
    footprint_tags_dropped_reads: u64,
    /// Reads whose `bi` barcode tag was not a valid barcode window and were
    /// left untrimmed by that stage.
    barcode_tag_malformed_reads: u64,
    /// Reads with a recorded barcode span at which no barcode sequence was
    /// found; those spans were left untrimmed.
    barcode_tag_unverified_reads: u64,
}

impl Summary {
    /// Builds the summary from a finished run. `command` is the shell-quoted
    /// invocation (see `crate::command_line`), `output` the output path or
    /// `<stdout>` label already computed for the banner.
    pub fn new(
        cfg: &Config,
        stats: &Stats,
        command: String,
        output: String,
        elapsed: std::time::Duration,
    ) -> Self {
        Summary {
            schema_version: SCHEMA_VERSION,
            tool: "whittle",
            version: env!("CARGO_PKG_VERSION"),
            command,
            input: cfg
                .io
                .input
                .as_deref()
                .map_or_else(|| "<stdin>".to_string(), |p| p.display().to_string()),
            output,
            elapsed_seconds: elapsed.as_secs_f64(),
            params: Params::from_config(cfg),
            reads: Reads {
                input: stats.input_reads,
                output: stats.output_reads,
                with_output: stats.reads_with_output,
                trimmed_to_nothing: stats.reads_trimmed_to_nothing,
                all_filtered: stats.reads_all_filtered,
                tag_filtered: stats.reads_tag_filtered,
            },
            bases: Bases {
                input: stats.input_bases,
                output: stats.output_bases,
            },
            segments_dropped: SegmentsDropped {
                too_short: stats.segments_dropped_short,
                too_long: stats.segments_dropped_long,
                low_quality: stats.segments_dropped_low_qual,
                high_quality: stats.segments_dropped_high_qual,
                expected_errors: stats.segments_dropped_expected_errors,
                gc_out_of_range: stats.segments_dropped_gc,
            },
            warnings: Warnings {
                malformed_tag_reads: stats.malformed_tag_reads,
                malformed_mod_reads: stats.malformed_mod_reads,
                undo_tags_dropped_reads: stats.undo_tags_dropped_reads,
                footprint_tags_dropped_reads: stats.footprint_tags_dropped_reads,
                barcode_tag_malformed_reads: stats.barcode_tag_malformed_reads,
                barcode_tag_unverified_reads: stats.barcode_tag_unverified_reads,
            },
        }
    }

    /// Serializes to pretty-printed JSON with a trailing newline, so the file is
    /// diff-friendly and safe to `cat` in a shell.
    pub fn to_json(&self) -> anyhow::Result<String> {
        let mut s = serde_json::to_string_pretty(self)?;
        s.push('\n');
        Ok(s)
    }

    /// Writes the summary to `path`. A write failure is a hard error, since a
    /// stale file from a previous invocation would otherwise remain in place.
    pub fn write(&self, path: &Path) -> anyhow::Result<()> {
        let json = self.to_json()?;
        std::fs::write(path, json)
            .map_err(|e| anyhow::anyhow!("writing summary JSON to {}: {e}", path.display()))
    }
}

impl Params {
    fn from_config(cfg: &Config) -> Self {
        Params {
            threads: cfg.threads,
            compression_level: cfg.compression_level,
            min_length: cfg.filter.min_length,
            max_length: (cfg.filter.max_length != usize::MAX).then_some(cfg.filter.max_length),
            min_qual: cfg.filter.min_qual,
            max_qual: cfg.filter.max_qual,
            max_expected_errors: cfg.filter.max_expected_errors,
            min_gc: cfg.filter.min_gc,
            max_gc: cfg.filter.max_gc,
            qual_mode: cfg.filter.qual_mode.label(),
            head_crop: cfg.trim.head,
            tail_crop: cfg.trim.tail,
            quality_trim: cfg.trim.quality.as_ref().map(|op| QualityTrimParams {
                method: op.method.label(),
                cutoff: op.cutoff,
                min_low_quality_run: (op.method == QualityMethod::Runs)
                    .then_some(op.min_low_quality_run),
                end_cutoff: matches!(op.method, QualityMethod::Segments | QualityMethod::Runs)
                    .then_some(op.end_cutoff),
            }),
            update_moves: cfg.update_moves,
            ordered: cfg.ordered,
            remove_tags: cfg
                .remove_tags
                .tags()
                .map(|t| String::from_utf8_lossy(t).into_owned())
                .collect(),
            tag_filter: cfg.tag_filters.texts().map(str::to_owned).collect(),
            rejected_output: cfg
                .rejected_output
                .as_ref()
                .map(|p| p.display().to_string()),
            fastq_tags: match &cfg.fastq_tags {
                FastqTags::All => "all".to_string(),
                FastqTags::None => "none".to_string(),
                FastqTags::Only(tags) => tags
                    .iter()
                    .map(|t| String::from_utf8_lossy(t).into_owned())
                    .collect::<Vec<_>>()
                    .join(","),
            },
            adapters: cfg.adapters.as_ref().map(|ac| AdapterParams {
                // Falls back to the resolved count for a caller that drove the
                // workflow directly and never went through `settle`.
                configured: cfg.adapters_configured.unwrap_or(ac.adapters.len()),
                count: ac.adapters.len(),
                error_rate: ac.error_rate,
                end_size: ac.end_size,
                split: ac.split,
                sample: cfg.adapter_sample,
                infer: cfg.adapter_infer.label(),
            }),
        }
    }
}

#[cfg(test)]
mod tests {
    use std::collections::BTreeSet;

    use super::*;
    use crate::config::IoConfig;
    use crate::filter::FilterConfig;
    use crate::trim::TrimPlan;

    fn cfg() -> Config {
        Config {
            io: IoConfig {
                input: Some("reads.bam".into()),
                output: Some("out.fastq".into()),
                in_format: None,
                out_format: None,
            },
            filter: FilterConfig {
                min_length: 500,
                max_length: usize::MAX,
                min_qual: 10.0,
                max_qual: 1000.0,
                max_expected_errors: Some(1.5),
                min_gc: None,
                max_gc: None,
                qual_mode: crate::qual::QualMode::Mean,
            },
            trim: TrimPlan {
                head: 20,
                tail: 20,
                quality: Some(crate::trim::QualityOp::runs(9, 50)),
            },
            threads: 8,
            ..Config::default()
        }
    }

    fn stats() -> Stats {
        Stats {
            input_reads: 100,
            output_reads: 110,
            input_bases: 10_000,
            output_bases: 9_000,
            malformed_tag_reads: 2,
            malformed_mod_reads: 0,
            undo_tags_dropped_reads: 0,
            footprint_tags_dropped_reads: 0,
            barcode_tag_malformed_reads: 0,
            barcode_tag_unverified_reads: 0,
            reads_with_output: 92,
            reads_trimmed_to_nothing: 5,
            reads_all_filtered: 3,
            reads_tag_filtered: 0,
            segments_dropped_short: 7,
            segments_dropped_long: 0,
            segments_dropped_low_qual: 1,
            segments_dropped_high_qual: 0,
            segments_dropped_expected_errors: 4,
            segments_dropped_gc: 0,
        }
    }

    fn value(summary: &Summary) -> serde_json::Value {
        serde_json::from_str(&summary.to_json().unwrap()).unwrap()
    }

    /// The three read-level buckets partition `input_reads`, so `with_output` is
    /// derived rather than counted, and must not go negative on a partial run.
    #[test]
    fn read_buckets_partition_the_input() {
        let s = Summary::new(
            &cfg(),
            &stats(),
            "whittle -i reads.bam".into(),
            "out.fastq".into(),
            std::time::Duration::ZERO,
        );
        let v = value(&s);
        assert_eq!(v["reads"]["input"], 100);
        assert_eq!(v["reads"]["with_output"], 92);
        assert_eq!(v["reads"]["trimmed_to_nothing"], 5);
        assert_eq!(v["reads"]["all_filtered"], 3);
        // Output segments can exceed input reads under quality splitting.
        assert_eq!(v["reads"]["output"], 110);
    }

    #[test]
    fn params_record_the_resolved_run() {
        let s = Summary::new(
            &cfg(),
            &stats(),
            String::new(),
            String::new(),
            std::time::Duration::ZERO,
        );
        let v = value(&s);
        assert_eq!(v["schema_version"], 2);
        assert_eq!(v["tool"], "whittle");
        assert_eq!(v["params"]["threads"], 8);
        assert_eq!(v["params"]["min_length"], 500);
        assert_eq!(v["params"]["qual_mode"], "mean");
        assert_eq!(v["params"]["head_crop"], 20);
        assert_eq!(v["params"]["quality_trim"]["method"], "runs");
        assert_eq!(v["params"]["quality_trim"]["cutoff"], 9);
        assert_eq!(v["params"]["quality_trim"]["min_low_quality_run"], 50);
        assert_eq!(v["params"]["quality_trim"]["end_cutoff"], 9);
        assert_eq!(v["params"]["fastq_tags"], "all");
        assert_eq!(v["params"]["max_expected_errors"], 1.5);
        // An unset `--max-length` is null, not `usize::MAX` leaking into the file.
        assert!(v["params"]["max_length"].is_null());
        // Adapter trimming off is null, not a zeroed block.
        assert!(v["params"]["adapters"].is_null());
    }

    #[test]
    fn adapter_block_present_when_trimming_is_on() {
        let mut c = cfg();
        c.adapters = Some(crate::adapter::AdapterConfig {
            adapters: Vec::new(),
            error_rate: 0.2,
            end_size: 150,
            split: true,
            min_piece: 1,
            candidate_index: std::sync::OnceLock::new(),
            amplicon: false,
        });
        c.adapter_sample = 5_000;
        c.adapters_configured = Some(124);
        let s = Summary::new(
            &c,
            &stats(),
            String::new(),
            String::new(),
            std::time::Duration::ZERO,
        );
        let v = value(&s);
        // Both figures are reported: detection narrowed 124 down to 0 here.
        assert_eq!(v["params"]["adapters"]["configured"], 124);
        assert_eq!(v["params"]["adapters"]["count"], 0);
        assert_eq!(v["params"]["adapters"]["error_rate"], 0.2);
        assert_eq!(v["params"]["adapters"]["end_size"], 150);
        assert_eq!(v["params"]["adapters"]["split"], true);
        assert_eq!(v["params"]["adapters"]["sample"], 5_000);
        assert_eq!(v["params"]["adapters"]["infer"], "off");
        assert!(v["params"]["adapters"].get("infer_policy").is_none());
    }

    #[test]
    fn fastq_tag_list_renders_as_a_comma_list() {
        let mut c = cfg();
        c.fastq_tags = FastqTags::Only(BTreeSet::from([*b"MM", *b"ML", *b"RG"]));
        let s = Summary::new(
            &c,
            &stats(),
            String::new(),
            String::new(),
            std::time::Duration::ZERO,
        );
        assert_eq!(value(&s)["params"]["fastq_tags"], "ML,MM,RG");
    }

    #[test]
    fn elapsed_is_seconds() {
        let s = Summary::new(
            &cfg(),
            &stats(),
            String::new(),
            String::new(),
            std::time::Duration::from_millis(2500),
        );
        assert_eq!(value(&s)["elapsed_seconds"], 2.5);
    }

    /// A stdin or stdout run names its endpoints, so the summary file records
    /// where the reads came from and went.
    #[test]
    fn stdin_and_stdout_get_explicit_labels() {
        let mut c = cfg();
        c.io.input = None;
        let s = Summary::new(
            &c,
            &stats(),
            String::new(),
            "<stdout>".into(),
            std::time::Duration::ZERO,
        );
        let v = value(&s);
        assert_eq!(v["input"], "<stdin>");
        assert_eq!(v["output"], "<stdout>");
    }

    #[test]
    fn write_creates_a_parseable_file_ending_in_a_newline() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("summary.json");
        Summary::new(
            &cfg(),
            &stats(),
            String::new(),
            String::new(),
            std::time::Duration::ZERO,
        )
        .write(&path)
        .unwrap();
        let text = std::fs::read_to_string(&path).unwrap();
        assert!(text.ends_with("}\n"));
        let v: serde_json::Value = serde_json::from_str(&text).unwrap();
        assert_eq!(v["bases"]["input"], 10_000);
        assert_eq!(v["segments_dropped"]["too_short"], 7);
        assert_eq!(v["segments_dropped"]["expected_errors"], 4);
        assert_eq!(v["warnings"]["malformed_tag_reads"], 2);
    }
}