Exercise 9. SNP-Based Heritability

Post-GWAS Analysis Course

1 Overview

This notebook estimates SNP-based heritability for ADHD and related traits using LDSC and GWAS summary statistics. You will prepare the inputs, run the heritability analysis, and compare results across traits.

NoteLearning goals

By the end of this notebook, you should be able to: - explain what SNP-based heritability estimates measure - prepare GWAS summary statistics for LDSC using the required format and filters - interpret heritability output across several traits in a comparative way

Warning

You will need the following input files: GWAS sumstats for ADHD, BMI, educational attainment, age at first birth, and depression. Those are available as input data.

## Table of Contents

2 1. Set up

Code
import pandas as pd
import numpy as np
import os
import warnings

warnings.filterwarnings("ignore")

3 2. Pepare the input files for LDSC

To estimate the SNP-based heritability (h2-SNP) of the different traits, we are going to use a tool named Linkage Disequilibrium Score Regression (LDSC). (https://github.com/bulik/LDSC) Several tutorials are available on the github page, including how to estimate h2-SNP: https://github.com/bulik/ldsc/wiki/Heritability-and-Genetic-Correlation

Before running the analysis, we need to harmonise the format of the summary statistics, and restrict them to high quality SNPs found in HapMap3

3.0.1 2.1 Inspect headers and sumstats formats

To harmonize the summary statistics, we will use the munge function from LDSC. This function takes as input the sumstats you want to harmonize, as well as a list of SNP to filter the sumstats. Here we use the HapMap3 SNPs present in the reference file w_hm3.snplist. The function requires that the sumstats have the following columns: SNP (SNP identifier is rs number format), N (sample size), signed statistics column (OR, BETA or Z-score), A1 and A2 (with A1 the effect allele). You can use -h to get an overview of the munge function

Code
#Check out the munge function from ldsc

os.system("munge_sumstats -h")
usage: munge_sumstats.py [-h] [--sumstats SUMSTATS] [--N N] [--N-cas N_CAS]
                         [--N-con N_CON] [--out OUT] [--info-min INFO_MIN]
                         [--maf-min MAF_MIN] [--daner] [--daner-n]
                         [--no-alleles] [--merge-alleles MERGE_ALLELES]
                         [--n-min N_MIN] [--chunksize CHUNKSIZE] [--snp SNP]
                         [--N-col N_COL] [--N-cas-col N_CAS_COL]
                         [--N-con-col N_CON_COL] [--a1 A1] [--a2 A2] [--p P]
                         [--frq FRQ] [--signed-sumstats SIGNED_SUMSTATS]
                         [--info INFO] [--info-list INFO_LIST]
                         [--nstudy NSTUDY] [--nstudy-min NSTUDY_MIN]
                         [--ignore IGNORE] [--a1-inc] [--keep-maf]

optional arguments:
  -h, --help            show this help message and exit
  --sumstats SUMSTATS   Input filename.
  --N N                 Sample size If this option is not set, will try to
                        infer the sample size from the input file. If the
                        input file contains a sample size column, and this
                        flag is set, the argument to this flag has priority.
  --N-cas N_CAS         Number of cases. If this option is not set, will try
                        to infer the number of cases from the input file. If
                        the input file contains a number of cases column, and
                        this flag is set, the argument to this flag has
                        priority.
  --N-con N_CON         Number of controls. If this option is not set, will
                        try to infer the number of controls from the input
                        file. If the input file contains a number of controls
                        column, and this flag is set, the argument to this
                        flag has priority.
  --out OUT             Output filename prefix.
  --info-min INFO_MIN   Minimum INFO score.
  --maf-min MAF_MIN     Minimum MAF.
  --daner               Use this flag to parse Stephan Ripke's daner* file
                        format.
  --daner-n             Use this flag to parse more recent daner* formatted
                        files, which include sample size column 'Nca' and
                        'Nco'.
  --no-alleles          Don't require alleles. Useful if only unsigned summary
                        statistics are available and the goal is h2 /
                        partitioned h2 estimation rather than rg estimation.
  --merge-alleles MERGE_ALLELES
                        Same as --merge, except the file should have three
                        columns: SNP, A1, A2, and all alleles will be matched
                        to the --merge-alleles file alleles.
  --n-min N_MIN         Minimum N (sample size). Default is (90th percentile
                        N) / 2.
  --chunksize CHUNKSIZE
                        Chunksize.
  --snp SNP             Name of SNP column (if not a name that ldsc
                        understands). NB: case insensitive.
  --N-col N_COL         Name of N column (if not a name that ldsc
                        understands). NB: case insensitive.
  --N-cas-col N_CAS_COL
                        Name of N column (if not a name that ldsc
                        understands). NB: case insensitive.
  --N-con-col N_CON_COL
                        Name of N column (if not a name that ldsc
                        understands). NB: case insensitive.
  --a1 A1               Name of A1 column (if not a name that ldsc
                        understands). NB: case insensitive.
  --a2 A2               Name of A2 column (if not a name that ldsc
                        understands). NB: case insensitive.
  --p P                 Name of p-value column (if not a name that ldsc
                        understands). NB: case insensitive.
  --frq FRQ             Name of FRQ or MAF column (if not a name that ldsc
                        understands). NB: case insensitive.
  --signed-sumstats SIGNED_SUMSTATS
                        Name of signed sumstat column, comma null value (e.g.,
                        Z,0 or OR,1). NB: case insensitive.
  --info INFO           Name of INFO column (if not a name that ldsc
                        understands). NB: case insensitive.
  --info-list INFO_LIST
                        Comma-separated list of INFO columns. Will filter on
                        the mean. NB: case insensitive.
  --nstudy NSTUDY       Name of NSTUDY column (if not a name that ldsc
                        understands). NB: case insensitive.
  --nstudy-min NSTUDY_MIN
                        Minimum # of studies. Default is to remove everything
                        below the max, unless there is an N column, in which
                        case do nothing.
  --ignore IGNORE       Comma-separated list of column names to ignore.
  --a1-inc              A1 is the increasing allele.
  --keep-maf            Keep the MAF column (if one exists).
0

As you can see, there are a lot of arguments that we can use to adapt the munging step to the format of the sumstats. A good practice when using new sumstats is to check the columns and their format as well as the metadata to determine: - What is the genome build? Hg38 or Hg19? - Which allele is the effect allele? A1? ALT? EFFECT_ALLELE? - Is there a sample size? A number of controls/cases? - What is the signed sumstat? OR, BETA, etc

You will now inspect the sumstats that we will be using and their metadata to answer these questions and be ready for the munge step. You might have to refer to the original publication or to the method if the information is not available with the data you have here.

Code
os.makedirs("./output/ldsc", exist_ok=True)
Note

In input/ldsc open the files with extension .sumstats. You can open them in the file browser of jupyterlab. For each sumstats (ADHD, BMI, educational attainment, age at first birth, depression) answer the following questions

  • What is the genome build?
  • Which allele is the effect allele?
  • What is the sample size?
  • What is the signed sumstat?

3.0.2 2.2 Munge sumstats

Now that we have all the information we need, we can munge the sumstats. Here is the example on how to do it with the BMI sumstats:

Code
#Example command to run the munge function on the BMI sumstats

command = 'munge_sumstats \
    --sumstats input/ldsc/bmi_yengo_2018.txt \
    --a1 Tested_Allele \
    --out input/ldsc/bmi_yengo_2018_munged \
    --merge-alleles ./reference_data/w_hm3.snplist'

os.system(command)
*********************************************************************
* LD Score Regression (LDSC)
* Version 3.0.1
* (C) 2014-2019 Brendan Bulik-Sullivan and Hilary Finucane
* Broad Institute of MIT and Harvard / MIT Department of Mathematics
* GNU General Public License v3
*********************************************************************
Call: 
./munge_sumstats.py \
--sumstats input/ldsc/bmi_yengo_2018.txt \
--out input/ldsc/bmi_yengo_2018_munged \
--merge-alleles ./reference_data/w_hm3.snplist \
--a1 Tested_Allele 

{'SNP': 'SNP', 'Tested_Allele': 'A1', 'Other_Allele': 'A2', 'BETA': 'BETA', 'P': 'P', 'N': 'N'}
Interpreting column names as follows:
SNP:    Variant ID (e.g., rs number)
Tested_Allele:  Allele 1, interpreted as ref allele for signed sumstat.
Other_Allele:   Allele 2, interpreted as non-ref allele for signed sumstat.
BETA:   [linear/logistic] regression coefficient (0 --> no effect; above 0 --> A1 is trait/risk increasing)
P:  p-Value
N:  Sample size

Reading list of SNPs for allele merge from ./reference_data/w_hm3.snplist
Read 1217311 SNPs for allele merge.
Reading sumstats from input/ldsc/bmi_yengo_2018.txt into memory 5000000 SNPs at a time.
.WARNING: 48 SNPs had P outside of (0,1]. The P column may be mislabeled.
 done
Read 2334001 SNPs from --sumstats file.
Removed 1315341 SNPs not in --merge-alleles.
Removed 0 SNPs with missing values.
Removed 0 SNPs with INFO <= 0.9.
Removed 0 SNPs with MAF <= 0.01.
Removed 48 SNPs with out-of-bounds p-values.
Removed 0 variants that were not SNPs or were strand-ambiguous.
1018612 SNPs remain.
Removed 0 SNPs with duplicated rs numbers (1018612 SNPs remain).
Removed 0 SNPs with N < 472784.6666666667 (1018612 SNPs remain).
Median value of BETA was 0.0, which seems sensible.
Removed 0 SNPs whose alleles did not match --merge-alleles (1018612 SNPs remain).
Writing summary statistics for 1217311 SNPs (1018612 with nonmissing beta) to input/ldsc/bmi_yengo_2018_munged.sumstats.gz.

Metadata:
Mean chi^2 = 8.986
Lambda GC = 3.61
Max chi^2 = 1480.885
61727 Genome-wide significant SNPs (some may have been removed by filtering).

Conversion finished at Sat Aug 22 16:52:55 2026
Total time elapsed: 23.47s
0
Code
#You can now adapt this command and munge the other sumstats 
 #add more lines after --sumstats if needed

#ADHD

command = 'munge_sumstats \
--N-cas-col ___ --N-con-col ___ \
--sumstats ./input/ldsc/ADHD2022_iPSYCH_deCODE_PGC.meta \
--out ./output/ldsc/adhd_pgc_2022_munged \
--merge-alleles reference_data/w_hm3.snplist'

os.system(command)
Code
#Educational attainment

command = 'munge_sumstats \
--sumstats ./input/ldsc/educational_attainment_xia_2025.tsv \
--a1 ___ --a2 ___ \
--snp ___ \
--p ___ \
--N-col ___ \
--out ./output/ldsc/educational_attainment_xia_2025_munged \
--merge-alleles reference_data/w_hm3.snplist'

os.system(command)
Code
#Age at first birth 

command = 'munge_sumstats \
--sumstats input/ldsc/year_at_first_birth_mills_2020.tsv \
--a1 ___ --a2 ___ \
--snp ___ \
--p ___ \
--N ___ \
--out output/ldsc/year_at_first_birth_mills_2020_munged \
--merge-alleles reference_data/w_hm3.snplist'

os.system(command)
Code
#Depression (ALREADY written because it has default parameters names)

command = 'munge_sumstats \
--sumstats input/ldsc/depression_pgc_2025.tsv \
--out output/ldsc/depression_pgc_2025_munged \
--merge-alleles reference_data/w_hm3.snplist'

os.system(command)
Note

A good practice is to check the output log of munge_stats make sure that at least 200,000 SNPs remain in the munged file for each trait

3.1 3. Run LDSC to estimate the h2-SNP for each trait

Now that the sumstats are harmonized, we can calculate the h2-SNP for each trait using ldsc. The function takes as input the munged sumstats, the LD scores for a list of reference SNPs and the list of reference SNPs.

Code
#Example of command for BMI

command = 'ldsc \
--h2 input/ldsc/bmi_yengo_2018_munged.sumstats.gz \
--ref-ld-chr reference_data/eur_w_ld_chr/ \
--w-ld-chr reference_data/eur_w_ld_chr/ \
--n-blocks 200 \
--out output/ldsc/bmi_yengo_2018_h2'

os.system(command)
Code
#You can now adapt this command to calculate h2 for the other traits

#ADHD

command = 'ldsc \
--h2 input/ldsc/___ \
--ref-ld-chr reference_data/eur_w_ld_chr/ \
--w-ld-chr reference_data/eur_w_ld_chr/ \
--n-blocks 200 \
--out output/ldsc/adhd_pgc_2022_h2'

os.system(command)
Code
#Educational attainment

command = 'ldsc \
--h2 input/ldsc/___ \
--ref-ld-chr reference_data/eur_w_ld_chr/ \
--w-ld-chr reference_data/eur_w_ld_chr/ \
--n-blocks 200 \
--out output/ldsc/educational_attainment_xia_2025_h2'

os.system(command)
Code
#Year at first birth

command = 'ldsc \
--h2 input/ldsc/___ \
--ref-ld-chr reference_data/eur_w_ld_chr/ \
--w-ld-chr reference_data/eur_w_ld_chr/ \
--n-blocks 200 \
--out output/ldsc/year_at_first_birth_mills_2020_h2'

os.system(command)
Code
#Depression

command = 'ldsc \
--h2 input/ldsc/___ \
--ref-ld-chr reference_data/eur_w_ld_chr/ \
--w-ld-chr reference_data/eur_w_ld_chr/ \
--n-blocks 200 \
--out output/ldsc/depression_pgc_2025_h2'

os.system(command)

3.2 4. Analyse and present results

You now have calculated the SNP-based heritability for each of the trait. We will extract that information from the log file, and present the results in a table.

Code
#Create a list with the file paths
path_list = ["output/ldsc/adhd_pgc_2022_h2.log", 
             "output/ldsc/bmi_yengo_2018_h2.log", 
             "output/ldsc/educational_attainment_xia_2025_h2.log", 
             "output/ldsc/year_at_first_birth_mills_2020_h2.log", 
             "output/ldsc/depression_pgc_2025_h2.log"]

#Create a list of trait names
trait_list = ["adhd", "bmi", "educational_attainment", "year_first_birth", "depression"]

#Initiate an empty list 
rows = []

#We iterate over all the files 
for i in range(len(path_list)):

    # Read only the 26th line (index 25) -> line where h2 is
    with open(path_list[i], "r") as f:
        for j, line in enumerate(f):
            if j == 25:
                words = line.strip().split()

                if len(words)>=6:
                    # Extract 5th and 6th "words" (indices 4 and 5) -> corresponds to h2 and se
                    word5 = words[4] 
                    word6 = words[5].strip("()")

                    #Store in rows
                    rows.append({
                        "trait":trait_list[i],
                        "h2_observed": word5,
                        "se": word6
                    })
                break
   
        
# Store in a DataFrame
df = pd.DataFrame(rows)

df
Note

Question. Based on the result table, are the results in line with what you expect/the literature?