Algorithmadvanced
SNP heritability estimation
Also called GREML, GCTA-GREML, genomic-relatedness-based restricted maximum likelihood.
Estimates the fraction of trait variance explained by all genotyped SNPs, by REML in a mixed model whose random effect has the genomic relationship matrix as covariance.
- Time
- Θ(n^2 m + t (n^3 + r n^2)) worst · averageΘ(n^2 m + n^3) best
- Space
- Θ(r n^2) extra
- Where
- m = the number of SNPs; n = the number of individuals; r = the number of relationship matrices; t = the number of iterations
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Jian Yang, Beben Benyamin, Peter M. Visscher, 2010
SNP heritability estimation measures how much of the variance of a trait the genotyped SNPs explain together, without finding any single SNP. It fits a linear mixed model in which the genetic part of the trait has the genomic relationship matrix as covariance, and estimates the two variance components by restricted maximum likelihood. The usual solver is the average information algorithm, a Newton-type method whose curvature matrix is cheap to compute. The ratio of the genetic component to the total is the SNP heritability .
In plain words
Two unrelated people still share a little more or a little less of their genome than average. If the trait is partly genetic, pairs who share more should also have slightly more similar trait values. The method measures the genetic similarity of every pair from the SNPs, then asks how strongly trait similarity follows it. A strong link means the SNPs explain much of the trait. The answer comes from a likelihood that splits the total variance into a genetic part and a noise part. An iterative search finds the split under which the observed traits are most probable. Each step uses the slope of the likelihood and a cheap measure of its curvature. The search stops when the split no longer changes.
The problem
Input. A trait , a matrix of fixed covariates with full column rank, and symmetric relationship matrices of size . With one matrix, is the genomic relationship matrix, with entries off the diagonal for genotypes and allele frequencies .
Model.
so . Write and , which is or .
Output. The REML estimate , the SNP heritability and its standard error.
The REML log-likelihood is, up to a constant,
The algorithm
GREML(y, X, A_1, ..., A_r)- 1
θ ← (v, ..., v) with v = Var(y)/(r + 1) - 2
V ← Σ_k θ_k A_k + θ_e I; P ← V⁻¹ - V⁻¹X(XᵀV⁻¹X)⁻¹XᵀV⁻¹; ℓ ← ℓ_R(θ) repeat- 3
d_k ← -½ [tr(P V_k) - yᵀ P V_k P y] for each component k - 4
AI_kl ← ½ yᵀ P V_k P V_l P y - 5
Δ ← AI⁻¹ d (in the first round, the EM-REML step Δ_k = θ_k² (yᵀPV_kPy - tr(PV_k))/n) - 6
θ ← θ + Δ, halving Δ until V is positive definite and ℓ_R does not go down; update P, ℓ until the gain in ℓ_R is below a tolerance- 7
h² ← Σ_k θ_k / (Σ_k θ_k + θ_e) - 8
return θ, h², and the standard error of h² from AI⁻¹ by the delta method
The vector of line L3 is the gradient of . The matrix of line L4 is the mean of the observed and the expected information, but it needs only the vectors , not the traces of products of matrices. Components that the step would make negative are set to a small positive floor, in the code. The standard error of line L8 uses the gradient of in , for each genetic component and for , with the total.
Example
Take three pairs of identical twins, so that is 1 within a pair and 0 between pairs, with the trait values , and and only an intercept in . With this the model is the balanced one-way layout, and REML has the closed form of the analysis of variance.
- The pair means are 2, 6 and 10, and the grand mean is 6.
- Within pairs, each pair has the sum of squares 2, so .
- Between pairs, with 2 degrees of freedom, so .
- So , , and .
The code starts at from and reaches in 7 rounds. At the estimate, has the diagonal and , which are and , the sampling variances of the two estimates. The delta method gives the standard error 0.143 for .
Correctness
Differentiating , and with the identity gives the score of line L3. Because is linear in , the observed information is and the expected information is , so their mean is the matrix of line L4. This matrix is a Gram matrix in the semidefinite form , so when it is positive definite the step points uphill, and halving it in line L6 ends with not lower than before. A limit point in the interior with a positive definite AI matrix therefore has , a stationary point of the REML likelihood. The full proof is below.
Proof: The average information step goes uphill on the REML likelihood and stops at a stationary pointfull
Let , let be with full column rank and , and let be symmetric. For put , and let be the open set of with positive definite. On put , , and
is for and for , and does not depend on .
Lemma 1 (properties of ). is symmetric, , , and is positive semidefinite.
Proof. Symmetry is clear. . Let be the symmetric square root and . Then with , the orthogonal projection on the columns of . is a symmetric idempotent matrix, so it is positive semidefinite, and .
Lemma 2 (derivative of ). .
Proof. With and , the product rule gives
Write , so . The four terms are .
Lemma 3 (score, line L3). .
Proof. and by the cyclic property of the trace. Their sum is . By Lemma 2, .
Lemma 4 (the average information, line L4). Let be the observed information and under the expected information. Then , and is positive semidefinite.
Proof. Differentiate Lemma 3 in with Lemma 2: and (two terms, equal because the matrices are symmetric). So . For a symmetric , . With , by Lemma 1, and since . So , and the mean of and is . With , , so for any , by Lemma 1.
Lemma 5 (the halving of line L6 ends). Let have every component above the floor, let , let be positive definite, and let . Then for all small enough , , every component stays above the floor, and .
Proof. is open and the floor constraints are strict at , so both hold for small . is positive definite, so . is smooth on , so , which is above for small . Halving reaches such a after finitely many steps.
The first round uses the EM-REML step . This is with the positive diagonal matrix , so when , and the proof of Lemma 5 applies to it too.
Theorem. (a) The values of the accepted iterates never decrease. (b) Let the iterates converge to with every component above the floor and positive definite, with steps of length for some . Then , so is a stationary point of the REML likelihood.
Proof. (a) Line L6 accepts a point only when does not go down. (b) The iterates converge, so the accepted steps go to . Since , . The functions and are continuous on and is invertible, so and .
Line L7 computes from the returned . Line L8 uses at the end point as the covariance matrix of , and the gradient of , with for and , where . The standard error is , the delta method.
What the theorem does not say. It does not say that the stationary point is the global maximum, and it does not cover a maximum on the boundary, where a component sits at the floor. At a stationary point the AI matrix differs from the expected information by a term with mean zero, so the standard error is an approximation that is good in large samples and away from the boundary. The tests check the stationary point against an independent maximization of the profile likelihood, against the closed form of the balanced one-way layout, and against finite differences of .
Complexity
- Relationship matrix. Building from SNPs costs , once.
- Each round. A Cholesky factor and the inverse of cost . Forming costs , and the score and the AI matrix cost for the products and the traces, and for the entries of AI.
- Rounds. Near the maximum the method converges like a Newton method, and a few to a few tens of rounds are usual. The tests use at most a few tens.
- Space. for the matrices.
- One matrix. With , an eigendecomposition of makes diagonal for every , as in mixed model association. Each round then costs after one step.
Properties
- Increasing likelihood. With the step halving of line L6, never goes down from one round to the next.
- Invariant to the fixed effects. REML uses only the error contrasts with , so the estimate does not depend on .
- A lower bound on heritability. The SNPs capture the causal variants only through linkage disequilibrium, so is in general below the narrow-sense heritability from family studies.
- Partitioning. With one matrix per chromosome, per class of allele frequency or per annotation, the components add up to the total SNP heritability.
- Standard error falls like . For unrelated people the off-diagonal entries of are small, and the information about grows with the number of pairs, .
Variants and improvements
- Several components. Fit matrices at once to split the SNP heritability between genome regions, as in the test with two halves of the SNPs.
- Spectral form. With one matrix, rotate the data by the eigenvectors of and search over the variance ratio, as for association testing.
- Case-control traits. Fit the linear model to the 0/1 status, then transform the estimate to the liability scale with the disease prevalence and the case fraction of the sample.
- Methods of moments. Haseman-Elston regression and its multi-component forms regress the products of trait values on the entries of . They need no matrix inverse and scale to biobanks, with larger standard errors.
- Summary statistics only. LD score regression estimates the SNP heritability from association statistics and a reference panel, without individual genotypes.
When to use it
- Measuring how much of a trait the genotyped SNPs explain, in a sample of individual-level genotypes.
- Comparing the SNP heritability with the pedigree heritability, to see how much is missing from the SNPs.
- Splitting the genetic variance between chromosomes, functional annotations or allele frequency classes.
- Estimating the genetic correlation of two traits with a bivariate model on the same samples.
Pitfalls
- Close relatives. With relatives in the sample, shared environment and causal variants not tagged by the SNPs both raise the similarity of relatives, and the estimate is no longer a SNP heritability. Remove one person from each pair above a small relatedness cutoff.
- Population structure. Ancestry differences show in and can follow the trait for non-genetic reasons. Add principal components as covariates.
- Boundary estimates. With small samples, the maximum is often at or . The usual standard error and the chi-squared test of the likelihood ratio do not apply at the boundary.
- A matrix that is not positive semidefinite. The genomic relationship matrix with the usual diagonal can have small negative eigenvalues. The step must keep positive definite.
- Linkage disequilibrium and frequency. The estimate assumes that every standardized SNP has the same expected contribution. When this is wrong, for example because rare SNPs or SNPs in regions of low linkage disequilibrium contribute more, the estimate is biased.
- Cost. The per round limits the exact method to tens of thousands of people.
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
# Group module of the pg4 pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Dense linear algebra and genotype simulation for the mixed model pages.
This module holds no method of a page. It has the matrix routines that the
pages mixed-model-association and snp-heritability-estimation both use
(Cholesky factor, solves, a symmetric eigendecomposition), the genomic
relationship matrix of GCTA, and a simulator of genotypes from two
populations. Matrices are lists of rows of floats.
"""
from __future__ import annotations
import math
from typing import List, Sequence, Tuple
Matrix = List[List[float]]
# Small helpers
def dot(a: Sequence[float], b: Sequence[float]) -> float:
s = 0.0
for x, y in zip(a, b):
s += x * y
return s
def matvec(A: Matrix, x: Sequence[float]) -> List[float]:
return [dot(row, x) for row in A]
def tmatvec(A: Matrix, x: Sequence[float]) -> List[float]:
"""A^T x."""
out = [0.0] * len(A[0])
for row, xi in zip(A, x):
if xi != 0.0:
for j, a in enumerate(row):
out[j] += a * xi
return out
def transpose(A: Matrix) -> Matrix:
return [list(col) for col in zip(*A)]
def matmul(A: Matrix, B: Matrix) -> Matrix:
Bt = transpose(B)
return [[dot(row, col) for col in Bt] for row in A]
def identity(n: int) -> Matrix:
return [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]
# Cholesky factor and solves
def cholesky(A: Matrix) -> Matrix:
"""Lower triangular L with L L^T = A, for a symmetric positive definite A."""
n = len(A)
L = [[0.0] * n for _ in range(n)]
for i in range(n):
Li = L[i]
for j in range(i + 1):
Lj = L[j]
s = A[i][j]
for k in range(j):
s -= Li[k] * Lj[k]
if i == j:
if s <= 0.0:
raise ValueError("matrix is not positive definite")
Li[i] = math.sqrt(s)
else:
Li[j] = s / Lj[j]
return L
def chol_solve(L: Matrix, b: Sequence[float]) -> List[float]:
"""Solve (L L^T) x = b."""
n = len(L)
y = [0.0] * n
for i in range(n):
s = b[i]
Li = L[i]
for k in range(i):
s -= Li[k] * y[k]
y[i] = s / Li[i]
x = [0.0] * n
for i in range(n - 1, -1, -1):
s = y[i]
for k in range(i + 1, n):
s -= L[k][i] * x[k]
x[i] = s / L[i][i]
return x
def chol_logdet(L: Matrix) -> float:
return 2.0 * sum(math.log(L[i][i]) for i in range(len(L)))
def chol_inverse(L: Matrix) -> Matrix:
"""(L L^T)^-1, column by column."""
n = len(L)
cols = []
for j in range(n):
e = [0.0] * n
e[j] = 1.0
cols.append(chol_solve(L, e))
return transpose(cols)
def solve_small(A: Matrix, b: Sequence[float]) -> List[float]:
"""Solve A x = b by Gaussian elimination with partial pivoting."""
n = len(A)
M = [list(A[i]) + [b[i]] for i in range(n)]
for c in range(n):
piv = max(range(c, n), key=lambda r: abs(M[r][c]))
if M[piv][c] == 0.0:
raise ValueError("singular matrix")
M[c], M[piv] = M[piv], M[c]
for r in range(c + 1, n):
f = M[r][c] / M[c][c]
if f != 0.0:
for k in range(c, n + 1):
M[r][k] -= f * M[c][k]
x = [0.0] * n
for r in range(n - 1, -1, -1):
s = M[r][n]
for k in range(r + 1, n):
s -= M[r][k] * x[k]
x[r] = s / M[r][r]
return x
def inverse_small(A: Matrix) -> Matrix:
n = len(A)
cols = [solve_small(A, [1.0 if i == j else 0.0 for i in range(n)]) for j in range(n)]
return transpose(cols)
# Symmetric eigendecomposition: Householder tridiagonalization, then the
# implicit QL method (the tred2 and tql2 routines of EISPACK, as in JAMA).
def eigh(A: Matrix) -> Tuple[List[float], Matrix]:
"""Eigenvalues (ascending) and eigenvectors of a symmetric matrix.
Returns (d, V): column k of V is a unit eigenvector for d[k], so
A = V diag(d) V^T.
"""
n = len(A)
V = [list(map(float, row)) for row in A]
d = [0.0] * n
e = [0.0] * n
if n == 1:
return [V[0][0]], [[1.0]]
# tred2
for j in range(n):
d[j] = V[n - 1][j]
for i in range(n - 1, 0, -1):
scale = 0.0
h = 0.0
for k in range(i):
scale += abs(d[k])
if scale == 0.0:
e[i] = d[i - 1]
for j in range(i):
d[j] = V[i - 1][j]
V[i][j] = 0.0
V[j][i] = 0.0
else:
for k in range(i):
d[k] /= scale
h += d[k] * d[k]
f = d[i - 1]
g = math.sqrt(h)
if f > 0:
g = -g
e[i] = scale * g
h -= f * g
d[i - 1] = f - g
for j in range(i):
e[j] = 0.0
for j in range(i):
f = d[j]
V[j][i] = f
g = e[j] + V[j][j] * f
for k in range(j + 1, i):
g += V[k][j] * d[k]
e[k] += V[k][j] * f
e[j] = g
f = 0.0
for j in range(i):
e[j] /= h
f += e[j] * d[j]
hh = f / (h + h)
for j in range(i):
e[j] -= hh * d[j]
for j in range(i):
f = d[j]
g = e[j]
for k in range(j, i):
V[k][j] -= f * e[k] + g * d[k]
d[j] = V[i - 1][j]
V[i][j] = 0.0
d[i] = h
for i in range(n - 1):
V[n - 1][i] = V[i][i]
V[i][i] = 1.0
h = d[i + 1]
if h != 0.0:
for k in range(i + 1):
d[k] = V[k][i + 1] / h
for j in range(i + 1):
g = 0.0
for k in range(i + 1):
g += V[k][i + 1] * V[k][j]
for k in range(i + 1):
V[k][j] -= g * d[k]
for k in range(i + 1):
V[k][i + 1] = 0.0
for j in range(n):
d[j] = V[n - 1][j]
V[n - 1][j] = 0.0
V[n - 1][n - 1] = 1.0
e[0] = 0.0
# tql2
for i in range(1, n):
e[i - 1] = e[i]
e[n - 1] = 0.0
f = 0.0
tst1 = 0.0
eps = 2.0 ** -52
for l in range(n):
tst1 = max(tst1, abs(d[l]) + abs(e[l]))
m = l
while m < n:
if abs(e[m]) <= eps * tst1:
break
m += 1
if m == n:
m = n - 1
if m > l:
for _ in range(200):
g = d[l]
p = (d[l + 1] - g) / (2.0 * e[l])
r = math.hypot(p, 1.0)
if p < 0:
r = -r
d[l] = e[l] / (p + r)
d[l + 1] = e[l] * (p + r)
dl1 = d[l + 1]
h = g - d[l]
for i in range(l + 2, n):
d[i] -= h
f += h
p = d[m]
c = c2 = c3 = 1.0
el1 = e[l + 1]
s = s2 = 0.0
for i in range(m - 1, l - 1, -1):
c3 = c2
c2 = c
s2 = s
g = c * e[i]
h = c * p
r = math.hypot(p, e[i])
e[i + 1] = s * r
s = e[i] / r
c = p / r
p = c * d[i] - s * g
d[i + 1] = h + s * (c * g + s * d[i])
for k in range(n):
Vk = V[k]
h = Vk[i + 1]
Vk[i + 1] = s * Vk[i] + c * h
Vk[i] = c * Vk[i] - s * h
p = -s * s2 * c3 * el1 * e[l] / dl1
e[l] = s * p
d[l] = c * p
if abs(e[l]) <= eps * tst1:
break
else:
raise ArithmeticError("eigenvalue iteration did not converge")
d[l] += f
e[l] = 0.0
order = sorted(range(n), key=lambda k: d[k])
d_sorted = [d[k] for k in order]
V_sorted = [[V[i][k] for k in order] for i in range(n)]
return d_sorted, V_sorted
# Genotypes
def allele_freqs(G: Sequence[Sequence[int]]) -> List[float]:
"""Sample frequency of the counted allele at each SNP; G is n people by m SNPs."""
n = len(G)
m = len(G[0])
return [sum(G[i][j] for i in range(n)) / (2.0 * n) for j in range(m)]
def standardize(G: Sequence[Sequence[int]], freqs=None) -> Matrix:
"""W[i][j] = (x_ij - 2 p_j) / sqrt(2 p_j (1 - p_j)); monomorphic SNPs give 0."""
p = freqs or allele_freqs(G)
sd = [math.sqrt(2.0 * q * (1.0 - q)) for q in p]
return [[(row[j] - 2.0 * p[j]) / sd[j] if sd[j] > 0 else 0.0 for j in range(len(p))]
for row in G]
def grm(G: Sequence[Sequence[int]]) -> Matrix:
"""The genomic relationship matrix of GCTA (Yang et al. 2011).
Off the diagonal, A_jk = (1/m) sum_i (x_ji - 2p_i)(x_ki - 2p_i) / (2p_i(1-p_i)).
On the diagonal, A_jj = 1 + (1/m) sum_i (x_ji^2 - (1 + 2p_i) x_ji + 2p_i^2) / (2p_i(1-p_i)).
Here j and k are people and i runs over the m polymorphic SNPs.
"""
p = allele_freqs(G)
keep = [i for i, q in enumerate(p) if 0.0 < q < 1.0]
m = len(keep)
n = len(G)
W = [[(G[a][i] - 2.0 * p[i]) / math.sqrt(2.0 * p[i] * (1.0 - p[i])) for i in keep] for a in range(n)]
A = [[0.0] * n for _ in range(n)]
for a in range(n):
Wa = W[a]
for b in range(a + 1, n):
v = dot(Wa, W[b]) / m
A[a][b] = v
A[b][a] = v
s = 0.0
for i in keep:
x = G[a][i]
q = p[i]
s += (x * x - (1.0 + 2.0 * q) * x + 2.0 * q * q) / (2.0 * q * (1.0 - q))
A[a][a] = 1.0 + s / m
return A
def simulate_two_populations(rng, n_a: int, n_b: int, m: int, fst: float,
pmin: float = 0.1, pmax: float = 0.9):
"""Genotypes of n_a + n_b people from two populations, m unlinked SNPs.
For each SNP, in order: an ancestral frequency p ~ Uniform(pmin, pmax),
then a frequency for population A and one for B, each from the
Balding-Nichols beta law with mean p and variance fst p (1 - p). Then the
genotypes, person by person, as Binomial(2, frequency) by two
rng.random() draws each. Returns (G, pop), G as n by m, pop[i] in {0, 1}.
"""
pops = [0] * n_a + [1] * n_b
freqs = []
c = (1.0 - fst) / fst
for _ in range(m):
p = pmin + (pmax - pmin) * rng.random()
fa = rng.betavariate(c * p, c * (1.0 - p))
fb = rng.betavariate(c * p, c * (1.0 - p))
freqs.append((fa, fb))
G = []
for k in pops:
row = []
for j in range(m):
f = freqs[j][k]
row.append((rng.random() < f) + (rng.random() < f))
G.append(row)
return G, pops
snp_heritability_estimation.py 126 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/snp-heritability-estimation/. The authors are listed in prov/Q44QVJ.jsonl.
"""SNP heritability by REML with the average information algorithm.
The model for n individuals is
y = X beta + g_1 + ... + g_r + e, g_i ~ N(0, s_i A_i), e ~ N(0, s_e I),
so Var(y) = V = s_1 A_1 + ... + s_r A_r + s_e I. Each A_i is a genomic
relationship matrix (one for all SNPs gives the usual GREML model). The
SNP heritability is h2 = (s_1 + ... + s_r) / (s_1 + ... + s_r + s_e).
The variance components theta = (s_1, ..., s_r, s_e) maximize the restricted
log-likelihood
l_R = -1/2 [ log det V + log det(X^T V^-1 X) + y^T P y ] + const,
P = V^-1 - V^-1 X (X^T V^-1 X)^-1 X^T V^-1.
With V_k the derivative of V in theta_k (A_k, or I for s_e), the score is
d_k = -1/2 [ tr(P V_k) - y^T P V_k P y ],
and the average information matrix is
AI_kl = 1/2 y^T P V_k P V_l P y.
The update is theta <- theta + AI^-1 d (Gilmour, Thompson and Cullis 1995).
The first iteration is one EM-REML step, which is slower but stays positive.
"""
from __future__ import annotations
import math
from typing import Dict, List, Sequence
from pg4lmm import chol_inverse, chol_logdet, cholesky, dot, inverse_small, matvec, solve_small
def _reml_parts(As, y, X, theta):
"""P, P y and l_R (without the constant) at theta."""
n, p = len(y), len(X[0])
r = len(As)
V = [[theta[r] if i == j else 0.0 for j in range(n)] for i in range(n)]
for k in range(r):
sk, Ak = theta[k], As[k]
for i in range(n):
Vi, Aki = V[i], Ak[i]
for j in range(n):
Vi[j] += sk * Aki[j]
L = cholesky(V)
Vinv = chol_inverse(L)
VX = [[dot(Vinv[i], [X[t][a] for t in range(n)]) for a in range(p)] for i in range(n)]
C = [[sum(X[t][a] * VX[t][b] for t in range(n)) for b in range(p)] for a in range(p)]
Cinv = inverse_small(C)
LC = cholesky(C)
# P = Vinv - VX Cinv VX^T
VXC = [[sum(VX[i][a] * Cinv[a][b] for a in range(p)) for b in range(p)] for i in range(n)]
P = [[Vinv[i][j] - dot(VXC[i], VX[j]) for j in range(n)] for i in range(n)]
Py = matvec(P, y)
loglik = -0.5 * (chol_logdet(L) + chol_logdet(LC) + dot(y, Py))
return P, Py, loglik
def reml_loglik(As, y, X, theta) -> float:
"""The restricted log-likelihood at theta = (s_1, ..., s_r, s_e), up to a constant."""
return _reml_parts(As, y, X, theta)[2]
def greml(As: Sequence[Sequence[Sequence[float]]], y: Sequence[float], X,
tol: float = 1e-10, max_iter: int = 200) -> Dict[str, object]:
"""REML estimates of the variance components and the SNP heritability.
As is a list of r relationship matrices (n by n), X is n by p with full
column rank. Returns a dict with theta, h2, its standard error se_h2,
the inverse AI matrix, the log-likelihood and the number of iterations.
"""
n, p = len(y), len(X[0])
r = len(As)
if n <= p:
raise ValueError("need more individuals than covariates")
mean = sum(y) / n
vp = sum((v - mean) ** 2 for v in y) / (n - 1)
theta = [vp / (r + 1)] * (r + 1) # @line L1
floor = 1e-6 * vp
Vk = list(As) + [None] # None stands for the identity
P, Py, loglik = _reml_parts(As, y, X, theta) # @line L2
it = 0
for it in range(1, max_iter + 1):
VPy = [Py if M is None else matvec(M, Py) for M in Vk]
PVPy = [matvec(P, u) for u in VPy]
tr = [sum(P[i][i] for i in range(n)) if M is None
else sum(dot(P[i], M[i]) for i in range(n)) for M in Vk]
quad = [dot(Py, u) for u in VPy]
score = [-0.5 * (tr[k] - quad[k]) for k in range(r + 1)] # @line L3
AI = [[0.5 * dot(VPy[k], PVPy[l]) for l in range(r + 1)] for k in range(r + 1)] # @line L4
if it == 1:
# One EM-REML step: s_k <- s_k + s_k^2 (y'P V_k P y - tr(P V_k)) / n.
step = [theta[k] ** 2 * (quad[k] - tr[k]) / n for k in range(r + 1)]
else:
step = solve_small(AI, score) # @line L5
# Keep the components above the floor and V positive definite, and do
# not let l_R go down: halve the step until both hold.
for _ in range(60):
new = [max(theta[k] + step[k], floor) for k in range(r + 1)]
try:
parts = _reml_parts(As, y, X, new)
except ValueError:
parts = None
if parts is not None and parts[2] >= loglik - 1e-12 * abs(loglik):
break
step = [v / 2.0 for v in step]
else:
break
gain = parts[2] - loglik
theta = new # @line L6
P, Py, loglik = parts
if abs(gain) < tol:
break
VPy = [Py if M is None else matvec(M, Py) for M in Vk]
PVPy = [matvec(P, u) for u in VPy]
AI = [[0.5 * dot(VPy[k], PVPy[l]) for l in range(r + 1)] for k in range(r + 1)]
AIinv = inverse_small(AI)
sg = sum(theta[:r])
total = sg + theta[r]
h2 = sg / total # @line L7
# Delta method: dh2/ds_k = s_e / total^2 for k < r, and -sg / total^2 for s_e.
grad = [theta[r] / total ** 2] * r + [-sg / total ** 2]
var = sum(grad[a] * AIinv[a][b] * grad[b] for a in range(r + 1) for b in range(r + 1))
return {"theta": theta, "h2": h2, "se_h2": math.sqrt(max(var, 0.0)),
"AIinv": AIinv, "loglik": loglik, "iterations": it} # @line L8
test_snp_heritability_estimation.py 136 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/snp-heritability-estimation/. The authors are listed in prov/Q44QVJ.jsonl.
import math
import random
from fractions import Fraction
from pg4lmm import chol_logdet, chol_solve, cholesky, eigh, grm, standardize
from snp_heritability_estimation import greml, reml_loglik
def profile_reml(K, y, X, delta):
"""REML with sigma_g^2 profiled out, at V = sigma_g^2 (K + delta I), by a Cholesky factor."""
n, p = len(y), len(X[0])
V = [[K[i][j] + (delta if i == j else 0.0) for j in range(n)] for i in range(n)]
L = cholesky(V)
Vinv_X = [chol_solve(L, [X[i][a] for i in range(n)]) for a in range(p)]
Vinv_y = chol_solve(L, y)
A = [[sum(X[i][a] * Vinv_X[c][i] for i in range(n)) for c in range(p)] for a in range(p)]
rhs = [sum(X[i][a] * Vinv_y[i] for i in range(n)) for a in range(p)]
LA = cholesky(A)
beta = chol_solve(LA, rhs)
r = [y[i] - sum(X[i][a] * beta[a] for a in range(p)) for i in range(n)]
R = sum(a * b for a, b in zip(r, chol_solve(L, r)))
df = n - p
return 0.5 * (df * math.log(df / (2 * math.pi * R)) - df - chol_logdet(L) - chol_logdet(LA))
def simulate(rng, n, m, h2, pmin=0.1, pmax=0.9):
"""Unrelated people, m unlinked SNPs, y = W b + e with Var(W b) about h2 and Var(e) = 1 - h2."""
freqs = [pmin + (pmax - pmin) * rng.random() for _ in range(m)]
G = [[(rng.random() < f) + (rng.random() < f) for f in freqs] for _ in range(n)]
W = standardize(G)
b = [rng.gauss(0.0, math.sqrt(h2 / m)) for _ in range(m)]
y = [sum(w * e for w, e in zip(row, b)) + rng.gauss(0.0, math.sqrt(1.0 - h2)) for row in W]
return G, y
def test_balanced_one_way_layout_gives_the_anova_estimates():
# With A = blocks of ones (clones in g groups of size k) and an intercept, REML
# equals the ANOVA estimators: s_e = MSW and s_g = (MSB - MSW) / k when positive.
rng = random.Random(11)
g, k = 8, 4
y = []
for _ in range(g):
u = rng.gauss(0.0, 1.0)
y += [u + rng.gauss(0.0, 0.7) for _ in range(k)]
n = g * k
A = [[1.0 if i // k == j // k else 0.0 for j in range(n)] for i in range(n)]
X = [[1.0] for _ in range(n)]
fy = [Fraction(v) for v in y]
grand = sum(fy) / n
means = [sum(fy[a * k:(a + 1) * k]) / k for a in range(g)]
msb = k * sum((mu - grand) ** 2 for mu in means) / (g - 1)
msw = sum((fy[i] - means[i // k]) ** 2 for i in range(n)) / (n - g)
assert msb > msw
fit = greml([A], y, X)
sg, se = fit["theta"]
assert abs(se - float(msw)) < 1e-7
assert abs(sg - float((msb - msw) / k)) < 1e-7
def test_estimate_equals_the_maximum_of_the_profile_likelihood():
rng = random.Random(12)
n, m = 40, 80
G, y = simulate(rng, n, m, 0.5)
K = grm(G)
X = [[1.0] for _ in range(n)]
fit = greml([K], y, X)
sg, se = fit["theta"]
# The same likelihood, maximized over delta = s_e / s_g by a grid and golden-section search.
s_min = eigh(K)[0][0]
lo = math.log(max(-s_min, 0.0) + 1e-3)
grid = [lo + 0.05 * t for t in range(int((6.0 - lo) / 0.05) + 1)]
vals = [profile_reml(K, y, X, math.exp(t)) for t in grid]
j = max(range(len(grid)), key=lambda i: vals[i])
assert 0 < j < len(grid) - 1
a, b = grid[j - 1], grid[j + 1]
gr = (math.sqrt(5.0) - 1.0) / 2.0
for _ in range(60):
c, d = b - gr * (b - a), a + gr * (b - a)
if profile_reml(K, y, X, math.exp(c)) >= profile_reml(K, y, X, math.exp(d)):
b = d
else:
a = c
delta = math.exp((a + b) / 2)
best = profile_reml(K, y, X, delta)
assert abs(se / sg - delta) < 1e-5 * delta
assert abs(fit["h2"] - 1.0 / (1.0 + delta)) < 1e-5
# l_R at the estimate, with the constant -(n - p)/2 log(2 pi), equals the profile maximum.
assert abs(fit["loglik"] - 0.5 * (n - 1) * math.log(2 * math.pi) - best) < 1e-8
def test_two_components_give_a_stationary_point_and_a_local_maximum():
rng = random.Random(15)
n, m = 40, 120
G, y = simulate(rng, n, m, 0.5)
# Relationship matrices W W^T / m, positive semidefinite, from two halves of the SNPs.
As = []
for part in ([row[:m // 2] for row in G], [row[m // 2:] for row in G]):
W = standardize(part)
As.append([[sum(a * b for a, b in zip(wi, wj)) / len(wi) for wj in W] for wi in W])
X = [[1.0, float(i % 2)] for i in range(n)]
fit = greml(As, y, X)
th = fit["theta"]
assert all(v > 1e-3 for v in th)
f0 = reml_loglik(As, y, X, th)
for k in range(3):
h = 1e-4 * th[k]
up = list(th)
dn = list(th)
up[k] += h
dn[k] -= h
fu, fd = reml_loglik(As, y, X, up), reml_loglik(As, y, X, dn)
assert abs(fu - fd) / (2 * h) < 1e-5
assert fu <= f0 + 1e-12 and fd <= f0 + 1e-12
def test_simulated_heritability_within_four_standard_errors():
rng = random.Random(14)
n, m, h2 = 100, 50, 0.6
G, y = simulate(rng, n, m, h2)
fit = greml([grm(G)], y, [[1.0] for _ in range(n)])
z = 4.0
assert fit["se_h2"] < 0.2
assert abs(fit["h2"] - h2) <= z * fit["se_h2"]
def test_null_trait_estimate_within_four_standard_errors_of_zero():
rng = random.Random(15)
n, m = 100, 50
G, _ = simulate(rng, n, m, 0.5)
y = [rng.gauss(0.0, 1.0) for _ in range(n)]
fit = greml([grm(G)], y, [[1.0] for _ in range(n)])
z = 4.0
assert 0.0 <= fit["h2"] <= z * fit["se_h2"]
History
Before 2010, the genome-wide association studies of height had found SNPs that together explained only a few percent of its variance, although family studies put its heritability near 80%. Yang and coworkers (2010) asked how much all SNPs explain together and fitted a mixed model with a relationship matrix from 294,831 SNPs to 3,925 unrelated people. They found about 45%, which showed that much of the missing heritability is in many SNPs of small effect, not detected one by one. The GCTA software (Yang and coworkers 2011) made the method a standard tool. Its REML solver is the average information algorithm of Gilmour, Thompson and Cullis (1995), from animal breeding, where mixed models with pedigree relationship matrices had been fitted for decades.
References
- Jian Yang, Beben Benyamin, Brian P. McEvoy, Scott Gordon, Anjali K. Henders, Dale R. Nyholt, Pamela A. Madden, Andrew C. Heath, Nicholas G. Martin, Grant W. Montgomery, Michael E. Goddard and Peter M. Visscher, Common SNPs explain a large proportion of the heritability for human height, Nature Genetics 42(7), 2010, pp. 565-569 (the model with a SNP relationship matrix and the height estimate)
- Jian Yang, S. Hong Lee, Michael E. Goddard and Peter M. Visscher, GCTA, a tool for genome-wide complex trait analysis, American Journal of Human Genetics 88(1), 2011, pp. 76-82 (the genomic relationship matrix and the REML fit with the average information algorithm)
- Arthur R. Gilmour, Robin Thompson and Brian R. Cullis, Average information REML, an efficient algorithm for variance parameter estimation in linear mixed models, Biometrics 51(4), 1995, from p. 1440 (the average information matrix as the mean of the observed and expected information)
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 Q44QVJ Edit this page History Report an error Markdown