Algorithmadvanced
Mixed model association testing
Also called EMMAX, linear mixed model GWAS, LMM association test.
Tests each variant in a linear mixed model whose random effect has the genetic relationship matrix as covariance, to control for structure and relatedness.
- Time
- Θ(n^3 + M n^2) worst · average · best
- Space
- Θ(n^2) extra
- Where
- M = the number of tested SNPs; n = the number of individuals; p = the number of fixed covariates
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Hyun Min Kang, Noah A. Zaitlen, Eleazar Eskin, 2008
Mixed model association testing runs a genome-wide association study in a sample with population structure or relatives. It adds to the regression of the trait on each SNP a random effect whose covariance is proportional to a genetic relationship matrix , so that people who share more of their genome are allowed to have more similar traits. One eigendecomposition of makes the covariance diagonal, after which the variance components are found by a one-dimensional search, and each SNP costs one rotation and a small weighted least squares fit. It corrects structure and relatedness better than one constant factor or a few principal components.
In plain words
If a sample mixes groups of different ancestry, or contains relatives, people who are closely related tend to have similar traits and similar genotypes at many places. A plain test then finds links between the trait and many markers that have nothing to do with it. A mixed model first measures, from the genotypes, how related each pair of people is. It then lets the trait of related people be similar for that reason alone, and asks whether a marker adds anything beyond it. To keep a scan of millions of markers fast, the model fixes how much of the trait is explained by relatedness once, before the scan, and then tests the markers one by one with this fixed amount.
The problem
Input. A trait for individuals, a matrix of covariates (a column of ones and, for example, age and sex), a genetic relationship matrix of size , and SNPs, each a dosage vector .
Model. For SNP ,
so with . This is a linear mixed model with one variance component besides the noise.
Output. For each SNP, the estimate , its standard error and a test of .
is usually the genomic relationship matrix, the average over SNPs of products of standardized genotypes. It estimates twice the kinship coefficient of each pair, relative to the sample.
The algorithm
MIXED-MODEL-SCAN(y, X, K, g_1, ..., g_M)- 1
K = U diag(s) U^T, an eigendecomposition - 2
ỹ ← U^T y, X̃ ← U^T X - 3
δ̂ ← the δ that maximizes the REML profile ℓ_R(δ), with weights 1/(s_i + δ) on the rotated rows - 4
σ̂_g² ← R(δ̂)/(n - p), σ̂_e² ← δ̂ σ̂_g² - 5
for j ← 1 to M do g̃ ← U^T g_j - 6
b̂_j, Var(b̂_j) ← weighted least squares of ỹ on [X̃, g̃] with weights 1/(σ̂_g² (s_i + δ̂)) - 7
T_j ← b̂_j² / Var(b̂_j); p_j ← P(χ²_1 > T_j) - 8
return T, p
After the rotation of line L2, the covariance is diagonal: . So each evaluation of the REML profile in line L3 is a weighted regression with rows and columns. The search is a grid of 100 points over , then golden-section search around the best point. Line L7 is a Wald test with the variance components held fixed.
Example
Take two pairs of full sibs and the relationship matrix with 1 on the diagonal, within each pair and 0 between the pairs. The trait is , the only covariate is the intercept, and the SNP is . Fix , so .
- The eigenvectors of are the sum and the difference within each pair, with eigenvalue , with , and the same for the second pair. The weights are for the sums and for the differences.
- Rotated, , the intercept is and .
- The weighted cross products are , , , and . The determinant of the system is .
- So , , and , with .
Ordinary least squares on the same data gives . The mixed model gives more weight to the differences within pairs, where the SNP and the trait vary together beyond what the shared family background explains.
Correctness
is orthogonal, so and . Every quadratic form and determinant of the REML likelihood therefore has the same value in the rotated coordinates, where it is a weighted sum. Maximizing over in closed form leaves a function of alone. In the same way, the weighted regression of line L6 gives exactly the generalized least squares estimate and its variance on the original data. If were the true covariance, would be exactly chi-squared with 1 degree of freedom under the null. With estimated once under the null, it is a close approximation for SNPs of small effect. The full proof is below.
Proof: The rotated computations equal REML and generalized least squares on the original datafull
Let , let be an matrix of full column rank with , and let be a symmetric matrix with the eigendecomposition from line L1, where is orthogonal. For , put , which is positive definite, with . The model is .
Lemma 1 (rotation). Let and (line L2), and . Then for all , , and .
Proof. since is orthogonal, and the determinant of is the product of the .
Lemma 2 (REML profile). The restricted log-likelihood of , up to a constant that does not depend on them, is
where and is the generalized least squares estimate. For fixed it is maximized at , and the profile is
which is the function of the code.
Proof. The first display is the standard REML likelihood of a linear model with covariance , with the term left out (Patterson and Thompson; see the page on restricted maximum likelihood). The derivative in is , which is zero only at , and the function goes to at and at , so this is the maximum. Substituting gives in the bracket. By Lemma 1, , , and and are the weighted least squares estimate and weighted residual sum of squares of on with the weights .
So the search of line L3 maximizes the true REML profile, and line L4 returns the REML estimates of and at the found. The search is a grid over followed by golden-section search between the neighbours of the best grid point. Golden-section search keeps a bracket that contains the maximizer of a unimodal function and shrinks it by a constant factor at each step, so it returns the maximum when is unimodal between these neighbours. The returned value is never below the best grid value, because the code keeps the grid point when it is better.
Theorem (per-SNP test). For a SNP with dosage vector , let and . Lines L5 to L7 return the generalized least squares estimate
and . If with this , then follows the chi-squared law with 1 degree of freedom.
Proof. Line L5 computes , so . By Lemma 1 with the weights , and are the weighted cross products of the rotated data, which line L6 forms and solves. So the code returns the stated and variance. Under the model, is a linear function of the normal vector . Its mean is the coefficient of in the mean of , which is under the null, and its variance is the stated one by the usual computation with . So is standard normal and is chi-squared with 1 degree of freedom.
What the theorem does not say. In practice is estimated, once, under the null and from the same data. Then is only approximately chi-squared. The approximation is good when each SNP explains a small part of the variance, which is the setting of the method. For a SNP with a large effect, the null estimate of and absorbs part of its effect, and the test loses some power. Re-estimating the components for each SNP gives the exact REML test at a cost of per evaluation of per SNP, after the same rotation.
Complexity
- Time. The eigendecomposition costs once. Each evaluation of costs , and the search uses about 150 of them. Each SNP costs for the rotation and for the fit. With small, the total is .
- Space. for . The genotypes are streamed one SNP at a time.
- Re-estimating per SNP. Repeating line L3 for each SNP, the exact REML test, costs per evaluation and SNP, after rotating the SNP. It is affordable because of the rotation.
- Low rank. If with SNPs, the thin singular value decomposition of costs , and each SNP costs . This is the route of FaST-LMM (Lippert and coworkers 2011), linear in .
Properties
- Controls structure and relatedness at once. Population structure, family structure and cryptic relatedness all show in , and the model does not need to know which is which.
- Exact for known components. With the true and the test is exact under the model. Estimating them once loses a little power for SNPs of large effect.
- Same ranking as the exact test for small effects. Most SNPs explain a tiny part of the variance, so the null components are close to the per-SNP components.
- Not a fixed factor. Unlike genomic control, the correction depends on the SNP: a SNP whose frequency follows the structure of is corrected more.
- Gains power with polygenic traits. The random effect absorbs part of the background genetic variance, so the residual variance shrinks and the test of a real SNP gains power.
Variants and improvements
- Exact per-SNP REML. Re-estimate for every SNP. This is the original form of Kang and coworkers (2008), exact but slower.
- Leave one chromosome out. Build from all chromosomes except the one of the tested SNP. Otherwise the SNP is in and partly explains itself, which lowers power (proximal contamination).
- Low-rank and sparse relationship matrices. Build from a subset of SNPs, or keep only the entries of close relatives, to save time on large samples.
- Bayesian and mixture random effects. Methods with a mixture prior on SNP effects replace the single variance component and gain power for traits with a few large effects.
- Binary traits. The linear model on a 0/1 trait works for balanced designs but can be miscalibrated for unbalanced case-control ratios. Logistic mixed models with a saddle point approximation fix this.
When to use it
- Association studies in samples with relatives, such as founder populations, family cohorts or model organism strains.
- Large biobanks, where cryptic relatedness is common and PCA alone leaves inflation.
- Samples with complex structure, such as admixed populations or inbred lines.
- When genomic control or a few principal components do not bring the inflation of the null statistics down.
Pitfalls
- The SNP in its own matrix. If includes the tested SNP and its neighbours, the test loses power. Use the leave-one-chromosome-out matrix.
- Inflation under polygenicity. With many causal SNPs of small effect, even a correct mixed model scan has an inflation factor above 1, because the real signal is spread over many SNPs in linkage disequilibrium with the causal ones. Judge confounding by the intercept of LD score regression, not by the inflation factor alone.
- Non-positive-definite . The genomic relationship matrix with the usual diagonal can have small negative eigenvalues. is then positive definite only for above them, and the search must stay in that range.
- Variance ratio at the edge. If the REML maximum is at the edge of the search range, the trait shows no genetic variance in this sample, and the model reduces to ordinary least squares.
- Environment that follows ancestry. If an environmental factor is shared by relatives but not captured by , the model does not remove it.
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
# Shared helper of the biology pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Random variates, exact probability mass functions and test helpers for
the stochastic pages of the biology area.
Every sampler takes a random.Random object as its first argument and never
uses the module-level random functions. Each sampler draws its random
numbers in the order that its docstring gives, so two runs with the same
seed give the same output.
Conventions:
- A reaction network with n species and m reactions is given by `stoich`, a
list of the m change vectors nu_1, ..., nu_m. So stoich[j][i] is the entry
S[i][j] of the n by m stoichiometric matrix S.
- `propensity(x)` takes the state as a tuple of n integer counts and returns
the m propensities a_1(x), ..., a_m(x) as a sequence of floats >= 0.
- nbinom_pmf uses the mean mu and the dispersion alpha, with
Var = mu + alpha mu^2. The size is r = 1 / alpha; alpha = 0 is Poisson.
- hypergeom_pmf(k, total, good, draws) is the probability of k good items
in `draws` draws without replacement from `total` items of which `good`
are good.
Requires Python 3.12 or later (random.Random.binomialvariate).
"""
from __future__ import annotations
import math
from statistics import NormalDist
from typing import Callable, List, Sequence, Tuple
State = Tuple[int, ...]
_POISSON_PART = 30.0
# Random variates
def poisson(rng, lam: float) -> int:
"""A Poisson(lam) variate.
For lam <= 30, inversion of the cumulative distribution with one
rng.random() draw. For lam > 30, the sum of p = ceil(lam / 30)
independent Poisson(lam / p) variates, drawn one after the other by
inversion (one rng.random() draw each).
"""
if lam < 0 or math.isnan(lam):
raise ValueError("lam must be >= 0")
if lam == 0:
return 0
if lam > _POISSON_PART:
parts = math.ceil(lam / _POISSON_PART)
part = lam / parts
return sum(_poisson_inversion(rng, part) for _ in range(parts))
return _poisson_inversion(rng, lam)
def _poisson_inversion(rng, lam: float) -> int:
u = rng.random()
k = 0
p = math.exp(-lam)
cdf = p
while u >= cdf:
k += 1
p *= lam / k
if p == 0.0:
# Rounding left u above the computed total mass; stop at the tail.
break
cdf += p
return k
def binomial(rng, n: int, p: float) -> int:
"""A Binomial(n, p) variate by rng.binomialvariate (one call)."""
if n < 0 or not 0.0 <= p <= 1.0:
raise ValueError("need n >= 0 and 0 <= p <= 1")
if n == 0 or p == 0.0:
return 0
if p == 1.0:
return n
return rng.binomialvariate(n, p)
def multinomial(rng, n: int, probs: Sequence[float]) -> List[int]:
"""A Multinomial(n, probs) vector by conditional binomials.
probs are weights >= 0 with a positive sum; they need not sum to 1. Cell
i gets Binomial(rest of n, probs[i] / rest of the weight), for i in
order; the last cell with positive weight gets the rest.
"""
if n < 0:
raise ValueError("n must be >= 0")
w = [float(q) for q in probs]
if any(q < 0 for q in w):
raise ValueError("weights must be >= 0")
total = sum(w)
if total <= 0:
raise ValueError("weights must have a positive sum")
last = max(i for i, q in enumerate(w) if q > 0)
out = [0] * len(w)
left = n
rest = total
for i in range(last):
if left == 0:
break
if w[i] == 0:
continue
x = binomial(rng, left, min(1.0, w[i] / rest))
out[i] = x
left -= x
rest -= w[i]
out[last] += left
return out
def categorical(rng, weights: Sequence[float]) -> int:
"""An index i with probability weights[i] / sum(weights).
One draw u = rng.random() * sum(weights), then a cumulative search from
index 0. Indices with weight 0 are never returned.
"""
total = 0.0
for w in weights:
if w < 0:
raise ValueError("weights must be >= 0")
total += w
if total <= 0:
raise ValueError("weights must have a positive sum")
u = rng.random() * total
acc = 0.0
last = -1
for i, w in enumerate(weights):
if w > 0:
acc += w
last = i
if u < acc:
return i
return last
def ssa_direct(rng, x0: Sequence[int], stoich: Sequence[Sequence[int]],
propensity: Callable[[State], Sequence[float]], t_end: float,
max_events: int = 10 ** 6):
"""Gillespie's direct method from state x0 at time 0 up to time t_end.
Each step computes a = propensity(x) and a0 = sum(a). If a0 = 0 the run
stops. Otherwise it draws tau = rng.expovariate(a0) first. If
t + tau > t_end the run stops, and no second number is drawn. Else it
draws u = rng.random() * a0 and fires the first reaction j with
a_1 + ... + a_j > u (a linear search), then adds stoich[j] to x.
Returns (times, states, complete). times[0] = 0.0 and states[0] =
tuple(x0); entry k > 0 is the time and the state just after event k.
The state at t_end is states[-1]. complete is False only when the run
stopped because max_events events had fired before t_end.
"""
x = tuple(int(v) for v in x0)
times = [0.0]
states = [x]
t = 0.0
m = len(stoich)
for _ in range(max_events):
a = propensity(x)
a0 = 0.0
for v in a:
if v < 0:
raise ValueError("propensities must be >= 0")
a0 += v
if a0 <= 0.0:
return times, states, True
t += rng.expovariate(a0)
if t > t_end:
return times, states, True
u = rng.random() * a0
acc = 0.0
j = -1
for i in range(m):
if a[i] > 0:
acc += a[i]
j = i
if u < acc:
break
nu = stoich[j]
x = tuple(x[i] + nu[i] for i in range(len(x)))
times.append(t)
states.append(x)
return times, states, False
# Sample statistics and test helpers
def mean_var(xs) -> Tuple[float, float]:
"""The mean and the unbiased sample variance (divisor n - 1) by the
Welford method. The variance is 0.0 for fewer than two values."""
n = 0
mean = 0.0
m2 = 0.0
for x in xs:
n += 1
d = x - mean
mean += d / n
m2 += d * (x - mean)
if n == 0:
raise ValueError("empty sample")
return mean, (m2 / (n - 1) if n > 1 else 0.0)
def check_mean(m: float, mu: float, var: float, n: int, z: float = 4.0) -> bool:
"""True when |m - mu| <= z sqrt(var / n): a sample mean m of n
independent values with exact mean mu and exact variance var."""
return abs(m - mu) <= z * math.sqrt(var / n)
# Exact probability mass functions
def log_choose(n: int, k: int) -> float:
"""ln C(n, k), or -inf when k < 0 or k > n."""
if k < 0 or k > n:
return -math.inf
return math.lgamma(n + 1) - math.lgamma(k + 1) - math.lgamma(n - k + 1)
def binom_pmf(k: int, n: int, p: float) -> float:
"""P(K = k) for K ~ Binomial(n, p)."""
if k < 0 or k > n:
return 0.0
if p == 0.0:
return 1.0 if k == 0 else 0.0
if p == 1.0:
return 1.0 if k == n else 0.0
return math.exp(log_choose(n, k) + k * math.log(p) + (n - k) * math.log1p(-p))
def poisson_pmf(k: int, lam: float) -> float:
"""P(K = k) for K ~ Poisson(lam)."""
if k < 0:
return 0.0
if lam == 0:
return 1.0 if k == 0 else 0.0
return math.exp(k * math.log(lam) - lam - math.lgamma(k + 1))
def nbinom_pmf(k: int, mu: float, alpha: float) -> float:
"""P(K = k) for the negative binomial with mean mu and Var = mu + alpha mu^2."""
if k < 0:
return 0.0
if alpha == 0:
return poisson_pmf(k, mu)
if mu == 0:
return 1.0 if k == 0 else 0.0
r = 1.0 / alpha
return math.exp(math.lgamma(k + r) - math.lgamma(r) - math.lgamma(k + 1)
+ r * math.log(r / (r + mu)) + k * math.log(mu / (r + mu)))
def hypergeom_pmf(k: int, total: int, good: int, draws: int) -> float:
"""P(K = k) for k good items in `draws` draws without replacement from
`total` items of which `good` are good."""
if k < 0 or k > good or draws - k < 0 or draws - k > total - good:
return 0.0
return math.exp(log_choose(good, k) + log_choose(total - good, draws - k)
- log_choose(total, draws))
def logsumexp(xs) -> float:
"""ln(sum of exp(x)) without overflow; -inf for an empty input."""
xs = list(xs)
if not xs:
return -math.inf
top = max(xs)
if top == -math.inf:
return -math.inf
if top == math.inf:
return math.inf
return top + math.log(sum(math.exp(x - top) for x in xs))
# Tail probabilities
def _gamma_q(a: float, x: float) -> float:
"""The regularized upper incomplete gamma function Q(a, x)."""
if a <= 0:
raise ValueError("a must be > 0")
if x <= 0:
return 1.0
log_front = -x + a * math.log(x) - math.lgamma(a)
if x < a + 1.0:
# Series for P(a, x).
ap = a
term = 1.0 / a
total = term
for _ in range(100000):
ap += 1.0
term *= x / ap
total += term
if abs(term) < abs(total) * 1e-16:
break
return max(0.0, 1.0 - total * math.exp(log_front))
# Continued fraction for Q(a, x), by the modified Lentz method.
tiny = 1e-300
b = x + 1.0 - a
c = 1.0 / tiny
d = 1.0 / b
h = d
for i in range(1, 100000):
an = -i * (i - a)
b += 2.0
d = an * d + b
if abs(d) < tiny:
d = tiny
c = b + an / c
if abs(c) < tiny:
c = tiny
d = 1.0 / d
delta = d * c
h *= delta
if abs(delta - 1.0) < 1e-16:
break
return math.exp(log_front) * h
def chi2_sf(x: float, df: float) -> float:
"""P(X > x) for X chi-squared with df degrees of freedom."""
if df <= 0:
raise ValueError("df must be > 0")
if x <= 0:
return 1.0
return _gamma_q(df / 2.0, x / 2.0)
_STD_NORMAL = NormalDist()
def normal_sf(x: float, mu: float = 0.0, sigma: float = 1.0) -> float:
"""P(X > x) for X ~ Normal(mu, sigma^2), by statistics.NormalDist."""
return _STD_NORMAL.cdf(-(x - mu) / sigma)
mixed_model_association.py 167 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mixed-model-association/. The authors are listed in prov/HRTZ5C.jsonl.
"""Mixed model association: variance components once under the null, then
generalized least squares for each SNP.
The model for n individuals is
y = X beta + g_j b_j + u + e, u ~ N(0, sigma_g^2 K), e ~ N(0, sigma_e^2 I),
where X holds p fixed covariates (a column of ones first), g_j is the
dosage vector of the tested SNP and K is a genetic relationship matrix. So
Var(y) = sigma_g^2 (K + delta I) with delta = sigma_e^2 / sigma_g^2.
The variance components are estimated once, under the null model without
any SNP, by REML. With the eigendecomposition K = U diag(s) U^T, the rotated
data U^T y have the diagonal covariance sigma_g^2 diag(s + delta), so each
evaluation of the REML likelihood for a given delta costs O(n p^2). The
search over log(delta) is a grid followed by golden-section refinement, as
in EMMA (Kang et al. 2008). Each SNP is then tested by weighted least squares
on the rotated data with these components held fixed (Kang et al. 2010).
"""
from __future__ import annotations
import math
from typing import List, Sequence, Tuple
from biostoch import chi2_sf
from pg4lmm import eigh, inverse_small, solve_small, tmatvec
LOG_DELTA_RANGE = (-10.0, 10.0)
GRID_POINTS = 100
def weighted_ls(Z: Sequence[Sequence[float]], y: Sequence[float], w: Sequence[float]):
"""Weighted least squares: (coef, (Z^T W Z)^-1, residual sum sum w r^2)."""
q = len(Z[0])
A = [[0.0] * q for _ in range(q)]
b = [0.0] * q
for zi, yi, wi in zip(Z, y, w):
for a in range(q):
wz = wi * zi[a]
b[a] += wz * yi
Aa = A[a]
for c in range(a, q):
Aa[c] += wz * zi[c]
for a in range(q):
for c in range(a):
A[a][c] = A[c][a]
coef = solve_small(A, b)
rss = 0.0
for zi, yi, wi in zip(Z, y, w):
r = yi - sum(zi[a] * coef[a] for a in range(q))
rss += wi * r * r
return coef, inverse_small(A), rss
def logdet_small(A: Sequence[Sequence[float]]) -> float:
"""log det of a small symmetric positive definite matrix."""
n = len(A)
M = [list(r) for r in A]
s = 0.0
for c in range(n):
piv = M[c][c]
if piv <= 0:
raise ValueError("matrix is not positive definite")
s += math.log(piv)
for r in range(c + 1, n):
f = M[r][c] / piv
for k in range(c, n):
M[r][k] -= f * M[c][k]
return s
def reml_profile(s: Sequence[float], yt: Sequence[float], Xt, delta: float) -> float:
"""The REML log-likelihood at delta with sigma_g^2 profiled out.
In rotated coordinates the covariance is sigma_g^2 diag(s + delta), and
l_R(delta) = 1/2 [ (n - p) log((n - p) / (2 pi R)) - (n - p)
- sum log(s_i + delta) - log det(Xt^T W Xt) ],
with W = diag(1 / (s_i + delta)) and R the weighted residual sum of
squares of the regression of yt on Xt. The constant log det(X^T X) of
the REML likelihood is left out.
"""
n, p = len(yt), len(Xt[0])
w = [1.0 / (si + delta) for si in s]
_, inv, R = weighted_ls(Xt, yt, w)
A = [[sum(Xt[i][a] * w[i] * Xt[i][c] for i in range(n)) for c in range(p)] for a in range(p)]
df = n - p
return 0.5 * (df * math.log(df / (2.0 * math.pi * R)) - df
- sum(math.log(si + delta) for si in s) - logdet_small(A))
def _golden(f, a: float, b: float, tol: float = 1e-10) -> float:
"""The maximizer of a unimodal f on [a, b] by golden-section search."""
g = (math.sqrt(5.0) - 1.0) / 2.0
c, d = b - g * (b - a), a + g * (b - a)
fc, fd = f(c), f(d)
while b - a > tol:
if fc >= fd:
b, d, fd = d, c, fc
c = b - g * (b - a)
fc = f(c)
else:
a, c, fc = c, d, fd
d = a + g * (b - a)
fd = f(d)
return (a + b) / 2.0
def fit_null(K, y: Sequence[float], X):
"""REML fit of the null model y = X beta + u + e.
Returns a dict with delta, sigma_g2, sigma_e2, the eigenvalues s, the
eigenvectors U (as columns), and the rotated yt and Xt.
"""
n, p = len(y), len(X[0])
if n <= p:
raise ValueError("need more individuals than covariates")
s, U = eigh(K) # @line L1
yt = tmatvec(U, y) # @line L2
Xt_cols = [tmatvec(U, [X[i][a] for i in range(n)]) for a in range(p)]
Xt = [[Xt_cols[a][i] for a in range(p)] for i in range(n)]
def f(t):
return reml_profile(s, yt, Xt, math.exp(t))
lo, hi = LOG_DELTA_RANGE
if s[0] < 0.0:
# The GRM of GCTA need not be positive semidefinite; keep K + delta I
# positive definite.
lo = max(lo, math.log(-s[0]) + 1e-6)
step = (hi - lo) / (GRID_POINTS - 1)
grid = [lo + k * step for k in range(GRID_POINTS)]
vals = [f(t) for t in grid]
k = max(range(GRID_POINTS), key=lambda i: vals[i])
a, b = grid[max(k - 1, 0)], grid[min(k + 1, GRID_POINTS - 1)]
t_best = _golden(f, a, b)
if vals[k] > f(t_best):
t_best = grid[k]
delta = math.exp(t_best) # @line L3
w = [1.0 / (si + delta) for si in s]
_, _, R = weighted_ls(Xt, yt, w)
sigma_g2 = R / (n - p) # @line L4
return {"delta": delta, "sigma_g2": sigma_g2, "sigma_e2": delta * sigma_g2,
"s": s, "U": U, "yt": yt, "Xt": Xt, "reml": f(t_best)}
def scan(fit, snps: Sequence[Sequence[float]]) -> List[Tuple[float, float, float, float]]:
"""Test each SNP (a dosage vector of length n) with the null components fixed.
Returns (b, se, T, p) per SNP: the GLS effect, its standard error, the
Wald statistic T = b^2 / se^2 and its chi-squared (1 df) p-value.
"""
s, U, yt, Xt = fit["s"], fit["U"], fit["yt"], fit["Xt"]
delta, sg2 = fit["delta"], fit["sigma_g2"]
w = [1.0 / (sg2 * (si + delta)) for si in s]
out = []
for g in snps:
gt = tmatvec(U, g) # @line L5
Z = [row + [gt[i]] for i, row in enumerate(Xt)]
coef, inv, _ = weighted_ls(Z, yt, w) # @line L6
b = coef[-1]
var = inv[-1][-1]
T = b * b / var # @line L7
out.append((b, math.sqrt(var), T, chi2_sf(T, 1)))
return out # @line L8
pg4lmm.py 362 lines
# 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
test_mixed_model_association.py 160 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mixed-model-association/. The authors are listed in prov/HRTZ5C.jsonl.
import math
import random
from statistics import NormalDist
from mixed_model_association import fit_null, reml_profile, scan, weighted_ls
from pg4lmm import (
chol_inverse,
chol_logdet,
chol_solve,
cholesky,
eigh,
grm,
matmul,
simulate_two_populations,
transpose,
)
MEDIAN = NormalDist().inv_cdf(0.75) ** 2
def lambda_sd(m):
x = MEDIAN
dens = math.exp(-x / 2) / math.sqrt(2 * math.pi * x)
return 1.0 / (2 * dens * math.sqrt(m)) / x
def direct_reml(K, y, X, delta):
"""REML profile likelihood from V = 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)]
Vr = chol_solve(L, r)
R = sum(a * b for a, b in zip(r, Vr))
df = n - p
return 0.5 * (df * math.log(df / (2 * math.pi * R)) - df - chol_logdet(L) - chol_logdet(LA))
def direct_gls(K, y, X, g, sg2, se2):
"""GLS of y on [X, g] with V = sg2 K + se2 I, by a dense inverse."""
n = len(y)
V = [[sg2 * K[i][j] + (se2 if i == j else 0.0) for j in range(n)] for i in range(n)]
Vi = chol_inverse(cholesky(V))
Z = [X[i] + [g[i]] for i in range(n)]
Zt = transpose(Z)
A = matmul(matmul(Zt, Vi), Z)
LA = cholesky(A)
rhs = [sum(Zt[a][i] * sum(Vi[i][k] * y[k] for k in range(n)) for i in range(n)) for a in range(len(Zt))]
coef = chol_solve(LA, rhs)
Ainv = chol_inverse(LA)
return coef[-1], Ainv[-1][-1]
def small_data(rng, n=30, m=60):
G, pop = simulate_two_populations(rng, n // 2, n - n // 2, m, 0.1)
K = grm(G)
X = [[1.0, rng.gauss(0, 1)] for _ in range(n)]
y = [0.5 * pop[i] + 0.3 * X[i][1] + rng.gauss(0, 1) for i in range(n)]
return G, K, X, y
def test_eigh_reconstructs_matrix():
rng = random.Random(1)
n = 12
B = [[rng.gauss(0, 1) for _ in range(n)] for _ in range(n)]
A = [[(B[i][j] + B[j][i]) / 2 for j in range(n)] for i in range(n)]
d, V = eigh(A)
assert all(d[k] <= d[k + 1] for k in range(n - 1))
for i in range(n):
for j in range(n):
a = sum(V[i][k] * d[k] * V[j][k] for k in range(n))
o = sum(V[k][i] * V[k][j] for k in range(n))
assert abs(a - A[i][j]) < 1e-10
assert abs(o - (1.0 if i == j else 0.0)) < 1e-10
def test_spectral_reml_equals_direct_reml():
rng = random.Random(2)
G, K, X, y = small_data(rng)
fit = fit_null(K, y, X)
for delta in (0.05, 0.3, 1.0, 4.0, 30.0):
a = reml_profile(fit["s"], fit["yt"], fit["Xt"], delta)
b = direct_reml(K, y, X, delta)
assert abs(a - b) < 1e-8
def test_reml_maximum_beats_a_fine_grid():
rng = random.Random(3)
G, K, X, y = small_data(rng)
fit = fit_null(K, y, X)
# The GRM has a slightly negative eigenvalue (about -0.03), so K + delta I
# is positive definite only for delta above it.
lo = math.log(-min(fit["s"]) + 1e-3)
best = max(direct_reml(K, y, X, math.exp(lo + 0.01 * k)) for k in range(1201))
assert fit["reml"] >= best - 1e-9
assert abs(direct_reml(K, y, X, fit["delta"]) - fit["reml"]) < 1e-8
def test_scan_equals_dense_gls():
rng = random.Random(4)
G, K, X, y = small_data(rng)
fit = fit_null(K, y, X)
snps = [[float(G[i][j]) for i in range(len(G))] for j in range(5)]
res = scan(fit, snps)
for g, (b, se, T, p) in zip(snps, res):
b2, v2 = direct_gls(K, y, X, g, fit["sigma_g2"], fit["sigma_e2"])
assert abs(b - b2) < 1e-8 * max(1.0, abs(b2))
assert abs(se * se - v2) < 1e-8 * v2
assert abs(T - b2 * b2 / v2) < 1e-6 * max(1.0, T)
def test_identity_kinship_gives_weighted_ols():
# With K = I the model is ordinary least squares with variance sg2 + se2.
rng = random.Random(6)
n = 25
K = [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]
X = [[1.0] for _ in range(n)]
y = [rng.gauss(2.0, 1.5) for _ in range(n)]
fit = fit_null(K, y, X)
g = [float(rng.randint(0, 2)) for _ in range(n)]
(b, se, T, p), = scan(fit, [g])
coef, inv, rss = weighted_ls([[1.0, gi] for gi in g], y, [1.0] * n)
total = fit["sigma_g2"] + fit["sigma_e2"]
assert abs(b - coef[1]) < 1e-9
assert abs(se * se - total * inv[1][1]) < 1e-9
def ols_wald(y, X, g):
n = len(y)
Z = [X[i] + [g[i]] for i in range(n)]
coef, inv, rss = weighted_ls(Z, y, [1.0] * n)
s2 = rss / (n - len(Z[0]))
return coef[-1] ** 2 / (s2 * inv[-1][-1])
def test_structured_sample_ols_inflated_mixed_model_calibrated():
rng = random.Random(8)
n, m, m_test = 100, 400, 400
G, pop = simulate_two_populations(rng, 50, 50, m + m_test, 0.1)
K = grm([row[:m] for row in G])
X = [[1.0] for _ in range(n)]
# The trait differs between the populations; no tested SNP has an effect.
y = [1.5 * pop[i] + rng.gauss(0, 1) for i in range(n)]
snps = [[float(G[i][j]) for i in range(n)] for j in range(m, m + m_test)]
ols = sorted(ols_wald(y, X, g) for g in snps)
lam_ols = (ols[m_test // 2 - 1] + ols[m_test // 2]) / 2 / MEDIAN
fit = fit_null(K, y, X)
T = sorted(r[2] for r in scan(fit, snps))
lam_mm = (T[m_test // 2 - 1] + T[m_test // 2]) / 2 / MEDIAN
assert lam_ols > 1.0 + 4 * lambda_sd(m_test)
assert abs(lam_mm - 1.0) <= 4 * lambda_sd(m_test)
History
Yu and coworkers (2006) used a mixed model with a kinship matrix to map traits in maize and other plants, where structure and relatedness are strong. The REML fit for each marker was slow. Kang and coworkers (2008) rotated the data by the eigenvectors of the kinship matrix, so that each likelihood evaluation became a weighted sum. Kang and coworkers (2010) then estimated the variance components once under the null, which made a genome-wide scan in humans cost little more than a regression. Lippert and coworkers (2011) used a low-rank relationship matrix to make the cost linear in the sample size. Later methods for biobanks with hundreds of thousands of people use iterative solvers instead of an eigendecomposition.
References
- Hyun Min Kang, Noah A. Zaitlen, Claire M. Wade, Andrew Kirby, David Heckerman, Mark J. Daly and Eleazar Eskin, Efficient control of population structure in model organism association mapping, Genetics 178(3), 2008, pp. 1709-1723 (the spectral form of the ML and REML likelihoods in the variance ratio, and the grid and Newton search)
- Hyun Min Kang, Jae Hoon Sul, Susan K. Service, Noah A. Zaitlen, Sit-yee Kong, Nelson B. Freimer, Chiara Sabatti and Eleazar Eskin, Variance component model to account for sample structure in genome-wide association studies, Nature Genetics 42(4), 2010, pp. 348-354 (variance components estimated once under the null, then generalized least squares for each marker)
- Christoph Lippert, Jennifer Listgarten, Ying Liu, Carl M. Kadie, Robert I. Davidson and David Heckerman, FaST linear mixed models for genome-wide association studies, Nature Methods 8(10), 2011, pp. 833-835 (the spectral rotation with a low-rank relationship matrix, linear in the number of individuals)
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 HRTZ5C Edit this page History Report an error Markdown