Algorithmadvanced
HMM copy number calling
Also called hidden Markov model CNV calling.
Model the copy number of each window as the hidden state of a Markov chain along the genome, emit the read depth from it, and decode the states with Viterbi.
- Solves
- Copy number segmentation
- Time
- Θ(K^2 n) worst · average · best
- Space
- Θ(K n) extra
- Where
- K = the number of copy number states; n = the number of windows
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Jane Fridlyand, Antoine M. Snijders, Dan Pinkel, Donna G. Albertson, Ajay N. Jain, 2004
HMM copy number calling turns the read depth along a chromosome into an integer copy number for each window. It treats the copy number as the hidden state of a hidden Markov model: the state stays the same from one window to the next with high probability, and each state emits read counts around its own mean. The Viterbi algorithm finds the most probable sequence of states, which gives the segments and their copy numbers at once. The cost is for states and windows. Fridlyand et al. (2004) used this approach for array CGH, PennCNV (2007) for SNP arrays, and tools such as XHMM use it for read depth from exome sequencing.
In plain words
Cut the genome into windows of the same size and count the reads that land in each one. A normal window has two copies of its DNA and gets some usual number of reads. A window with one copy gets about half as many, and one with three copies about one and a half times as many.
The counts are noisy, so one low window is not enough. But copy number changes seldom, so the true answer is a few long stretches. The model scores every possible list of copy numbers: it rewards lists that fit the counts and punishes each change. A fast table search finds the list with the best score without trying them all.
The problem
The input is a list of read counts , one for each window of the same size, after correction for GC content and mappability. The hidden copy numbers are in . The model of the code is:
- Emission. is Poisson with mean , where is the mean count of a window with two copies and allows a few misplaced reads in a deleted region.
- Transition. , and each other state has probability .
- Start. Each state has probability .
The task is to find , the most probable path, and, if needed, the posterior of each window. Without a given , the code takes the median count, which assumes that most of the chromosome has two copies.
The algorithm
All values are logarithms, so that a long chromosome does not underflow. is and is .
HMM-CNV(x, K, λ, p)- 1
E[t][c] ← x_t ln μ_c - μ_c - ln(x_t!), with μ_c = λ max(c, ε)/2, for each t and c - 2
V[0][c] ← ln(1/K) + E[0][c] for each c - 3
for t ← 1 to n - 1 do - 4
for c ← 0 to K - 1 do - 5
V[t][c] ← max_b (V[t - 1][b] + T[b][c]) + E[t][c] - 6
ptr[t][c] ← the b that reaches the max, the smallest on ties - 7
c*[n - 1] ← the c with the largest V[n - 1][c], the smallest on ties - 8
for t ← n - 1 down to 1 do c*[t - 1] ← ptr[t][c*[t]] - 9
return c* and its runs of equal states as segments
is the log probability of the best path that ends in state at window , joint with the first counts. The forward algorithm is the same table with the max of line L5 replaced by a sum, done with the log-sum-exp trick. With the backward pass, it gives the posterior of each state at each window.
Example
Ten windows, with , states (0 to 3 copies) and :
The state means are 0.5, 10, 20 and 30. Three rows of the emission table, :
| window | count | ||||
|---|---|---|---|---|---|
| 0 | 19 | -53.01 | -5.59 | -2.42 | -4.72 |
| 2 | 10 | -22.54 | -2.08 | -5.15 | -11.09 |
| 7 | 32 | -104.24 | -17.88 | -5.69 | -2.72 |
A change of state costs and staying costs . The Viterbi path is
with : a loss of one copy in windows 2 to 4 and a gain in windows 7 to 9. The forward algorithm gives , so this one path has about 35% of the probability of the data.
The posteriors show where the path is unsure. At window 5, . At window 6, and , so the state with the largest posterior there is 3, while the best path has 2. Each window can be decoded on its own, but the path of those choices need not be the best path.
With , a change costs more, and the path becomes : one jump from 1 to 3 at window 5 costs less than two jumps, even though counts of 20 and 21 fit 2 copies better. Its log probability is , against for the path with the 2-copy stretch. The value of sets the shortest segment that the method can call.
Correctness
By induction on , is the largest over the paths with : the joint probability of a path is the product of its start, transitions and emissions, so the best path into at is the best path into some at plus one step, which is line L5. Line L6 stores the , and lines L7 and L8 follow the pointers back from the best last state, which gives a path with the largest joint probability. The forward table is the same induction with sums. The proofs are in proofs/correctness.md, and the tests check both against a search over all paths for small cases. The decoding is exact for the model; the model itself is an approximation of real read depth.
Proof: The Viterbi pass returns a most probable copy number path, and the forward pass returns the probability of the countsfull
Setting. There are windows with counts and hidden states , the copy numbers. The model is a hidden Markov chain with start probabilities , transition probabilities and emission probabilities . Given the states, the counts are independent, and depends only on . So for a path ,
In the code, , , for , and is the Poisson law with mean . The proof uses only the product form above, so it holds for any start, transition and emission tables. All values are logarithms: (line L1), , and .
Lemma 1 (Viterbi table). After line L2, and after lines L4 to L6 for step , over the paths with .
Proof. By induction on . For the only path is , and line L2 sets . For , by the product form,
Fix and split the paths by . For fixed , the largest value of the first term is by the hypothesis, and the other two terms do not depend on . So the maximum over the paths is , which is line L5.
Lemma 2 (back pointers). For , the state of line L6 satisfies .
Proof. Line L6 stores the that reaches the maximum of line L5, the smallest such if several do.
Theorem 1 (Viterbi). The path of lines L7 and L8 maximizes over all paths, and . Among the maximizers, it is the one that the tie rule picks: the smallest last state, and then at each step back the smallest previous state.
Proof. By Lemma 1, is the largest over all paths, and line L7 takes a state that reaches it. Line L8 sets . By Lemma 2, for each , . Adding these equations for to gives , so reaches the maximum.
The tests check Theorem 1 against a search over all paths for small and .
Theorem 2 (forward and posteriors). The forward table satisfies , and its last value is in log space. The backward table satisfies , and .
Proof. The forward claim is Lemma 1 with the maximum over replaced by a sum over , which is valid for the same reason: the sum over the paths with splits by , and the last two factors do not depend on the earlier states. The code forms the sum of exponentials with log-sum-exp, with , which is an identity. For the backward table, , and by the Markov property
which is the code. Last, , because given the later counts do not depend on the earlier states and counts. Dividing by gives the posterior.
Viterbi and posterior decoding can differ. Theorem 1 is about the whole path. The state of largest posterior at each window, from Theorem 2, need not lie on the best path. In the page example with , window 6 has posterior 0.512 for state 3 and 0.485 for state 2, while the Viterbi path has state 2 there.
Cost. Line L1 costs . Each step of line L3 does maximizations over values, so the Viterbi pass takes time and keeps back pointers; the forward and backward passes have the same cost. With the transition matrix of the code, is the larger of and . The two largest values of give for every , so a pass can be done in time. The code uses the general loop.
Complexity
- Time. Line L1 is . Each window does maximizations over states, so the Viterbi pass is , and so are the forward and backward passes.
- A faster step. With the transition matrix of this page, the best predecessor of is itself or the best other state, so one step can be done in with the two largest values of , for in total. The code keeps the general loop.
- Space. The back pointers take . The forward and backward tables take for posteriors.
- Training. If , or the emissions are learned with Baum-Welch, each iteration costs one forward and one backward pass, , and the number of iterations depends on the data.
Properties
- Exact for its model. Viterbi returns a most probable path, and forward returns , both theorems up to rounding.
- Integer states. The output is a copy number, not only a segment mean, which is what CBS gives.
- One smoothing parameter. The transition probability acts as a penalty for each change point.
- Geometric segment lengths. A Markov chain gives segment lengths with a geometric distribution, which is a poor fit for real copy number changes; a hidden semi-Markov model allows other length distributions.
Variants and improvements
- B allele frequency. At heterozygous SNPs, the fraction of reads with each allele shows 1:1 for two copies, 1:2 for three and 0:1 for a copy-neutral loss of heterozygosity. PennCNV emits both the intensity and this fraction from each state.
- Overdispersion. Read counts vary more than a Poisson law allows; a negative binomial emission is a better fit.
- Tumor purity and ploidy. In a tumor sample, the expected depth of copy number is a mix of the tumor and the normal cells, so the means of the states depend on the purity, which is estimated with the states.
- Distance-dependent transitions. If the windows or probes are not evenly spaced, the probability of a change can grow with the distance.
- Exome data. XHMM and similar tools use an HMM over the depth of exome targets, after removing systematic noise with principal components.
When to use it
Use an HMM when you want integer copy numbers directly, when you can state the expected depth of each state, or when you want to combine depth with allele fractions. It is a good fit for germline copy number variants, which have a few known states. For tumors with many subclonal levels, or when the noise is hard to model, CBS followed by a separate calling step is a common choice.
Pitfalls
- The diploid level. Setting to the median count is wrong when most of the chromosome is not diploid, as in many tumors.
- Uncorrected depth. GC content and mappability bias make waves that the HMM calls as gains and losses.
- Overconfident emissions. A Poisson model with real, overdispersed counts makes each window look more certain than it is, and the path changes state too often.
- The value of . It decides the smallest segment that can be called, as the example shows. It needs tuning or training.
- Viterbi versus posteriors. The best path can have windows whose most probable state is another one; report the posterior when the confidence of a call matters.
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/.
"""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)
hmm_copy_number_calling.py 141 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hmm-copy-number-calling/. The authors are listed in prov/HP6C4B.jsonl.
"""Copy number calls from read depth with a hidden Markov model.
The input is a list of read counts, one for each window of the same size
along a chromosome. The hidden state of a window is its copy number c in
0, 1, ..., K - 1. The model is:
- emission: the count of a window with copy number c is Poisson with mean
lam * max(c, eps) / 2, where lam is the mean count of a diploid window and
eps > 0 stands for the reads that map to a deleted region by error;
- transition: a window keeps the state of the window before it with
probability 1 - p, and moves to each of the other K - 1 states with
probability p / (K - 1);
- start: each state with probability 1 / K.
viterbi gives the most probable state path and forward gives the
probability of the counts. Both work in log space and take O(K^2 n) time
for n windows; viterbi keeps an n by K table of back pointers.
What this code leaves out compared with tools such as CNVnator or the HMM of
PennCNV: correction of the counts for GC content and mappability, the
dispersion of real counts (a negative binomial emission fits better), the
B allele frequency, training of the parameters, and tumor purity.
"""
from __future__ import annotations
import math
from statistics import median
from typing import List, Sequence, Tuple
from biostoch import logsumexp
def emission_logs(counts: Sequence[int], lam: float, K: int, eps: float = 0.05) -> List[List[float]]:
"""E[t][c] = ln P(count t | copy number c) under the Poisson model."""
E = []
for x in counts:
row = []
for c in range(K):
mu = lam * max(c, eps) / 2.0
row.append(x * math.log(mu) - mu - math.lgamma(x + 1))
E.append(row)
return E
def transition_logs(K: int, p: float) -> List[List[float]]:
"""T[b][c] = ln P(state c at t | state b at t - 1)."""
if K == 1:
return [[0.0]]
stay, move = math.log(1.0 - p), math.log(p / (K - 1))
return [[stay if b == c else move for c in range(K)] for b in range(K)]
def viterbi(log_init: Sequence[float], T: Sequence[Sequence[float]],
E: Sequence[Sequence[float]]) -> Tuple[List[int], float]:
"""The most probable state path and its log probability (joint with the counts).
Ties go to the smaller state.
"""
n = len(E)
if n == 0:
return [], 0.0
K = len(log_init)
V = [log_init[c] + E[0][c] for c in range(K)] # @line L2
back: List[List[int]] = []
for t in range(1, n): # @line L3
new, ptr = [], []
for c in range(K): # @line L4
b = max(range(K), key=lambda b: (V[b] + T[b][c], -b))
new.append(V[b] + T[b][c] + E[t][c]) # @line L5
ptr.append(b) # @line L6
V = new
back.append(ptr)
last = max(range(K), key=lambda c: (V[c], -c)) # @line L7
path = [last]
for t in range(n - 2, -1, -1): # @line L8
path.append(back[t][path[-1]])
path.reverse()
return path, V[last]
def forward(log_init: Sequence[float], T: Sequence[Sequence[float]],
E: Sequence[Sequence[float]]) -> Tuple[List[List[float]], float]:
"""The forward table F[t][c] = ln P(counts 0..t, state c at t) and ln P(all counts)."""
K = len(log_init)
if not E:
return [], 0.0
F = [[log_init[c] + E[0][c] for c in range(K)]]
for t in range(1, len(E)):
F.append([E[t][c] + logsumexp(F[-1][b] + T[b][c] for b in range(K)) for c in range(K)])
return F, logsumexp(F[-1])
def backward(T: Sequence[Sequence[float]], E: Sequence[Sequence[float]]) -> List[List[float]]:
"""The backward table B[t][c] = ln P(counts t+1..n-1 | state c at t)."""
n = len(E)
if n == 0:
return []
K = len(T)
B = [[0.0] * K for _ in range(n)]
for t in range(n - 2, -1, -1):
B[t] = [logsumexp(T[c][d] + E[t + 1][d] + B[t + 1][d] for d in range(K)) for c in range(K)]
return B
def posteriors(log_init, T, E) -> List[List[float]]:
"""P(state c at t | all counts), by the forward and backward tables."""
F, total = forward(log_init, T, E)
B = backward(T, E)
return [[math.exp(f + b - total) for f, b in zip(Ft, Bt)] for Ft, Bt in zip(F, B)]
def segments(path: Sequence[int]) -> List[Tuple[int, int, int]]:
"""The runs (lo, hi, c) of equal states, half-open."""
out = []
lo = 0
for t in range(1, len(path) + 1):
if t == len(path) or path[t] != path[lo]:
out.append((lo, t, path[lo]))
lo = t
return out
def call_copy_number(counts: Sequence[int], K: int = 5, p: float = 1e-3, lam: float = None,
eps: float = 0.05) -> Tuple[List[int], List[Tuple[int, int, int]]]:
"""Viterbi copy numbers of the windows and their segments.
With lam not given, the median count stands for a diploid window, which
assumes that most of the chromosome has copy number 2.
"""
if not counts:
return [], []
if lam is None:
lam = max(float(median(counts)), 1e-9)
E = emission_logs(counts, lam, K, eps) # @line L1
T = transition_logs(K, p)
init = [-math.log(K)] * K
path, _ = viterbi(init, T, E)
return path, segments(path) # @line L9
test_hmm_copy_number_calling.py 131 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hmm-copy-number-calling/. The authors are listed in prov/HP6C4B.jsonl.
import itertools
import math
import random
from biostoch import logsumexp, poisson, poisson_pmf
from hmm_copy_number_calling import (backward, call_copy_number, emission_logs, forward, posteriors,
segments, transition_logs, viterbi)
EXAMPLE = [19, 22, 10, 8, 11, 20, 21, 32, 29, 31]
def path_log_prob(path, init, T, E):
s = init[path[0]] + E[0][path[0]]
for t in range(1, len(path)):
s += T[path[t - 1]][path[t]] + E[t][path[t]]
return s
def brute(init, T, E):
"""The best path and the total log probability by enumeration of all K^n paths."""
K, n = len(init), len(E)
best, best_path, scores = -math.inf, None, []
for path in itertools.product(range(K), repeat=n):
s = path_log_prob(path, init, T, E)
scores.append(s)
if s > best + 1e-12:
best, best_path = s, list(path)
return best_path, best, logsumexp(scores)
def random_model(rng, K, n):
lam = rng.uniform(5, 30)
counts = [rng.randint(0, 40) for _ in range(n)]
p = rng.uniform(0.01, 0.4)
return [-math.log(K)] * K, transition_logs(K, p), emission_logs(counts, lam, K)
def test_emission_is_poisson():
E = emission_logs([0, 7, 30], 20.0, 4, eps=0.05)
for t, x in enumerate([0, 7, 30]):
for c in range(4):
assert abs(math.exp(E[t][c]) - poisson_pmf(x, 20.0 * max(c, 0.05) / 2)) < 1e-12
def test_transition_rows_sum_to_one():
for K in (1, 2, 5):
for row in transition_logs(K, 0.1):
assert abs(sum(math.exp(v) for v in row) - 1.0) < 1e-12
def test_viterbi_and_forward_against_brute_force():
rng = random.Random(4)
for K, n in [(2, 1), (2, 8), (3, 7), (4, 5), (5, 4)]:
for _ in range(6):
init, T, E = random_model(rng, K, n)
path, score = viterbi(init, T, E)
bpath, bscore, btotal = brute(init, T, E)
assert abs(score - bscore) < 1e-9
assert path == bpath
assert abs(path_log_prob(path, init, T, E) - score) < 1e-9
_, total = forward(init, T, E)
assert abs(total - btotal) < 1e-9
def test_backward_agrees_with_forward():
rng = random.Random(5)
init, T, E = random_model(rng, 3, 9)
_, total = forward(init, T, E)
B = backward(T, E)
assert abs(logsumexp(init[c] + E[0][c] + B[0][c] for c in range(3)) - total) < 1e-9
for row in posteriors(init, T, E):
assert abs(sum(row) - 1.0) < 1e-12
def test_example_calls():
path, segs = call_copy_number(EXAMPLE, K=4, p=0.1, lam=20.0)
assert path == [2, 2, 1, 1, 1, 2, 2, 3, 3, 3]
assert segs == [(0, 2, 2), (2, 5, 1), (5, 7, 2), (7, 10, 3)]
init = [-math.log(4)] * 4
T, E = transition_logs(4, 0.1), emission_logs(EXAMPLE, 20.0, 4)
bpath, bscore, btotal = brute(init, T, E)
assert path == bpath
assert abs(bscore - (-36.532)) < 1e-3
assert abs(btotal - (-35.482)) < 1e-3
# The two diploid windows between the loss and the gain are not sure calls, and at
# window 6 the state of largest posterior (3) is not the Viterbi state (2).
post = posteriors(init, T, E)
assert 0.57 < post[5][2] < 0.58
assert 0.48 < post[6][2] < 0.49 < 0.51 < post[6][3] < 0.52
# With p = 0.05 one jump from 1 to 3 is cheaper than the two jumps 1 to 2 to 3.
path, _ = call_copy_number(EXAMPLE, K=4, p=0.05, lam=20.0)
assert path == [2, 2, 1, 1, 1, 3, 3, 3, 3, 3]
def test_sticky_transition_merges_short_runs():
# A very small switch probability makes one odd window too costly to call.
path, _ = call_copy_number([20, 20, 20, 40, 20, 20, 20], K=5, p=1e-6, lam=20.0)
assert path == [2] * 7
path, _ = call_copy_number([20, 20, 20, 40, 20, 20, 20], K=5, p=0.1, lam=20.0)
assert path == [2, 2, 2, 4, 2, 2, 2]
def test_segments_and_empty():
assert segments([]) == []
assert segments([1, 1, 0, 0, 0, 2]) == [(0, 2, 1), (2, 5, 0), (5, 6, 2)]
assert call_copy_number([]) == ([], [])
assert viterbi([0.0], [[0.0]], []) == ([], 0.0)
def test_simulated_genome():
rng = random.Random(2007)
truth = [(0, 120, 2), (120, 150, 1), (150, 260, 2), (260, 300, 3), (300, 320, 0), (320, 400, 2)]
lam = 20.0
states, counts = [], []
for lo, hi, c in truth:
for _ in range(lo, hi):
states.append(c)
counts.append(poisson(rng, lam * max(c, 0.05) / 2))
path, segs = call_copy_number(counts, K=5, p=1e-3)
wrong = sum(a != b for a, b in zip(path, states))
assert wrong <= 4
assert len(segs) == len(truth)
for (lo, hi, c), (lo2, hi2, c2) in zip(segs, truth):
assert c == c2 and abs(lo - lo2) <= 2 and abs(hi - hi2) <= 2
# The mean count of the diploid windows is close to lam: z = 4 times sigma over sqrt(n).
diploid = [x for x, c in zip(counts, states) if c == 2]
mean = sum(diploid) / len(diploid)
assert abs(mean - lam) <= 4 * math.sqrt(lam) / math.sqrt(len(diploid))
History
Fridlyand, Snijders, Pinkel, Albertson and Jain (2004) segmented array CGH data with a hidden Markov model whose states are levels of copy number, fitted by expectation maximization and decoded by Viterbi. Wang et al. (2007) built PennCNV, which combines the log R ratio and the B allele frequency of SNP arrays in one HMM. With whole-genome and exome sequencing, the same model was applied to read depth in windows or exome targets, in tools such as XHMM.
References
- Jane Fridlyand, Antoine M. Snijders, Dan Pinkel, Donna G. Albertson and Ajay N. Jain, Hidden Markov models approach to the analysis of array CGH data, Journal of Multivariate Analysis 90(1), 2004, pp. 132 to 153 (an HMM along each chromosome with states for copy number levels, fitted by EM and decoded by Viterbi)
- Kai Wang, Mingyao Li, Dexter Hadley and others, PennCNV, an integrated hidden Markov model designed for high-resolution copy number variation detection in whole-genome SNP genotyping data, Genome Research 17(11), 2007, the sections on the hidden states of copy number, the emissions of the log R ratio and the B allele frequency, and the transitions
- Lawrence R. Rabiner, A tutorial on hidden Markov models and selected applications in speech recognition, Proceedings of the IEEE 77(2), 1989, the sections on the forward procedure and the Viterbi algorithm
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 HP6C4B Edit this page History Report an error Markdown