Algorithmadvanced
Haplotype-based variant calling
Also called local reassembly variant calling, active region reassembly.
Assemble candidate haplotypes in an active region with a local de Bruijn graph, score reads against them with a pair HMM, then call genotypes.
- Solves
- Variant calling
- Time
- O(R H L n + R H^2 + R H V) worstO(L n) per_read_haplotype
- Space
- O(R H + L n) extra
- Where
- H = the number of candidate haplotypes; L = the read length; R = the number of reads; V = the number of candidate variants; n = the region length
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Erik Garrison, Gabor Marth, Ryan Poplin, Mark A. DePristo, 2012
A haplotype-based variant caller does not look at each column of the alignment on its own. In a short region where the reads suggest a variant, it builds the full sequences that the two copies of the genome may have there, the candidate haplotypes, by local assembly of the reads. It then measures how well each read fits each haplotype, chooses the pair of haplotypes that explains the reads best, and reads the variants and their genotypes off that pair. Local assembly removes most of the errors that a mapper makes near insertions and deletions, because each read is compared with whole haplotypes, not with the reference. GATK HaplotypeCaller is the best known caller of this kind; this page describes its steps, in a small form, for one diploid sample.
In plain words
Near an insertion or a deletion, a mapper often places the reads badly, and the columns of the alignment then show false mismatches. So do not trust the columns.
Instead, take the reads of a short stretch and join the ones that overlap, like a small jigsaw. Each way through the puzzle is a possible version of the stretch. Then ask, for each read and each version, how likely the read is if it came from that version. A person has two versions of each stretch, one from each parent, so try every two versions and keep the best ones. The differences between those versions and the reference are the variants.
The problem
The input is a region of the reference of length , and the reads that map to it, each with a Phred quality for each base. The sample is diploid. The output is a list of variants (substitutions, insertions and deletions) with a genotype of 1 or 2 copies, and their likelihoods. This is the variant calling problem for one region, solved with haplotypes as the hidden variables, not with one allele per column as in Bayesian genotype calling.
The algorithm
HAPLOTYPE-CALLER(ref, reads, k)- 1
G ← the de Bruijn graph of the k-mers of the reads and of ref, with a count on each edge - 2
remove each edge not on ref that fewer than min_count reads support - 3
H ← the paths of G from the first to the last k-mer of ref, ref first, at most H_max - 4
ℓ[r][h] ← ln P(r | h) by PAIR-HMM, for each read r and haplotype h - 5
(a, b) ← the pair with the largest Σ_r ln(½ e^ℓ[r][a] + ½ e^ℓ[r][b]) - 6
for each h ≠ ref in H: align h to ref with affine gaps and list its variants - 7
for each variant v, with A the set of haplotypes that carry it do - 8
GL[g] ← Σ_r ln((g/2) max_{h ∈ A} e^ℓ[r][h] + (1 - g/2) max_{h ∉ A} e^ℓ[r][h]) for g = 0, 1, 2 - 9
the posterior of g is proportional to e^GL[g] times the prior of g; call the g with the largest one - 10
return H, the pair (a, b), and the variants with a called genotype of 1 or 2
An edge of the graph is a -mer, and its count is the number of times it occurs in the reads. The edges of the reference stay, so the reference is always a path. A path that does not repeat a k-mer spells a haplotype of the region. Line L2 is the error filter: a sequencing error makes a few new -mers that only one read supports, and the threshold removes them. This is the local form of de Bruijn assembly.
The likelihood of a read is the sum over all its alignments to the haplotype, computed by the forward algorithm of a pair HMM with three states, match , insertion and deletion . A match emits for the same base and for another, with from the base quality . A gap opens with probability and goes on with probability . The read may start at any place of the haplotype.
PAIR-HMM(r, q, h)P1 for i ← 1 to L doP2 for j ← 1 to n doP3 M[i][j] ← emit(i, j) ((1 - 2δ) M[i-1][j-1] + (1 - γ)(I[i-1][j-1] + D[i-1][j-1])), with M[1][j] = emit(1, j) / nP4 I[i][j] ← ¼ (δ M[i-1][j] + γ I[i-1][j])P5 D[i][j] ← δ M[i][j-1] + γ D[i][j-1]P6 return ln Σ_j (M[L][j] + I[L][j])
Line L6 uses an alignment with affine gaps and shifts each insertion or deletion to the left, so that the same event on two haplotypes gets the same name, as in variant normalization. Line L8 is the genotype likelihood of copies of the variant: a read comes from a copy with the variant with probability . The likelihood of a read given an allele is the largest of its likelihoods over the haplotypes with that allele. The prior of lines L9 is for 0, 1 and 2 copies, with .
What this version leaves out
A real caller does more. This version omits:
- the choice of active regions from the pileup,
- the larger that HaplotypeCaller tries when the graph has a cycle,
- the recovery of dangling ends,
- gap penalties that depend on the context, such as a repeat,
- the reference confidence of the sites with no variant,
- multi-allelic sites,
- downsampling and the fast pair HMM in hardware.
A region whose reference has a repeated -mer is rejected, not assembled with a larger .
Example
The reference has 12 bases, and a heterozygous sample has a C to T change at position 6:
With and five full-length reads, two of the reference and three of the alternative, every edge of the alternative has a count of 3, so the graph has two paths, . With only one read of the alternative, its edges have a count of 1 and line L2 removes them.
All bases have quality 30, so . A read of the reference fits the reference with : the start, twelve matching bases and eleven steps without a gap. Against the other haplotype, one match becomes a mismatch, and . The difference is .
The best pair is . The variant is , and its genotype likelihoods, in , are for no copy, for one copy and for two copies. With the prior, the posterior of one copy is 0.999997.
A larger simulation used a region of 120 bases with a homozygous substitution, a heterozygous substitution on one haplotype and a heterozygous deletion of 2 bases on the other. With 24 reads of 40 bases from each haplotype, a 1% error rate and , the caller found the three variants with the right genotypes and posteriors above 0.999, and the best pair was the true phase. The graph had 8 paths, since it allows every mix of the three variants. Over 20 random seeds it found 58 of the 60 variants, called no wrong genotype and no false variant, and found the true phase in 18 runs.
Correctness
Lines P3 to P5 are the forward recurrence of the pair HMM, so by induction on and , , and are the total probability of all state paths that emit the first bases of the read, end at position of the haplotype and end in that state. Line P6 sums the paths that end in a state that emits, so it returns under the model. Line L5 tries every pair, so it returns a pair with the largest likelihood. Line L8 is the stated mixture for each genotype, and line L9 is Bayes' rule. These are theorems about the model, proved in proofs/correctness.md and checked in the tests against a sum over all alignments for short reads.
The whole method is a heuristic for the variant calling problem. The true haplotypes are found only when every edge of them has enough reads and the region has no repeated -mer, the pair HMM is a model of the errors, and the max over haplotypes in line L8 is an approximation of the sum over them.
Proof: The caller lists the supported haplotypes, the pair HMM sums over all alignments, and the genotypes are the MAP calls of the stated modelfull
The caller has three parts, and this file proves what each part computes. The model is a simplification, and the genotype likelihoods of line L8 are an approximation of the full marginal likelihood; the last section says which steps are exact and which are not.
Setting. The reference of the region is , with no repeated -mer (the code raises ValueError otherwise). The reads are strings on the forward strand, each base with a Phred quality and error rate . A -mer of a string is a substring . Its count is its number of occurrences, over all the reads.
The candidate haplotypes
Line L1 builds the graph whose nodes are -mers and whose edges are the -mers of the reads and of , from the first bases to the last bases. Line L2 keeps every edge of and every other edge with count at least . Line L3 lists, by depth-first search from the source , the paths to the sink that do not visit a node twice, and spells each path as a string.
Lemma 1 (supported haplotypes are found). Let be a string that starts with the source and ends with the sink, has no repeated -mer, and whose every -mer is a -mer of or has count at least . Then is in the list of line L3, unless the list has reached its cap of max_haplotypes strings. The reference is always in .
Proof. The -mers of in order are a walk in the graph, and each step is an edge that line L2 keeps. The -mers are distinct, so the walk is a simple path. The sink is the last -mer of and is not repeated, so the path meets the sink only at its end. The search of line L3 tries, from each node, every kept edge to a node that is not on the current path, and records the path when it reaches the sink. By induction on the length of the path, it reaches every simple path from the source that meets the sink only at its end, so it reaches the path of , unless it stopped at the cap. Two adjacent -mers overlap in bases, so the spelled string is . The reference satisfies the conditions, and the code puts it first.
The converse also holds: every string in is spelled by a simple path of kept edges, so each of its -mers is in or has count at least . A true haplotype is missed when one of its -mers has fewer supporting occurrences (low coverage or errors at one place), when it has a repeated -mer, or when it differs from the reference in the first or last bases of the region.
The pair HMM
For a read of length and a haplotype of length , an alignment path starts in state M at a position of chosen with probability , emits from left to right, and ends after the last read base in state M or I. State M emits the next read base against the next base of , with probability for the same base and for another. State I emits the next read base alone with probability . State D uses the next base of and emits nothing. The transitions are with , and with each, and with , and and with . The bases of before the start and after the last used base are free. The probability of a path is the product of its start, transition and emission probabilities, and PAIR-HMM returns over all alignment paths.
Lemma 2 (forward recurrence). For and , the values of lines P3 to P5 are of the probabilities of the path prefixes that have emitted , whose last state is , and whose last used base of is (for I, the last used base before the insertion).
Proof. By induction in the order of the loops of lines P1 and P2. The last step of a prefix fixes the cell of the step before it: an M step at comes from , an I step from and a D step from . At , a prefix in M has just started, so its probability is times the emission, which is line P3 for ; an I at would need an M before it with no read base, so it has probability 0, as line P4 gives with the row before it all zero. For , an M step can follow M, I or D, with the transition probabilities of the model, which is line P3. An I step follows M or I and emits , which is line P4. A D step follows M or D in the same row and emits nothing, which is line P5. The sum over the prefixes with a given last step is the sum over the previous state of the earlier value times the transition and the emission, so each line is the claim by the induction hypothesis.
Theorem 1 (pair HMM). Line P6 returns , the log of the sum of the probabilities of all alignment paths.
Proof. A full alignment path ends after its last read base in M or I, at some last used base . By Lemma 2 with , the sum over all of them is .
The tests compare this value with a sum over the paths listed one by one. The sum is over the alignments, so the value is a likelihood, not the score of the best alignment.
Genotypes
Line L4 computes for every read and candidate. In the diploid model, each read comes from one of the two haplotypes of the sample, with probability each, and the reads are independent given the pair. So
Lemma 3 (best pair). Line L5 returns a pair , possibly with , that maximizes this likelihood over all pairs of candidates.
Proof. The loop visits every unordered pair with repetition and keeps the first one whose value is larger than the best so far by more than .
Line L6 aligns each non-reference candidate to with affine gaps, writes each difference as a VCF-style variant shifted to the left, and lists the candidates that carry each variant. For a variant with carriers , line L8 sets
Theorem 2 (calls). For each variant , line L9 returns the posterior with the prior , and the genotype of largest posterior, the smallest on ties. Line L10 returns the variants with .
Proof. The formula of line L8 is the genotype likelihood of a site whose two alleles are represented by one haplotype each: a read comes from a chromosome with the variant with probability . The code forms each mixture with log-sum-exp, which is an identity. Line L9 adds , normalizes by log-sum-exp, and takes the largest value with ties to the smaller , which is Bayes' theorem and the MAP rule as in Bayesian genotype calling.
What is exact and what is not
- Lemma 1, Theorem 1 and Lemma 3 are exact statements about the code, up to rounding.
- The likelihood of a read given an allele, at line L8, takes the best haplotype of each class. The full marginal under the model would average over the haplotypes of each class with weights, and the max rule is an approximation of it. The genotype likelihoods of two variants on the same haplotypes are also treated one at a time, so the calls of nearby variants are not a joint genotype.
- The pair HMM is a model of the errors. Its gap rates do not depend on the context here, and the reads are taken as independent, which PCR duplicates break.
- The prior is the per-site heterozygosity prior, not a prior on haplotype pairs.
Cost. For reads of length and candidates of length about , line L4 costs , and line L5 costs . The graph has edges for read bases, and the search of line L3 is exponential in the number of bubbles in the worst case, which the cap on limits.
Complexity
- Assembly. The graph has edges and takes time to build. The search for paths can take time exponential in the number of bubbles, so the number of haplotypes is capped at , 64 here.
- Likelihoods. One pair HMM is , and line L4 does of them, in total. This is the main cost, and real callers run it on vector units or special hardware.
- Genotypes. Line L5 tries pairs over reads, and lines L7 and L8 take for each read and variant.
- Space. for the likelihoods and for one pair HMM table, or with two rows, as the code does.
Properties
- Good near indels. The reads are compared with whole haplotypes, so a read with a deletion is not forced into false mismatches.
- Phase for free. The best pair says which variants of the region are on the same copy.
- Exact within the model. The forward sums and the search over pairs are exact; the assembly and the model are not.
- Region by region. Each region is solved alone. Variants farther apart than the region are not phased together.
Variants and improvements
- Other sources of haplotypes. FreeBayes takes the haplotypes from the alignments in a short window, without assembly. Platypus combines local assembly and the alignments.
- Joint calling. GATK computes the likelihoods per sample and genotypes many samples together.
- Somatic calling. Mutect2 uses the same assembly and pair HMM, but tests the allele fraction in a tumor against a normal sample, as in somatic variant calling.
- Graphs of known variants. Aligning reads to a variation graph gives some of the same benefit for known variants, without local assembly.
- Learned models. DeepVariant also realigns the reads of a region to locally assembled haplotypes, but replaces the genotype model with a neural network on images of the pileup.
When to use it
Use it for germline calls of substitutions and short insertions and deletions from short reads, where it is the standard. It costs more than a pileup caller, so the active region step keeps it to the places where a variant is likely. For large structural variants, use split reads or read pairs; for low allele fractions, use a somatic caller.
Pitfalls
- Linear gaps in line L6. With a linear gap cost, the alignment of a haplotype with a 2-base deletion to the reference can be two separate 1-base deletions with the same score, which gives two false variants. An affine cost with a high open penalty keeps the deletion in one piece.
- Repeats in the region. A repeated -mer makes a cycle, and the paths through it are not the haplotypes. Use a larger or a smaller region.
- The pruning threshold. At low depth, the edges of a true haplotype can fall below min_count and the variant is lost; at high depth, errors that repeat can pass.
- Too many paths. Every mix of the variants is a path, so the number of haplotypes grows as a power of 2 in the number of variants of the region; the cap can drop the true one.
- Base qualities. The pair HMM trusts the qualities. Badly calibrated qualities make the likelihoods too sure; see base quality score recalibration.
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)
haplotype_based_variant_calling.py 263 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/haplotype-based-variant-calling/. The authors are listed in prov/REPJDG.jsonl.
"""A small haplotype-based variant caller for one diploid sample and one region.
The steps follow the local reassembly of callers such as GATK HaplotypeCaller:
1. build a de Bruijn graph of k-mers from the reads of the region and from
the reference of the region;
2. drop the edges that fewer than min_count reads support, except the edges
of the reference;
3. take every path from the first to the last k-mer of the reference as a
candidate haplotype;
4. score every read against every haplotype with a pair HMM (the forward
algorithm);
5. align each haplotype to the reference to find its variants, and give each
variant the genotype likelihoods of 0, 1 or 2 copies, then a genotype.
Reads are given on the forward strand of the reference, as a mapper reports
them, with one Phred quality for each base.
What this code leaves out: the choice of active regions, the mapping of
reads, downsampling, the increase of k when the graph has a cycle, the
recovery of dangling ends, the gap penalties that depend on the context (the
PCR indel model), the reference confidence model, multi-allelic sites that
overlap, and the speedups of the pair HMM. A region whose reference has a
repeated k-mer raises ValueError.
"""
from __future__ import annotations
import itertools
import math
from typing import Dict, List, Sequence, Tuple
Variant = Tuple[int, str, str] # (0-based position on the reference, reference allele, alternative allele)
def build_graph(ref: str, reads: Sequence[str], k: int) -> Tuple[Dict[Tuple[str, str], int], set]:
"""The edge counts of the de Bruijn graph of the reads, and the set of reference edges.
A node is a k-mer and an edge joins two k-mers that overlap in k - 1 bases
in a read (a (k + 1)-mer). The count of an edge is its number of occurrences in the reads.
"""
ref_kmers = [ref[i:i + k] for i in range(len(ref) - k + 1)]
if len(set(ref_kmers)) != len(ref_kmers):
raise ValueError("the reference of the region has a repeated k-mer; use a larger k")
ref_edges = {(ref[i:i + k], ref[i + 1:i + k + 1]) for i in range(len(ref) - k)}
counts: Dict[Tuple[str, str], int] = {}
for r in reads:
for i in range(len(r) - k):
e = (r[i:i + k], r[i + 1:i + k + 1])
counts[e] = counts.get(e, 0) + 1
return counts, ref_edges
def haplotypes(ref: str, reads: Sequence[str], k: int, min_count: int = 2,
max_haplotypes: int = 64) -> List[str]:
"""The candidate haplotypes: the reference first, then the other paths in sorted order.
A path may not visit a k-mer twice, so a cycle in the graph is not followed.
"""
counts, ref_edges = build_graph(ref, reads, k) # @line L1
adj: Dict[str, List[str]] = {}
for (u, v), c in counts.items():
if c >= min_count and (u, v) not in ref_edges: # @line L2
adj.setdefault(u, []).append(v)
for u, v in ref_edges:
adj.setdefault(u, []).append(v)
for u in adj:
adj[u].sort()
source, sink = ref[:k], ref[-k:]
out: List[str] = []
path = [source]
on_path = {source}
def dfs(u: str) -> None: # @line L3
if len(out) >= max_haplotypes:
return
if u == sink:
out.append(path[0] + "".join(x[-1] for x in path[1:]))
return
for v in adj.get(u, []):
if v not in on_path:
path.append(v)
on_path.add(v)
dfs(v)
on_path.discard(v)
path.pop()
dfs(source)
rest = sorted(h for h in out if h != ref)
return [ref] + rest
def pair_hmm(read: str, quals: Sequence[int], hap: str, gap_open: float = 1e-3,
gap_ext: float = 0.1) -> float:
"""ln P(read | hap) by the forward algorithm of a pair HMM.
The read starts in the match state at a position of hap chosen uniformly
and must end in the match or the insertion state; the parts of hap before
and after the read are free. A match emits 1 - e for the same base and
e / 3 for another, with e = 10^(-q / 10). An inserted read base has
probability 1/4. From the match state the chain opens an insertion or a
deletion with probability gap_open each; a gap goes on with probability gap_ext.
"""
n, L = len(hap), len(read)
mm, gap_close = 1.0 - 2.0 * gap_open, 1.0 - gap_ext
prev_m = [0.0] * (n + 1)
prev_i = [0.0] * (n + 1)
prev_d = [0.0] * (n + 1)
for i in range(1, L + 1): # @line P1
b = read[i - 1]
e = 10.0 ** (-quals[i - 1] / 10.0)
same, other = 1.0 - e, e / 3.0
cur_m = [0.0] * (n + 1)
cur_i = [0.0] * (n + 1)
cur_d = [0.0] * (n + 1)
for j in range(1, n + 1): # @line P2
emit = same if hap[j - 1] == b else other
if i == 1:
cur_m[j] = emit / n
else:
cur_m[j] = emit * (mm * prev_m[j - 1] + gap_close * (prev_i[j - 1] + prev_d[j - 1])) # @line P3
cur_i[j] = 0.25 * (gap_open * prev_m[j] + gap_ext * prev_i[j]) # @line P4
cur_d[j] = gap_open * cur_m[j - 1] + gap_ext * cur_d[j - 1] # @line P5
prev_m, prev_i, prev_d = cur_m, cur_i, cur_d
total = sum(prev_m) + sum(prev_i) # @line P6
return math.log(total) if total > 0 else -math.inf
def affine_align(a: str, b: str, match: int = 2, mismatch: int = -3, gap_open: int = -6,
gap_ext: int = -1) -> List[str]:
"""The operations of a best global alignment of a with b under affine gaps (Gotoh).
A gap of length g scores gap_open + (g - 1) gap_ext. "M" uses a base of
both, "I" a base of a only and "D" a base of b only. Affine gaps keep a
deletion of two bases in one piece, where linear gaps may cut it in two.
"""
n, m = len(a), len(b)
NEG = -10 ** 9
M = [[NEG] * (m + 1) for _ in range(n + 1)]
X = [[NEG] * (m + 1) for _ in range(n + 1)]
Y = [[NEG] * (m + 1) for _ in range(n + 1)]
M[0][0] = 0
for i in range(1, n + 1):
X[i][0] = gap_open + (i - 1) * gap_ext
for j in range(1, m + 1):
Y[0][j] = gap_open + (j - 1) * gap_ext
for i in range(n + 1):
for j in range(m + 1):
if i and j:
s = match if a[i - 1] == b[j - 1] else mismatch
M[i][j] = s + max(M[i - 1][j - 1], X[i - 1][j - 1], Y[i - 1][j - 1])
if i and j:
X[i][j] = max(M[i - 1][j] + gap_open, X[i - 1][j] + gap_ext)
Y[i][j] = max(M[i][j - 1] + gap_open, Y[i][j - 1] + gap_ext)
tables = {"M": M, "I": X, "D": Y}
state = max("MID", key=lambda t: tables[t][n][m])
i, j, ops = n, m, []
while i or j:
ops.append(state)
if state == "M":
s = match if a[i - 1] == b[j - 1] else mismatch
prev = M[i][j] - s
i, j = i - 1, j - 1
state = next(t for t in "MID" if tables[t][i][j] == prev)
elif state == "I":
state = "M" if X[i][j] == M[i - 1][j] + gap_open else "I"
i -= 1
else:
state = "M" if Y[i][j] == M[i][j - 1] + gap_open else "D"
j -= 1
ops.reverse()
return ops
def _left_shift(ref: str, v: Variant) -> Variant:
"""Move an indel to the left as far as the reference allows, as in VCF normalization."""
pos, a, b = v
while len(a) != len(b) and pos > 0 and a[-1] == b[-1]:
pos -= 1
a, b = ref[pos] + a[:-1], ref[pos] + b[:-1]
return pos, a, b
def variants_of(hap: str, ref: str) -> List[Variant]:
"""The variants of hap against ref from an affine gap alignment, in VCF style.
A substitution is (pos, ref base, alt base). An insertion or a deletion is
written with the base before it, as in VCF, and shifted to the left. A gap
at the very start of the region is not allowed, because it has no base before it.
"""
ops = affine_align(hap, ref)
out: List[Variant] = []
i = j = 0 # i in hap, j in ref
t = 0
while t < len(ops):
op = ops[t]
if op == "M":
if hap[i] != ref[j]:
out.append((j, ref[j], hap[i]))
i, j, t = i + 1, j + 1, t + 1
continue
run = 1
while t + run < len(ops) and ops[t + run] == op:
run += 1
if j == 0 or i == 0:
raise ValueError("a gap at the start of the region")
if op == "I":
out.append(_left_shift(ref, (j - 1, ref[j - 1], ref[j - 1] + hap[i:i + run])))
i += run
else:
out.append(_left_shift(ref, (j - 1, ref[j - 1:j + run], ref[j - 1])))
j += run
t += run
return out
def _mix(w: float, la: float, lb: float) -> float:
"""ln(w e^la + (1 - w) e^lb) without underflow."""
terms = [math.log(w) + la if w > 0 else -math.inf, math.log(1.0 - w) + lb if w < 1 else -math.inf]
top = max(terms)
if top == -math.inf:
return -math.inf
return top + math.log(sum(math.exp(x - top) for x in terms))
def call(ref: str, reads: Sequence[str], quals: Sequence[Sequence[int]], k: int = 15,
min_count: int = 2, theta: float = 1e-3) -> dict:
"""Run the caller. Returns a dict with the haplotypes, the best haplotype pair
(as indices into the haplotypes), and the calls: for each variant, the genotype
(0, 1 or 2 copies), the three log10 likelihoods and the three posteriors.
"""
H = haplotypes(ref, reads, k, min_count)
lik = [[pair_hmm(r, q, h) for h in H] for r, q in zip(reads, quals)] # @line L4
best_pair, best_ll = (0, 0), -math.inf
for a, b in itertools.combinations_with_replacement(range(len(H)), 2): # @line L5
ll = sum(_mix(0.5, row[a], row[b]) for row in lik)
if ll > best_ll + 1e-9:
best_pair, best_ll = (a, b), ll
carriers: Dict[Variant, set] = {}
for h_index, h in enumerate(H[1:], start=1): # @line L6
for v in variants_of(h, ref):
carriers.setdefault(v, set()).add(h_index)
prior = [1.0 - 1.5 * theta, theta, theta / 2.0]
calls = []
for v in sorted(carriers): # @line L7
alt_set = carriers[v]
gl = [0.0, 0.0, 0.0]
for row in lik:
l_alt = max(row[h] for h in alt_set)
l_ref = max(row[h] for h in range(len(H)) if h not in alt_set)
for g in range(3): # @line L8
gl[g] += _mix(g / 2.0, l_alt, l_ref)
lp = [gl[g] + math.log(prior[g]) for g in range(3)] # @line L9
top = max(lp)
z = top + math.log(sum(math.exp(x - top) for x in lp))
post = [math.exp(x - z) for x in lp]
g = max(range(3), key=lambda x: (lp[x], -x))
calls.append({"variant": v, "genotype": g, "log10_gl": [x / math.log(10) for x in gl],
"posterior": post})
return {"haplotypes": H, "best_pair": best_pair,
"calls": [c for c in calls if c["genotype"] > 0]} # @line L10
test_haplotype_based_variant_calling.py 186 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/haplotype-based-variant-calling/. The authors are listed in prov/REPJDG.jsonl.
import math
import random
from bioseq import global_align, random_dna, revcomp, simulate_reads
from haplotype_based_variant_calling import affine_align, build_graph, call, haplotypes, pair_hmm, variants_of
def enumerate_pair_hmm(read, quals, hap, gap_open=1e-3, gap_ext=0.1):
"""P(read | hap) as the sum over every state path, listed one by one."""
n, L = len(hap), len(read)
trans = {("M", "M"): 1 - 2 * gap_open, ("M", "I"): gap_open, ("M", "D"): gap_open,
("I", "I"): gap_ext, ("I", "M"): 1 - gap_ext, ("D", "D"): gap_ext, ("D", "M"): 1 - gap_ext}
def emit(i, j):
e = 10 ** (-quals[i] / 10)
return 1 - e if read[i] == hap[j] else e / 3
total = 0.0
def walk(i, j, state, p):
# i read bases and j haplotype bases are used; state is the state of the last step.
nonlocal total
if i == L:
if state in ("M", "I"):
total += p
return
if j < n and (state, "M") in trans:
walk(i + 1, j + 1, "M", p * trans[(state, "M")] * emit(i, j))
if (state, "I") in trans:
walk(i + 1, j, "I", p * trans[(state, "I")] * 0.25)
if j < n and (state, "D") in trans:
walk(i, j + 1, "D", p * trans[(state, "D")])
for j in range(n):
walk(1, j + 1, "M", emit(0, j) / n)
return total
def normalize(ref, v):
"""Shift a VCF-style indel to the left as far as the reference allows."""
pos, a, b = v
while len(a) != len(b) and pos > 0 and a[-1] == b[-1]:
pos -= 1
a, b = ref[pos] + a[:-1], ref[pos] + b[:-1]
return pos, a, b
def test_pair_hmm_against_path_enumeration():
rng = random.Random(3)
for _ in range(40):
hap = random_dna(rng, rng.randint(1, 5))
read = random_dna(rng, rng.randint(1, 4))
quals = [rng.randint(5, 40) for _ in read]
go, ge = rng.uniform(0.01, 0.2), rng.uniform(0.05, 0.5)
got = pair_hmm(read, quals, hap, go, ge)
want = enumerate_pair_hmm(read, quals, hap, go, ge)
assert abs(math.exp(got) - want) <= 1e-12 * max(1.0, want)
def test_pair_hmm_prefers_the_source_haplotype():
rng = random.Random(4)
hap = random_dna(rng, 60)
alt = hap[:30] + ("A" if hap[30] != "A" else "C") + hap[31:]
read = alt[10:50]
quals = [30] * 40
assert pair_hmm(read, quals, alt) > pair_hmm(read, quals, hap) + 5
# One mismatch at Q30 against a match: about ln((1 - e) / (e / 3)) = ln(2997) = 8.0.
assert abs(pair_hmm(read, quals, alt) - pair_hmm(read, quals, hap) - math.log(0.999 / (0.001 / 3))) < 0.01
def test_graph_counts_and_bubble():
ref = "ACGTTGCAAGTC"
alt = "ACGTTGTAAGTC"
reads = [alt, alt, ref[2:]]
counts, ref_edges = build_graph(ref, reads, 4)
assert counts[("TTGT", "TGTA")] == 2
assert ("TTGC", "TGCA") in ref_edges
assert haplotypes(ref, reads, 4) == [ref, alt]
# With one supporting read the edge is pruned.
assert haplotypes(ref, [alt, ref], 4) == [ref]
def test_repeated_kmer_raises():
try:
haplotypes("ACGTACGTAA", ["ACGTACGTAA"], 4)
except ValueError:
return
raise AssertionError("expected ValueError")
def ops_score(a, b, ops, match, mismatch, go, ge):
i = j = 0
s, prev = 0, None
for op in ops:
if op == "M":
s += match if a[i] == b[j] else mismatch
i, j = i + 1, j + 1
else:
s += ge if op == prev else go
if op == "I":
i += 1
else:
j += 1
prev = op
assert (i, j) == (len(a), len(b))
return s
def test_affine_align_against_linear_and_brute_force():
rng = random.Random(6)
for _ in range(60):
a = random_dna(rng, rng.randint(0, 7))
b = random_dna(rng, rng.randint(0, 7))
# With equal open and extend scores the gaps are linear, and bioseq.global_align is an oracle.
ops = affine_align(a, b, 1, -1, -1, -1)
assert ops_score(a, b, ops, 1, -1, -1, -1) == global_align(a, b, 1, -1, -1)[0]
for _ in range(40):
a = random_dna(rng, rng.randint(0, 4))
b = random_dna(rng, rng.randint(0, 4))
ops = affine_align(a, b)
best = max(ops_score(a, b, list(w), 2, -3, -6, -1) for w in all_alignments(len(a), len(b)))
assert ops_score(a, b, ops, 2, -3, -6, -1) == best
def all_alignments(n, m):
if n == 0 and m == 0:
yield ""
return
if n and m:
for w in all_alignments(n - 1, m - 1):
yield w + "M"
if n:
for w in all_alignments(n - 1, m):
yield w + "I"
if m:
for w in all_alignments(n, m - 1):
yield w + "D"
def test_variants_of():
ref = "GATTACAGGCATTCGA"
assert variants_of(ref, ref) == []
assert variants_of(ref[:5] + "G" + ref[6:], ref) == [(5, "C", "G")]
assert variants_of(ref[:8] + ref[10:], ref) == [(7, "GGC", "G")]
assert variants_of(ref[:9] + "TT" + ref[9:], ref) == [(8, "G", "GTT")]
def simulate(seed):
rng = random.Random(seed)
ref = random_dna(rng, 120)
hom = "G" if ref[30] != "G" else "T"
snp = "A" if ref[50] != "A" else "C"
h1 = ref[:30] + hom + ref[31:50] + snp + ref[51:]
h2 = ref[:30] + hom + ref[31:80] + ref[82:]
reads = []
for h in (h1, h2):
for s in simulate_reads(rng, h, 24, 40, 0.01):
reads.append(s.read if s.strand == "+" else revcomp(s.read))
truth = {(30, ref[30], hom): 2, (50, ref[50], snp): 1, normalize(ref, (79, ref[79:82], ref[79])): 1}
return ref, h1, h2, reads, truth
def test_simulated_diploid_sample():
ref, h1, h2, reads, truth = simulate(2017)
res = call(ref, reads, [[20] * len(r) for r in reads])
got = {c["variant"]: c["genotype"] for c in res["calls"]}
assert got == truth
for c in res["calls"]:
assert max(c["posterior"]) > 0.999
# Reads of 40 bases join the sites at 50 and 80, so the best pair is the true phase.
H = res["haplotypes"]
assert {H[i] for i in res["best_pair"]} == {h1, h2}
# Two independent bubbles and one fixed change give 2^3 = 8 paths.
assert len(H) == 8
def test_no_variants_without_alt_reads():
rng = random.Random(9)
ref = random_dna(rng, 80)
reads = [ref[s:s + 30] for s in range(0, 51, 5)]
res = call(ref, reads, [[30] * 30 for _ in reads])
assert res["haplotypes"] == [ref]
assert res["calls"] == []
History
Callers in the early years of short reads used the pileup column by column, and indels were often called badly because the mapper placed the reads in different ways around them. Garrison and Marth (2012) described FreeBayes, which calls variants from the haplotypes of the reads in short windows. GATK HaplotypeCaller, described with its joint calling by Poplin et al. (2017), assembles candidate haplotypes in each active region with a de Bruijn graph and scores each read against each haplotype with a pair HMM. The same plan is used in Mutect2 for somatic calls and for the candidates of later callers.
References
- Ryan Poplin, Valentin Ruano-Rubio, Mark A. DePristo and others, Scaling accurate genetic variant discovery to tens of thousands of samples, bioRxiv 201178, 2017, the sections on the HaplotypeCaller (the active regions, the local assembly of haplotypes, the pair HMM likelihoods of the reads and the genotyping)
- Erik Garrison and Gabor Marth, Haplotype-based variant detection from short-read sequencing, arXiv 1207.3907, 2012, the sections on the haplotype windows, the observed haplotypes of the reads and the Bayesian model of the genotypes
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 REPJDG Edit this page History Report an error Markdown