Algorithm Search⌘K

Algorithmresearch

LD score regression

Also called LDSC, linkage disequilibrium score regression.

Regresses GWAS chi-squared statistics on the LD scores of the SNPs, so that the slope estimates the SNP heritability and the intercept measures confounding such as stratification.

Time
Θ(M w n + B M) worst · average · best
Space
Θ(M n) extra
Where
B = the number of jackknife blocks; M = the number of SNPs; n = the size of the reference panel; w = the number of SNPs in an LD window
Properties
deterministicnot exactofflineiterative
Origin
Brendan K. Bulik Sullivan, Po Ru Loh, Hilary K. Finucane, Benjamin M. Neale, 2015

LD score regression separates the two reasons why the test statistics of a genome-wide association study can be larger than expected under the null. Confounding, such as population stratification, raises all statistics by about the same amount. Polygenic signal raises the statistic of a SNP in proportion to how many other SNPs it tags through linkage disequilibrium, its LD score. A regression of the chi-squared statistics on the LD scores therefore estimates the SNP heritability from the slope and the confounding from the intercept. It needs only the summary statistics of the study and LD scores from a reference panel.

In plain words

In a study of a trait with many small genetic effects, a marker near many other markers picks up the effects of all its neighbours, so its test statistic tends to be large. A marker with few neighbours picks up less. Problems in the study design, such as a mix of ancestries, make all markers look stronger by about the same amount, no matter how many neighbours they have. The method counts the neighbours of each marker in a reference sample. It then fits a straight line of the test statistic against this count. A steep line means much real genetic signal, and a line that starts high means a problem in the study. The method can also say how much of the trait the markers explain.

The problem

Input. Association statistics χj2\chi^2_j for JJ SNPs from a GWAS of NN people, the LD scores lj=∑krjk2l_j = \sum_k r^2_{jk} of these SNPs over a window, and the number MM of SNPs that the heritability refers to. In this version the LD scores are computed from a reference panel of genotypes with genetic positions.

Model. Under a polygenic model in which every standardized SNP has an effect of mean 00 and variance h2/Mh^2 / M,

E[χj2∣lj]=Nh2Mlj+Na+1,\mathrm E[\chi^2_j \mid l_j] = \frac{N h^2}{M} l_j + N a + 1,

where h2h^2 is the SNP heritability and NaN a is the inflation from confounding (equation 1 of Bulik-Sullivan and coworkers 2015).

Output. The estimates of h2h^2 and of the intercept 1+Na1 + N a, their standard errors, and the ratio (intercept−1)/(χ2‾−1)(\text{intercept} - 1) / (\overline{\chi^2} - 1), the part of the mean inflation that the intercept explains.

The algorithm

  1. LD-SCORE-REGRESSION(reference genotypes, positions, window, χ², N, M, B)
  2. 1for each SNP j, for each SNP k > j with pos_k - pos_j ≤ window do
  3. 2r̃² ← r²_jk - (1 - r²_jk)/(n - 2); add r̃² to l_j and l_k (each l_j starts at 1)
  4. 3h² ← M (mean χ² - 1)/(N mean l); a ← 1
  5. repeat for a few rounds
  6. 4w_j ← 1 / (max(l_j, 1) (a + N h² l_j / M)²)
  7. 5(a, b) ← weighted least squares fit of χ²_j = a + b l_j
  8. 6h² ← b M / N
  9. 7for each block t of consecutive SNPs, refit lines L5 and L6 without block t, with w fixed
  10. 8return h², a, their block jackknife standard errors, and (a - 1)/(mean χ² - 1)

Line L2 corrects the upward bias of the sample r2r^2 in a panel of nn people, about 1/n1/n per pair, which adds up over a window. The first weight in line L4 lowers SNPs in high LD, whose statistics are counted many times through their neighbours. The second is the inverse of the variance of χj2\chi^2_j under the model. The block jackknife of line L7 accounts for the correlation of nearby statistics.

What this version leaves out. The ldsc software reads LD scores computed in advance from a large panel, with a 1 cM window and a separate set of regression SNPs. It filters SNPs by allele frequency and very large statistics, can fix the intercept in a first step, partitions the heritability over annotations, estimates genetic correlations, and converts h2h^2 to the liability scale for case-control traits. None of this is in the code.

Example

Take four SNPs with LD scores 1,2,3,41, 2, 3, 4 and statistics 1.6,1.9,2.6,2.91.6, 1.9, 2.6, 2.9, from a study with N=20,000N = 20{,}000, and let M=10,000M = 10{,}000. Use equal weights so that the fit is by hand.

  • The means are lˉ=2.5\bar l = 2.5 and χ2‾=2.25\overline{\chi^2} = 2.25.
  • ∑(l−lˉ)(χ2−χ2‾)=0.975+0.175+0.175+0.975=2.3\sum (l - \bar l)(\chi^2 - \overline{\chi^2}) = 0.975 + 0.175 + 0.175 + 0.975 = 2.3 and ∑(l−lˉ)2=5\sum (l - \bar l)^2 = 5, so the slope is 0.460.46 and the intercept is 2.25−0.46⋅2.5=1.102.25 - 0.46 \cdot 2.5 = 1.10.
  • h2=0.46⋅10,000/20,000=0.23h^2 = 0.46 \cdot 10{,}000 / 20{,}000 = 0.23.
  • The ratio is (1.10−1)/(2.25−1)=0.08(1.10 - 1)/(2.25 - 1) = 0.08. So 8% of the mean inflation is due to confounding, and the rest is polygenic signal.

The starting value of line L3 is 10,000⋅1.25/(20,000⋅2.5)=0.2510{,}000 \cdot 1.25 / (20{,}000 \cdot 2.5) = 0.25, which assumes an intercept of exactly 1. Genomic control would divide all four statistics by one factor and so treat all of the inflation as confounding.

Correctness

Write the GWAS statistics as z=NRβ+ε+Na sz = \sqrt N R \beta + \varepsilon + \sqrt{N a}\, s, with the LD matrix RR, polygenic effects β\beta of variance h2/Mh^2/M each, sampling noise ε\varepsilon of covariance RR, and confounding ss of variance 11 per SNP. The three parts are independent with mean 00, so E[zj2]=Nh2∑kRjk2/M+1+Na\mathrm E[z_j^2] = N h^2 \sum_k R_{jk}^2 / M + 1 + N a, which is the model equation. Weighted least squares with weights that depend only on the LD scores is linear in χ2\chi^2, so it returns the slope and intercept of this line in expectation, and exactly when the points lie on the line. The corrected r2r^2 of line L2 has mean 0 for unlinked SNPs and mean ρ2+O(1/n)\rho^2 + O(1/n) in general, so the panel LD scores estimate ljl_j. The full proof is below.

Proof: The expected chi-squared statistic is linear in the LD score, and weighted regression recovers the linefull

Setting. There are MM SNPs. Let RR be the M×MM \times M matrix of population correlations between the standardized genotypes, and let the LD score of SNP jj be lj=∑kRjk2l_j = \sum_k R_{jk}^2. A GWAS of NN people gives the statistics zjz_j and χj2=zj2\chi^2_j = z_j^2. We use the model of the summary statistics

z=N Rβ+ε+Na s,β∼(0,h2MI),ε∼(0,R),s∼(0,I),z = \sqrt N\, R \beta + \varepsilon + \sqrt{N a}\, s, \qquad \beta \sim (0, \tfrac{h^2}{M} I), \quad \varepsilon \sim (0, R), \quad s \sim (0, I),

with β\beta, ε\varepsilon and ss independent, where (μ,Σ)(\mu, \Sigma) gives the mean and the covariance of a law. Here NRβ\sqrt N R \beta is the part of zz due to the polygenic effects β\beta of the standardized SNPs, ε\varepsilon is the sampling noise, which has the LD correlation, and Na s\sqrt{N a}\, s is confounding that adds the same variance NaN a to every SNP. The genetic variance has mean E[β⊤Rβ]=h2Mtr⁡R=h2\mathrm E[\beta^\top R \beta] = \frac{h^2}{M} \operatorname{tr} R = h^2, since Rjj=1R_{jj} = 1.

Lemma 1 (equation 1 of Bulik-Sullivan and coworkers). E[χj2]=Nh2lj/M+Na+1\mathrm E[\chi^2_j] = N h^2 l_j / M + N a + 1.

Proof. The three terms of zjz_j have mean 00 and are independent, so E[zj2]\mathrm E[z_j^2] is the sum of their variances. Var⁡(N(Rβ)j)=N∑kRjk2Var⁡(βk)=Nh2lj/M\operatorname{Var}(\sqrt N (R\beta)_j) = N \sum_k R_{jk}^2 \operatorname{Var}(\beta_k) = N h^2 l_j / M. Var⁡(εj)=Rjj=1\operatorname{Var}(\varepsilon_j) = R_{jj} = 1, and Var⁡(Na sj)=Na\operatorname{Var}(\sqrt{N a}\, s_j) = N a. □\square

So the points (lj,χj2)(l_j, \chi^2_j) scatter around a line with slope Nh2/MN h^2 / M and intercept 1+Na1 + N a. Confounding moves the intercept and polygenicity moves the slope. The summary model is an approximation of the individual-level model with NN large and each SNP of small effect, where zj≈Nr^jz_j \approx \sqrt N \hat r_j for the sample correlation r^j\hat r_j of the trait and SNP jj.

Lemma 2 (the corrected r2r^2, line L2). Let r^\hat r be the sample correlation of nn independent pairs from a bivariate normal law with correlation ρ\rho, and r~2=r^2−(1−r^2)/(n−2)=((n−1)r^2−1)/(n−2)\tilde r^2 = \hat r^2 - (1 - \hat r^2)/(n - 2) = ((n - 1) \hat r^2 - 1)/(n - 2). If ρ=0\rho = 0, E[r~2]=0\mathrm E[\tilde r^2] = 0. For any ρ\rho, E[r~2]=ρ2+O(ρ2(1−ρ2)/n)\mathrm E[\tilde r^2] = \rho^2 + O(\rho^2 (1 - \rho^2)/n).

Proof. If ρ=0\rho = 0, r^2\hat r^2 follows the beta law with parameters 12\frac12 and n−22\frac{n-2}{2}, whose mean is 1/(n−1)1/(n - 1), and E[r~2]=((n−1)/(n−1)−1)/(n−2)=0\mathrm E[\tilde r^2] = ((n-1)/(n-1) - 1)/(n - 2) = 0. For general ρ\rho, the exact mean of r^2\hat r^2 under the bivariate normal law is E[r^2]=1−n−2n−1(1−ρ2) 2F1(1,1;n+12;ρ2)\mathrm E[\hat r^2] = 1 - \frac{n-2}{n-1} (1 - \rho^2)\, {}_2F_1(1, 1; \tfrac{n+1}{2}; \rho^2), and 2F1(1,1;n+12;ρ2)=1+2ρ2n+1+O(ρ4/n2){}_2F_1(1, 1; \tfrac{n+1}{2}; \rho^2) = 1 + \frac{2 \rho^2}{n + 1} + O(\rho^4 / n^2). Substituting, E[r~2]=1−(1−ρ2) 2F1(⋅)=ρ2−2ρ2(1−ρ2)n+1+O(ρ4(1−ρ2)/n2)\mathrm E[\tilde r^2] = 1 - (1 - \rho^2)\,{}_2F_1(\cdot) = \rho^2 - \frac{2\rho^2 (1 - \rho^2)}{n + 1} + O(\rho^4 (1 - \rho^2)/n^2). □\square

The plain r^2\hat r^2 has the bias (1−ρ2)/(n−1)(1 - \rho^2)/(n - 1) at every pair, and a window holds many pairs with ρ\rho near 00, so without the correction the LD score of every SNP would be too large by about w/nw/n for a window of ww SNPs. Line L1 adds r~jk2\tilde r^2_{jk} for each pair in the window once to ljl_j and once to lkl_k, and line L2 adds 11 for k=jk = j, where r~2=1\tilde r^2 = 1 exactly. So the code returns ∑k∈window(j)r~jk2\sum_{k \in \text{window}(j)} \tilde r^2_{jk}, which estimates ljl_j when RjkR_{jk} is negligible outside the window.

Lemma 3 (weighted regression, lines L4 to L6). Let wj>0w_j > 0 be weights that depend on the LD scores only, and let (a^,b^)(\hat a, \hat b) minimize ∑jwj(χj2−a−b lj)2\sum_j w_j (\chi^2_j - a - b\, l_j)^2, with not all ljl_j equal. Then E[a^]=1+Na\mathrm E[\hat a] = 1 + N a and E[b^]=Nh2/M\mathrm E[\hat b] = N h^2 / M. If every χj2\chi^2_j is exactly 1+Na+(Nh2/M)lj1 + N a + (N h^2/M) l_j, then a^\hat a and b^\hat b equal these values for any positive weights.

Proof. The weighted least squares estimate is (a^,b^)⊤=(L⊤WL)−1L⊤Wχ2(\hat a, \hat b)^\top = (L^\top W L)^{-1} L^\top W \chi^2 with the rows (1,lj)(1, l_j) of LL and W=diag⁡(w)W = \operatorname{diag}(w), a linear function of χ2\chi^2 whose matrix is fixed. L⊤WLL^\top W L is invertible because the weighted variance of the ljl_j is positive. By Lemma 1, E[χ2]=L(1+Na,Nh2/M)⊤\mathrm E[\chi^2] = L (1 + N a, N h^2/M)^\top, and (L⊤WL)−1L⊤WL=I(L^\top W L)^{-1} L^\top W L = I. The exact case is the same computation without the expectation. Line L6 multiplies b^\hat b by M/NM/N. □\square

The weights of line L4 are those of the method. 1/max⁡(lj,1)1/\max(l_j, 1) lowers the weight of SNPs in high LD, whose statistics are correlated with many others and so count more than once. 1/(a+Nh2lj/M)21/(a + N h^2 l_j/M)^2 is proportional to 1/Var⁡(χj2)1/\operatorname{Var}(\chi^2_j) when zjz_j is normal, since then Var⁡(zj2)=2 E[zj2]2\operatorname{Var}(z_j^2) = 2\,\mathrm E[z_j^2]^2, which makes the fit more efficient. In the code they depend on h2h^2 and aa of the previous round, so they depend weakly on the data. Lemma 3 then holds only approximately. The estimate stays consistent when the weights converge, since a weighted least squares estimate with any fixed positive weights is consistent for the line of Lemma 1.

The jackknife, line L7. The SNPs are split into BB blocks of consecutive SNPs. For each block tt the code refits the line without the block, with the weights held fixed, and returns B−1B∑t(θ^(t)−θˉ)2\sqrt{\frac{B-1}{B} \sum_t (\hat\theta_{(t)} - \bar\theta)^2} for θ=h2\theta = h^2 and for the intercept. This is the delete-one-group jackknife estimate of the standard error. The statistics are correlated within an LD window, so the blocks must be much longer than a window, and then the blocks are close to independent. The jackknife is used because the dependence between the χj2\chi^2_j through RR makes the usual standard error of the regression too small. When all points lie on the line, every refit returns the same line, so both standard errors are 00, which the tests check.

What this does not cover. Lemma 1 is about the summary model. In real data the LD scores come from a reference panel, which differs from the GWAS sample in ancestry and size, and the effect sizes may depend on allele frequency or LD. Then the slope and the intercept are biased in ways that this version does not model.

Complexity

  • LD scores. Each SNP is paired with the ww SNPs of its window, and each correlation costs Θ(n)\Theta(n) over the panel, so Θ(Mwn)\Theta(M w n). The scores are computed once per panel and reused for every trait.
  • Regression. Each round costs Θ(J)\Theta(J). The jackknife in the code refits from scratch, Θ(BJ)\Theta(B J). With sums per block it costs Θ(J+B)\Theta(J + B).
  • Space. Θ(Mn)\Theta(M n) for the standardized panel; the regression needs Θ(J)\Theta(J).
  • No individual data. The study enters only through JJ statistics and its sample size.

Properties

  • Separates confounding from polygenicity. Under the model, confounding that does not depend on LD affects only the intercept.
  • LD from another sample. The LD scores can come from a different, smaller sample of the same ancestry, because only the expected LD enters the model.
  • Depends on the panel. If the panel ancestry differs from the study, the LD scores are wrong, and the slope and the intercept are both biased.
  • Less precise than REML. With individual genotypes, SNP heritability estimation by REML uses all pairs of people and has a smaller standard error.
  • A method of moments. The fit matches the mean of χj2\chi^2_j to the model line and uses no likelihood, so it does not need the joint law of the statistics.

Variants and improvements

  • Partitioned heritability. Regress on several LD scores, one per functional annotation, to estimate how much heritability each annotation holds.
  • Genetic correlation. Regress the product z1jz2jz_{1j} z_{2j} of the statistics of two traits on ljl_j, to estimate their genetic correlation from summary statistics.
  • Constrained intercept. Fix the intercept at 1 when the study is known to be free of confounding, to estimate h2h^2 with a smaller standard error.
  • Effects that depend on frequency and LD. Models that let the effect variance depend on allele frequency and on LD fit real traits better.

When to use it

  • Checking whether the inflation of a GWAS comes from confounding or from polygenic signal, before or instead of genomic control.
  • Estimating SNP heritability when only summary statistics are available.
  • Estimating the genetic correlation of many pairs of traits from published summary statistics.
  • Finding the cell types and annotations enriched in heritability.

Pitfalls

  • Small samples. The standard errors are large unless NN is in the tens of thousands, because the signal per SNP is small.
  • Panel mismatch. LD scores from a panel of a different ancestry, or computed on a different set of SNPs, bias both the slope and the intercept.
  • Regions of long-range LD. The major histocompatibility complex and some inversions have LD beyond the window and very large statistics in many studies. They are usually left out.
  • Corrected statistics. Statistics already divided by the genomic control factor have their intercept pushed down, and the slope with it.
  • Choice of MM. h2h^2 refers to the MM SNPs used to define the model, often the common SNPs of the panel. A different MM changes the estimate in proportion.

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.

ld_score_regression.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ld-score-regression/. The authors are listed in prov/E6NC45.jsonl.
"""A small version of LD score regression (Bulik-Sullivan et al. 2015).

Under a polygenic model, the chi-squared statistic of SNP j in a GWAS of N
people satisfies

    E[chi2_j | l_j] = N h2 l_j / M + N a + 1,

where l_j = sum_k r2_jk is the LD score of SNP j, M is the number of SNPs,
h2 is the SNP heritability and N a measures confounding such as population
stratification. Regressing chi2_j on l_j gives h2 from the slope and the
confounding from the intercept.

What this version leaves out, compared with the ldsc software:
- LD scores come from one small reference panel given as genotypes, with
  SNP windows by genetic position; no reading of real panels or annotations.
- No partitioned (stratified) regression over functional annotations.
- No genetic correlation between two traits.
- No filtering of SNPs (minor allele frequency, strand, large chi2 values)
  and no two-step estimator that fixes the intercept from SNPs with small
  chi2 first.
- The regression weight 1/max(l_j, 1) uses the LD score over all SNPs, not
  over the regression SNPs only.
- No transformation of h2 to the liability scale for case-control studies.
"""

from __future__ import annotations

import math
from typing import Dict, List, Sequence


def r2_unbiased(r2: float, n: int) -> float:
    """The approximately unbiased estimate r2 - (1 - r2) / (n - 2) of the squared correlation."""
    return r2 - (1.0 - r2) / (n - 2)


def ld_scores(G: Sequence[Sequence[int]], pos: Sequence[float], window: float) -> List[float]:
    """LD scores from a reference panel.

    G is n_ref people by M SNPs, pos the sorted genetic positions of the SNPs,
    and window the half width: l_j sums the corrected r2_jk over the SNPs k with
    |pos_k - pos_j| <= window, including k = j, which adds exactly 1.
    """
    n = len(G)
    M = len(pos)
    cols = []
    for j in range(M):
        x = [float(G[i][j]) for i in range(n)]
        mu = sum(x) / n
        c = [v - mu for v in x]
        s = math.sqrt(sum(v * v for v in c))
        cols.append([v / s for v in c] if s > 0 else None)
    l = [1.0 if cols[j] is not None else 0.0 for j in range(M)]
    for j in range(M):
        if cols[j] is None:
            continue
        cj = cols[j]
        k = j + 1
        while k < M and pos[k] - pos[j] <= window:  # @line L1
            if cols[k] is not None:
                r = sum(a * b for a, b in zip(cj, cols[k]))
                v = r2_unbiased(r * r, n)  # @line L2
                l[j] += v
                l[k] += v
            k += 1
    return l


def _wls_line(x: Sequence[float], y: Sequence[float], w: Sequence[float]):
    """Weighted least squares fit of y = a + b x. Returns (a, b)."""
    sw = sum(w)
    mx = sum(wi * xi for wi, xi in zip(w, x)) / sw
    my = sum(wi * yi for wi, yi in zip(w, y)) / sw
    sxx = sum(wi * (xi - mx) ** 2 for wi, xi in zip(w, x))
    sxy = sum(wi * (xi - mx) * (yi - my) for wi, xi, yi in zip(w, x, y))
    b = sxy / sxx
    return my - b * mx, b


def ldsc(chi2: Sequence[float], l: Sequence[float], N: float, M: int,
         n_blocks: int = 20, rounds: int = 3) -> Dict[str, float]:
    """LD score regression of chi2 on l, with a block jackknife.

    Returns h2, intercept, their jackknife standard errors, and the ratio
    (intercept - 1) / (mean chi2 - 1).
    """
    J = len(chi2)
    if n_blocks < 2 or J < 2 * n_blocks:
        raise ValueError("need at least two SNPs per block and two blocks")
    mean_chi2 = sum(chi2) / J
    mean_l = sum(l) / J
    h2 = min(max(M * (mean_chi2 - 1.0) / (N * mean_l), 0.0), 1.0)  # @line L3
    a = 1.0
    w: List[float] = []
    for _ in range(rounds):
        w = [1.0 / (max(lj, 1.0) * max(a + N * h2 * lj / M, 1.0) ** 2) for lj in l]  # @line L4
        a, b = _wls_line(l, chi2, w)  # @line L5
        h2 = min(max(b * M / N, 0.0), 1.0)  # @line L6
    h2_hat = b * M / N
    # Delete-one-block jackknife over contiguous blocks, with the weights fixed.
    bounds = [round(t * J / n_blocks) for t in range(n_blocks + 1)]
    ps_a, ps_h = [], []
    for t in range(n_blocks):
        keep = [j for j in range(J) if not bounds[t] <= j < bounds[t + 1]]
        aa, bb = _wls_line([l[j] for j in keep], [chi2[j] for j in keep], [w[j] for j in keep])  # @line L7
        ps_a.append(aa)
        ps_h.append(bb * M / N)

    def jk_se(vals):
        m = sum(vals) / n_blocks
        return math.sqrt((n_blocks - 1) / n_blocks * sum((v - m) ** 2 for v in vals))

    ratio = (a - 1.0) / (mean_chi2 - 1.0) if mean_chi2 > 1.0 else float("nan")
    return {"h2": h2_hat, "intercept": a, "se_h2": jk_se(ps_h),
            "se_intercept": jk_se(ps_a), "ratio": ratio}  # @line L8
test_ld_score_regression.py 223 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ld-score-regression/. The authors are listed in prov/E6NC45.jsonl.

import math
import random
from fractions import Fraction
from statistics import correlation

from ld_score_regression import ld_scores, ldsc, r2_unbiased

# Regions of 40 SNPs; within a region the next allele on a haplotype copies the
# previous one with this probability, so LD (and the LD score) varies by region.
COPY = [0.0, 0.5, 0.8, 0.9]
REGION = 40
SPACING = 0.1  # cM between neighbouring SNPs
WINDOW = 2.0  # cM; r2 at 20 SNPs is at most 0.81^20, about 0.015


def snp_design(rng, M):
    """Allele frequencies and copy probabilities of the SNPs."""
    freqs = [0.15 + 0.7 * rng.random() for _ in range(M)]
    copy = [COPY[(j // REGION) % len(COPY)] for j in range(M)]
    return freqs, copy


def haplotype(rng, freqs, copy):
    h = []
    for j, f in enumerate(freqs):
        if j > 0 and rng.random() < copy[j]:
            h.append(h[-1])
        else:
            h.append(1 if rng.random() < f else 0)
    return h


def genotypes(rng, n, freqs, copy):
    G = []
    for _ in range(n):
        a, b = haplotype(rng, freqs, copy), haplotype(rng, freqs, copy)
        G.append([x + y for x, y in zip(a, b)])
    return G


def gwas_chi2(G, y):
    """chi2_j = N r_j^2, the trend statistic of each SNP."""
    n = len(y)
    my = sum(y) / n
    cy = [v - my for v in y]
    syy = sum(v * v for v in cy)
    out = []
    for j in range(len(G[0])):
        x = [G[i][j] for i in range(n)]
        mx = sum(x) / n
        sxy = sum((a - mx) * b for a, b in zip(x, cy))
        sxx = sum((a - mx) ** 2 for a in x)
        out.append(n * sxy * sxy / (sxx * syy))
    return out


def polygenic_trait(rng, G, h2):
    n, M = len(G), len(G[0])
    p = [sum(G[i][j] for i in range(n)) / (2.0 * n) for j in range(M)]
    sd = [math.sqrt(2.0 * q * (1.0 - q)) for q in p]
    beta = [rng.gauss(0.0, math.sqrt(h2 / M)) for _ in range(M)]
    y = []
    for i in range(n):
        g = sum((G[i][j] - 2.0 * p[j]) / sd[j] * beta[j] for j in range(M) if sd[j] > 0)
        y.append(g + rng.gauss(0.0, math.sqrt(1.0 - h2)))
    return y


def simulate(rng, N, M, n_ref, h2):
    """GWAS chi2 of N people and LD scores from a separate panel of n_ref people."""
    freqs, copy = snp_design(rng, M)
    G = genotypes(rng, N, freqs, copy)
    y = polygenic_trait(rng, G, h2)
    ref = genotypes(rng, n_ref, freqs, copy)
    pos = [SPACING * j for j in range(M)]
    return gwas_chi2(G, y), ld_scores(ref, pos, WINDOW)


def test_ld_scores_match_all_pairs_brute_force():
    rng = random.Random(21)
    n, M = 30, 25
    freqs, copy = snp_design(rng, M)
    G = genotypes(rng, n, freqs, copy)
    pos = sorted(rng.uniform(0.0, 3.0) for _ in range(M))
    l = ld_scores(G, pos, 0.5)
    for j in range(M):
        xj = [G[i][j] for i in range(n)]
        want = 0.0
        for k in range(M):
            if abs(pos[k] - pos[j]) <= 0.5:
                xk = [G[i][k] for i in range(n)]
                r = correlation(xj, xk)
                want += r * r - (1 - r * r) / (n - 2)
        assert abs(l[j] - want) < 1e-9


def test_r2_correction_is_exact_at_the_null_mean():
    # For independent SNPs, E[r^2] = 1/(n - 1), and the correction maps it to 0.
    for n in (5, 50, 1000):
        assert r2_unbiased(Fraction(1, n - 1), n) == 0
    assert r2_unbiased(Fraction(1), 10) == 1


def test_corrected_r2_of_independent_snps_averages_zero():
    rng = random.Random(22)
    n, reps = 20, 3000
    vals = []
    for _ in range(reps):
        x = [rng.gauss(0, 1) for _ in range(n)]
        z = [rng.gauss(0, 1) for _ in range(n)]
        r = correlation(x, z)
        vals.append(r2_unbiased(r * r, n))
    m = sum(vals) / reps
    sd = math.sqrt(sum((v - m) ** 2 for v in vals) / (reps - 1))
    assert abs(m) <= 4 * sd / math.sqrt(reps)


def test_statistics_that_follow_equation_one_exactly():
    rng = random.Random(23)
    J, N, M, h2, a = 400, 5000, 400, 0.3, 0.002
    l = [1.0 + 20.0 * rng.random() for _ in range(J)]
    chi2 = [N * h2 * lj / M + N * a + 1.0 for lj in l]
    res = ldsc(chi2, l, N, M)
    assert abs(res["h2"] - h2) < 1e-9
    assert abs(res["intercept"] - (1.0 + N * a)) < 1e-9
    assert res["se_h2"] < 1e-9 and res["se_intercept"] < 1e-9


def wls_by_normal_equations(x, y, w):
    s0 = sum(w)
    s1 = sum(wi * xi for wi, xi in zip(w, x))
    s2 = sum(wi * xi * xi for wi, xi in zip(w, x))
    t0 = sum(wi * yi for wi, yi in zip(w, y))
    t1 = sum(wi * xi * yi for wi, xi, yi in zip(w, x, y))
    det = s0 * s2 - s1 * s1
    return (s2 * t0 - s1 * t1) / det, (s0 * t1 - s1 * t0) / det


def test_one_round_and_jackknife_against_direct_refits():
    rng = random.Random(24)
    J, N, M, B = 200, 3000, 200, 10
    l = [1.0 + 15.0 * rng.random() for _ in range(J)]
    chi2 = [(1.0 + N * 0.4 * lj / M) * rng.gammavariate(0.5, 2.0) for lj in l]
    res = ldsc(chi2, l, N, M, n_blocks=B, rounds=1)
    h0 = min(max(M * (sum(chi2) / J - 1.0) / (N * sum(l) / J), 0.0), 1.0)
    w = [1.0 / (max(lj, 1.0) * max(1.0 + N * h0 * lj / M, 1.0) ** 2) for lj in l]
    a, b = wls_by_normal_equations(l, chi2, w)
    assert abs(res["intercept"] - a) < 1e-9
    assert abs(res["h2"] - b * M / N) < 1e-12
    hs = []
    for t in range(B):
        idx = [j for j in range(J) if j // (J // B) != t]
        hs.append(wls_by_normal_equations([l[j] for j in idx], [chi2[j] for j in idx],
                                          [w[j] for j in idx])[1] * M / N)
    mean = sum(hs) / B
    se = math.sqrt((B - 1) / B * sum((v - mean) ** 2 for v in hs))
    assert abs(res["se_h2"] - se) < 1e-12


def test_polygenic_trait_slope_gives_h2_and_intercept_near_one():
    rng = random.Random(25)
    h2 = 0.5
    chi2, l = simulate(rng, N=1500, M=480, n_ref=300, h2=h2)
    res = ldsc(chi2, l, 1500, 480)
    z = 4.0
    assert abs(res["h2"] - h2) <= z * res["se_h2"]
    assert abs(res["intercept"] - 1.0) <= z * res["se_intercept"]


def summary_statistics(rng, N, M, h2, a, reach=60):
    """z statistics drawn from their joint law, with a confounding term.

    The correlation of SNPs j < k is the product of the copy probabilities
    from j + 1 to k, so R is known. z = sqrt(N) R beta + eps + sqrt(N a) s with
    beta_j ~ N(0, h2 / M), eps ~ N(0, R) (an autoregressive recursion) and s_j
    independent standard normal. Then E[z_j^2] = N h2 l_j / M + N a + 1 with
    l_j = sum_k R_jk^2, which is returned (to reach SNPs on each side).
    """
    copy = [COPY[(j // REGION) % len(COPY)] for j in range(M)]
    beta = [rng.gauss(0.0, math.sqrt(h2 / M)) for _ in range(M)]
    chi2, l = [], []
    eps = 0.0
    for j in range(M):
        eps = copy[j] * eps + math.sqrt(1.0 - copy[j] ** 2) * rng.gauss(0.0, 1.0) if j else rng.gauss(0.0, 1.0)
        rb, lj = beta[j], 1.0
        r = 1.0
        for k in range(j + 1, min(M, j + reach + 1)):
            r *= copy[k]
            rb += r * beta[k]
            lj += r * r
        r = 1.0
        for k in range(j - 1, max(-1, j - reach - 1), -1):
            r *= copy[k + 1]
            rb += r * beta[k]
            lj += r * r
        zj = math.sqrt(N) * rb + eps + math.sqrt(N * a) * rng.gauss(0.0, 1.0)
        chi2.append(zj * zj)
        l.append(lj)
    return chi2, l


def test_summary_level_simulation_without_confounding():
    rng = random.Random(27)
    N, M, h2 = 5000, 4000, 0.3
    chi2, l = summary_statistics(rng, N, M, h2, 0.0)
    res = ldsc(chi2, l, N, M)
    z = 4.0
    assert abs(res["h2"] - h2) <= z * res["se_h2"]
    assert abs(res["intercept"] - 1.0) <= z * res["se_intercept"]


def test_confounding_raises_the_intercept_not_the_slope():
    rng = random.Random(28)
    N, M, h2, a = 5000, 4000, 0.3, 2e-4
    chi2, l = summary_statistics(rng, N, M, h2, a)
    res = ldsc(chi2, l, N, M)
    z = 4.0
    assert res["intercept"] > 1.0 + z * res["se_intercept"]
    assert abs(res["intercept"] - (1.0 + N * a)) <= z * res["se_intercept"]
    assert abs(res["h2"] - h2) <= z * res["se_h2"]

History

The genomic control of Devlin and Roeder (1999) treats all inflation of the null statistics as confounding. With the large GWAS of the early 2010s it became clear that a polygenic trait inflates the statistics even in a well-controlled study, so a large inflation factor no longer showed that a study was confounded. Bulik-Sullivan and coworkers (2015) used the LD scores of the SNPs to separate the two, since only the polygenic signal grows with the LD score. They found that in many large studies most of the inflation is polygenic signal. The same idea, with products of statistics or with several LD scores, was then used for genetic correlations and for partitioning heritability by annotation.

References

  1. Brendan K. Bulik-Sullivan, Po-Ru Loh, Hilary K. Finucane, Stephan Ripke, Jian Yang, Schizophrenia Working Group of the Psychiatric Genomics Consortium, Nick Patterson, Mark J. Daly, Alkes L. Price and Benjamin M. Neale, LD Score regression distinguishes confounding from polygenicity in genome-wide association studies, Nature Genetics 47(3), 2015, pp. 291-295 (equation 1, the LD scores from a 1 cM window, the regression weights and the block jackknife)
  2. Bernie Devlin and Kathryn Roeder, Genomic control for association studies, Biometrics 55(4), 1999, pp. 997-1004 (the inflation factor that LD score regression refines)

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
  • at least three sources
  • a scene preset for the example