Algorithm Search⌘K

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
Properties
deterministicnot exactofflineiterative
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 uu whose covariance is proportional to a genetic relationship matrix KK, so that people who share more of their genome are allowed to have more similar traits. One eigendecomposition of KK 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 y∈Rny \in \mathbb R^n for nn individuals, a matrix XX of pp covariates (a column of ones and, for example, age and sex), a genetic relationship matrix KK of size n×nn \times n, and MM SNPs, each a dosage vector gj∈{0,1,2}ng_j \in \{0, 1, 2\}^n.

Model. For SNP jj,

y=Xβ+gjbj+u+e,u∼N(0,σg2K),e∼N(0,σe2I),y = X \beta + g_j b_j + u + e, \qquad u \sim N(0, \sigma_g^2 K), \qquad e \sim N(0, \sigma_e^2 I),

so Var⁡(y)=σg2(K+δI)\operatorname{Var}(y) = \sigma_g^2 (K + \delta I) with δ=σe2/σg2\delta = \sigma_e^2 / \sigma_g^2. This is a linear mixed model with one variance component besides the noise.

Output. For each SNP, the estimate b^j\hat b_j, its standard error and a test of bj=0b_j = 0.

KK 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

  1. MIXED-MODEL-SCAN(y, X, K, g_1, ..., g_M)
  2. 1K = U diag(s) U^T, an eigendecomposition
  3. 2ỹ ← U^T y, X̃ ← U^T X
  4. 3δ̂ ← the δ that maximizes the REML profile ℓ_R(δ), with weights 1/(s_i + δ) on the rotated rows
  5. 4σ̂_g² ← R(δ̂)/(n - p), σ̂_e² ← δ̂ σ̂_g²
  6. 5for j ← 1 to M do g̃ ← U^T g_j
  7. 6b̂_j, Var(b̂_j) ← weighted least squares of ỹ on [X̃, g̃] with weights 1/(σ̂_g² (s_i + δ̂))
  8. 7T_j ← b̂_j² / Var(b̂_j); p_j ← P(χ²_1 > T_j)
  9. 8return T, p

After the rotation of line L2, the covariance is diagonal: Var⁡(y~)=σg2diag⁡(s+δ)\operatorname{Var}(\tilde y) = \sigma_g^2 \operatorname{diag}(s + \delta). So each evaluation of the REML profile in line L3 is a weighted regression with nn rows and pp columns. The search is a grid of 100 points over log⁡δ∈[−10,10]\log \delta \in [-10, 10], 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 KK with 1 on the diagonal, 1/21/2 within each pair and 0 between the pairs. The trait is y=(1,3,2,6)y = (1, 3, 2, 6), the only covariate is the intercept, and the SNP is g=(0,1,1,2)g = (0, 1, 1, 2). Fix σg2=σe2=1\sigma_g^2 = \sigma_e^2 = 1, so δ=1\delta = 1.

  • The eigenvectors of KK are the sum and the difference within each pair, (1,1,0,0)/2(1, 1, 0, 0)/\sqrt2 with eigenvalue 3/23/2, (1,−1,0,0)/2(1, -1, 0, 0)/\sqrt2 with 1/21/2, and the same for the second pair. The weights are 1/(3/2+1)=0.41/(3/2 + 1) = 0.4 for the sums and 1/(1/2+1)=2/31/(1/2 + 1) = 2/3 for the differences.
  • Rotated, y~=(4,−2,8,−4)/2\tilde y = (4, -2, 8, -4)/\sqrt2, the intercept is (2,0,2,0)(\sqrt2, 0, \sqrt2, 0) and g~=(1,−1,3,−1)/2\tilde g = (1, -1, 3, -1)/\sqrt2.
  • The weighted cross products are ∑wx2=1.6\sum w x^2 = 1.6, ∑wxg=1.6\sum w x g = 1.6, ∑wg2=8/3\sum w g^2 = 8/3, ∑wxy=4.8\sum w x y = 4.8 and ∑wgy=7.6\sum w g y = 7.6. The determinant of the 2×22 \times 2 system is 1.6⋅8/3−1.62=128/751.6 \cdot 8/3 - 1.6^2 = 128/75.
  • So b^=1.6(7.6−4.8)/(128/75)=2.625\hat b = 1.6 (7.6 - 4.8) / (128/75) = 2.625, Var⁡(b^)=1.6/(128/75)=15/16\operatorname{Var}(\hat b) = 1.6 / (128/75) = 15/16, and T=2.6252/0.9375=7.35T = 2.625^2 / 0.9375 = 7.35, with p=0.0067p = 0.0067.

Ordinary least squares on the same data gives b^=2.5\hat b = 2.5. 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

UU is orthogonal, so (K+δI)−1=Udiag⁡(1/(s+δ))U⊤(K + \delta I)^{-1} = U \operatorname{diag}(1/(s + \delta)) U^\top and log⁡det⁡(K+δI)=∑ilog⁡(si+δ)\log\det(K + \delta I) = \sum_i \log(s_i + \delta). 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 σg2\sigma_g^2 in closed form leaves a function of δ\delta alone. In the same way, the weighted regression of line L6 gives exactly the generalized least squares estimate b^\hat b and its variance [(Z⊤V−1Z)−1]jj[(Z^\top V^{-1} Z)^{-1}]_{jj} on the original data. If VV were the true covariance, TT would be exactly chi-squared with 1 degree of freedom under the null. With VV 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 y∈Rny \in \mathbb R^n, let XX be an n×pn \times p matrix of full column rank with p<np < n, and let KK be a symmetric n×nn \times n matrix with the eigendecomposition K=Udiag⁡(s)U⊤K = U \operatorname{diag}(s) U^\top from line L1, where UU is orthogonal. For δ>−min⁡isi\delta > -\min_i s_i, put Hδ=K+δIH_\delta = K + \delta I, which is positive definite, with Hδ=Udiag⁡(s+δ)U⊤H_\delta = U \operatorname{diag}(s + \delta) U^\top. The model is y∼N(Xβ,σg2Hδ)y \sim N(X \beta, \sigma_g^2 H_\delta).

Lemma 1 (rotation). Let y~=U⊤y\tilde y = U^\top y and X~=U⊤X\tilde X = U^\top X (line L2), and Wδ=diag⁡(1/(si+δ))W_\delta = \operatorname{diag}(1/(s_i + \delta)). Then for all a,ba, b, a⊤Hδ−1b=(U⊤a)⊤Wδ(U⊤b)a^\top H_\delta^{-1} b = (U^\top a)^\top W_\delta (U^\top b), and log⁡det⁡Hδ=∑ilog⁡(si+δ)\log \det H_\delta = \sum_i \log(s_i + \delta).

Proof. Hδ−1=UWδU⊤H_\delta^{-1} = U W_\delta U^\top since UU is orthogonal, and the determinant of Udiag⁡(s+δ)U⊤U \operatorname{diag}(s + \delta) U^\top is the product of the si+δs_i + \delta. □\square

Lemma 2 (REML profile). The restricted log-likelihood of (σg2,δ)(\sigma_g^2, \delta), up to a constant that does not depend on them, is

ℓR(σg2,δ)=−12[(n−p)log⁡(2πσg2)+log⁡det⁡Hδ+log⁡det⁡(X⊤Hδ−1X)+R(δ)/σg2],\ell_R(\sigma_g^2, \delta) = -\tfrac12 \Bigl[(n - p) \log(2 \pi \sigma_g^2) + \log\det H_\delta + \log\det(X^\top H_\delta^{-1} X) + R(\delta) / \sigma_g^2\Bigr],

where R(δ)=(y−Xβ^δ)⊤Hδ−1(y−Xβ^δ)R(\delta) = (y - X \hat\beta_\delta)^\top H_\delta^{-1} (y - X \hat\beta_\delta) and β^δ\hat\beta_\delta is the generalized least squares estimate. For fixed δ\delta it is maximized at σ^g2=R(δ)/(n−p)\hat\sigma_g^2 = R(\delta)/(n - p), and the profile is

ℓR(δ)=12[(n−p)log⁡n−p2πR(δ)−(n−p)−∑ilog⁡(si+δ)−log⁡det⁡(X~⊤WδX~)],\ell_R(\delta) = \tfrac12 \Bigl[(n - p) \log \frac{n - p}{2 \pi R(\delta)} - (n - p) - \sum_i \log(s_i + \delta) - \log\det(\tilde X^\top W_\delta \tilde X)\Bigr],

which is the function of the code.

Proof. The first display is the standard REML likelihood of a linear model with covariance σg2Hδ\sigma_g^2 H_\delta, with the term 12log⁡det⁡X⊤X\tfrac12 \log\det X^\top X left out (Patterson and Thompson; see the page on restricted maximum likelihood). The derivative in σg2\sigma_g^2 is −12[(n−p)/σg2−R/σg4]-\tfrac12[(n - p)/\sigma_g^2 - R/\sigma_g^4], which is zero only at R/(n−p)R/(n - p), and the function goes to −∞-\infty at 00 and at ∞\infty, so this is the maximum. Substituting gives (n−p)log⁡(2πR/(n−p))+(n−p)(n-p) \log(2\pi R/(n-p)) + (n - p) in the bracket. By Lemma 1, log⁡det⁡Hδ=∑log⁡(si+δ)\log\det H_\delta = \sum \log(s_i + \delta), X⊤Hδ−1X=X~⊤WδX~X^\top H_\delta^{-1} X = \tilde X^\top W_\delta \tilde X, and β^δ\hat\beta_\delta and R(δ)R(\delta) are the weighted least squares estimate and weighted residual sum of squares of y~\tilde y on X~\tilde X with the weights WδW_\delta. □\square

So the search of line L3 maximizes the true REML profile, and line L4 returns the REML estimates of σg2\sigma_g^2 and σe2=δσg2\sigma_e^2 = \delta \sigma_g^2 at the δ\delta found. The search is a grid over log⁡δ\log \delta 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 ℓR\ell_R 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 gg, let Z=[X,g]Z = [X, g] and V=σ^g2Hδ^V = \hat\sigma_g^2 H_{\hat\delta}. Lines L5 to L7 return the generalized least squares estimate

b^=[(Z⊤V−1Z)−1Z⊤V−1y]p+1,Var⁡(b^)=[(Z⊤V−1Z)−1]p+1,p+1,\hat b = \bigl[(Z^\top V^{-1} Z)^{-1} Z^\top V^{-1} y\bigr]_{p+1}, \qquad \operatorname{Var}(\hat b) = \bigl[(Z^\top V^{-1} Z)^{-1}\bigr]_{p+1, p+1},

and T=b^2/Var⁡(b^)T = \hat b^2 / \operatorname{Var}(\hat b). If y∼N(Xβ,V)y \sim N(X \beta, V) with this VV, then TT follows the chi-squared law with 1 degree of freedom.

Proof. Line L5 computes g~=U⊤g\tilde g = U^\top g, so U⊤Z=[X~,g~]U^\top Z = [\tilde X, \tilde g]. By Lemma 1 with the weights 1/(σ^g2(si+δ^))1/(\hat\sigma_g^2 (s_i + \hat\delta)), Z⊤V−1ZZ^\top V^{-1} Z and Z⊤V−1yZ^\top V^{-1} y are the weighted cross products of the rotated data, which line L6 forms and solves. So the code returns the stated b^\hat b and variance. Under the model, b^\hat b is a linear function of the normal vector yy. Its mean is the coefficient of gg in the mean of yy, which is 00 under the null, and its variance is the stated one by the usual computation Var⁡(Ay)=AVA⊤\operatorname{Var}(A y) = A V A^\top with A=(Z⊤V−1Z)−1Z⊤V−1A = (Z^\top V^{-1} Z)^{-1} Z^\top V^{-1}. So b^/Var⁡(b^)\hat b / \sqrt{\operatorname{Var}(\hat b)} is standard normal and TT is chi-squared with 1 degree of freedom. □\square

What the theorem does not say. In practice VV is estimated, once, under the null and from the same data. Then TT 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 σg2\sigma_g^2 and σe2\sigma_e^2 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 O(np2)O(n p^2) per evaluation of ℓR\ell_R per SNP, after the same rotation.

Complexity

  • Time. The eigendecomposition costs Θ(n3)\Theta(n^3) once. Each evaluation of ℓR\ell_R costs O(np2)O(n p^2), and the search uses about 150 of them. Each SNP costs Θ(n2)\Theta(n^2) for the rotation U⊤gU^\top g and O(np2)O(n p^2) for the fit. With pp small, the total is Θ(n3+Mn2)\Theta(n^3 + M n^2).
  • Space. Θ(n2)\Theta(n^2) for UU. The genotypes are streamed one SNP at a time.
  • Re-estimating per SNP. Repeating line L3 for each SNP, the exact REML test, costs O(np2)O(n p^2) per evaluation and SNP, after rotating the SNP. It is affordable because of the rotation.
  • Low rank. If K=WW⊤/mK = W W^\top / m with m<nm < n SNPs, the thin singular value decomposition of WW costs O(nm2)O(n m^2), and each SNP costs O(nm)O(n m). This is the route of FaST-LMM (Lippert and coworkers 2011), linear in nn.

Properties

  • Controls structure and relatedness at once. Population structure, family structure and cryptic relatedness all show in KK, and the model does not need to know which is which.
  • Exact for known components. With the true σg2\sigma_g^2 and σe2\sigma_e^2 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 KK 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 δ\delta for every SNP. This is the original form of Kang and coworkers (2008), exact but slower.
  • Leave one chromosome out. Build KK from all chromosomes except the one of the tested SNP. Otherwise the SNP is in KK and partly explains itself, which lowers power (proximal contamination).
  • Low-rank and sparse relationship matrices. Build KK 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 KK 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 KK. The genomic relationship matrix with the usual diagonal can have small negative eigenvalues. K+δIK + \delta I is then positive definite only for δ\delta 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 KK, 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.

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

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

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