Algorithmcore
EM haplotype frequency estimation
Also called Excoffier-Slatkin algorithm.
Estimate haplotype frequencies from unphased genotypes with EM. Split each genotype over its compatible haplotype pairs, then count again.
- Time
- O(T n m 2^h) worst · averageO(n m) best
- Space
- O(n m 2^h) extra
- Where
- T = the number of iterations; h = the largest number of heterozygous sites in one genotype; m = the number of sites; n = the number of individuals
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Laurent Excoffier, Montgomery Slatkin, 1995
EM haplotype frequency estimation finds the maximum likelihood frequencies of multi-site haplotypes from genotypes whose phase is not known. A genotype tells how many copies of each allele an individual has at each site, but not which alleles sit together on one chromosome. The algorithm is the expectation-maximization method for this missing phase: it splits each individual over the haplotype pairs that fit its genotype, in proportion to their current probability, and then counts the haplotypes again. Excoffier and Slatkin published it in 1995, at the same time as two other groups. It estimates frequencies in the population. It does not by itself give the best phase of each individual; that is the haplotype phasing problem.
In plain words
Each person has two copies of a chromosome. A genotype test tells you, at each site, whether the person has zero, one or two copies of a variant, but it does not tell you which copy carries which variant. If a person differs between the two copies at only one site, there is only one way to split the genotype. If the person differs at two or more sites, there are several ways.
The method keeps a guess of how common each full haplotype is. For each person, it shares the person out over the possible splits, with more weight on splits made of common haplotypes. Then it counts all the haplotypes again, with these shares, to make a new guess. It repeats these two steps. Each round makes the data at least as likely as before.
The problem
Input. Genotypes of diploid individuals at biallelic sites. Here is the number of copies of allele 1 that individual has at site . A haplotype is a vector .
Model. The two haplotypes of each individual are drawn independently from one frequency vector , and the individuals are independent. This is Hardy-Weinberg proportions for haplotypes. A pair is compatible with when site by site. Let be the set of unordered compatible pairs. Then
because an ordered pair with two different haplotypes can occur in two orders.
Output. A frequency vector on the simplex that is a stationary point of the log-likelihood , and the value .
If has heterozygous sites, then for and for : each heterozygous site can put allele 1 on either haplotype, and swapping the two haplotypes gives the same unordered pair.
The algorithm
EM-HAPLOTYPES(g_1, ..., g_n, T, ε)- 1
for each individual i, list the compatible pairs S_i ← S(g_i) - 2
H ← the haplotypes that occur in some pair; p_h ← 1/|H| for each h in H - 3
repeat at most T times - 4
c_h ← 0 for each h in H ▷ expected copies of h - 5
for each individual i do - 6
P_i ← Σ over {h, h'} in S_i of w(h, h') p_h p_h' - 7
for each {h, h'} in S_i: e ← w(h, h') p_h p_h' / P_i; c_h ← c_h + e; c_h' ← c_h' + e - 8
p_h ← c_h / (2n) for each h in H ▷ M-step: gene counting - 9
if ℓ(p) gained less than ε in this round then stop - 10
return p
Line L7 is the E-step: is the posterior probability that the individual carries the pair . When , both updates of line L7 go to the same haplotype, which then gets two copies. Line L8 is the M-step: the expected number of copies of each haplotype over the total . A haplotype that is in no compatible pair has zero likelihood weight and never enters .
Example
Ten individuals at two sites. The sum of allele 1 counts over the two sites gives these genotype classes, written as :
| genotype | (0, 0) | (0, 1) | (1, 0) | (1, 1) | (1, 2) | (2, 2) |
|---|---|---|---|---|---|---|
| individuals | 2 | 1 | 1 | 3 | 1 | 2 |
Only the three double heterozygotes are ambiguous: each is (the cis pair) or (the trans pair). The other seven individuals give 14 haplotype copies directly: 6 of 00, 2 of 01, 1 of 10 and 5 of 11.
Round 1. From the uniform start, each double heterozygote splits and . The counts are , , and out of 20, so for 00, 01, 10 and 11. The log-likelihood rises from to .
Round 2. The cis weight is and the trans weight is , so each double heterozygote is cis with probability . The new frequency of 00 is .
Limit. After 13 rounds the gain is below , and with . Each double heterozygote is now cis with probability . The allele frequencies are and , the sample values. The linkage disequilibrium of the estimate is , and .
Correctness
The proof has three parts. First, line L7 computes the exact posterior probability of each compatible pair under the current , by Bayes' rule on the model. Second, line L8 maximizes the expected complete-data log-likelihood, because the complete data are independent draws from , and the maximum likelihood estimate of a multinomial is the vector of observed shares. Third, the general EM inequality gives . The log-likelihood is bounded above by 0, so the values converge. At a fixed point with all , the gradient of is the same for all in , which is the stationarity condition on the simplex. A further fact helps in practice: after the first round, the allele frequency at each site equals its sample value, since every compatible pair of an individual holds the same alleles. The full proof is below.
Proof: Each round of EM computes the exact posterior of the phase, never lowers the likelihood, and its fixed points are stationary pointsfull
Setting. Individuals have genotypes . The unobserved complete data are the ordered haplotype pairs , independent over , with and independent draws from on . We observe . Write for the set of unordered pairs with , and if , else 2. Let be the set of haplotypes that occur in some .
Lemma 1 (enumeration). If has heterozygous sites, then , and every pair in has . If , then has the one pair with .
Proof. At a site with , both haplotypes have the allele . At a heterozygous site, one haplotype has 0 and the other 1. An ordered pair is fixed by the choice, at each of the heterozygous sites, of which haplotype has 1: ordered pairs. When , the two haplotypes differ at a heterozygous site, so each unordered pair comes from exactly two ordered pairs. Fixing allele 0 on the first haplotype at the first heterozygous site picks one of the two, which is how the code lists them.
Lemma 2 (E-step). For , with .
Proof. The event is the union of the ordered events and , which are the same event when . Its probability is . These events for the pairs of are disjoint, and their union is the event , so . Bayes' rule gives the ratio.
So line L7 adds to the posterior expected number of copies of carried by individual : one copy for each side of the pair, and two copies when . After line L5, , where is the number of the haplotypes equal to , and .
Lemma 3 (M-step). Define . Over the simplex on , has its maximum at .
Proof. The complete-data log-likelihood is , and its conditional mean is the formula. Let . For any on the simplex, , since the sum is the Kullback-Leibler divergence of from , which is non-negative by Gibbs' inequality.
Theorem 1 (ascent). If is the result of lines L4 to L8 from , then , with equality only if or the posterior of the phase is the same under and .
Proof. For each and each with , write , which holds because for every compatible with . Summing over , , where is the expected log of the conditional law of the phase under . By Gibbs' inequality, , with equality only when the two conditional laws agree. So , where the first bracket is non-negative by Lemma 3.
Corollary (convergence of the values). Each , so . The values do not decrease and are bounded above, so they converge. This shows the stopping rule of line L9 is met after a finite number of rounds for every . It does not show that the limit is the global maximum.
Theorem 2 (fixed points). Let be a fixed point with for all . Then for every , so is a stationary point of on the simplex (the Lagrange condition with multiplier ). If some at a fixed point, that coordinate stays 0 forever.
Proof. Differentiate: , which counts each copy of in the pair. Then by Lemma 2. At a fixed point, , so when . If , every term of has the factor , so and the next value is 0 again.
Lemma 4 (allele frequencies). After one round, for every site .
Proof. Each pair in has , so it adds copies of allele 1 at site to the counts. The posteriors of the pairs of individual sum to 1 by Lemma 2, so individual adds exactly copies. Line L8 divides by .
Phase-known case. If every has at most one heterozygous site, Lemma 1 gives for all . Then is the number of copies of in the known pairs, and Lemma 3 says that this count over is the maximum of the full likelihood, which now equals the complete-data likelihood. So EM stops at the maximum likelihood estimate after one round.
Complexity
Let be the number of heterozygous sites of individual and .
- Setup. Line L1 builds pairs, each of length : time and space.
- One round. Lines L4 to L8 do arithmetic per pair, plus the cost of a dictionary lookup on a haplotype of length : . With haplotypes stored as integer codes, a round costs .
- Rounds. The number of rounds depends on the data, and EM converges only linearly near the limit, at a rate set by the fraction of missing information (Dempster, Laird and Rubin). A measured round count is not a bound.
- Exponential growth. With many sites, grows, and pairs per individual become too many. Excoffier and Slatkin used the method for a moderate number of sites. Longer regions need the methods under Variants.
Properties
- A local optimum. The likelihood can have several local maxima, so EM can end at a point that is not the global maximum. Runs from several starting points are the usual guard.
- Allele frequencies. After one round, the frequency of allele 1 at each site is its sample count over , whatever the start.
- Phase-known data. If no individual is heterozygous at two or more sites, each genotype has one compatible pair, and one round gives the direct haplotype count, which is the maximum likelihood estimate.
- Two sites. Only the double heterozygotes are ambiguous, and the estimate of the frequency of haplotype 11 is the root of a cubic (Hill 1974). EM finds a root by iteration.
- Zeros. A frequency that is 0 at some round stays 0. A uniform start, with every compatible haplotype positive, avoids this.
Variants and improvements
- Partition ligation. Estimate frequencies in short blocks of sites, keep the common haplotypes, and join neighbouring blocks (Niu and coauthors 2002, and Qin and coauthors 2002). This avoids the pairs of a long region.
- Bayesian and coalescent priors. PHASE puts a prior from coalescent theory on the haplotypes and samples the phase of each individual (Stephens, Smith and Donnelly 2001). See haplotype phasing.
- Copying models. Modern phasing uses the Li-Stephens model, whose cost is linear in the number of sites.
- Missing genotypes. A missing site adds both alleles as options, so the set of compatible pairs grows. The E-step stays the same.
- Likelihood ratio test of LD. Fit the model with and without independence between sites and compare the maximized likelihoods (Long, Williams and Urbanek 1995; likelihood ratio test).
When to use it
Use it to estimate the frequencies of haplotypes over a few to about ten sites from unrelated individuals, for example for association tests on haplotypes or for a measure of linkage disequilibrium between two sites from unphased data. For whole chromosomes, or when you need the phase of each individual, use a phasing method.
Pitfalls
- Hardy-Weinberg assumption. The model draws the two haplotypes of an individual independently. Inbreeding or population structure breaks this, and the estimates are then biased.
- Frequencies are not phases. The posterior of the pairs of one individual is a by-product. Taking the most likely pair for each individual is a crude phasing method; its error rate is not controlled.
- The double weight. A pair of two different haplotypes has weight , and a pair of one haplotype twice has weight . A genotype with a heterozygous site has only pairs of two different haplotypes, so the factor 2 cancels in the E-step. It does not cancel in the log-likelihood, and a program that drops it reports wrong likelihoods and wrong likelihood ratio tests.
- Stopping rule. A small change of the parameters per round can hide slow convergence. Stop on the gain in log-likelihood and run from several starts.
- Too many sites. The number of compatible pairs doubles with each heterozygous site.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/em-haplotype-frequency-estimation/. The authors are listed in prov/5PQV9Z.jsonl.
"""EM estimation of haplotype frequencies from unphased genotypes
(Excoffier and Slatkin 1995).
Input: n diploid genotypes at m biallelic sites. A genotype is a tuple of
m values in {0, 1, 2}, the number of copies of allele 1 at each site. A
haplotype is a tuple of m values in {0, 1}.
Model: the two haplotypes of each individual are drawn independently from
the haplotype frequencies p (Hardy-Weinberg proportions for haplotypes).
The probability of a genotype g is the sum, over the unordered haplotype
pairs {h, h'} that are compatible with g, of w p_h p_h', where w = 2 if
h != h' and w = 1 if h = h'.
EM: the E-step splits each individual over its compatible pairs in
proportion to w p_h p_h'; the M-step sets p_h to the expected number of
copies of h divided by 2n. The log-likelihood never decreases.
"""
from __future__ import annotations
import math
from itertools import product
Genotype = tuple[int, ...]
Haplotype = tuple[int, ...]
def compatible_pairs(g: Genotype) -> list[tuple[Haplotype, Haplotype]]:
"""The unordered haplotype pairs that give genotype g.
With h heterozygous sites there are 2^(h-1) pairs (1 pair when h = 0).
The allele of the first heterozygous site is fixed to 0 on the first
haplotype of each pair, so that each unordered pair appears once.
"""
het = [j for j, x in enumerate(g) if x == 1]
for x in g:
if x not in (0, 1, 2):
raise ValueError("a genotype value must be 0, 1 or 2")
base = [1 if x == 2 else 0 for x in g]
if not het:
h = tuple(base)
return [(h, h)]
pairs = []
for bits in product((0, 1), repeat=len(het) - 1):
a = list(base)
b = list(base)
a[het[0]], b[het[0]] = 0, 1
for j, bit in zip(het[1:], bits):
a[j], b[j] = bit, 1 - bit
pairs.append((tuple(a), tuple(b)))
return pairs
def genotype_prob(pairs: list[tuple[Haplotype, Haplotype]], p: dict[Haplotype, float]) -> float:
"""P(g) = sum over compatible pairs of w p_h p_h'."""
total = 0.0
for h, k in pairs:
w = 1.0 if h == k else 2.0
total += w * p.get(h, 0.0) * p.get(k, 0.0)
return total
def log_likelihood(genotypes: list[Genotype], p: dict[Haplotype, float]) -> float:
"""The log-likelihood of the haplotype frequencies p for the genotypes."""
s = 0.0
for g in genotypes:
q = genotype_prob(compatible_pairs(g), p)
if q <= 0.0:
return -math.inf
s += math.log(q)
return s
def em_haplotype_frequencies(genotypes: list[Genotype], max_iter: int = 1000, tol: float = 1e-10,
init: dict[Haplotype, float] | None = None
) -> tuple[dict[Haplotype, float], list[float]]:
"""Run EM. Return the frequencies and the log-likelihood after each step.
The start is uniform over the haplotypes that occur in some compatible
pair, unless init is given. EM stops when the log-likelihood gains less
than tol in one step, or after max_iter steps.
"""
n = len(genotypes)
if n == 0:
raise ValueError("need at least one genotype")
s = [compatible_pairs(g) for g in genotypes] # @line L1
hap_set = sorted({h for pairs in s for pair in pairs for h in pair}) # @line L2
if init is None:
p = {h: 1.0 / len(hap_set) for h in hap_set}
else:
p = {h: init.get(h, 0.0) for h in hap_set}
z = sum(p.values())
p = {h: v / z for h, v in p.items()}
trace = [log_likelihood(genotypes, p)]
for _ in range(max_iter): # @line L3
c = {h: 0.0 for h in hap_set} # @line L4
for pairs in s: # @line L5
weights = [(1.0 if h == k else 2.0) * p[h] * p[k] for h, k in pairs]
total = sum(weights) # @line L6
for (h, k), w in zip(pairs, weights): # @line L7
e = w / total
c[h] += e
c[k] += e
p = {h: c[h] / (2 * n) for h in hap_set} # @line L8
trace.append(log_likelihood(genotypes, p))
if trace[-1] - trace[-2] < tol: # @line L9
break
return p, trace # @line L10
def gene_count(haplotype_pairs: list[tuple[Haplotype, Haplotype]]) -> dict[Haplotype, float]:
"""Haplotype frequencies by direct counting when the phase is known."""
c: dict[Haplotype, float] = {}
for h, k in haplotype_pairs:
c[h] = c.get(h, 0.0) + 1.0
c[k] = c.get(k, 0.0) + 1.0
total = 2.0 * len(haplotype_pairs)
return {h: v / total for h, v in c.items()}
def two_site_ld(p: dict[Haplotype, float]) -> tuple[float, float, float]:
"""D, D' and r^2 from two-site haplotype frequencies (allele 1 at each site)."""
p11 = p.get((1, 1), 0.0)
pa = p11 + p.get((1, 0), 0.0)
pb = p11 + p.get((0, 1), 0.0)
d = p11 - pa * pb
if d >= 0:
dmax = min(pa * (1 - pb), (1 - pa) * pb)
else:
dmax = min(pa * pb, (1 - pa) * (1 - pb))
dprime = d / dmax if dmax > 0 else 0.0
den = pa * (1 - pa) * pb * (1 - pb)
r2 = d * d / den if den > 0 else 0.0
return d, dprime, r2
test_em_haplotype_frequency_estimation.py 155 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/em-haplotype-frequency-estimation/. The authors are listed in prov/5PQV9Z.jsonl.
import math
import random
from itertools import product
import pytest
from em_haplotype_frequency_estimation import (compatible_pairs, em_haplotype_frequencies, gene_count,
log_likelihood, two_site_ld)
EXAMPLE = {(0, 0): 2, (0, 1): 1, (1, 0): 1, (1, 1): 3, (1, 2): 1, (2, 2): 2}
def example_genotypes():
return [g for g, c in EXAMPLE.items() for _ in range(c)]
def brute_pairs(g):
"""All unordered pairs of haplotypes whose sum is g, by enumeration of all haplotypes."""
m = len(g)
haps = list(product((0, 1), repeat=m))
out = set()
for h in haps:
for k in haps:
if tuple(a + b for a, b in zip(h, k)) == tuple(g):
out.add(tuple(sorted((h, k))))
return out
def test_compatible_pairs_against_enumeration():
for m in range(1, 5):
for g in product((0, 1, 2), repeat=m):
pairs = compatible_pairs(g)
got = {tuple(sorted(pq)) for pq in pairs}
assert len(got) == len(pairs)
assert got == brute_pairs(g)
het = sum(1 for x in g if x == 1)
assert len(pairs) == (2 ** (het - 1) if het else 1)
def test_example_first_step_by_hand():
p, trace = em_haplotype_frequencies(example_genotypes(), max_iter=1)
assert p[(0, 0)] == pytest.approx(7.5 / 20)
assert p[(0, 1)] == pytest.approx(3.5 / 20)
assert p[(1, 0)] == pytest.approx(2.5 / 20)
assert p[(1, 1)] == pytest.approx(6.5 / 20)
def test_example_converged_values():
p, trace = em_haplotype_frequencies(example_genotypes(), tol=1e-15)
assert p[(0, 0)] == pytest.approx(0.445269, abs=1e-6)
assert p[(0, 1)] == pytest.approx(0.104731, abs=1e-6)
assert p[(1, 0)] == pytest.approx(0.054731, abs=1e-6)
assert p[(1, 1)] == pytest.approx(0.395269, abs=1e-6)
assert trace[-1] == pytest.approx(-17.870215, abs=1e-6)
d, dprime, r2 = two_site_ld(p)
assert d == pytest.approx(0.170269, abs=1e-6)
assert r2 == pytest.approx(0.468549, abs=1e-6)
def test_likelihood_never_decreases():
rng = random.Random(7)
for _ in range(20):
m = rng.randint(2, 4)
genos = [tuple(rng.randint(0, 2) for _ in range(m)) for _ in range(rng.randint(3, 15))]
p, trace = em_haplotype_frequencies(genos, max_iter=60, tol=-1.0)
for a, b in zip(trace, trace[1:]):
assert b >= a - 1e-12
def two_site_grid_mle(genos, steps):
"""Maximize the two-site likelihood over p_11 on a grid, with the allele
frequencies fixed at their sample values (every EM iterate has them)."""
n = len(genos)
pa = sum(g[0] for g in genos) / (2 * n)
pb = sum(g[1] for g in genos) / (2 * n)
lo = max(0.0, pa + pb - 1.0)
hi = min(pa, pb)
best = (-math.inf, None)
for t in range(steps + 1):
x = lo + (hi - lo) * t / steps
p = {(1, 1): x, (1, 0): pa - x, (0, 1): pb - x, (0, 0): 1 - pa - pb + x}
ll = log_likelihood(genos, p)
if ll > best[0]:
best = (ll, x)
return best
def test_two_sites_against_grid():
rng = random.Random(11)
for case in range(15):
genos = [tuple(rng.randint(0, 2) for _ in range(2)) for _ in range(rng.randint(5, 30))]
if case == 0:
genos = example_genotypes()
p, trace = em_haplotype_frequencies(genos, max_iter=5000, tol=1e-13)
ll_grid, x = two_site_grid_mle(genos, 4000)
assert trace[-1] >= ll_grid - 1e-6
def test_kkt_conditions_three_sites():
"""At an interior fixed point the gradient of the log-likelihood is 2n for
every haplotype with positive frequency, and at most 2n for the others."""
rng = random.Random(5)
haps = list(product((0, 1), repeat=3))
freqs = [0.4, 0.05, 0.1, 0.05, 0.05, 0.15, 0.05, 0.15]
genos = []
for _ in range(80):
h = rng.choices(haps, freqs)[0]
k = rng.choices(haps, freqs)[0]
genos.append(tuple(a + b for a, b in zip(h, k)))
p, trace = em_haplotype_frequencies(genos, max_iter=20000, tol=1e-15)
n = len(genos)
grad = {h: 0.0 for h in p}
for g in genos:
pairs = compatible_pairs(g)
tot = sum((1 if h == k else 2) * p[h] * p[k] for h, k in pairs)
for h, k in pairs:
if h == k:
grad[h] += 2 * p[h] / tot
else:
grad[h] += 2 * p[k] / tot
grad[k] += 2 * p[h] / tot
for h, v in p.items():
if v > 1e-6:
assert grad[h] == pytest.approx(2 * n, rel=1e-4)
else:
assert grad[h] <= 2 * n * (1 + 1e-3)
def test_phase_known_equals_gene_counting():
"""When no genotype has two or more heterozygous sites, the phase is known,
and the maximum likelihood estimate is the direct haplotype count."""
rng = random.Random(3)
haps = list(product((0, 1), repeat=3))
pairs = []
while len(pairs) < 40:
h, k = rng.choice(haps), rng.choice(haps)
if sum(1 for a, b in zip(h, k) if a != b) <= 1:
pairs.append((h, k))
genos = [tuple(a + b for a, b in zip(h, k)) for h, k in pairs]
p, trace = em_haplotype_frequencies(genos, max_iter=5)
want = gene_count(pairs)
for h in set(p) | set(want):
assert p.get(h, 0.0) == pytest.approx(want.get(h, 0.0), abs=1e-12)
def test_frequencies_sum_to_one_and_reject_bad_input():
p, _ = em_haplotype_frequencies(example_genotypes())
assert sum(p.values()) == pytest.approx(1.0, abs=1e-12)
with pytest.raises(ValueError):
compatible_pairs((0, 3))
with pytest.raises(ValueError):
em_haplotype_frequencies([])
History
Hill in 1974 estimated two-site haplotype frequencies from unphased genotypes by maximum likelihood, where the double heterozygotes are the only missing data. In 1995 three groups published the general EM algorithm for many sites: Excoffier and Slatkin, Hawley and Kidd (the program HAPLO), and Long, Williams and Urbanek. The method follows the EM framework of Dempster, Laird and Rubin (1977). Later Bayesian methods such as PHASE, and HMM methods based on the Li-Stephens model, replaced it for long regions.
References
- Laurent Excoffier and Montgomery Slatkin, Maximum-likelihood estimation of molecular haplotype frequencies in a diploid population, Molecular Biology and Evolution 12(5), 1995, pp. 921-927 (the likelihood of the genotypes, the E-step over the compatible haplotype pairs, the M-step by gene counting, and the tests on simulated data)
- Arthur P. Dempster, Nan M. Laird and Donald B. Rubin, Maximum likelihood from incomplete data via the EM algorithm, Journal of the Royal Statistical Society Series B 39(1), 1977, pp. 1-38 (the EM algorithm and the proof that each step does not lower the likelihood)
- Long, Williams and Urbanek 1995, pp. 799-810 (the same EM method, with a likelihood ratio test of linkage disequilibrium)
- Hawley and Kidd 1995, pp. 409-411 (the program HAPLO)
- Hill 1974, pp. 229-239 (two sites, where only the double heterozygotes are ambiguous; the maximum likelihood estimate of the haplotype frequency is a root of a cubic)
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 5PQV9Z Edit this page History Report an error Markdown