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 given known haplotypes from the same population. It builds as a mosaic: along the sequence, 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 time for sites, and it is the core of most methods for haplotype phasing, genotype imputation and local ancestry inference.
The machine
Data. Known haplotypes and a new haplotype , over biallelic sites in order along a chromosome. is the scaled recombination rate between sites and , times their distance, where is the effective population size and the recombination rate per generation per unit distance.
Hidden state. is the known haplotype that copies at site .
Start. is uniform on .
Transitions. With ,
So the chain keeps the same haplotype with probability , and moves to each other one with probability . In words, a recombination event happens with probability , and then the next haplotype to copy is uniform, which may be the same one.
Emissions. With a mutation parameter ,
Li and Stephens set , from Watterson's estimator of 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 per state once the total is known. With and forward vectors scaled to sum to 1:
LS-FORWARD(h_1..h_K, h, rho, theta)- 1
alpha(x) ← e_1(x) / K for each x - 2
c_1 ← sum of alpha; divide alpha by c_1 - 3
for j = 2 to m do - 4
s ← 1 - exp(-rho_{j-1} / K); jump ← s / K - 5
alpha(x) ← ((1 - s) alpha(x) + jump) e_j(x) for each x ▷ uses sum of alpha = 1 - 6
c_j ← sum of alpha - 7
divide alpha by c_j - 8
return 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 time each.
A step by hand. Take , , , , , and , so . A match has probability and a mismatch ; the chain stays with probability and switches with probability . Without scaling, the forward values are at site 1 and at site 2. Both haplotypes carry 1 at site 3, so . The posterior probability that copies at site 2 is .
What it counts
- The conditional probability. , 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 , Li and Stephens multiply a probability for by the conditionals for . 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 , it gives estimates of recombination rates and of hotspots.
- The copying path. The posterior of tells which known haplotype is closest to near site . Summed by population, this gives the local ancestry of , and summed by donor it gives the "painting" of a genome by donors.
- Missing alleles. For a site where is missing, the posterior predictive allele is , 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 is large, and less so when is large. Recombination makes the closest haplotype change along the sequence. The rate of change falls like , 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 , 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 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 instead of .
- 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 , 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 time, as shown in the proof for this page. A sample of haplotypes, each conditioned on the others, takes time.
- The limits of . With all , . As all , the sites are independent and .
- 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 , a new haplotype over sites , switch probabilities for , and emission probabilities , which are or . The transition is , and the start is uniform. With , every .
Lemma 1 (the model is a distribution). Each row of sums to 1, and summed over the two alleles of is 1.
Proof. , and all entries are at least . The two emission values add to .
Lemma 2 (the forward recursion). Let . Then and
Proof. The first claim is the uniform start times the emission. For the second, condition on : given , the next state does not depend on , and depends only on . So , and .
Theorem 1 (the scaled pass). Let and be the values after lines L2 and L7 at site in the code. Then , , and the returned value is .
Proof. By induction on . At , line L1 computes , and , so . Suppose the claim holds at . Then , so line L5 computes
by Lemma 2. Its sum at line L6 is , and line L7 divides by it, which gives . Finally by the chain rule, so the sum of is . Every because every emission is positive, so the logarithms are defined.
Theorem 2 (backward and posterior). Let , with . The code computes , and .
Proof. Conditioning on gives . The code applies this to and divides by , so by induction from each equals . Then .
Theorem 3 (most likely path). most_likely_path returns a path that maximizes .
Proof. Let be the largest log probability of a path ending in state at site together with . The Viterbi recursion is . The transition takes only two values: for and for , and the first is at least the second. So the maximum is the larger of and , where maximizes . If , the first term wins, so it is correct to use even when it equals . 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.
Complexity. Lines L4 to L7 cost per site, because the sum over the previous state is replaced by the constant term . So the forward pass takes time and extra space beyond the stored vectors. The backward pass computes once per site, and the Viterbi pass finds once per site, so both are . The reference function enumerate_likelihood sums over all 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.
# 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
- 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)
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H2 full proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag QN36N8 Edit this page History Report an error Markdown