pmdshodh 0.4.1

Per-read post-mortem damage (PMD) scoring and filtering of ancient DNA alignments, compatible with PMDtools
Documentation

pmdshodh

CI PyPI Bioconda crates.io GitHub release Rust 1.91+ License: MIT

Fast post-mortem damage (PMD) scoring and filtering for ancient DNA alignments.

pmdshodh scores every read in a SAM, BAM or CRAM file for ancient DNA damage, keeps or removes reads by score, and summarises damage patterns. It uses the scoring model of PMDtools 0.60 and fixes PMDtools' known errors by default; --pmdtools-compat reproduces PMDtools for comparisons. It reads and writes alignments directly and runs on multiple threads.

Status: alpha. Scores have been validated read by read against PMDtools on real and synthetic data (validation).

Contents

Overview

Ancient DNA molecules carry characteristic damage. Cytosine deamination appears as C→T substitutions near the 5′ end of reads, and as G→A near the 3′ end in double-stranded libraries. The PMD score of Skoglund et al. (2014) is a per-read log-likelihood ratio comparing a damage model with a no-damage model. Reads scoring above a threshold (commonly 3) are likely to be ancient rather than modern contamination.

pmdshodh computes this score in a single program, with no samtools calmd | python | samtools view pipeline:

  • PMDtools-compatible scores: the same likelihood model, defaults and options (--threshold, --ss, --CpG, --UDGhalf, -m, -q, …). Single-stranded scores follow the paper's model and are lower than PMDtools' (details).
  • Direct SAM, BAM and CRAM input, SAM and BAM output. Kept records are written unchanged and in input order, with an @PG header line.
  • Multi-threaded scoring and BGZF compression, with identical results for any thread count.
  • JSON run summary with read counts, a score histogram and damage tables, designed for MultiQC.
  • Self-contained HTML damage report from one or more run summaries, with no JavaScript or network access.
  • No silent data loss: every skipped read is counted by reason, and invalid input stops with a clear error.

pmdshodh does not classify taxa, estimate contamination, call genotypes or rescale base qualities.

Installation

Method Command
Bioconda conda install -c conda-forge -c bioconda pmdshodh
pip pip install pmdshodh
Prebuilt binary download from GitHub Releases
crates.io cargo install pmdshodh (Rust 1.91 or newer; builds from source)
From source cargo build --release (Rust 1.91 or newer)
  • pip wheels contain the compiled binary only and install the pmdshodh command.
  • Prebuilt archives are named pmdshodh-<version>-<target>; check them against SHA256SUMS.
  • Platforms: wheels and binaries are built for Linux x86_64 and aarch64 (glibc 2.17 or newer: CentOS/RHEL 7 and later), macOS arm64 and x86_64, and Windows x86_64.
  • From source: Rust 1.91 is the minimum of the noodles dependency, and CI tests it as well as the latest stable release.
git clone https://github.com/dpatel511/pmdshodh.git
cd pmdshodh
cargo build --release
./target/release/pmdshodh --version

Reference bases: MD tags or -r

pmdshodh needs each read's reference bases. Either pass the reference with -r, or give it reads with an MD tag.

  • With -r ref.fa: the FASTA must be indexed with samtools faidx. Reference bases come from the FASTA, so reads need no MD tag. Any MD tags present are checked against the reference, and stale ones are counted.
  • CRAM input always needs -r, with the reference the CRAM was written against. Each reference sequence is checked against the M5 checksum in the CRAM header when it is loaded. A different reference is therefore an input error, instead of giving wrong reads and scores without warning. samtools writes M5; without it, only single-reference slices are checked, against their own MD5. REF_PATH, REF_CACHE and downloads are not used.
  • Without -r: every mapped read needs an MD tag. If your aligner does not write one, add it with samtools calmd -b input.bam reference.fa > input.md.bam.
  • Aligners tested without MD tags: strobealign 0.20.0, minimap2 2.31 (-ax sr, without --MD) and bowtie2 2.5.5 (MD tags removed), single-end and paired. Scored with -r, every read's score, the kept reads and the damage tables equal those after samtools calmd (see Validation).

Quick start

New to pmdshodh? The user guide walks through a first run. Coming from PMDtools? See migrating from PMDtools.

# Keep reads with PMD score >= 3 (double-stranded library, no UDG treatment)
pmdshodh filter --threshold 3 sample.bam -o sample.pmd3.bam

# Add the score to each kept read, write a run summary, use 8 threads
pmdshodh filter --threshold 3 --tag --summary sample.json --threads 8 sample.bam -o sample.pmd3.bam

# Single-stranded, UDG-half treated library
pmdshodh filter --threshold 3 --library ss --treatment half sample.bam -o sample.pmd3.bam

# Per-read scores as a table
pmdshodh score sample.bam -o sample.scores.tsv

# Damage summary only
pmdshodh damage sample.bam -o sample.damage.json

# HTML report from one or more run summaries
pmdshodh report sample.damage.json other.damage.json -o damage-report.html

# CRAM input (needs its reference); writes BAM
pmdshodh filter --threshold 3 -r ref.fa sample.cram -o sample.pmd3.bam

Commands

Command Purpose Output
filter Keep reads by PMD score SAM or BAM, chosen by the -o extension (-o - writes BAM to stdout)
score Score every read Tab-separated table: read_name, flag, pmds, n_sites
damage Summarise damage without filtering JSON run summary
report Report on run summaries (never re-reads alignments) One HTML file (-o - writes it to stdout)

filter keeps reads with score ≥ --threshold and/or < --upper-threshold; at least one is required. Run pmdshodh <command> --help for every option, grouped by purpose, with examples.

Options

PMDtools option names are accepted as aliases (second column).

Library and treatment

Option PMDtools Default Description
--library ds|ss --ss ds Double- or single-stranded library. Never inferred from the data.
--treatment none|half|full --UDGminus, --UDGhalf, --UDGplus / --CpG none half: CpG sites plus the terminal base; full: CpG sites only.

After every run, the damage pattern is compared with these two options, and when it disagrees with them the summary on stderr has a note (and the JSON run summary mode_check); scores are not changed.

Read and base selection

Option PMDtools Default Description
-m, --min-mapq N -m, --requiremapq 0 Skip reads below this mapping quality.
-q, --min-baseq N -q, --requirebaseq 0 Ignore bases below this base quality.
--no-clips --noclips off Skip reads with soft or hard clips.
--no-indels --noindels off Skip reads with insertions or deletions.
--skip-flags LIST — none Skip mapped reads with any of these SAM flags, comma-separated: secondary, supplementary, duplicate, qcfail. By default they are scored, as by PMDtools.

Model parameters

Option PMDtools Default
--pmd-p --PMDpparam 0.3
--pmd-c --PMDconstant 0.01
--pi-ancient --polymorphism_ancient 0.001
--pi-contamination --polymorphism_contamination 0.001

Each is between 0 and 1, and --pmd-p + --pmd-c (the damage rate at the read end) must be at most 1; larger values would make scores undefined (NaN).

The defaults are close to the best any damage curve can do on double-stranded libraries (damage-curve study). For untreated single-stranded libraries, --pmd-c 0.05 helped on one of three libraries (ancient reads mixed with modern reads, at the same removal of modern reads). On UKY001.B0102 mtDNA, with about 7% C→T inside the molecule, it kept 3–4 percentage points more ancient reads. On two libraries with about 4%, it kept fewer: 1–2 points on ZKU002.A0102 mtDNA and 2–3 points on wolf library MCJ066-2 (two nuclear chromosomes). Keep the default unless a test on your own data shows a gain. Scores with a changed --pmd-c are not comparable with published thresholds.

Output and performance

Option Applies to Description
-t, --threshold X filter Keep reads with score ≥ X.
--upper-threshold X filter Keep reads with score < X.
--tag, --tag-name pm|DS filter Add the score to kept reads as pm:f (32-bit float, default) or DS:Z (3 decimals, as PMDtools --writesamfield).
--summary FILE filter, score Also write the JSON run summary.
--range N all Positions from each read end in damage tables (default 30, from 1 to 1000).
-n, --max-reads N damage Stop after N reads.
-@, --threads N all Threads (default 1, at most 1024). At most N do work at once, so you can pass your CPU allocation.
-r, --reference FILE all Indexed reference FASTA (samtools faidx; bgzip also needs .gzi). Reference bases come from it instead of MD tags, and MD tags are checked against it. Header sequences in it must have the same length; ones missing from it are allowed (and counted) as long as no read is mapped to them.
--pmdtools-compat all Reproduce PMDtools 0.60, including its bugs (limits).
--quiet all Suppress the summary and the progress line on stderr.

Output

Alignments (filter)

  • Kept records are unchanged (identical when decoded) apart from the optional score tag, and input order is preserved.
  • The input header is copied, and one @PG line records the command.
  • From CRAM input, records are written as stored in the CRAM. MD and NM tags that htslib left out, because it can regenerate them, are not added back (limitations).
  • The output format comes from a .bam or .sam extension (any case). For stdout and devices, which have none, --output-format decides, BAM by default: -o /dev/null --summary run.json keeps only the summary.
  • Output files are written under a temporary name and renamed only on success, so a failed run never leaves a partial file. A symlink is followed and the file it points to is replaced. FIFOs and devices (/dev/null, NUL on Windows, /dev/stdout, >(...)) are written in place.
  • If Ctrl-C, SIGTERM (for example a scheduler's time limit) or SIGHUP ends the run, the temporary files are removed first, and the process still ends by that signal (status 130, 143 or 129).
  • An output may not be the input, the reference or another output (exit 2).

JSON run summary

One file per run, versioned with format_version (currently 5, which adds filters.skip_flags, the skip reason skip_flags, reads.kept_at_threshold and mode_check). The fields and their types are frozen (see Compatibility below):

Section Contents
tool, command, mode, model, filters Version, command line, library and treatment, model parameters, thresholds
input_format sam, bam or cram, detected from the file contents
reference The -r FASTA (if any); whether reference bases came from MD or the FASTA; with -r, how many scored reads had MD tags agreeing, disagreeing or absent (for CRAM, only MD tags stored in the file count)
reads Input, scored, kept and removed counts; kept_at_threshold: scored reads that filter -t T alone would keep, for T = 1, 2, 3 and 5; skipped reads by reason; flag counts (duplicate, secondary, supplementary, …)
score_histogram, length_histogram Score distribution (0.5-wide bins from −20 to 40), read lengths
damage Counts of read bases A/C/G/T at reference C and G, by position from each molecule end; first-base C→T rate with standard error
mode_check The damage pattern against --library and --treatment. library: 3′ terminal C→T and G→A, in all contexts and at CpG sites. treatment: 5′ C→T outside CpG sites at the first and second base and in the background (bases 21–25), and at CpG sites at the first base. Each has a pattern (ss or ds; none, half or full) and whether it agrees with the mode; both are null without a clear call, for example with fewer than 500 sites or in modern DNA. These counts use every site and the reference's CpG context, so they are the same in every mode, and are counted in every run.

Compatibility of the JSON run summary

format_version 5 is frozen from pmdshodh 0.4.0. A test pins every field and its JSON type, and the fixed values: the histogram bins and the names listed below.

Keeps format_version 5:

  • A new field, anywhere. Readers must ignore fields they do not know, and treat fields added after 0.4.0 as optional: an older version 5 file lacks them.
  • A new key in reads.skipped or reads.flags. These are open maps: read every key, not a fixed list. reads.input equals reads.scored plus the sum of all reads.skipped counts, whatever their names.

Needs a new format_version:

  • A field removed or renamed.
  • A field given another JSON type, including a field that is never null becoming nullable.
  • A field given another meaning, unit or scale, including the histogram bins.
  • A new value for a field with a fixed set of names:
    • subcommand;
    • input_format;
    • reference.bases_from;
    • mode.library and mode.treatment;
    • mode_check.*.pattern;
    • the names in filters.skip_flags.

When it changes:

  • A new field comes in a minor release or a new 1.0.0-beta.
  • A new format_version comes in a minor release before 1.0.0 (0.y.0), in a new 1.0.0-beta, or in a major release from 1.0.0 (docs/roadmap.md, Versioning).
  • A patch release changes the JSON only where a fix corrects a value.
  • Readers should accept the versions they know, and treat a higher one as unknown.
  • report reads every version from 1 on. Dropping one needs a major release.

HTML damage report (report)

pmdshodh report run.json [more.json ...] -o report.html reads summaries written by damage -o, filter --summary or score --summary (format_version 1 to 5; fields missing from version 1 are shown as "not recorded"). The JSON stays the source of truth: the report computes rates from its counts and adds nothing new. Per sample, it shows:

  • the run: input, reference, command line, library, treatment, model parameters and thresholds;
  • read counts, reads with a score of at least 1, 2, 3 and 5 (when the summary has them), skipped reads by reason, flag counts and, with -r, MD tag agreement;
  • damage by position in percent, from position 1: 5′ C→T, and 3′ G→A for double-stranded or 3′ C→T for single-stranded libraries, with all other substitutions as a dashed baseline; and the first-base C→T rate with its standard error;
  • the PMD score histogram as a percentage of scored reads, with the thresholds marked and, for filter, the fraction of scored reads kept;
  • read lengths of scored reads and, for filter, of kept reads in a separate chart.

With several summaries, an "All samples" section overlays their damage curves and score histograms. Samples are labelled by the input's file name, with the summary's file name added when two would clash.

The file uses inline SVG, with no JavaScript, external files or network access, so it opens offline or as an e-mail attachment. The same summaries give a byte-identical report, and plotted values are also in data-values attributes, so scripts can check them against the JSON. An unreadable or invalid summary, or an unsupported format_version, exits with status 2 and names the file and field.

Exit status and streams

Exit status Meaning
0 Success, including input with only a header
1 Runtime failure, for example the output cannot be written
2 Invalid options or invalid input, for example a mapped read without an MD tag (the read is named in the message), or an input with no data at all
141 The reader of stdout closed it early (for example | head): pmdshodh stops without a message, as samtools does when SIGPIPE ends it

Results go to stdout only when requested (-o -, or score/damage without -o). Errors and the run summary go to stderr. The summary is a short block: input, read counts, skip reasons, reads kept, reads scoring at least 1, 2, 3 and 5, first-base damage (when counted), files written, and time. Notes flag paired mates that were not merged (each mate is scored on its own) and runs that score or keep no reads; they do not change the exit status. In a terminal, a progress line shows reads, rate and how much of the input has been read, and the summary is coloured. Set NO_COLOR to turn colour off. In pipes and pipeline logs there is no progress line and no colour.

Compatibility with PMDtools

Validation

pmdshodh was built from the published model and black-box testing of PMDtools 0.60; PMDtools' source code was not used. Every read in each test set was compared:

Test set Reads Largest score difference
Single-site score terms (ds and ss, base quality 0–93, 6 parameter sets) 5,412 1.1 × 10⁻¹³
Synthetic reads with clips, indels and =/X CIGARs, both strands, 8 modes 1,500 per mode 8.3 × 10⁻¹⁴ ¹
nf-core/eager test BAMs (mammoth mtDNA, human 1240k capture), ds, --CpG, --UDGhalf, --ss 13,670 per mode 3.0 × 10⁻¹⁴ ¹
Real single-stranded library, not UDG-treated (ENA PRJEB37007, UKY001.B0102: mtDNA and 1240k capture), --ss 281,906 and 14,461,790 8.2 × 10⁻¹⁴ ¹
Real libraries: single-stranded USER-treated (ERR7195621), ds UDG-half (ERR4589292), ds full UDG (ERR1995180), in the modes each implies plus untreated 273,326, 755,825 and 141,943 4.4 × 10⁻¹⁴ ¹
Damage tables vs pmdtools --deamination --range 30 (no UDG, UDG-half and full UDG) 1,500 identical at all 30 positions
BAMs without MD tags scored with -r, against the same BAMs after samtools calmd: UKY001 mtDNA aligned with strobealign, minimap2 (-ax sr) and bowtie2 (MD removed), single-end and paired, --library ds and ss, default and compat (audit_no_md.py) 63,933 to 194,682 per BAM identical scores, kept reads and damage tables

¹ With --pmdtools-compat. Without it, scores differ only where PMDtools has a bug (below).

Methods and full results: docs/blackbox.md and the 0.3 audit, docs/audit-0.3.md.

How well the score separates damaged from undamaged reads, and how much room any damage curve leaves, was measured on simulated reads and on real ancient and modern reads mixed with known labels: docs/fit-validation.md.

Differences that change scores

pmdshodh corrects these PMDtools behaviours by default. --pmdtools-compat reproduces them.

PMDtools 0.60 behaviour Effect pmdshodh default
The reference is rebuilt wrongly for reads that combine an insertion or soft clip with a deletion or = CIGAR operations Deleted bases are scored against later read bases, and positions shift Reference rebuilt correctly from CIGAR and MD
CpG context wraps around the read ends in --CpG and --UDGhalf modes Changed 6% of read scores (up to 1.62) on the human UDG test BAM No wrap-around
--ss counts every C site twice (the double-stranded term plus the paper's single-stranded term, SI Eq. S1) ss scores are about twice as large as the model gives, and lopsided: a terminal C→T scores 9.68 at the 5′ end and 6.34 at the 3′ end (Q40), so a threshold of 3 is far looser than for ds libraries One term per C site (Eq. S1): 4.65 at either end. ss scores are lower than PMDtools'; re-check thresholds tuned on PMDtools ss scores
--upperthreshold keeps reads with no informative sites (score 0) Reads with no C/G evidence at all are output as "non-damaged" Not kept by --upper-threshold (still counted as no_informative_sites)
Lowercase reference bases in MD (outside the SAM spec) are never counted as C or G 339 of 14.0 M reads scored differently on a public horse BAM (ENA ERR1892229) Read as uppercase
On reverse-strand reads, MD characters other than ACGTNRY/acgt (for example lowercase n) are dropped when the reference is reverse-complemented The reference shifts against the read; scores up to 15.7 too high No shift
Read bases written as = (same as the reference; samtools calmd -e) never count as C or G Matches at those sites are missed: a read with nine = at reference C scored 5.03 from 1 site instead of 4.22 from 10 Taken from -r; without -r, an input error (MD does not give their reference bases)

In CpG modes, expect pmdshodh's default results to differ from PMDtools on some reads.

What this does to filtering (details):

  • Double-stranded libraries: default and --pmdtools-compat kept nearly the same reads in 78 audit runs, so thresholds carry over. One UDG-half library kept up to 4.4% fewer reads at threshold 3 in default mode.
  • Single-stranded libraries: scored as untreated, default mode kept 11–28% fewer reads than compat at threshold 3 and 47–88% fewer at threshold 5; with UDG-half or full scoring, over 90% fewer at threshold 5. It separated ancient from modern reads as well as compat did (within about 1 percentage point, at equal removal of modern reads), so this is a change of scale. On two mtDNA libraries, a PMDtools ss threshold of 3 matched about 1.6 in default mode, and 5 matched about 2.8. To use thresholds tuned on PMDtools ss scores, add --pmdtools-compat.
  • Choosing a threshold: after every filter, score and damage run, the summary on stderr and the JSON run summary give how many scored reads filter -t would keep at 1, 2, 3 and 5.

Differences that prevent crashes or data loss

Situation PMDtools 0.60 pmdshodh default
Mapped read without an MD tag Dropped silently Error (exit 2); with -r, scored from the reference
MD string without a 0 after a deletion (as written by MALT) Misparsed silently Parsed correctly
Hard-clipped reads Dropped Scored (compat drops them, counted as unsupported_cigar)
Reads whose SEQ is 1 base Dropped silently Scored (compat drops them, counted as too_short)
--threshold ≤ −10000 (for example -1000000 to keep every read), unless --upperthreshold is below 1,000,000; or --upperthreshold ≥ 1,000,000 alone Counted as not given: no reads written, no message Applied as given (compat keeps no reads, with a note on stderr)
Existing DS:Z tag, or DS:Z: text in qualities Crash Handled
Input with only a header Crash Empty output, exit 0
BAM without its end-of-file marker (cut at a block boundary) samtools view warns and passes on the reads before the cut Error (exit 2), no output file
Damage site ≥ 1,000 bp from a read end, or hundreds of mismatches in one read Crash Scored
--first (first-base damage rate with standard error) Crashes in the 0.60 release Reported in the JSON summary

Behaviour kept for compatibility

pmdshodh keeps these parts of PMDtools' score as computed, so that scores mean the same:

  • The no-damage model assumes a background damage rate of 0.001.
  • By default, reads are scored regardless of SAM flags (duplicates, secondary and supplementary alignments, paired reads). Remove unwanted reads beforehand, or skip them with --skip-flags; the summary counts them.

The complete list, with reasoning: docs/design.md §5.

Limitations

  • CRAM is input only; filter writes SAM or BAM.

  • MD and NM from CRAM: kept records have no MD or NM tag unless the CRAM stored one. htslib usually leaves these tags out and regenerates them on decoding; pmdshodh does not. Run samtools calmd on the output if a later step needs MD.

  • CRAM reference: CRAM input must be scored against the reference it was written with, so a masked FASTA (as nf-core/eager uses to mask positions) fails the checksum check. Mask BAM input instead, or decode the CRAM to BAM first.

  • CRAM speed and memory: CRAM input loads whole reference sequences, because noodles decodes against them. With filter -r -@ 8, CRAM took 38.7 s (horse) and 58.5 s (human) with peak memory of 1,190 MB and 1,248 MB, against 12.6 s and 14.8 s with 112 MB for the same reads as BAM (median of 5 runs, docs/benchmarks.md). CRAM input also checks every reference sequence against its checksum (docs/design.md §11).

  • Last-digit differences between platforms: each platform's math library rounds ln and powf differently. On the test fixture, Windows differed from Linux and macOS by at most 1.8e-15. Only a score this close to a threshold could be filtered differently.

  • Benchmarks cover one laptop and two double-stranded libraries (docs/benchmarks.md). On one thread, pmdshodh filter was 32–39× faster than the PMDtools pipeline, and pmdshodh score was faster than metaDMG pmd in all 10 alternating pairs: 48.8 s against 61.7 s and 60.6 s against 71.9 s (medians).

  • What --pmdtools-compat does not reproduce:

    • = read bases (samtools calmd -e output) on reverse-strand reads, which PMDtools scores as if their explicit bases were at the read end;
    • reads made only of =, which PMDtools drops (default mode resolves = from -r);
    • lowercase bases in SAM SEQ, which PMDtools does not recognise and pmdshodh reads as uppercase;
    • mapped reads with CIGAR * and an MD tag, which PMDtools scores from the MD and pmdshodh rejects (exit 2).

    See docs/design.md §5.

  • Single-stranded libraries: two real ones have been tested, one not UDG-treated (PRJEB37007) and one USER-treated (ERR7195621, in ss and ss --UDGhalf modes). Single-stranded full-UDG scoring rests on synthetic reads.

Citation

pmdshodh has no paper of its own. If you use it, please cite the PMD score's original description and this repository:

Development

cargo fmt --check
cargo clippy --all-targets -- -D warnings
cargo test
  • Reference data: the tests compare against values produced by PMDtools 0.60, stored in tests/data/. The scripts in tests/oracle/ regenerate them; they need PMDtools 0.60 on Linux or WSL.
  • Readable model: tests/oracle/pmd_reference.py is a short Python version of the scoring model.
  • Background: research, design decisions, black-box findings and the 0.3 audit are in docs/. Changes are listed in CHANGELOG.md.

License

MIT.