Algorithm Search⌘K

Algorithmcore

Genomic control

Also called genomic inflation factor correction, lambda GC correction.

Divides the association statistics of a scan by the inflation factor lambda, the median observed chi-squared over its null median 0.4549, to correct for stratification.

Time
Θ(M N + M log M) worst · average · best
Space
Θ(M) extra
Where
M = the number of SNPs; N = the number of individuals
Properties
deterministicexactofflineiterative
Origin
Bernie Devlin, Kathryn Roeder, 1999

Genomic control corrects the test statistics of a genome-wide association study for population stratification and cryptic relatedness. These effects make the null statistics larger than a chi-squared law with 1 degree of freedom predicts, roughly by one common factor λ\lambda. Genomic control estimates λ\lambda as the median of all MM statistics divided by 0.454936, the median of that chi-squared law, and divides every statistic by λ^\hat\lambda. It uses only the statistics, so it costs nothing beyond the scan.

In plain words

In a scan of a million genetic markers, almost all markers have nothing to do with the disease. Their test results should look like pure chance. If cases and controls come from groups of different ancestry, many markers look a little linked to the disease only because their frequency differs between the groups. Then the whole set of results is shifted upward. Genomic control compares the middle result of the scan with the middle result that pure chance gives. If the middle result is 30 percent too large, it shrinks every result by 30 percent. The middle is used because a few real hits at the top do not move it.

The problem

Input. Genotypes of NN individuals at MM SNPs, as dosages xij∈{0,1,2}x_{ij} \in \{0, 1, 2\}, and case status yi∈{0,1}y_i \in \{0, 1\}. Or directly a list of MM statistics that are chi-squared with 1 degree of freedom under the null.

Model. For a null SNP, the statistic is Tj=λZjT_j = \lambda Z_j, with ZjZ_j chi-squared with 1 degree of freedom and the same λ≥1\lambda \ge 1 for all SNPs (Devlin and Roeder 1999). Most SNPs are null.

Output. The estimate λ^\hat\lambda, the corrected statistics Tj/λ^T_j / \hat\lambda and their p-values.

For a case-control study, the statistic is the Cochran-Armitage trend test, which equals Nrj2N r_j^2, where rjr_j is the correlation of the dosage at SNP jj with the case status. It is the score test of a logistic or linear regression of status on dosage, and it does not assume Hardy-Weinberg proportions, unlike the allele-count chi-squared test.

The algorithm

  1. GENOMIC-CONTROL(x, y)
  2. 1for j ← 1 to M do T_j ← N r_j^2, the trend statistic of SNP j
  3. 2m ← median of T_1, ..., T_M
  4. 3λ ← max(1, m / 0.454936)
  5. 4for j ← 1 to M do T_j ← T_j / λ
  6. 5p_j ← P(χ²_1 > T_j)
  7. 6return λ, T, p

Line L1 needs five integer sums per SNP: N(NSxy−SxSy)2/((NSxx−Sx2)(NSy−Sy2))N (N S_{xy} - S_x S_y)^2 / ((N S_{xx} - S_x^2)(N S_y - S_y^2)). The median of line L2 can come from a sort or from quickselect. The floor at 1 in line L3 keeps a scan with less spread than chance from being made larger.

Example

One SNP. Take 100 cases with dosages 0, 1, 2 in the counts 20, 50, 30, and 100 controls with the counts 35, 45, 20. So N=200N = 200, Sx=195S_x = 195, Sxx=295S_{xx} = 295, Sy=100S_y = 100 and Sxy=110S_{xy} = 110. Then NSxy−SxSy=2500N S_{xy} - S_x S_y = 2500, NSxx−Sx2=20975N S_{xx} - S_x^2 = 20975 and NSy−Sy2=10000N S_y - S_y^2 = 10000, so

T=200⋅2500220975⋅10000=5000839=5.9595,T = \frac{200 \cdot 2500^2}{20975 \cdot 10000} = \frac{5000}{839} = 5.9595,

with a p-value of 0.0146.

A small scan. Take five statistics 0.10,0.30,0.62,0.95,2.400.10, 0.30, 0.62, 0.95, 2.40. The median is 0.620.62, so λ^=0.62/0.454936=1.3628\hat\lambda = 0.62 / 0.454936 = 1.3628. The corrected statistics are 0.0734,0.2201,0.4549,0.6971,1.76100.0734, 0.2201, 0.4549, 0.6971, 1.7610. The largest one had the p-value 0.121 and now has 0.184. A real scan has far more SNPs; five values only show the arithmetic.

Correctness

Line L1 is right because the Armitage statistic on the 2×32 \times 3 table, with the scores 0, 1, 2, reduces to Nr2N r^2 when the cell counts are written as sums over individuals. Under the model, the median of λZ\lambda Z is λ⋅0.454936\lambda \cdot 0.454936, because 0.454936=Φ−1(3/4)20.454936 = \Phi^{-1}(3/4)^2 is the median of the chi-squared law with 1 degree of freedom. The sample median of many SNPs converges to this value, so λ^→λ\hat\lambda \to \lambda, and by Slutsky's theorem the corrected statistics are chi-squared with 1 degree of freedom in the limit. The median, unlike the mean, changes little when a small share of the SNPs have real effects. The full proof is below.

Proof: The trend statistic is N r squared, and genomic control is consistent under a constant inflationfull

There are two claims. The first is an identity for the statistic of line L1. The second says what the estimate of line L3 does under the model of Devlin and Roeder (1999).

Lemma 1. Let NN individuals have dosages xi∈{0,1,2}x_i \in \{0, 1, 2\} and status yi∈{0,1}y_i \in \{0, 1\}, with RR cases and S=N−RS = N - R controls, both positive, and with the xix_i not all equal. Let rkr_k and sks_k be the numbers of cases and controls with dosage kk, and nk=rk+skn_k = r_k + s_k. Then the Cochran-Armitage trend statistic with the scores 0,1,20, 1, 2,

T=N[∑kk(Srk−Rsk)]2RS[N∑kk2nk−(∑kknk)2],T = \frac{N \bigl[\sum_k k (S r_k - R s_k)\bigr]^2}{R S \bigl[N \sum_k k^2 n_k - (\sum_k k n_k)^2\bigr]},

equals Nr2N r^2, where rr is the Pearson correlation of xx and yy, and also

Nr2=N(NSxy−SxSy)2(NSxx−Sx2)(NSy−Sy2),N r^2 = \frac{N (N S_{xy} - S_x S_y)^2}{(N S_{xx} - S_x^2)(N S_y - S_y^2)},

with Sx=∑xiS_x = \sum x_i, Sxx=∑xi2S_{xx} = \sum x_i^2, Sy=∑yi=RS_y = \sum y_i = R and Sxy=∑xiyiS_{xy} = \sum x_i y_i.

Proof. The second form is the definition of r2r^2, multiplied by NN, with numerator and denominator of rr both multiplied by NN. Now ∑kkrk=Sxy\sum_k k r_k = S_{xy} and ∑kksk=Sx−Sxy\sum_k k s_k = S_x - S_{xy}, so

∑kk(Srk−Rsk)=SSxy−R(Sx−Sxy)=NSxy−RSx=NSxy−SxSy.\sum_k k (S r_k - R s_k) = S S_{xy} - R (S_x - S_{xy}) = N S_{xy} - R S_x = N S_{xy} - S_x S_y.

Also ∑kknk=Sx\sum_k k n_k = S_x, ∑kk2nk=Sxx\sum_k k^2 n_k = S_{xx}, and RS=R(N−R)=NSy−Sy2R S = R (N - R) = N S_y - S_y^2 since yi2=yiy_i^2 = y_i. Putting these into TT gives the second form. □\square

So line L1 computes the trend test from five integer sums in one pass over the NN individuals.

The model. Devlin and Roeder model a null SNP jj in a structured or cryptically related sample as Tj=λZjT_j = \lambda Z_j, where ZjZ_j follows the chi-squared law with 1 degree of freedom and λ≥1\lambda \ge 1 is the same for all SNPs. Assume that Z1,…,ZMZ_1, \ldots, Z_M are identically distributed, and that the sample median of T1,…,TMT_1, \ldots, T_M converges in probability to the population median as M→∞M \to \infty (for example, the SNPs are independent or weakly dependent, as unlinked SNPs are).

Lemma 2. The chi-squared law with 1 degree of freedom has the median μ=Φ−1(3/4)2=0.454936…\mu = \Phi^{-1}(3/4)^2 = 0.454936\ldots, where Φ\Phi is the standard normal distribution function.

Proof. If Z=U2Z = U^2 with UU standard normal, then Pr⁡(Z≤x)=Pr⁡(∣U∣≤x)=2Φ(x)−1\Pr(Z \le x) = \Pr(|U| \le \sqrt x) = 2 \Phi(\sqrt x) - 1. This equals 1/21/2 when Φ(x)=3/4\Phi(\sqrt x) = 3/4. □\square

Theorem. Under the model, λ^=max⁡(1,median⁡(T)/μ)\hat\lambda = \max(1, \operatorname{median}(T) / \mu) from line L3 converges in probability to λ\lambda, and for each fixed jj the corrected statistic Tj/λ^T_j / \hat\lambda of line L4 converges in law to the chi-squared law with 1 degree of freedom. So the p-values of line L5 are asymptotically uniform under the null.

Proof. The law of Tj=λZjT_j = \lambda Z_j has the median λμ\lambda \mu, because scaling by λ>0\lambda > 0 keeps the order. Its distribution function is continuous and strictly increasing near λμ\lambda\mu, so the population median is unique and, by assumption, the sample median converges in probability to λμ\lambda \mu. Dividing by the constant μ\mu gives median⁡(T)/μ→λ\operatorname{median}(T)/\mu \to \lambda. The map t↦max⁡(1,t)t \mapsto \max(1, t) is continuous and equals tt at t=λ≥1t = \lambda \ge 1, so λ^→λ\hat\lambda \to \lambda in probability by the continuous mapping theorem. Then Tj/λ^=Zj⋅(λ/λ^)T_j / \hat\lambda = Z_j \cdot (\lambda / \hat\lambda), and λ/λ^→1\lambda / \hat\lambda \to 1 in probability, so by Slutsky's theorem Tj/λ^T_j / \hat\lambda converges in law to ZjZ_j. If ZZ is chi-squared with 1 degree of freedom, Pr⁡(chi2_sf(Z)≤α)=α\Pr(\text{chi2\_sf}(Z) \le \alpha) = \alpha, which gives the last claim. □\square

Remark. The theorem needs the model. If some SNPs have real effects, the median moves only a little as long as these SNPs are a small fraction of all SNPs, because the median ignores the size of the large values. If the inflation differs between SNPs, for example because it grows with the difference in allele frequency between populations, then one constant cannot correct every SNP. If many SNPs each have a small real effect, the median grows with NN and genomic control removes real signal. These are the limits listed on the page.

Complexity

  • Time. Line L1 is one pass over the NMN M genotypes. The median costs Θ(Mlog⁡M)\Theta(M \log M) by sorting or Θ(M)\Theta(M) by selection. The rest is Θ(M)\Theta(M).
  • Space. Θ(M)\Theta(M) for the statistics. The genotypes can be streamed one SNP at a time.
  • From summary statistics. If only the MM statistics or p-values are given, the method costs Θ(M)\Theta(M) with selection and needs no genotypes. This is why it is easy to use in a meta-analysis.

Properties

  • One factor for all SNPs. Every statistic is divided by the same λ^\hat\lambda, so the ranking of SNPs does not change.
  • Robust to a few hits. The median ignores the size of the largest values. A small fraction of real associations moves λ^\hat\lambda only a little.
  • Conservative for real signal. Dividing by λ^\hat\lambda also shrinks the statistics of real hits, so power goes down.
  • Works for any 1-df test. The method applies to any test that is chi-squared with 1 degree of freedom under the null, for example a Wald test in a regression. For a test with kk degrees of freedom, use the median of that law.
  • Reported as a quality measure. Studies report λ^\hat\lambda with the results. A value near 1 means little inflation of the bulk of the statistics.

Variants and improvements

  • Scale to a fixed sample size. λ^\hat\lambda grows with NN for the same structure, so studies also report λ1000=1+(λ^−1)(1/Ncases+1/Ncontrols)/(1/1000+1/1000)\lambda_{1000} = 1 + (\hat\lambda - 1)(1/N_{\text{cases}} + 1/N_{\text{controls}}) / (1/1000 + 1/1000), the value for 1000 cases and 1000 controls.
  • Principal components. Adding the top genetic principal components as covariates corrects each SNP by its own pattern of frequency differences, instead of one factor for all.
  • Mixed models. Mixed model association models structure and relatedness with a random effect whose covariance is the genetic relationship matrix.
  • LD score regression. The intercept of LD score regression measures confounding, while λ^\hat\lambda mixes confounding with real polygenic signal.
  • Second round. In a meta-analysis, genomic control is applied to each study and then again to the combined result.

When to use it

  • As a check of every GWAS: report λ^\hat\lambda, and look at a quantile-quantile plot of the statistics.
  • To correct a scan of modest size with mild structure, when genotypes for a better method are not available, for example in a meta-analysis of summary statistics.
  • For candidate gene studies with a set of null markers typed only to estimate λ\lambda, which was the original design of Devlin and Roeder.

Pitfalls

  • Polygenic inflation is not confounding. With many causal variants of small effect, the median statistic grows with NN even without any structure (Yang and coworkers 2011). Genomic control then removes real signal. LD score regression separates the two.
  • Differential inflation. Structure inflates SNPs with large frequency differences between populations more than others. One constant over-corrects some SNPs and under-corrects others.
  • Biased SNP sets. Estimate λ^\hat\lambda from all SNPs or from a random set. A set chosen for a candidate region, or filtered by p-value, gives a wrong median.
  • Deflation. A λ^\hat\lambda below 1 suggests an error, such as over-correction upstream or a wrong test. The floor at 1 hides it.
  • Multiple testing. Genomic control does not replace the genome-wide threshold of the multiple comparisons problem.

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)
genomic_control.py 94 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/genomic-control/. The authors are listed in prov/MQGC1J.jsonl.
"""Genomic control for a case-control association scan.

Each SNP is tested with the Cochran-Armitage trend test, which equals
N r^2, where N is the number of individuals and r is the Pearson
correlation of the allele dosage (0, 1 or 2) with the case status (1 for a
case, 0 for a control). Under the null of no association and no
confounding, each statistic is approximately chi-squared with 1 degree of
freedom. Genomic control estimates the inflation factor lambda as the
median of the M statistics divided by the median of the chi-squared law
with 1 degree of freedom, and divides every statistic by lambda
(Devlin and Roeder 1999).
"""

from __future__ import annotations

from fractions import Fraction
from statistics import NormalDist
from typing import List, Sequence, Tuple

from biostoch import chi2_sf

# The median of the chi-squared law with 1 df is the square of the 0.75
# quantile of the standard normal law: 0.454936...
CHI2_1_MEDIAN = NormalDist().inv_cdf(0.75) ** 2


def trend_statistic(dosage: Sequence[int], status: Sequence[int], exact: bool = False):
    """The Cochran-Armitage trend statistic N r^2 for one SNP.

    It is computed from integer sums, as
    N (N Sxy - Sx Sy)^2 / ((N Sxx - Sx^2) (N Sy - Sy^2)),
    so with exact=True the result is a Fraction. A SNP without variation, or
    a sample with only cases or only controls, gives 0.
    """
    n = len(dosage)
    if n != len(status):
        raise ValueError("dosage and status need the same length")
    sx = sxx = sy = sxy = 0
    for x, y in zip(dosage, status):
        sx += x
        sxx += x * x
        sy += y
        sxy += x * y
    vx = n * sxx - sx * sx
    vy = n * sy - sy * sy
    if vx == 0 or vy == 0:
        return Fraction(0) if exact else 0.0
    num = n * (n * sxy - sx * sy) ** 2
    den = vx * vy
    return Fraction(num, den) if exact else num / den


def median(xs: Sequence[float]) -> float:
    """The sample median (the mean of the two middle values for an even count)."""
    s = sorted(xs)
    k = len(s)
    if k == 0:
        raise ValueError("empty sample")
    mid = k // 2
    return s[mid] if k % 2 else (s[mid - 1] + s[mid]) / 2


def inflation_factor(stats: Sequence[float]) -> float:
    """lambda = median(stats) / 0.454936, without the floor at 1."""
    return median(stats) / CHI2_1_MEDIAN


def genomic_control(stats: Sequence[float]) -> Tuple[float, List[float], List[float]]:
    """Apply genomic control to 1-df association statistics.

    Returns (lam, adjusted, pvalues): lam = max(1, median / 0.454936), the
    statistics divided by lam, and their chi-squared (1 df) p-values.
    """
    m = median(stats)  # @line L2
    lam = max(1.0, m / CHI2_1_MEDIAN)  # @line L3
    adjusted = [t / lam for t in stats]  # @line L4
    pvalues = [chi2_sf(t, 1) for t in adjusted]  # @line L5
    return lam, adjusted, pvalues  # @line L6


def association_scan(genotypes: Sequence[Sequence[int]], status: Sequence[int]):
    """Trend test at every SNP, then genomic control.

    genotypes[i][j] is the dosage of individual i at SNP j. Returns the raw
    statistics followed by the result of genomic_control.
    """
    m = len(genotypes[0])
    stats = []
    for j in range(m):  # @line L1
        stats.append(trend_statistic([row[j] for row in genotypes], status))
    lam, adjusted, pvalues = genomic_control(stats)
    return stats, lam, adjusted, pvalues
test_genomic_control.py 122 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/genomic-control/. The authors are listed in prov/MQGC1J.jsonl.

import math
import random
from fractions import Fraction

from biostoch import chi2_sf
from genomic_control import (
    CHI2_1_MEDIAN,
    association_scan,
    genomic_control,
    inflation_factor,
    median,
    trend_statistic,
)


def armitage_from_table(cases, controls):
    """The textbook form on a 2 by 3 table with scores 0, 1, 2 (exact)."""
    R, S = sum(cases), sum(controls)
    N = R + S
    n = [cases[k] + controls[k] for k in range(3)]
    u = sum(k * (S * cases[k] - R * controls[k]) for k in range(3))
    v = Fraction(R * S, N) * (N * sum(k * k * n[k] for k in range(3)) - sum(k * n[k] for k in range(3)) ** 2)
    return Fraction(N * u * u) / (N * v)


def expand(cases, controls):
    dosage, status = [], []
    for k in range(3):
        dosage += [k] * cases[k] + [k] * controls[k]
        status += [1] * cases[k] + [0] * controls[k]
    return dosage, status


def lambda_sd(lam, m):
    """Large-sample sd of median/0.454936 for m values of lam * chi2_1."""
    x = CHI2_1_MEDIAN
    dens = math.exp(-x / 2) / math.sqrt(2 * math.pi * x)
    return lam / (2 * dens * math.sqrt(m)) / x


def test_median_constant():
    assert abs(CHI2_1_MEDIAN - 0.454936) < 1e-6
    assert abs(chi2_sf(CHI2_1_MEDIAN, 1) - 0.5) < 1e-12
    assert median([3, 1, 2]) == 2
    assert median([4, 1, 3, 2]) == 2.5


def test_trend_equals_armitage_form():
    cases, controls = (20, 50, 30), (35, 45, 20)
    d, s = expand(cases, controls)
    t = trend_statistic(d, s, exact=True)
    assert t == armitage_from_table(cases, controls)
    # N = 200, N Sxy - Sx Sy = 2500, N Sxx - Sx^2 = 20975, N Sy - Sy^2 = 10000.
    assert t == Fraction(200 * 2500 ** 2, 20975 * 10000) == Fraction(5000, 839)
    rng = random.Random(3)
    for _ in range(50):
        ca = tuple(rng.randint(0, 30) for _ in range(3))
        co = tuple(rng.randint(0, 30) for _ in range(3))
        n = [ca[k] + co[k] for k in range(3)]
        if sum(ca) == 0 or sum(co) == 0 or sum(1 for x in n if x) < 2:
            continue
        d, s = expand(ca, co)
        assert trend_statistic(d, s, exact=True) == armitage_from_table(ca, co)


def test_hand_example_of_the_page():
    stats = [0.10, 0.30, 0.62, 0.95, 2.40]
    lam, adj, p = genomic_control(stats)
    assert abs(lam - 0.62 / 0.454936423119572) < 1e-12
    assert abs(adj[4] - 2.40 / lam) < 1e-12
    assert abs(p[4] - chi2_sf(2.40 / lam, 1)) < 1e-15
    # A deflated scan is left alone.
    lam2, adj2, _ = genomic_control([0.1, 0.2, 0.3])
    assert lam2 == 1.0 and adj2 == [0.1, 0.2, 0.3]


def test_scaled_chi_square_recovers_lambda():
    rng = random.Random(11)
    m, lam0 = 20000, 1.3
    stats = [lam0 * rng.gauss(0.0, 1.0) ** 2 for _ in range(m)]
    lam, adj, p = genomic_control(stats)
    assert abs(lam - lam0) <= 4 * lambda_sd(lam0, m)
    assert abs(median(adj) - CHI2_1_MEDIAN) < 1e-12
    # After the correction, the share of p-values below 0.05 is near 0.05.
    k = sum(1 for x in p if x < 0.05)
    assert abs(k / m - 0.05) <= 4 * math.sqrt(0.05 * 0.95 / m)


def simulate_case_control(rng, n_per_pop, m, fst, case_rate):
    """Two populations of n_per_pop people each, m null SNPs.

    For each SNP: an ancestral frequency p ~ Uniform(0.1, 0.9), then a
    Balding-Nichols frequency for each population. Then, person by person,
    the status (case with probability case_rate[pop]) and the m genotypes.
    """
    c = (1 - fst) / fst
    freqs = []
    for _ in range(m):
        p = 0.1 + 0.8 * rng.random()
        freqs.append((rng.betavariate(c * p, c * (1 - p)), rng.betavariate(c * p, c * (1 - p))))
    G, y = [], []
    for pop in (0, 1):
        for _ in range(n_per_pop):
            y.append(1 if rng.random() < case_rate[pop] else 0)
            G.append([(rng.random() < f[pop]) + (rng.random() < f[pop]) for f in freqs])
    return G, y


def test_stratified_scan_is_inflated_and_corrected():
    rng = random.Random(5)
    m = 1500
    G, y = simulate_case_control(rng, 200, m, 0.01, (0.7, 0.3))
    stats, lam, adj, p = association_scan(G, y)
    assert lam > 1.0 + 4 * lambda_sd(1.0, m)
    assert abs(median(adj) - CHI2_1_MEDIAN) < 1e-12
    # Without a difference in case rates, the same structure gives no inflation.
    G2, y2 = simulate_case_control(rng, 200, m, 0.01, (0.5, 0.5))
    stats2 = association_scan(G2, y2)[0]
    assert abs(inflation_factor(stats2) - 1.0) <= 4 * lambda_sd(1.0, m)

History

Bernie Devlin and Kathryn Roeder (1999) showed that population structure and cryptic relatedness inflate the variance of the Armitage trend test by a factor that is roughly the same at every marker, and that this factor can be estimated from markers unlinked to the trait. They proposed the median for robustness. The method became a standard check and correction in genome-wide association studies. Later work showed that the inflation factor also grows under polygenic inheritance, and LD score regression (2015) gave a way to tell the two apart.

References

  1. Bernie Devlin and Kathryn Roeder, Genomic control for association studies, Biometrics 55(4), 1999, pp. 997-1004 (the trend test, the inflation of its variance under structure and cryptic relatedness, and the estimate of lambda from the median)
  2. Peter Armitage, Tests for linear trends in proportions and frequencies, Biometrics 11(3), 1955, pp. 375-386 (the test for a linear trend in proportions)
  3. Jian Yang and coworkers, Genomic inflation factors under polygenic inheritance, European Journal of Human Genetics 19(7), 2011, pp. 807-812 (lambda grows with the sample size under polygenic inheritance without any structure)
  4. Brendan K. Bulik-Sullivan and coworkers, LD Score regression distinguishes confounding from polygenicity in genome-wide association studies, Nature Genetics 47(3), 2015, pp. 291-295 (the LD score intercept as a measure of confounding, compared with lambda GC)

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