Algorithm Search⌘K

Algorithmadvanced

Maximum likelihood admixture estimation

Also called ADMIXTURE algorithm.

Fit ancestry proportions and population allele frequencies by maximum likelihood with block relaxation and quasi-Newton acceleration.

Time
O(T n m k) worst · averageO(n m k) best
Space
O(n m + n k + m k) extra
Where
T = the number of rounds; k = the number of ancestral populations; m = the number of sites; n = the number of individuals
Properties
randomizednot exactofflineiterative
Origin
David H. Alexander, John Novembre, Kenneth Lange, 2009

Maximum likelihood admixture estimation fits the admixture model of the Pritchard-Stephens-Donnelly model by maximizing its likelihood instead of sampling from a posterior. Each individual ii has ancestry proportions qi1,…,qiKq_{i1}, \ldots, q_{iK} over KK ancestral populations, and each population kk has an allele frequency fkjf_{kj} at site jj. The best known program is ADMIXTURE, by Alexander, Novembre and Lange (2009). It updates all ancestry proportions with the frequencies fixed, then all frequencies with the proportions fixed, and repeats; this is block relaxation, a form of coordinate descent by blocks. A quasi-Newton step speeds up the repetition. The result is a local maximum of the likelihood, found much faster than with the Gibbs sampler of STRUCTURE.

In plain words

Assume that there were a few source populations, each with its own share of each variant. Every person is a mix of these sources in some proportions. The method looks for the source frequencies and the mixing proportions that make the observed genotypes most likely.

It improves one set while it holds the other fixed. With the source frequencies fixed, it finds better mixing proportions for each person. With the proportions fixed, it finds better frequencies for each variant and source. Each of these steps makes the data at least as likely as before. A jump that guesses where the steps are going makes the method faster. The answer can depend on the start, so users run it from several starts and keep the best.

The problem

Input. Genotypes gij∈{0,1,2}g_{ij} \in \{0, 1, 2\} for nn individuals at mm biallelic sites, and a number KK of ancestral populations.

Model. Given Q=(qik)Q = (q_{ik}) with each row on the simplex and F=(fkj)F = (f_{kj}) with entries in [0,1][0, 1], each of the two allele copies of individual ii at site jj comes from population kk with probability qikq_{ik} and then carries allele 1 with probability fkjf_{kj}, independently of all other copies. So gijg_{ij} is binomial with 2 trials and success probability ϕij=∑kqikfkj\phi_{ij} = \sum_k q_{ik} f_{kj}, and the log-likelihood is

L(Q,F)=∑i,j[gijln⁡ϕij+(2−gij)ln⁡(1−ϕij)].L(Q, F) = \sum_{i, j} \big[ g_{ij} \ln \phi_{ij} + (2 - g_{ij}) \ln (1 - \phi_{ij}) \big].

This is the likelihood of the admixture model of STRUCTURE, without the prior. The matrix Φ=QF\Phi = Q F of expected allele frequencies is a product of two nonnegative factors, so the problem is a nonnegative matrix factorization with a binomial likelihood in place of the squared error and with the rows of QQ on the simplex.

Output. (Q^,F^)(\hat Q, \hat F) at a local maximum of LL over the product of simplices and boxes, and the value L(Q^,F^)L(\hat Q, \hat F).

The algorithm

  1. ADMIXTURE(G, K, rng)
  2. 1Q, F ← a random start from rng
  3. 2repeat at most T times ▷ x = (Q, F)
  4. 3x1 ← BLOCK(x) ▷ improve Q with F fixed, then F with Q fixed
  5. 4x2 ← BLOCK(x1)
  6. 5u ← x1 - x; v ← x2 - x1
  7. 6c ← -uᵀu / uᵀ(v - u)
  8. 7y ← project((1 - c) x1 + c x2) onto the feasible set
  9. 8if L(y) < L(x2) then y ← x2
  10. 9x ← y
  11. 10if L gained less than ε in this round then stop
  12. 11return Q, F

The blocks. With FF fixed, LL splits into nn problems, one per row qiq_i, each concave in qiq_i on a simplex of dimension K−1K - 1. With QQ fixed, LL splits into mm problems, one per column fjf_j, each concave in fjf_j on the box [0,1]K[0, 1]^K. ADMIXTURE solves each small problem approximately by sequential quadratic programming: a quadratic approximation of the log-likelihood is maximized under the constraints. The code on this page takes one EM step in each block instead. The hidden data are the source populations of the allele copies. With ϕij\phi_{ij} at the current values, the expected number of copies of allele 1 in gijg_{ij} that come from population kk is aijk=gijqikfkj/ϕija_{ijk} = g_{ij} q_{ik} f_{kj} / \phi_{ij}, and of allele 0 it is bijk=(2−gij)qik(1−fkj)/(1−ϕij)b_{ijk} = (2 - g_{ij}) q_{ik} (1 - f_{kj}) / (1 - \phi_{ij}). The EM updates are

qik←12m∑j(aijk+bijk),fkj←∑iaijk∑i(aijk+bijk).q_{ik} \leftarrow \frac{1}{2m} \sum_j (a_{ijk} + b_{ijk}), \qquad f_{kj} \leftarrow \frac{\sum_i a_{ijk}}{\sum_i (a_{ijk} + b_{ijk})}.

These are the updates of FRAPPE, applied one block at a time. They are slower per unit of progress than the SQP steps, but they also never lower LL, and they keep QQ and FF feasible.

The acceleration. Lines L5 to L7 treat a round of block relaxation as a map x↦F(x)x \mapsto \mathcal F(x) whose fixed point is wanted. The secant pair (u,v)(u, v) gives a rank-one estimate of the differential of F\mathcal F, and line L6 solves the linearized fixed point equation along it. With c=1c = 1 the step is x2x_2; larger cc extrapolates further along the path. Line L7 puts each row of QQ back on the simplex and clips FF to [δ,1−δ][\delta, 1 - \delta], and line L8 rejects a step that is worse than two plain rounds. This is the scheme of Zhou, Alexander and Lange (2011) with one secant pair.

Example

One individual, three sites and K=2K = 2, with FF fixed to f1=(0.8,0.4,0.9)f_1 = (0.8, 0.4, 0.9) and f2=(0.2,0.4,0.3)f_2 = (0.2, 0.4, 0.3), genotype g=(2,0,1)g = (2, 0, 1) and start q=(0.5,0.5)q = (0.5, 0.5).

  • Site 1: ϕ=0.5\phi = 0.5. The two copies of allele 1 split as 0.4/0.50.4/0.5 and 0.1/0.50.1/0.5, so 1.61.6 copies go to population 1 and 0.40.4 to population 2.
  • Site 2: ϕ=0.4\phi = 0.4. The two copies of allele 0 split as 0.3/0.60.3/0.6 and 0.3/0.60.3/0.6: 1.01.0 and 1.01.0.
  • Site 3: ϕ=0.6\phi = 0.6. The copy of allele 1 splits 0.750.75 and 0.250.25; the copy of allele 0 splits 0.05/0.4=0.1250.05/0.4 = 0.125 and 0.8750.875.

The totals are 3.4753.475 and 2.5252.525 out of 6, so the new qq is (0.5792,0.4208)(0.5792, 0.4208), and LL rises from −3.8351-3.8351 to −3.7038-3.7038. Further EM steps give q1=0.6367,0.6774,0.7059,…q_1 = 0.6367, 0.6774, 0.7059, \ldots, which approach the maximum q1=0.7790q_1 = 0.7790, where L=−3.5536L = -3.5536. After 7 steps q1q_1 is only 0.75080.7508. The gap shrinks by a nearly constant factor per step, which is the slow linear convergence that the SQP steps and the acceleration of ADMIXTURE avoid.

Correctness

Each block step never lowers LL. For the EM step, the reason is the usual EM inequality for the model with known source populations: in that model the log-likelihood is a sum of multinomial terms, and the updates are its maximum likelihood values given the expected counts. The Q update keeps each row on the simplex, because ∑k(aijk+bijk)=2\sum_k (a_{ijk} + b_{ijk}) = 2 for every (i,j)(i, j), so the row sums are 2m/2m=12m / 2m = 1. The F update is a ratio in [0,1][0, 1]. Line L8 accepts the extrapolated point only if its likelihood is at least that of x2x_2, which is at least L(x)L(x), so the values LL never decrease. Since L≤0L \le 0, they converge. At a fixed point with positive entries, the partial derivatives of LL in a row of QQ are all equal to 2m2m, and the partial derivatives in the interior entries of FF are 0. These are the Karush-Kuhn-Tucker conditions of the constrained problem. The full proof is below. Nothing here shows that the point is the global maximum.

Proof: Each block step keeps Q and F feasible and never lowers the likelihood, the accelerated round never lowers it, and fixed points satisfy the KKT conditionsfull

Setting. gij∈{0,1,2}g_{ij} \in \{0, 1, 2\}, each row qiq_i of QQ is on the simplex ΔK\Delta_K, and fkj∈[0,1]f_{kj} \in [0, 1]. Write ϕij=∑kqikfkj\phi_{ij} = \sum_k q_{ik} f_{kj} and L(Q,F)=∑i,j[gijln⁡ϕij+(2−gij)ln⁡(1−ϕij)]L(Q, F) = \sum_{i, j} [g_{ij} \ln \phi_{ij} + (2 - g_{ij}) \ln(1 - \phi_{ij})], where a term with a zero count is 0. Assume the current point has L>−∞L > -\infty. On ΔK\Delta_K, 1−ϕij=∑kqik(1−fkj)1 - \phi_{ij} = \sum_k q_{ik} (1 - f_{kj}).

Complete data. Give each of the two allele copies of (i,j)(i, j) a hidden label z∈{1,…,K}z \in \{1, \ldots, K\}, its source population. In the complete model, P(z=k)=qikP(z = k) = q_{ik}, and given z=kz = k the copy is allele 1 with probability fkjf_{kj}, independently over copies. Summing over the labels gives the binomial law of gijg_{ij} with parameter ϕij\phi_{ij}, so LL is the observed-data log-likelihood of this model.

Lemma 1 (E-step). Given gijg_{ij} and the current (Q,F)(Q, F), the expected number of the gijg_{ij} copies of allele 1 with label kk is aijk=gijqikfkj/ϕija_{ijk} = g_{ij} q_{ik} f_{kj} / \phi_{ij}, and of the 2−gij2 - g_{ij} copies of allele 0 it is bijk=(2−gij)qik(1−fkj)/(1−ϕij)b_{ijk} = (2 - g_{ij}) q_{ik} (1 - f_{kj}) / (1 - \phi_{ij}). Also ∑k(aijk+bijk)=2\sum_k (a_{ijk} + b_{ijk}) = 2.

Proof. For a copy of allele 1, Bayes' rule gives P(z=k∣allele 1)=qikfkj/ϕijP(z = k \mid \text{allele } 1) = q_{ik} f_{kj} / \phi_{ij}, and the copies are independent given the parameters, so the expectation is gijg_{ij} times this. The same holds for allele 0 with 1−ϕij=∑kqik(1−fkj)1 - \phi_{ij} = \sum_k q_{ik}(1 - f_{kj}). The posteriors of one copy sum to 1 over kk, and there are 2 copies. □\square

Lemma 2 (M-steps). Let Nijk1N^1_{ijk} and Nijk0N^0_{ijk} be the numbers of copies of allele 1 and of allele 0 with label kk. The complete-data log-likelihood is

ℓc=∑i,k(Ni⋅k1+Ni⋅k0)ln⁡qik+∑k,j(N⋅jk1ln⁡fkj+N⋅jk0ln⁡(1−fkj)),\ell_c = \sum_{i, k} (N^1_{i \cdot k} + N^0_{i \cdot k}) \ln q_{ik} + \sum_{k, j} \big( N^1_{\cdot jk} \ln f_{kj} + N^0_{\cdot jk} \ln(1 - f_{kj}) \big),

where a dot means a sum over that index. With NN replaced by its conditional means aa and bb (Lemma 1), the function QcQ_c so obtained has its maximum over ΔK\Delta_K in each row qiq_i at qik=12m∑j(aijk+bijk)q_{ik} = \frac{1}{2m} \sum_j (a_{ijk} + b_{ijk}), and its maximum over [0,1][0, 1] in each fkjf_{kj} at fkj=∑iaijk/∑i(aijk+bijk)f_{kj} = \sum_i a_{ijk} / \sum_i (a_{ijk} + b_{ijk}) when the denominator is positive.

Proof. The qiq_i part is ∑kckln⁡qik\sum_k c_k \ln q_{ik} with ck=∑j(aijk+bijk)≥0c_k = \sum_j (a_{ijk} + b_{ijk}) \ge 0 and ∑kck=2m\sum_k c_k = 2m by Lemma 1. By Gibbs' inequality its maximum on the simplex is at qik=ck/2mq_{ik} = c_k / 2m. The fkjf_{kj} part is Aln⁡f+Bln⁡(1−f)A \ln f + B \ln(1 - f) with A,B≥0A, B \ge 0, which is concave with maximum at A/(A+B)A / (A + B). □\square

Theorem 1 (block steps). Let Q′Q' be the result of the Q update with FF fixed. Then each row of Q′Q' is on ΔK\Delta_K, and L(Q′,F)≥L(Q,F)L(Q', F) \ge L(Q, F). Let F′F' be the result of the F update with QQ fixed. Then F′∈[0,1]K×mF' \in [0, 1]^{K \times m} and L(Q,F′)≥L(Q,F)L(Q, F') \ge L(Q, F).

Proof. Feasibility: the entries of Q′Q' are non-negative, and its row sums are 12m∑j2=1\frac{1}{2m} \sum_j 2 = 1 by Lemma 1. The entries of F′F' are ratios of a non-negative number to a larger or equal one; where the denominator is 0, the code keeps the old value. Ascent: consider the complete-data model in which only the block being updated is free. The Q update maximizes the expected complete-data log-likelihood over QQ with FF fixed, by Lemma 2, so it is one EM step of the model with parameter QQ alone. The standard EM inequality (the observed log-likelihood equals the expected complete-data log-likelihood minus the expected log of the conditional law of the labels, and the second term is largest at the current value by Gibbs' inequality) gives L(Q′,F)≥L(Q,F)L(Q', F) \ge L(Q, F). The same argument with FF as the free block gives the second claim. □\square

Corollary (one round). The map BLOCK of line L3 gives L(BLOCK(x))≥L(x)L(\mathrm{BLOCK}(x)) \ge L(x), so L(x2)≥L(x1)≥L(x)L(x_2) \ge L(x_1) \ge L(x).

Theorem 2 (accelerated round). The point chosen by lines L6 to L9 is feasible, and its likelihood is at least L(x)L(x).

Proof. If the extrapolated point is used, line L7 has made it feasible: each row of QQ is the Euclidean projection onto ΔK\Delta_K, then raised to at least δq>0\delta_q > 0 and renormalized, so it is on ΔK\Delta_K; each fkjf_{kj} is clipped to [δ,1−δ][\delta, 1 - \delta]. Then ϕij∈[δ,1−δ]\phi_{ij} \in [\delta, 1 - \delta], so LL is finite. Line L8 keeps the extrapolated point only if its likelihood is at least L(x2)L(x_2), and otherwise keeps x2x_2. In both cases the likelihood is at least L(x2)≥L(x)L(x_2) \ge L(x) by the corollary. If u=0u = 0 or uT(v−u)≥0u^{\mathsf T}(v - u) \ge 0, the code keeps x2x_2. □\square

So the values L(t)L^{(t)} do not decrease. Each ϕij∈[0,1]\phi_{ij} \in [0, 1] makes every term at most 0, so L≤0L \le 0, and the values converge. This shows that the test of line L10 is met for every ε>0\varepsilon > 0.

Lemma 3 (the projection). For y∈RKy \in \mathbb R^K, the function project_simplex returns the unique point of ΔK\Delta_K nearest to yy.

Proof. ΔK\Delta_K is closed and convex, so the nearest point pp is unique. The KKT conditions of minimizing 12∥p−y∥2\frac12 \lVert p - y \rVert^2 under ∑pk=1\sum p_k = 1 and p≥0p \ge 0 say that pk=max⁡(yk−τ,0)p_k = \max(y_k - \tau, 0) for one number τ\tau with ∑kmax⁡(yk−τ,0)=1\sum_k \max(y_k - \tau, 0) = 1. The left side is continuous and strictly decreasing in τ\tau where it is positive, so τ\tau is unique. With yy sorted as u1≥⋯≥uKu_1 \ge \cdots \ge u_K, let ρ\rho be the largest index with uρ−(∑s≤ρus−1)/ρ>0u_\rho - (\sum_{s \le \rho} u_s - 1)/\rho > 0; then τ=(∑s≤ρus−1)/ρ\tau = (\sum_{s \le \rho} u_s - 1)/\rho makes exactly the first ρ\rho entries positive and gives sum 1, which is what the code computes. □\square

Theorem 3 (fixed points). Suppose a BLOCK round leaves (Q,F)(Q, F) unchanged. Then for each ii and each kk with qik>0q_{ik} > 0, ∂L/∂qik=2m\partial L / \partial q_{ik} = 2m, where the derivative is taken with 1−ϕij1 - \phi_{ij} written as ∑kqik(1−fkj)\sum_k q_{ik}(1 - f_{kj}). For each k,jk, j with 0<fkj<10 < f_{kj} < 1, ∂L/∂fkj=0\partial L / \partial f_{kj} = 0.

Proof. With that form of 1−ϕ1 - \phi, ∂L/∂qik=∑j[gijfkj/ϕij+(2−gij)(1−fkj)/(1−ϕij)]\partial L / \partial q_{ik} = \sum_j [g_{ij} f_{kj} / \phi_{ij} + (2 - g_{ij})(1 - f_{kj}) / (1 - \phi_{ij})], so qik ∂L/∂qik=∑j(aijk+bijk)=2m qik′q_{ik}\, \partial L / \partial q_{ik} = \sum_j (a_{ijk} + b_{ijk}) = 2m\, q'_{ik}. If Q′=QQ' = Q and qik>0q_{ik} > 0, dividing by qikq_{ik} gives 2m2m. For FF, ∂L/∂fkj=∑iqik[gij/ϕij−(2−gij)/(1−ϕij)]=A/fkj−B/(1−fkj)\partial L / \partial f_{kj} = \sum_i q_{ik} [g_{ij} / \phi_{ij} - (2 - g_{ij}) / (1 - \phi_{ij})] = A / f_{kj} - B / (1 - f_{kj}) with A=∑iaijkA = \sum_i a_{ijk} and B=∑ibijkB = \sum_i b_{ijk}. If F′=FF' = F then fkj=A/(A+B)f_{kj} = A / (A + B), and the derivative is (A+B)−(A+B)=0(A + B) - (A + B) = 0. Since BLOCK first updates QQ and then updates FF with the new QQ, a fixed point of BLOCK has Q′=QQ' = Q and then F′=FF' = F. □\square

The derivative in a row of QQ is equal on the support of qiq_i, with Lagrange multiplier 2m2m for the constraint ∑kqik=1\sum_k q_{ik} = 1. This is the KKT condition on the support. For LL written with 1−ϕ=1−∑kqikfkj1 - \phi = 1 - \sum_k q_{ik} f_{kj}, the derivatives differ by the constant ∑j(2−gij)/(1−ϕij)\sum_j (2 - g_{ij}) / (1 - \phi_{ij}) in all kk, so the condition is the same. The theorem does not say that the point is a local maximum; the symmetric start of the tests is a fixed point with L=8ln⁡12L = 8 \ln \frac12, while q1=(1,0)q_1 = (1, 0), q2=(0,1)q_2 = (0, 1) with matching frequencies gives L=0L = 0.

Complexity

  • One block step. Computing ϕij\phi_{ij} for all pairs costs O(nmK)O(n m K), and so do the sums of the EM updates. A round of line L3 costs O(nmK)O(n m K), and lines L4 to L8 add a constant factor.
  • Rounds. The number of rounds TT depends on the data and the start. Plain EM converges linearly and can need thousands of rounds; the SQP blocks and the acceleration cut this a lot in the experiments of Alexander and coauthors.
  • Space. O(nm)O(n m) for the genotypes and O((n+m)K)O((n + m) K) for QQ and FF.
  • Comparison. One sweep of the STRUCTURE Gibbs sampler also costs O(nmK)O(n m K), but it needs many thousands of sweeps for a posterior summary, and ADMIXTURE reached similar estimates in far less time on the data of its paper.

Properties

  • Local maxima. LL is concave in each block but not jointly. Different starts can end at different local maxima, so several starts are the norm.
  • Label switching. Any permutation of the KK populations gives the same likelihood. Runs must be aligned before they are compared.
  • Saddle points. A start where all rows of QQ are equal and all populations have the same frequencies is a fixed point of the EM steps, and for structured data it is not a maximum. A random start avoids it.
  • Boundary values. Many maximum likelihood values lie on the boundary, with fkj=0f_{kj} = 0 or 11 or qik=0q_{ik} = 0. EM often approaches them slowly, because it multiplies each entry by a factor and an entry that is positive stays positive unless the data give it no weight at all. SQP treats the bounds as constraints and can land on them.
  • K=1K = 1. The maximum is f^1j=∑igij/(2n)\hat f_{1j} = \sum_i g_{ij} / (2n), the sample allele frequency, reached in one F step.

Variants and improvements

  • Choosing KK. A later version of ADMIXTURE adds cross-validation: it holds out entries of GG, fits the model to the rest and measures how well it predicts the held-out genotypes.
  • Supervised mode. If some individuals are known to come from one population, their rows of QQ are fixed, and only the rest are fitted.
  • Bayesian fits. STRUCTURE samples from the posterior by Gibbs sampling, which gives uncertainty but is much slower. Variational methods give an approximate posterior at a cost close to that of ADMIXTURE.
  • Large data. Programs for millions of individuals use stochastic or alternating least squares versions of the same factorization.
  • Other optimizers. Projected gradient descent and quasi-Newton methods on the full parameter vector also work, but the block form keeps each subproblem small.

When to use it

Use it for genome-wide data on many unrelated individuals when you want ancestry proportions with a clear meaning, and when the sample has no strong relatedness. For a first look, or to choose covariates, principal components of genotypes are faster and need no KK. For the ancestry of each segment of a genome, use local ancestry inference.

Pitfalls

  • The model is a simplification. Real populations do not come from KK discrete sources without drift between them. The method fits a KK-source model to any data, including data from a continuous gradient, and the bars it draws can then mislead.
  • Linkage. The likelihood treats sites as independent. Dense data in linkage disequilibrium count the same signal many times, which makes the fit look more certain than it is. Pruning sites in high LD is common.
  • Relatives. Families form their own cluster, which takes one of the KK components.
  • Sample sizes. A large group can split into several components while small groups merge, so proportions depend on the sampling design.
  • Convergence. Stop on the gain in log-likelihood and compare several starts. A small change of the parameters per round does not mean a maximum.

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.

maximum_likelihood_admixture_estimation.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/maximum-likelihood-admixture-estimation/. The authors are listed in prov/KYJWNZ.jsonl.
"""Maximum likelihood estimation of ancestry proportions Q and population
allele frequencies F, the model of STRUCTURE and ADMIXTURE.

g[i][j] in {0, 1, 2} is the count of allele 1 of individual i at site j.
q[i] is a point of the simplex in R^K, and f[k][j] is in [0, 1]. With
phi_ij = sum_k q_ik f_kj the log-likelihood is

    L(Q, F) = sum_ij g_ij ln(phi_ij) + (2 - g_ij) ln(1 - phi_ij).

The fit is block relaxation: improve Q with F fixed, then F with Q fixed.
ADMIXTURE (Alexander, Novembre and Lange 2009) solves each block by
sequential quadratic programming. Here each block takes one EM step, in
which the hidden data are the source population of each allele copy. The
EM step is simpler and also never lowers L. A quasi-Newton step of the
form of Zhou, Alexander and Lange (2011), with one secant pair, speeds up
the iteration; a step that lowers L is replaced by two plain rounds.
"""

from __future__ import annotations

import math
import random

Matrix = list[list[float]]

F_MIN = 1e-9
Q_MIN = 1e-6


def _phi(q: Matrix, f: Matrix) -> Matrix:
    """phi_ij = sum_k q_ik f_kj."""
    cols = list(zip(*f))
    return [[sum(a * b for a, b in zip(qi, col)) for col in cols] for qi in q]


def _weights(g: list[list[int]], q: Matrix, f: Matrix) -> tuple[Matrix, Matrix]:
    """wa_ij = g_ij / phi_ij and wb_ij = (2 - g_ij) / (1 - phi_ij), with 0 for a zero count."""
    phi = _phi(q, f)
    wa = [[x / p if x > 0 else 0.0 for x, p in zip(row, prow)] for row, prow in zip(g, phi)]
    wb = [[(2 - x) / (1.0 - p) if x < 2 else 0.0 for x, p in zip(row, prow)] for row, prow in zip(g, phi)]
    return wa, wb


def log_likelihood(g: list[list[int]], q: Matrix, f: Matrix) -> float:
    total = 0.0
    for row, prow in zip(g, _phi(q, f)):
        for x, p in zip(row, prow):
            if x > 0:
                total += x * math.log(p)
            if x < 2:
                total += (2 - x) * math.log(1.0 - p)
    return total


def update_q(g: list[list[int]], q: Matrix, f: Matrix) -> Matrix:
    """One EM step for Q with F fixed: q_ik <- q_ik sum_j (f_kj wa_ij + (1 - f_kj) wb_ij) / (2m).

    The term q_ik f_kj wa_ij is the expected number of the g_ij copies of
    allele 1 that come from population k, and q_ik (1 - f_kj) wb_ij is the
    same for allele 0."""
    m = len(g[0])
    wa, wb = _weights(g, q, f)
    out = []
    for qi, ra, rb in zip(q, wa, wb):
        out.append([qk * sum(fk[j] * ra[j] + (1.0 - fk[j]) * rb[j] for j in range(m)) / (2.0 * m)
                    for qk, fk in zip(qi, f)])
    return out


def update_f(g: list[list[int]], q: Matrix, f: Matrix) -> Matrix:
    """One EM step for F with Q fixed: f_kj <- A_kj / (A_kj + B_kj), where A_kj is the
    expected number of copies of allele 1 from population k at site j, and B_kj of allele 0."""
    n = len(g)
    m = len(g[0])
    wa, wb = _weights(g, q, f)
    out = []
    for c, fk in enumerate(f):
        sa = [sum(q[i][c] * wa[i][j] for i in range(n)) for j in range(m)]
        sb = [sum(q[i][c] * wb[i][j] for i in range(n)) for j in range(m)]
        row = []
        for j in range(m):
            a = fk[j] * sa[j]
            b = (1.0 - fk[j]) * sb[j]
            row.append(a / (a + b) if a + b > 0 else fk[j])
        out.append(row)
    return out


def block_round(g: list[list[int]], q: Matrix, f: Matrix) -> tuple[Matrix, Matrix]:
    """Block relaxation: first the Q block, then the F block with the new Q."""
    q2 = update_q(g, q, f)
    return q2, update_f(g, q2, f)


def project_simplex(v: list[float]) -> list[float]:
    """Euclidean projection onto {x : x >= 0, sum x = 1}."""
    u = sorted(v, reverse=True)
    run = 0.0
    tau = 0.0
    for idx, val in enumerate(u, start=1):
        run += val
        t = (run - 1.0) / idx
        if val - t > 0:
            tau = t
    return [max(x - tau, 0.0) for x in v]


def _flatten(q: Matrix, f: Matrix) -> list[float]:
    return [x for row in q for x in row] + [x for row in f for x in row]


def _unflatten(x: list[float], n: int, k: int, m: int) -> tuple[Matrix, Matrix]:
    q = [x[i * k:(i + 1) * k] for i in range(n)]
    base = n * k
    f = [x[base + c * m: base + (c + 1) * m] for c in range(k)]
    return q, f


def _feasible(q: Matrix, f: Matrix) -> tuple[Matrix, Matrix]:
    """Project Q rows onto the simplex with a small floor, and clip F to [F_MIN, 1 - F_MIN]."""
    q_out = []
    for row in q:
        p = [max(v, Q_MIN) for v in project_simplex(row)]
        s = sum(p)
        q_out.append([v / s for v in p])
    f_out = [[min(1.0 - F_MIN, max(F_MIN, v)) for v in row] for row in f]
    return q_out, f_out


def random_start(n: int, k: int, m: int, rng: random.Random) -> tuple[Matrix, Matrix]:
    q = []
    for _ in range(n):
        w = [rng.random() + 0.1 for _ in range(k)]
        s = sum(w)
        q.append([v / s for v in w])
    f = [[rng.uniform(0.05, 0.95) for _ in range(m)] for _ in range(k)]
    return q, f


def admixture(g: list[list[int]], k: int, rng: random.Random, max_iter: int = 2000, tol: float = 1e-9,
              accelerate: bool = True, start: tuple[Matrix, Matrix] | None = None):
    """Fit Q and F. Return (q, f, trace), where trace is the log-likelihood after each round."""
    n = len(g)
    if n == 0 or k < 1:
        raise ValueError("need at least one individual and k >= 1")
    m = len(g[0])
    for row in g:
        if len(row) != m or any(x not in (0, 1, 2) for x in row):
            raise ValueError("genotypes must be rows of equal length with values 0, 1 or 2")
    q, f = start if start is not None else random_start(n, k, m, rng)  # @line L1
    ll = log_likelihood(g, q, f)
    trace = [ll]
    for _ in range(max_iter):  # @line L2
        q1, f1 = block_round(g, q, f)  # @line L3
        if not accelerate:
            chosen = (q1, f1, log_likelihood(g, q1, f1))
        else:
            q2, f2 = block_round(g, q1, f1)  # @line L4
            x0, x1, x2 = _flatten(q, f), _flatten(q1, f1), _flatten(q2, f2)
            u = [b - a for a, b in zip(x0, x1)]  # @line L5
            v = [b - a for a, b in zip(x1, x2)]
            uu = sum(a * a for a in u)
            u_vu = sum(a * (b - a) for a, b in zip(u, v))
            chosen = (q2, f2, log_likelihood(g, q2, f2))
            if uu > 0 and u_vu < 0:
                c = -uu / u_vu  # @line L6
                y = [(1.0 - c) * a + c * b for a, b in zip(x1, x2)]
                qy, fy = _feasible(*_unflatten(y, n, k, m))  # @line L7
                lly = log_likelihood(g, qy, fy)
                if lly >= chosen[2]:  # @line L8
                    chosen = (qy, fy, lly)
        q, f, new_ll = chosen  # @line L9
        trace.append(new_ll)
        if new_ll - ll < tol * (1.0 + abs(ll)):  # @line L10
            break
        ll = new_ll
    return q, f, trace  # @line L11


def gradients(g: list[list[int]], q: Matrix, f: Matrix) -> tuple[Matrix, Matrix]:
    """Partial derivatives of L, with 1 - phi written as sum_k q_ik (1 - f_kj) for Q."""
    k = len(f)
    m = len(g[0])
    gq = [[0.0] * k for _ in g]
    gf = [[0.0] * m for _ in range(k)]
    for i, row in enumerate(g):
        qi = q[i]
        for j, x in enumerate(row):
            phi = sum(qi[c] * f[c][j] for c in range(k))
            s1 = x / phi if x > 0 else 0.0
            s0 = (2 - x) / (1.0 - phi) if x < 2 else 0.0
            for c in range(k):
                gq[i][c] += s1 * f[c][j] + s0 * (1.0 - f[c][j])
                gf[c][j] += qi[c] * (s1 - s0)
    return gq, gf
test_maximum_likelihood_admixture_estimation.py 170 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/maximum-likelihood-admixture-estimation/. The authors are listed in prov/KYJWNZ.jsonl.

import math
import random

import pytest

from maximum_likelihood_admixture_estimation import (admixture, block_round, gradients, log_likelihood,
                                                     project_simplex, update_f, update_q)


def simulate(rng, n, m, k):
    """Ancestry proportions from a Dirichlet(1/2, ..., 1/2) law, frequencies uniform on [0.05, 0.95]."""
    q = []
    for _ in range(n):
        w = [rng.gammavariate(0.5, 1.0) + 1e-12 for _ in range(k)]
        s = sum(w)
        q.append([v / s for v in w])
    f = [[rng.uniform(0.05, 0.95) for _ in range(m)] for _ in range(k)]
    g = []
    for i in range(n):
        row = []
        for j in range(m):
            phi = sum(q[i][c] * f[c][j] for c in range(k))
            row.append((rng.random() < phi) + (rng.random() < phi))
        g.append(row)
    return g, q, f


def test_log_likelihood_by_hand():
    g = [[0, 1, 2]]
    q = [[0.25, 0.75]]
    f = [[0.2, 0.4, 0.8], [0.6, 0.4, 0.4]]
    # phi = 0.5, 0.4, 0.5
    want = 2 * math.log(0.5) + (math.log(0.4) + math.log(0.6)) + 2 * math.log(0.5)
    assert log_likelihood(g, q, f) == pytest.approx(want)


def test_one_em_step_by_hand():
    g = [[2, 0]]
    q = [[0.5, 0.5]]
    f = [[0.8, 0.4], [0.2, 0.4]]
    # Site 0: phi = 0.5; both copies of allele 1 split 0.8 : 0.2. Site 1: phi = 0.4; both copies of allele 0 split 0.5 : 0.5.
    q1 = update_q(g, q, f)
    assert q1[0] == pytest.approx([(1.6 + 1.0) / 4, (0.4 + 1.0) / 4])
    f1 = update_f(g, q, f)
    assert f1[0] == pytest.approx([1.0, 0.0])
    assert f1[1] == pytest.approx([1.0, 0.0])


def test_block_steps_never_lower_likelihood():
    rng = random.Random(1)
    g, _, _ = simulate(rng, 10, 30, 3)
    q = [[1 / 3] * 3 for _ in range(10)]
    f = [[rng.uniform(0.1, 0.9) for _ in range(30)] for _ in range(3)]
    ll = log_likelihood(g, q, f)
    for _ in range(25):
        q = update_q(g, q, f)
        l1 = log_likelihood(g, q, f)
        assert l1 >= ll - 1e-9
        f = update_f(g, q, f)
        l2 = log_likelihood(g, q, f)
        assert l2 >= l1 - 1e-9
        ll = l2
    for row in q:
        assert sum(row) == pytest.approx(1.0)
        assert min(row) >= 0


def test_traces_are_monotone():
    rng = random.Random(2)
    g, _, _ = simulate(rng, 10, 30, 2)
    for acc in (True, False):
        _, _, trace = admixture(g, 2, random.Random(5), accelerate=acc, max_iter=80)
        for a, b in zip(trace, trace[1:]):
            assert b >= a - 1e-9


def test_q_block_against_grid():
    rng = random.Random(3)
    g, _, f = simulate(rng, 3, 40, 2)
    q = [[0.5, 0.5] for _ in range(3)]
    for _ in range(600):
        q = update_q(g, q, f)
    for i in range(3):
        def ll(t):
            return log_likelihood([g[i]], [[t, 1 - t]], f)
        best = max((t / 2000 for t in range(2001)), key=ll)
        assert q[i][0] == pytest.approx(best, abs=1e-3)


def test_f_block_kkt():
    rng = random.Random(6)
    g, q, f_true = simulate(rng, 8, 30, 2)
    f = [row[:] for row in f_true]
    for _ in range(400):
        f = update_f(g, q, f)
    _, gf = gradients(g, q, f)
    for c in range(2):
        for j in range(30):
            if 1e-3 < f[c][j] < 1 - 1e-3:
                assert abs(gf[c][j]) < 1e-3
            elif f[c][j] <= 1e-3:
                assert gf[c][j] <= 1e-3
            else:
                assert gf[c][j] >= -1e-3


def test_q_fixed_point_has_equal_gradients():
    rng = random.Random(12)
    g, _, f = simulate(rng, 4, 30, 3)
    q = [[1 / 3] * 3 for _ in range(4)]
    for _ in range(1500):
        q = update_q(g, q, f)
    gq, _ = gradients(g, q, f)
    for i in range(4):
        for c in range(3):
            if q[i][c] > 1e-2:
                assert gq[i][c] == pytest.approx(60.0, rel=1e-4)  # the multiplier is 2m
            else:
                assert gq[i][c] <= 60.0 * (1 + 1e-4)


def test_fit_beats_truth_and_recovers_ancestry():
    rng = random.Random(4)
    g, q_true, f_true = simulate(rng, 20, 60, 2)
    q, f, trace = admixture(g, 2, random.Random(7))
    assert trace[-1] >= log_likelihood(g, q_true, f_true)
    err_a = sum(abs(a[0] - b[0]) for a, b in zip(q, q_true)) / 20
    err_b = sum(abs(a[0] - b[1]) for a, b in zip(q, q_true)) / 20
    assert min(err_a, err_b) < 0.12  # up to the swap of the two labels


def test_one_population_is_allele_frequency():
    rng = random.Random(9)
    g, _, _ = simulate(rng, 10, 20, 1)
    q, f, _ = admixture(g, 1, random.Random(1))
    for j in range(20):
        assert f[0][j] == pytest.approx(sum(row[j] for row in g) / 20, abs=1e-9)
    assert all(row == [1.0] for row in q)


def test_project_simplex():
    assert project_simplex([0.5, 0.5, 0.5]) == pytest.approx([1 / 3] * 3)
    assert project_simplex([2.0, 0.0, 0.0]) == pytest.approx([1.0, 0.0, 0.0])
    assert project_simplex([0.2, 0.3, 0.5]) == pytest.approx([0.2, 0.3, 0.5])
    rng = random.Random(11)
    for _ in range(30):
        y = [rng.uniform(-1, 2) for _ in range(4)]
        p = project_simplex(y)
        assert sum(p) == pytest.approx(1.0) and min(p) >= 0
        d = sum((a - b) ** 2 for a, b in zip(p, y))
        for _ in range(100):
            w = [rng.random() for _ in range(4)]
            s = sum(w)
            z = [v / s for v in w]
            assert d <= sum((a - b) ** 2 for a, b in zip(z, y)) + 1e-12


def test_symmetric_start_and_errors():
    g = [[0, 2], [2, 0]]
    q = [[0.5, 0.5], [0.5, 0.5]]
    f = [[0.5, 0.5], [0.5, 0.5]]
    q1, f1 = block_round(g, q, f)
    assert q1 == q and f1 == f  # a symmetric start is a fixed point that is not the maximum
    with pytest.raises(ValueError):
        admixture([[0, 3]], 2, random.Random(1))
    with pytest.raises(ValueError):
        admixture([], 2, random.Random(1))

History

Pritchard, Stephens and Donnelly (2000) defined the admixture model and fitted it with a Gibbs sampler in STRUCTURE. Tang, Peng, Wang and Risch (2005) maximized the same likelihood by EM in FRAPPE. Alexander, Novembre and Lange (2009) released ADMIXTURE, which uses block relaxation with sequential quadratic programming and a quasi-Newton acceleration, and was much faster on genome-wide data. Zhou, Alexander and Lange (2011) published the acceleration as a general method for algorithm maps.

References

  1. David H. Alexander, John Novembre and Kenneth Lange, Fast model-based estimation of ancestry in unrelated individuals, Genome Research 19(9), 2009, pp. 1655-1664 (the log-likelihood, block relaxation over Q and F, sequential quadratic programming for each block, and quasi-Newton acceleration)
  2. Tang, Peng, Wang and Risch 2005, pp. 289-301 (FRAPPE, an EM algorithm for the same likelihood)
  3. Hua Zhou, David H. Alexander and Kenneth Lange, A quasi-Newton acceleration for high-dimensional optimization algorithms, Statistics and Computing 21(2), 2011, pp. 261-273 (the secant approximation of the differential of an algorithm map and the extrapolated step)
  4. Jonathan K. Pritchard, Matthew Stephens and Peter Donnelly, Inference of population structure using multilocus genotype data, Genetics 155(2), 2000, pp. 945-959 (the admixture model whose likelihood ADMIXTURE maximizes)

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