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
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
//! Damage tables: read bases (A, C, G, T) at reference C and G, by distance from each end of the
//! molecule. Reverse-strand reads are reverse-complemented first (molecule orientation), as in
//! PMDtools `--deamination` (docs/blackbox.md). Index 0 is the terminal base.
//!
//! Also the pattern counters for the mode check ([`PatternCounts`]), which do not depend on the
//! mode and are counted in every run.

use crate::sites::{Settings, Treatment};

/// Read-base order in every count array.
pub const BASES: [u8; 4] = *b"ACGT";

/// Counts per position for one molecule end: `[ref C, ref G][position][read base A, C, G, T]`.
pub type EndCounts = [Vec<[u64; 4]>; 2];

#[derive(Debug, Clone, PartialEq)]
pub struct DamageCounts {
    pub range: usize,
    pub five_prime: EndCounts,
    pub three_prime: EndCounts,
}

fn complement(b: u8) -> u8 {
    match b {
        b'A' => b'T',
        b'C' => b'G',
        b'G' => b'C',
        b'T' => b'A',
        _ => b'N',
    }
}

/// Index of `b` in [`BASES`].
fn base_index(b: u8) -> Option<usize> {
    match b {
        b'A' => Some(0),
        b'C' => Some(1),
        b'G' => Some(2),
        b'T' => Some(3),
        _ => None,
    }
}

impl DamageCounts {
    pub fn new(range: usize) -> Self {
        let end = || [vec![[0; 4]; range], vec![[0; 4]; range]];
        DamageCounts {
            range,
            five_prime: end(),
            three_prime: end(),
        }
    }

    /// Add one read (SAM orientation in; `refs` from the site module).
    /// Sites follow the treatment and base-quality settings used for scoring. CpG context is
    /// taken from the reference; with `pmdtools_compat` it is taken as PMDtools does for its
    /// table (C: next *read* base is G with full UDG, next reference base with UDG-half; G:
    /// previous reference base is C, wrapping at the start).
    pub fn add_read(
        &mut self,
        seq: &[u8],
        qual: &[u8],
        refs: &[Option<u8>],
        reverse: bool,
        s: &Settings,
    ) {
        let n = seq.len();
        // Molecule orientation without copying: molecule position j is SAM position at(j),
        // complemented for reverse-strand reads.
        let at = |j: usize| if reverse { n - 1 - j } else { j };
        let mref = |j: usize| {
            let r = refs[at(j)];
            if reverse { r.map(complement) } else { r }
        };
        let mbase = |j: usize| {
            let b = seq[at(j)].to_ascii_uppercase();
            if reverse { complement(b) } else { b }
        };
        // Only positions within `range` of either end are counted, so skip the middle of the read.
        let head = self.range.min(n);
        let tail = n.saturating_sub(self.range).max(head);
        for i in (0..head).chain(tail..n) {
            let (Some(r), Some(b)) = (mref(i), base_index(mbase(i))) else {
                continue;
            };
            if qual[at(i)] < s.min_baseq {
                continue;
            }
            let ref_index = match r {
                b'C' => 0,
                b'G' => 1,
                _ => continue,
            };
            let cpg = if ref_index == 0 {
                // PMDtools' --CpG table takes a C's context from the next read base; its
                // UDG-half table, like scoring, from the reference (docs/blackbox.md 1.6d).
                if s.pmdtools_compat && matches!(s.treatment, Treatment::Full) {
                    i + 1 < n && mbase(i + 1) == b'G'
                } else {
                    i + 1 < n && mref(i + 1) == Some(b'G')
                }
            } else if i > 0 {
                mref(i - 1) == Some(b'C')
            } else {
                s.pmdtools_compat && mref(n - 1) == Some(b'C')
            };
            let terminal = if ref_index == 0 { i == 0 } else { i == n - 1 };
            let keep = match s.treatment {
                Treatment::None => true,
                Treatment::Half => terminal || cpg,
                Treatment::Full => cpg,
            };
            if !keep {
                continue;
            }
            if i < self.range {
                self.five_prime[ref_index][i][b] += 1;
            }
            if n - 1 - i < self.range {
                self.three_prime[ref_index][n - 1 - i][b] += 1;
            }
        }
    }

    /// C→T rate at the 5′ terminal base, its binomial standard error, and the number of sites.
    pub fn first_position(&self) -> (Option<f64>, Option<f64>, u64) {
        let Some(c) = self.five_prime[0].first() else {
            return (None, None, 0);
        };
        let n: u64 = c.iter().sum();
        if n == 0 {
            return (None, None, 0);
        }
        let p = c[3] as f64 / n as f64;
        (Some(p), Some((p * (1.0 - p) / n as f64).sqrt()), n)
    }
}

impl DamageCounts {
    /// Add another set of counts (same range). Integer sums, so the order does not matter.
    pub fn merge(&mut self, other: &DamageCounts) {
        for (mine, theirs) in [
            (&mut self.five_prime, &other.five_prime),
            (&mut self.three_prime, &other.three_prime),
        ] {
            for (a, b) in mine.iter_mut().zip(theirs) {
                for (x, y) in a.iter_mut().zip(b) {
                    for (u, v) in x.iter_mut().zip(y) {
                        *u += v;
                    }
                }
            }
        }
    }
}

/// Sites and how many of them carry the substitution counted (C→T at C, G→A at G).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct SiteCount {
    pub sites: u64,
    pub changed: u64,
}

impl SiteCount {
    fn add(&mut self, changed: bool) {
        self.sites += 1;
        self.changed += u64::from(changed);
    }

    fn merge(&mut self, other: SiteCount) {
        self.sites += other.sites;
        self.changed += other.changed;
    }

    /// The share of sites changed; `None` without sites.
    pub fn rate(&self) -> Option<f64> {
        (self.sites > 0).then(|| self.changed as f64 / self.sites as f64)
    }
}

/// 5′ positions pooled for the background non-CpG C→T rate: bases 21 to 25.
pub const PATTERN_BACKGROUND: std::ops::RangeInclusive<usize> = 20..=24;
/// Reads must be longer than this, and a 5′ position is counted only if more than this many bases
/// follow it, so that 3′-end damage stays out of the 5′ counts in short reads.
const PATTERN_CLEARANCE: usize = 10;

/// The counts the mode check (src/mode_check.rs) compares with `--library` and `--treatment`.
/// Unlike [`DamageCounts`] they never depend on the mode: every site counts, CpG context comes from
/// the reference, and only `min_baseq` applies. Molecule orientation; position 0 is the terminal
/// base. Only the positions the check uses are counted, since this runs for every read.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct PatternCounts {
    /// 5′ C→T at reference C not followed by G (non-CpG) at positions 0 and 1, and pooled over
    /// [`PATTERN_BACKGROUND`]; each position only where position + 10 < read length.
    pub five_prime_first: SiteCount,
    pub five_prime_second: SiteCount,
    pub five_prime_background: SiteCount,
    /// 5′ C→T at the terminal base when it is a reference CpG C.
    pub five_prime_cpg: SiteCount,
    /// The 3′ terminal base: C→T at reference C, G→A at reference G.
    pub three_prime_c: SiteCount,
    pub three_prime_g: SiteCount,
    /// A reference CpG at the 3′ end (C second to last, G last): C→T at the C, G→A at the G.
    pub three_prime_cpg_c: SiteCount,
    pub three_prime_cpg_g: SiteCount,
}

impl PatternCounts {
    /// Add one scored read (SAM orientation in, as for [`DamageCounts::add_read`]).
    pub fn add_read(
        &mut self,
        seq: &[u8],
        qual: &[u8],
        refs: &[Option<u8>],
        reverse: bool,
        min_baseq: u8,
    ) {
        if seq.len() <= PATTERN_CLEARANCE {
            return;
        }
        // Counted for every read of every run, so the strand is resolved at compile time.
        if reverse {
            self.add::<true>(seq, qual, refs, min_baseq);
        } else {
            self.add::<false>(seq, qual, refs, min_baseq);
        }
    }

    fn add<const REVERSE: bool>(
        &mut self,
        seq: &[u8],
        qual: &[u8],
        refs: &[Option<u8>],
        min_baseq: u8,
    ) {
        let n = seq.len();
        // Molecule position j is SAM position at(j), where molecule bases A, C, G, T are SAM
        // bases `a`, `c`, `g`, `t` (complemented on the reverse strand), so nothing is copied.
        let at = |j: usize| if REVERSE { n - 1 - j } else { j };
        let [a, c, g, t] = if REVERSE { *b"TGCA" } else { *b"ACGT" };
        // The reference base at molecule position j (as a SAM base; 0 if unknown), and the read
        // base, uppercased, if it counts.
        let reference = |j: usize| refs[at(j)].unwrap_or(0);
        let read = |j: usize| {
            let k = at(j);
            let b = seq[k].to_ascii_uppercase();
            (qual[k] >= min_baseq && matches!(b, b'A' | b'C' | b'G' | b'T')).then_some(b)
        };
        let non_cpg = |count: &mut SiteCount, i: usize| {
            if i + PATTERN_CLEARANCE < n
                && reference(i) == c
                && reference(i + 1) != g
                && let Some(b) = read(i)
            {
                count.add(b == t);
            }
        };
        non_cpg(&mut self.five_prime_first, 0);
        non_cpg(&mut self.five_prime_second, 1);
        for i in PATTERN_BACKGROUND {
            non_cpg(&mut self.five_prime_background, i);
        }
        if reference(0) == c
            && reference(1) == g
            && let Some(b) = read(0)
        {
            self.five_prime_cpg.add(b == t);
        }
        let last = n - 1;
        let (r1, r0) = (reference(last - 1), reference(last));
        let (b1, b0) = (read(last - 1), read(last));
        if let Some(b) = b0 {
            if r0 == c {
                self.three_prime_c.add(b == t);
            } else if r0 == g {
                self.three_prime_g.add(b == a);
            }
        }
        if r1 == c && r0 == g {
            if let Some(b) = b1 {
                self.three_prime_cpg_c.add(b == t);
            }
            if let Some(b) = b0 {
                self.three_prime_cpg_g.add(b == a);
            }
        }
    }

    /// Add another set of counts. Integer sums, so the order does not matter.
    pub fn merge(&mut self, other: &PatternCounts) {
        for (a, b) in [
            (&mut self.five_prime_first, other.five_prime_first),
            (&mut self.five_prime_second, other.five_prime_second),
            (&mut self.five_prime_background, other.five_prime_background),
            (&mut self.five_prime_cpg, other.five_prime_cpg),
            (&mut self.three_prime_c, other.three_prime_c),
            (&mut self.three_prime_g, other.three_prime_g),
            (&mut self.three_prime_cpg_c, other.three_prime_cpg_c),
            (&mut self.three_prime_cpg_g, other.three_prime_cpg_g),
        ] {
            a.merge(b);
        }
    }
}

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

    /// Counting only the ends gives the same table as counting every position: a position's
    /// counts do not depend on `range`, so a range longer than every read (nothing skipped) must
    /// agree with a short one on the short one's positions. Reads shorter than, equal to and
    /// longer than twice the range; both strands; every treatment; with and without compat.
    #[test]
    fn counting_only_the_ends_matches_counting_every_position() {
        let mut x: u64 = 0x9E3779B97F4A7C15;
        let mut rand = |n: u64| {
            x ^= x << 13;
            x ^= x >> 7;
            x ^= x << 17;
            x % n
        };
        let range = 10;
        for treatment in [Treatment::None, Treatment::Half, Treatment::Full] {
            for pmdtools_compat in [false, true] {
                let s = Settings {
                    library: Library::DoubleStranded,
                    treatment,
                    params: Params::default(),
                    min_baseq: 20,
                    pmdtools_compat,
                };
                let (mut short, mut full) = (DamageCounts::new(range), DamageCounts::new(1000));
                for n in [1, 5, 9, 10, 11, 19, 20, 21, 35, 150] {
                    for reverse in [false, true] {
                        let refs: Vec<Option<u8>> = (0..n)
                            .map(|_| (rand(8) != 0).then(|| b"ACGT"[rand(4) as usize]))
                            .collect();
                        let seq: Vec<u8> = refs
                            .iter()
                            .map(|r| match (r, rand(4)) {
                                (Some(b'C'), 0) => b'T',
                                (Some(b'G'), 0) => b'A',
                                (Some(b), _) => *b,
                                (None, _) => b"ACGTN"[rand(5) as usize],
                            })
                            .collect();
                        let qual: Vec<u8> = (0..n).map(|_| rand(41) as u8).collect();
                        short.add_read(&seq, &qual, &refs, reverse, &s);
                        full.add_read(&seq, &qual, &refs, reverse, &s);
                    }
                }
                for (a, b) in [
                    (&short.five_prime, &full.five_prime),
                    (&short.three_prime, &full.three_prime),
                ] {
                    for k in 0..2 {
                        assert_eq!(
                            a[k][..],
                            b[k][..range],
                            "{treatment:?} compat={pmdtools_compat}"
                        );
                    }
                }
                assert!(short.five_prime[0].iter().flatten().sum::<u64>() > 0);
            }
        }
    }

    /// Pattern counts written out directly: reverse-complement the read first, then count.
    fn pattern_naive(
        seq: &[u8],
        qual: &[u8],
        refs: &[Option<u8>],
        reverse: bool,
        min_baseq: u8,
    ) -> PatternCounts {
        let n = seq.len();
        let mut c = PatternCounts::default();
        if n <= 10 {
            return c;
        }
        let mut s: Vec<u8> = seq.iter().map(u8::to_ascii_uppercase).collect();
        let (mut q, mut r) = (qual.to_vec(), refs.to_vec());
        if reverse {
            s = s.iter().rev().map(|&b| complement(b)).collect();
            q.reverse();
            r = r.iter().rev().map(|x| x.map(complement)).collect();
        }
        let ok = |j: usize| q[j] >= min_baseq && b"ACGT".contains(&s[j]);
        for i in 0..25 {
            if i + 10 < n && r[i] == Some(b'C') && ok(i) {
                let t = s[i] == b'T';
                if r[i + 1] != Some(b'G') {
                    match i {
                        0 => c.five_prime_first.add(t),
                        1 => c.five_prime_second.add(t),
                        20..=24 => c.five_prime_background.add(t),
                        _ => {}
                    }
                } else if i == 0 {
                    c.five_prime_cpg.add(t);
                }
            }
        }
        let l = n - 1;
        if ok(l) && r[l] == Some(b'C') {
            c.three_prime_c.add(s[l] == b'T');
        }
        if ok(l) && r[l] == Some(b'G') {
            c.three_prime_g.add(s[l] == b'A');
        }
        if r[l - 1] == Some(b'C') && r[l] == Some(b'G') {
            if ok(l - 1) {
                c.three_prime_cpg_c.add(s[l - 1] == b'T');
            }
            if ok(l) {
                c.three_prime_cpg_g.add(s[l] == b'A');
            }
        }
        c
    }

    /// The pattern counters are the same in every mode (both libraries, all treatments, with and
    /// without compat), equal a direct count, and add up by `merge` in any split. Random reads of
    /// many lengths (short ones included), on both strands, with damage at both ends, N and
    /// lowercase bases, and low base qualities.
    #[test]
    fn pattern_counts_do_not_depend_on_the_mode() {
        let mut x: u64 = 0x2545F4914F6CDD1D;
        let mut rand = |n: u64| {
            x ^= x << 13;
            x ^= x >> 7;
            x ^= x << 17;
            x % n
        };
        let mut reads = Vec::new();
        for _ in 0..40 {
            for n in [1, 2, 5, 10, 11, 12, 20, 34, 35, 36, 60, 150] {
                for reverse in [false, true] {
                    // CpG-rich reference, so every counter is reached.
                    let refs: Vec<Option<u8>> = (0..n)
                        .map(|_| (rand(10) != 0).then(|| b"ACGTCG"[rand(6) as usize]))
                        .collect();
                    let seq: Vec<u8> = refs
                        .iter()
                        .map(|r| match (r, rand(4)) {
                            (Some(b'C'), 0) => b'T',
                            (Some(b'G'), 0) => b'A',
                            (Some(b), 1) => b.to_ascii_lowercase(),
                            (Some(b), _) => *b,
                            (None, _) => b"ACGTN"[rand(5) as usize],
                        })
                        .collect();
                    let qual: Vec<u8> = (0..n).map(|_| rand(41) as u8).collect();
                    reads.push((seq, qual, refs, reverse));
                }
            }
        }
        let mut expected = PatternCounts::default();
        for (seq, qual, refs, reverse) in &reads {
            expected.merge(&pattern_naive(seq, qual, refs, *reverse, 20));
        }
        assert!(expected.five_prime_background.sites > 0 && expected.five_prime_cpg.changed > 0);
        assert!(expected.three_prime_cpg_c.changed > 0 && expected.three_prime_cpg_g.changed > 0);
        for library in [Library::DoubleStranded, Library::SingleStranded] {
            for treatment in [Treatment::None, Treatment::Half, Treatment::Full] {
                for pmdtools_compat in [false, true] {
                    let s = Settings {
                        library,
                        treatment,
                        params: Params::default(),
                        min_baseq: 20,
                        pmdtools_compat,
                    };
                    let (mut one, mut halves) =
                        (PatternCounts::default(), [PatternCounts::default(); 2]);
                    for (k, (seq, qual, refs, reverse)) in reads.iter().enumerate() {
                        one.add_read(seq, qual, refs, *reverse, s.min_baseq);
                        halves[k % 2].add_read(seq, qual, refs, *reverse, s.min_baseq);
                    }
                    let [mut merged, other] = halves;
                    merged.merge(&other);
                    let mode = format!("{library:?} {treatment:?} compat={pmdtools_compat}");
                    assert_eq!(one, expected, "{mode}");
                    assert_eq!(merged, expected, "{mode}");
                }
            }
        }
    }

    fn site_count(sites: u64, changed: u64) -> SiteCount {
        SiteCount { sites, changed }
    }

    #[test]
    fn pattern_counts_use_molecule_orientation_and_skip_short_reads() {
        let refs = |s: &str| s.bytes().map(Some).collect::<Vec<_>>();
        let mut c = PatternCounts::default();
        // Forward, 12 bases: 5′ non-CpG C→T at 0; CpG C at 1 (not counted, only i = 0 is);
        // the 3′ end is a reference CpG, read TA: C→T at j = 1 and G→A at j = 0.
        c.add_read(b"TCGAAAAAAATA", &[40; 12], &refs("CCGAAAAAAACG"), false, 0);
        // Reverse: in molecule orientation the reference is CGTTTTTTTTTG (CpG C at 5′ i = 0, read
        // T) and the read ends in A at reference G (3′ G→A at j = 0).
        c.add_read(b"TAAAAAAAAACA", &[40; 12], &refs("CAAAAAAAAACG"), true, 0);
        // Ten bases: too short for any counter.
        c.add_read(b"TAAAAAAAAA", &[40; 10], &refs("CAAAAAAAAA"), false, 0);
        assert_eq!(c.five_prime_first, site_count(1, 1));
        assert_eq!(c.five_prime_second, SiteCount::default());
        assert_eq!(c.five_prime_cpg, site_count(1, 1));
        assert_eq!(c.three_prime_c, SiteCount::default());
        assert_eq!(c.three_prime_g, site_count(2, 2));
        assert_eq!(c.three_prime_cpg_c, site_count(1, 1));
        assert_eq!(c.three_prime_cpg_g, site_count(1, 1));
        assert_eq!(c.five_prime_first.rate(), Some(1.0));
        assert_eq!(c.five_prime_second.rate(), None);
    }
}