Exons, aligned reads and binding sites are all intervals on a chromosome. Learn the BED format and its 0-based coordinates, find overlaps with bedtools, and turn a BAM file into coverage tracks for a genome browser.
In Aligning reads to a genome you made a sorted, indexed BAM file for each sample. Every read in it now has an address: a chromosome, a start and an end. This lesson is about working with addresses like these directly, so that you can ask which reads fall in which genes, how deeply each base is covered, and how to draw that coverage in a genome browser.
Intervals and the BED format
A genomic interval is a stretch of a chromosome, given by three things: the chromosome name, a start and an end. An exon is an interval. So is an aligned read, a region where a protein binds DNA, or a stretch of the genome that a gene panel targets. Much of genomics comes down to comparing two lists of intervals: which reads overlap which exons, which binding sites sit near which genes, which variants fall inside which targeted regions.
The simplest file for intervals is BED (Browser Extensible Data). It is plain text, one interval per line, with tab-separated columns. The first three columns are required: chromosome, start and end. Three optional columns often follow: a name, a score and a strand (+ or -). A file with those six columns is often called BED6. Further columns exist, for example to draw exons as thick and thin blocks in a browser, but most tools only need the first three or six.
Counting from zero, or from one
The detail that causes most trouble is how positions are numbered. BED is 0-based and half-open: the first base of a chromosome is position 0, and the end position is not part of the interval. GTF and GFF files, the annotation formats from Module 2 and Counting reads per gene, are 1-based and closed: the first base is position 1, and both the start and the end are included. SAM and BAM positions, as you saw in column 4 of samtools view, are 1-based too, and so is the VCF format you will meet in Module 5.
So the same 100 bases at the very start of a chromosome are written 1 100 in a GTF file and 0 100 in a BED file. To convert from GTF to BED, subtract 1 from the start and leave the end alone. The length of a BED interval is simply end − start; the length of a GTF feature is end − start + 1. Both give 100 here.
Making a BED file from the practice annotation
The practice annotation from Counting reads per gene is a GTF file. The command below keeps its exon lines and writes them as BED6, with the gene ID as the name.
conda activate hts
conda install -c conda-forge -c bioconda bedtools
mkdir -p intervals
awk 'BEGIN{OFS="\t"} $3=="exon" {
match($0, /gene_id "[^"]+"/); id = substr($0, RSTART+9, RLENGTH-10)
print $1, $4-1, $5, id, ".", $7 }' data/practice_genes.gtf \
| sort -k1,1 -k2,2n > intervals/exons.bed
head -n 3 intervals/exons.bedWhat this does
conda installadds bedtools to the hts environment from From sample to reads. bedtools is a set of small programs, each doing one kind of interval arithmetic.- The
awkprogram keeps lines whose third column is exon.matchfinds the text gene_id "…" in the line, andsubstrkeeps only what sits between the quotes: 9 characters for gene_id " are skipped at the start and 1 for the closing quote at the end. print $1, $4-1, $5, id, ".", $7writes chromosome, start minus one, end, gene ID, an empty score (.) and strand. The $4-1 is the whole conversion from 1-based to 0-based.sort -k1,1 -k2,2nsorts by chromosome, then by start as a number. Several bedtools commands need sorted input, and sorting once now saves errors later.
The first lines should show chrP, a start one lower than the matching GTF line, the same end, a gene ID such as PRG001, a dot and a strand. Compare one line with the GTF by eye; a single check like this catches most conversion mistakes.
Worked example · converting and measuring one exon
BED: start 10,000 − 1 = 9,999 · end 10,305 → length 10,305 − 9,999 = 306
a read at SAM position 10,300 with CIGAR 100M covers 10,300–10,399 → it overlaps the last 6 bases
Step by step. The GTF interval includes both ends, so its length needs the extra 1. In BED the start drops by one and the length is end minus start, with no correction, and the answer is the same 306 bases. The read starts at 10,300 (1-based) and covers 100 bases, so it ends at 10,300 + 100 − 1 = 10,399. Its overlap with the exon is from 10,300 to 10,305: 10,305 − 10,300 + 1 = 6 bases.
What the answer means. The two systems describe the same bases; only the bookkeeping differs. Mistakes happen when a number is copied from one system into a file of the other without converting, which shifts every interval by one base. One base sounds harmless, but it can move a variant out of an exon or a splice site into an intron.
Go deeper: why half-open intervals are convenient
Half-open intervals make arithmetic simple. The length is end − start with no extra 1. Two intervals that touch, such as 0 100 and 100 200, share a boundary but no base, so splitting a region into windows never counts a base twice. An interval whose start equals its end has length zero and marks a point between two bases, which is a natural way to describe where an insertion happens.
1-based closed numbering matches how people talk: "the first base", "bases 1 to 100". That is why annotation and variant formats, which people read, tend to use it, while formats designed mainly for programs tend to use 0-based half-open numbering. Neither is wrong; each file states which one it uses in its specification.
Overlaps with bedtools
The central question for two interval lists is overlap: do two intervals share at least one base? bedtools intersect answers it for every pair. It takes a file with -a and a file with -b, and by default prints the part of each -a interval that overlaps something in -b. A few options change what you get back, and choosing the right one matters more than anything else in this section.
bedtools merge -i intervals/exons.bed -c 4 -o distinct > intervals/exonic.bed bedtools intersect -a aligned/ctrl_1.bam -b intervals/exonic.bed -u | samtools view -c - bedtools intersect -a aligned/ctrl_1.bam -b intervals/exonic.bed -v | samtools view -c - bedtools closest -a intervals/regions.bed -b intervals/exonic.bed -d | head -n 5
What this does
bedtools mergejoins intervals that overlap or touch into one. Many genes have several transcripts that share exons, so the exon list repeats the same bases many times; merging gives each exonic base once.-c 4 -o distinctkeeps column 4, the gene IDs, listing each distinct name once per merged interval.bedtools intersectcan read a BAM file as-a. With-u("unique") it writes each read that overlaps any exon once, however many exons it touches; with-vit writes the reads that overlap none. The output is BAM, sosamtools view -c -counts the reads arriving on the pipe (the - means "read from the pipe").bedtools closestreports, for each interval in-a, the nearest interval in-b, and with-dadds the distance in bases (0 when they overlap). Here regions.bed stands for any list of regions of your own, for example the peaks you will call in Module 5. Both files must be sorted.
Reading the output
The first count is the number of reads that touch at least one exon, the second the number that touch none. Dividing the first by the number of aligned reads, which samtools view -c -F 4 aligned/ctrl_1.bam reports (-F 4 leaves out unaligned reads), gives the share of reads that are exonic. For this RNA-seq practice sample, simulated from the annotated genes, nearly all reads should be exonic. On real RNA-seq data a small share falls in introns and between genes, and a large share there is a warning sign: it can mean genomic DNA in the RNA sample, as Counting reads per gene noted for the Unassigned_NoFeatures line.
| Option | What it changes |
|---|---|
| -u / -v | Report each -a interval once if it overlaps anything / only if it overlaps nothing. |
| -wa -wb | Write the whole -a interval and the whole -b interval it overlaps, side by side. |
| -f 0.5 | Count an overlap only if it covers at least half of the -a interval. |
| -s | Count an overlap only when both intervals are on the same strand. |
How to read this table
Each row is an option of bedtools intersect. The default, with none of them, trims each -a interval to the overlapping part, which is useful for measuring how many bases overlap but surprising if you expected whole intervals back. -wa -wb is the option for "which gene is each region in?", because it puts both intervals on one line. A minimum overlap such as -f 0.5 stops a read that only grazes an exon by one base from counting as exonic. -s matters for stranded data, in the sense explained in Counting reads per gene: two genes on opposite strands can overlap, and only the strand tells their reads apart.
These operations are the building blocks of much larger questions. Which variants fall in coding exons? Intersect the variants with exons. Which binding sites lie within a few thousand bases of a gene's start? Use closest, or make a window around each start and intersect. Which regions are shared by two replicates? Intersect one replicate's list with the other's. The same three or four commands answer all of them.
Coverage: how many reads cover each base
Depth, or coverage at a base, is the number of reads that cover that base. It is the measure behind variant calling, where a variant needs enough reads to be trusted, and behind every coverage track you see in a genome browser. There are three common ways to compute it, depending on whether you want one number per base, one row per interval or a track for a browser.
samtools depth -a -r chrP:10200-10300 aligned/ctrl_1.bam | head -n 5 bedtools coverage -a intervals/exonic.bed -b aligned/ctrl_1.bam | head -n 3 bedtools genomecov -ibam aligned/ctrl_1.bam -bg -split | sort -k1,1 -k2,2n > intervals/ctrl_1.bedGraph samtools faidx data/practice_genome.fa cut -f 1,2 data/practice_genome.fa.fai > intervals/chrom.sizes conda install -c conda-forge -c bioconda ucsc-bedgraphtobigwig bedGraphToBigWig intervals/ctrl_1.bedGraph intervals/chrom.sizes intervals/ctrl_1.bw
What this does
samtools depthprints three columns: chromosome, position (1-based) and depth.-rlimits it to one region, which uses the BAM index, and-aalso prints positions with zero depth, which are otherwise left out.bedtools coverageadds four columns to each interval in-a: the number of reads that overlap it, the number of its bases covered by at least one read, its length, and the fraction of it that is covered.bedtools genomecov -bgwrites a bedGraph: BED-style intervals, each with the depth that is constant along it, so long runs of equal depth take one line.-splittreats the two blocks of a spliced read separately, so the intron it skips is not counted as covered.samtools faidxindexes the genome FASTA, and the first two columns of the index give each chromosome's name and length, the chrom.sizes file the next tool needs.bedGraphToBigWig, a UCSC tool packaged on Bioconda, turns the bedGraph into a bigWig: a compressed, indexed binary file. A browser such as IGV reads only the part of a bigWig it is showing, so even whole-genome tracks open quickly.
The -split option is easy to forget and matters only for RNA-seq. Without it, a read with CIGAR 90M351N10M, the spliced read from Aligning reads to a genome, would be treated as covering all 451 genome bases, intron included, and the coverage track would show reads where there are none. For DNA sequencing, which has no spliced reads, the option makes no difference.
Raw depth also depends on how many reads a sample has, for the same reason as the raw counts in Counting reads per gene. To compare tracks from samples of different depth, scale each one, for example with -scale set to one million divided by the sample's number of mapped reads, so that each track shows reads per million. The Python tool deepTools (bamCoverage) does the counting, scaling and bigWig writing in one step and is widely used for ChIP-seq and ATAC-seq tracks.
bedtools is described by Quinlan and Hall (2010, Bioinformatics). The bigWig and bigBed formats come from Kent et al. (2010, Bioinformatics), at UCSC, and the BED format itself now has a formal specification maintained by the GA4GH alongside the SAM and VCF specifications on the hts-specs site. Tools disagree on details such as whether reads that only touch an interval's edge count as overlapping, so in a methods section name the tool, its version and the exact options, for example the minimum overlap fraction and whether strand was required.
Common mistakes
- Copying coordinates between a GTF, VCF or SAM file and a BED file without subtracting or adding 1.
- Comparing files whose chromosome names differ, such as chr1 and 1: bedtools then finds no overlaps and reports no error.
- Running closest or merge on unsorted files.
- Forgetting
-splitwhen making coverage from RNA-seq reads. - Comparing raw coverage between samples that were sequenced to different depths.
Key point
Know which coordinate system each file uses, convert once at the point where you make the BED file, and check one interval by eye. After that, overlaps and coverage are a handful of bedtools commands.
For example, a gene panel's target list usually arrives as a BED file. Intersecting your variant calls with it, after checking that both use the same genome build and chromosome names, tells you at once which calls lie inside the regions the panel was designed to read and which lie outside, where coverage is often too thin to trust.
Further reading · Module 4The bedtools documentation: every command with worked examples. · UCSC file format FAQ: BED, bedGraph and bigWig described column by column. · All reading for this course
Check your understanding
1. A GTF exon runs from 201 to 300. How is it written in a BED file?
2. Which bedtools command reports the nearest gene to each region, with the distance?
3. Why use -split with bedtools genomecov on RNA-seq reads?