Algorithmcore
Bayesian genotype calling
Also called Bayesian SNP calling.
Combine genotype likelihoods with a prior from allele frequency or heterozygosity, and call the genotype of highest posterior probability.
- Solves
- Variant calling
- Time
- Θ(n) worst · average · best
- Space
- Θ(1) extra
- Where
- n = the number of reads at the site
- Model
- Real RAM
- Properties
- deterministicexactonlineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Heng Li, Jue Ruan, Richard Durbin, 2008
Bayesian genotype calling decides the genotype of a sample at one site from the reads that cover it. It computes the genotype likelihood of each genotype from the bases and their qualities, multiplies it by a prior, normalizes by Bayes' theorem, and calls the genotype of highest posterior probability. The prior is what lets the method resist a few sequencing errors, and the posterior gives the confidence of the call on the Phred scale, the GQ and QUAL fields of VCF. Maq used this scheme in 2008, and it is the core of per-site callers such as bcftools and the GATK UnifiedGenotyper.
In plain words
At one place in the genome, a person can have the reference letter on both chromosomes, on one, or on neither. Each read that covers the place shows a letter, and each letter has a score that says how often such a letter is a mistake.
For each of the three choices, work out how likely the reads would be if that choice were true. Then weigh each choice by how common it is before you look at any reads: most places match the reference, so that choice starts far ahead. Pick the choice that comes out with the most weight, and report how much weight is left for the others. Little weight left means a sure call.
The problem
At a site with reference allele and one alternate allele , a diploid sample has genotype , the number of copies of . The data are the read bases and qualities of the pileup column, . Given a prior , find the posterior , the genotype that maximizes it, and
The model is that of genotype likelihood: a base of quality has error rate , it shows the true allele with probability and each other base with probability , each read comes from either chromosome with probability , and the reads are independent given .
Priors. Two priors are common.
- From the heterozygosity. With the expected rate of differences between two chromosomes, . GATK's default heterozygosity is , about the rate for humans.
- From an allele frequency. If the frequency of in the population is , the Hardy-Weinberg prior is .
The first prior follows from the neutral site frequency spectrum for three sequences, the reference and the two chromosomes of the sample. A site is segregating with one derived copy with probability about and with two with probability about . Given one derived copy, it is on a chromosome of the sample with probability , which makes a heterozygote, and on the reference with probability , which makes the sample homozygous for . Given two, they are on the reference and one chromosome with probability , a heterozygote, and on both chromosomes with probability . So and , to first order in .
The algorithm
The sums are in logarithms, with the log-sum-exp trick, so that a deep pileup does not underflow.
BAYES-GENOTYPE(pileup, r, a, π)- 1
λ[g] ← ln π(g) for g = 0, 1, 2 - 2
for each read (b, Q) in the pileup do - 3
e ← 10^(-Q/10) - 4
for g ← 0 to 2 do - 5
λ[g] ← λ[g] + ln((g/2) P(b | a, e) + (1 - g/2) P(b | r, e)) - 6
z ← LOG-SUM-EXP(λ[0], λ[1], λ[2]) - 7
post[g] ← exp(λ[g] - z) for g = 0, 1, 2 - 8
ĝ ← the g of largest λ[g], ties to the smaller g - 9
w ← LOG-SUM-EXP(λ[g] for g ≠ ĝ) - z - 10
return ĝ, post, GQ = -10 w / ln 10, QUAL = -10 (λ[0] - z) / ln 10
At line L6, , so is and line L7 gives the posterior. Line L9 is the log of , computed from the other two terms instead of by a subtraction, which keeps its precision when the call is sure. If the alternate allele is not given, the code takes the most common non-reference base of the pileup, with ties in ACGT order.
Example
Six reads at a site with and : A at qualities 30, 30, 20, and G at 30, 20, 10. The genotype likelihoods are , which is PL 56, 0, 76.
With the prior from , , the posterior is
| genotype | posterior | |
|---|---|---|
| 0 | A/A | 0.002538 |
| 1 | A/G | 0.997462 |
| 2 | G/G |
The call is A/G with . Here QUAL is almost the same, 25.96, because nearly all of the weight that is not on A/G is on A/A. The likelihood ratio of A/G to A/A is about , but the prior ratio is , so the posterior ratio is about 390.
With the Hardy-Weinberg prior for , a common variant, and the call is A/G with . The same reads give a surer call when the variant is known to be common.
Two more cases, with the prior:
- One G among ten Q30 reads. The call is A/A, with a posterior of 0.002932 for A/G. One base with a 1 in 1000 error rate, against nine reference bases, is not enough to overturn a prior of 1000 to 1 against the heterozygote.
- Two G reads at Q30. The posteriors are 0.000148, 0.333432 and 0.666420, and the call is G/G with , but . The site is surely variant, but two reads cannot tell G/G from A/G.
Correctness
For one read, the probability of its base given is the mixture in line L5, by the law of total probability over the chromosome it came from. The reads are independent given , so the likelihood is the product of the read terms, which line L5 adds in logarithms. The product of the mixtures is also the sum, over all ways to assign the reads to the two chromosomes, of the probability of the bases under that assignment; the test checks the code against that brute force sum. After the loop, , so lines L6 and L7 give the posterior by Bayes' theorem, line L8 the maximum a posteriori genotype, and lines L9 and L10 the stated GQ and QUAL. The full proof, which needs for every read, is in proofs/correctness.md.
Proof: The genotype caller returns the posterior of each genotype and its MAP genotypefull
Fix a biallelic site with reference allele and alternate allele in a diploid sample. The data are pairs : the base that read shows at the site and its Phred quality, with . The genotype is the number of chromosomes that carry . The model has three parts.
- Read comes from one of the two chromosomes, each with probability , independently of the other reads.
- Given the allele of that chromosome, the read shows with probability if and otherwise.
- Given , the reads are independent, and has the prior with and .
We assume in floating point, that is, and not so large that underflows to 0. Then every factor below has a finite logarithm.
Lemma 1 (one read). .
Proof. Under genotype , of the two chromosomes carry and carry . By part 1 the read comes from a chromosome with with probability , and from one with with probability . The law of total probability over the two cases gives the formula.
Lemma 2 (all reads). . The same value is the sum, over the maps from the reads to the two chromosomes, of , where are the alleles of the chromosomes.
Proof. The first form is part 3 with Lemma 1. For the second form, the sum of a product over independent choices , where factor depends only on , is the product of the sums: . With , the inner sum is Lemma 1.
The brute-force test of the implementation computes the second form.
Lemma 3 (loop invariant). After lines L2 to L5 have run for the first reads, for each , with .
Proof. Line L1 sets , which is the claim for . Line L3 computes , and line L5 adds , which is by Lemma 1. The term is finite: and are each or , both positive for , and the term is a mixture of the two with weights that sum to 1.
So after the loop, by Lemma 2.
Theorem. Line L7 gives for each . Line L8 returns a genotype of largest posterior, the smallest one if several tie. The returned GQ is for the returned genotype , and QUAL is .
Proof. Line L6 computes by the log-sum-exp identity with , which holds for any real . Since at least one and every likelihood is positive, is finite. So , and by Bayes' theorem , which is line L7.
The posterior is with the same for each , and is increasing, so the order of the posteriors is the order of the values . Line L8 takes the largest and breaks ties by the key , which picks the smallest .
Line L9 computes , and GQ is . If every other genotype has prior 0, then and GQ is , the limit of the formula. In the same way QUAL is , and if .
Numerical range. The code never forms itself. Each is a sum of logarithms, each between and 0, so it stays a finite double for any pileup that real data give, and the subtraction of in log-sum-exp keeps each exponent at most 0. So a pileup of thousands of reads, whose likelihood is below the smallest positive double, still gives correct posteriors.
Cost. Each read costs a constant number of operations for the three genotypes, so the time is and the extra space is .
Choice of the alternate allele. call_site picks as the most common base other than in the pileup, before the posterior is computed. The theorem is about the posterior given that choice. It is not the posterior over all three possible alternate alleles, which would need the ten genotypes of four alleles.
Complexity
- Time. per site: three log terms per read. A genome at 30x has about sites times 30 reads, so callers first skip the sites where no read differs from the reference by more than a threshold.
- Space. beyond the pileup, since the reads can be added one at a time.
- More alleles. With alleles, a diploid has genotypes, and the cost is .
Properties
- Exact for its model. The posterior is computed exactly, up to rounding. The model itself, independent reads with calibrated qualities, is an approximation.
- Incremental. Each read adds one term to each , so a caller can update the call as reads arrive.
- Prior dominance at low depth. With no reads, the posterior is the prior and the call is A/A. As the depth grows, the likelihood dominates and the prior matters less.
- Phred outputs. GQ uses the posterior of the called genotype. GATK writes GQ in another way, as the gap between the two smallest PL values capped at 99, so values from two callers need care.
Variants and improvements
- Multi-sample calling. Li (2011) estimates the allele frequency of a site from the genotype likelihoods of all samples by expectation maximization and uses it in a Hardy-Weinberg prior, so samples with few reads borrow strength from the others.
- Mapping quality. Many callers mix in the chance that the read is misplaced, or cap each base quality at the mapping quality of the read.
- Indels. Per-site callers can score indels as alleles with the probability of the read given each allele, but haplotype-based calling does this better, with a pair HMM over candidate haplotypes.
- Dependent errors. Some callers give less weight to repeated errors on the same strand at the same site, which the independent model overcounts.
- Somatic and pooled samples. Allele fractions other than 0, 1/2 and 1 replace the three genotypes; see somatic variant calling.
When to use it
Use it for SNVs at sites where the reads are well aligned, for one or many samples, and when you need a calibrated posterior. It is fast and simple, and it is the reference point for other callers. For indels and for clusters of nearby variants, prefer haplotype-based callers. At low coverage, pass the likelihoods to population methods instead of calling hard genotypes.
Pitfalls
- Wrong qualities. Overstated base qualities make errors look like evidence; run base quality score recalibration first.
- Duplicates. PCR copies are not independent reads; mark them with duplicate marking.
- Misaligned indels. Reads aligned across an indel can show false SNVs near it.
- The prior in a population with another rate. A fixed is set for humans. Another species, or a known common variant, needs another prior.
- GQ versus QUAL. A site can be surely variant while the genotype is unsure, as in the two-read example.
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/bayesian-genotype-calling/. The authors are listed in prov/YB8C7J.jsonl.
"""Bayesian genotype calling at one biallelic site of a diploid sample.
A pileup is a list of (base, quality) pairs: the base that each read shows
at the site and its Phred base quality. The genotype g is the number of
copies of the alternate allele, 0, 1 or 2. The error model is the usual one
of the genotype likelihood page: a base is read correctly with probability
1 - e, and as each of the three other bases with probability e / 3, where
e = 10^(-Q/10). Reads are independent given the genotype, and each read
comes from either chromosome with probability 1/2.
All sums are in log space, so a deep pileup does not underflow.
"""
from __future__ import annotations
import math
from collections import namedtuple
from typing import List, Sequence, Tuple
from biostoch import logsumexp
Call = namedtuple("Call", ["genotype", "posterior", "gq", "qual", "alt"])
_LN10 = math.log(10.0)
def base_prob(base: str, allele: str, e: float) -> float:
"""P(read shows base | the read comes from a chromosome with allele)."""
return 1.0 - e if base == allele else e / 3.0
def prior_theta(theta: float) -> List[float]:
"""The prior (1 - 3 theta / 2, theta, theta / 2) from the population mutation rate."""
if not 0.0 <= theta <= 2.0 / 3.0:
raise ValueError("need 0 <= theta <= 2/3")
return [1.0 - 1.5 * theta, theta, theta / 2.0]
def prior_hwe(f: float) -> List[float]:
"""The Hardy-Weinberg prior ((1 - f)^2, 2 f (1 - f), f^2) for alternate allele frequency f."""
if not 0.0 <= f <= 1.0:
raise ValueError("need 0 <= f <= 1")
return [(1.0 - f) ** 2, 2.0 * f * (1.0 - f), f * f]
def log_likelihoods(pileup: Sequence[Tuple[str, float]], ref: str, alt: str) -> List[float]:
"""ln P(D | g) for g = 0, 1, 2."""
ll = [0.0, 0.0, 0.0]
for b, q in pileup:
e = 10.0 ** (-q / 10.0)
pr, pa = base_prob(b, ref, e), base_prob(b, alt, e)
for g in range(3):
ll[g] += math.log((g / 2.0) * pa + (1.0 - g / 2.0) * pr)
return ll
def call_genotype(pileup: Sequence[Tuple[str, float]], ref: str, alt: str,
prior: Sequence[float]) -> Call:
"""The maximum a posteriori genotype, its posterior, GQ and QUAL.
GQ is -10 log10 of the posterior probability that the called genotype is
wrong. QUAL is -10 log10 P(g = 0 | D), the Phred-scaled probability that
the site is not variant. Ties in the posterior go to the smaller g.
"""
if alt == ref:
raise ValueError("alt must differ from ref")
lp = [math.log(p) if p > 0 else -math.inf for p in prior] # @line L1
for b, q in pileup: # @line L2
e = 10.0 ** (-q / 10.0) # @line L3
pr, pa = base_prob(b, ref, e), base_prob(b, alt, e)
for g in range(3): # @line L4
lp[g] += math.log((g / 2.0) * pa + (1.0 - g / 2.0) * pr) # @line L5
z = logsumexp(lp) # @line L6
post = [math.exp(x - z) for x in lp] # @line L7
best = max(range(3), key=lambda g: (lp[g], -g)) # @line L8
wrong = logsumexp([lp[g] for g in range(3) if g != best]) - z # @line L9
gq = -10.0 * wrong / _LN10 if wrong > -math.inf else math.inf
qual = -10.0 * (lp[0] - z) / _LN10 if lp[0] > -math.inf else math.inf
return Call(best, post, gq, qual, alt) # @line L10
def call_site(ref: str, pileup: Sequence[Tuple[str, float]], prior: Sequence[float]) -> Call:
"""Call one site, with the most common non-reference base as the alternate allele.
Ties between non-reference bases go to the first in ACGT order, so a site
with no non-reference base is tested against the first other base.
"""
others = [b for b in "ACGT" if b != ref]
counts = {b: 0 for b in others}
for b, _ in pileup:
if b in counts:
counts[b] += 1
alt = max(others, key=lambda b: (counts[b], -others.index(b)))
return call_genotype(pileup, ref, alt, prior)
bioseq.py 249 lines
# 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)
biostoch.py 336 lines
# SPDX-License-Identifier: MIT
# Shared helper of the biology pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Random variates, exact probability mass functions and test helpers for
the stochastic pages of the biology area.
Every sampler takes a random.Random object as its first argument and never
uses the module-level random functions. Each sampler draws its random
numbers in the order that its docstring gives, so two runs with the same
seed give the same output.
Conventions:
- A reaction network with n species and m reactions is given by `stoich`, a
list of the m change vectors nu_1, ..., nu_m. So stoich[j][i] is the entry
S[i][j] of the n by m stoichiometric matrix S.
- `propensity(x)` takes the state as a tuple of n integer counts and returns
the m propensities a_1(x), ..., a_m(x) as a sequence of floats >= 0.
- nbinom_pmf uses the mean mu and the dispersion alpha, with
Var = mu + alpha mu^2. The size is r = 1 / alpha; alpha = 0 is Poisson.
- hypergeom_pmf(k, total, good, draws) is the probability of k good items
in `draws` draws without replacement from `total` items of which `good`
are good.
Requires Python 3.12 or later (random.Random.binomialvariate).
"""
from __future__ import annotations
import math
from statistics import NormalDist
from typing import Callable, List, Sequence, Tuple
State = Tuple[int, ...]
_POISSON_PART = 30.0
# Random variates
def poisson(rng, lam: float) -> int:
"""A Poisson(lam) variate.
For lam <= 30, inversion of the cumulative distribution with one
rng.random() draw. For lam > 30, the sum of p = ceil(lam / 30)
independent Poisson(lam / p) variates, drawn one after the other by
inversion (one rng.random() draw each).
"""
if lam < 0 or math.isnan(lam):
raise ValueError("lam must be >= 0")
if lam == 0:
return 0
if lam > _POISSON_PART:
parts = math.ceil(lam / _POISSON_PART)
part = lam / parts
return sum(_poisson_inversion(rng, part) for _ in range(parts))
return _poisson_inversion(rng, lam)
def _poisson_inversion(rng, lam: float) -> int:
u = rng.random()
k = 0
p = math.exp(-lam)
cdf = p
while u >= cdf:
k += 1
p *= lam / k
if p == 0.0:
# Rounding left u above the computed total mass; stop at the tail.
break
cdf += p
return k
def binomial(rng, n: int, p: float) -> int:
"""A Binomial(n, p) variate by rng.binomialvariate (one call)."""
if n < 0 or not 0.0 <= p <= 1.0:
raise ValueError("need n >= 0 and 0 <= p <= 1")
if n == 0 or p == 0.0:
return 0
if p == 1.0:
return n
return rng.binomialvariate(n, p)
def multinomial(rng, n: int, probs: Sequence[float]) -> List[int]:
"""A Multinomial(n, probs) vector by conditional binomials.
probs are weights >= 0 with a positive sum; they need not sum to 1. Cell
i gets Binomial(rest of n, probs[i] / rest of the weight), for i in
order; the last cell with positive weight gets the rest.
"""
if n < 0:
raise ValueError("n must be >= 0")
w = [float(q) for q in probs]
if any(q < 0 for q in w):
raise ValueError("weights must be >= 0")
total = sum(w)
if total <= 0:
raise ValueError("weights must have a positive sum")
last = max(i for i, q in enumerate(w) if q > 0)
out = [0] * len(w)
left = n
rest = total
for i in range(last):
if left == 0:
break
if w[i] == 0:
continue
x = binomial(rng, left, min(1.0, w[i] / rest))
out[i] = x
left -= x
rest -= w[i]
out[last] += left
return out
def categorical(rng, weights: Sequence[float]) -> int:
"""An index i with probability weights[i] / sum(weights).
One draw u = rng.random() * sum(weights), then a cumulative search from
index 0. Indices with weight 0 are never returned.
"""
total = 0.0
for w in weights:
if w < 0:
raise ValueError("weights must be >= 0")
total += w
if total <= 0:
raise ValueError("weights must have a positive sum")
u = rng.random() * total
acc = 0.0
last = -1
for i, w in enumerate(weights):
if w > 0:
acc += w
last = i
if u < acc:
return i
return last
def ssa_direct(rng, x0: Sequence[int], stoich: Sequence[Sequence[int]],
propensity: Callable[[State], Sequence[float]], t_end: float,
max_events: int = 10 ** 6):
"""Gillespie's direct method from state x0 at time 0 up to time t_end.
Each step computes a = propensity(x) and a0 = sum(a). If a0 = 0 the run
stops. Otherwise it draws tau = rng.expovariate(a0) first. If
t + tau > t_end the run stops, and no second number is drawn. Else it
draws u = rng.random() * a0 and fires the first reaction j with
a_1 + ... + a_j > u (a linear search), then adds stoich[j] to x.
Returns (times, states, complete). times[0] = 0.0 and states[0] =
tuple(x0); entry k > 0 is the time and the state just after event k.
The state at t_end is states[-1]. complete is False only when the run
stopped because max_events events had fired before t_end.
"""
x = tuple(int(v) for v in x0)
times = [0.0]
states = [x]
t = 0.0
m = len(stoich)
for _ in range(max_events):
a = propensity(x)
a0 = 0.0
for v in a:
if v < 0:
raise ValueError("propensities must be >= 0")
a0 += v
if a0 <= 0.0:
return times, states, True
t += rng.expovariate(a0)
if t > t_end:
return times, states, True
u = rng.random() * a0
acc = 0.0
j = -1
for i in range(m):
if a[i] > 0:
acc += a[i]
j = i
if u < acc:
break
nu = stoich[j]
x = tuple(x[i] + nu[i] for i in range(len(x)))
times.append(t)
states.append(x)
return times, states, False
# Sample statistics and test helpers
def mean_var(xs) -> Tuple[float, float]:
"""The mean and the unbiased sample variance (divisor n - 1) by the
Welford method. The variance is 0.0 for fewer than two values."""
n = 0
mean = 0.0
m2 = 0.0
for x in xs:
n += 1
d = x - mean
mean += d / n
m2 += d * (x - mean)
if n == 0:
raise ValueError("empty sample")
return mean, (m2 / (n - 1) if n > 1 else 0.0)
def check_mean(m: float, mu: float, var: float, n: int, z: float = 4.0) -> bool:
"""True when |m - mu| <= z sqrt(var / n): a sample mean m of n
independent values with exact mean mu and exact variance var."""
return abs(m - mu) <= z * math.sqrt(var / n)
# Exact probability mass functions
def log_choose(n: int, k: int) -> float:
"""ln C(n, k), or -inf when k < 0 or k > n."""
if k < 0 or k > n:
return -math.inf
return math.lgamma(n + 1) - math.lgamma(k + 1) - math.lgamma(n - k + 1)
def binom_pmf(k: int, n: int, p: float) -> float:
"""P(K = k) for K ~ Binomial(n, p)."""
if k < 0 or k > n:
return 0.0
if p == 0.0:
return 1.0 if k == 0 else 0.0
if p == 1.0:
return 1.0 if k == n else 0.0
return math.exp(log_choose(n, k) + k * math.log(p) + (n - k) * math.log1p(-p))
def poisson_pmf(k: int, lam: float) -> float:
"""P(K = k) for K ~ Poisson(lam)."""
if k < 0:
return 0.0
if lam == 0:
return 1.0 if k == 0 else 0.0
return math.exp(k * math.log(lam) - lam - math.lgamma(k + 1))
def nbinom_pmf(k: int, mu: float, alpha: float) -> float:
"""P(K = k) for the negative binomial with mean mu and Var = mu + alpha mu^2."""
if k < 0:
return 0.0
if alpha == 0:
return poisson_pmf(k, mu)
if mu == 0:
return 1.0 if k == 0 else 0.0
r = 1.0 / alpha
return math.exp(math.lgamma(k + r) - math.lgamma(r) - math.lgamma(k + 1)
+ r * math.log(r / (r + mu)) + k * math.log(mu / (r + mu)))
def hypergeom_pmf(k: int, total: int, good: int, draws: int) -> float:
"""P(K = k) for k good items in `draws` draws without replacement from
`total` items of which `good` are good."""
if k < 0 or k > good or draws - k < 0 or draws - k > total - good:
return 0.0
return math.exp(log_choose(good, k) + log_choose(total - good, draws - k)
- log_choose(total, draws))
def logsumexp(xs) -> float:
"""ln(sum of exp(x)) without overflow; -inf for an empty input."""
xs = list(xs)
if not xs:
return -math.inf
top = max(xs)
if top == -math.inf:
return -math.inf
if top == math.inf:
return math.inf
return top + math.log(sum(math.exp(x - top) for x in xs))
# Tail probabilities
def _gamma_q(a: float, x: float) -> float:
"""The regularized upper incomplete gamma function Q(a, x)."""
if a <= 0:
raise ValueError("a must be > 0")
if x <= 0:
return 1.0
log_front = -x + a * math.log(x) - math.lgamma(a)
if x < a + 1.0:
# Series for P(a, x).
ap = a
term = 1.0 / a
total = term
for _ in range(100000):
ap += 1.0
term *= x / ap
total += term
if abs(term) < abs(total) * 1e-16:
break
return max(0.0, 1.0 - total * math.exp(log_front))
# Continued fraction for Q(a, x), by the modified Lentz method.
tiny = 1e-300
b = x + 1.0 - a
c = 1.0 / tiny
d = 1.0 / b
h = d
for i in range(1, 100000):
an = -i * (i - a)
b += 2.0
d = an * d + b
if abs(d) < tiny:
d = tiny
c = b + an / c
if abs(c) < tiny:
c = tiny
d = 1.0 / d
delta = d * c
h *= delta
if abs(delta - 1.0) < 1e-16:
break
return math.exp(log_front) * h
def chi2_sf(x: float, df: float) -> float:
"""P(X > x) for X chi-squared with df degrees of freedom."""
if df <= 0:
raise ValueError("df must be > 0")
if x <= 0:
return 1.0
return _gamma_q(df / 2.0, x / 2.0)
_STD_NORMAL = NormalDist()
def normal_sf(x: float, mu: float = 0.0, sigma: float = 1.0) -> float:
"""P(X > x) for X ~ Normal(mu, sigma^2), by statistics.NormalDist."""
return _STD_NORMAL.cdf(-(x - mu) / sigma)
test_bayesian_genotype_calling.py 121 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/bayesian-genotype-calling/. The authors are listed in prov/YB8C7J.jsonl.
import itertools
import math
import random
from bioseq import random_dna, revcomp, simulate_reads, phred_to_prob
from biostoch import binom_pmf
from bayesian_genotype_calling import (base_prob, call_genotype, call_site, log_likelihoods,
prior_hwe, prior_theta)
EXAMPLE = [("A", 30), ("A", 30), ("A", 20), ("G", 30), ("G", 20), ("G", 10)]
def brute_posterior(pileup, ref, alt, prior):
"""P(g | D) by a sum over every way to assign each read to one of the two chromosomes."""
joint = []
for g in range(3):
chroms = [(ref, ref), (ref, alt), (alt, alt)][g]
lik = 0.0
for origin in itertools.product((0, 1), repeat=len(pileup)):
term = 0.5 ** len(pileup)
for (b, q), c in zip(pileup, origin):
term *= base_prob(b, chroms[c], phred_to_prob(q))
lik += term
joint.append(prior[g] * lik)
s = sum(joint)
return [x / s for x in joint]
def test_page_example():
ll = log_likelihoods(EXAMPLE, "A", "G")
pl = [round(-10 * (x - max(ll)) / math.log(10)) for x in ll]
assert pl == [56, 0, 76]
c = call_genotype(EXAMPLE, "A", "G", prior_theta(0.001))
assert c.genotype == 1
assert abs(c.posterior[1] - 0.997462) < 1e-6
assert abs(c.gq - 25.955) < 1e-3 and abs(c.qual - 25.955) < 1e-3
c = call_genotype(EXAMPLE, "A", "G", prior_hwe(0.3))
assert c.genotype == 1 and abs(c.gq - 55.261) < 1e-3
def test_two_reads_and_one_of_ten():
c = call_genotype([("G", 30)] * 2, "A", "G", prior_theta(0.001))
assert c.genotype == 2
assert abs(c.posterior[1] - 0.333432) < 1e-6 and abs(c.posterior[2] - 0.666420) < 1e-6
c = call_genotype([("G", 30)] + [("A", 30)] * 9, "A", "G", prior_theta(0.001))
assert c.genotype == 0 and abs(c.posterior[1] - 0.002932) < 1e-6
def test_against_brute_force():
rng = random.Random(7)
for _ in range(200):
n = rng.randint(0, 8)
pile = [(rng.choice("AAGGC"), rng.choice((5, 10, 20, 30, 40))) for _ in range(n)]
prior = prior_theta(rng.choice((0.001, 0.01, 0.1))) if rng.random() < 0.5 else prior_hwe(rng.random())
c = call_genotype(pile, "A", "G", prior)
brute = brute_posterior(pile, "A", "G", prior)
for g in range(3):
assert abs(c.posterior[g] - brute[g]) < 1e-9
assert c.genotype == max(range(3), key=lambda g: (brute[g], -g)) or \
abs(brute[c.genotype] - max(brute)) < 1e-12
def test_equal_qualities_match_binomial():
e = phred_to_prob(20)
for n in range(0, 12):
for k in range(n + 1):
pile = [("G", 20)] * k + [("A", 20)] * (n - k)
ll = log_likelihoods(pile, "A", "G")
for g in range(3):
pa = (g / 2) * (1 - e) + (1 - g / 2) * (e / 3)
pr = (g / 2) * (e / 3) + (1 - g / 2) * (1 - e)
# pa^k pr^(n-k) = (pa + pr)^n t^k (1 - t)^(n-k) with t = pa / (pa + pr).
expect = (pa + pr) ** n * binom_pmf(k, n, pa / (pa + pr)) / math.comb(n, k)
assert abs(math.exp(ll[g]) - expect) <= 1e-12 * max(1.0, expect)
def test_no_reads_gives_prior_and_deep_pileup_is_finite():
prior = prior_theta(0.001)
c = call_genotype([], "A", "G", prior)
assert all(abs(a - b) < 1e-15 for a, b in zip(c.posterior, prior))
deep = [("A", 40)] * 3000 + [("G", 40)] * 3000
c = call_genotype(deep, "A", "G", prior)
assert c.genotype == 1 and math.isfinite(c.qual) and c.qual > 1000
def test_priors_sum_to_one():
for t in (0.0, 0.001, 0.5):
assert abs(sum(prior_theta(t)) - 1) < 1e-15
for f in (0.0, 0.2, 1.0):
assert abs(sum(prior_hwe(f)) - 1) < 1e-15
def test_recovers_simulated_variants():
rng = random.Random(2024)
g_len, read_len, q = 3000, 100, 20
genome = random_dna(rng, g_len)
sites = rng.sample(range(50, g_len - 50), 24)
truth = {}
hap = [list(genome), list(genome)]
for i, s in enumerate(sites):
alt = rng.choice([b for b in "ACGT" if b != genome[s]])
g = 2 if i % 4 == 0 else 1
truth[s] = (alt, g)
hap[0][s] = alt
if g == 2:
hap[1][s] = alt
piles = [[] for _ in range(g_len)]
for h in hap:
for r in simulate_reads(rng, "".join(h), 450, read_len, phred_to_prob(q)):
fwd = r.read if r.strand == "+" else revcomp(r.read)
for j, b in enumerate(fwd):
piles[r.pos + j].append((b, q))
called = {}
for s in range(g_len):
c = call_site(genome[s], piles[s], prior_theta(0.001))
if c.genotype > 0:
called[s] = (c.alt, c.genotype)
assert called == truth
History
Maq (Li, Ruan and Durbin, 2008) called the consensus genotype of a sample with a Bayesian model of the bases and qualities at each site, and gave the consensus quality on the Phred scale. In 2011, Li described a framework for many samples in samtools, and DePristo et al. described the UnifiedGenotyper of GATK, both with priors of this form. The review of Nielsen et al. (2011) set out the difference between SNP calling and genotype calling and the role of the prior.
References
- Heng Li, Jue Ruan and Richard Durbin, Mapping short DNA sequencing reads and calling variants using mapping quality scores, Genome Research 18(11), 2008, pp. 1851 to 1858, Methods (the consensus genotype calling of Maq, with a prior on the heterozygote and the Phred-scaled consensus quality)
- Heng Li, A statistical framework for SNP calling, mutation discovery, association mapping and population genetical parameter estimation from sequencing data, Bioinformatics 27(21), 2011, pp. 2987 to 2993, Section 2 (genotype likelihoods, the posterior of the genotype, and the estimation of the allele frequency across samples)
- 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, the section on SNP discovery and genotyping (the Bayesian model of the UnifiedGenotyper and the prior from the heterozygosity)
- Rasmus Nielsen, Joshua S. Paul, Anders Albrechtsen and Yun S. Song, Genotype and SNP calling from next-generation sequencing data, Nature Reviews Genetics 12(6), 2011, pp. 443 to 451, the section on probabilistic genotype calling (priors from a fixed rate or from the allele frequencies of a population)
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 YB8C7J Edit this page History Report an error Markdown