Algorithm Search⌘K

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.

Time
Θ(K^2 n) worst · average · best
Space
Θ(K n) extra
Where
K = the number of copy number states; n = the number of windows
Properties
deterministicexactofflineiterative
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 Θ(K2n)\Theta(K^2 n) for KK states and nn 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 x0,…,xn−1x_0, \ldots, x_{n-1}, one for each window of the same size, after correction for GC content and mappability. The hidden copy numbers are c0,…,cn−1c_0, \ldots, c_{n-1} in {0,…,K−1}\{0, \ldots, K - 1\}. The model of the code is:

  • Emission. xt∣ct=cx_t \mid c_t = c is Poisson with mean λmax⁡(c,ε)/2\lambda \max(c, \varepsilon)/2, where λ\lambda is the mean count of a window with two copies and ε>0\varepsilon > 0 allows a few misplaced reads in a deleted region.
  • Transition. P(ct=ct−1)=1−pP(c_t = c_{t-1}) = 1 - p, and each other state has probability p/(K−1)p/(K - 1).
  • Start. Each state has probability 1/K1/K.

The task is to find c∗=arg⁡max⁡cP(x,c)c^* = \arg\max_c P(x, c), the most probable path, and, if needed, the posterior P(ct=c∣x)P(c_t = c \mid x) of each window. Without a given λ\lambda, 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. E[t][c]E[t][c] is ln⁡P(xt∣c)\ln P(x_t \mid c) and T[b][c]T[b][c] is ln⁡P(c∣b)\ln P(c \mid b).

  1. HMM-CNV(x, K, λ, p)
  2. 1E[t][c] ← x_t ln μ_c - μ_c - ln(x_t!), with μ_c = λ max(c, ε)/2, for each t and c
  3. 2V[0][c] ← ln(1/K) + E[0][c] for each c
  4. 3for t ← 1 to n - 1 do
  5. 4for c ← 0 to K - 1 do
  6. 5V[t][c] ← max_b (V[t - 1][b] + T[b][c]) + E[t][c]
  7. 6ptr[t][c] ← the b that reaches the max, the smallest on ties
  8. 7c*[n - 1] ← the c with the largest V[n - 1][c], the smallest on ties
  9. 8for t ← n - 1 down to 1 do c*[t - 1] ← ptr[t][c*[t]]
  10. 9return c* and its runs of equal states as segments

V[t][c]V[t][c] is the log probability of the best path that ends in state cc at window tt, joint with the first t+1t + 1 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 λ=20\lambda = 20, K=4K = 4 states (0 to 3 copies) and p=0.1p = 0.1:

x=(19,22,10,8,11,20,21,32,29,31).x = (19, 22, 10, 8, 11, 20, 21, 32, 29, 31).

The state means are 0.5, 10, 20 and 30. Three rows of the emission table, ln⁡P(xt∣c)\ln P(x_t \mid c):

window count c=0c = 0 c=1c = 1 c=2c = 2 c=3c = 3
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 ln⁡(0.1/3)=−3.40\ln(0.1/3) = -3.40 and staying costs ln⁡0.9=−0.105\ln 0.9 = -0.105. The Viterbi path is

c∗=(2,2,1,1,1,2,2,3,3,3),c^* = (2, 2, 1, 1, 1, 2, 2, 3, 3, 3),

with ln⁡P(x,c∗)=−36.53\ln P(x, c^*) = -36.53: a loss of one copy in windows 2 to 4 and a gain in windows 7 to 9. The forward algorithm gives ln⁡P(x)=−35.48\ln P(x) = -35.48, so this one path has about 35% of the probability of the data.

The posteriors show where the path is unsure. At window 5, P(c=2∣x)=0.574P(c = 2 \mid x) = 0.574. At window 6, P(c=2∣x)=0.485P(c = 2 \mid x) = 0.485 and P(c=3∣x)=0.512P(c = 3 \mid x) = 0.512, 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 p=0.05p = 0.05, a change costs more, and the path becomes (2,2,1,1,1,3,3,3,3,3)(2, 2, 1, 1, 1, 3, 3, 3, 3, 3): 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 −37.62-37.62, against −38.29-38.29 for the path with the 2-copy stretch. The value of pp sets the shortest segment that the method can call.

Correctness

By induction on tt, V[t][c]V[t][c] is the largest ln⁡P(x0,…,xt,c0,…,ct)\ln P(x_0, \ldots, x_t, c_0, \ldots, c_t) over the paths with ct=cc_t = c: the joint probability of a path is the product of its start, transitions and emissions, so the best path into cc at tt is the best path into some bb at t−1t - 1 plus one step, which is line L5. Line L6 stores the bb, 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 KnK^n 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 n≥1n \ge 1 windows with counts x0,…,xn−1x_0, \ldots, x_{n-1} and KK hidden states 0,…,K−10, \ldots, K - 1, the copy numbers. The model is a hidden Markov chain c0,…,cn−1c_0, \ldots, c_{n-1} with start probabilities π(c)\pi(c), transition probabilities A(b,c)=P(ct=c∣ct−1=b)A(b, c) = P(c_t = c \mid c_{t-1} = b) and emission probabilities ec(x)=P(xt=x∣ct=c)e_c(x) = P(x_t = x \mid c_t = c). Given the states, the counts are independent, and xtx_t depends only on ctc_t. So for a path c=(c0,…,cn−1)c = (c_0, \ldots, c_{n-1}),

P(x,c)=π(c0) ec0(x0)∏t=1n−1A(ct−1,ct) ect(xt).P(x, c) = \pi(c_0)\, e_{c_0}(x_0) \prod_{t=1}^{n-1} A(c_{t-1}, c_t)\, e_{c_t}(x_t).

In the code, π(c)=1/K\pi(c) = 1/K, A(b,b)=1−pA(b, b) = 1 - p, A(b,c)=p/(K−1)A(b, c) = p / (K - 1) for c≠bc \ne b, and ece_c is the Poisson law with mean λmax⁡(c,ε)/2\lambda \max(c, \varepsilon)/2. The proof uses only the product form above, so it holds for any start, transition and emission tables. All values are logarithms: E[t][c]=ln⁡ec(xt)E[t][c] = \ln e_c(x_t) (line L1), T[b][c]=ln⁡A(b,c)T[b][c] = \ln A(b, c), and ln⁡0=−∞\ln 0 = -\infty.

Lemma 1 (Viterbi table). After line L2, and after lines L4 to L6 for step tt, V[t][c]=max⁡ln⁡P(x0,…,xt,c0,…,ct)V[t][c] = \max \ln P(x_0, \ldots, x_t, c_0, \ldots, c_t) over the paths c0,…,ctc_0, \ldots, c_t with ct=cc_t = c.

Proof. By induction on tt. For t=0t = 0 the only path is (c)(c), and line L2 sets V[0][c]=ln⁡π(c)+E[0][c]V[0][c] = \ln \pi(c) + E[0][c]. For t>0t > 0, by the product form,

ln⁡P(x0..t,c0..t)=ln⁡P(x0..t−1,c0..t−1)+T[ct−1][ct]+E[t][ct].\ln P(x_{0..t}, c_{0..t}) = \ln P(x_{0..t-1}, c_{0..t-1}) + T[c_{t-1}][c_t] + E[t][c_t].

Fix ct=cc_t = c and split the paths by b=ct−1b = c_{t-1}. For fixed bb, the largest value of the first term is V[t−1][b]V[t-1][b] by the hypothesis, and the other two terms do not depend on c0,…,ct−2c_0, \ldots, c_{t-2}. So the maximum over the paths is max⁡b(V[t−1][b]+T[b][c])+E[t][c]\max_b (V[t-1][b] + T[b][c]) + E[t][c], which is line L5. □\square

Lemma 2 (back pointers). For t≥1t \ge 1, the state b=ptr[t][c]b = \mathrm{ptr}[t][c] of line L6 satisfies V[t][c]=V[t−1][b]+T[b][c]+E[t][c]V[t][c] = V[t-1][b] + T[b][c] + E[t][c].

Proof. Line L6 stores the bb that reaches the maximum of line L5, the smallest such bb if several do. □\square

Theorem 1 (Viterbi). The path c∗c^* of lines L7 and L8 maximizes P(x,c)P(x, c) over all KnK^n paths, and V[n−1][cn−1∗]=ln⁡P(x,c∗)V[n-1][c^*_{n-1}] = \ln P(x, c^*). 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, max⁡cV[n−1][c]\max_c V[n-1][c] is the largest ln⁡P(x,c)\ln P(x, c) over all paths, and line L7 takes a state cn−1∗c^*_{n-1} that reaches it. Line L8 sets ct−1∗=ptr[t][ct∗]c^*_{t-1} = \mathrm{ptr}[t][c^*_t]. By Lemma 2, for each t≥1t \ge 1, V[t][ct∗]=V[t−1][ct−1∗]+T[ct−1∗][ct∗]+E[t][ct∗]V[t][c^*_t] = V[t-1][c^*_{t-1}] + T[c^*_{t-1}][c^*_t] + E[t][c^*_t]. Adding these equations for t=1,…,n−1t = 1, \ldots, n-1 to V[0][c0∗]=ln⁡π(c0∗)+E[0][c0∗]V[0][c^*_0] = \ln \pi(c^*_0) + E[0][c^*_0] gives V[n−1][cn−1∗]=ln⁡P(x,c∗)V[n-1][c^*_{n-1}] = \ln P(x, c^*), so c∗c^* reaches the maximum. □\square

The tests check Theorem 1 against a search over all KnK^n paths for small KK and nn.

Theorem 2 (forward and posteriors). The forward table satisfies F[t][c]=ln⁡P(x0,…,xt,ct=c)F[t][c] = \ln P(x_0, \ldots, x_t, c_t = c), and its last value is ln⁡P(x)=ln⁡∑cF[n−1][c]\ln P(x) = \ln \sum_{c} F[n-1][c] in log space. The backward table satisfies B[t][c]=ln⁡P(xt+1,…,xn−1∣ct=c)B[t][c] = \ln P(x_{t+1}, \ldots, x_{n-1} \mid c_t = c), and exp⁡(F[t][c]+B[t][c]−ln⁡P(x))=P(ct=c∣x)\exp(F[t][c] + B[t][c] - \ln P(x)) = P(c_t = c \mid x).

Proof. The forward claim is Lemma 1 with the maximum over bb replaced by a sum over bb, which is valid for the same reason: the sum over the paths with ct=cc_t = c splits by b=ct−1b = c_{t-1}, and the last two factors do not depend on the earlier states. The code forms the sum of exponentials with log-sum-exp, ln⁡∑beub=M+ln⁡∑beub−M\ln \sum_b e^{u_b} = M + \ln \sum_b e^{u_b - M} with M=max⁡bubM = \max_b u_b, which is an identity. For the backward table, B[n−1][c]=0=ln⁡1B[n-1][c] = 0 = \ln 1, and by the Markov property

P(xt+1..n−1∣ct=c)=∑dA(c,d) ed(xt+1) P(xt+2..n−1∣ct+1=d),P(x_{t+1..n-1} \mid c_t = c) = \sum_d A(c, d)\, e_d(x_{t+1})\, P(x_{t+2..n-1} \mid c_{t+1} = d),

which is the code. Last, P(x,ct=c)=P(x0..t,ct=c) P(xt+1..n−1∣ct=c)P(x, c_t = c) = P(x_{0..t}, c_t = c)\, P(x_{t+1..n-1} \mid c_t = c), because given ctc_t the later counts do not depend on the earlier states and counts. Dividing by P(x)P(x) gives the posterior. □\square

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 p=0.1p = 0.1, 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 Θ(nK)\Theta(n K). Each step of line L3 does KK maximizations over KK values, so the Viterbi pass takes Θ(nK2)\Theta(n K^2) time and keeps Θ(nK)\Theta(n K) back pointers; the forward and backward passes have the same cost. With the transition matrix of the code, max⁡b(V[b]+T[b][c])\max_b (V[b] + T[b][c]) is the larger of V[c]+ln⁡(1−p)V[c] + \ln(1 - p) and max⁡b≠cV[b]+ln⁡(p/(K−1))\max_{b \ne c} V[b] + \ln(p/(K-1)). The two largest values of VV give max⁡b≠cV[b]\max_{b \ne c} V[b] for every cc, so a pass can be done in Θ(nK)\Theta(n K) time. The code uses the general Θ(nK2)\Theta(n K^2) loop.

Complexity

  • Time. Line L1 is Θ(Kn)\Theta(K n). Each window does KK maximizations over KK states, so the Viterbi pass is Θ(K2n)\Theta(K^2 n), and so are the forward and backward passes.
  • A faster step. With the transition matrix of this page, the best predecessor of cc is cc itself or the best other state, so one step can be done in Θ(K)\Theta(K) with the two largest values of VV, for Θ(Kn)\Theta(K n) in total. The code keeps the general loop.
  • Space. The back pointers take Θ(Kn)\Theta(K n). The forward and backward tables take Θ(Kn)\Theta(K n) for posteriors.
  • Training. If λ\lambda, pp or the emissions are learned with Baum-Welch, each iteration costs one forward and one backward pass, Θ(K2n)\Theta(K^2 n), and the number of iterations depends on the data.

Properties

  • Exact for its model. Viterbi returns a most probable path, and forward returns P(x)P(x), 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 pp 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 cc 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 λ\lambda 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 pp. 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.

biostoch.pyI0RawGitHub
# 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

  1. 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)
  2. 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
  3. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example