Algorithmcore
UMI deduplication
Also called directional UMI network, UMI collapsing.
Count molecules, not reads, by grouping reads by cell and locus and merging UMIs one substitution apart when the count of one is at least about twice the other.
- Time
- O(n + m^2 l) worst
- Space
- O(m l) extra
- Where
- l = the UMI length; m = the number of distinct UMIs over all bundles; n = the number of reads
- Model
- Word RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Tom Smith, Andreas Heger, Ian Sudbery, 2017
UMI deduplication counts the molecules behind a set of sequencing reads. Before PCR, each cDNA molecule gets a short random tag, the unique molecular identifier (UMI). All PCR copies of a molecule then carry the same UMI and map to the same place, so the number of distinct UMIs at a locus estimates the number of molecules, not the number of copies. Errors in PCR and in sequencing change some UMIs, and each changed UMI looks like a new molecule. The directional method of UMI-tools (Smith, Heger and Sudbery 2017) joins a UMI to a neighbor that differs at one position when the neighbor has at least about twice as many reads, and it counts the groups that this makes. It is the default of UMI-tools and the method behind the cell by gene count matrices of single-cell RNA-seq. It differs from duplicate read marking, which has no UMIs and can use only the mapping position of each read.
In plain words
Each molecule gets a random name before it is copied many times. To count the molecules, count the names. The problem is that some copies get a misspelled name, and a misspelled name looks like a new molecule. A misspelling usually changes one letter, and it is usually rare: the true name has many reads, and the misspelled one has few. So link two names that differ in one letter when one of them has at least about twice as many reads. Start from the most common name, follow the links to the rarer names, and call everything you reach one molecule. Then take the most common name that is left and do the same. Two names that differ in one letter but have similar counts stay apart, because they are probably two real molecules.
The problem
Input. Reads , each with a cell barcode , a locus and a UMI , a string of length . For bulk data the locus is a mapping position and strand; for droplet single-cell data it is the gene that the read maps to. The reads with the same form a bundle, and is the number of reads with UMI in the bundle.
Output. For each bundle, an estimate of the number of distinct molecules, and a partition of its UMIs into groups, one group for each molecule, with the UMI that stands for it.
Model. Every molecule has its own UMI. A read shows the UMI of its molecule, or a copy with one or more substitutions. The task has no exact solution: two real molecules can have UMIs one letter apart, and an error can turn one UMI into another real one. The directional method is a heuristic for this model.
The algorithm
DIRECTIONAL-DEDUP(reads) ▷ reads: (cell, locus, UMI) triples- 1
n[b][u] ← the number of reads of bundle b = (cell, locus) with UMI u - 2
for each bundle b do - 3
U ← the UMIs of b by decreasing n[b][u], ties by the UMI string - 4
for each pair u, v of U with hamming(u, v) = 1 do - 5
add the arc u → v if n[b][u] ≥ 2 n[b][v] - 1 - 6
T ← ∅ ▷ the UMIs taken by earlier groups - 7
for each u in U, in order do - 8
if u ∈ T then skip u - 9
R ← the UMIs reached from u by breadth-first search along the arcs - 10
make R \ T a group with representative u; T ← T ∪ R - 11
molecules[b] ← the number of groups of b - 12
return molecules
Line L1 groups the reads into bundles. Lines L4 and L5 build the directed graph. The rule says that has at least about twice the reads of . For it allows , so two single reads one letter apart join in both directions. Lines L7 to L10 take the UMIs from the most common down. Each UMI that no earlier group holds starts a breadth-first search, and the UMIs it reaches that are still free form one group. Line L11 counts the groups.
UMI-tools has three other methods on the same graph of Hamming distance 1. "Unique" counts each distinct UMI as a molecule. "Cluster" counts the connected components of the undirected graph. "Adjacency" takes each component and removes, from the most common UMI down, the UMI and its direct neighbors, until the component is covered. The directional method lies between "cluster", which merges too much when UMIs are dense, and "unique", which keeps every error. The code has "unique", "cluster" and "directional".
Example
One bundle has six UMIs of length 4.
| UMI | reads | arcs out (line L5) |
|---|---|---|
| ACGT | 50 | ACGA, ACGC, TCGT |
| ACGA | 20 | ACGC |
| TCGA | 18 | TCGT |
| GGGG | 5 | none |
| ACGC | 2 | none |
| TCGT | 1 | none |
ACGT and ACGA differ at the last position, and , so there is an arc ACGT → ACGA. ACGA and TCGA also differ at one position, but and , so there is no arc in either direction. TCGT is one letter from both ACGT and TCGA, and both point to it.
The visit order is ACGT, ACGA, TCGA, GGGG, ACGC, TCGT. The search from ACGT reaches ACGA, ACGC and TCGT, which form the first group. ACGA is now taken. TCGA starts a search that reaches TCGT, but TCGT is taken, so the second group is TCGA alone. GGGG is the third group, and the last two UMIs are taken. The bundle has 3 molecules, with representatives ACGT, TCGA and GGGG.
The other methods give other counts. "Unique" gives 6. "Cluster" gives 2, because ACGA, TCGA and TCGT link ACGT and TCGA into one component, even though their counts of 50 and 18 suggest two molecules.
Correctness
The proof shows four facts. Counts never increase along an arc, and they stay equal only between two UMIs with one read each. The groups partition the UMIs of the bundle, and the UMI that starts a group has the highest count in it. The number of groups is at least the number of connected components and at most the number of distinct UMIs. Last, under a model of errors the method is exact: if the true UMIs differ pairwise in at least 4 positions, each other UMI is one substitution from a true UMI, and each true UMI has at least reads for each of its error UMIs with reads, then each group is one true UMI with its errors. A read with two errors is two positions from its UMI and is always counted as an extra molecule. On real data the count is an estimate, and the error rate it reaches is a measurement.
Proof: The directional method returns a partition between the connected components and the distinct UMIs, and it is exact when the errors are single substitutions of well separated UMIsfull
We prove what the directional method of UMI-tools computes on one bundle. Its groups partition the UMIs, the first UMI of each group has the highest count in the group (Lemma 2), and the number of groups lies between the number of connected components of the distance-1 graph and the number of distinct UMIs (Theorem 3). Under an explicit error model, single substitutions of true UMIs that are far apart, the groups are exactly the molecules (Theorem 4). Whether real data follow this model is not proved here; the tests measure the error on simulated reads.
Setting. One bundle has a set of distinct UMIs, all of length , and a count for each . Let be the Hamming distance. The directional graph has an arc when and (lines L4 and L5). Write when comes before in the visit order of line L3: decreasing count, then the UMI string. Let be the set of UMIs reachable from along arcs, with . Lines L6 to L10 visit ; when is not in (the set taken so far) they add the group and set .
Lemma 1 (counts along an arc). If is an arc, then , with equality only when . So does not increase along a path of .
Proof. , since . Equality needs and then .
Lemma 2 (partition and representative). The groups are non-empty, pairwise disjoint and cover . The UMI that starts a group is its first element in the visit order and has the highest count in it.
Proof. A group starts at only when , and , so is in its group and the group is not empty. Each group is and then grows by , so later groups avoid the UMIs of earlier groups. Every is either in when it is visited, so in an earlier group, or it starts a group, so the groups cover . Let be in the group of . By Lemma 1, . If , then was visited before , and at that moment was either in already or it started a group and entered . In both cases before is visited, which contradicts . So for each of the group.
The code writes each group in visit order, so group[0] is the starting UMI and the representative.
Theorem 3 (bounds). Let be the number of connected components of the undirected graph on with an edge when , and let be the number of directional groups. Then .
Proof. The bound follows from Lemma 2, because the groups are disjoint and non-empty. Every arc of is an edge of , so lies inside the component of , and so does each group. Take a component and let be its first UMI in the visit order. Every UMI visited before is in another component, so it reaches nothing in , and when is visited. So starts a group inside . Different components give different groups, so .
The "cluster" method returns the components and the "unique" method returns the UMIs, so the directional count always lies between the two. Both ends are reached: with no edges all three are equal, and on a path whose counts halve from one UMI to the next the directional method gives .
Theorem 4 (exact under single substitution errors). Let be the true UMIs of the molecules of the bundle, all distinct and all in , with for . Suppose that every other UMI has for some and . Then the directional groups are exactly the families , so .
Proof. The families cover , and they are disjoint because a UMI at distance 1 from and from would give . Two UMIs in different families are at distance at least by the triangle inequality, so every arc of joins two UMIs of one family, and for . Inside there is an arc for each error , by the assumption on the counts, so .
Let be the first UMI of in the visit order. No UMI of another family reaches , so starts a group, and the group is minus UMIs of other families, that is . If , the group is . Otherwise is an error with , and with Lemma 1 applied to the arc this gives . Then also holds, so there is an arc , and . In both cases the group of is . The first UMI of each family starts one group and the other UMIs of the family are then taken, so there are exactly groups.
The separation is a sufficient condition, not a necessary one. The point of the count rule shows when it fails: if and the two counts are similar, and , then there is no arc between them, while the cluster method joins them. A read with two errors is at distance 2 from its true UMI and is never joined, so it is counted as an extra molecule.
What the lines compute. Line L1 counts the reads of each UMI in each bundle. Line L3 is the visit order . Lines L4 and L5 build the arcs of , from the neighbors at distance 1. Lines L6 to L10 are the loop of the setting, with a breadth-first search for at line L9. Line L11 returns for each bundle, and line L12 returns all bundles.
Complexity. Comparing all pairs at line L4 takes time per bundle; looking up the substitution variants of each UMI in a hash table takes expected time. Each breadth-first search at line L9 is for arcs, and there are at most of them, so lines L6 to L10 are in the worst case. The sort is .
What the tests check. The test file compares the groups with a brute force that computes reachability by a transitive closure, checks that the two ways to find neighbors agree, and checks Lemma 1, Lemma 2 and Theorem 3 on random bundles. It checks the cluster method against a brute-force merge of sets, the page example, the case of two UMIs with count 1, and the bundle keys. Two simulations of PCR copies with 1 percent base errors measure the error of the three methods; these are measurements, not theorems.
Complexity
On a word RAM, line L1 takes expected time with a hash table. For a bundle with distinct UMIs, comparing all pairs at line L4 takes time. This is what UMI-tools does, and over all bundles it is at most . In place of the pairs, one can look up the substitution variants of each UMI in a hash table, in expected time; the code has both. Each search at line L9 takes time linear in the part of the graph it reaches, and in the worst case the searches together take . The extra space is for the counts and the arcs, since a UMI has at most neighbors over the alphabet ACGT.
Properties
- Deterministic. With the tie rule of line L3, the groups depend only on the counts.
- Between two simple methods. The count is never below the number of components and never above the number of distinct UMIs.
- The representative is the most common UMI of its group.
- One step at a time. An arc joins UMIs one substitution apart, and a path can join UMIs several substitutions apart, but only along falling counts.
- Local to a bundle. Bundles are independent, so they can run in parallel.
Variants and improvements
- Threshold. UMI-tools has an edit distance threshold, 1 by default. A larger threshold joins reads with two errors and also joins more real molecules.
- Adjacency method. Removes the most common UMI and its direct neighbors at each step. It does not follow paths of falling counts.
- Cell barcode correction. The same idea, a graph of one-letter differences weighted by counts, also corrects errors in cell barcodes. Tools such as UMI-tools whitelist and the 10x Genomics pipeline use a known list of barcodes for this.
- Gene as locus. For droplet data the bundle is (cell, gene) after the reads are assigned to genes, so reads of one molecule at different positions count once.
- Insertions and deletions. The Hamming distance sees only substitutions. An edit distance version finds UMIs with an indel, at a higher cost.
When to use it
Use it on any data with UMIs: droplet and plate single-cell RNA-seq, and UMI-tagged bulk or targeted sequencing. It is the default of UMI-tools, and pipelines for droplet data apply methods of the same kind. Without UMIs, use duplicate read marking by position, which cannot tell true duplicates from two molecules that start at the same place. When the number of molecules per bundle is close to the number of possible UMIs, , no method can separate the molecules well, and a longer UMI is the fix.
Pitfalls
- Short UMIs saturate. With many molecules and short UMIs, real UMIs are often one letter apart, and they are then merged when their counts differ by a factor of two or more. With 6-base UMIs and 150 molecules in one bundle this already costs about one molecule in ten.
- Errors with two substitutions stay separate and inflate the count.
- Different UMI lengths in one bundle give no Hamming distance; trim or split them first.
- Bundles must be right. Reads of one molecule that map to two positions, or to two genes, are counted twice. Reads of two molecules in one bundle with equal UMIs are counted once.
- Counts of 1. Two UMIs with one read each and one letter apart join in both directions, so the result for them depends on the tie rule.
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
# Shared helper of the biology pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small DNA utilities shared by the biology pages.
Conventions:
- DNA is a str over "ACGT", written 5' to 3'. Positions are 0-based.
- Random draws use a random.Random object that the caller passes in, and the
order of the draws is fixed and written in each docstring, so that a seed
gives the same output on every run.
- Alignment scores are added: pass match as a positive number and mismatch and
gap as negative numbers. A CIGAR string uses M (a column with a base of both
strings, equal or not), I (a base of a, the query, against a gap) and D (a
base of b, the reference, against a gap).
This module holds no algorithm of a page: no ORF finder, no motif finder and
no caller. The functions are building blocks for the page code and its tests.
"""
from __future__ import annotations
import math
import random
from collections import namedtuple
from typing import Dict, List, Sequence, Tuple, Union
DNA = "ACGT"
_COMPLEMENT = {"A": "T", "C": "G", "G": "C", "T": "A", "N": "N",
"a": "t", "c": "g", "g": "c", "t": "a", "n": "n"}
def revcomp(seq: str) -> str:
"""The reverse complement of seq. N maps to N; other letters raise KeyError."""
return "".join(_COMPLEMENT[c] for c in reversed(seq))
# NCBI genetic code table 1 (the standard code), in the TCAG order of the NCBI
# listing: the first base changes slowest and the third base fastest.
_AAS = "FFLLSSSSYY**CC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG"
_ORDER = "TCAG"
CODON_TABLE: Dict[str, str] = {
a + b + c: _AAS[16 * i + 4 * j + k]
for i, a in enumerate(_ORDER)
for j, b in enumerate(_ORDER)
for k, c in enumerate(_ORDER)
}
STOPS = frozenset(c for c, aa in CODON_TABLE.items() if aa == "*")
def translate(seq: str, frame: int = 0) -> str:
"""Translate seq[frame:] codon by codon with CODON_TABLE.
frame is 0, 1 or 2. A stop codon gives "*", a codon with a letter other than
A, C, G or T gives "X", and a last part shorter than three bases is dropped.
The function does not look for start or stop codons.
"""
if frame not in (0, 1, 2):
raise ValueError("frame must be 0, 1 or 2")
s = seq.upper()
out = []
for i in range(frame, len(s) - 2, 3):
out.append(CODON_TABLE.get(s[i:i + 3], "X"))
return "".join(out)
def random_dna(rng: random.Random, n: int, gc: float = 0.5) -> str:
"""n random bases, independent, with P(G) = P(C) = gc/2 and P(A) = P(T) = (1 - gc)/2.
Draw order: one rng.random() per base, from left to right.
"""
if not 0.0 <= gc <= 1.0:
raise ValueError("gc must be in [0, 1]")
half_gc, cut = gc / 2.0, gc + (1.0 - gc) / 2.0
out = []
for _ in range(n):
u = rng.random()
if u < half_gc:
out.append("C")
elif u < gc:
out.append("G")
elif u < cut:
out.append("A")
else:
out.append("T")
return "".join(out)
def _other_base(rng: random.Random, base: str) -> str:
"""A base other than base, uniform among the other three (one rng.choice)."""
return rng.choice([b for b in DNA if b != base])
def mutate(rng: random.Random, seq: str, rate: float) -> str:
"""Substitute each base with probability rate, uniformly by one of the other three.
Draw order: for each position from left to right, one rng.random(); if it is
below rate, one rng.choice for the new base. Letters other than A, C, G and T
are kept and use no draw. No insertions or deletions.
"""
out = []
for c in seq:
if c in DNA and rng.random() < rate:
out.append(_other_base(rng, c))
else:
out.append(c)
return "".join(out)
SimRead = namedtuple("SimRead", ["read", "pos", "strand", "true_seq"])
def simulate_reads(rng: random.Random, genome: str, n: int, length: int,
error_rate: float) -> List[SimRead]:
"""n single-end reads of the given length from both strands of genome.
Each item is SimRead(read, pos, strand, true_seq): pos is the 0-based start
of the read on the forward strand of genome, strand is "+" or "-", true_seq
is the error-free read (genome[pos:pos + length], or its reverse complement
for "-"), and read is true_seq with substitution errors at rate error_rate.
Draw order for each read: rng.randrange(len(genome) - length + 1) for pos,
then rng.random() < 0.5 for the "+" strand, then the draws of mutate on
true_seq.
"""
if length > len(genome) or length <= 0:
raise ValueError("need 0 < length <= len(genome)")
reads = []
for _ in range(n):
pos = rng.randrange(len(genome) - length + 1)
strand = "+" if rng.random() < 0.5 else "-"
frag = genome[pos:pos + length]
true_seq = frag if strand == "+" else revcomp(frag)
reads.append(SimRead(mutate(rng, true_seq, error_rate), pos, strand, true_seq))
return reads
def phred_to_prob(q: float) -> float:
"""Error probability of the Phred score q: p = 10^(-q/10)."""
return 10.0 ** (-q / 10.0)
def prob_to_phred(p: float) -> float:
"""Phred score of the error probability p in (0, 1]: Q = -10 log10(p)."""
if not 0.0 < p <= 1.0:
raise ValueError("p must be in (0, 1]")
return -10.0 * math.log10(p)
def hamming(a: Sequence, b: Sequence) -> int:
"""The number of positions where a and b differ; they must have the same length."""
if len(a) != len(b):
raise ValueError("hamming needs sequences of equal length")
return sum(1 for x, y in zip(a, b) if x != y)
def kmers(seq: str, k: int) -> List[str]:
"""All len(seq) - k + 1 substrings of length k, from left to right (with repeats)."""
if k <= 0:
raise ValueError("k must be positive")
return [seq[i:i + k] for i in range(len(seq) - k + 1)]
def gc_content(seq: str) -> float:
"""The fraction of G and C letters in seq (upper or lower case); 0.0 for an empty seq."""
if not seq:
return 0.0
s = seq.upper()
return (s.count("G") + s.count("C")) / len(s)
Number = Union[int, float]
def _cigar(ops: List[str]) -> str:
"""Run-length code a list of single-letter operations, for example MMMID to 3M1I1D."""
out = []
i = 0
while i < len(ops):
j = i
while j < len(ops) and ops[j] == ops[i]:
j += 1
out.append(f"{j - i}{ops[i]}")
i = j
return "".join(out)
def _fill(a: str, b: str, match: Number, mismatch: Number, gap: Number, free_b_ends: bool):
"""The dynamic programming table of a linear gap alignment of a and b."""
n, m = len(a), len(b)
S = [[0] * (m + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
S[i][0] = i * gap
for j in range(1, m + 1):
S[0][j] = 0 if free_b_ends else j * gap
for i in range(1, n + 1):
ai = a[i - 1]
row, up = S[i], S[i - 1]
for j in range(1, m + 1):
diag = up[j - 1] + (match if ai == b[j - 1] else mismatch)
row[j] = max(diag, up[j] + gap, row[j - 1] + gap)
return S
def _trace(S, a: str, b: str, i: int, j: int, match: Number, mismatch: Number,
gap: Number, free_b_ends: bool) -> Tuple[List[str], int]:
"""Trace back from cell (i, j); prefer M, then I, then D. Returns the ops and the start in b."""
ops: List[str] = []
while i > 0 or (j > 0 and not free_b_ends):
if i > 0 and j > 0 and S[i][j] == S[i - 1][j - 1] + (match if a[i - 1] == b[j - 1] else mismatch):
ops.append("M")
i, j = i - 1, j - 1
elif i > 0 and S[i][j] == S[i - 1][j] + gap:
ops.append("I")
i -= 1
else:
ops.append("D")
j -= 1
ops.reverse()
return ops, j
def global_align(a: str, b: str, match: Number = 1, mismatch: Number = -1,
gap: Number = -1) -> Tuple[Number, str]:
"""Needleman-Wunsch alignment of all of a with all of b, with linear gaps.
Returns (score, cigar). The cigar uses M, I (a base of a only) and D (a base of
b only); an empty alignment gives "".
"""
S = _fill(a, b, match, mismatch, gap, False)
ops, _ = _trace(S, a, b, len(a), len(b), match, mismatch, gap, False)
return S[len(a)][len(b)], _cigar(ops)
def semiglobal_align(a: str, b: str, match: Number = 1, mismatch: Number = -1,
gap: Number = -1, with_start: bool = False):
"""Align all of a (the query) to a substring of b (the reference), with linear gaps.
Bases of b before and after the aligned part cost nothing and are not in the
cigar, as in SAM. Returns (score, cigar), or (score, cigar, start) with
with_start=True, where start is the 0-based position in b of the first
reference base of the alignment. Among best end columns the leftmost wins.
"""
S = _fill(a, b, match, mismatch, gap, True)
n = len(a)
best_j = max(range(len(b) + 1), key=lambda j: (S[n][j], -j))
ops, start = _trace(S, a, b, n, best_j, match, mismatch, gap, True)
if with_start:
return S[n][best_j], _cigar(ops), start
return S[n][best_j], _cigar(ops)
umi_deduplication.py 164 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/umi-deduplication/. The authors are listed in prov/5HMHYS.jsonl.
"""UMI deduplication with the directional network method of UMI-tools.
Smith, Heger and Sudbery (2017), Genome Research 27(3), 491-499.
A read is a tuple (cell, locus, umi). The locus is a mapping position and
strand for bulk data, or a gene for droplet single-cell data. Reads with the
same cell and locus form one bundle. In one bundle, n[u] is the number of
reads with UMI u. The directional graph has an edge u -> v when the UMIs u and
v differ at exactly one position and n[u] >= 2 n[v] - 1. The UMIs are visited
in order of decreasing count (ties by the UMI string). Each UMI that no earlier
search has reached starts a breadth-first search along the edges; the UMIs it
reaches and that are not yet taken form one group. Each group is one molecule,
and its first UMI (the one with the highest count) represents it.
Two simpler methods are here for comparison: "unique" (each distinct UMI is a
molecule) and "cluster" (each connected component of the undirected graph of
Hamming distance 1 is a molecule).
"""
from __future__ import annotations
from collections import defaultdict, deque
from typing import Dict, Hashable, Iterable, List, Sequence, Tuple
from bioseq import hamming
ALPHABET = "ACGTN"
def bundle_counts(reads: Iterable[Tuple[Hashable, Hashable, str]]) -> Dict[tuple, Dict[str, int]]:
"""The read count of each UMI in each bundle (cell, locus)."""
out: Dict[tuple, Dict[str, int]] = defaultdict(lambda: defaultdict(int))
for cell, locus, umi in reads:
out[(cell, locus)][umi] += 1 # @line L1
return {k: dict(v) for k, v in out.items()}
def visit_order(counts: Dict[str, int]) -> List[str]:
"""The UMIs by decreasing count; equal counts in the order of the UMI string."""
return sorted(counts, key=lambda u: (-counts[u], u)) # @line L3
def neighbors_pairs(counts: Dict[str, int]) -> Dict[str, List[str]]:
"""For each UMI, the UMIs at Hamming distance 1, by comparing all pairs (as UMI-tools)."""
umis = visit_order(counts)
lengths = {len(u) for u in umis}
if len(lengths) > 1:
raise ValueError("all UMIs of a bundle must have the same length")
nb: Dict[str, List[str]] = {u: [] for u in umis}
for i, u in enumerate(umis):
for v in umis[i + 1:]:
if hamming(u, v) == 1:
nb[u].append(v)
nb[v].append(u)
return nb
def neighbors_hash(counts: Dict[str, int]) -> Dict[str, List[str]]:
"""The same neighbors, by looking up every one-substitution variant of each UMI."""
umis = visit_order(counts)
rank = {u: i for i, u in enumerate(umis)}
nb: Dict[str, List[str]] = {}
for u in umis:
found = []
for p in range(len(u)):
for b in ALPHABET:
if b != u[p]:
v = u[:p] + b + u[p + 1:]
if v in counts:
found.append(v)
found.sort(key=rank.__getitem__)
nb[u] = found
return nb
def directional_edges(counts: Dict[str, int], neighbors=neighbors_pairs) -> Dict[str, List[str]]:
"""The edges u -> v of the directional graph, in visit order."""
nb = neighbors(counts)
adj: Dict[str, List[str]] = {}
for u in visit_order(counts):
out = []
for v in nb[u]: # @line L4
if counts[u] >= 2 * counts[v] - 1: # @line L5
out.append(v)
adj[u] = out
return adj
def group_directional(counts: Dict[str, int], neighbors=neighbors_pairs) -> List[List[str]]:
"""The molecules of one bundle as lists of UMIs; the first UMI of a list represents it."""
adj = directional_edges(counts, neighbors)
taken = set() # @line L6
groups = []
for u in visit_order(counts): # @line L7
if u in taken: # @line L8
continue
reached, seen, queue = [], {u}, deque([u]) # @line L9
while queue:
x = queue.popleft()
reached.append(x)
for y in adj[x]:
if y not in seen:
seen.add(y)
queue.append(y)
group = [x for x in visit_order({x: counts[x] for x in reached}) if x not in taken] # @line L10
taken.update(group)
groups.append(group)
return groups
def group_cluster(counts: Dict[str, int], neighbors=neighbors_pairs) -> List[List[str]]:
"""Connected components of the undirected graph of Hamming distance 1."""
nb = neighbors(counts)
taken, groups = set(), []
for u in visit_order(counts):
if u in taken:
continue
comp, queue = [], deque([u])
taken.add(u)
while queue:
x = queue.popleft()
comp.append(x)
for y in nb[x]:
if y not in taken:
taken.add(y)
queue.append(y)
groups.append(visit_order({x: counts[x] for x in comp}))
return groups
def group_unique(counts: Dict[str, int]) -> List[List[str]]:
"""Each distinct UMI is one molecule."""
return [[u] for u in visit_order(counts)]
METHODS = {"directional": group_directional, "cluster": group_cluster, "unique": group_unique}
def count_molecules(reads: Iterable[Tuple[Hashable, Hashable, str]],
method: str = "directional") -> Dict[tuple, int]:
"""The number of molecules of each bundle (cell, locus)."""
if method not in METHODS:
raise ValueError(f"unknown method {method!r}")
out = {}
for key, counts in bundle_counts(reads).items(): # @line L2
out[key] = len(METHODS[method](counts)) # @line L11
return out # @line L12
def deduplicate(reads: Sequence[Tuple[Hashable, Hashable, str]],
method: str = "directional") -> List[int]:
"""The indices of the reads to keep: one read per molecule, with the UMI that represents it."""
groups_of = {}
for key, counts in bundle_counts(reads).items():
groups_of[key] = {g[0] for g in METHODS[method](counts)}
keep, done = [], set()
for i, (cell, locus, umi) in enumerate(reads):
key = (cell, locus)
if umi in groups_of[key] and (key, umi) not in done:
done.add((key, umi))
keep.append(i)
return keep
test_umi_deduplication.py 211 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/umi-deduplication/. The authors are listed in prov/5HMHYS.jsonl.
import random
import pytest
from bioseq import hamming, mutate, random_dna
from umi_deduplication import (
count_molecules,
deduplicate,
directional_edges,
group_cluster,
group_directional,
group_unique,
neighbors_hash,
neighbors_pairs,
)
PAGE = {"ACGT": 50, "ACGA": 20, "ACGC": 2, "TCGA": 18, "TCGT": 1, "GGGG": 5}
def random_bundle(rng, n_umis, length, alphabet="ACGT"):
"""Random UMIs that are close to each other, so that the graph has many edges."""
base = "".join(rng.choice(alphabet) for _ in range(length))
counts = {}
while len(counts) < n_umis:
u = list(base)
for _ in range(rng.randint(0, 2)):
u[rng.randrange(length)] = rng.choice(alphabet)
counts["".join(u)] = rng.choice([1, 1, 2, 3, 5, 8, 20, 60])
return counts
def brute_force_directional(counts):
"""Reachability by a transitive closure of the edge matrix, then the greedy assignment."""
umis = sorted(counts, key=lambda u: (-counts[u], u))
n = len(umis)
reach = [[i == j or (hamming(umis[i], umis[j]) == 1 and counts[umis[i]] >= 2 * counts[umis[j]] - 1)
for j in range(n)] for i in range(n)]
for k in range(n):
for i in range(n):
if reach[i][k]:
for j in range(n):
if reach[k][j]:
reach[i][j] = True
taken, groups = set(), []
for i in range(n):
if i in taken:
continue
group = [j for j in range(n) if reach[i][j] and j not in taken]
taken.update(group)
groups.append([umis[j] for j in group])
return groups
def components_brute(counts):
"""Connected components of the undirected distance-1 graph, by repeated merging of sets."""
sets = [{u} for u in counts]
merged = True
while merged:
merged = False
for a in range(len(sets)):
for b in range(a + 1, len(sets)):
if any(hamming(x, y) == 1 for x in sets[a] for y in sets[b]):
sets[a] |= sets.pop(b)
merged = True
break
if merged:
break
return sorted(sorted(s) for s in sets)
def test_page_example():
assert directional_edges(PAGE) == {
"ACGT": ["ACGA", "ACGC", "TCGT"], "ACGA": ["ACGC"], "TCGA": ["TCGT"],
"GGGG": [], "ACGC": [], "TCGT": []}
assert group_directional(PAGE) == [["ACGT", "ACGA", "ACGC", "TCGT"], ["TCGA"], ["GGGG"]]
assert len(group_cluster(PAGE)) == 2
assert len(group_unique(PAGE)) == 6
def test_against_brute_force():
rng = random.Random(11)
for _ in range(300):
counts = random_bundle(rng, rng.randint(1, 12), rng.randint(3, 6))
assert group_directional(counts) == brute_force_directional(counts)
def test_neighbor_methods_agree():
rng = random.Random(12)
for _ in range(200):
counts = random_bundle(rng, rng.randint(1, 15), rng.randint(3, 7), alphabet="ACGTN")
assert neighbors_hash(counts) == neighbors_pairs(counts)
assert group_directional(counts, neighbors_hash) == group_directional(counts)
def test_partition_and_representative():
rng = random.Random(13)
for _ in range(300):
counts = random_bundle(rng, rng.randint(1, 15), rng.randint(3, 6))
groups = group_directional(counts)
flat = [u for g in groups for u in g]
assert sorted(flat) == sorted(counts)
for g in groups:
assert counts[g[0]] == max(counts[u] for u in g)
def test_counts_never_increase_along_an_edge():
rng = random.Random(14)
for _ in range(300):
counts = random_bundle(rng, rng.randint(1, 15), rng.randint(3, 6))
for u, out in directional_edges(counts).items():
for v in out:
assert hamming(u, v) == 1
assert counts[u] >= counts[v]
if counts[u] == counts[v]:
assert counts[u] == 1
def test_cluster_is_connected_components():
rng = random.Random(15)
for _ in range(150):
counts = random_bundle(rng, rng.randint(1, 10), rng.randint(3, 6))
assert sorted(sorted(g) for g in group_cluster(counts)) == components_brute(counts)
def test_bounds_between_cluster_and_unique():
rng = random.Random(16)
for _ in range(300):
counts = random_bundle(rng, rng.randint(1, 15), rng.randint(3, 6))
c, d, u = len(group_cluster(counts)), len(group_directional(counts)), len(group_unique(counts))
assert c <= d <= u
def test_every_directional_group_is_inside_one_component():
rng = random.Random(17)
for _ in range(200):
counts = random_bundle(rng, rng.randint(1, 15), rng.randint(3, 6))
comp_of = {u: i for i, g in enumerate(group_cluster(counts)) for u in g}
for g in group_directional(counts):
assert len({comp_of[u] for u in g}) == 1
def test_far_apart_umis_are_all_kept():
counts = {"AAAAAA": 9, "CCCCCC": 9, "GGGGGG": 1, "TTTTTT": 30}
assert len(group_directional(counts)) == 4
assert len(group_cluster(counts)) == 4
def test_two_singletons_join_in_both_directions():
counts = {"AAAA": 1, "AAAC": 1}
assert directional_edges(counts) == {"AAAA": ["AAAC"], "AAAC": ["AAAA"]}
assert group_directional(counts) == [["AAAA", "AAAC"]]
counts = {"AAAA": 2, "AAAC": 2}
assert len(group_directional(counts)) == 2
def test_bundles_are_separate_and_dedup_keeps_one_read_per_molecule():
reads = [("c1", "g1", "ACGT")] * 5 + [("c1", "g1", "ACGA")] * 2 + [("c1", "g2", "ACGA")] * 3
reads += [("c2", "g1", "ACGA")] * 4 + [("c2", "g1", "TTTT")]
assert count_molecules(reads) == {("c1", "g1"): 1, ("c1", "g2"): 1, ("c2", "g1"): 2}
keep = deduplicate(reads)
assert [reads[i] for i in keep] == [("c1", "g1", "ACGT"), ("c1", "g2", "ACGA"),
("c2", "g1", "ACGA"), ("c2", "g1", "TTTT")]
def test_errors():
with pytest.raises(ValueError):
count_molecules([("c", "g", "ACGT")], method="best")
with pytest.raises(ValueError):
group_directional({"ACG": 1, "ACGT": 1})
def test_simulated_pcr_and_sequencing_errors_measured():
"""A measurement, not a theorem: 40 molecules, 5 to 40 reads each, 1 percent base errors."""
rng = random.Random(2017)
err = {"unique": 0, "cluster": 0, "directional": 0}
trials = 20
for _ in range(trials):
truth = set()
while len(truth) < 40:
truth.add(random_dna(rng, 10))
reads = []
for umi in sorted(truth):
for _ in range(rng.randint(5, 40)):
reads.append(("cell", "gene", mutate(rng, umi, 0.01)))
for m in err:
err[m] += abs(count_molecules(reads, m)[("cell", "gene")] - 40)
# About 0.4 percent of the reads carry two errors, so every method that joins only
# distance 1 keeps them as extra molecules; the measured excess is near 3 per bundle.
assert err["directional"] <= 0.15 * 40 * trials
assert err["directional"] * 10 < err["unique"]
def test_dense_umis_cluster_merges_distinct_molecules_measured():
"""A measurement: 150 molecules with 6-base UMIs, so true UMIs are often 1 apart."""
rng = random.Random(2016)
err = {"unique": 0, "cluster": 0, "directional": 0}
for _ in range(5):
truth = set()
while len(truth) < 150:
truth.add(random_dna(rng, 6))
reads = []
for umi in sorted(truth):
for _ in range(rng.randint(5, 40)):
reads.append(("cell", "gene", mutate(rng, umi, 0.01)))
for m in err:
err[m] += abs(count_molecules(reads, m)[("cell", "gene")] - 150)
assert err["directional"] * 4 < err["cluster"]
assert err["directional"] * 4 < err["unique"]
History
Kivioja et al. (2012) showed that random molecular labels attached before PCR let one count molecules in place of reads. Islam et al. (2014) used UMIs in single-cell RNA-seq, and droplet methods such as Drop-seq (Macosko et al. 2015) put a cell barcode and a UMI on every bead. Early tools counted distinct UMIs. Smith, Heger and Sudbery (2017) showed that errors in UMIs inflate these counts and proposed the network methods of UMI-tools, with the directional method as the default.
References
- Tom Smith, Andreas Heger and Ian Sudbery, UMI-tools, modeling sequencing errors in Unique Molecular Identifiers to improve quantification accuracy, Genome Research 27(3) (2017), 491-499, the unique, cluster, adjacency and directional methods, and the directional edge rule n(a) >= 2 n(b) - 1 at Hamming distance 1
- Teemu Kivioja et al., Counting absolute numbers of molecules using unique molecular identifiers, Nature Methods 9(1) (2012), 72-74, the use of random molecular labels to count molecules after PCR
- Saiful Islam et al., Quantitative single-cell RNA-seq with unique molecular identifiers, Nature Methods 11(2) (2014), 163-166, UMIs in single-cell RNA-seq
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 5HMHYS Edit this page History Report an error Markdown