1000 Genomes: sample notebook
A worked notebook for 1000 Genomes, with 11 code cells and the output each one printed. On Scigantic it opens in a hosted JupyterLab with the dataset already mounted, so nothing is downloaded first.
- Provider
- National Institutes of Health
- License
- Custom (see documentation)
- Stored at
- Amazon S3, s3://1000genomes (us-east-1)
- Access
- Free and public. No account with the data provider is needed.
The notebook
1000 Genomes Project — Phase 3 variant archive
The 1000 Genomes Project (International Genome Sample Resource, IGSR) is the reference catalog of human genetic variation. The Phase 3 release catalogs variants across 2,504 individuals from 26 populations grouped into 5 super-populations (African, Admixed American, East Asian, European, South Asian).
The AWS Open Data bucket s3://1000genomes/ mirrors the full project: raw sequencing reads, alignments, and per-chromosome VCFs are all here. This notebook focuses on the Phase 3 genotype VCFs under release/20130502/, which are the release most external tools (PLINK, bcftools, population-genetics courses) reference by default.
The bucket is FUSE-mounted read-only at /mnt/archive, so every VCF is accessible as a local file path. We use cyvcf2 (pre-installed on the genomics image) for streaming VCF reads — it's the fastest Python path and doesn't need to decompress the whole file.
import os
from pathlib import Path
mount_path = Path(os.environ.get('SCIGANTIC_MOUNT_PATH', '/mnt/archive'))
bucket = os.environ.get('SCIGANTIC_BUCKET_NAME', '1000genomes')
release = mount_path / 'release' / '20130502'
print(f'Archive: 1000 Genomes Project (Phase 3)')
print(f'Source: s3://{bucket}/')
print(f'FUSE mount: {mount_path}')
print(f'Release: {release}')
Output:
Archive: 1000 Genomes Project (Phase 3) Source: s3://1000genomes/ FUSE mount: /mnt/archive Release: /mnt/archive/release/20130502
1. Population breakdown
The panel file integrated_call_samples_v3.20130502.ALL.panel maps each sample to its population code and super-population. It's a small TSV — read it with pandas.
import pandas as pd
panel = pd.read_csv(
release / 'integrated_call_samples_v3.20130502.ALL.panel',
sep='\t',
)
print(f'Samples: {len(panel):,}')
print(f'Columns: {list(panel.columns)}')
print()
print('Super-population counts:')
print(panel['super_pop'].value_counts().to_string())
Output:
Samples: 2,504 Columns: ['sample', 'pop', 'super_pop', 'gender', 'Unnamed: 4', 'Unnamed: 5'] Super-population counts: super_pop AFR 661 EAS 504 EUR 503 SAS 489 AMR 347
# All 26 populations with their super-pop grouping and sample count.
(
panel
.groupby(['super_pop', 'pop'])
.size()
.rename('n')
.reset_index()
.sort_values(['super_pop', 'pop'])
)
Output:
super_pop pop n 0 AFR ACB 96 1 AFR ASW 61 2 AFR ESN 99 3 AFR GWD 113 4 AFR LWK 99 5 AFR MSL 85 6 AFR YRI 108 7 AMR CLM 94 8 AMR MXL 64 9 AMR PEL 85 10 AMR PUR 104 11 EAS CDX 93 12 EAS CHB 103 13 EAS CHS 105 ...
2. Stream a variant region with cyvcf2
VCFs are per-chromosome and tabix-indexed (the .tbi file sits next to each .vcf.gz). cyvcf2 uses the index to jump straight to a genomic region — we don't pay for the rest of the chromosome even though the file is ~1 GB.
Example region: LCT (lactase) on chromosome 2, around 136.5 Mb. This gene carries the classic rs4988235 variant driving adult lactase persistence — allele frequencies differ dramatically between super-populations.
from cyvcf2 import VCF
chr2_vcf = release / 'ALL.chr2.phase3_shapeit2_mvncall_integrated_v5a.20130502.genotypes.vcf.gz'
vcf = VCF(str(chr2_vcf))
print(f'VCF samples: {len(vcf.samples):,}')
region = '2:136500000-136620000'
variants = list(vcf(region))
print(f'Variants in {region}: {len(variants):,}')
print()
print('First 5:')
for v in variants[:5]:
print(f' {v.CHROM}:{v.POS} {v.REF}>{",".join(v.ALT)} {v.ID or "."}')
Output:
VCF samples: 2,504 Variants in 2:136500000-136620000: 3,402 First 5: 2:136500172 C>T rs531175347 2:136500201 A>C rs552490605 2:136500208 G>A rs564629861 2:136500223 G>C rs146955578 2:136500298 A>G rs546652091
3. Allele frequency by super-population for rs4988235
rs4988235 is the canonical lactase-persistence variant — ancestral G, derived A. The derived allele is common in Europeans, rare in East Asians. We compute the allele frequency of the derived allele in each super-population directly from the genotype matrix.
import numpy as np
target = next((v for v in vcf('2:136608646-136608646') if v.ID == 'rs4988235'), None)
if target is None:
print('rs4988235 not found in expected position — spot-check the VCF coords.')
else:
# gt_types: 0=HOM_REF, 1=HET, 2=HOM_ALT, 3=UNKNOWN
gt = target.gt_types
print(f'Variant: {target.CHROM}:{target.POS} {target.REF}>{",".join(target.ALT)} {target.ID}')
print()
sample_to_pop = dict(zip(panel['sample'], panel['super_pop']))
rows = []
for superpop in sorted(panel['super_pop'].unique()):
mask = np.array([sample_to_pop.get(s) == superpop for s in vcf.samples])
sub = gt[mask]
# count derived alleles: HOM_REF=0 derived, HET=1, HOM_ALT=2.
derived = np.where(sub == 3, 0, sub).sum()
total = (sub != 3).sum() * 2
rows.append((superpop, int(mask.sum()), derived / total if total else float('nan')))
freq = pd.DataFrame(rows, columns=['super_pop', 'n_samples', 'derived_af']).round(3)
print(freq.to_string(index=False))
Output:
Variant: 2:136608646 G>A rs4988235
super_pop n_samples derived_af
AFR 661 0.021
AMR 347 0.163
EAS 504 0.000
EUR 503 0.274
SAS 489 0.097
5. Ancestry PCA with PLINK2 (bcftools and plink2 are installed on this image)
cyvcf2 above is great for streaming a region, but for a real population-genetics workflow -- LD-pruning and PCA -- you want plink2. This does it on a 10 Mb slice of chr22 (fast, for the demo); drop the --from-bp/--to-bp range for a real genome-wide analysis.
import subprocess
from pathlib import Path
WORKDIR = Path('/tmp/ancestry_pca')
WORKDIR.mkdir(exist_ok=True)
chr22_vcf = release / 'ALL.chr22.phase3_shapeit2_mvncall_integrated_v5a.20130502.genotypes.vcf.gz'
def run(cmd):
r = subprocess.run(cmd, shell=True, capture_output=True, text=True)
if r.returncode != 0:
raise RuntimeError(r.stderr[-3000:])
return r.stdout
# Biallelic SNPs only, in a 10 Mb window; --set-all-var-ids gives every variant a
# unique id (chrom:pos:ref:alt) since 1000 Genomes' own VCF IDs aren't unique,
# which plink2's LD-pruning step requires.
run(
f"plink2 --vcf {chr22_vcf} --chr 22 --from-bp 20000000 --to-bp 30000000 "
f"--snps-only just-acgt --max-alleles 2 --set-all-var-ids '@:#:$r:$a' "
f"--make-pgen --out {WORKDIR}/ref_snps"
)
run(f"plink2 --pfile {WORKDIR}/ref_snps --indep-pairwise 500kb 0.1 --out {WORKDIR}/ref_pruned")
run(
f"plink2 --pfile {WORKDIR}/ref_snps --extract {WORKDIR}/ref_pruned.prune.in "
f"--pca 10 --out {WORKDIR}/ref_pca"
)
ref_pca = pd.read_csv(WORKDIR / 'ref_pca.eigenvec', sep='\t').rename(columns={'#IID': 'sample'})
ref_pca = ref_pca.merge(panel[['sample', 'pop', 'super_pop']], on='sample')
print(f'{len(ref_pca):,} samples, PCA on {sum(1 for _ in open(WORKDIR / "ref_pruned.prune.in")):,} LD-pruned variants')
ref_pca.head()
Output:
2,504 samples, PCA on 18,407 LD-pruned variants
sample PC1 PC2 PC3 PC4 PC5 PC6 \
0 HG00096 0.008236 0.023814 -0.016365 0.007854 -0.005123 -0.003614
1 HG00097 0.007818 0.024597 -0.020948 0.013520 -0.000287 0.000456
2 HG00099 0.008254 0.023803 -0.016685 0.014040 0.000143 0.002423
3 HG00100 0.008340 0.023828 -0.019180 0.012256 -0.000468 0.007221
4 HG00101 0.007433 0.023332 -0.021136 0.010258 -0.000792 0.009711
PC7 PC8 PC9 PC10 pop super_pop
0 -0.000664 -0.002682 -0.010250 0.001103 GBR EUR
1 -0.004536 0.010209 0.000582 0.002787 GBR EUR
2 0.001368 0.002407 -0.007206 0.007934 GBR EUR
3 0.002190 -0.005550 -0.014818 -0.008472 GBR EUR
4 -0.008442 0.007580 -0.009369 0.005889 GBR EUR
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(7, 6))
for sp, grp in ref_pca.groupby('super_pop'):
ax.scatter(grp['PC1'], grp['PC2'], s=10, alpha=0.6, label=sp)
ax.set_xlabel('PC1')
ax.set_ylabel('PC2')
ax.set_title('1000 Genomes, chr22:20-30 Mb, colored by super-population')
ax.legend()
plt.show()
6. Place genomes on the 1000 Genomes PCA without merging
Section 5 recomputes a PCA from scratch. To place *new* genomes, you do not need to merge them with 1000 Genomes or rerun anything: we computed the reference PCA once, on the 2,504 unrelated samples at GRCh38 positions over LD-pruned common SNPs, and placing a genome on it is one matrix product over those sites.
Before your own data, here is the method on five real DRAGEN v4.2 hard-filtered VCFs, the file a DRAGEN germline run writes. They come from the public 1000 Genomes DRAGEN reanalysis bucket, and the five people are relatives of panel members who are *not* in the panel themselves, so this is an honest out-of-panel test. bcftools streams each 430 MB file once and keeps only the panel sites, which takes under a minute per genome.
import sys, urllib.request, zipfile
from pathlib import Path
PANEL_URL = 'https://scigantic-public-assets.s3.amazonaws.com/reference/1kg-pca-grch38/v1/1kg-pca-grch38-v1.zip'
PANEL = Path.home() / '1kg-pca-grch38'
if not (PANEL / 'loadings.npy').exists():
zpath = PANEL.with_suffix('.zip')
urllib.request.urlretrieve(PANEL_URL, zpath)
zipfile.ZipFile(zpath).extractall(PANEL)
zpath.unlink()
sys.path.insert(0, str(PANEL))
from project import load_panel, project_vcfs, plot
kg = load_panel(str(PANEL))
print(f"Panel: {len(kg['sites']):,} SNPs x {len(kg['reference']):,} reference genomes, {len(kg['pcs'])} PCs")
Output:
Panel: 132,554 SNPs x 2,504 reference genomes, 10 PCs
DRAGEN = 'https://1000genomes-dragen-v4-2-7.s3.amazonaws.com/data/individuals/hg38_alt_masked_graph_v3'
labels = {'HG00405': 'CHS (EAS)', 'HG00552': 'PUR (AMR)', 'HG01502': 'IBS (EUR)',
'HG01881': 'ACB (AFR)', 'HG02492': 'PJL (SAS)'}
demo = project_vcfs([f'{DRAGEN}/{s}/{s}.final.hard-filtered.vcf.gz' for s in labels], kg)
demo['1KG label'] = demo['sample'].map(labels)
demo[['sample', '1KG label', 'nearest_superpop', 'nearest_share', 'nearest_pop', 'coverage', 'PC1', 'PC2']]
Output:
sample 1KG label nearest_superpop nearest_share nearest_pop coverage \
0 HG00405 CHS (EAS) EAS 1.0 CHS 0.9999
1 HG00552 PUR (AMR) AMR 1.0 PUR 0.9999
2 HG01502 IBS (EUR) EUR 1.0 TSI 0.9999
3 HG01881 ACB (AFR) AFR 1.0 ASW 0.9999
4 HG02492 PJL (SAS) SAS 1.0 PJL 0.9999
PC1 PC2
0 -68.037753 107.123023
1 -30.725001 -65.711946
2 -39.702239 -85.111442
3 94.870646 2.927457
4 -47.099611 -36.416909
import matplotlib.pyplot as plt
plot(demo, kg)
plt.show()
Read the table this way: nearest_superpop is the most common super-population among the 15 nearest reference genomes on PCs 1 to 6, and nearest_share is how many of the 15 agree. It measures genetic similarity to the 1000 Genomes groups, not identity. Admixed genomes (the PUR and ACB samples above) sit between clusters and get a lower share, and a genome from a population 1000 Genomes does not sample is still assigned its nearest group, so look at the share and the plot, not only the label. coverage is the share of panel sites the file informed.
7. Your own cohort
Point MY_VCFS at your files and rerun. It works on single-sample or multi-sample VCFs, chr1 or 1 contig names, and multi-allelic records. Two practical routes:
- Files on your machine or a NAS. You only need the panel sites. Download panel_regions.tsv and run bcftools view -R panel_regions.tsv -Oz -o sample.panel.vcf.gz sample.vcf.gz locally (if your VCF names contigs 1, 2, ... rather than chr1, strip the prefix first: sed 's/^chr//' panel_regions.tsv). Each whole-genome VCF shrinks to a few MB, small enough to upload with My Data (it lands in your home folder).
- Files in a cloud bucket. Use Connect a bucket and point MY_VCFS at the mount. The projection streams each file once from the mount and keeps only the panel sites, so nothing is copied into your home folder.
A whole-genome VCF that lists only variant sites (DRAGEN and GATK hard-filtered output) says nothing about sites where a sample matches the reference, so a panel site missing from the file counts as homozygous REF. That is right for whole genomes and wrong for exomes, gene panels and arrays: pass absent='missing' for those. Merging your own samples first is optional; if you do, use bcftools merge -0 so absent sites become 0/0 rather than missing.
import glob
# Edit this to point at your files. The default picks up VCFs uploaded with My Data.
MY_VCFS = sorted(set(glob.glob(str(Path.home() / '*.vcf.gz'))
+ glob.glob(str(Path.home() / 'additional-datasets' / '**' / '*.vcf.gz'), recursive=True)))
if not MY_VCFS:
print('No VCFs found yet. Upload them with My Data, or set MY_VCFS to their paths, then rerun this cell.')
else:
mine = project_vcfs(MY_VCFS, kg) # absent='missing' for exome, panel or array data
mine.to_csv(Path.home() / 'my_cohort_1kg_pcs.tsv', sep='\t', index=False)
print(mine['nearest_superpop'].value_counts().to_string())
plot(mine, kg)
plt.show()
Output:
No VCFs found yet. Upload them with My Data, or set MY_VCFS to their paths, then rerun this cell.
4. Where to go from here
- Alignments (BAM/CRAM) — per-sample alignments live under phase3/data/ /alignment/. Use pysam.AlignmentFile to stream reads; pair the .bam with its .bai.
- Structural variants — the Phase 3 structural variant release is at phase3/integrated_sv_map/.
- High-coverage (30x) re-calls — 1000G_2504_high_coverage/ holds the NYGC re-sequencing of all 3,202 samples including trios. On this bucket the joint-genotyped VCFs are under working/20201028_3202_raw_GT_with_annot/ (about 26 GB per chromosome for chr22; the .annotated.vcf.gz files there are sites-only). The per-chromosome files under working/20201028_3202_phased/ are 0-byte placeholders, so do not point a pipeline at them.
- PLINK format — if you prefer BED/BIM/FAM, cyvcf2 output pipes cleanly into plink2 --vcf ... --make-bed; plink2 is pre-installed on the genomics image.
- Single-variant lookups — for quick queries across many variants, build a small SQLite index keyed on CHROM,POS,ID rather than re-scanning the VCF each time.
Anything you write goes to your home directory (~) — the archive mount is read-only.
Run it
Open this notebook to run it, see the dataset page for the full description, or browse the full catalog.