# Reading genomic files
```{r}
#| include: false
source("_setup.R")
```
Your collaborator sends you a file called `peaks.bed` and asks how many peaks fall on chromosome 22. Before you run any tool, look at the file. Does it have a header? Tabs between the columns? Is it compressed? Does it say `chr22` or `22`? Does it count from 0 or from 1? Get one wrong and your answer is quietly wrong, with no error message. A two-second look answers them all. **Look before you analyze.**
When I started, a 2 GB text file defeated me because Excel couldn't open it. The commands in this lesson open a file of any size in a blink, because they read only the part you ask for.
This lesson stands on its own. Every command has a **▶ Run** button that runs it in a real Linux terminal at the bottom of the page, with the files already in `data/`: nothing to install (though typing the commands yourself is better). New to the terminal? Lessons 1 and 2 cover the basics, and the [Welcome](index.qmd) page shows how to set up your own copy.
**In this lesson you'll learn**
- how to peek at any file, however big: `cat`, `head`, `tail` and `less`
- how to count lines and records with `wc`
- how to read compressed files without unpacking them: `zcat`, `zless`, `zgrep`
- how to see invisible characters such as tabs and Windows line endings
- what every column means in FASTA, FASTQ, BED, GTF, GFF3, VCF and SAM, and which formats count from 0
Every file is real: human chromosome 22, reads from Richard Lenski's evolving E. coli, the binding sites of the DNA-looping protein CTCF, and the variants of NA12878, one of the most studied people in the world, and her parents.
## Look before you analyze
Start with the people. `cat` prints a whole file, which is fine for a small one:
```{bash}
cat data/variants/samples.tsv
```
These are the 20 people in our variant files, from the 1000 Genomes Project, with their sex, population and super-population (YRI are Yoruba from Nigeria, CEU are Utah residents of European ancestry, GIH are Gujarati Indians from Houston, and so on). Now look at NA12878: her father is NA12891 and her mother is NA12892. She is the Genome in a Bottle reference sample, the genome that sequencing technologies are benchmarked against.
`head` shows the first lines of a file, `tail` the last ones, and `-n` says how many:
```{bash}
head -n 3 data/variants/samples.tsv
```
```{bash}
tail -n 2 data/variants/samples.tsv
```
The first line is a **header**: column names, not data. To skip it, put a plus sign in front of the number. `tail -n +2` means "start at line 2":
```{bash}
tail -n +2 data/variants/samples.tsv | head -n 3
```
The vertical bar `|` is a **pipe**: it sends the output of `tail` into `head` (lesson 6 is all about pipes).
`cat -n` numbers the lines, and `head` and `tail` together cut out any range. Lines 13 to 15 are the family:
```{bash}
cat -n data/variants/samples.tsv | head -n 15 | tail -n 3
```
For lines M to N, use `head -n N | tail -n K`, where K = N − M + 1: here 15 − 13 + 1 = 3. Forget the "+ 1" and you get one line too few: an **off-by-one error**, my vote for the most common mistake in bioinformatics. We'll meet it again with BED files.
### Scroll through a big file: less
`less` shows a file one screen at a time and loads only what you see, so even a 100 GB file opens instantly. `-S` stops long lines from wrapping:
```{bash}
#| eval: false
less -S data/reads/NA12878.small.sam
```
| Key | What it does |
|---|---|
| Space or `f` | Next page |
| `b` | Previous page |
| ↓ ↑ ← → | Move by a line, or sideways along long lines (with `-S`) |
| `/word` then Enter | Search for "word"; `n` jumps to the next match |
| `g` / `G` | Go to the start / the end |
| `q` | Quit |
### Count lines: wc
`wc` (**w**ord **c**ount) counts lines, words and bytes:
```{bash}
wc data/variants/samples.tsv
```
21 lines, 126 words, 586 bytes. Usually you want only the lines: `-l`. Feed the file in with `<` and you get the bare number, handy in scripts:
```{bash}
wc -l data/variants/samples.tsv
wc -l < data/variants/samples.tsv
```
21 lines: one header plus 20 people. Always ask whether a count includes a header.
::: {.callout-note title="From my blog"}
- [use linux commands to extract lines from a file by line number](https://divingintogeneticsandgenomics.com/archive/use-linux-commands-to-extract-lines-from-a-file-by-line-number/) (2013): one of my first posts. Its second `head | tail` example has exactly the off-by-one error described above: lines 16224 to 16482 are 259 lines, not 258. I made the mistake too.
:::
## Compressed files: zcat, gzip and friends
Most genomics files end in `.gz`: compressed with gzip. Why? `wc -c` counts bytes, and `zcat` decompresses a file to the screen (here, straight into `wc`). Compare the chromosome 22 gene annotation on disk and as text:
```{bash}
wc -c data/annotation/gencode.v50.chr22.gtf.gz
zcat data/annotation/gencode.v50.chr22.gtf.gz | wc -c
```
3 MB on disk, 116 MB as text: 38 times smaller, because annotation text repeats the same words over and over. And you rarely need to unpack anything: `zcat` streams the text and leaves the file alone. Pipe it into `head` to peek:
```{bash}
zcat data/annotation/gencode.v50.chr22.gtf.gz | head -n 5
```
`gzip -dc` does the same (`-d` decompress, `-c` to the screen). `zless` and `zgrep` are `less` and `grep` for compressed files. Linux and Macs have them, and they're worth knowing, but the terminal on this page doesn't. So the tour below pipes `zcat` into `grep` and `less` instead: `zcat file.gz | grep 'pattern'` prints exactly what `zgrep 'pattern' file.gz` prints.
If a program really needs the plain file, `gunzip` unpacks it. Work on a copy, and add `-k` to **k**eep the `.gz` (without it, `gunzip` deletes it):
```{bash}
cp data/reads/SRR2589044_1.fastq.gz sample.fastq.gz
gunzip -k sample.fastq.gz
wc -c sample.fastq.gz sample.fastq
```
Three times bigger unpacked. `gzip` compresses it again and replaces `sample.fastq` with `sample.fastq.gz`, so remove the old copy first:
```{bash}
rm sample.fastq.gz
gzip sample.fastq
ls
rm sample.fastq.gz
```
::: {.callout-warning title="Gotcha: zcat on a Mac"}
The `zcat` built into macOS expects old `.Z` files. On a `.gz` file it fails with `zcat: can't stat: file.gz (file.gz.Z): No such file or directory`. Use `gzip -dc file.gz` instead, which works everywhere (on a Mac, `gzcat file.gz` works too), or install GNU gzip (`brew install gzip`), or use the Codespace.
:::
A note for later: the `.vcf.gz` and `.bam` files here use **bgzip**, a gzip variant built in blocks so tools can jump to any position (lesson 10). `zcat` reads a `.vcf.gz` like any other `.gz` file.
## See the invisible: tabs and line endings
A tab and a few spaces look the same on screen, but not to a program. `cat -A` shows **a**ll the invisible characters: a tab becomes `^I`, and `$` marks the end of each line (on a Mac the built-in `cat` has no `-A`; `cat -vet` shows the same `^I`, `^M` and `$`):
```{bash}
head -n 2 data/peaks/ctcf_gm12878.narrowPeak | cat -A
```
Tabs between the columns and nothing hiding at the ends: a clean file. Now a sample sheet saved from Excel on Windows (simulated for the course, but this is how such files arrive):
```{bash}
head -n 3 data/messy/sample_sheet_from_excel.csv | cat -A
```
Every line ends in `^M$`: Windows ends lines with a carriage return (`^M`, or `\r`) plus a newline, where Linux uses only the newline. The `M-oM-;M-?` at the start is a byte-order mark, three invisible bytes Excel glues onto the first column name. So a program sees a last column called `Sequencing batch\r`, and code that asks for `Sequencing batch` finds nothing. Windows line endings have bitten me many times; lesson 8 cleans this file.
To read a table by eye, `column -t` lines up its columns. It's for your eyes only; don't save its output as data:
```{bash}
head -n 5 data/variants/samples.tsv | column -t
```
`cut -f` keeps only the columns (fields) you list, splitting on tabs; `-f 1-3` means fields 1 to 3:
```{bash}
cut -f 1-3 data/peaks/ctcf_gm12878.narrowPeak | head -n 3
```
`cut -c 1-80` keeps the first 80 **c**haracters of each line instead. Lesson 5 covers `cut` properly; below, I use it to keep outputs readable.
## FASTA: genomes and proteins
FASTA stores DNA or protein sequences. A line starting with `>` names a sequence; the lines after it, up to the next `>`, are the sequence.
```{bash}
head -n 3 data/genome/chr22.fa
```
This is human chromosome 22 from the GRCh38 reference genome. `N` means an unknown base: the short arm of chromosome 22 is a long stretch of repeats, including ribosomal RNA genes, that the reference could not assemble. The known sequence starts on line 210,202, after 10,510,000 N's (I found that line with `grep`, the subject of lesson 4). A little further in:
```{bash}
tail -n +210211 data/genome/chr22.fa | head -n 3
```
Lowercase letters are repeats, such as transposable elements, flagged by programs like RepeatMasker. This **soft-masking** keeps every base and lets the case carry the extra information. Some tools ignore it, others treat lowercase specially.
How big is it?
```{bash}
wc -l data/genome/chr22.fa
cat data/genome/chr22.fa.fai
```
1,016,371 lines: a name line, then 50 letters per line. The `.fai` index, made by `samtools faidx`, stores the name, the length (50,818,468 bases), the byte where the sequence starts (7), the letters per line (50) and the bytes per line (51, with the newline). With it, tools jump straight to any position (lesson 10).
A protein FASTA holds one record per protein. The first two proteins of E. coli REL606, the ancestor of Lenski's long-term evolution experiment (running since 1988):
```{bash}
head -n 4 data/ecoli/rel606_proteins.faa
```
The letters are amino acids; each protein starts with `M`, methionine. Every record has one `>` line, so counting `>` lines counts proteins. `grep` finds lines that contain a pattern and `-c` **c**ounts them (lesson 4 is all about `grep`):
```{bash}
grep -c '>' data/ecoli/rel606_proteins.faa
```
4,167 proteins.
::: {.callout-warning title="Gotcha: always quote the >"}
Without quotes, `grep -c > data/ecoli/rel606_proteins.faa` means "run `grep -c` and save its output into `rel606_proteins.faa`". The shell empties the file before `grep` even starts, and your protein file is gone. Quote the `>`, every time.
:::
## FASTQ: sequencing reads
FASTQ files hold the raw reads from a sequencer, with a quality score for every base. Ours come from three evolved E. coli samples from Lenski's experiment, sequenced paired-end: each DNA fragment was read from both ends, so each sample has a `_1` and a `_2` file.
```{bash}
zcat data/reads/SRR2589044_1.fastq.gz | head -n 4
```
One read takes exactly four lines:
1. `@` and the read name: read 1 of run SRR2589044, then the instrument, run number, flowcell, lane, tile and x:y position of the DNA cluster (`HWI-ST957:244:H73TDADXX:1:1101:10469:2228`). `/1` marks the first read of the pair.
2. The sequence: 150 bases.
3. A `+`, a separator.
4. The quality: one character for each base.
Look at the end of the sequence: `CTGTCTCTTATACACATCT` is the Nextera library adapter, not E. coli DNA. The fragment was shorter than 150 bases, so the sequencer read through it into the adapter. Trimming tools remove it before alignment.
Each quality character is a number, the Phred score Q: its ASCII code minus 33. Q says how likely the base is wrong: Q20 is 1 in 100, Q30 is 1 in 1,000.
| Character | `#` | `5` | `?` | `@` | `I` | `J` |
|---|---|---|---|---|---|---|
| Phred score Q | 2 | 20 | 30 | 31 | 40 | 41 |
| Chance the base is wrong | 63% | 1% | 0.1% | 0.08% | 0.01% | 0.008% |
This read is mostly `B` to `J` (Q33 to Q41): very good. Now its mate, the other end of the same fragment:
```{bash}
zcat data/reads/SRR2589044_2.fastq.gz | head -n 4
```
Same name, ending in `/2`, but full of `N`s with a `#` (Q2) under each: bases the sequencer could not call. Quality control tools catch reads like this.
To count reads, count lines and divide by 4:
```{bash}
zcat data/reads/SRR2589044_1.fastq.gz | wc -l
```
40,000 lines, so 10,000 reads.
::: {.callout-warning title="Gotcha: don't count reads by counting @"}
Every read name starts with `@`, so why not count those lines? `^@` means "lines that start with `@`":
```{bash}
zcat data/reads/SRR2589044_1.fastq.gz | grep -c '^@'
```
13,450, for a file with 10,000 reads. The problem is that `@` is also a quality character (Q31), and quality lines can start with it. Here are lines 5 to 8, the second read:
```{bash}
zcat data/reads/SRR2589044_1.fastq.gz | head -n 8 | tail -n 4
```
Its quality line starts with `@@`. Count lines and divide by 4.
:::
## BED and narrowPeak: genomic intervals
BED files store genome intervals: a chromosome, a start, an end, and optional extra columns. These are ENCODE CTCF ChIP-seq peaks, the places on chromosome 22 where CTCF binds DNA in GM12878 cells. GM12878 was made from NA12878's own blood cells, so these peaks and her variants come from the same person.
```{bash}
head -n 3 data/peaks/ctcf_gm12878.narrowPeak
```
narrowPeak is BED with 10 columns, the format that peak callers such as MACS2 write:
| Column | Name | First peak | Meaning |
|---|---|---|---|
| 1 | chrom | `chr22` | Chromosome |
| 2 | chromStart | `36856375` | Start, counting from **0** |
| 3 | chromEnd | `36856663` | End (not included) |
| 4 | name | `.` | Peak name (none here) |
| 5 | score | `1000` | 0 to 1000, used by genome browsers to shade the peak |
| 6 | strand | `.` | No strand: binding is on double-stranded DNA |
| 7 | signalValue | `317.01925` | How strong the enrichment is |
| 8 | pValue | `-1.00000` | −log10 p-value; −1 means not computed |
| 9 | qValue | `4.81020` | −log10 q-value (FDR) |
| 10 | peak | `144` | The summit, as an offset from chromStart |
::: {.callout-warning title="Gotcha: BED counts from 0"}
BED coordinates are **0-based, half-open**: the start is counted from 0 and the end is not included. So the first peak is 36856663 − 36856375 = **288** bases wide, with no "+ 1". In the 1-based counting that genome browsers display, it covers bases 36,856,376 to 36,856,663. GTF, GFF3, VCF and SAM count from 1 and include both ends. Mixing the two is the classic off-by-one error.
:::
Count the peaks in all three files at once. The `*` matches every file name that ends in `.narrowPeak` (lesson 4 explains these wildcards):
```{bash}
wc -l data/peaks/*.narrowPeak
```
789 CTCF peaks in GM12878, 1,124 in K562 (a leukemia cell line), and 395 peaks of RAD21, part of cohesin. CTCF and cohesin fold DNA into loops together, so most RAD21 peaks sit on CTCF peaks (lesson 10 counts them). Notice too that the peaks are sorted by signal, not by position; many tools need sorted input (lesson 5).
::: {.callout-note title="From my blog"}
- [The Most Common Mistake In Bioinformatics, one-off error](https://divingintogeneticsandgenomics.com/post/most-common-mistake-for-bioinformatics/) (2024)
- [You need to master it if you deal with genomics data](https://divingintogeneticsandgenomics.com/post/genomic-interval/) (2024): genomic intervals, and the Python script I wrote in 2012 to overlap peaks with genes, two years after bedtools could do it in one command
:::
## GTF and GFF3: gene annotation
GTF files say where the genes, transcripts, exons and coding sequences are. Let's find COMT, a 22q11.2 gene whose enzyme breaks down dopamine. `zcat` streams the file into `grep` (that's all `zgrep` does), and `-m 1` stops at the first match, which for a gene is its `gene` line:
```{bash}
zcat data/annotation/gencode.v50.chr22.gtf.gz | grep -m 1 'gene_name "COMT";' | cut -f 1-8
```
A GTF line has 9 tab-separated columns:
| Column | Name | COMT | Meaning |
|---|---|---|---|
| 1 | seqname | `chr22` | Chromosome |
| 2 | source | `HAVANA` | Who annotated it (HAVANA is the manual annotation team) |
| 3 | feature | `gene` | gene, transcript, exon, CDS, UTR, start_codon... |
| 4 | start | `19941371` | Start, counting from **1** |
| 5 | end | `19969975` | End, included |
| 6 | score | `.` | Not used here |
| 7 | strand | `+` | The gene reads left to right on this strand |
| 8 | frame | `.` | For CDS lines: 0, 1 or 2 bases to skip to reach the first full codon |
| 9 | attributes | see below | Everything else, as `key "value";` pairs |
Because GTF is 1-based and includes both ends, the length is end − start **+ 1**: 19969975 − 19941371 + 1 = 28,605 bases. The ninth column is long, so here are its first 100 characters:
```{bash}
zcat data/annotation/gencode.v50.chr22.gtf.gz | grep -m 1 'gene_name "COMT";' | cut -f 9 | cut -c 1-100
```
The gene ID (`ENSG00000093010.17`, version after the dot), type and name. Every transcript, exon and CDS line of COMT carries the same `gene_id`; that's how they connect. How many lines in total?
```{bash}
zcat data/annotation/gencode.v50.chr22.gtf.gz | wc -l
```
278,854 lines for one chromosome, including the 5 `##` header lines you saw earlier (later lessons count the genes, transcripts and exons). To scroll through it, pipe it into `less -S` (`q` quits; `zless -S file.gz` does the same where you have it):
```{bash}
#| eval: false
zcat data/annotation/gencode.v50.chr22.gtf.gz | less -S
```
**GFF3** is the same idea in a stricter dialect. Here is the start of Ensembl's annotation:
```{bash}
zcat data/annotation/Homo_sapiens.GRCh38.116.chr22.gff3.gz | head -n 10 | cut -c 1-100
```
The same 9 columns. Header lines start with `##` or `#!`, `###` lines separate groups of features, and column 9 holds `key=value` pairs, where `ID` and `Parent` link exons to transcripts and transcripts to genes. Now COMT again:
```{bash}
zcat data/annotation/Homo_sapiens.GRCh38.116.chr22.gff3.gz | grep -m 1 'Name=COMT;' | cut -f 1-8
```
Same coordinates, but the first column says `22`, not `chr22`.
::: {.callout-warning title="Gotcha: chr22 or 22?"}
UCSC and GENCODE say `chr22`; Ensembl says `22`; NCBI files often use the accession `NC_000022.11` (all three appear in the `Alias` of the GFF3's chromosome line above). Compare a `chr22` file with a `22` file and a tool finds nothing in common, with no error. Check the first column of every file before combining them; lesson 10 shows how to rename chromosomes safely.
:::
## VCF: variants
VCF files hold genetic variants: where a person's DNA differs from the reference. Our big VCF covers chromosome 22 from 19 to 21 million bases, the 22q11.2 region, whose deletion causes 22q11.2 deletion (DiGeorge) syndrome, the most common microdeletion in people, in about 1 in 4,000 births. A VCF starts with meta-information lines beginning with `##`:
```{bash}
zcat data/variants/1kgp.chr22_22q11.20samples.vcf.gz | head -n 4
```
Count them with `grep -c` and the pattern `^##`, "lines that start with ##":
```{bash}
zcat data/variants/1kgp.chr22_22q11.20samples.vcf.gz | grep -c '^##'
```
41 meta lines, so line 42 is the **header** line, which starts with a single `#`. Here are its first 12 columns:
```{bash}
zcat data/variants/1kgp.chr22_22q11.20samples.vcf.gz | head -n 42 | tail -n 1 | cut -f 1-12
```
Eight fixed columns, `FORMAT`, then one column per person: 29 columns for 20 people. The first three variants, skipping the long INFO column, for the first five people:
```{bash}
zcat data/variants/1kgp.chr22_22q11.20samples.vcf.gz | head -n 45 | tail -n 3 | cut -f 1-7,9-14
```
| Column | First variant | Meaning |
|---|---|---|
| CHROM | `chr22` | Chromosome |
| POS | `19000085` | Position, counting from **1** |
| ID | `22:19000085:A:G` | An ID (here chromosome:position:REF:ALT; often an rsID such as `rs4680`) |
| REF | `A` | The base in the reference genome |
| ALT | `G` | The other allele seen in these people |
| QUAL | `.` | Quality of the call (`.` means missing; not stored in this file) |
| FILTER | `.` | `PASS` or the name of a failed filter (missing here) |
| INFO | see below | Facts about the site, as `KEY=value` pairs |
| FORMAT | `GT` | What each person's column holds: here just GT, the genotype |
```{bash}
zcat data/variants/1kgp.chr22_22q11.20samples.vcf.gz | head -n 43 | tail -n 1 | cut -f 8
```
`AN=40` alleles were called (20 people, two copies each) and `AC=1` of them is a G, so `AF=0.025`. The `AF_..._unrel` values are frequencies in 2,504 unrelated 1000 Genomes people per super-population: this G is rare except in Africans (7.5%), and our one carrier, NA18488, is Yoruba.
A genotype is two alleles, one per chromosome copy: `0` is REF and `1` is ALT. So `0|0` is homozygous reference, `0|1` or `1|0` heterozygous, `1|1` homozygous ALT. `|` means **phased** (we know which copy carries which allele); `/` means unphased.
Now the family. Columns 21, 22 and 23 are NA12878, her father NA12891 and her mother NA12892:
```{bash}
zcat data/variants/1kgp.chr22_22q11.20samples.vcf.gz | head -n 47 | tail -n 6 | cut -f 2,4,5,21-23
```
At 19001039, NA12878 is `1|1`, two copies of the A, and each parent carries one (`1|0`): she got one from each. At 19001685 she is `0|1`; her father has no C (`0|0`) and her mother has one (`1|0`), so her C came from her mother. Mendel, in a text file.
How many variants? Count the lines that do **not** start with `#`; `-v` inverts the match:
```{bash}
zcat data/variants/1kgp.chr22_22q11.20samples.vcf.gz | grep -v -c '^#'
```
11,955 variants across the 20 people.
Variant callers also fill in QUAL, FILTER and per-sample details. The first variants called from NA12878's own reads:
```{bash}
zcat data/variants/NA12878.chr22_calls.vcf.gz | grep -v '^#' | head -n 6 | cut -f 1-7,9,10
```
The first is a C to T change with QUAL 137.9 that passed the filters (`PASS`). FORMAT `GT:PL:DP:AD` gives the order of the values after it: genotype `0/1` (heterozygous, unphased), PL (genotype likelihoods; skip them for now), depth DP `25` reads, and allele depths AD `17,8`: 17 reads show C and 8 show T. Rows 2 and 3 are a deletion and an insertion (REF and ALT differ in length), row 4 has two ALT alleles (`1/2`), and row 6 is homozygous: all 29 reads show the C.
## SAM and BAM: aligned reads
SAM files hold aligned reads: where each read landed on the genome and how well it fit. Header lines come first, starting with `@`:
```{bash}
head -n 5 data/reads/NA12878.small.sam | cut -c 1-90
```
`@HD`: format version, sorted by coordinate. `@PG`: the aligner (novoalign). `@SQ`: the reference, chr22, 50,818,468 bases, the same as our FASTA. `@CO`: a comment. `@RG`: the read group, with the sample name (`SM`) NA12878. Now the reads:
```{bash}
grep -v '^@' data/reads/NA12878.small.sam | head -n 3 | cut -f 1-9
```
| Column | Name | First read | Meaning |
|---|---|---|---|
| 1 | QNAME | `HISEQ1:12:H8GVUADXX:...` | Read name |
| 2 | FLAG | `99` | A number that packs yes/no facts about the read (below) |
| 3 | RNAME | `chr22` | Chromosome it aligned to |
| 4 | POS | `19949853` | Leftmost aligned position, counting from **1** |
| 5 | MAPQ | `70` | How sure the aligner is that the read belongs here (0 means it could equally belong elsewhere) |
| 6 | CIGAR | `148M` | How the read lines up with the reference (below) |
| 7 | RNEXT | `=` | Chromosome of its mate (`=` means the same one) |
| 8 | PNEXT | `19950092` | Position of its mate |
| 9 | TLEN | `387` | Length of the DNA fragment (negative for the mate on the right) |
| 10 | SEQ | | The read sequence |
| 11 | QUAL | | Its quality string, as in FASTQ |
Position 19,949,853 is inside COMT (19,941,371 to 19,969,975, from the GTF): these are NA12878's reads from her COMT gene.
**FLAG** adds up powers of two, each a yes/no fact. 99 = 1 + 2 + 32 + 64: paired (1), aligned as a proper pair (2), mate on the reverse strand (32), first read of the pair (64). The second read's 83 = 1 + 2 + 16 + 64: this time the read itself is on the reverse strand (16), and its mate is forward. Don't memorize them: [Explain SAM Flags](https://broadinstitute.github.io/picard/explain-flags.html) decodes any number.
**CIGAR** describes the alignment in counts and letters. `148M`: all 148 bases align (M is "match", mismatches included). A more interesting read, on line 67:
```{bash}
head -n 67 data/reads/NA12878.small.sam | tail -n 1 | cut -f 1-9
```
`103M4I40M1S`: 103 bases align, 4 are **I**nserted in the read (not in the reference), 40 more align, and the last base is **S**oft-clipped (in the read, but not aligned). 103 + 4 + 40 + 1 = 148, the read length.
**BAM** is the same information in compressed binary form: smaller and faster, but not text. `head -c 32` takes the first 32 bytes, and `cat -v` shows the unprintable ones:
```{bash}
head -c 32 data/reads/NA12878.chr22.bam | cat -v
```
Garbage to us. (The first two bytes, `^_M-^K`, are the "magic number" that starts every gzip file.) To read a BAM, use `samtools`, which turns it back into SAM text:
```{bash}
samtools view data/reads/NA12878.chr22.bam | head -n 2 | cut -f 1-9
samtools view -c data/reads/NA12878.chr22.bam
```
52,318 reads, covering chr22 from 19.70 to 20.00 million bases, from the TBX1 gene to COMT. Lesson 10 does much more with `samtools`.
## The formats at a glance
| Format | Extensions | Counts positions from | One record is | Count records with |
|---|---|---|---|---|
| FASTA | `.fa` `.fasta` `.faa` | (regions are given 1-based) | a `>` line plus its sequence lines | `grep -c '>' file` |
| FASTQ | `.fastq.gz` `.fq.gz` | n/a | 4 lines | `zcat file \| wc -l`, then divide by 4 |
| BED, narrowPeak | `.bed` `.narrowPeak` | **0**, end not included | 1 line | `wc -l file` (if there is no header) |
| GTF | `.gtf.gz` | 1, both ends included | 1 line | `zcat file \| grep -v -c '^#'` |
| GFF3 | `.gff3.gz` | 1, both ends included | 1 line | `zcat file \| grep -v -c '^#'` |
| VCF | `.vcf.gz` | 1 | 1 line per variant site | `zcat file \| grep -v -c '^#'` |
| SAM | `.sam` | 1 | 1 line per alignment | `grep -v -c '^@' file` |
| BAM | `.bam` | 1 (as shown by samtools) | binary | `samtools view -c file` |
## Your turn
Save each answer with `> name.txt` at the end of the command, and the box under the question ticks itself when it's right.
**1.** How many people are in `data/variants/samples.tsv`? Don't count the header. Save the number to `people.txt`.
```{=html}
<div data-sandboxbio-exercise="l03-people"></div>
```
::: {.callout-tip collapse="true" title="Solution"}
```{bash}
tail -n +2 data/variants/samples.tsv | wc -l
```
20. `tail -n +2` drops the header line before `wc -l` counts.
To tick the box, save the answer:
```{bash}
#| eval: false
tail -n +2 data/variants/samples.tsv | wc -l > people.txt
```
:::
**2.** Look at the first read of `data/reads/SRR2584863_1.fastq.gz`. What is the quality character of its very last base, and what is that base's Phred score? Save the character to `last_quality.txt` and the score to `phred.txt`.
```{=html}
<div data-sandboxbio-exercise="l03-quality"></div>
```
::: {.callout-tip collapse="true" title="Solution"}
```{bash}
zcat data/reads/SRR2584863_1.fastq.gz | head -n 4
```
It ends in `#`, Q2: that base is more likely wrong than right. Quality often drops toward the end of a read; this one ends in a long run of `#`.
To tick the box, save the answers (the quotes matter: without them, the shell reads `#` as the start of a comment):
```{bash}
#| eval: false
echo '#' > last_quality.txt
echo 2 > phred.txt
```
:::
**3.** What is the strongest CTCF peak in K562 cells (`data/peaks/ctcf_k562.narrowPeak`)? Give its position and its width in bases. Save its chromosome, start and end to `peak.txt`, and its width to `peak_width.txt`.
```{=html}
<div data-sandboxbio-exercise="l03-peak"></div>
```
::: {.callout-tip collapse="true" title="Solution"}
```{bash}
head -n 1 data/peaks/ctcf_k562.narrowPeak
```
The file is sorted by signal, so line 1 is the strongest peak: chr22, 20564140 to 20564886. BED is 0-based and half-open, so it is 20564886 − 20564140 = 746 bases wide, no "+ 1". At 20.56 million bases, it is inside the 22q11.2 region.
To tick the box, save the answers:
```{bash}
#| eval: false
head -n 1 data/peaks/ctcf_k562.narrowPeak | cut -f 1-3 > peak.txt
echo 746 > peak_width.txt
```
:::
**4.** Where is the gene TBX1 in the GENCODE annotation, and how long is it? Save its chromosome, start, end and strand to `tbx1.txt`, and its length to `tbx1_length.txt`.
```{=html}
<div data-sandboxbio-exercise="l03-tbx1"></div>
```
::: {.callout-tip collapse="true" title="Solution"}
```{bash}
zcat data/annotation/gencode.v50.chr22.gtf.gz | grep -m 1 'gene_name "TBX1";' | cut -f 1-8
```
chr22, 19756703 to 19783593, + strand. GTF is 1-based and includes both ends, so it is 19783593 − 19756703 + 1 = 26,891 bases. TBX1 is a key gene behind many features of 22q11.2 deletion syndrome, including heart defects.
To tick the box, save the answers:
```{bash}
#| eval: false
zcat data/annotation/gencode.v50.chr22.gtf.gz | grep -m 1 'gene_name "TBX1";' | cut -f 1,4,5,7 > tbx1.txt
echo 26891 > tbx1_length.txt
```
:::
**5.** At position 19002241 of the 22q11.2 VCF, which parent gave NA12878 her ALT allele? (Columns 21, 22 and 23 are NA12878, her father and her mother.) Save `father` or `mother` to `alt_parent.txt`.
```{=html}
<div data-sandboxbio-exercise="l03-parent"></div>
```
::: {.callout-tip collapse="true" title="Solution"}
```{bash}
zcat data/variants/1kgp.chr22_22q11.20samples.vcf.gz | grep -m 1 '19002241' | cut -f 2,4,5,21-23
```
NA12878 is `1|0`, her father NA12891 `1|0`, her mother NA12892 `0|0`. Her mother has no T to give, so it came from her father.
To tick the box, save the answer:
```{bash}
#| eval: false
echo father > alt_parent.txt
```
:::
**6. (Stretch)** Check the length of chromosome 22 yourself, using only `wc` and `tail` on `data/genome/chr22.fa`. Every sequence line holds 50 bases except the last one. Do you get the 50,818,468 bases that the `.fai` index reports? Save the length you work out to `chr22_length.txt`.
```{=html}
<div data-sandboxbio-exercise="l03-chr22"></div>
```
::: {.callout-tip collapse="true" title="Solution"}
```{bash}
wc -l data/genome/chr22.fa
tail -n 1 data/genome/chr22.fa | wc -c
```
1,016,371 lines minus the name line leaves 1,016,370 sequence lines. The last one has 19 bytes: 18 bases plus the newline. So 1,016,369 × 50 + 18 = 50,818,468 bases. It matches.
To tick the box, save the answer:
```{bash}
#| eval: false
echo $(( 1016369 * 50 + 18 )) > chr22_length.txt
```
:::
## Summary
- Look before you analyze: `head`, `tail`, `less -S` and `cat -A` answer most questions in seconds, whatever the file size.
- `tail -n +2` skips a header; `head -n N | tail -n K` cuts out any range of lines. Watch for off-by-one errors.
- `wc -l` counts lines. Always ask whether the count includes a header.
- Keep files compressed: `zcat`, `zless` and `zgrep` read `.gz` files directly. On a Mac, use `gzip -dc`.
- `cat -A` reveals tabs (`^I`), Windows line endings (`^M`) and other invisible problems.
- BED is 0-based and half-open; GTF, GFF3, VCF and SAM are 1-based and include both ends.
- One record is one line in BED, GTF, VCF and SAM; two or more lines in FASTA; exactly four lines in FASTQ.
- Check chromosome names (`chr22` or `22`) before you combine files.
## Cheat sheet
| Command | What it does |
|---|---|
| `cat file` | Print a whole (small) file |
| `cat -n file` | Print with line numbers |
| `cat -A file` | Show tabs as `^I`, line ends as `$`, Windows `\r` as `^M` |
| `cat -v` | Show unprintable bytes |
| `head -n 5 file` | First 5 lines |
| `head -c 32 file` | First 32 bytes |
| `tail -n 5 file` | Last 5 lines |
| `tail -n +2 file` | Everything from line 2 on (skip a header) |
| `head -n N file \| tail -n K` | The K lines that end at line N |
| `less -S file` | Scroll through a file without wrapping lines (`q` quits) |
| `wc file` | Count lines, words and bytes |
| `wc -l file` / `wc -l < file` | Count lines (with / without the file name) |
| `wc -c file` | Count bytes |
| `zcat file.gz` | Decompress to the screen; the file stays compressed |
| `gzip -dc file.gz` | Same as `zcat` (works on a Mac) |
| `zless -S file.gz` | `less` for compressed files (here: `zcat file.gz \| less -S`) |
| `zgrep -m 1 'pattern' file.gz` | First line matching a pattern in a compressed file (here: `zcat file.gz \| grep -m 1 'pattern'`) |
| `gunzip -k file.gz` | Decompress to a file, keeping the `.gz` |
| `gzip file` | Compress a file (replaces it with `file.gz`) |
| `column -t` | Line up columns for reading |
| `cut -f 1-3` | Keep tab-separated fields 1 to 3 |
| `cut -c 1-80` | Keep the first 80 characters of each line |
| `grep -c 'pattern' file` | Count lines that contain a pattern |
| `grep -v -c '^#' file` | Count lines that don't start with `#` |
| `samtools view file.bam` | Print a BAM file as SAM text |
| `samtools view -c file.bam` | Count the reads in a BAM file |