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
- Model
- Real RAM
- Properties
- randomizednot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 has ancestry proportions over ancestral populations, and each population has an allele frequency at site . 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 for individuals at biallelic sites, and a number of ancestral populations.
Model. Given with each row on the simplex and with entries in , each of the two allele copies of individual at site comes from population with probability and then carries allele 1 with probability , independently of all other copies. So is binomial with 2 trials and success probability , and the log-likelihood is
This is the likelihood of the admixture model of STRUCTURE, without the prior. The matrix 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 on the simplex.
Output. at a local maximum of over the product of simplices and boxes, and the value .
The algorithm
ADMIXTURE(G, K, rng)- 1
Q, F ← a random start from rng - 2
repeat at most T times ▷ x = (Q, F) - 3
x1 ← BLOCK(x) ▷ improve Q with F fixed, then F with Q fixed - 4
x2 ← BLOCK(x1) - 5
u ← x1 - x; v ← x2 - x1 - 6
c ← -uᵀu / uᵀ(v - u) - 7
y ← project((1 - c) x1 + c x2) onto the feasible set - 8
if L(y) < L(x2) then y ← x2 - 9
x ← y - 10
if L gained less than ε in this round then stop - 11
return Q, F
The blocks. With fixed, splits into problems, one per row , each concave in on a simplex of dimension . With fixed, splits into problems, one per column , each concave in on the box . 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 at the current values, the expected number of copies of allele 1 in that come from population is , and of allele 0 it is . The EM updates are
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 , and they keep and feasible.
The acceleration. Lines L5 to L7 treat a round of block relaxation as a map whose fixed point is wanted. The secant pair gives a rank-one estimate of the differential of , and line L6 solves the linearized fixed point equation along it. With the step is ; larger extrapolates further along the path. Line L7 puts each row of back on the simplex and clips to , 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 , with fixed to and , genotype and start .
- Site 1: . The two copies of allele 1 split as and , so copies go to population 1 and to population 2.
- Site 2: . The two copies of allele 0 split as and : and .
- Site 3: . The copy of allele 1 splits and ; the copy of allele 0 splits and .
The totals are and out of 6, so the new is , and rises from to . Further EM steps give , which approach the maximum , where . After 7 steps is only . 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 . 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 for every , so the row sums are . The F update is a ratio in . Line L8 accepts the extrapolated point only if its likelihood is at least that of , which is at least , so the values never decrease. Since , they converge. At a fixed point with positive entries, the partial derivatives of in a row of are all equal to , and the partial derivatives in the interior entries of 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. , each row of is on the simplex , and . Write and , where a term with a zero count is 0. Assume the current point has . On , .
Complete data. Give each of the two allele copies of a hidden label , its source population. In the complete model, , and given the copy is allele 1 with probability , independently over copies. Summing over the labels gives the binomial law of with parameter , so is the observed-data log-likelihood of this model.
Lemma 1 (E-step). Given and the current , the expected number of the copies of allele 1 with label is , and of the copies of allele 0 it is . Also .
Proof. For a copy of allele 1, Bayes' rule gives , and the copies are independent given the parameters, so the expectation is times this. The same holds for allele 0 with . The posteriors of one copy sum to 1 over , and there are 2 copies.
Lemma 2 (M-steps). Let and be the numbers of copies of allele 1 and of allele 0 with label . The complete-data log-likelihood is
where a dot means a sum over that index. With replaced by its conditional means and (Lemma 1), the function so obtained has its maximum over in each row at , and its maximum over in each at when the denominator is positive.
Proof. The part is with and by Lemma 1. By Gibbs' inequality its maximum on the simplex is at . The part is with , which is concave with maximum at .
Theorem 1 (block steps). Let be the result of the Q update with fixed. Then each row of is on , and . Let be the result of the F update with fixed. Then and .
Proof. Feasibility: the entries of are non-negative, and its row sums are by Lemma 1. The entries of 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 with fixed, by Lemma 2, so it is one EM step of the model with parameter 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 . The same argument with as the free block gives the second claim.
Corollary (one round). The map BLOCK of line L3 gives , so .
Theorem 2 (accelerated round). The point chosen by lines L6 to L9 is feasible, and its likelihood is at least .
Proof. If the extrapolated point is used, line L7 has made it feasible: each row of is the Euclidean projection onto , then raised to at least and renormalized, so it is on ; each is clipped to . Then , so is finite. Line L8 keeps the extrapolated point only if its likelihood is at least , and otherwise keeps . In both cases the likelihood is at least by the corollary. If or , the code keeps .
So the values do not decrease. Each makes every term at most 0, so , and the values converge. This shows that the test of line L10 is met for every .
Lemma 3 (the projection). For , the function project_simplex returns the unique point of nearest to .
Proof. is closed and convex, so the nearest point is unique. The KKT conditions of minimizing under and say that for one number with . The left side is continuous and strictly decreasing in where it is positive, so is unique. With sorted as , let be the largest index with ; then makes exactly the first entries positive and gives sum 1, which is what the code computes.
Theorem 3 (fixed points). Suppose a BLOCK round leaves unchanged. Then for each and each with , , where the derivative is taken with written as . For each with , .
Proof. With that form of , , so . If and , dividing by gives . For , with and . If then , and the derivative is . Since BLOCK first updates and then updates with the new , a fixed point of BLOCK has and then .
The derivative in a row of is equal on the support of , with Lagrange multiplier for the constraint . This is the KKT condition on the support. For written with , the derivatives differ by the constant in all , 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 , while , with matching frequencies gives .
Complexity
- One block step. Computing for all pairs costs , and so do the sums of the EM updates. A round of line L3 costs , and lines L4 to L8 add a constant factor.
- Rounds. The number of rounds 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. for the genotypes and for and .
- Comparison. One sweep of the STRUCTURE Gibbs sampler also costs , 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. 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 populations gives the same likelihood. Runs must be aligned before they are compared.
- Saddle points. A start where all rows of 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 or or . 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.
- . The maximum is , the sample allele frequency, reached in one F step.
Variants and improvements
- Choosing . A later version of ADMIXTURE adds cross-validation: it holds out entries of , 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 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 . 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 discrete sources without drift between them. The method fits a -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 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.
# 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
- 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)
- Tang, Peng, Wang and Risch 2005, pp. 289-301 (FRAPPE, an EM algorithm for the same likelihood)
- 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)
- 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.
| 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 KYJWNZ Edit this page History Report an error Markdown