Genomic intervals

Coordinates, file formats and interval arithmetic on the command line and in R

Epigenetics

About this lecture

In RNA-seq you counted reads per gene: the annotation told you where to count. In epigenomics there is no such list. Peaks, domains, CpG islands, loops and methylated regions are all intervals that you find in the data, and most of the analysis is arithmetic on intervals: which overlap, how far apart, how many more than by chance.

  • Coordinates: genome builds, and the two numbering systems (0-based and 1-based) that cause most off-by-one bugs.
  • File formats: BED and narrowPeak, GTF, bedGraph and bigWig.
  • Interval operations with bedtools on the command line.
  • Is an overlap meaningful? Comparing with shuffled intervals.
  • The same operations in R with GenomicRanges.

Everything is an interval

  • A genomic interval is a chromosome, a start, an end and (sometimes) a strand: chr21:33,000,000–33,002,000 (+).
  • Genes, exons, promoters, peaks, CpG islands, methylated regions, reads, Hi-C loop anchors: all intervals.
  • Questions about biology become questions about intervals: do my peaks overlap promoters? which gene is nearest? how many reads fall in each peak?

A coordinate only means something with its genome build

  • The reference genome is updated: GRCh37/hg19 (2009) and GRCh38/hg38 (2013) are both still used. The same gene has different coordinates in each.
  • Chromosome names differ too: UCSC writes chr1, Ensembl/NCBI write 1. Mitochondria: chrM vs MT.
  • Always check that all your files use the same build and the same naming. Mixing builds gives no error, just wrong answers.
  • This course uses GRCh38 with chr names throughout.

Two ways to number the bases

  • 1-based, closed [s, e]: the first base is 1, and the end base is included. Used by GTF/GFF, SAM, VCF, and by genome browsers when they display a position.
  • 0-based, half-open [s, e): count the gaps between bases from 0; the interval runs from gap s to gap e. Used by BED, bedGraph, BAM internally, and most programming languages.
  • The bases CGT above are chr1:3-5 in 1-based, chr1 2 5 in BED. Length: e - s + 1 in 1-based, e - s in BED.

Getting it wrong

  • Copy a 1-based position from a VCF into a BED file without subtracting 1 and your SNP sits one base to the right: next to the CpG you wanted, not on it.
  • For peaks of hundreds of bp an off-by-one hardly matters. For single bases (SNPs, CpGs, TSSs, Tn5 insertion sites) it changes the answer.
  • Tools convert for you when they read a format they know (rtracklayer::import adds 1 to BED starts). Trouble starts when you write files by hand with awk or paste.

BED and narrowPeak

  • BED: tab-separated; three required columns chrom start end (0-based), then optional name score strand and more.
  • narrowPeak (BED6+4): what peak callers like MACS write. Adds signalValue (enrichment), pValue and qValue (as -\log_{10}), and peak: the summit, as an offset from start.
  • broadPeak is the same without the summit column, for broad domains.

Annotation: GTF

  • Gene annotation (GENCODE, Ensembl) comes as GTF/GFF: one line per feature (gene, transcript, exon, CDS, …), 1-based closed.
  • Column 9 holds attributes: gene_id, gene_name, gene_type, transcript_id, ….
  • A gene has several transcripts, often with different start sites. “The TSS of a gene” is a choice: the gene start, every transcript start, or a canonical transcript.

Strand: where is upstream?

  • Coordinates always increase left to right along the + strand. A gene on the − strand is read right to left.
  • TSS = start for a + gene, end for a − gene. Upstream of a − gene means higher coordinates.
  • “Promoter = 2 kb upstream to 500 bp downstream of the TSS” therefore needs the strand. GenomicRanges::promoters() handles it; bedtools slop -s -l 2000 -r 500 too.

Signal tracks: bedGraph and bigWig

  • A signal track gives a number for every position: reads piled up, divided by a normaliser (CPM, fold change over input).
  • bedGraph: a BED-like text file, chrom start end value, one line per run of constant value.
  • bigWig: the same data in a compressed, indexed binary file, with precomputed summaries at several zoom levels. A browser can fetch just the region on screen, even over the internet.

The file formats at a glance

content text format indexed binary coordinates
intervals (peaks, regions) BED, narrowPeak bigBed 0-based
signal per position bedGraph, wig bigWig 0-based
aligned reads SAM BAM, CRAM 1-based in SAM text
annotation GTF, GFF3 (tabix-indexed .gz) 1-based
variants VCF BCF 1-based in VCF text

A genome browser shows intervals and signals together

  • Real data: GM12878 CTCF ChIP-seq on chr21. Top: the fold-change bigWig. Middle: the narrowPeak intervals, with summits. Bottom: GENCODE genes.
  • Peaks are where the signal is high; a summit sits at the top of each peak.
  • IGV (desktop or igv.js in a browser) loads all of these formats directly.

The basic interval operations

  • intersect: the parts of A that overlap B (or: the A intervals that overlap any B, -u).
  • subtract / -v: A minus B, or the A intervals that overlap no B.
  • merge: collapse overlapping (or nearby, -d) intervals into one.
  • closest: for each A, the nearest B and the distance.
  • slop / flank: grow intervals, or make windows next to them. complement: the gaps.

What counts as an overlap?

  • By default, one shared base is an overlap. A 1 bp touch between a 2 kb peak and a promoter counts.
  • Ask for a minimum: bedtools intersect -f 0.5 (at least 50% of A), -r (reciprocal), or a minimum number of bases (minoverlap in R).
  • Report choices: one line per pair (default), each A once (-u), or count of B per A (-c). These give different numbers of “overlapping peaks”.

Sorting and merging

  • Most tools that walk along the genome need input sorted by chromosome, then start: sort -k1,1 -k2,2n.
  • bedtools merge collapses overlapping intervals: e.g. peaks from two replicates into one consensus set.
  • Merging loses the per-interval information unless you ask for it (-c 5 -o max, keep the maximum score).

Nearest feature and distance

  • bedtools closest -a peaks.bed -b tss.bed -d reports, for each peak, the nearest TSS and the distance (0 if they overlap).
  • Ties (two TSSs at the same distance) give several lines per peak; -t first keeps one.
  • The distribution of distances says what kind of element a mark labels: promoter marks sit at 0, enhancer marks kilobases away.

Windows around intervals

  • slop extends each interval (e.g. ±1 kb around a summit), flank makes windows next to it (e.g. the 2 kb upstream), both strand-aware with -s.
  • Near a chromosome end, a window would run off the end: these tools need a genome file with chromosome lengths (-g hg38.chrom.sizes) and clip at the end.

bedtools on the command line

# promoter windows: 1 kb either side of each protein-coding TSS
bedtools slop -i tss.bed -g hg38.chrom.sizes -b 1000 > promoters.bed

# H3K4me3 peaks at a promoter (each peak once) vs. not
bedtools intersect -u -a h3k4me3.bed -b promoters.bed | wc -l
bedtools intersect -v -a h3k4me3.bed -b promoters.bed | wc -l

# candidate enhancers: H3K27ac peaks with no H3K4me3 peak and away from TSSs
bedtools intersect -v -a h3k27ac.bed -b h3k4me3.bed \
  | bedtools intersect -v -a - -b promoters.bed > enhancers.bed

# distance from every enhancer to its nearest TSS
sort -k1,1 -k2,2n enhancers.bed | bedtools closest -a - -b tss.bed -d -t first
  • Every command reads and writes plain text, so they chain with pipes (- means standard input).

Real data: where do the peaks sit?

  • Distance from each GM12878 peak to the nearest protein-coding TSS.
  • H3K4me3 peaks pile up at the TSS. H3K27ac is at TSSs and at distal enhancers. CTCF is mostly far from TSSs.

Is an overlap more than chance?

  • Two sets of intervals will overlap somewhat by chance, more so if they are wide or numerous. A raw overlap count is not evidence.
  • Null by shuffling: place the same intervals (same widths) at random positions, count overlaps, repeat many times. Compare the observed count with this distribution.
  • Enrichment = observed / mean of shuffled. Empirical p-value = (number of shuffles with at least the observed overlap + 1) / (number of shuffles + 1).

Real data: H3K27ac and CTCF overlap more than chance

  • Grey: overlaps between CTCF peaks and shuffled H3K27ac peaks (100 shuffles, same chromosome, same widths). Red: the observed overlap.
  • The observed overlap is far outside the shuffled distribution: the two sets are associated.

Shuffling has assumptions

  • A naive shuffle puts intervals in gaps (runs of N), centromeres and unmappable repeats, where real peaks can never be. This inflates enrichment.
  • Keep shuffled intervals on the same chromosome (-chrom) and inside the mappable, non-blacklisted genome (-incl / -excl).
  • Peaks also prefer GC-rich, gene-dense regions. The more of that structure the null ignores, the more “significant” everything looks. Choose the background with care; state it.

Intervals in R: GRanges

  • GRanges (package GenomicRanges): seqnames, ranges (start, end, width, 1-based closed), strand, and any metadata columns (mcols).
  • seqinfo holds chromosome names, lengths and genome build: R refuses to compare ranges from different builds if they are set.
  • rtracklayer::import() reads BED, narrowPeak, GTF and bigWig, and converts BED’s 0-based starts to 1-based.

findOverlaps returns pairs

hits <- findOverlaps(peaks, promoters)      # one row per overlapping pair
queryHits(hits); subjectHits(hits)          # indices into peaks and promoters
peaks[unique(queryHits(hits))]              # each peak once
overlapsAny(peaks, promoters)               # TRUE/FALSE per peak (= bedtools -u)
countOverlaps(peaks, promoters)             # number of promoters per peak (= -c)

bedtools ↔︎ GenomicRanges

task bedtools GenomicRanges
A that overlap B intersect -u subsetByOverlaps(A, B)
A that do not overlap B intersect -v A[!overlapsAny(A, B)]
all overlapping pairs intersect -wa -wb findOverlaps(A, B)
merge overlapping merge reduce(A)
nearest and distance closest -d distanceToNearest(A, B)
windows around TSS slop -s -l -r / flank promoters(A, upstream, downstream), flank(), resize()
gaps complement gaps(A)
count per interval intersect -c, coverage countOverlaps(A, B)
  • Use the command line for big files and pipelines, R for analysis, statistics and plots. The answers must agree (exercise R5).

Same bases, different numbers

  • The BED line chr1 2 5 and the GRanges chr1:3-5 are the same three bases.
  • rtracklayer::import() and export() convert in both directions. If you read a BED file with read.table() and build a GRanges yourself, add 1 to the start.

Moving between builds: liftOver

  • liftOver maps intervals from one build to another using a chain file of aligned blocks (UCSC tool; rtracklayer::liftOver in R).
  • Some intervals fail (deleted or rearranged in the new build) or split into pieces. Check how many you lose.
  • Better, when possible: re-align the raw reads to the new build, or download the data already processed in the build you need.

Summary

idea key fact
intervals chrom, start, end, strand; same build and same chromosome names in every file
0-based half-open BED, bedGraph: length = end − start; first base is 0
1-based closed GTF, SAM, VCF, GRanges, browser display: first base is 1
narrowPeak BED6 + signalValue, −log10 p, −log10 q, summit offset from start
bigWig indexed binary signal track; read only the region you need
strand TSS and upstream depend on strand; peaks have none
bedtools intersect (-u, -v, -c, -f), merge, closest, slop/flank (-g), shuffle
GenomicRanges findOverlaps, subsetByOverlaps, reduce, distanceToNearest, promoters
overlap statistics compare with shuffled intervals; the null decides the answer

Key papers (optional further reading)

Not required reading and not examined. For those who want the primary literature.