# Reading a BAM file

```elixir
Mix.install([
  {:bam, path: Path.expand("..", __DIR__)}
])
```

## What this notebook does

A BAM file is the binary form of a set of alignments. Each alignment says where one sequencing read landed on a reference sequence, which bases matched, and how confident that placement was. SAM is the same information as text. This notebook writes a three-read BAM in memory, reads it back, and asks for the reads that overlap one interval.

Positions on a `BAM.Alignment` are zero-based, which is how BAM stores them. SAM text and a samtools region such as `chr1:1-2` are one-based and inclusive. `BAM.SAM.region/1` converts that text into the zero-based half-open interval `BAM.read/3` expects.

The longer account of the formats, and a glossary, is [What SAM and BAM are for](../docs/sam-and-bam.md). The rules are [SAMv1](https://samtools.github.io/hts-specs/SAMv1.pdf).

## Write three alignments

`chr1` is 1,000 bases long. The reads land at zero-based positions 0, 1, and 50. Each one matches 4 bases.

```elixir
{:ok, header} =
  BAM.Header.new([%{name: "chr1", length: 1_000}], sort_order: "coordinate")

reads = [
  %BAM.Alignment{
    qname: "r1",
    flag: 0,
    reference: "chr1",
    pos: 0,
    mapq: 30,
    cigar: [{"M", 4}],
    sequence: "ACGT",
    quality_raw: <<20, 20, 20, 20>>
  },
  %BAM.Alignment{
    qname: "r2",
    flag: 0,
    reference: "chr1",
    pos: 1,
    mapq: 30,
    cigar: [{"M", 4}],
    sequence: "CGTA",
    quality_raw: <<20, 20, 20, 20>>
  },
  %BAM.Alignment{
    qname: "r3",
    flag: 0,
    reference: "chr1",
    pos: 50,
    mapq: 20,
    cigar: [{"M", 4}],
    sequence: "TTTT",
    quality_raw: <<20, 20, 20, 20>>
  }
]

{:ok, binary} = BAM.write({:memory, :binary}, header, reads)
byte_size(binary)
```

## Read the header

`BAM.info/1` reports the references and does not decode the alignments.

```elixir
{:ok, handle} = BAM.open({:memory, binary})
{:ok, info} = BAM.info(handle)
info.references
```

## Stream every alignment

`BAM.stream/2` yields one alignment at a time. The stream closes the handle when it finishes, including when you stop early.

```elixir
{:ok, handle} = BAM.open({:memory, binary})

names =
  handle
  |> BAM.stream()
  |> Enum.map(& &1.qname)

names
```

## Ask for one interval

The query is zero-based and half-open: positions `0` inclusive through `2` exclusive. That overlaps `r1` (positions 0 through 4) and `r2` (positions 1 through 5). `r3` starts at 50 and stays out.

The same interval written as a samtools region is `chr1:1-2`. A region query on a path uses the `.bai` file written next to the BAM.

```elixir
{:ok, region} = BAM.SAM.region("chr1:1-2")
region
```

```elixir
dir = Path.join(System.tmp_dir!(), "bam-livebook")
File.mkdir_p!(dir)
path = Path.join(dir, "three.bam")
:ok = BAM.write(path, header, reads, index: :bai, compression_level: 1)

{:ok, handle} = BAM.open(path)
{:ok, query} = BAM.read(handle, region)

query
|> Enum.map(&{&1.qname, &1.pos})
```

`r1` and `r2` overlap the start of `chr1`. `r3` does not.

## Look at one record as SAM text

SAM writes the position one-based. The BAM position `0` becomes SAM position `1`.

```elixir
{:ok, handle} = BAM.open({:memory, binary})
{:ok, header} = BAM.metadata(handle)
[first | _] = handle |> BAM.stream() |> Enum.take(1)
{:ok, line} = BAM.SAM.format_alignment(first, header)
line
```
