Algorithmcore
Principal components of genotypes
Also called EIGENSTRAT, smartpca.
Standardize each site of the genotype matrix, then take the top eigenvectors of the individual by individual matrix to show structure and to correct association tests.
- Time
- O(n^2 m + T n^2 k) worst · averageO(n^2 m) best
- Space
- O(n m + n^2) extra
- Where
- T = the number of iterations; k = the number of components; m = the number of sites; n = the number of individuals
- Model
- Real RAM
- Properties
- randomizednot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Nick Patterson, Alkes L. Price, David Reich, 2006
Principal components of genotypes is the use of principal component analysis on a matrix of genotypes, with one row per individual and one column per site. Each site is centered and divided by its binomial standard deviation, and the top eigenvectors of the resulting individual by individual matrix give the coordinates of the individuals. The first few axes usually follow ancestry, so a plot of axis 1 against axis 2 shows population structure without a model. The smartpca program of Patterson, Price and Reich (2006) computes the axes and tests how many are significant. EIGENSTRAT, by Price and coauthors (2006), removes the top axes from genotypes and phenotypes before an association test, which corrects for population stratification.
In plain words
Each person has a row of numbers: for each variant, how many copies they carry. People whose ancestors came from the same place share many variants, so their rows look alike. The method finds the few directions in which the rows differ most. Each person gets a score along each direction. A plot of the scores puts related people close together and often looks like a map of where their ancestors lived.
The same scores help a study that looks for variants linked to a disease. If cases come more often from one group than from another, every variant common in that group looks linked to the disease. Removing the scores from the data first takes out this false signal.
The problem
Input. A genotype matrix with rows (individuals) and columns (biallelic sites), where is the number of copies of allele 1. A number of axes.
Normalization. For site , let and , the sample allele frequency. Keep the sites with , say of them, and set
Under Hardy-Weinberg proportions, is the variance of , so after the scaling every site has variance about 2 and about the same weight in . The matrix is , symmetric and positive semidefinite. Patterson and coauthors write ; the factor changes the eigenvalues by a constant and not the eigenvectors.
Output. The largest eigenvalues of and unit eigenvectors . The number is the coordinate of individual on axis . Equivalently, is the -th left singular vector of in its singular value decomposition, with singular value .
The algorithm
GENETIC-PCA(G, k, rng)- 1
for each site j do - 2
p_j ← mean of column j / 2; if p_j = 0 or p_j = 1 then skip site j - 3
column j of M ← (column j of G - 2 p_j) / sqrt(p_j (1 - p_j)) - 4
X ← M Mᵀ / m' ▷ n × n - 5
Q ← k random Gaussian vectors from rng, orthonormalized - 6
repeat at most T times - 7
Z ← X Q - 8
λ_c ← q_cᵀ z_c for c = 1..k ▷ Ritz values - 9
Q ← Gram-Schmidt(Z) - 10
if no λ_c changed by more than tol then stop - 11
diagonalize Qᵀ X Q, rotate Q by its eigenvectors, and return the k eigenpairs
Lines L1 to L4 build the normalized matrix. Lines L5 to L10 are orthogonal iteration, the block form of power iteration: multiplying by grows the parts of the vectors along the top eigenvectors faster than the rest, and Gram-Schmidt keeps the vectors from collapsing onto the first one. Line L11 is the Rayleigh-Ritz step. It solves the small eigenproblem of restricted to the span of , which sorts the vectors and separates close eigenvalues. Large programs replace lines L5 to L11 with a Lanczos or randomized method.
EIGENSTRAT. With the axes , take a site to test and a phenotype . Remove from the genotype column and from their means and their projections on . Let be the correlation of the two residual vectors. The statistic is compared with a chi-square law with 1 degree of freedom. Because the axes come from all sites, a phenotype that differs between groups only through ancestry has no correlation left after the step.
Example
Four individuals at four sites. Individuals 1 and 2 come from one group and 3 and 4 from another:
The column means are , so , and the scale factors are for the first two sites and for the last two. The first row of is . Then
Each row sums to 0, because each column of has mean 0. The eigenvalues are , , and , with sum , the trace. The first axis is : it puts individuals 1 and 2 on one side and 3 and 4 on the other, and it carries percent of the total variance. The second axis separates the members within each group. The eigenvector of eigenvalue 0 is , the direction removed by centering.
Correctness
Three facts make the method correct. First, after centering, , so is symmetric positive semidefinite with rank at most , and every eigenvector with a positive eigenvalue is orthogonal to : the coordinates of each axis sum to zero. Second, if and the start has a nonsingular projection on the top eigenvectors, which a Gaussian start has with probability 1, then the span of after rounds tends to the span of , and the error falls like . Third, when the span of is the top eigenspace, the Rayleigh-Ritz step of line L11 returns the exact eigenpairs. For EIGENSTRAT, the residual step is the orthogonal projection away from the span of , because these vectors are orthonormal (with scaled) by the first fact. The chi-square law of the statistic is an approximation, not a theorem. The full proof is below.
Proof: The normalized matrix is positive semidefinite with the all-ones vector in its kernel, orthogonal iteration converges to the top eigenspace, and the EIGENSTRAT step is a projectionfull
Setting. is the matrix of lines L1 to L3, and is the matrix of line L4. Let be the eigenvalues of with orthonormal eigenvectors . Write , , and .
Lemma 1 (structure of ). is symmetric and positive semidefinite, , and every eigenvector of with a positive eigenvalue is orthogonal to .
Proof. is clear, and . Each column of is , and its entries sum to , so and . If with , then , so .
So the rank of is at most , and the eigenvalues sum to the trace, .
Lemma 2 (spans). Let be the matrix of line L5 and the matrix after rounds of lines L7 and L9. If has full column rank, then for each the first columns of span the same space as the first columns of .
Proof. Gram-Schmidt on vectors of full rank gives orthonormal with for each ; that is, with upper triangular and invertible. Then , and by induction . A product of invertible upper triangular matrices is invertible and upper triangular, which gives the claim.
Lemma 3 (the start). Let the entries of the matrix be independent standard Gaussian, and let come from by Gram-Schmidt. Then is invertible with probability 1.
Proof. with invertible (with probability 1 the columns of are independent). So is invertible exactly when is. Because has orthonormal columns, the entries of are independent standard Gaussian, and the determinant of a Gaussian matrix is a non-zero polynomial in its entries, which is 0 only on a set of measure 0.
Theorem 1 (convergence of the subspace). Suppose and is invertible, and let . Let be the orthogonal projection onto and the projection onto . Then .
Proof. , so . Multiply on the right by the invertible matrix (here , so is invertible). This does not change the column span, and gives with . Since and , we get . In the basis , the span of is the graph of . For the graph of a matrix , the distance between the projections equals , with the tangent of the largest principal angle, so it is at most . By Lemma 2, has the same span as .
Lemma 4 (Rayleigh-Ritz). Let have orthonormal columns and let be the eigendecomposition of line L11. If is invariant under , then the columns of are eigenvectors of with eigenvalues . In general, the -th largest Ritz value satisfies .
Proof. If for some , then and . For the bound, by the Courant-Fischer theorem is the maximum over -dimensional subspaces of of the minimum Rayleigh quotient on , and is the same maximum over all -dimensional subspaces of .
With Theorem 1, tends to the top eigenspace, so the output of line L11 tends to and to eigenvectors , up to sign; the sign rule of the code fixes the sign. When some of are equal, the eigenvectors inside the equal group are any orthonormal basis of its eigenspace. The stopping rule of line L10 tests the change of the Ritz values, which is a heuristic; the theorem bounds the error of the limit process, not of the stop.
Lemma 5 (singular vectors). If is a singular value decomposition, then the columns of are eigenvectors of with eigenvalues .
Proof. .
Lemma 6 (the EIGENSTRAT step). Let be orthonormal eigenvectors of with positive eigenvalues. For any , the vector computed by the function residualize is the orthogonal projection of onto the complement of , which is the residual of the least squares regression of on an intercept and the axes.
Proof. By Lemma 1, are orthonormal. Removing the mean subtracts the projection on . Each later step subtracts . For an orthonormal set, subtracting the projections one at a time gives the projection onto the complement of their span, because each step leaves the earlier coefficients at 0. The least squares residual on a set of regressors is this projection.
So in the statistic is the partial correlation of the genotype and the phenotype given the axes, and is the residual degrees of freedom. That this statistic is close to a chi-square law with 1 degree of freedom under the null is an asymptotic approximation of linear regression, not a fact proved here.
Complexity
- Normalization. Lines L1 to L3 take time.
- The matrix . Line L4 takes time and space. This term dominates when is much larger than , which is usual.
- Iteration. Each round of lines L7 to L9 costs . The number of rounds grows like , so a small gap between and makes it slow.
- Rayleigh-Ritz. Line L11 costs .
- Large samples. For hundreds of thousands of individuals, does not fit in memory. Programs then multiply by and without forming , at per round.
Properties
- No model. The method fits no ancestry model. The axes are summaries of the data, and their meaning has to be read from the sample labels.
- Genealogy. McVean (2009) showed that the expected is a function of the mean coalescence times between pairs of individuals. So the axes reflect the genealogy of the sample, which is also shaped by sample sizes.
- Sample composition. A group with many samples pulls the first axes toward its own internal variation, and a small group can stay hidden.
- The number of axes. Patterson and coauthors rescale so that the eigenvalues sum to , and compare it, after centering and scaling, with the Tracy-Widom law of the largest eigenvalue of a random matrix. The test is then repeated on the remaining eigenvalues. The 5 percent point of the law is .
- Admixture. An individual with ancestry from two groups lies between their clusters, near the point given by its ancestry proportions, when the groups are well separated.
Variants and improvements
- Projection. Compute the axes on reference samples and project new samples onto them, with replaced by . Projected samples shrink toward the center, and some programs correct for this shrinkage.
- LD pruning. Correlated nearby sites can make an axis follow one region of the genome, such as an inversion. Keeping only weakly correlated sites, or regressing out the previous sites, avoids this.
- Randomized and Lanczos methods. For very large , block Lanczos or randomized subspace iteration on gives the top axes in time per pass.
- Model-based alternatives. Maximum likelihood admixture estimation and the Pritchard-Stephens-Donnelly model give ancestry proportions with a direct meaning. Mixed models use the full matrix as a relatedness matrix instead of a few axes.
When to use it
Use it as the first look at a new genotype data set, to find structure, outliers and duplicate or mislabeled samples, and to choose covariates for a genome-wide association study. Use model-based methods when you need ancestry proportions, and mixed models when the sample has close relatives or fine structure.
Pitfalls
- Monomorphic sites. A site with or has a zero scale factor and must be dropped before the division.
- Relatives. Close relatives form their own axes. Remove one of each related pair before computing the axes, and project the others.
- Reading axes as migrations. Gradients and clusters on a plot can come from different histories, and the same history can give different plots with different sample sizes. The axes do not identify a demographic model.
- Sign and order. The sign of an eigenvector is arbitrary, and close eigenvalues can swap order between runs. Compare runs up to sign and rotation.
- Too few axes. EIGENSTRAT with too few axes leaves stratification in the test; too many costs a little power. Genomic control on the test statistics is a check.
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/genetic-principal-components/. The authors are listed in prov/HDK5SD.jsonl.
"""Principal components of a genotype matrix, as in smartpca (Patterson,
Price and Reich 2006) and EIGENSTRAT (Price and coauthors 2006).
Input: a genotype matrix G with n rows (individuals) and m columns (sites).
G[i][j] in {0, 1, 2} is the number of copies of allele 1.
Steps:
1. For each site j, mu_j = the mean of column j and p_j = mu_j / 2. Drop
the sites with p_j = 0 or 1. Set M[i][j] = (G[i][j] - mu_j) / sqrt(p_j (1 - p_j)).
2. X = M M^T / m', with m' the number of kept sites (an n by n matrix).
3. The top k eigenvectors of X, by orthogonal (subspace) iteration from a
random start. Their entries are the coordinates of the individuals.
EIGENSTRAT: regress the top k axes out of each genotype column and out of
the phenotype, and use (n - k - 1) r^2 as an approximate chi-square
statistic with 1 degree of freedom, where r is the correlation of the two
residual vectors.
A dense symmetric Jacobi eigenvalue method is included as an independent
reference for the tests.
"""
from __future__ import annotations
import math
import random
Matrix = list[list[float]]
def normalize(g: list[list[int]]) -> tuple[Matrix, list[int]]:
"""Center each site and divide by sqrt(p (1 - p)). Return M and the kept site indices."""
n = len(g)
m = len(g[0]) if n else 0
kept = []
cols = []
for j in range(m): # @line L1
mu = sum(row[j] for row in g) / n
p = mu / 2.0
if p <= 0.0 or p >= 1.0:
continue # @line L2
s = math.sqrt(p * (1.0 - p))
cols.append([(row[j] - mu) / s for row in g]) # @line L3
kept.append(j)
mat = [[cols[c][i] for c in range(len(cols))] for i in range(n)]
return mat, kept
def covariance(mat: Matrix) -> Matrix:
"""X = M M^T / m for an n by m matrix M."""
n = len(mat)
m = len(mat[0]) if n else 0
if m == 0:
raise ValueError("no polymorphic site")
x = [[0.0] * n for _ in range(n)]
for a in range(n): # @line L4
ra = mat[a]
for b in range(a, n):
rb = mat[b]
v = sum(u * w for u, w in zip(ra, rb)) / m
x[a][b] = v
x[b][a] = v
return x
def _matvec(x: Matrix, v: list[float]) -> list[float]:
return [sum(a * b for a, b in zip(row, v)) for row in x]
def _dot(u: list[float], v: list[float]) -> float:
return sum(a * b for a, b in zip(u, v))
def _orthonormalize(vs: list[list[float]]) -> list[list[float]]:
"""Modified Gram-Schmidt. A vector that is dependent on the earlier ones is replaced by 0."""
out: list[list[float]] = []
for v in vs:
w = list(v)
for q in out:
c = _dot(q, w)
w = [a - c * b for a, b in zip(w, q)]
norm = math.sqrt(_dot(w, w))
out.append([a / norm for a in w] if norm > 1e-300 else [0.0] * len(w))
return out
def top_eigenvectors(x: Matrix, k: int, rng: random.Random, max_iter: int = 5000,
tol: float = 1e-12) -> tuple[list[float], list[list[float]]]:
"""The k largest eigenvalues of a symmetric positive semidefinite matrix
and their unit eigenvectors, by orthogonal iteration.
The start vectors have entries rng.gauss(0, 1), drawn vector by vector
and entry by entry. The sign of each vector is fixed so that its entry
of largest absolute value is positive.
"""
n = len(x)
if not 1 <= k <= n:
raise ValueError("need 1 <= k <= n")
q = _orthonormalize([[rng.gauss(0.0, 1.0) for _ in range(n)] for _ in range(k)]) # @line L5
lam = [0.0] * k
for _ in range(max_iter): # @line L6
z = [_matvec(x, v) for v in q] # @line L7
new_lam = [_dot(v, w) for v, w in zip(q, z)] # @line L8
q_new = _orthonormalize(z) # @line L9
change = max(abs(a - b) for a, b in zip(new_lam, lam))
lam = new_lam
q = q_new
if change <= tol * max(1.0, abs(lam[0])): # @line L10
break
# Rayleigh-Ritz on the final subspace, so that the vectors are sorted
# eigenvectors even when two eigenvalues are close.
z = [_matvec(x, v) for v in q]
small = [[_dot(q[a], z[b]) for b in range(k)] for a in range(k)]
vals, vecs = jacobi_eigen(small)
lam_out = []
q_out = []
for c in range(k):
y = [sum(vecs[r][c] * q[r][i] for r in range(k)) for i in range(n)]
big = max(range(n), key=lambda i: abs(y[i]))
if y[big] < 0:
y = [-a for a in y]
lam_out.append(vals[c])
q_out.append(y)
return lam_out, q_out # @line L11
def jacobi_eigen(a: Matrix, tol: float = 1e-14, max_sweeps: int = 100) -> tuple[list[float], Matrix]:
"""All eigenvalues (in decreasing order) and eigenvectors (as columns) of a
symmetric matrix, by the cyclic Jacobi rotation method."""
n = len(a)
s = [list(row) for row in a]
v = [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]
for _ in range(max_sweeps):
off = sum(s[i][j] ** 2 for i in range(n) for j in range(n) if i != j)
scale = sum(s[i][i] ** 2 for i in range(n)) + off
if off <= tol * tol * max(scale, 1e-300):
break
for p in range(n - 1):
for r in range(p + 1, n):
if abs(s[p][r]) < 1e-300:
continue
theta = (s[r][r] - s[p][p]) / (2.0 * s[p][r])
t = (1.0 if theta >= 0 else -1.0) / (abs(theta) + math.sqrt(theta * theta + 1.0))
c = 1.0 / math.sqrt(t * t + 1.0)
sn = t * c
for i in range(n):
sip, sir = s[i][p], s[i][r]
s[i][p] = c * sip - sn * sir
s[i][r] = sn * sip + c * sir
for i in range(n):
spi, sri = s[p][i], s[r][i]
s[p][i] = c * spi - sn * sri
s[r][i] = sn * spi + c * sri
for i in range(n):
vip, vir = v[i][p], v[i][r]
v[i][p] = c * vip - sn * vir
v[i][r] = sn * vip + c * vir
order = sorted(range(n), key=lambda i: -s[i][i])
vals = [s[i][i] for i in order]
vecs = [[v[r][i] for i in order] for r in range(n)]
return vals, vecs
def principal_components(g: list[list[int]], k: int, rng: random.Random
) -> tuple[list[float], list[list[float]], list[int]]:
"""The smartpca pipeline: normalize, form X, take the top k eigenpairs."""
mat, kept = normalize(g)
x = covariance(mat)
vals, vecs = top_eigenvectors(x, k, rng)
return vals, vecs, kept
def residualize(y: list[float], axes: list[list[float]]) -> list[float]:
"""Remove the mean and the projection on each axis (the axes are orthonormal
and orthogonal to the all-ones vector)."""
n = len(y)
mean = sum(y) / n
r = [a - mean for a in y]
for q in axes:
c = _dot(q, r)
r = [a - c * b for a, b in zip(r, q)]
return r
def eigenstrat_statistic(genotype: list[float], phenotype: list[float], axes: list[list[float]]) -> float:
"""(n - k - 1) r^2 for the residual genotype and phenotype after removing k axes."""
n = len(genotype)
k = len(axes)
a = residualize(genotype, axes)
b = residualize(phenotype, axes)
saa, sbb, sab = _dot(a, a), _dot(b, b), _dot(a, b)
if saa <= 0 or sbb <= 0:
return 0.0
r2 = sab * sab / (saa * sbb)
return (n - k - 1) * r2
test_genetic_principal_components.py 182 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/genetic-principal-components/. The authors are listed in prov/HDK5SD.jsonl.
import math
import random
import pytest
from genetic_principal_components import (covariance, eigenstrat_statistic, jacobi_eigen, normalize,
principal_components, residualize, top_eigenvectors)
def simulate(rng, sizes, m, spread=0.15):
"""Genotypes of len(sizes) populations that drift apart from one ancestral frequency per site."""
g, labels = [], []
anc = [rng.uniform(0.1, 0.9) for _ in range(m)]
freqs = [[min(0.99, max(0.01, a + rng.gauss(0.0, spread))) for a in anc] for _ in sizes]
for k, size in enumerate(sizes):
for _ in range(size):
g.append([(rng.random() < f) + (rng.random() < f) for f in freqs[k]])
labels.append(k)
return g, labels
def matvec(x, v):
return [sum(a * b for a, b in zip(row, v)) for row in x]
def dot(u, v):
return sum(a * b for a, b in zip(u, v))
def test_normalize_by_hand():
g = [[0, 2, 1], [1, 2, 1], [2, 2, 0], [1, 2, 0]]
mat, kept = normalize(g)
assert kept == [0, 2] # site 1 is monomorphic
# site 0: mu = 1, p = 0.5, s = 0.5
assert [row[0] for row in mat] == pytest.approx([-2.0, 0.0, 2.0, 0.0])
# site 2: mu = 0.5, p = 0.25, s = sqrt(0.1875)
s = math.sqrt(0.1875)
assert [row[1] for row in mat] == pytest.approx([0.5 / s, 0.5 / s, -0.5 / s, -0.5 / s])
for c in range(2):
assert sum(row[c] for row in mat) == pytest.approx(0.0, abs=1e-12)
def test_covariance_rows_sum_to_zero():
rng = random.Random(3)
g, _ = simulate(rng, [6, 6], 40)
x = covariance(normalize(g)[0])
n = len(x)
for a in range(n):
assert sum(x[a]) == pytest.approx(0.0, abs=1e-10)
for b in range(n):
assert x[a][b] == x[b][a]
def test_jacobi_reconstructs_matrix():
rng = random.Random(5)
n = 7
b = [[rng.gauss(0, 1) for _ in range(n)] for _ in range(n)]
a = [[sum(b[i][t] * b[j][t] for t in range(n)) for j in range(n)] for i in range(n)]
vals, vecs = jacobi_eigen(a)
assert vals == sorted(vals, reverse=True)
for c in range(n):
v = [vecs[r][c] for r in range(n)]
av = matvec(a, v)
assert av == pytest.approx([vals[c] * t for t in v], abs=1e-9)
for d in range(n):
w = [vecs[r][d] for r in range(n)]
assert dot(v, w) == pytest.approx(1.0 if c == d else 0.0, abs=1e-10)
assert sum(vals) == pytest.approx(sum(a[i][i] for i in range(n)))
def test_planted_spectrum():
rng = random.Random(11)
n = 10
spectrum = [9.0, 4.0, 2.0, 1.0, 0.5, 0.4, 0.3, 0.2, 0.1, 0.0]
raw = [[rng.gauss(0, 1) for _ in range(n)] for _ in range(n)]
q = []
for v in raw: # Gram-Schmidt to a random orthonormal basis
w = list(v)
for u in q:
c = dot(u, w)
w = [a - c * b for a, b in zip(w, u)]
nrm = math.sqrt(dot(w, w))
q.append([a / nrm for a in w])
x = [[sum(spectrum[t] * q[t][i] * q[t][j] for t in range(n)) for j in range(n)] for i in range(n)]
vals, vecs = top_eigenvectors(x, 3, random.Random(1))
assert vals == pytest.approx(spectrum[:3], abs=1e-9)
for c in range(3):
assert abs(dot(vecs[c], q[c])) == pytest.approx(1.0, abs=1e-8)
def test_against_jacobi_on_genotypes():
rng = random.Random(7)
g, _ = simulate(rng, [8, 8, 8], 120)
mat, kept = normalize(g)
x = covariance(mat)
vals, vecs = top_eigenvectors(x, 2, random.Random(2))
ref_vals, ref_vecs = jacobi_eigen(x)
n = len(x)
assert vals == pytest.approx(ref_vals[:2], rel=1e-8)
for c in range(2):
ref = [ref_vecs[r][c] for r in range(n)]
assert abs(dot(vecs[c], ref)) == pytest.approx(1.0, abs=1e-6)
assert matvec(x, vecs[c]) == pytest.approx([vals[c] * t for t in vecs[c]], abs=1e-7)
assert sum(vecs[c]) == pytest.approx(0.0, abs=1e-7) # orthogonal to the all-ones vector
assert dot(vecs[0], vecs[1]) == pytest.approx(0.0, abs=1e-8)
# The trace is the mean over sites of the squared column norms, and the smallest eigenvalue is 0.
assert sum(ref_vals) == pytest.approx(sum(x[i][i] for i in range(n)))
assert ref_vals[-1] == pytest.approx(0.0, abs=1e-9)
def test_first_axis_separates_two_populations():
rng = random.Random(13)
g, labels = simulate(rng, [10, 10], 300)
vals, vecs, kept = principal_components(g, 2, random.Random(4))
pc1 = vecs[0]
side = [v > 0 for v in pc1]
agree = sum(s == (lab == 1) for s, lab in zip(side, labels))
assert agree in (0, len(labels))
assert vals[0] > 1.5 * vals[1]
def test_three_populations_need_two_axes():
rng = random.Random(17)
g, labels = simulate(rng, [8, 8, 8], 300)
vals, vecs, _ = principal_components(g, 3, random.Random(6))
centers = []
for k in range(3):
idx = [i for i, lab in enumerate(labels) if lab == k]
centers.append([sum(vecs[c][i] for i in idx) / len(idx) for c in range(2)])
# Every individual is closest to the center of its own population in the plane of PC1 and PC2.
for i, lab in enumerate(labels):
pt = [vecs[0][i], vecs[1][i]]
dist = [sum((a - b) ** 2 for a, b in zip(pt, ctr)) for ctr in centers]
assert min(range(3), key=lambda k: dist[k]) == lab
assert vals[1] > 1.5 * vals[2]
def test_eigenstrat_removes_stratification():
rng = random.Random(19)
g, labels = simulate(rng, [15, 15], 300, spread=0.2)
vals, vecs, kept = principal_components(g, 1, random.Random(8))
# A phenotype that depends only on the population, not on any site.
pheno = [lab + rng.gauss(0.0, 0.3) for lab in labels]
# The site with the largest frequency difference between the populations.
def diff(j):
a = sum(g[i][j] for i in range(15)) / 30
b = sum(g[i][j] for i in range(15, 30)) / 30
return abs(a - b)
j = max(range(len(g[0])), key=diff)
geno = [float(row[j]) for row in g]
raw = eigenstrat_statistic(geno, pheno, [])
adjusted = eigenstrat_statistic(geno, pheno, vecs[:1])
assert raw > 10.0
assert adjusted < 3.84
def test_statistic_without_axes_is_correlation():
rng = random.Random(23)
y = [rng.gauss(0, 1) for _ in range(25)]
x = [rng.choice((0.0, 1.0, 2.0)) for _ in range(25)]
mx, my = sum(x) / 25, sum(y) / 25
r = sum((a - mx) * (b - my) for a, b in zip(x, y))
r /= math.sqrt(sum((a - mx) ** 2 for a in x) * sum((b - my) ** 2 for b in y))
assert eigenstrat_statistic(x, y, []) == pytest.approx(24 * r * r)
res = residualize(y, [])
assert sum(res) == pytest.approx(0.0, abs=1e-12)
def test_seed_and_errors():
rng = random.Random(29)
g, _ = simulate(rng, [5, 5], 50)
a = principal_components(g, 2, random.Random(1))
b = principal_components(g, 2, random.Random(1))
assert a == b
x = covariance(normalize(g)[0])
with pytest.raises(ValueError):
top_eigenvectors(x, 0, random.Random(1))
with pytest.raises(ValueError):
covariance(normalize([[0, 0], [0, 0]])[0])
History
Cavalli-Sforza and coauthors used principal components of population allele frequencies from the late 1970s to draw maps of human genetic variation. For individual genotypes at many sites, Patterson, Price and Reich (2006) set the normalization used here, gave the smartpca program and proposed the Tracy-Widom test. In the same year Price and coauthors introduced EIGENSTRAT for association studies. Novembre and coauthors (2008) showed that the first two axes of European genotypes resemble a map of Europe, and McVean (2009) linked the axes to coalescence times.
References
- Nick Patterson, Alkes L. Price and David Reich, Population structure and eigenanalysis, PLoS Genetics 2(12), 2006, e190 (the normalization by sqrt(p(1 - p)) with p the sample allele frequency, the matrix X = MM', and the Tracy-Widom test of the largest eigenvalue)
- Alkes L. Price, Nick J. Patterson, Robert M. Plenge, Michael E. Weinblatt, Nancy A. Shadick and David Reich, Principal components analysis corrects for stratification in genome-wide association studies, Nature Genetics 38(8), 2006, pp. 904-909 (EIGENSTRAT, the adjustment of genotypes and phenotypes along the top axes and the association statistic)
- Gil McVean, A genealogical interpretation of principal components analysis, PLoS Genetics 5(10), 2009, e1000686 (the projection of the samples as a function of the mean coalescence times between pairs)
- John Novembre and coauthors, Genes mirror geography within Europe, Nature 456(7218), 2008, pp. 98-101 (the first two axes of European genotypes match a map of Europe)
- Gene H. Golub and Charles F. Van Loan, Matrix Computations, 4th edition, Johns Hopkins University Press, 2013, Section 8.2 (the power method and orthogonal iteration for symmetric matrices, with their rate of convergence)
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 HDK5SD Edit this page History Report an error Markdown