Algorithm Search⌘K

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
Properties
randomizednot exactofflineiterative
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 GG with nn rows (individuals) and mm columns (biallelic sites), where gij∈{0,1,2}g_{ij} \in \{0, 1, 2\} is the number of copies of allele 1. A number k≥1k \ge 1 of axes.

Normalization. For site jj, let μj=1n∑igij\mu_j = \frac{1}{n} \sum_i g_{ij} and pj=μj/2p_j = \mu_j / 2, the sample allele frequency. Keep the sites with 0<pj<10 < p_j < 1, say m′m' of them, and set

Mij=gij−μjpj(1−pj),X=1m′MMT.M_{ij} = \frac{g_{ij} - \mu_j}{\sqrt{p_j (1 - p_j)}}, \qquad X = \frac{1}{m'} M M^{\mathsf T}.

Under Hardy-Weinberg proportions, 2pj(1−pj)2 p_j (1 - p_j) is the variance of gijg_{ij}, so after the scaling every site has variance about 2 and about the same weight in XX. The matrix XX is n×nn \times n, symmetric and positive semidefinite. Patterson and coauthors write X=MM′X = M M'; the factor 1/m′1/m' changes the eigenvalues by a constant and not the eigenvectors.

Output. The kk largest eigenvalues λ1≥⋯≥λk\lambda_1 \ge \cdots \ge \lambda_k of XX and unit eigenvectors v1,…,vkv_1, \ldots, v_k. The number vc(i)v_c(i) is the coordinate of individual ii on axis cc. Equivalently, vcv_c is the cc-th left singular vector of MM in its singular value decomposition, with singular value m′λc\sqrt{m' \lambda_c}.

The algorithm

  1. GENETIC-PCA(G, k, rng)
  2. 1for each site j do
  3. 2p_j ← mean of column j / 2; if p_j = 0 or p_j = 1 then skip site j
  4. 3column j of M ← (column j of G - 2 p_j) / sqrt(p_j (1 - p_j))
  5. 4X ← M Mᵀ / m' ▷ n × n
  6. 5Q ← k random Gaussian vectors from rng, orthonormalized
  7. 6repeat at most T times
  8. 7Z ← X Q
  9. 8λ_c ← q_cᵀ z_c for c = 1..k ▷ Ritz values
  10. 9Q ← Gram-Schmidt(Z)
  11. 10if no λ_c changed by more than tol then stop
  12. 11diagonalize 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 XX grows the parts of the vectors along the top eigenvectors faster than the rest, and Gram-Schmidt keeps the kk vectors from collapsing onto the first one. Line L11 is the Rayleigh-Ritz step. It solves the small k×kk \times k eigenproblem of XX restricted to the span of QQ, 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 v1,…,vkv_1, \ldots, v_k, take a site jj to test and a phenotype yy. Remove from the genotype column and from yy their means and their projections on v1,…,vkv_1, \ldots, v_k. Let rr be the correlation of the two residual vectors. The statistic (n−k−1)r2(n - k - 1) r^2 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:

G=(2201210000211022).G = \begin{pmatrix} 2 & 2 & 0 & 1 \\ 2 & 1 & 0 & 0 \\ 0 & 0 & 2 & 1 \\ 1 & 0 & 2 & 2 \end{pmatrix}.

The column means are 1.25,0.75,1,11.25, 0.75, 1, 1, so p=(0.625,0.375,0.5,0.5)p = (0.625, 0.375, 0.5, 0.5), and the scale factors are 0.234375=0.4841\sqrt{0.234375} = 0.4841 for the first two sites and 0.50.5 for the last two. The first row of MM is (1.5492,2.5820,−2,0)(1.5492, 2.5820, -2, 0). Then

X=(3.26671.9333−3.0−2.21.93332.6667−2.2−2.4−3.0−2.23.26671.9333−2.2−2.41.93332.6667).X = \begin{pmatrix} 3.2667 & 1.9333 & -3.0 & -2.2 \\ 1.9333 & 2.6667 & -2.2 & -2.4 \\ -3.0 & -2.2 & 3.2667 & 1.9333 \\ -2.2 & -2.4 & 1.9333 & 2.6667 \end{pmatrix}.

Each row sums to 0, because each column of MM has mean 0. The eigenvalues are 9.84339.8433, 1.49001.4900, 0.53330.5333 and 00, with sum 11.866711.8667, the trace. The first axis is v1=(0.535,0.463,−0.535,−0.463)v_1 = (0.535, 0.463, -0.535, -0.463): it puts individuals 1 and 2 on one side and 3 and 4 on the other, and it carries 9.8433/11.8667=839.8433 / 11.8667 = 83 percent of the total variance. The second axis (−0.463,0.535,0.463,−0.535)(-0.463, 0.535, 0.463, -0.535) separates the members within each group. The eigenvector of eigenvalue 0 is (0.5,0.5,0.5,0.5)(0.5, 0.5, 0.5, 0.5), the direction removed by centering.

Correctness

Three facts make the method correct. First, after centering, X1=0X \mathbf 1 = 0, so XX is symmetric positive semidefinite with rank at most n−1n - 1, and every eigenvector with a positive eigenvalue is orthogonal to 1\mathbf 1: the coordinates of each axis sum to zero. Second, if λk>λk+1\lambda_k > \lambda_{k+1} and the start QQ has a nonsingular projection on the top kk eigenvectors, which a Gaussian start has with probability 1, then the span of QQ after tt rounds tends to the span of v1,…,vkv_1, \ldots, v_k, and the error falls like (λk+1/λk)t(\lambda_{k+1} / \lambda_k)^t. Third, when the span of QQ 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 1,v1,…,vk\mathbf 1, v_1, \ldots, v_k, because these vectors are orthonormal (with 1\mathbf 1 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. MM is the n×m′n \times m' matrix of lines L1 to L3, and X=MMT/m′X = M M^{\mathsf T} / m' is the matrix of line L4. Let λ1≥⋯≥λn\lambda_1 \ge \cdots \ge \lambda_n be the eigenvalues of XX with orthonormal eigenvectors u1,…,unu_1, \ldots, u_n. Write U1=(u1,…,uk)U_1 = (u_1, \ldots, u_k), U2=(uk+1,…,un)U_2 = (u_{k+1}, \ldots, u_n), Λ1=diag(λ1,…,λk)\Lambda_1 = \mathrm{diag}(\lambda_1, \ldots, \lambda_k) and Λ2=diag(λk+1,…,λn)\Lambda_2 = \mathrm{diag}(\lambda_{k+1}, \ldots, \lambda_n).

Lemma 1 (structure of XX). XX is symmetric and positive semidefinite, X1=0X \mathbf 1 = 0, and every eigenvector of XX with a positive eigenvalue is orthogonal to 1\mathbf 1.

Proof. XT=XX^{\mathsf T} = X is clear, and vTXv=∥MTv∥2/m′≥0v^{\mathsf T} X v = \lVert M^{\mathsf T} v \rVert^2 / m' \ge 0. Each column of MM is (g⋅j−μj1)/sj(g_{\cdot j} - \mu_j \mathbf 1)/s_j, and its entries sum to nμj−nμj=0n \mu_j - n \mu_j = 0, so MT1=0M^{\mathsf T} \mathbf 1 = 0 and X1=0X \mathbf 1 = 0. If Xv=λvX v = \lambda v with λ>0\lambda > 0, then λ1Tv=1TXv=(X1)Tv=0\lambda \mathbf 1^{\mathsf T} v = \mathbf 1^{\mathsf T} X v = (X \mathbf 1)^{\mathsf T} v = 0, so 1Tv=0\mathbf 1^{\mathsf T} v = 0. □\square

So the rank of XX is at most n−1n - 1, and the eigenvalues sum to the trace, 1m′∑i,jMij2\frac{1}{m'} \sum_{i, j} M_{ij}^2.

Lemma 2 (spans). Let Q0Q_0 be the matrix of line L5 and QtQ_t the matrix after tt rounds of lines L7 and L9. If XtQ0X^t Q_0 has full column rank, then for each j≤kj \le k the first jj columns of QtQ_t span the same space as the first jj columns of XtQ0X^t Q_0.

Proof. Gram-Schmidt on vectors z1,…,zkz_1, \ldots, z_k of full rank gives orthonormal q1,…,qkq_1, \ldots, q_k with span(q1,…,qj)=span(z1,…,zj)\mathrm{span}(q_1, \ldots, q_j) = \mathrm{span}(z_1, \ldots, z_j) for each jj; that is, Z=QRZ = Q R with RR upper triangular and invertible. Then XQt−1=QtRtX Q_{t-1} = Q_t R_t, and by induction XtQ0=QtRt⋯R1X^t Q_0 = Q_t R_t \cdots R_1. A product of invertible upper triangular matrices is invertible and upper triangular, which gives the claim. □\square

Lemma 3 (the start). Let the entries of the n×kn \times k matrix WW be independent standard Gaussian, and let Q0Q_0 come from WW by Gram-Schmidt. Then C1=U1TQ0C_1 = U_1^{\mathsf T} Q_0 is invertible with probability 1.

Proof. Q0=WR−1Q_0 = W R^{-1} with RR invertible (with probability 1 the columns of WW are independent). So C1C_1 is invertible exactly when U1TWU_1^{\mathsf T} W is. Because U1U_1 has orthonormal columns, the entries of U1TWU_1^{\mathsf T} W are independent standard Gaussian, and the determinant of a k×kk \times k Gaussian matrix is a non-zero polynomial in its entries, which is 0 only on a set of measure 0. □\square

Theorem 1 (convergence of the subspace). Suppose λk>λk+1\lambda_k > \lambda_{k+1} and C1C_1 is invertible, and let C2=U2TQ0C_2 = U_2^{\mathsf T} Q_0. Let PtP_t be the orthogonal projection onto span(Qt)\mathrm{span}(Q_t) and PP the projection onto span(U1)\mathrm{span}(U_1). Then ∥Pt−P∥2≤∥C2C1−1∥2(λk+1/λk)t\lVert P_t - P \rVert_2 \le \lVert C_2 C_1^{-1} \rVert_2 (\lambda_{k+1} / \lambda_k)^t.

Proof. Q0=U1C1+U2C2Q_0 = U_1 C_1 + U_2 C_2, so XtQ0=U1Λ1tC1+U2Λ2tC2X^t Q_0 = U_1 \Lambda_1^t C_1 + U_2 \Lambda_2^t C_2. Multiply on the right by the invertible matrix C1−1Λ1−tC_1^{-1} \Lambda_1^{-t} (here λk>λk+1≥0\lambda_k > \lambda_{k+1} \ge 0, so Λ1\Lambda_1 is invertible). This does not change the column span, and gives Yt=U1+U2EtY_t = U_1 + U_2 E_t with Et=Λ2tC2C1−1Λ1−tE_t = \Lambda_2^t C_2 C_1^{-1} \Lambda_1^{-t}. Since ∥Λ2t∥2=λk+1t\lVert \Lambda_2^t \rVert_2 = \lambda_{k+1}^t and ∥Λ1−t∥2=λk−t\lVert \Lambda_1^{-t} \rVert_2 = \lambda_k^{-t}, we get ∥Et∥2≤∥C2C1−1∥2(λk+1/λk)t\lVert E_t \rVert_2 \le \lVert C_2 C_1^{-1} \rVert_2 (\lambda_{k+1} / \lambda_k)^t. In the basis (U1,U2)(U_1, U_2), the span of YtY_t is the graph of EtE_t. For the graph of a matrix EE, the distance ∥PE−P∥2\lVert P_E - P \rVert_2 between the projections equals sin⁡θ\sin \theta, with tan⁡θ=∥E∥2\tan \theta = \lVert E \rVert_2 the tangent of the largest principal angle, so it is at most ∥E∥2\lVert E \rVert_2. By Lemma 2, YtY_t has the same span as QtQ_t. □\square

Lemma 4 (Rayleigh-Ritz). Let QQ have orthonormal columns and let S=QTXQ=VΘVTS = Q^{\mathsf T} X Q = V \Theta V^{\mathsf T} be the eigendecomposition of line L11. If span(Q)\mathrm{span}(Q) is invariant under XX, then the columns of QVQ V are eigenvectors of XX with eigenvalues Θ\Theta. In general, the cc-th largest Ritz value θc\theta_c satisfies θc≤λc\theta_c \le \lambda_c.

Proof. If XQ=QSX Q = Q S for some SS, then S=QTXQS = Q^{\mathsf T} X Q and XQV=QSV=QVΘX Q V = Q S V = Q V \Theta. For the bound, by the Courant-Fischer theorem θc\theta_c is the maximum over cc-dimensional subspaces WW of span(Q)\mathrm{span}(Q) of the minimum Rayleigh quotient on WW, and λc\lambda_c is the same maximum over all cc-dimensional subspaces of Rn\mathbb R^n. □\square

With Theorem 1, span(Qt)\mathrm{span}(Q_t) tends to the top eigenspace, so the output of line L11 tends to λ1,…,λk\lambda_1, \ldots, \lambda_k and to eigenvectors u1,…,uku_1, \ldots, u_k, up to sign; the sign rule of the code fixes the sign. When some of λ1,…,λk\lambda_1, \ldots, \lambda_k 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 M=AΣBTM = A \Sigma B^{\mathsf T} is a singular value decomposition, then the columns of AA are eigenvectors of XX with eigenvalues σc2/m′\sigma_c^2 / m'.

Proof. X=AΣBTBΣAT/m′=A(Σ2/m′)ATX = A \Sigma B^{\mathsf T} B \Sigma A^{\mathsf T} / m' = A (\Sigma^2 / m') A^{\mathsf T}. □\square

Lemma 6 (the EIGENSTRAT step). Let v1,…,vkv_1, \ldots, v_k be orthonormal eigenvectors of XX with positive eigenvalues. For any y∈Rny \in \mathbb R^n, the vector rr computed by the function residualize is the orthogonal projection of yy onto the complement of span(1,v1,…,vk)\mathrm{span}(\mathbf 1, v_1, \ldots, v_k), which is the residual of the least squares regression of yy on an intercept and the kk axes.

Proof. By Lemma 1, 1/n,v1,…,vk\mathbf 1 / \sqrt n, v_1, \ldots, v_k are orthonormal. Removing the mean subtracts the projection on 1/n\mathbf 1 / \sqrt n. Each later step subtracts (vcTr)vc(v_c^{\mathsf T} r) v_c. 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. □\square

So rr in the statistic (n−k−1)r2(n - k - 1) r^2 is the partial correlation of the genotype and the phenotype given the axes, and n−k−1n - k - 1 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 O(nm)O(n m) time.
  • The matrix XX. Line L4 takes O(n2m)O(n^2 m) time and O(n2)O(n^2) space. This term dominates when mm is much larger than nn, which is usual.
  • Iteration. Each round of lines L7 to L9 costs O(n2k+nk2)O(n^2 k + n k^2). The number of rounds TT grows like log⁡(1/ε)/log⁡(λk/λk+1)\log(1/\varepsilon) / \log(\lambda_k / \lambda_{k+1}), so a small gap between λk\lambda_k and λk+1\lambda_{k+1} makes it slow.
  • Rayleigh-Ritz. Line L11 costs O(n2k+k3)O(n^2 k + k^3).
  • Large samples. For hundreds of thousands of individuals, XX does not fit in memory. Programs then multiply by MM and MTM^{\mathsf T} without forming XX, at O(nmk)O(n m k) 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 XX 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 λ1\lambda_1 so that the eigenvalues sum to n−1n - 1, 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 0.97940.9794.
  • 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 vcv_c replaced by MnewMTvc/(m′λc)M_{\text{new}} M^{\mathsf T} v_c / (m' \lambda_c). 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 nn, block Lanczos or randomized subspace iteration on MM gives the top axes in O(nmk)O(n m k) 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 XX 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 pj=0p_j = 0 or 11 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.

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

  1. 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)
  2. 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)
  3. 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)
  4. 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)
  5. 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.

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