Algorithm Search⌘K

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
Properties
deterministicnot exactofflineiterative
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 g1,…,gng_1, \ldots, g_n of nn diploid individuals at mm biallelic sites. Here gij∈{0,1,2}g_{ij} \in \{0, 1, 2\} is the number of copies of allele 1 that individual ii has at site jj. A haplotype is a vector h∈{0,1}mh \in \{0, 1\}^m.

Model. The two haplotypes of each individual are drawn independently from one frequency vector p=(ph)p = (p_h), and the individuals are independent. This is Hardy-Weinberg proportions for haplotypes. A pair {h,h′}\{h, h'\} is compatible with gg when h+h′=gh + h' = g site by site. Let S(g)S(g) be the set of unordered compatible pairs. Then

P(g∣p)=∑{h,h′}∈S(g)w(h,h′) phph′,w(h,h′)={1h=h′2h≠h′,P(g \mid p) = \sum_{\{h, h'\} \in S(g)} w(h, h')\, p_h p_{h'}, \qquad w(h, h') = \begin{cases} 1 & h = h' \\ 2 & h \ne h', \end{cases}

because an ordered pair with two different haplotypes can occur in two orders.

Output. A frequency vector p^\hat p on the simplex that is a stationary point of the log-likelihood ℓ(p)=∑iln⁡P(gi∣p)\ell(p) = \sum_i \ln P(g_i \mid p), and the value ℓ(p^)\ell(\hat p).

If gg has kk heterozygous sites, then ∣S(g)∣=2k−1|S(g)| = 2^{k - 1} for k≥1k \ge 1 and ∣S(g)∣=1|S(g)| = 1 for k=0k = 0: each heterozygous site can put allele 1 on either haplotype, and swapping the two haplotypes gives the same unordered pair.

The algorithm

  1. EM-HAPLOTYPES(g_1, ..., g_n, T, ε)
  2. 1for each individual i, list the compatible pairs S_i ← S(g_i)
  3. 2H ← the haplotypes that occur in some pair; p_h ← 1/|H| for each h in H
  4. 3repeat at most T times
  5. 4c_h ← 0 for each h in H ▷ expected copies of h
  6. 5for each individual i do
  7. 6P_i ← Σ over {h, h'} in S_i of w(h, h') p_h p_h'
  8. 7for 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
  9. 8p_h ← c_h / (2n) for each h in H ▷ M-step: gene counting
  10. 9if ℓ(p) gained less than ε in this round then stop
  11. 10return p

Line L7 is the E-step: ee is the posterior probability that the individual carries the pair {h,h′}\{h, h'\}. When h=h′h = h', 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 2n2n. A haplotype that is in no compatible pair has zero likelihood weight and never enters HH.

Example

Ten individuals at two sites. The sum of allele 1 counts over the two sites gives these genotype classes, written as (gi1,gi2)(g_{i1}, g_{i2}):

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 (1,1)(1, 1) are ambiguous: each is {00,11}\{00, 11\} (the cis pair) or {01,10}\{01, 10\} (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 1/21/2 and 1/21/2. The counts are 6+1.56 + 1.5, 2+1.52 + 1.5, 1+1.51 + 1.5 and 5+1.55 + 1.5 out of 20, so p=(0.375,0.175,0.125,0.325)p = (0.375, 0.175, 0.125, 0.325) for 00, 01, 10 and 11. The log-likelihood rises from −21.4876-21.4876 to −18.7302-18.7302.

Round 2. The cis weight is 2⋅0.375⋅0.325=0.243752 \cdot 0.375 \cdot 0.325 = 0.24375 and the trans weight is 2⋅0.175⋅0.125=0.043752 \cdot 0.175 \cdot 0.125 = 0.04375, so each double heterozygote is cis with probability 0.8478260.847826. The new frequency of 00 is (6+3⋅0.847826)/20=0.427174(6 + 3 \cdot 0.847826)/20 = 0.427174.

Limit. After 13 rounds the gain is below 10−1510^{-15}, and p^=(0.445269,0.104731,0.054731,0.395269)\hat p = (0.445269, 0.104731, 0.054731, 0.395269) with ℓ(p^)=−17.870215\ell(\hat p) = -17.870215. Each double heterozygote is now cis with probability 0.9680.968. The allele frequencies are 0.450.45 and 0.50.5, the sample values. The linkage disequilibrium of the estimate is D=0.395269−0.45⋅0.5=0.170269D = 0.395269 - 0.45 \cdot 0.5 = 0.170269, D′=0.757D' = 0.757 and r2=0.469r^2 = 0.469.

Correctness

The proof has three parts. First, line L7 computes the exact posterior probability of each compatible pair under the current pp, by Bayes' rule on the model. Second, line L8 maximizes the expected complete-data log-likelihood, because the complete data are 2n2n independent draws from pp, and the maximum likelihood estimate of a multinomial is the vector of observed shares. Third, the general EM inequality gives ℓ(p(t+1))≥ℓ(p(t))\ell(p^{(t+1)}) \ge \ell(p^{(t)}). The log-likelihood is bounded above by 0, so the values converge. At a fixed point with all ph>0p_h > 0, the gradient of ℓ\ell is the same for all hh in HH, 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 i=1,…,ni = 1, \ldots, n have genotypes gi∈{0,1,2}mg_i \in \{0, 1, 2\}^m. The unobserved complete data are the ordered haplotype pairs (Xi,Yi)(X_i, Y_i), independent over ii, with XiX_i and YiY_i independent draws from pp on {0,1}m\{0, 1\}^m. We observe gi=Xi+Yig_i = X_i + Y_i. Write Si=S(gi)S_i = S(g_i) for the set of unordered pairs {h,h′}\{h, h'\} with h+h′=gih + h' = g_i, and w(h,h′)=1w(h, h') = 1 if h=h′h = h', else 2. Let HH be the set of haplotypes that occur in some SiS_i.

Lemma 1 (enumeration). If gg has k≥1k \ge 1 heterozygous sites, then ∣S(g)∣=2k−1|S(g)| = 2^{k-1}, and every pair in S(g)S(g) has h≠h′h \ne h'. If k=0k = 0, then S(g)S(g) has the one pair {h,h}\{h, h\} with hj=gj/2h_j = g_j / 2.

Proof. At a site with gj∈{0,2}g_j \in \{0, 2\}, both haplotypes have the allele gj/2g_j / 2. At a heterozygous site, one haplotype has 0 and the other 1. An ordered pair is fixed by the choice, at each of the kk heterozygous sites, of which haplotype has 1: 2k2^k ordered pairs. When k≥1k \ge 1, 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. □\square

Lemma 2 (E-step). For {h,h′}∈Si\{h, h'\} \in S_i, P({Xi,Yi}={h,h′}∣gi,p)=w(h,h′)phph′/PiP(\{X_i, Y_i\} = \{h, h'\} \mid g_i, p) = w(h, h') p_h p_{h'} / P_i with Pi=∑{u,u′}∈Siw(u,u′)pupu′P_i = \sum_{\{u, u'\} \in S_i} w(u, u') p_u p_{u'}.

Proof. The event {Xi,Yi}={h,h′}\{X_i, Y_i\} = \{h, h'\} is the union of the ordered events (h,h′)(h, h') and (h′,h)(h', h), which are the same event when h=h′h = h'. Its probability is w(h,h′)phph′w(h, h') p_h p_{h'}. These events for the pairs of SiS_i are disjoint, and their union is the event Xi+Yi=giX_i + Y_i = g_i, so P(gi∣p)=PiP(g_i \mid p) = P_i. Bayes' rule gives the ratio. □\square

So line L7 adds to chc_h the posterior expected number of copies of hh carried by individual ii: one copy for each side of the pair, and two copies when h=h′h = h'. After line L5, ch=E[Nh∣g,p]c_h = E[N_h \mid g, p], where NhN_h is the number of the 2n2n haplotypes equal to hh, and ∑hch=2n\sum_h c_h = 2n.

Lemma 3 (M-step). Define Q(q∣p)=E[ln⁡P(X,Y∣q)∣g,p]=∑h∈Hchln⁡qhQ(q \mid p) = E[\ln P(X, Y \mid q) \mid g, p] = \sum_{h \in H} c_h \ln q_h. Over the simplex on HH, Q(⋅∣p)Q(\cdot \mid p) has its maximum at qh=ch/(2n)q_h = c_h / (2n).

Proof. The complete-data log-likelihood is ∑i(ln⁡qXi+ln⁡qYi)=∑hNhln⁡qh\sum_i (\ln q_{X_i} + \ln q_{Y_i}) = \sum_h N_h \ln q_h, and its conditional mean is the formula. Let rh=ch/(2n)r_h = c_h / (2n). For any qq on the simplex, Q(r∣p)−Q(q∣p)=2n∑hrhln⁡(rh/qh)≥0Q(r \mid p) - Q(q \mid p) = 2n \sum_h r_h \ln(r_h / q_h) \ge 0, since the sum is the Kullback-Leibler divergence of rr from qq, which is non-negative by Gibbs' inequality. □\square

Theorem 1 (ascent). If p′p' is the result of lines L4 to L8 from pp, then ℓ(p′)≥ℓ(p)\ell(p') \ge \ell(p), with equality only if p′=pp' = p or the posterior of the phase is the same under pp and p′p'.

Proof. For each ii and each qq with P(gi∣q)>0P(g_i \mid q) > 0, write ln⁡P(gi∣q)=E[ln⁡P(Xi,Yi∣q)∣gi,p]−E[ln⁡P(Xi,Yi∣gi,q)∣gi,p]\ln P(g_i \mid q) = E[\ln P(X_i, Y_i \mid q) \mid g_i, p] - E[\ln P(X_i, Y_i \mid g_i, q) \mid g_i, p], which holds because P(x,y∣q)=P(gi∣q)P(x,y∣gi,q)P(x, y \mid q) = P(g_i \mid q) P(x, y \mid g_i, q) for every (x,y)(x, y) compatible with gig_i. Summing over ii, ℓ(q)=Q(q∣p)−R(q∣p)\ell(q) = Q(q \mid p) - R(q \mid p), where R(q∣p)R(q \mid p) is the expected log of the conditional law of the phase under qq. By Gibbs' inequality, R(q∣p)≤R(p∣p)R(q \mid p) \le R(p \mid p), with equality only when the two conditional laws agree. So ℓ(p′)−ℓ(p)=[Q(p′∣p)−Q(p∣p)]+[R(p∣p)−R(p′∣p)]≥0\ell(p') - \ell(p) = [Q(p' \mid p) - Q(p \mid p)] + [R(p \mid p) - R(p' \mid p)] \ge 0, where the first bracket is non-negative by Lemma 3. □\square

Corollary (convergence of the values). Each P(gi∣p)≤1P(g_i \mid p) \le 1, so ℓ≤0\ell \le 0. The values ℓ(p(t))\ell(p^{(t)}) 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 ε>0\varepsilon > 0. It does not show that the limit is the global maximum.

Theorem 2 (fixed points). Let pp be a fixed point with ph>0p_h > 0 for all h∈Hh \in H. Then ∂ℓ/∂ph=2n\partial \ell / \partial p_h = 2n for every h∈Hh \in H, so pp is a stationary point of ℓ\ell on the simplex (the Lagrange condition with multiplier 2n2n). If some ph=0p_h = 0 at a fixed point, that coordinate stays 0 forever.

Proof. Differentiate: ∂Pi/∂ph=∑{h,h′}∈Siw(h,h′)ph′⋅(1+[h=h′])\partial P_i / \partial p_h = \sum_{\{h, h'\} \in S_i} w(h, h') p_{h'} \cdot (1 + [h = h']), which counts each copy of hh in the pair. Then ph ∂ℓ/∂ph=∑i∑{h,h′}∈Si(1+[h=h′]) w(h,h′)phph′/Pi=chp_h \, \partial \ell / \partial p_h = \sum_i \sum_{\{h, h'\} \in S_i} (1 + [h = h'])\, w(h, h') p_h p_{h'} / P_i = c_h by Lemma 2. At a fixed point, ch=2nphc_h = 2n p_h, so ∂ℓ/∂ph=2n\partial \ell / \partial p_h = 2n when ph>0p_h > 0. If ph=0p_h = 0, every term of chc_h has the factor php_h, so ch=0c_h = 0 and the next value is 0 again. □\square

Lemma 4 (allele frequencies). After one round, ∑h:hj=1ph′=12n∑igij\sum_{h : h_j = 1} p'_h = \frac{1}{2n} \sum_i g_{ij} for every site jj.

Proof. Each pair {h,h′}\{h, h'\} in SiS_i has hj+hj′=gijh_j + h'_j = g_{ij}, so it adds e⋅gije \cdot g_{ij} copies of allele 1 at site jj to the counts. The posteriors ee of the pairs of individual ii sum to 1 by Lemma 2, so individual ii adds exactly gijg_{ij} copies. Line L8 divides by 2n2n. □\square

Phase-known case. If every gig_i has at most one heterozygous site, Lemma 1 gives ∣Si∣=1|S_i| = 1 for all ii. Then chc_h is the number of copies of hh in the known pairs, and Lemma 3 says that this count over 2n2n 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 kik_i be the number of heterozygous sites of individual ii and h=max⁡ikih = \max_i k_i.

  • Setup. Line L1 builds ∑i2max⁡(ki−1,0)\sum_i 2^{\max(k_i - 1, 0)} pairs, each of length mm: O(nm2h)O(n m 2^h) time and space.
  • One round. Lines L4 to L8 do O(1)O(1) arithmetic per pair, plus the cost of a dictionary lookup on a haplotype of length mm: O(nm2h)O(n m 2^h). With haplotypes stored as integer codes, a round costs O(n2h+∣H∣)O(n 2^h + |H|).
  • Rounds. The number of rounds TT 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, hh grows, and 2h−12^{h-1} 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 2n2n, 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 2h−12^{h-1} 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 2phph′2 p_h p_{h'}, and a pair of one haplotype twice has weight ph2p_h^2. 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.

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

  1. 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)
  2. 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)
  3. Long, Williams and Urbanek 1995, pp. 799-810 (the same EM method, with a likelihood ratio test of linkage disequilibrium)
  4. Hawley and Kidd 1995, pp. 409-411 (the program HAPLO)
  5. 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.

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