pmdshodh 0.4.0

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
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
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
//! Turn one alignment into informative sites and sum their score terms.
//!
//! Behaviour follows PMDtools 0.60 as measured in docs/blackbox.md (sections 1.2, 1.4, 1.5, 1.6b),
//! except for the departures listed in docs/design.md section 5.

use crate::model::{Params, site_term_ds, site_term_s1, site_term_ss};

/// Library preparation, which decides which mismatches count as damage.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Library {
    /// C→T from the 5′ end and G→A from the 3′ end (PMDtools default).
    DoubleStranded,
    /// C→T in molecule orientation, measured from both ends (PMDtools `--ss`).
    SingleStranded,
}

/// UDG treatment, which decides which C/G sites keep damage.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Treatment {
    /// All sites (PMDtools default, `--UDGminus`).
    None,
    /// CpG sites plus the terminal base (PMDtools `--UDGhalf`).
    Half,
    /// CpG sites only (PMDtools `--CpG` / `--UDGplus`).
    Full,
}

/// Scoring settings for one run.
#[derive(Debug, Clone, Copy)]
pub struct Settings {
    pub library: Library,
    pub treatment: Treatment,
    pub params: Params,
    /// Bases with a lower phred quality are ignored (PMDtools `-q`).
    pub min_baseq: u8,
    /// Rebuild the reference the way PMDtools 0.60 does, including its bug with combined CIGAR
    /// operations (`--pmdtools-compat`; docs/blackbox.md 1.6c). Off by default.
    pub pmdtools_compat: bool,
}

/// One CIGAR operation with its length.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CigarOp {
    /// `M`.
    Match(usize),
    /// `=`.
    SequenceMatch(usize),
    /// `X`.
    SequenceMismatch(usize),
    Insertion(usize),
    Deletion(usize),
    SoftClip(usize),
    HardClip(usize),
    /// `N` or `P`: not supported, as in PMDtools.
    Unsupported,
}

/// Score of one read.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ReadScore {
    pub pmds: f64,
    /// Number of informative sites that contributed (0 gives PMDS 0, as in PMDtools).
    pub n_sites: u32,
}

/// Reference base at each SEQ position, rebuilt from the CIGAR and the MD tag.
/// Inserted and soft-clipped positions have no reference base (`None`).
///
/// MD deletions take exactly as many letters as the CIGAR deletion has, so MD strings without the
/// `0` separator after a deletion (written by MALT; PMDtools issue #5) are read correctly.
/// Any other disagreement between CIGAR, SEQ and MD is an error.
pub fn reference_along_read(
    seq: &[u8],
    cigar: &[CigarOp],
    md: &[u8],
) -> Result<Vec<Option<u8>>, String> {
    check_read_length(seq, cigar)?;
    let mut md = MdCursor { md, pos: 0, run: 0 };
    let mut refs = Vec::with_capacity(seq.len());
    for op in cigar {
        match *op {
            CigarOp::Match(n) | CigarOp::SequenceMatch(n) | CigarOp::SequenceMismatch(n) => {
                for _ in 0..n {
                    let read_base = seq[refs.len()].to_ascii_uppercase();
                    refs.push(Some(
                        md.next_aligned().map_err(md_hint)?.unwrap_or(read_base),
                    ));
                }
            }
            CigarOp::Insertion(n) | CigarOp::SoftClip(n) => refs.extend((0..n).map(|_| None)),
            CigarOp::Deletion(n) => md.deletion(n).map_err(md_hint)?,
            CigarOp::HardClip(_) => {}
            CigarOp::Unsupported => return Err("unsupported CIGAR operation (N or P)".into()),
        }
    }
    md.finish().map_err(md_hint)?;
    Ok(refs)
}

/// Reference bases the CIGAR consumes (`M`, `=`, `X`, `D`): the length of the window `-r` fetches.
/// Saturates rather than wrapping, so an absurd CIGAR asks for an out-of-bounds window.
pub fn reference_span(cigar: &[CigarOp]) -> usize {
    cigar
        .iter()
        .map(|op| match op {
            CigarOp::Match(n)
            | CigarOp::SequenceMatch(n)
            | CigarOp::SequenceMismatch(n)
            | CigarOp::Deletion(n) => *n,
            _ => 0,
        })
        .fold(0, usize::saturating_add)
}

/// The CIGAR must cover exactly SEQ's bases (`M`, `=`, `X`, `I`, `S`). Checked before any per-base
/// vector is built, with a saturating sum, so absurd lengths can neither allocate nor wrap round
/// to SEQ's length (audit finding B3).
fn check_read_length(seq: &[u8], cigar: &[CigarOp]) -> Result<(), String> {
    let read_len = cigar
        .iter()
        .map(|op| match op {
            CigarOp::Match(n)
            | CigarOp::SequenceMatch(n)
            | CigarOp::SequenceMismatch(n)
            | CigarOp::Insertion(n)
            | CigarOp::SoftClip(n) => *n,
            _ => 0,
        })
        .fold(0, usize::saturating_add);
    if read_len != seq.len() {
        return Err(format!(
            "CIGAR covers {read_len} read bases but SEQ has {}",
            seq.len()
        ));
    }
    Ok(())
}

/// [`reference_along_read`] from the reference itself (`-r`): `window` holds the reference bases
/// from the alignment start, [`reference_span`] long. Bases are uppercased, as the default
/// reconstruction does for MD.
pub fn reference_along_read_from_fasta(
    seq: &[u8],
    cigar: &[CigarOp],
    window: &[u8],
) -> Result<Vec<Option<u8>>, String> {
    check_read_length(seq, cigar)?;
    let mut refs = Vec::with_capacity(seq.len());
    let mut r = 0;
    for op in cigar {
        match *op {
            CigarOp::Match(n) | CigarOp::SequenceMatch(n) | CigarOp::SequenceMismatch(n) => {
                refs.extend(
                    window[r..r + n]
                        .iter()
                        .map(|b| Some(b.to_ascii_uppercase())),
                );
                r += n;
            }
            CigarOp::Insertion(n) | CigarOp::SoftClip(n) => refs.extend((0..n).map(|_| None)),
            CigarOp::Deletion(n) => r += n,
            CigarOp::HardClip(_) => {}
            CigarOp::Unsupported => return Err("unsupported CIGAR operation (N or P)".into()),
        }
    }
    Ok(refs)
}

/// The MD tag `samtools calmd` would write for this read: matching runs as numbers, mismatched
/// and deleted reference bases uppercased (calmd writes soft-masked bases in uppercase too, so
/// PMDtools counts them as C or G when it reads its output), a `0` between adjacent
/// letters and after a deletion that a mismatch follows. Read and reference bases match when
/// equal ignoring case, or when the read has `=`; as in calmd, `N` never matches, not even `N`.
pub fn md_from_reference(seq: &[u8], cigar: &[CigarOp], window: &[u8]) -> Vec<u8> {
    let mut md = Vec::new();
    let mut run = 0usize;
    let (mut s, mut r) = (0, 0);
    let flush = |md: &mut Vec<u8>, run: &mut usize| {
        md.extend_from_slice(run.to_string().as_bytes());
        *run = 0;
    };
    for op in cigar {
        match *op {
            CigarOp::Match(n) | CigarOp::SequenceMatch(n) | CigarOp::SequenceMismatch(n) => {
                for _ in 0..n {
                    let (read, refb) = (seq[s], window[r]);
                    let n = |b: u8| b.eq_ignore_ascii_case(&b'N');
                    if read == b'=' || (read.eq_ignore_ascii_case(&refb) && !n(read)) {
                        run += 1;
                    } else {
                        flush(&mut md, &mut run);
                        md.push(refb.to_ascii_uppercase());
                    }
                    s += 1;
                    r += 1;
                }
            }
            CigarOp::Insertion(n) | CigarOp::SoftClip(n) => s += n,
            CigarOp::Deletion(n) => {
                flush(&mut md, &mut run);
                md.push(b'^');
                md.extend(window[r..r + n].iter().map(u8::to_ascii_uppercase));
                r += n;
            }
            CigarOp::HardClip(_) | CigarOp::Unsupported => {}
        }
    }
    flush(&mut md, &mut run);
    md
}

/// MD tags that disagree with the alignment are usually stale (the read was realigned after MD
/// was written), so say how to fix them.
fn md_hint(e: String) -> String {
    format!("{e} (MD does not match the alignment; recompute it with samtools calmd)")
}

/// Reference base at each SEQ position as PMDtools 0.60 rebuilds it, bug included
/// (docs/blackbox.md 1.6c). Only for `--pmdtools-compat`; call [`reference_along_read`] first so
/// that invalid records are still rejected.
///
/// - No `I` and no `S` in the CIGAR: the MD reference without deleted bases is laid along SEQ.
/// - Otherwise: gaps are placed by a counter that `M` and `X` advance, `I` and `S` mark and
///   advance, `D` also advances and `=` ignores; the MD reference *with* deleted bases fills the
///   remaining positions in order.
///
/// MD is read as PMDtools reads it: after `^`, every letter up to the next digit is deleted, and
/// lowercase letters are kept as they are, so they never count as C or G (sites, CpG context or
/// the damage table). The default reconstruction reads them as uppercase.
///
/// For a reverse-strand read, PMDtools' reverse complement keeps only `ACGTNRY` and `acgt` and
/// drops every other reference character (e.g. lowercase `n`, most IUPAC codes), so the rest of
/// the reference shifts towards the molecule's 5′ end (the SAM end) and the positions left over at
/// the SAM start have no reference base (docs/blackbox.md, 2026-11-13).
pub fn reference_along_read_pmdtools(
    seq: &[u8],
    cigar: &[CigarOp],
    md: &[u8],
    reverse: bool,
) -> Vec<Option<u8>> {
    let refs = pmdtools_reference_sam_order(seq, cigar, md);
    let dropped = |r: &Option<u8>| r.is_some_and(|b| !b"ACGTNRYacgt".contains(&b));
    if !reverse || !refs.iter().any(dropped) {
        return refs;
    }
    let kept: Vec<Option<u8>> = refs.iter().copied().filter(|r| !dropped(r)).collect();
    std::iter::repeat_n(None, refs.len() - kept.len())
        .chain(kept)
        .collect()
}

fn pmdtools_reference_sam_order(seq: &[u8], cigar: &[CigarOp], md: &[u8]) -> Vec<Option<u8>> {
    // MD reference: None = matches the read, Some(base) = mismatch or deleted base.
    // Vecs here are sized up front: growing them calls realloc, which always takes glibc's arena
    // lock, and with several threads that contention made compat `-@ 8` 2-5x slower.
    let mut expansion: Vec<(Option<u8>, bool)> = Vec::with_capacity(seq.len()); // (base, is_deleted)
    let mut i = 0;
    while i < md.len() {
        if md[i].is_ascii_digit() {
            let start = i;
            while i < md.len() && md[i].is_ascii_digit() {
                i += 1;
            }
            let n: usize = std::str::from_utf8(&md[start..i])
                .ok()
                .and_then(|s| s.parse().ok())
                .unwrap_or(0);
            expansion.extend(std::iter::repeat_n((None, false), n));
        } else if md[i] == b'^' {
            i += 1;
            while i < md.len() && md[i].is_ascii_alphabetic() {
                expansion.push((Some(md[i]), true));
                i += 1;
            }
        } else {
            expansion.push((Some(md[i]), false));
            i += 1;
        }
    }

    let n = seq.len();
    let fill = |e: Option<&(Option<u8>, bool)>, i: usize| -> Option<u8> {
        e.map(|(base, _)| base.unwrap_or(seq[i].to_ascii_uppercase()))
    };
    let simple = !cigar
        .iter()
        .any(|op| matches!(op, CigarOp::Insertion(_) | CigarOp::SoftClip(_)));
    if simple {
        let mut aligned = Vec::with_capacity(expansion.len());
        aligned.extend(expansion.iter().filter(|(_, del)| !del));
        return (0..n).map(|i| fill(aligned.get(i).copied(), i)).collect();
    }

    let mut gap = vec![false; n];
    let mut pos = 0usize;
    for op in cigar {
        match *op {
            CigarOp::Match(k) | CigarOp::SequenceMismatch(k) | CigarOp::Deletion(k) => pos += k,
            CigarOp::Insertion(k) | CigarOp::SoftClip(k) => {
                for g in gap.iter_mut().skip(pos).take(k) {
                    *g = true;
                }
                pos += k;
            }
            CigarOp::SequenceMatch(_) | CigarOp::HardClip(_) | CigarOp::Unsupported => {}
        }
    }
    let mut next = expansion.iter();
    (0..n)
        .map(|i| if gap[i] { None } else { fill(next.next(), i) })
        .collect()
}

/// Reads the MD tag in step with the CIGAR.
struct MdCursor<'a> {
    md: &'a [u8],
    pos: usize,
    /// Matching bases left in the current MD number.
    run: usize,
}

impl MdCursor<'_> {
    fn read_number(&mut self) -> Option<usize> {
        let start = self.pos;
        while self.pos < self.md.len() && self.md[self.pos].is_ascii_digit() {
            self.pos += 1;
        }
        if self.pos == start {
            return None;
        }
        std::str::from_utf8(&self.md[start..self.pos])
            .ok()?
            .parse()
            .ok()
    }

    /// Next aligned base: `None` if it matches the read, or the reference base if it is a mismatch.
    fn next_aligned(&mut self) -> Result<Option<u8>, String> {
        loop {
            if self.run > 0 {
                self.run -= 1;
                return Ok(None);
            }
            if let Some(n) = self.read_number() {
                self.run = n;
                continue;
            }
            return match self.md.get(self.pos) {
                Some(b) if b.is_ascii_alphabetic() => {
                    self.pos += 1;
                    Ok(Some(b.to_ascii_uppercase()))
                }
                Some(b'^') => Err("MD has a deletion where the CIGAR has an aligned base".into()),
                Some(_) => Err("MD contains an invalid character".into()),
                None => Err("MD is shorter than the CIGAR".into()),
            };
        }
    }

    /// Consume a deletion of `n` bases: `^` followed by exactly `n` letters.
    fn deletion(&mut self, n: usize) -> Result<(), String> {
        if self.run > 0 {
            return Err("CIGAR has a deletion inside an MD match run".into());
        }
        while let Some(k) = self.read_number() {
            if k != 0 {
                return Err("CIGAR has a deletion where MD has matching bases".into());
            }
        }
        if self.md.get(self.pos) != Some(&b'^') {
            return Err("CIGAR has a deletion that MD does not have".into());
        }
        self.pos += 1;
        let letters = &self.md[self.pos..];
        if letters.len() < n || !letters[..n].iter().all(u8::is_ascii_alphabetic) {
            return Err("MD deletion is shorter than the CIGAR deletion".into());
        }
        self.pos += n;
        Ok(())
    }

    /// Everything left in MD must be zero-length matches.
    fn finish(&mut self) -> Result<(), String> {
        while self.run == 0 {
            match self.read_number() {
                Some(k) => self.run = k,
                None => break,
            }
        }
        if self.run > 0 || self.pos < self.md.len() {
            return Err("MD is longer than the CIGAR".into());
        }
        Ok(())
    }
}

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',
    }
}

/// True if the reference base at the next SEQ position is G.
/// With `wrap`, a C at the last position takes the first position's reference base as its next base.
fn g_follows(refs: &[Option<u8>], i: usize, wrap: bool) -> bool {
    if i + 1 < refs.len() {
        refs[i + 1] == Some(b'G')
    } else {
        wrap && refs.first() == Some(&Some(b'G'))
    }
}

/// True if the reference base at the previous SEQ position is C.
/// With `wrap`, a G at the first position takes the last position's reference base as its
/// previous base.
fn c_precedes(refs: &[Option<u8>], i: usize, wrap: bool) -> bool {
    if i > 0 {
        refs[i - 1] == Some(b'C')
    } else {
        wrap && refs.last() == Some(&Some(b'C'))
    }
}

/// Score one read. `seq`, `qual` and `refs` are in SAM orientation and have the same length;
/// `qual` holds raw phred values.
pub fn score_read(
    seq: &[u8],
    qual: &[u8],
    refs: &[Option<u8>],
    reverse: bool,
    s: &Settings,
) -> ReadScore {
    let n = seq.len();
    let mut score = ReadScore {
        pmds: 0.0,
        n_sites: 0,
    };
    match s.library {
        Library::DoubleStranded => {
            // Scored in SAM orientation; the ds model is symmetric under reverse complement.
            // PMDtools 0.60 works in molecule orientation, where a G at the molecule's first base
            // takes the molecule's last base as its previous base. In SAM orientation that is the
            // first G of a forward read, or the last C of a reverse read (docs/blackbox.md 1.6c).
            let wrap_g = s.pmdtools_compat && !reverse;
            let wrap_c = s.pmdtools_compat && reverse;
            for i in 0..n {
                let (Some(r), b, q) = (refs[i], seq[i].to_ascii_uppercase(), qual[i]) else {
                    continue;
                };
                if q < s.min_baseq {
                    continue;
                }
                if r == b'C' && (b == b'C' || b == b'T') {
                    let keep = match s.treatment {
                        Treatment::None => true,
                        Treatment::Half => i == 0 || g_follows(refs, i, wrap_c),
                        Treatment::Full => g_follows(refs, i, wrap_c),
                    };
                    if keep {
                        score.pmds += site_term_ds(b == b'C', (i + 1) as u32, q, &s.params);
                        score.n_sites += 1;
                    }
                } else if r == b'G' && (b == b'G' || b == b'A') {
                    let keep = match s.treatment {
                        Treatment::None => true,
                        Treatment::Half => i == n - 1 || c_precedes(refs, i, wrap_g),
                        Treatment::Full => c_precedes(refs, i, wrap_g),
                    };
                    if keep {
                        score.pmds += site_term_ds(b == b'G', (n - i) as u32, q, &s.params);
                        score.n_sites += 1;
                    }
                }
            }
        }
        Library::SingleStranded => {
            // Scored in molecule orientation: reverse-strand reads are reverse-complemented.
            // Molecule position i is SAM position at(i), complemented for reverse reads.
            let at = |i: usize| if reverse { n - 1 - i } else { i };
            let mref = |i: usize| {
                let r = refs[at(i)];
                if reverse { r.map(complement) } else { r }
            };
            for i in 0..n {
                let b = seq[at(i)].to_ascii_uppercase();
                let (Some(r), b, q) = (
                    mref(i),
                    if reverse { complement(b) } else { b },
                    qual[at(i)],
                ) else {
                    continue;
                };
                if q < s.min_baseq || r != b'C' || !(b == b'C' || b == b'T') {
                    continue;
                }
                let keep = match s.treatment {
                    Treatment::None => true,
                    // Only the molecule's 5′ first base is exempt (docs/blackbox.md 1.6b).
                    Treatment::Half => i == 0 || (i + 1 < n && mref(i + 1) == Some(b'G')),
                    Treatment::Full => i + 1 < n && mref(i + 1) == Some(b'G'),
                };
                if keep {
                    let (z, y) = ((i + 1) as u32, (n - i) as u32);
                    score.pmds += if s.pmdtools_compat {
                        site_term_ss(b == b'C', z, y, q, &s.params)
                    } else {
                        site_term_s1(b == b'C', z, y, q, &s.params)
                    };
                    score.n_sites += 1;
                }
            }
        }
    }
    score
}

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

    fn refs(seq: &str, cigar: &[CigarOp], md: &str) -> Result<String, String> {
        let r = reference_along_read(seq.as_bytes(), cigar, md.as_bytes())?;
        Ok(r.iter().map(|b| b.map_or('-', char::from)).collect())
    }

    #[test]
    fn mismatches_and_matches_from_md() {
        assert_eq!(refs("TAAC", &[CigarOp::Match(4)], "0C3"), Ok("CAAC".into()));
    }

    #[test]
    fn clips_and_insertions_have_no_reference_base() {
        let cigar = [
            CigarOp::SoftClip(2),
            CigarOp::Match(2),
            CigarOp::Insertion(1),
            CigarOp::Match(1),
            CigarOp::HardClip(5),
        ];
        assert_eq!(refs("GGTAAC", &cigar, "0C2"), Ok("--CA-C".into()));
    }

    #[test]
    fn deletion_with_and_without_zero_separator() {
        // PMDtools issue #5: MALT writes ^CCTTT0C instead of ^CCTT0T0C.
        let cigar = [CigarOp::Match(4), CigarOp::Deletion(4), CigarOp::Match(3)];
        let spec = refs("AAAACTA", &cigar, "4^CCTT0T0C1");
        let malt = refs("AAAACTA", &cigar, "4^CCTTT0C1");
        assert_eq!(spec, Ok("AAAATCA".into()));
        assert_eq!(malt, spec);
    }

    #[test]
    fn md_that_contradicts_cigar_is_an_error() {
        assert!(refs("TAAC", &[CigarOp::Match(4)], "0C2").is_err()); // MD too short
        assert!(refs("TAAC", &[CigarOp::Match(4)], "0C4").is_err()); // MD too long
        assert!(refs("TAAC", &[CigarOp::Match(3)], "0C2").is_err()); // CIGAR vs SEQ length
        assert!(refs("TAAC", &[CigarOp::Match(4)], "0^C3").is_err()); // deletion not in CIGAR
        assert!(refs("TAAC", &[CigarOp::Match(2), CigarOp::Unsupported], "4").is_err());
        // MD/CIGAR disagreements say how to fix them; the CIGAR/SEQ check does not mention MD.
        let hint = "MD does not match the alignment; recompute it with samtools calmd";
        assert!(
            refs("TAAC", &[CigarOp::Match(4)], "0C2")
                .unwrap_err()
                .contains(hint)
        );
        assert!(
            refs("TAAC", &[CigarOp::Match(4)], "0^C3")
                .unwrap_err()
                .contains(hint)
        );
        assert!(
            !refs("TAAC", &[CigarOp::Match(3)], "0C2")
                .unwrap_err()
                .contains("calmd")
        );
    }

    fn compat(seq: &str, cigar: &[CigarOp], md: &str) -> String {
        reference_along_read_pmdtools(seq.as_bytes(), cigar, md.as_bytes(), false)
            .iter()
            .map(|b| b.map_or('-', char::from))
            .collect()
    }

    // Expected strings are PMDtools 0.60 --printalignments reference lines (docs/blackbox.md probes 15–16).
    #[test]
    fn compat_reproduces_pmdtools_reference_lines() {
        use CigarOp::*;
        let read = "ACGTACGTACTTCCAAGGTT";
        assert_eq!(
            compat(read, &[Match(10), Deletion(2), Match(10)], "10^GG10"),
            "ACGTACGTACTTCCAAGGTT"
        );
        assert_eq!(
            compat(
                &format!("NN{read}"),
                &[SoftClip(2), Match(10), Deletion(2), Match(10)],
                "10^GG10"
            ),
            "--ACGTACGTACGGCCAAGGTT"
        );
        assert_eq!(
            compat(
                &format!("{read}NNN"),
                &[Match(10), Deletion(2), Match(10), SoftClip(3)],
                "10^GG10"
            ),
            "ACGTACGTACGGCCAAGGTTNN-"
        );
        assert_eq!(
            compat(
                "ACGTACGTACNNTTCCAAGGTT",
                &[SequenceMatch(10), Insertion(2), SequenceMatch(10)],
                "20"
            ),
            "--GTACGTACNNTTCCAAGGTT"
        );
    }

    // Departure from PMDtools (docs/blackbox.md 1.6c): the default reconstruction is correct.
    #[test]
    fn default_reconstruction_fixes_clip_plus_deletion() {
        let cigar = [
            CigarOp::SoftClip(2),
            CigarOp::Match(10),
            CigarOp::Deletion(2),
            CigarOp::Match(10),
        ];
        let read = "NNACGTACGTACTTCCAAGGTT";
        assert_eq!(
            refs(read, &cigar, "10^GG10"),
            Ok("--ACGTACGTACTTCCAAGGTT".into())
        );
        assert_ne!(compat(read, &cigar, "10^GG10"), "--ACGTACGTACTTCCAAGGTT");
    }

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

    fn score(seq: &str, ref_seq: &str, reverse: bool, s: &Settings) -> ReadScore {
        let refs: Vec<Option<u8>> = ref_seq.bytes().map(Some).collect();
        score_read(seq.as_bytes(), &vec![40; seq.len()], &refs, reverse, s)
    }

    fn close(a: f64, b: f64) -> bool {
        (a - b).abs() < 1e-12
    }

    // Expected values are PMDtools 0.60 outputs from docs/blackbox.md probes 1, 6, 9 and 12.
    #[test]
    fn terminal_damage_scores_like_pmdtools() {
        let ds = default_settings(Library::DoubleStranded, Treatment::None);
        let a = "A".repeat(29);
        assert!(close(
            score(&format!("T{a}"), &format!("C{a}"), false, &ds).pmds,
            5.029717285061266
        ));
        assert!(close(
            score(&format!("{a}A"), &format!("{a}G"), false, &ds).pmds,
            5.029717285061266
        ));
    }

    #[test]
    fn no_informative_sites_scores_zero() {
        let ds = default_settings(Library::DoubleStranded, Treatment::None);
        let r = score("AAAA", "AAAA", false, &ds);
        assert_eq!(
            r,
            ReadScore {
                pmds: 0.0,
                n_sites: 0
            }
        );
    }

    #[test]
    fn single_stranded_uses_molecule_orientation() {
        let ss = default_settings(Library::SingleStranded, Treatment::None);
        let a = "A".repeat(29);
        // Forward: C→T at the first base. Reverse: SAM G→A at the last base is the molecule's 5′ C→T.
        let fwd = score(&format!("T{a}"), &format!("C{a}"), false, &ss).pmds;
        let rev = score(&format!("{a}A"), &format!("{a}G"), true, &ss).pmds;
        // Default: Eq. S1 alone. --pmdtools-compat: PMDtools 0.60's double-counted 9.68.
        assert!(close(fwd, 4.65219207891691));
        assert!(close(rev, 4.65219207891691));
        let compat = Settings {
            pmdtools_compat: true,
            ..ss
        };
        assert!(close(
            score(&format!("T{a}"), &format!("C{a}"), false, &compat).pmds,
            9.681909363978177
        ));
        // G→A on a forward read is not damage in ss mode.
        assert_eq!(
            score(&format!("{a}A"), &format!("{a}G"), false, &ss).n_sites,
            0
        );
    }

    #[test]
    fn cpg_modes_select_sites_like_pmdtools() {
        let full = default_settings(Library::DoubleStranded, Treatment::Full);
        let half = default_settings(Library::DoubleStranded, Treatment::Half);
        let a = "A".repeat(28);
        // Terminal C→T, not CpG: dropped by full, kept by half.
        assert_eq!(
            score(&format!("TA{a}"), &format!("CA{a}"), false, &full).n_sites,
            0
        );
        assert!(close(
            score(&format!("TA{a}"), &format!("CA{a}"), false, &half).pmds,
            5.029717285061266
        ));
        // Interior CpG C→T (z = 5) plus its G (match, z = 25): kept by both.
        let read = format!("AAAATG{}", "A".repeat(24));
        let reference = format!("AAAACG{}", "A".repeat(24));
        assert!(close(
            score(&read, &reference, false, &full).pmds,
            3.7003221261207053
        ));
        assert!(close(
            score(&read, &reference, false, &half).pmds,
            3.7003221261207053
        ));
    }

    // Departure from PMDtools (docs/blackbox.md 1.6c): CpG context does not wrap around the read
    // ends by default. PMDtools (and --pmdtools-compat) treats a forward read's first G, or a
    // reverse read's last C, as CpG when the base at the other end completes the pair.
    #[test]
    fn cpg_context_wraps_only_in_compat_mode() {
        let mut s = default_settings(Library::DoubleStranded, Treatment::Full);
        let (read, reference) = ("GAAAC", "GAAAC");
        assert_eq!(score(read, reference, false, &s).n_sites, 0);
        assert_eq!(score(read, reference, true, &s).n_sites, 0);
        s.pmdtools_compat = true;
        let fwd = score(read, reference, false, &s);
        let rev = score(read, reference, true, &s);
        assert_eq!((fwd.n_sites, rev.n_sites), (1, 1));
        // Forward: the first G (3′ distance 5). Reverse: the last C (5′ distance 5). Same term.
        assert!(close(fwd.pmds, site_term_ds(true, 5, 40, &s.params)));
        assert!(close(rev.pmds, fwd.pmds));
    }

    #[test]
    fn low_quality_bases_are_ignored() {
        let mut s = default_settings(Library::DoubleStranded, Treatment::None);
        s.min_baseq = 41;
        assert_eq!(score("TAAA", "CAAA", false, &s).n_sites, 0);
    }
    /// Audit finding B3 (docs/audit-0.3.md §10): with -r, a CIGAR that covers far more read bases
    /// than SEQ had its per-base vector built before the length check (a 2e16-base insertion
    /// aborted on allocation), and CIGAR lengths could add up past usize::MAX, wrap round to
    /// SEQ's length and pass. Both reconstructions now reject them first, without allocating.
    #[test]
    fn absurd_cigar_lengths_are_rejected_before_allocating() {
        use CigarOp::*;
        let huge = usize::MAX / 2;
        for cigar in [
            vec![Match(1), Insertion(20_000_000_000_000_000)],
            vec![Match(1), SoftClip(huge)],
            // Wraps to 2 with a plain sum.
            vec![Insertion(usize::MAX), Insertion(usize::MAX), Match(4)],
        ] {
            let e = reference_along_read_from_fasta(b"AC", &cigar, b"ACGT").unwrap_err();
            assert!(e.contains("but SEQ has 2"), "{cigar:?}: {e}");
            let e = reference_along_read(b"AC", &cigar, b"2").unwrap_err();
            assert!(e.contains("but SEQ has 2"), "{cigar:?}: {e}");
        }
        // The reference window length saturates instead of wrapping to a short window.
        assert_eq!(
            reference_span(&[Deletion(usize::MAX), Match(5)]),
            usize::MAX
        );
    }

    /// `-r` reconstruction equals the MD reconstruction of the MD that calmd-style
    /// `md_from_reference` writes, for mismatches, deletions, insertions, soft clips, lowercase
    /// (soft-masked) reference bases; `=` read bases are checked separately.
    #[test]
    fn reference_window_matches_md_written_from_it() {
        use CigarOp::*;
        let cases: &[(&str, &[CigarOp], &str, &str)] = &[
            ("ACGTACGT", &[Match(8)], "ACGTACGT", "8"),
            ("ACGTACGT", &[Match(8)], "TCGTACGA", "0T6A0"),
            ("ACGTACGT", &[Match(8)], "acgtaCgt", "8"),
            // Soft-masked mismatches are written in uppercase, as calmd writes them; otherwise
            // --pmdtools-compat would not count the C->T below as a C site.
            ("TCGTACGT", &[Match(8)], "ccgtacgt", "0C7"),
            (
                "ACGTACGT",
                &[Match(4), Deletion(2), Match(4)],
                "ACGTggACGA",
                "4^GG3A0",
            ),
            (
                "ACGTACGT",
                &[Match(4), Deletion(1), Match(4)],
                "ACGTcTCGT",
                "4^C0T3",
            ),
            (
                "ACGTACGT",
                &[SoftClip(2), Match(3), Insertion(1), Match(2)],
                "GTACG",
                "3C0G0",
            ),
            (
                "ACGTACGT",
                &[HardClip(3), Match(8), HardClip(2)],
                "ACGTACGG",
                "7G0",
            ),
        ];
        for &(seq, cigar, window, md) in cases {
            let (seq, window) = (seq.as_bytes(), window.as_bytes());
            assert_eq!(reference_span(cigar), window.len(), "{cigar:?}");
            let written = md_from_reference(seq, cigar, window);
            assert_eq!(
                String::from_utf8_lossy(&written),
                md,
                "{cigar:?} {:?}",
                window
            );
            let from_md = reference_along_read(seq, cigar, &written).unwrap();
            let from_fasta = reference_along_read_from_fasta(seq, cigar, window).unwrap();
            assert_eq!(from_md, from_fasta, "{cigar:?} {md}");
        }
        // Audit finding B2 (docs/audit-0.3.md §10): calmd counts N against N as a mismatch and
        // writes the N, so --pmdtools-compat -r must too. Expected MD strings are samtools 1.25
        // calmd's output for these reads (2026-11-21).
        assert_eq!(
            String::from_utf8_lossy(&md_from_reference(b"ACGTANGT", &[Match(8)], b"ACGTANGT")),
            "5N2"
        );
        assert_eq!(
            String::from_utf8_lossy(&md_from_reference(
                b"GGACGNNAC",
                &[SoftClip(2), Match(3), Deletion(1), Match(4)],
                b"ACGTNNAC"
            )),
            "3^T0N0N2"
        );
        // A `=` read base matches; MD can only give `=` back for it, the reference gives the base.
        assert_eq!(md_from_reference(b"AC=T", &[Match(4)], b"ACGT"), b"4");
        assert_eq!(
            reference_along_read_from_fasta(b"AC=T", &[Match(4)], b"ACGT").unwrap()[2],
            Some(b'G')
        );
        assert!(reference_along_read_from_fasta(b"ACG", &[Match(2)], b"AC").is_err());
    }
}