Algorithm Search⌘K

Modeladvanced

Li-Stephens haplotype copying model

Also called Li and Stephens model, product of approximate conditionals.

An HMM that builds a new haplotype as a mosaic of known ones, with switches for recombination and errors for mutation.

The Li-Stephens model gives a probability to a new haplotype hh given KK known haplotypes from the same population. It builds hh as a mosaic: along the sequence, hh copies one of the known haplotypes, switches to another at a rate set by the recombination rate, and at each site differs from the copied allele with a small probability set by the mutation rate. This is a hidden Markov model whose hidden state is the haplotype being copied. Li and Stephens (2003) proposed it as a simple approximation to the conditional distribution of a new haplotype under the coalescent with recombination, which has no closed form. Its forward and backward passes cost O(mK)O(mK) time for mm sites, and it is the core of most methods for haplotype phasing, genotype imputation and local ancestry inference.

The machine

Data. Known haplotypes h1,…,hKh_1, \ldots, h_K and a new haplotype hh, over mm biallelic sites in order along a chromosome. ρj≥0\rho_j \ge 0 is the scaled recombination rate 4Ner4 N_e r between sites jj and j+1j + 1, times their distance, where NeN_e is the effective population size and rr the recombination rate per generation per unit distance.

Hidden state. Xj∈{1,…,K}X_j \in \{1, \ldots, K\} is the known haplotype that hh copies at site jj.

Start. X1X_1 is uniform on {1,…,K}\{1, \ldots, K\}.

Transitions. With sj=1−e−ρj/Ks_j = 1 - e^{-\rho_j / K},

P(Xj+1=y∣Xj=x)=(1−sj) [x=y]+sjK.P(X_{j+1} = y \mid X_j = x) = (1 - s_j)\,[x = y] + \frac{s_j}{K}.

So the chain keeps the same haplotype with probability e−ρj/K+(1−e−ρj/K)/Ke^{-\rho_j / K} + (1 - e^{-\rho_j / K})/K, and moves to each other one with probability (1−e−ρj/K)/K(1 - e^{-\rho_j / K})/K. In words, a recombination event happens with probability sjs_j, and then the next haplotype to copy is uniform, which may be the same one.

Emissions. With a mutation parameter θ~>0\tilde\theta > 0,

P(hj=hXj,j)=K+θ~/2K+θ~,P(hj≠hXj,j)=θ~/2K+θ~.P(h_j = h_{X_j, j}) = \frac{K + \tilde\theta / 2}{K + \tilde\theta}, \qquad P(h_j \ne h_{X_j, j}) = \frac{\tilde\theta / 2}{K + \tilde\theta}.

Li and Stephens set θ~=(∑i=1K−11/i)−1\tilde\theta = \big(\sum_{i=1}^{K-1} 1/i\big)^{-1}, from Watterson's estimator of θ\theta per site.

Standing assumptions. The known haplotypes are fixed and phased. Sites are biallelic. Switches and mismatches at different places are independent given the path. The model has no notion of the tree that relates the known haplotypes to each other.

The forward algorithm. The transition is a mix of "stay" and "jump to a uniform state", so the sum over the previous state takes O(1)O(1) per state once the total is known. With ej(x)=P(hj∣Xj=x)e_j(x) = P(h_j \mid X_j = x) and forward vectors scaled to sum to 1:

  1. LS-FORWARD(h_1..h_K, h, rho, theta)
  2. 1alpha(x) ← e_1(x) / K for each x
  3. 2c_1 ← sum of alpha; divide alpha by c_1
  4. 3for j = 2 to m do
  5. 4s ← 1 - exp(-rho_{j-1} / K); jump ← s / K
  6. 5alpha(x) ← ((1 - s) alpha(x) + jump) e_j(x) for each x ▷ uses sum of alpha = 1
  7. 6c_j ← sum of alpha
  8. 7divide alpha by c_j
  9. 8return log P(h | h_1..h_K) = sum of log c_j

The same structure gives the backward pass, the posterior copying probabilities and the most likely path in O(mK)O(mK) time each.

A step by hand. Take h1=001h_1 = 001, h2=111h_2 = 111, h=011h = 011, K=2K = 2, θ~=1\tilde\theta = 1, and ρ1=ρ2=2ln⁡2\rho_1 = \rho_2 = 2 \ln 2, so s=1/2s = 1/2. A match has probability 5/65/6 and a mismatch 1/61/6; the chain stays with probability 3/43/4 and switches with probability 1/41/4. Without scaling, the forward values are (5/12,1/12)(5/12, 1/12) at site 1 and ((5/12⋅3/4+1/12⋅1/4)⋅1/6, (5/12⋅1/4+1/12⋅3/4)⋅5/6)=(1/18,5/36)\big((5/12 \cdot 3/4 + 1/12 \cdot 1/4) \cdot 1/6,\ (5/12 \cdot 1/4 + 1/12 \cdot 3/4) \cdot 5/6\big) = (1/18, 5/36) at site 2. Both haplotypes carry 1 at site 3, so P(h)=(1/18+5/36)⋅5/6=35/216≈0.162P(h) = (1/18 + 5/36) \cdot 5/6 = 35/216 \approx 0.162. The posterior probability that hh copies h2h_2 at site 2 is 5/75/7.

What it counts

  • The conditional probability. π^(h∣h1,…,hK)\hat\pi(h \mid h_1, \ldots, h_K), the probability of the new haplotype given the known ones, is the output of the forward algorithm.
  • A likelihood for a sample. For a sample h1,…,hnh_1, \ldots, h_n, Li and Stephens multiply a probability for h1h_1 by the conditionals π^(hk∣h1,…,hk−1)\hat\pi(h_k \mid h_1, \ldots, h_{k-1}) for k=2,…,nk = 2, \ldots, n. This is not a true joint probability: it depends on the order of the haplotypes, and they average it over several random orders. As a function of the ρj\rho_j, it gives estimates of recombination rates and of hotspots.
  • The copying path. The posterior of XjX_j tells which known haplotype is closest to hh near site jj. Summed by population, this gives the local ancestry of hh, and summed by donor it gives the "painting" of a genome by donors.
  • Missing alleles. For a site where hh is missing, the posterior predictive allele is ∑xP(Xj=x∣h) P(allele∣Xj=x)\sum_x P(X_j = x \mid h)\, P(\text{allele} \mid X_j = x), which is the basis of imputation.

Relation to other models

  • Coalescent with recombination. The true conditional distribution of a new haplotype comes from the ancestral recombination graph, and has no closed form. The copying model keeps the main features: the new haplotype tends to look like an existing one, more so when KK is large, and less so when θ\theta is large. Recombination makes the closest haplotype change along the sequence. The rate of change falls like ρ/K\rho / K, because with more known haplotypes the new lineage joins their tree sooner, so recombination has less time to act.
  • The model without recombination. With all ρj=0\rho_j = 0, the path never switches, and the model is a mixture over which known haplotype is copied, close to the conditional of Stephens, Smith and Donnelly (2001) used in PHASE.
  • Hidden Markov models. It is an HMM with KK states and a transition matrix of rank-one-plus-identity form, so the forward algorithm, the forward-backward algorithm and the Viterbi algorithm all run in O(mK)O(mK) instead of O(mK2)O(mK^2).
  • Admixture HMMs. The linkage model of Falush and coauthors and HAPMIX switch among a few ancestral populations instead of among haplotypes, or among haplotypes grouped by population. See local ancestry inference.
  • Matching structures. The positional Burrows-Wheeler transform finds the known haplotypes with the longest exact matches to hh, which methods use to keep only a few states per region.

Known results in the model

  • Linear time. One forward pass, one backward pass, the posterior and the most likely path each take O(mK)O(mK) time, as shown in the proof for this page. A sample of nn haplotypes, each conditioned on the others, takes O(mn2)O(mn^2) time.
  • The limits of ρ\rho. With all ρj=0\rho_j = 0, P(h)=1K∑x∏jej(x)P(h) = \frac{1}{K} \sum_x \prod_j e_j(x). As all ρj→∞\rho_j \to \infty, the sites are independent and P(h)=∏j1K∑xej(x)P(h) = \prod_j \frac{1}{K} \sum_x e_j(x).
  • Bias of the rate estimates. Li and Stephens found that the recombination rates estimated from the product of conditionals are biased, and gave a modified conditional that reduces the bias in simulations.
  • Hotspots. Applied to SNP data in human genes, the model detected local peaks of recombination rate that match hotspots found by sperm typing.
  • Phasing and imputation. Methods such as PHASE, IMPUTE, SHAPEIT, Beagle and Eagle use this model, or a close variant, as the conditional distribution of a haplotype given a reference panel or the other haplotypes in the sample. For large panels they restrict the states to a few haplotypes chosen by matching.
Proof: The scaled forward pass computes the probability of the new haplotype in O(mK) time, and the backward, posterior and most likely path use the same structurefull

Setting. Known haplotypes h1,…,hKh_1, \ldots, h_K, a new haplotype hh over sites 1,…,m1, \ldots, m, switch probabilities sj=1−e−ρj/K∈[0,1)s_j = 1 - e^{-\rho_j / K} \in [0, 1) for j=1,…,m−1j = 1, \ldots, m - 1, and emission probabilities ej(x)=P(hj∣Xj=x)e_j(x) = P(h_j \mid X_j = x), which are (K+θ~/2)/(K+θ~)(K + \tilde\theta/2)/(K + \tilde\theta) or (θ~/2)/(K+θ~)(\tilde\theta/2)/(K + \tilde\theta). The transition is Tj(x,y)=(1−sj)[x=y]+sj/KT_j(x, y) = (1 - s_j)[x = y] + s_j / K, and the start is uniform. With θ~>0\tilde\theta > 0, every ej(x)>0e_j(x) > 0.

Lemma 1 (the model is a distribution). Each row of TjT_j sums to 1, and ej(x)e_j(x) summed over the two alleles of hjh_j is 1.

Proof. ∑yTj(x,y)=(1−sj)+K⋅sj/K=1\sum_y T_j(x, y) = (1 - s_j) + K \cdot s_j / K = 1, and all entries are at least sj/K≥0s_j / K \ge 0. The two emission values add to (K+θ~)/(K+θ~)=1(K + \tilde\theta)/(K + \tilde\theta) = 1. □\square

Lemma 2 (the forward recursion). Let Aj(x)=P(h1,…,hj,Xj=x)A_j(x) = P(h_1, \ldots, h_j, X_j = x). Then A1(x)=e1(x)/KA_1(x) = e_1(x)/K and

Aj+1(y)=ej+1(y)[(1−sj)Aj(y)+sjK∑xAj(x)].A_{j+1}(y) = e_{j+1}(y)\Big[(1 - s_j) A_j(y) + \frac{s_j}{K} \sum_x A_j(x)\Big].

Proof. The first claim is the uniform start times the emission. For the second, condition on XjX_j: given Xj=xX_j = x, the next state does not depend on h1,…,hjh_1, \ldots, h_j, and hj+1h_{j+1} depends only on Xj+1X_{j+1}. So Aj+1(y)=ej+1(y)∑xAj(x)Tj(x,y)A_{j+1}(y) = e_{j+1}(y) \sum_x A_j(x) T_j(x, y), and ∑xAj(x)Tj(x,y)=(1−sj)Aj(y)+(sj/K)∑xAj(x)\sum_x A_j(x) T_j(x, y) = (1 - s_j) A_j(y) + (s_j / K) \sum_x A_j(x). □\square

Theorem 1 (the scaled pass). Let αj\alpha_j and cjc_j be the values after lines L2 and L7 at site jj in the code. Then αj(x)=Aj(x)/P(h1,…,hj)\alpha_j(x) = A_j(x) / P(h_1, \ldots, h_j), cj=P(hj∣h1,…,hj−1)c_j = P(h_j \mid h_1, \ldots, h_{j-1}), and the returned value is log⁡P(h)\log P(h).

Proof. By induction on jj. At j=1j = 1, line L1 computes A1A_1, and c1=∑xA1(x)=P(h1)c_1 = \sum_x A_1(x) = P(h_1), so α1=A1/P(h1)\alpha_1 = A_1 / P(h_1). Suppose the claim holds at jj. Then ∑xαj(x)=1\sum_x \alpha_j(x) = 1, so line L5 computes

ej+1(y)[(1−sj)αj(y)+sj/K]=ej+1(y)[(1−sj)Aj(y)+(sj/K)∑xAj(x)]P(h1,…,hj)=Aj+1(y)P(h1,…,hj)e_{j+1}(y)\big[(1 - s_j)\alpha_j(y) + s_j/K\big] = \frac{e_{j+1}(y)\big[(1 - s_j) A_j(y) + (s_j/K) \sum_x A_j(x)\big]}{P(h_1, \ldots, h_j)} = \frac{A_{j+1}(y)}{P(h_1, \ldots, h_j)}

by Lemma 2. Its sum at line L6 is P(h1,…,hj+1)/P(h1,…,hj)=P(hj+1∣h1,…,hj)=cj+1P(h_1, \ldots, h_{j+1}) / P(h_1, \ldots, h_j) = P(h_{j+1} \mid h_1, \ldots, h_j) = c_{j+1}, and line L7 divides by it, which gives Aj+1/P(h1,…,hj+1)A_{j+1} / P(h_1, \ldots, h_{j+1}). Finally ∏jcj=P(h1,…,hm)=P(h)\prod_j c_j = P(h_1, \ldots, h_m) = P(h) by the chain rule, so the sum of log⁡cj\log c_j is log⁡P(h)\log P(h). Every cj>0c_j > 0 because every emission is positive, so the logarithms are defined. □\square

Theorem 2 (backward and posterior). Let Bj(x)=P(hj+1,…,hm∣Xj=x)B_j(x) = P(h_{j+1}, \ldots, h_m \mid X_j = x), with Bm=1B_m = 1. The code computes βj=Bj/∏t>jct\beta_j = B_j / \prod_{t > j} c_t, and αj(x)βj(x)=P(Xj=x∣h)\alpha_j(x)\beta_j(x) = P(X_j = x \mid h).

Proof. Conditioning on Xj+1X_{j+1} gives Bj(x)=∑yTj(x,y)ej+1(y)Bj+1(y)=(1−sj)ej+1(x)Bj+1(x)+(sj/K)∑yej+1(y)Bj+1(y)B_j(x) = \sum_y T_j(x, y) e_{j+1}(y) B_{j+1}(y) = (1 - s_j) e_{j+1}(x) B_{j+1}(x) + (s_j/K) \sum_y e_{j+1}(y) B_{j+1}(y). The code applies this to βj+1\beta_{j+1} and divides by cj+1c_{j+1}, so by induction from βm=1\beta_m = 1 each βj\beta_j equals Bj/∏t>jctB_j / \prod_{t > j} c_t. Then αj(x)βj(x)=Aj(x)Bj(x)/∏tct=P(h,Xj=x)/P(h)\alpha_j(x) \beta_j(x) = A_j(x) B_j(x) / \prod_t c_t = P(h, X_j = x) / P(h). □\square

Theorem 3 (most likely path). most_likely_path returns a path that maximizes P(X1,…,Xm,h)P(X_1, \ldots, X_m, h).

Proof. Let Vj(x)V_j(x) be the largest log probability of a path ending in state xx at site jj together with h1,…,hjh_1, \ldots, h_j. The Viterbi recursion is Vj+1(x)=log⁡ej+1(x)+max⁡y[Vj(y)+log⁡Tj(y,x)]V_{j+1}(x) = \log e_{j+1}(x) + \max_y [V_j(y) + \log T_j(y, x)]. The transition takes only two values: log⁡(1−sj+sj/K)\log(1 - s_j + s_j/K) for y=xy = x and log⁡(sj/K)\log(s_j/K) for y≠xy \ne x, and the first is at least the second. So the maximum is the larger of Vj(x)+log⁡(1−sj+sj/K)V_j(x) + \log(1 - s_j + s_j/K) and Vj(y∗)+log⁡(sj/K)V_j(y^*) + \log(s_j/K), where y∗y^* maximizes VjV_j. If y∗=xy^* = x, the first term wins, so it is correct to use y∗y^* even when it equals xx. The code keeps the argument of the maximum as a pointer and traces the pointers back from the best final state, which gives a maximizing path by the usual argument for dynamic programming. □\square

Complexity. Lines L4 to L7 cost O(K)O(K) per site, because the sum over the previous state is replaced by the constant term s/Ks/K. So the forward pass takes O(mK)O(mK) time and O(K)O(K) extra space beyond the stored vectors. The backward pass computes ∑yej+1(y)βj+1(y)\sum_y e_{j+1}(y)\beta_{j+1}(y) once per site, and the Viterbi pass finds y∗y^* once per site, so both are O(mK)O(mK). The reference function enumerate_likelihood sums over all KmK^m paths and serves only to check these results on small inputs.

Code

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.

li_stephens_model.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/li-stephens-model/. The authors are listed in prov/QN36N8.jsonl.
"""The Li-Stephens haplotype copying model (Li and Stephens 2003).

A new haplotype h over m biallelic sites is built as a mosaic of K known
haplotypes (the panel). The hidden state X_j in 0..K-1 is the panel
haplotype copied at site j.

  X_1 is uniform on the panel.
  Between sites j and j+1, with s_j = 1 - exp(-rho_j / K), where rho_j is
  the scaled recombination rate 4 Ne r times the distance between the
  sites, the chain switches with probability s_j to a haplotype drawn
  uniformly from the panel (which may be the same one):
      P(X_{j+1} = y | X_j = x) = (1 - s_j) [x == y] + s_j / K.
  At site j, the copy has the allele of the copied haplotype with
  probability (K + theta / 2) / (K + theta), and the other allele with
  probability (theta / 2) / (K + theta).

The default theta is Watterson's 1 / (1 + 1/2 + ... + 1/(K-1)).

The forward algorithm gives P(h | panel) in O(mK) time, because each
transition is a mix of "stay" and "jump to a uniform state". Posterior
copying probabilities come from forward and backward passes.
"""

from __future__ import annotations

import itertools
import math
from typing import Sequence


def watterson_theta(k: int) -> float:
    if k < 2:
        raise ValueError("need at least two panel haplotypes for the default theta")
    return 1.0 / sum(1.0 / i for i in range(1, k))


def emission(k: int, theta: float) -> tuple[float, float]:
    """(probability of copying the allele, probability of the other allele)."""
    return (k + theta / 2.0) / (k + theta), (theta / 2.0) / (k + theta)


def switch_probabilities(rho: Sequence[float], k: int) -> list[float]:
    """s_j = 1 - exp(-rho_j / K) for each of the m - 1 gaps."""
    return [1.0 - math.exp(-r / k) for r in rho]


def check(panel: Sequence[Sequence[int]], h: Sequence[int], rho: Sequence[float], theta: float) -> tuple[int, int]:
    k = len(panel)
    if k == 0:
        raise ValueError("empty panel")
    m = len(h)
    if m == 0:
        raise ValueError("empty haplotype")
    for row in list(panel) + [h]:
        if len(row) != m or any(v not in (0, 1) for v in row):
            raise ValueError("haplotypes must be 0/1 rows of equal length")
    if len(rho) != m - 1 or any(r < 0 for r in rho):
        raise ValueError("need m - 1 nonnegative recombination rates")
    if theta <= 0:
        raise ValueError("theta must be positive, so that every haplotype has positive probability")
    return k, m


def forward(panel: Sequence[Sequence[int]], h: Sequence[int], rho: Sequence[float],
            theta: float | None = None) -> tuple[float, list[list[float]], list[float]]:
    """Scaled forward pass. Returns log P(h | panel), the scaled forward
    vectors (each sums to 1) and the scale factors c_j."""
    if theta is None:
        theta = watterson_theta(len(panel))
    k, m = check(panel, h, rho, theta)
    same, diff = emission(k, theta)
    s = switch_probabilities(rho, k)
    alpha = [(same if panel[x][0] == h[0] else diff) / k for x in range(k)]  # @line L1
    c = sum(alpha)  # @line L2
    alpha = [v / c for v in alpha]
    alphas, scales = [alpha], [c]
    for j in range(1, m):  # @line L3
        jump = s[j - 1] / k  # @line L4
        alpha = [((1.0 - s[j - 1]) * alpha[x] + jump) * (same if panel[x][j] == h[j] else diff)
                 for x in range(k)]  # @line L5
        c = sum(alpha)  # @line L6
        alpha = [v / c for v in alpha]  # @line L7
        alphas.append(alpha)
        scales.append(c)
    return sum(math.log(v) for v in scales), alphas, scales  # @line L8


def backward(panel: Sequence[Sequence[int]], h: Sequence[int], rho: Sequence[float],
             scales: Sequence[float], theta: float) -> list[list[float]]:
    """Backward vectors scaled with the forward factors."""
    k, m = check(panel, h, rho, theta)
    same, diff = emission(k, theta)
    s = switch_probabilities(rho, k)
    beta = [1.0] * k
    betas = [beta]
    for j in range(m - 1, 0, -1):
        e = [(same if panel[y][j] == h[j] else diff) * beta[y] for y in range(k)]
        total = sum(e) / k
        beta = [((1.0 - s[j - 1]) * e[x] + s[j - 1] * total) / scales[j] for x in range(k)]
        betas.append(beta)
    betas.reverse()
    return betas


def posterior(panel: Sequence[Sequence[int]], h: Sequence[int], rho: Sequence[float],
              theta: float | None = None) -> list[list[float]]:
    """P(X_j = x | h, panel) for each site j and panel haplotype x."""
    if theta is None:
        theta = watterson_theta(len(panel))
    _, alphas, scales = forward(panel, h, rho, theta)
    betas = backward(panel, h, rho, scales, theta)
    return [[a * b for a, b in zip(al, be)] for al, be in zip(alphas, betas)]


def path_probability(path: Sequence[int], panel: Sequence[Sequence[int]], h: Sequence[int],
                     rho: Sequence[float], theta: float) -> float:
    """Joint probability of one copying path and the haplotype h."""
    k, m = check(panel, h, rho, theta)
    same, diff = emission(k, theta)
    s = switch_probabilities(rho, k)
    p = 1.0 / k
    for j, x in enumerate(path):
        if j > 0:
            p *= (1.0 - s[j - 1]) * (path[j - 1] == x) + s[j - 1] / k
        p *= same if panel[x][j] == h[j] else diff
    return p


def enumerate_likelihood(panel: Sequence[Sequence[int]], h: Sequence[int], rho: Sequence[float],
                         theta: float) -> tuple[float, list[list[float]]]:
    """P(h | panel) and the posterior copying probabilities, by summing over all K^m paths."""
    k, m = check(panel, h, rho, theta)
    total = 0.0
    marg = [[0.0] * k for _ in range(m)]
    for path in itertools.product(range(k), repeat=m):
        p = path_probability(path, panel, h, rho, theta)
        total += p
        for j, x in enumerate(path):
            marg[j][x] += p
    return total, [[v / total for v in row] for row in marg]


def most_likely_path(panel: Sequence[Sequence[int]], h: Sequence[int], rho: Sequence[float],
                     theta: float | None = None) -> list[int]:
    """Viterbi path in O(mK) time, using the same stay-or-jump structure."""
    if theta is None:
        theta = watterson_theta(len(panel))
    k, m = check(panel, h, rho, theta)
    same, diff = emission(k, theta)
    s = switch_probabilities(rho, k)
    neg = -math.inf

    def lg(v: float) -> float:
        return math.log(v) if v > 0 else neg

    score = [lg(1.0 / k) + lg(same if panel[x][0] == h[0] else diff) for x in range(k)]
    back: list[list[int]] = []
    for j in range(1, m):
        best = max(range(k), key=lambda y: score[y])
        stay, jump = lg(1.0 - s[j - 1] + s[j - 1] / k), lg(s[j - 1] / k)
        new, ptr = [], []
        for x in range(k):
            a, b = score[x] + stay, score[best] + jump
            if a >= b:
                new.append(a)
                ptr.append(x)
            else:
                new.append(b)
                ptr.append(best)
            new[-1] += lg(same if panel[x][j] == h[j] else diff)
        score = new
        back.append(ptr)
    x = max(range(k), key=lambda y: score[y])
    path = [x]
    for ptr in reversed(back):
        x = ptr[x]
        path.append(x)
    path.reverse()
    return path
test_li_stephens_model.py 139 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/li-stephens-model/. The authors are listed in prov/QN36N8.jsonl.

import itertools
import math
import random

import pytest

from li_stephens_model import (emission, enumerate_likelihood, forward, most_likely_path, path_probability,
                               posterior, switch_probabilities, watterson_theta)


def random_case(rng, k, m):
    panel = [[rng.randrange(2) for _ in range(m)] for _ in range(k)]
    h = [rng.randrange(2) for _ in range(m)]
    rho = [rng.choice([0.0, 0.3, 2.0, 10.0]) for _ in range(m - 1)]
    return panel, h, rho


def test_watterson_theta_and_emission():
    assert watterson_theta(2) == 1.0
    assert watterson_theta(3) == pytest.approx(2.0 / 3.0)
    same, diff = emission(4, 1.0)
    assert same == pytest.approx(4.5 / 5.0)
    assert diff == pytest.approx(0.5 / 5.0)
    assert same + diff == pytest.approx(1.0)
    with pytest.raises(ValueError):
        watterson_theta(1)


def test_transition_rows_sum_to_one():
    k = 5
    for s in switch_probabilities([0.0, 0.5, 3.0, 100.0], k):
        for x in range(k):
            row = [(1.0 - s) * (x == y) + s / k for y in range(k)]
            assert sum(row) == pytest.approx(1.0)


def test_example_by_hand():
    panel = [[0, 0, 1], [1, 1, 1]]
    h = [0, 1, 1]
    rho = [2 * math.log(2), 2 * math.log(2)]  # so s = 1/2 in both gaps
    theta = 1.0
    assert switch_probabilities(rho, 2) == pytest.approx([0.5, 0.5])
    logp, _, _ = forward(panel, h, rho, theta)
    total, post = enumerate_likelihood(panel, h, rho, theta)
    assert math.exp(logp) == pytest.approx(total)
    # Emissions 5/6 and 1/6; stay 3/4 and switch 1/4. alpha_1 = (5/12, 1/12),
    # alpha_2 = (1/18, 5/36), and both haplotypes match at the last site.
    assert total == pytest.approx(35 / 216)
    assert post[1] == pytest.approx([2 / 7, 5 / 7])


def test_forward_matches_enumeration():
    rng = random.Random(11)
    for _ in range(60):
        k, m = rng.randint(1, 3), rng.randint(1, 5)
        panel, h, rho = random_case(rng, k, m)
        theta = rng.choice([0.01, 0.2, 1.0]) if k == 1 else rng.choice([None, 0.01, 0.5])
        t = watterson_theta(k) if theta is None else theta
        logp, alphas, _ = forward(panel, h, rho, theta)
        total, _ = enumerate_likelihood(panel, h, rho, t)
        assert logp == pytest.approx(math.log(total), rel=1e-9, abs=1e-9)
        for a in alphas:
            assert sum(a) == pytest.approx(1.0)


def test_posterior_matches_enumeration():
    rng = random.Random(12)
    for _ in range(40):
        k, m = rng.randint(2, 4), rng.randint(1, 4)
        panel, h, rho = random_case(rng, k, m)
        post = posterior(panel, h, rho)
        _, want = enumerate_likelihood(panel, h, rho, watterson_theta(k))
        for row, wrow in zip(post, want):
            assert row == pytest.approx(wrow, abs=1e-9)


def test_viterbi_matches_enumeration():
    rng = random.Random(13)
    for _ in range(40):
        k, m = rng.randint(2, 3), rng.randint(1, 5)
        panel, h, rho = random_case(rng, k, m)
        t = watterson_theta(k)
        path = most_likely_path(panel, h, rho)
        best = max(path_probability(p, panel, h, rho, t) for p in itertools.product(range(k), repeat=m))
        assert path_probability(path, panel, h, rho, t) == pytest.approx(best)


def test_limits_of_rho():
    rng = random.Random(14)
    k, m = 3, 6
    panel, h, _ = random_case(rng, k, m)
    t = watterson_theta(k)
    same, diff = emission(k, t)
    e = [[same if panel[x][j] == h[j] else diff for j in range(m)] for x in range(k)]
    # No recombination: one haplotype is copied along the whole sequence.
    logp, _, _ = forward(panel, h, [0.0] * (m - 1))
    assert math.exp(logp) == pytest.approx(sum(math.prod(row) for row in e) / k)
    # Free recombination: the sites are independent.
    logp, _, _ = forward(panel, h, [1e6] * (m - 1))
    assert math.exp(logp) == pytest.approx(math.prod(sum(e[x][j] for x in range(k)) / k for j in range(m)))


def test_mosaic_is_recovered():
    rng = random.Random(15)
    k, m = 6, 400
    panel = [[rng.randrange(2) for _ in range(m)] for _ in range(k)]
    truth = [0] * 150 + [3] * 130 + [5] * 120
    h = [panel[x][j] for j, x in enumerate(truth)]
    rho = [0.05] * (m - 1)
    path = most_likely_path(panel, h, rho)
    agree = sum(a == b for a, b in zip(path, truth)) / m
    assert agree > 0.95
    post = posterior(panel, h, rho)
    assert sum(post[j][truth[j]] for j in range(m)) / m > 0.9


def test_long_input_does_not_underflow():
    rng = random.Random(16)
    panel, h, rho = random_case(rng, 4, 3000)
    logp, _, _ = forward(panel, h, rho)
    assert math.isfinite(logp) and logp < -100


def test_bad_input():
    with pytest.raises(ValueError):
        forward([], [0], [])
    with pytest.raises(ValueError):
        forward([[0, 1]], [0, 1, 1], [0.1])
    with pytest.raises(ValueError):
        forward([[0, 1], [1, 1]], [0, 1], [])
    with pytest.raises(ValueError):
        forward([[0, 1], [1, 1]], [0, 1], [-1.0])
    with pytest.raises(ValueError):
        forward([[0, 2], [1, 1]], [0, 1], [0.1])
    with pytest.raises(ValueError):
        forward([[0, 1], [1, 1]], [0, 1], [0.1], theta=0.0)

References

  1. Na Li and Matthew Stephens, Modeling linkage disequilibrium and identifying recombination hotspots using single-nucleotide polymorphism data, Genetics 165(4), 2003, pp. 2213-2233 (the copying model, its transition and emission probabilities, the choice of theta, the likelihood of a sample as a product of conditionals, and the estimates of recombination rates)
  2. Matthew Stephens, Nicholas J. Smith and Peter Donnelly, A new statistical method for haplotype reconstruction from population data, American Journal of Human Genetics 68(4), 2001, pp. 978-989 (the conditional distribution of a new haplotype given the others, without recombination, used in PHASE)
  3. Richard Durbin, Efficient haplotype matching and storage using the positional Burrows-Wheeler transform (PBWT), Bioinformatics 30(9), 2014, pp. 1266-1272 (fast matching of a new haplotype to a panel, used to choose copying states)

Where this leads

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 proofH2 full proof
  • correctness: no review record reviews/QN36N8/proof-correctness.yaml
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)
WritingW4 complete
  • a review of the text: no review record reviews/QN36N8/text.yaml