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
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 . Genomic control estimates as the median of all statistics divided by 0.454936, the median of that chi-squared law, and divides every statistic by . 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 individuals at SNPs, as dosages , and case status . Or directly a list of statistics that are chi-squared with 1 degree of freedom under the null.
Model. For a null SNP, the statistic is , with chi-squared with 1 degree of freedom and the same for all SNPs (Devlin and Roeder 1999). Most SNPs are null.
Output. The estimate , the corrected statistics and their p-values.
For a case-control study, the statistic is the Cochran-Armitage trend test, which equals , where is the correlation of the dosage at SNP 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
GENOMIC-CONTROL(x, y)- 1
for j ← 1 to M do T_j ← N r_j^2, the trend statistic of SNP j - 2
m ← median of T_1, ..., T_M - 3
λ ← max(1, m / 0.454936) - 4
for j ← 1 to M do T_j ← T_j / λ - 5
p_j ← P(χ²_1 > T_j) - 6
return λ, T, p
Line L1 needs five integer sums per SNP: . 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 , , , and . Then , and , so
with a p-value of 0.0146.
A small scan. Take five statistics . The median is , so . The corrected statistics are . 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 table, with the scores 0, 1, 2, reduces to when the cell counts are written as sums over individuals. Under the model, the median of is , because is the median of the chi-squared law with 1 degree of freedom. The sample median of many SNPs converges to this value, so , 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 individuals have dosages and status , with cases and controls, both positive, and with the not all equal. Let and be the numbers of cases and controls with dosage , and . Then the Cochran-Armitage trend statistic with the scores ,
equals , where is the Pearson correlation of and , and also
with , , and .
Proof. The second form is the definition of , multiplied by , with numerator and denominator of both multiplied by . Now and , so
Also , , and since . Putting these into gives the second form.
So line L1 computes the trend test from five integer sums in one pass over the individuals.
The model. Devlin and Roeder model a null SNP in a structured or cryptically related sample as , where follows the chi-squared law with 1 degree of freedom and is the same for all SNPs. Assume that are identically distributed, and that the sample median of converges in probability to the population median as (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 , where is the standard normal distribution function.
Proof. If with standard normal, then . This equals when .
Theorem. Under the model, from line L3 converges in probability to , and for each fixed the corrected statistic 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 has the median , because scaling by keeps the order. Its distribution function is continuous and strictly increasing near , so the population median is unique and, by assumption, the sample median converges in probability to . Dividing by the constant gives . The map is continuous and equals at , so in probability by the continuous mapping theorem. Then , and in probability, so by Slutsky's theorem converges in law to . If is chi-squared with 1 degree of freedom, , which gives the last claim.
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 and genomic control removes real signal. These are the limits listed on the page.
Complexity
- Time. Line L1 is one pass over the genotypes. The median costs by sorting or by selection. The rest is .
- Space. for the statistics. The genotypes can be streamed one SNP at a time.
- From summary statistics. If only the statistics or p-values are given, the method costs 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 , 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 only a little.
- Conservative for real signal. Dividing by 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 degrees of freedom, use the median of that law.
- Reported as a quality measure. Studies report 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. grows with for the same structure, so studies also report , 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 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 , 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 , 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 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 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 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.
# 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
- 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)
- 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)
- 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)
- 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.
| 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 MQGC1J Edit this page History Report an error Markdown