Algorithmcore
Duplicate read marking
Also called PCR duplicate removal, duplicate marking.
Flag reads or pairs that start at the same positions on the same strand as copies of one molecule, and keep the one of best quality.
- Time
- O(n log n + b) worstO(n + b) averageΘ(n + b) best
- Space
- Θ(n) extra
- Where
- b = the total number of bases and CIGAR operations; n = the number of templates (pairs and single reads)
- Model
- Word RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Heng Li, 2009
Duplicate read marking finds reads that are copies of one original DNA fragment and flags all but one of them. Copies come from the PCR amplification of the library, and from the sequencer, when one cluster on the flow cell is read as two (optical duplicates). Copies are not independent evidence: an error made in an early PCR cycle shows up in every copy, so a caller that counts them as separate reads can call a false variant. The standard method, that of Picard MarkDuplicates, calls two read pairs duplicates when both of their unclipped 5' ends lie at the same positions on the same strands, keeps the pair with the highest sum of base qualities, and sets the SAM flag 0x400 on the others. It marks the reads and does not remove them, unless the user asks for that.
In plain words
Before sequencing, the DNA pieces are copied many times. If two reads start and end at exactly the same places, they are most likely copies of one piece, because two different pieces rarely break at the same two places. Copies are a problem: if the first copy had a mistake, all copies have it, and the mistake looks like it was seen many times.
So group the reads by where they start and end and on which strand. In each group, keep the read with the best quality and put a mark on the others. Later tools skip the marked reads. Reads that come alone, without a partner, are grouped by their start only. A lone read that starts where a pair starts is marked, because the pair tells more.
The problem
Positions are 1-based, as in SAM. The input is a list of templates. A template is a pair, with both reads mapped, or a fragment, a single-end read or a read whose mate did not map. Each read has a library, a chromosome, a position, a CIGAR string, a strand and base qualities.
The unclipped 5' end of a read is the reference position where its first sequenced base would lie if the clipped bases were aligned: for a forward read, POS minus the length of the leading soft and hard clips; for a reverse read, POS plus the reference span minus 1, plus the length of the trailing clips. The end key of a read is (library, chromosome, unclipped 5' end, strand). The score of a read is the sum of its base qualities that are at least 15, capped at 16383, and the score of a template is the sum over its reads.
Output. The set of templates to mark:
- a pair is marked if another pair has the same two end keys and a higher score;
- a fragment is marked if a pair has an end at its end key, or if another fragment has the same end key and a higher score.
Ties in the score go to the template that comes first in the input.
The algorithm
MARK-DUPLICATES(T_1, ..., T_n)- 1
P ← empty map; F ← empty map; E ← empty set - 2
for i ← 1 to n do - 3
if T_i is a pair (r, r') then append i to P[sorted(key(r), key(r'))]; add key(r) and key(r') to E - 4
else append i to F[key(r)] for the read r of T_i - 5
D ← empty set - 6
for each list S in P do add to D every index of S except the one of largest (score, -index) - 7
for each key k with list S in F do - 8
if k ∈ E then add every index of S to D - 9
else add to D every index of S except the one of largest (score, -index) - 10
return D
Line L3 sorts the two end keys, so that the order of the mates in the input does not matter. The set collects every end of every pair, which line L8 needs to mark the fragments that sit on a pair end. Lines L6 and L9 keep the one template of largest rank , which is unique because no two templates have the same index.
Example
Eight templates, all on chromosome 1 and in library L1 unless said otherwise, with reads of 10 bases.
| template | reads (POS, CIGAR, strand, qualities) | end keys | score |
|---|---|---|---|
| a | (100, 10M, +, ten Q30), (290, 10M, -, ten Q30) | 100+, 299- | 600 |
| b | (102, 2S8M, +, nine Q30 and one Q10), (290, 10M, -, ten Q30) | 100+, 299- | 570 |
| c | (100, 10M, +, ten Q30), (291, 10M, -, ten Q30) | 100+, 300- | 600 |
| d | (100, 10M, +, ten Q30) | 100+ | 300 |
| e | (500, 10M, +, ten Q20) | 500+ | 200 |
| f | (500, 10M, +, ten Q40) | 500+ | 400 |
| g | (500, 10M, -, ten Q40) | 509- | 400 |
| h | (100, 10M, +, ten Q30), library L2 | 100+ in L2 | 300 |
The first read of b starts at 102 after 2 soft-clipped bases, so its unclipped 5' end is 100, the same as that of a. The reverse reads at 290 with 10M end at 299, which is their 5' end. The Q10 base of b does not count in its score.
- Line L6 groups a and b, which have the ends 100+ and 299-, and marks b, the one of lower score. Pair c differs in one end, 300- instead of 299-, so it is alone and kept.
- Line L8 marks fragment d, because 100+ is an end of pairs a and c.
- Line L9 groups e and f at 500+ and marks e. Fragment g is on the other strand, with the 5' end 509-, and h is in another library, so both are kept.
The marked set is .
Correctness
Line L3 sends two pairs to the same list exactly when they have the same multiset of two end keys, because two multisets of two elements are equal exactly when their sorted tuples are. Line L4 sends two fragments to the same list exactly when they have the same end key, and ends up as the set of all pair ends. In each list, lines L6 and L9 keep only the template of largest rank, so a template is marked exactly when another template of its list ranks higher, which is the rule for pairs and for fragments that sit on no pair end. Line L8 marks every fragment on a pair end. The proof also shows that the unclipped 5' end computed from POS and the CIGAR string is the one of the definition. The full proof is in proofs/correctness.md.
Proof: Duplicate marking returns exactly the duplicates of the definitionfull
Positions are 1-based, as in SAM. The input is a list of templates . A template is a pair (two mapped reads) or a fragment (one mapped read). Each read has a library, a chromosome, a leftmost mapped position, a CIGAR string, a strand and a list of base qualities.
Definitions
Unclipped 5' end. For a forward read, the 5' end is the leftmost base. Its unclipped position is , where is the total length of the soft and hard clips (S and H) at the start of the CIGAR string. For a reverse read, the 5' end is the rightmost base. Its unclipped position is , where span is the total length of the CIGAR operations that consume the reference (M, D, N, = and X) and is the total length of the clips at the end of the CIGAR string. In both cases this is where the 5' end of the read would lie if the clipped bases were aligned without gaps next to the aligned ones.
End key. .
Score and rank. The score of a read is the sum of its base qualities that are at least 15, capped at 16383. The score of template is the sum over its reads. The rank of is the pair , compared in lexicographic order. Two different templates never have the same rank, so every non-empty set of templates has exactly one template of largest rank.
Duplicates. For a pair with reads , let be the multiset . Let be the set of all end keys of all pairs.
- A pair is a duplicate if there is a pair , , with and a larger rank.
- A fragment with read is a duplicate if , or if there is a fragment , , with read such that and a larger rank.
This is the rule of Picard MarkDuplicates, without optical duplicates. In words: in each set of pairs with the same two ends, all but the best are duplicates; a fragment is a duplicate of any pair with an end at its place; among the fragments with the same end and no pair there, all but the best are duplicates.
Proof
Lemma 1. The function unclipped_five_prime returns the unclipped 5' position of the definition.
Proof. For a forward read, the first loop adds up the lengths of the leading operations while they are S or H and stops at the first other operation, which is . For a reverse read, the sum of the lengths of the operations in M, D, N, = and X is the span, and the second loop adds the lengths of the trailing S and H operations, which is . The function returns the two formulas.
Lemma 2. After the loop of lines L2 to L4, the dictionary pairs maps each multiset that occurs to the list of the pairs with . The dictionary frags maps each end key that occurs to the list of the fragments whose read has end key . The set pair_ends is .
Proof. Line L3 sends each pair to the key made by sorting its two end keys. Two multisets of two elements are equal exactly when their sorted tuples are equal, so the pairs with the same key are exactly those with the same , whatever the order of the two mates in the template. Line L4 sends each fragment to its end key. Each template is visited once, so each list holds each matching template exactly once. Each pair adds both of its end keys to pair_ends, and nothing else is added.
Lemma 3. _best returns the template of largest rank in a group.
Proof. It takes the maximum of the group under the key , which is the rank. The maximum is unique, because the second component differs for different templates.
Theorem. mark_duplicates returns exactly the set of duplicates of the definition.
Proof. Take a pair . By Lemma 2 its group in pairs is the set of pairs with , and is in it. Line L6 marks every member of the group except the one of largest rank (Lemma 3). So is marked exactly when some other pair with has a larger rank, which is the definition. Pairs are not touched by the fragment loop.
Take a fragment with read . By Lemma 2 its group in frags is the set of fragments with end key . If , line L8 marks the whole group, included, which agrees with the first clause of the definition. Otherwise line L9 marks all members of the group but the one of largest rank, and is marked exactly when another fragment with the same end key has a larger rank, which is the second clause. Fragments are not touched by the pair loop.
Independence of the input order of the mates. The result does not depend on which read of a pair comes first, by the sorting in line L3. It depends on the order of the templates only through the tie rule : if two templates have the same score and the same key, the one that comes first is kept. Picard breaks such ties in its own way, so in a tie the code can keep a different template than Picard, but it marks the same number of templates.
Cost
Let be the total number of bases and CIGAR operations of all reads. Computing all the scores and end keys costs . With hash tables, the grouping of lines L2 to L4 costs expected time, and lines L5 to L9 touch each template a constant number of times, so the expected time is and the extra space is . Picard sorts the read ends instead of hashing them, which costs comparisons and lets it spill to disk when the ends do not fit in memory.
Complexity
- Time. Computing the end keys and the scores reads every base quality and every CIGAR operation once, which is . With hash maps, lines L2 to L4 take expected time and lines L5 to L9 touch each template a constant number of times, so the total is expected. Picard sorts the read ends instead, in comparisons, which also works when the ends do not fit in memory, by sorting on disk.
- Space. for the keys and the lists. A version that streams a coordinate-sorted file needs to keep only the templates whose first end is at the current position and the mates still to come, which is much less than in practice.
- Chance duplicates. For single-end reads on a genome of length , a read shares its 5' end and strand with at least one other read by chance with probability about . At 30x coverage with reads of 100 bases, and the probability is 13.9%, so single-end marking at high depth also marks many reads that are not copies. For pairs with an insert size of standard deviation 30, at the same depth, the chance that both ends match is about 0.07%.
Properties
- Exact for its rule. It returns exactly the set of the rule above. The rule is a model of what a copy looks like; it is not certain that two marked reads are copies or that two kept reads are not.
- Deterministic. The tie rule makes the output a function of the input order. Picard has its own tie rule, so in a tie it can keep another template of the group, but it marks the same number.
- Independent of the mate order. Swapping the two reads of a pair does not change the result.
- Marking, not removing. The output is a set of flags. Callers and coverage tools skip reads with flag 0x400 by default, and the reads stay in the file for other uses.
Variants and improvements
- Optical duplicates. Picard also looks at the tile and the x and y coordinates of the cluster, which it reads from the read names. Duplicates in one group whose clusters lie within a set pixel distance of each other are counted as optical, and the count goes into the metrics file. The default distance is 100; the documentation suggests 2500 for patterned flow cells. The code of this page leaves optical duplicates out.
- Read groups and libraries. Duplicates are only looked for within a library, because two libraries come from separate PCR reactions.
- Other scores. Besides the sum of base qualities, htsjdk has a strategy by the total mapped reference length and a random one.
- Unique molecular identifiers. If each fragment carries a random barcode before PCR, reads with the same positions but different barcodes come from different fragments. UMI deduplication groups by position and barcode, and allows for errors in the barcode.
- samtools markdup. A second widely used tool, which works on a coordinate-sorted file after
samtools fixmatehas added the mate information to each record. - Library size estimate. From the number of duplicates, Picard estimates how many distinct fragments the library holds, with a model in the spirit of the Lander-Waterman model.
When to use it
Use it on whole-genome and exome data before base quality score recalibration and variant calling, as in the GATK pipeline of DePristo et al. (2011). Skip it, or use UMIs, for amplicon sequencing, where all reads of one target start at the same primer and are duplicates by the rule without being PCR copies of one fragment. For PCR-free libraries the rule still finds optical duplicates. For RNA sequencing of highly expressed genes, reads pile up by chance, so many marked reads are not copies; count them with care.
Pitfalls
- Removing instead of marking. The alias "PCR duplicate removal" describes an older practice. The method marks reads, both PCR and optical copies, and the user may remove them.
- Clipped reads. Grouping by POS instead of the unclipped 5' end misses copies where one read has a soft clip that the other lacks, as with template b of the example.
- Reverse strand. The 5' end of a reverse read is its rightmost base, not POS. Using POS for both strands groups the wrong reads.
- Single-end data at high depth. At high coverage many independent reads share a 5' end by chance, as computed above. Marking them lowers the depth and the power to call variants, with no gain.
- Secondary and supplementary records. They carry the duplicate flag of their primary record; they must not be scored as templates of their own.
- Multiple libraries in one read group. If the library field is wrong, reads from separate libraries are compared, and real distinct fragments are marked.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/duplicate-read-marking/. The authors are listed in prov/398WVT.jsonl.
"""Duplicate marking of mapped reads by the rule of Picard MarkDuplicates.
A Read is one mapped read: library, chrom, pos (1-based leftmost mapped
reference base, as in SAM), cigar, reverse (True for the reverse strand) and
quals (the Phred base qualities). A template is a tuple of one Read (a
fragment: a single-end read, or a pair whose mate did not map) or two Reads
(a pair with both mates mapped).
Two pairs are duplicates when they have the same library and the same
unclipped 5' end, chromosome and strand for both mates. A fragment is a
duplicate of another fragment with the same end, and of every pair with an
end at that place. In each group the template with the highest score is
kept; the score of a read is the sum of its base qualities of at least 15,
capped at 16383, and the score of a pair is the sum over its two reads. Ties
go to the template that comes first in the input.
Left out: optical duplicates (Picard looks at tile and pixel coordinates of
the read names), the large score discount for reads that fail vendor
checks, and the secondary and supplementary records.
"""
from __future__ import annotations
import re
from collections import namedtuple
from typing import Dict, List, Sequence, Set, Tuple
Read = namedtuple("Read", ["library", "chrom", "pos", "cigar", "reverse", "quals"])
_CIGAR = re.compile(r"(\d+)([MIDNSHP=X])")
_REF_OPS = set("MDN=X")
def parse_cigar(cigar: str) -> List[Tuple[int, str]]:
ops = [(int(n), op) for n, op in _CIGAR.findall(cigar)]
if "".join(f"{n}{op}" for n, op in ops) != cigar or not ops:
raise ValueError(f"bad CIGAR {cigar!r}")
return ops
def unclipped_five_prime(r: Read) -> int:
"""The 1-based reference position of the 5' end of the read, with clipped bases put back."""
ops = parse_cigar(r.cigar)
if not r.reverse:
lead = 0
for n, op in ops:
if op not in "SH":
break
lead += n
return r.pos - lead
span = sum(n for n, op in ops if op in _REF_OPS)
trail = 0
for n, op in reversed(ops):
if op not in "SH":
break
trail += n
return r.pos + span - 1 + trail
def end_key(r: Read) -> Tuple:
return (r.library, r.chrom, unclipped_five_prime(r), r.reverse)
def read_score(r: Read) -> int:
return min(sum(q for q in r.quals if q >= 15), 16383)
def score(t: Sequence[Read]) -> int:
return sum(read_score(r) for r in t)
def _best(group: List[int], scores: List[int]) -> int:
return max(group, key=lambda i: (scores[i], -i))
def mark_duplicates(templates: Sequence[Sequence[Read]]) -> Set[int]:
"""The set of indices of the templates that are marked as duplicates."""
pairs: Dict[Tuple, List[int]] = {} # @line L1
frags: Dict[Tuple, List[int]] = {}
pair_ends: Set[Tuple] = set()
scores = [score(t) for t in templates]
for i, t in enumerate(templates): # @line L2
if len(t) == 2: # @line L3
e1, e2 = end_key(t[0]), end_key(t[1])
pairs.setdefault(tuple(sorted((e1, e2))), []).append(i)
pair_ends.update((e1, e2))
elif len(t) == 1:
frags.setdefault(end_key(t[0]), []).append(i) # @line L4
else:
raise ValueError("a template has one or two reads")
dups: Set[int] = set() # @line L5
for group in pairs.values(): # @line L6
keep = _best(group, scores)
dups.update(i for i in group if i != keep)
for key, group in frags.items(): # @line L7
if key in pair_ends: # @line L8
dups.update(group)
else: # @line L9
keep = _best(group, scores)
dups.update(i for i in group if i != keep)
return dups # @line L10
test_duplicate_read_marking.py 101 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/duplicate-read-marking/. The authors are listed in prov/398WVT.jsonl.
import os
import random
import pytest
from duplicate_read_marking import Read, mark_duplicates, read_score, unclipped_five_prime
def rd(pos, cigar, reverse, quals, chrom="chr1", library="L1"):
return Read(library, chrom, pos, cigar, reverse, tuple(quals))
def brute_force(templates):
"""Compare every template with every other one, straight from the definition."""
def ends(t):
return sorted((r.library, r.chrom, unclipped_five_prime(r), r.reverse) for r in t)
def rank(i):
return (sum(read_score(r) for r in templates[i]), -i)
dups = set()
for i, t in enumerate(templates):
for j, u in enumerate(templates):
if i == j:
continue
if len(t) == 2 and len(u) == 2 and ends(t) == ends(u) and rank(j) > rank(i):
dups.add(i)
if len(t) == 1 and len(u) == 2 and ends(t)[0] in ends(u):
dups.add(i)
if len(t) == 1 and len(u) == 1 and ends(t) == ends(u) and rank(j) > rank(i):
dups.add(i)
return dups
def test_unclipped_five_prime():
# Forward read: the 5' end is the leftmost base, moved left by the leading clip.
assert unclipped_five_prime(rd(100, "10M", False, [30] * 10)) == 100
assert unclipped_five_prime(rd(100, "3S7M", False, [30] * 10)) == 97
assert unclipped_five_prime(rd(100, "2H3S7M", False, [30] * 10)) == 95
# Reverse read: the 5' end is the rightmost base, moved right by the trailing clip.
assert unclipped_five_prime(rd(100, "10M", True, [30] * 10)) == 109
assert unclipped_five_prime(rd(100, "4M2D4M2S", True, [30] * 10)) == 111
assert unclipped_five_prime(rd(100, "4M2I4M", True, [30] * 10)) == 107
assert unclipped_five_prime(rd(16, "6M14N5M", True, [30] * 11)) == 40
def test_page_example():
q = [30] * 10
a = (rd(100, "10M", False, q), rd(290, "10M", True, q))
b = (rd(102, "2S8M", False, [30] * 9 + [10]), rd(290, "10M", True, q)) # same ends, lower score
c = (rd(100, "10M", False, q), rd(291, "10M", True, q)) # mate end differs: not a duplicate
d = (rd(100, "10M", False, q),) # fragment on a pair end
e = (rd(500, "10M", False, [20] * 10),)
f = (rd(500, "10M", False, [40] * 10),)
g = (rd(500, "10M", True, [40] * 10),) # other strand
h = (rd(100, "10M", False, q, library="L2"),) # other library
ts = [a, b, c, d, e, f, g, h]
assert mark_duplicates(ts) == {1, 3, 4}
def test_scores_follow_picard():
assert read_score(rd(1, "4M", False, [40, 14, 15, 2])) == 55
assert read_score(rd(1, "500M", False, [40] * 500)) == 16383
# Equal scores: the first template in the input is kept.
t = (rd(7, "5M", False, [30] * 5),)
assert mark_duplicates([t, t, t]) == {1, 2}
def test_mate_order_does_not_matter():
q = [30] * 10
x = (rd(100, "10M", False, q), rd(290, "10M", True, q))
y = (rd(290, "10M", True, [20] * 10), rd(100, "10M", False, q))
assert mark_duplicates([x, y]) == {1}
def test_against_brute_force():
rng = random.Random(5)
cigars = ["10M", "2S8M", "8M2S", "1S8M1S", "4M1D6M", "4M1I5M", "3H10M"]
for _ in range(300):
ts = []
for _ in range(rng.randint(0, 14)):
def one():
return rd(rng.randint(100, 104), rng.choice(cigars), rng.random() < 0.5,
[rng.choice((2, 10, 14, 15, 30, 40)) for _ in range(10)],
chrom=rng.choice(("chr1", "chr1", "chr2")), library=rng.choice(("L1", "L1", "L2")))
ts.append((one(), one()) if rng.random() < 0.6 else (one(),))
assert mark_duplicates(ts) == brute_force(ts)
def test_errors():
with pytest.raises(ValueError):
mark_duplicates([()])
with pytest.raises(ValueError):
unclipped_five_prime(rd(1, "10Q", False, [30]))
if __name__ == "__main__":
raise SystemExit(pytest.main([os.path.abspath(__file__), "-q"]))
History
Duplicate reads were known from the first short-read projects. The SAMtools paper of Li et al. (2009) listed a command, rmdup, that removed potential PCR duplicates with the same outer coordinates. Picard MarkDuplicates, from the Broad Institute, marks instead of removing, scores reads by the sum of their base qualities and counts optical duplicates. It is the duplicate step of the GATK pipeline of DePristo et al. (2011).
References
- Picard MarkDuplicates, source and documentation in the class comment, master branch of the broadinstitute/picard repository, the class documentation (5' positions of both reads, ranking by the sum of base qualities, the 0x400 flag, optical duplicates, REMOVE_DUPLICATES) and the pass that marks pairs and then fragments
- htsjdk DuplicateScoringStrategy, master branch of the samtools/htsjdk repository, the method that sums the base qualities of at least 15 and caps the sum, and the list of scoring strategies
- Heng Li, Bob Handsaker, Alec Wysoker, Tim Fennell, Jue Ruan, Nils Homer, Gabor Marth, Goncalo Abecasis, Richard Durbin and 1000 Genome Project Data Processing Subgroup, The Sequence Alignment/Map format and SAMtools, Bioinformatics 25(16), 2009, pp. 2078 to 2079 (the SAMtools commands, among them the removal of potential PCR duplicates)
- Mark A. DePristo, Eric Banks, Ryan Poplin and others, A framework for variation discovery and genotyping using next-generation DNA sequencing data, Nature Genetics 43(5), 2011, pp. 491 to 498 (duplicate marking as a step of the data processing before variant discovery)
- The SAM/BAM Format Specification, version 1.6, hts-specs, Section 1.4, FLAG bit 0x400 (PCR or optical duplicate)
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 398WVT Edit this page History Report an error Markdown