| name | samtools-bam-processing |
| description | CLI toolkit for SAM/BAM/CRAM: sort, index, convert, filter, QC alignments. Core commands: view, sort, index, flagstat, stats, depth, markdup, merge. Required between alignment and variant/peak calling. Use pysam for Python-native BAM access; deeptools for normalized coverage tracks. |
| license | MIT |
samtools — SAM/BAM/CRAM Alignment Toolkit
Overview
samtools is the standard command-line toolkit for processing sequence alignment files in SAM, BAM, and CRAM formats. It handles the complete alignment file lifecycle: format conversion, coordinate sorting, index creation, quality control statistics, read filtering, duplicate marking, and multi-file merging. samtools is a near-universal component of NGS pipelines between alignment (STAR, BWA) and downstream analysis (variant calling, peak calling, coverage).
When to Use
- Sorting BAM files by coordinate after alignment (required before indexing)
- Indexing sorted BAM files for random access and region queries
- Converting between SAM, BAM, and CRAM formats to save storage
- Generating alignment QC metrics: mapping rates, insert sizes, per-chromosome stats
- Filtering reads by mapping quality, FLAG bits, or genomic regions
- Marking or removing PCR duplicates before variant calling
- Merging multiple BAM files from different lanes or samples
- Calculating per-base depth or coverage breadth for target regions
- Use
pysam instead for Python-native BAM manipulation in custom scripts
- Use
deeptools bamCoverage instead when you need normalized bigWig coverage tracks
- Use
mosdepth instead for whole-genome per-base depth (faster, parallelized)
Prerequisites
- Installation: samtools 1.17+ recommended
- Input requirements: SAM/BAM/CRAM files; CRAM requires FASTA reference
- Companion tools:
samtools faidx for FASTA indexing; samtools sort before samtools index
Check before installing: The tool may already be available in the current environment (e.g., inside a pixi / conda env). Run command -v samtools first and skip the install commands below if it returns a path. When running inside a pixi project, invoke the tool via pixi run samtools rather than bare samtools.
conda install -c bioconda samtools
brew install samtools
samtools --version | head -1
Quick Start
samtools sort -@ 8 -o sorted.bam input.bam
samtools index sorted.bam
samtools flagstat sorted.bam
Core API
Module 1: BAM/SAM I/O and Format Conversion
Convert between SAM/BAM/CRAM formats and extract subsets.
samtools view -b -h input.sam -o output.bam
samtools view -C -T reference.fa input.bam -o output.cram
samtools view -q 20 -F 4 input.bam -o filtered.bam
samtools view -h sorted.bam "chr1:1000000-2000000" -o region.bam
samtools view -c -F 4 input.bam
samtools fastq -@ 4 -1 R1.fastq.gz -2 R2.fastq.gz -0 unpaired.fastq.gz input.bam
samtools fasta input.bam > reads.fasta
samtools view -r SAMPLE_001 multi_rg.bam -o sample001.bam
Module 2: Sorting and Indexing
Organize BAM files for efficient random access.
samtools sort -@ 8 -m 2G input.bam -o sorted.bam
samtools sort -n -@ 8 input.bam -o namesorted.bam
samtools index sorted.bam
samtools index -c sorted.bam
samtools collate -o collated.bam input.bam
Module 3: Quality Control and Statistics
Generate alignment QC metrics and coverage reports.
samtools flagstat sorted.bam
samtools idxstats sorted.bam
samtools stats -r reference.fa sorted.bam > full_stats.txt
grep "^SN" full_stats.txt | cut -f2,3
samtools coverage sorted.bam
samtools depth -b target_regions.bed sorted.bam > depth.txt
samtools stats -S RG sorted.bam > per_rg_stats.txt
Module 4: Read Filtering and FLAG Operations
Filter reads using SAM FLAG bits for specific subsets.
samtools view -f 2 -F 4 sorted.bam -o proper_pairs.bam
samtools view -f 64 sorted.bam -o R1.bam
samtools view -F 2304 sorted.bam -o primary.bam
samtools view -L regions.bed -b sorted.bam -o regions.bam
Module 5: Duplicate Handling
Mark or remove PCR duplicates before variant calling.
samtools collate -@ 8 -o collated.bam input.bam
samtools fixmate -m -@ 8 collated.bam fixmated.bam
samtools sort -@ 8 -o sorted.bam fixmated.bam
samtools markdup -@ 8 sorted.bam marked.bam
samtools index marked.bam
samtools flagstat marked.bam | grep "duplicates"
samtools markdup -d 2500 sorted.bam marked_novaseq.bam
samtools markdup -r sorted.bam deduped.bam
samtools markdup -s sorted.bam /dev/null
Module 6: Multi-file Operations and Region Analysis
Merge BAM files and perform region-level analysis.
samtools merge -@ 8 merged.bam lane1.bam lane2.bam lane3.bam
samtools merge -b bam_list.txt -@ 8 merged.bam
samtools merge -r merged.bam sample1.bam sample2.bam
samtools view -h merged.bam chr1 -b -o chr1.bam
Key Concepts
SAM FLAG Bits
FLAGS encode read properties as a sum of bit values. Common filtering patterns:
| Common Filter | -f (require) | -F (exclude) | Selects |
|---|
| Mapped reads | — | 4 | All aligned reads |
| Proper pairs | 2 | — | Properly paired, both mapped |
| Unique primary | — | 2308 | No secondary/supplementary/duplicate |
| R1 only | 64 | — | First-in-pair reads |
| Unmapped | 4 | — | Failed to align |
CRAM vs BAM vs SAM
| Format | Size | Speed | Requires |
|---|
| SAM | ~10× BAM | Slow I/O | Nothing |
| BAM | 1× | Fast | .bai index for random access |
| CRAM | ~0.6× BAM | Slightly slower | Reference FASTA + index |
Use CRAM for long-term storage; BAM for active analysis.
Common Workflows
Workflow 1: Post-Alignment QC and Preparation
Goal: Convert aligner output to analysis-ready BAM with QC metrics.
#!/bin/bash
SAMPLE="sample_001"
REF="reference.fa"
THREADS=8
samtools sort -@ $THREADS -o ${SAMPLE}.sorted.bam ${SAMPLE}.bam
samtools index ${SAMPLE}.sorted.bam
samtools flagstat ${SAMPLE}.sorted.bam > ${SAMPLE}.flagstat.txt
samtools stats -r $REF ${SAMPLE}.sorted.bam > ${SAMPLE}.stats.txt
samtools coverage ${SAMPLE}.sorted.bam > ${SAMPLE}.coverage.txt
samtools idxstats ${SAMPLE}.sorted.bam > ${SAMPLE}.idxstats.txt
echo "QC complete: $(grep 'mapped (' ${SAMPLE}.flagstat.txt | head -1)"
Workflow 2: Full Duplicate-Marking Pipeline
Goal: Prepare BAM for GATK or other variant callers requiring deduplicated input.
#!/bin/bash
INPUT="aligned.bam"
FINAL="deduped.bam"
THREADS=8
samtools collate -@ $THREADS -o collated.bam $INPUT
samtools fixmate -m -@ $THREADS collated.bam fixmated.bam
samtools sort -@ $THREADS -o sorted.bam fixmated.bam
samtools markdup -@ $THREADS -s sorted.bam $FINAL
rm collated.bam fixmated.bam sorted.bam
samtools index $FINAL
samtools flagstat $FINAL | grep "duplic"
Key Parameters
| Parameter | Command | Default | Range/Options | Effect |
|---|
-@ | Most | 0 | 1–N cores | Additional compression/I/O threads |
-m | sort | 768M | e.g., 2G, 4G | Memory per thread for sorting |
-q | view | 0 | 0–60 | Minimum mapping quality filter |
-f | view | 0 | FLAG bits | Include reads with ALL bits set |
-F | view | 0 | FLAG bits | Exclude reads with ANY bit set |
-b | view | — | flag | Output BAM format |
-C | view | — | flag | Output CRAM (requires -T) |
-T | view | — | FASTA path | Reference for CRAM output |
-d | markdup | 0 | 0–2500 | Optical duplicate pixel distance |
-r | markdup | — | flag | Remove duplicates (vs just mark) |
-n | sort | — | flag | Sort by read name instead of position |
-c | index | — | flag | Create CSI index (needed for chr > 512 Mb) |
Best Practices
-
Always sort before indexing: samtools index requires coordinate-sorted input. Attempting to index an unsorted BAM will fail or produce incorrect results.
-
Use -@ for all production runs: Most samtools commands are I/O-bound. Adding -@ 8 provides near-linear speedup for compression/decompression with minimal overhead.
-
Run flagstat before any analysis: samtools flagstat runs in seconds and catches alignment failures (low mapping rate, unexpected paired-end rates) before wasting time on downstream steps.
-
Use the collate → fixmate → sort → markdup pipeline: Running samtools markdup directly on coordinate-sorted BAM without fixmate produces incorrect duplicate detection. The mate information added by fixmate -m is essential.
-
Prefer CRAM for archiving: CRAM reduces storage 40-50% vs BAM with no loss. Always store the reference FASTA alongside CRAM files.
-
Use -L bed_file for targeted analyses: Restricting samtools view to BED-defined target regions (WES capture, amplicons) dramatically reduces I/O for downstream steps.
Common Recipes
Recipe: Batch Flagstat for Multiple Samples
for bam in *.sorted.bam; do
echo "=== $bam ==="
samtools flagstat $bam | grep -E "mapped|properly paired|duplicates"
done
Recipe: Extract Unmapped Reads for De Novo Assembly
samtools view -f 4 -b input.bam -o unmapped.bam
samtools fastq -@ 4 -1 unmapped_R1.fastq -2 unmapped_R2.fastq unmapped.bam
echo "Unmapped pairs ready for de novo assembly"
Recipe: Downsample BAM to Target Coverage
TOTAL=$(samtools flagstat input.bam | grep "mapped (" | head -1 | awk '{print $1}')
GENOME_SIZE=3100000000
READ_LEN=150
CURRENT_COV=$(echo "scale=1; $TOTAL * $READ_LEN / $GENOME_SIZE" | bc)
TARGET_FRAC=$(echo "scale=3; 30 / $CURRENT_COV" | bc)
echo "Current: ${CURRENT_COV}×; subsample fraction: $TARGET_FRAC"
samtools view -b -s $TARGET_FRAC input.bam -o downsampled.bam
samtools index downsampled.bam
Troubleshooting
| Problem | Cause | Solution |
|---|
[bam_index_build2] fail to index | BAM not sorted by coordinate | Sort first: samtools sort -o sorted.bam input.bam |
BAI index too large for chromosome | Chromosome > 512 Mbp | Use CSI index: samtools index -c input.bam |
CRAM: reference not found | Missing or wrong reference FASTA | Set REF_PATH env var or use -T ref.fa |
| Duplicate marking incorrect | fixmate step skipped | Run full pipeline: collate → fixmate → sort → markdup |
flagstat shows 0% properly paired | Paired-end BAM missing mate info | Run samtools fixmate to populate mate coordinates |
| Very slow sorting | Low memory per thread | Increase -m 4G; reduce -@ if memory-limited |
| Region query returns nothing | BAM not indexed or wrong coords | Run samtools index; use 1-based coords: chr1:1000-2000 |
[E::hts_open_format] fail to open | File path wrong or BAM corrupt | Verify path; test with samtools quickcheck file.bam |
Related Skills
- deeptools-ngs-analysis — normalized bigWig coverage tracks and ChIP-seq visualization downstream of samtools
- pysam-genomic-files — Python API for BAM manipulation in custom scripts
- bedtools-genomic-intervals — genomic interval operations on BAM/BED files produced by samtools
References