pmdshodh 0.4.1

Per-read post-mortem damage (PMD) scoring and filtering of ancient DNA alignments, compatible with PMDtools
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
//! Run summary written as JSON for MultiQC (docs/design.md section 6). `FORMAT_VERSION` 5 is frozen
//! (#102; README, "Compatibility of the JSON run summary"): a new field keeps it and is added to the
//! field list in `tests/cli.rs`; removing, renaming or retyping a field, or a new value for a field
//! with a fixed set of names, needs a new version. No timestamps: identical runs give identical files.

use std::collections::BTreeMap;

use noodles::sam::alignment::record::Flags;
use serde_json::{Value, json};

use crate::damage::{BASES, DamageCounts, EndCounts, PatternCounts};
use crate::mode_check::ModeCheck;
use crate::model::NULL_BACKGROUND;
use crate::reads::{MdCheck, ReadFilters, SkipReason};
use crate::sites::{Library, ReadScore, Settings, Treatment};

pub const FORMAT_VERSION: u32 = 5;
const HIST_MIN: f64 = -20.0;
const HIST_MAX: f64 = 40.0;
const HIST_BIN: f64 = 0.5;
/// Thresholds at which the summary counts the scored reads that `filter -t T` alone would keep
/// (`pmds >= T`, as in `filter`), to help choose a threshold (#97).
pub const KEPT_THRESHOLDS: [f64; 4] = [1.0, 2.0, 3.0, 5.0];

/// Facts about the run that are not counts.
pub struct RunInfo<'a> {
    pub subcommand: &'a str,
    pub command: String,
    pub input: String,
    /// "sam", "bam" or "cram", detected from the contents.
    pub input_format: &'a str,
    pub settings: Settings,
    pub filters: ReadFilters,
    pub threshold: Option<f64>,
    pub upper_threshold: Option<f64>,
    /// The `-r` FASTA, if given.
    pub reference: Option<String>,
}

pub struct Summary {
    input: u64,
    scored: u64,
    kept: u64,
    removed_by_threshold: u64,
    no_informative_sites: u64,
    /// Scored reads with `pmds >= T`, for each T in `KEPT_THRESHOLDS`. Counted exactly: a
    /// histogram bin can hold scores just below a threshold.
    kept_at_threshold: [u64; KEPT_THRESHOLDS.len()],
    skipped: [u64; SkipReason::ALL.len()],
    flags: BTreeMap<&'static str, u64>,
    histogram: Vec<u64>,
    underflow: u64,
    overflow: u64,
    length_scored: BTreeMap<usize, u64>,
    length_kept: BTreeMap<usize, u64>,
    /// With `-r`: scored reads whose MD tag agrees with the reference, disagrees, or is absent.
    md_agree: u64,
    md_disagree: u64,
    md_absent: u64,
    pub damage: DamageCounts,
    /// Counted in every run, for `mode_check`.
    pub pattern: PatternCounts,
}

impl Summary {
    /// Count how a scored read's MD tag compared with the `-r` reference.
    pub fn add_md_check(&mut self, md: MdCheck) {
        match md {
            MdCheck::NotChecked => {}
            MdCheck::Absent => self.md_absent += 1,
            MdCheck::Agrees => self.md_agree += 1,
            MdCheck::Disagrees => self.md_disagree += 1,
        }
    }

    /// Scored reads whose MD tag disagreed with the `-r` reference.
    pub fn md_disagreeing(&self) -> u64 {
        self.md_disagree
    }

    pub fn new(range: usize) -> Self {
        let bins = ((HIST_MAX - HIST_MIN) / HIST_BIN).round() as usize;
        Summary {
            input: 0,
            scored: 0,
            kept: 0,
            removed_by_threshold: 0,
            no_informative_sites: 0,
            kept_at_threshold: [0; KEPT_THRESHOLDS.len()],
            skipped: [0; SkipReason::ALL.len()],
            flags: [
                "secondary",
                "supplementary",
                "duplicate",
                "qc_fail",
                "paired",
                "reverse",
            ]
            .into_iter()
            .map(|k| (k, 0))
            .collect(),
            histogram: vec![0; bins],
            underflow: 0,
            overflow: 0,
            length_scored: BTreeMap::new(),
            md_agree: 0,
            md_disagree: 0,
            md_absent: 0,
            length_kept: BTreeMap::new(),
            damage: DamageCounts::new(range),
            pattern: PatternCounts::default(),
        }
    }

    /// Count an input record by its flags (before any filtering).
    pub fn add_input(&mut self, flags: Flags) {
        self.input += 1;
        for (key, set) in [
            ("secondary", flags.is_secondary()),
            ("supplementary", flags.is_supplementary()),
            ("duplicate", flags.is_duplicate()),
            ("qc_fail", flags.is_qc_fail()),
            ("paired", flags.is_segmented()),
            ("reverse", flags.is_reverse_complemented()),
        ] {
            if set {
                *self.flags.get_mut(key).unwrap() += 1;
            }
        }
    }

    pub fn add_skipped(&mut self, reason: SkipReason) {
        self.skipped[reason as usize] += 1;
    }

    /// Count a scored read. `kept` is `None` when there is no filtering (score, damage).
    pub fn add_scored(&mut self, score: &ReadScore, length: usize, kept: Option<bool>) {
        self.scored += 1;
        if score.n_sites == 0 {
            self.no_informative_sites += 1;
        }
        // The comparison `filter -t` makes; NaN never counts.
        for (n, t) in self.kept_at_threshold.iter_mut().zip(KEPT_THRESHOLDS) {
            if score.pmds >= t {
                *n += 1;
            }
        }
        if score.pmds < HIST_MIN {
            self.underflow += 1;
        } else if score.pmds >= HIST_MAX {
            self.overflow += 1;
        } else {
            let last = self.histogram.len() - 1;
            let i = ((score.pmds - HIST_MIN) / HIST_BIN).floor() as usize;
            self.histogram[i.min(last)] += 1;
        }
        *self.length_scored.entry(length).or_default() += 1;
        match kept {
            Some(true) => {
                self.kept += 1;
                *self.length_kept.entry(length).or_default() += 1;
            }
            Some(false) => self.removed_by_threshold += 1,
            None => {}
        }
    }

    pub fn skipped(&self) -> &[u64] {
        &self.skipped
    }

    /// (T, scored reads with `pmds >= T`) for each T in `KEPT_THRESHOLDS`.
    pub fn kept_at_threshold(&self) -> Vec<(f64, u64)> {
        KEPT_THRESHOLDS
            .into_iter()
            .zip(self.kept_at_threshold)
            .collect()
    }

    pub fn to_json(&self, info: &RunInfo) -> Value {
        let s = &info.settings;
        let filtering = info.subcommand == "filter";
        let end = |counts: &EndCounts| {
            json!({
                "C": base_columns(&counts[0]),
                "G": base_columns(&counts[1]),
            })
        };
        let (rate, se, n) = self.damage.first_position();
        let lengths = |m: &BTreeMap<usize, u64>| -> Value {
            m.iter().map(|(k, v)| (k.to_string(), json!(v))).collect()
        };
        json!({
            "format_version": FORMAT_VERSION,
            "tool": {"name": "pmdshodh", "version": env!("CARGO_PKG_VERSION")},
            "subcommand": info.subcommand,
            "command": info.command,
            "input": info.input,
            "input_format": info.input_format,
            "reference": {
                "path": info.reference,
                "bases_from": if info.reference.is_some() { "reference" } else { "md" },
                "md_tags": info.reference.as_ref().map(|_| json!({
                    "agree": self.md_agree,
                    "disagree": self.md_disagree,
                    "absent": self.md_absent,
                })),
            },
            "mode": {
                "library": match s.library { Library::DoubleStranded => "ds", Library::SingleStranded => "ss" },
                "treatment": match s.treatment { Treatment::None => "none", Treatment::Half => "half", Treatment::Full => "full" },
                "pmdtools_compat": s.pmdtools_compat,
            },
            "model": {
                "pmd_p": s.params.p,
                "pmd_c": s.params.c,
                "pi_ancient": s.params.pi_ancient,
                "pi_contamination": s.params.pi_contamination,
                "null_background": NULL_BACKGROUND,
            },
            "filters": {
                "threshold": info.threshold,
                "upper_threshold": info.upper_threshold,
                "min_mapq": info.filters.min_mapq,
                "min_baseq": s.min_baseq,
                "no_clips": info.filters.no_clips,
                "no_indels": info.filters.no_indels,
                "skip_flags": info.filters.skip_flag_names(),
            },
            "reads": {
                "input": self.input,
                "scored": self.scored,
                "kept": if filtering { json!(self.kept) } else { Value::Null },
                "removed_by_threshold": if filtering { json!(self.removed_by_threshold) } else { Value::Null },
                "no_informative_sites": self.no_informative_sites,
                "kept_at_threshold": self.kept_at_threshold().iter().map(|(t, n)| (t.to_string(), json!(n))).collect::<serde_json::Map<_, _>>(),
                "skipped": SkipReason::ALL.iter().map(|r| (r.name().to_string(), json!(self.skipped[*r as usize]))).collect::<serde_json::Map<_, _>>(),
                "flags": self.flags,
            },
            "score_histogram": {
                "bin_width": HIST_BIN,
                "min": HIST_MIN,
                "max": HIST_MAX,
                "underflow": self.underflow,
                "overflow": self.overflow,
                "counts": self.histogram,
            },
            "length_histogram": {
                "scored": lengths(&self.length_scored),
                "kept": if filtering { lengths(&self.length_kept) } else { Value::Null },
            },
            "damage": {
                "range": self.damage.range,
                "orientation": "molecule",
                "reads_used": "scored",
                "five_prime": end(&self.damage.five_prime),
                "three_prime": end(&self.damage.three_prime),
                "first_position": {"c_to_t": rate, "se": se, "n": n},
            },
            "mode_check": ModeCheck::new(&self.pattern, s.library, s.treatment).to_json(),
        })
    }
}

/// `{ "A": [...], "C": [...], "G": [...], "T": [...] }`, position 0 = terminal base.
fn base_columns(rows: &[[u64; 4]]) -> Value {
    BASES
        .iter()
        .enumerate()
        .map(|(j, b)| {
            (
                (*b as char).to_string(),
                json!(rows.iter().map(|r| r[j]).collect::<Vec<_>>()),
            )
        })
        .collect::<serde_json::Map<_, _>>()
        .into()
}

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

    fn settings() -> Settings {
        Settings {
            library: Library::DoubleStranded,
            treatment: Treatment::None,
            params: Params::default(),
            min_baseq: 0,
            pmdtools_compat: false,
        }
    }

    #[test]
    fn histogram_bins_and_overflow() {
        let mut s = Summary::new(5);
        for pmds in [-25.0, -20.0, -0.25, 0.0, 0.49, 39.99, 40.0] {
            s.add_scored(&ReadScore { pmds, n_sites: 1 }, 30, None);
        }
        assert_eq!((s.underflow, s.overflow), (1, 1));
        assert_eq!(s.histogram[0], 1); // -20.0
        assert_eq!(s.histogram[39], 1); // -0.25 in [-0.5, 0)
        assert_eq!(s.histogram[40], 2); // 0.0 and 0.49 in [0, 0.5)
        assert_eq!(s.histogram[119], 1); // 39.99
    }

    /// Kept-at-threshold counts for one score, in `KEPT_THRESHOLDS` order, and its histogram bin.
    fn kept_at(pmds: f64) -> ([u64; 4], Option<usize>) {
        let mut s = Summary::new(5);
        s.add_scored(&ReadScore { pmds, n_sites: 1 }, 30, None);
        let counts = s
            .kept_at_threshold()
            .iter()
            .map(|(_, n)| *n)
            .collect::<Vec<_>>();
        (
            counts.try_into().unwrap(),
            s.histogram.iter().position(|&n| n > 0),
        )
    }

    #[test]
    fn kept_at_threshold_counts_exactly_what_filter_keeps() {
        assert_eq!(kept_at(3.0).0, [1, 1, 1, 0]);
        assert_eq!(kept_at(1.0).0, [1, 0, 0, 0]);
        assert_eq!(kept_at(5.0).0, [1, 1, 1, 1]);
        // Just below 3: not kept by `-t 3`, although the histogram puts it in the bin [3, 3.5).
        for below in [3.0 - f64::EPSILON * 4.0, 3.0f64.next_down()] {
            assert!(below < 3.0);
            assert_eq!(kept_at(below), ([1, 1, 0, 0], Some(46)), "{below:e}");
        }
        assert_eq!(kept_at(3.0).1, Some(46));
        // NaN fails `>=`, as in `filter`; no informative sites (score 0) and negative scores
        // count nowhere; huge scores everywhere.
        for (pmds, want) in [
            (f64::NAN, [0, 0, 0, 0]),
            (0.0, [0, 0, 0, 0]),
            (-0.0, [0, 0, 0, 0]),
            (0.999_999, [0, 0, 0, 0]),
            (-1e300, [0, 0, 0, 0]),
            (f64::NEG_INFINITY, [0, 0, 0, 0]),
            (1e300, [1, 1, 1, 1]),
            (f64::INFINITY, [1, 1, 1, 1]),
        ] {
            assert_eq!(kept_at(pmds).0, want, "{pmds}");
        }
    }

    #[test]
    fn kept_at_threshold_is_in_every_summary_keyed_by_threshold() {
        let mut s = Summary::new(5);
        for pmds in [-2.0, 0.0, 1.5, 2.0, 2.5, 3.0, 4.9, 7.0] {
            s.add_scored(&ReadScore { pmds, n_sites: 1 }, 30, None);
        }
        for subcommand in ["score", "filter", "damage"] {
            let info = RunInfo {
                subcommand,
                command: String::new(),
                input: String::new(),
                input_format: "sam",
                settings: settings(),
                filters: ReadFilters::default(),
                threshold: None,
                upper_threshold: None,
                reference: None,
            };
            assert_eq!(
                s.to_json(&info)["reads"]["kept_at_threshold"],
                json!({"1": 6, "2": 5, "3": 3, "5": 1}),
                "{subcommand}"
            );
        }
    }

    #[test]
    fn skip_flags_are_listed_in_canonical_order_and_counted_last() {
        let info = |skip_flags| RunInfo {
            subcommand: "damage",
            command: String::new(),
            input: String::new(),
            input_format: "sam",
            settings: settings(),
            filters: ReadFilters {
                skip_flags,
                ..ReadFilters::default()
            },
            threshold: None,
            upper_threshold: None,
            reference: None,
        };
        let mut s = Summary::new(5);
        s.add_skipped(SkipReason::Flags);
        let j = s.to_json(&info(0));
        assert_eq!(j["format_version"], 5);
        assert_eq!(j["filters"]["skip_flags"], json!([]));
        assert_eq!(j["reads"]["skipped"]["skip_flags"], 1);
        // qcfail, duplicate and secondary bits, set in no particular order.
        let j = s.to_json(&info(0x200 | 0x400 | 0x100));
        assert_eq!(
            j["filters"]["skip_flags"],
            json!(["secondary", "duplicate", "qcfail"])
        );
        assert_eq!(SkipReason::ALL.last(), Some(&SkipReason::Flags));
    }

    #[test]
    fn damage_counts_use_molecule_orientation() {
        let mut d = DamageCounts::new(3);
        let refs = |s: &str| s.bytes().map(Some).collect::<Vec<_>>();
        // Forward: 5′ C→T at position 0. Reverse: SAM 3′ G→A is the molecule's 5′ C→T.
        d.add_read(b"TAAA", &[40; 4], &refs("CAAA"), false, &settings());
        d.add_read(b"AAAA", &[40; 4], &refs("AAAG"), true, &settings());
        assert_eq!(d.five_prime[0][0], [0, 0, 0, 2]); // two ref C at 5′ terminal, both read T
        let (rate, se, n) = d.first_position();
        assert_eq!((rate, se, n), (Some(1.0), Some(0.0), 2));
    }
}