- SAM (Sequence Alignment/Map), BAM (Binary Alignment/Map), and CRAM are widely used formats for storing and exchanging DNA and RNA sequence alignment data. They describe how sequencing reads are aligned to a reference genome or other reference sequences. These formats are fundamental to next-generation sequencing (NGS) analysis, whole-genome sequencing, whole-exome sequencing, RNA sequencing, variant detection, genome assembly, and many other bioinformatics applications. They preserve information about read sequences, genomic positions, alignment quality, sequencing quality scores, and relationships between paired-end reads.
- Sequence alignment is a central step in many bioinformatics workflows. After sequencing, raw reads are typically stored in FASTQ format. An alignment program, such as BWA-MEM2, Bowtie2, or STAR, compares these reads with a reference genome and determines their most likely genomic locations. The resulting alignment information is stored in SAM, BAM, or CRAM format. These files allow researchers to examine mapped reads, identify mismatches and insertions or deletions, calculate coverage, detect genetic variants, and investigate gene expression.
- SAM is a text-based format that represents sequence alignment information in a structured, tab-delimited form. It is designed to be human-readable and can be inspected using standard text-processing tools. A SAM file contains a header section followed by alignment records. The header provides information about the reference sequences, alignment settings, read groups, and software used to generate the file. The alignment records describe individual sequencing reads and their mapping positions.
- A SAM file may contain several header record types. The @HD record describes the format version and sorting information. The @SQ records describe reference sequences, including their names and lengths. The @RG records identify read groups, which can represent sequencing samples, libraries, platforms, or sequencing runs. The @PG records describe the programs used to process the data. The @CO record contains free-text comments.
- A simplified SAM header looks like this:
@HD VN:1.6 SO:coordinate
@SQ SN:chr1 LN:248956422
@SQ SN:chr2 LN:242193529
@RG ID:Sample1 SM:Sample1 PL:ILLUMINA
@PG ID:aligner PN:example_aligner VN:1.0
- The VN field identifies the SAM format version, while SO indicates the sorting order. In this example, the records are declared to be coordinate-sorted. Each @SQ line provides a reference sequence name (SN) and its length (LN). The read-group record includes an identifier (ID), sample name (SM), and sequencing platform (PL). Read groups are important when combining data from multiple sequencing libraries or runs because they preserve information about the origin of reads.
- Each SAM alignment record contains eleven mandatory columns, followed by optional fields. These columns are QNAME, FLAG, RNAME, POS, MAPQ, CIGAR, RNEXT, PNEXT, TLEN, SEQ, and QUAL. QNAME identifies the sequencing read. FLAG is a bitwise integer describing the read’s mapping status and other properties. RNAME identifies the reference sequence to which the read is aligned. POS gives the leftmost mapping position on the reference, using one-based coordinates. MAPQ represents mapping quality. CIGAR describes the alignment structure. RNEXT identifies the reference sequence of the next read in a pair, PNEXT gives the position of that read, and TLEN describes the observed template length when applicable. SEQ contains the read sequence, and QUAL contains its base quality scores.
- A simplified SAM alignment record is shown below:
READ001 99 chr1 1000 60 50M = 1150 200 ATGCGTACGTAGCTAGCTAGCTAGCTAGCTAGCTAGCTAGCTAGCTAGCT IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII
- This example represents a read named READ001 aligned to chromosome 1 at position 1000. The FLAG value is 99, MAPQ is 60, and the CIGAR string 50M indicates that 50 read bases are aligned to the reference using the M operation. The = symbol in RNEXT indicates that the mate is mapped to the same reference sequence as the current read. PNEXT gives the mate’s position, and TLEN records the template length according to the aligner’s convention. The sequence and quality fields contain the read’s nucleotide sequence and corresponding quality characters. The example is illustrative rather than a complete sequencing record.
- The FLAG column is particularly important because it encodes several alignment properties as a combination of binary bits. These properties include whether a read is paired, whether it is properly paired, whether the read or its mate is unmapped, whether the read is aligned to the reverse strand, whether it is the first or second read in a pair, and whether it is a secondary or supplementary alignment. Since multiple properties can be represented simultaneously, the FLAG value is calculated by adding the corresponding bit values.
- Some commonly used SAM FLAG values are shown below:
| FLAG bit value | Meaning |
| 1 | Read is paired |
| 2 | Read is mapped in a proper pair |
| 4 | Read itself is unmapped |
| 8 | Mate is unmapped |
| 16 | Read is aligned to the reverse strand |
| 32 | Mate is aligned to the reverse strand |
| 64 | First read in a pair |
| 128 | Second read in a pair |
| 256 | Secondary alignment |
| 512 | Fails platform or vendor quality checks |
| 1024 | PCR or optical duplicate |
| 2048 | Supplementary alignment |
- These bits can be combined. For example, a FLAG value of 99 represents a paired read, a properly paired alignment, a read whose mate is mapped to the same reference sequence, the first read in the pair, and a read aligned in the forward orientation. A FLAG value of 147 commonly represents the corresponding second read aligned in the reverse orientation in a typical inward-facing paired-end alignment. The exact interpretation of any FLAG value should be determined by examining its individual bits rather than relying on the number alone.
- MAPQ represents the mapping quality assigned by an aligner. It is commonly defined on a Phred-like scale related to the probability that the reported mapping position is incorrect. Higher values generally indicate greater confidence in the alignment. However, MAPQ values are aligner-dependent, and different software programs may calculate or assign them differently. A MAPQ of 0 often indicates an ambiguous or low-confidence mapping, while a value such as 60 is commonly used by some aligners to represent very high confidence. MAPQ should not be confused with base quality, which describes confidence in individual nucleotide calls.
- The CIGAR (Concise Idiosyncratic Gapped Alignment Report) string describes how the read sequence aligns to the reference sequence. It represents matches, mismatches, insertions, deletions, skipped reference regions, soft clipping, hard clipping, padding, and sequence-match operations. Common CIGAR operations include M, I, D, N, S, H, P, =, and X. The M operation indicates alignment of a read base to a reference base but does not distinguish between a match and a mismatch. The I operation represents inserted read bases, while D represents deleted reference bases. N represents a skipped region of the reference, commonly used for introns in RNA sequencing alignments. S represents soft-clipped read bases that remain in the sequence field, while H represents hard-clipped bases that are excluded from the stored sequence. P represents padding, and = and X explicitly indicate matching and mismatching bases, respectively.
- For example, the CIGAR string 30M2I18M indicates that 30 read bases align to the reference, followed by an insertion of two read bases, and then another 18 aligned bases. The CIGAR string 25M100N25M can represent a spliced RNA read in which two aligned segments are separated by a 100-base skipped region of the reference, often corresponding to an intron. These operations allow alignment software and downstream tools to reconstruct the relationship between the read and the reference genome.
- The optional fields in SAM records provide additional alignment information. Each optional field generally contains a two-character tag, a data type, and a value. Common tags include NM for edit distance, MD for mismatch and deletion information, AS for alignment score, RG for read-group identification, NH for the number of reported alignments for a read, and SA for supplementary alignment information. Other tags may describe barcode sequences, molecular identifiers, platform-specific information, or additional alignment statistics. The availability and interpretation of optional tags depend on the aligner and downstream software.
- BAM is the binary representation of SAM. It stores essentially the same alignment information but in a compact binary structure rather than readable text. BAM files are generally much smaller and faster to process than uncompressed SAM files, making them suitable for large sequencing datasets. BAM is commonly compressed using the BGZF (Blocked GNU Zip Format) compression method, which supports efficient access to individual portions of a file. Unlike ordinary gzip compression, BGZF divides the data into independently compressed blocks, allowing software to retrieve specific genomic regions without decompressing the entire file.
- BAM is widely used in bioinformatics pipelines because it combines efficient storage with support for indexing and rapid retrieval. After alignment, SAM files are often converted to BAM, sorted by genomic coordinate, and indexed. Coordinate sorting arranges alignment records according to their reference sequence and genomic position. An index allows software to locate alignments within selected genomic regions without scanning the entire file.
- CRAM is another format for storing sequence alignment data. It was developed to provide more efficient compression than conventional BAM files, particularly for large-scale sequencing projects. CRAM uses specialized compression techniques that exploit the relationship between sequencing reads and the reference genome. Because many aligned read bases are identical to the corresponding reference bases, CRAM can avoid storing all sequence information explicitly and instead encode differences from the reference. It can also compress alignment coordinates, quality scores, and other fields using specialized methods.
- CRAM commonly relies on access to the reference genome used during alignment. The reference is important for reconstructing sequence information that has been represented through differences from the reference. CRAM can also support reference-free or embedded-reference approaches in certain workflows, but these may affect file size and portability. The reference sequence and its version should therefore be recorded and made available when required. Using an incorrect reference genome can prevent successful decoding or lead to incorrect sequence reconstruction.
- The three formats differ mainly in their representation, storage efficiency, and intended use. SAM is human-readable and useful for inspection and debugging. BAM is a compressed binary format that is widely supported by alignment analysis tools. CRAM generally offers greater compression and is particularly useful for long-term storage and large-scale sequencing projects. All three formats can represent alignment records, but their practical handling differs.
| Feature | SAM | BAM | CRAM |
| Representation | Text | Binary | Binary |
| Storage efficiency | Low | High | Usually very high |
| Human readability | Yes | No | No |
| Compression | Usually uncompressed text | BGZF compression | Specialized compression |
| Reference dependency | No | No for ordinary decoding | Commonly reference-dependent |
| Indexing | Not commonly indexed | Supported | Supported |
| Regional retrieval | Inefficient without specialized processing | Efficient with index | Efficient with index |
| Typical use | Inspection and exchange | Routine analysis | Efficient storage and analysis |
- The SAM, BAM, and CRAM formats are closely associated with alignment software such as BWA-MEM2, Bowtie2, HISAT2, STAR, Minimap2, and other mapping programs. These aligners produce alignment records that can be stored in SAM or written directly in BAM or CRAM using appropriate options. The resulting files are then processed using tools such as SAMtools, Picard, and GATK. These tools support sorting, indexing, filtering, duplicate marking, read-group management, and other alignment-processing operations.
- SAMtools is one of the most widely used command-line toolkits for working with SAM, BAM, and CRAM files. It provides commands for viewing, converting, sorting, indexing, filtering, and analyzing alignment data. The view command can display alignments, convert between formats, and filter records. The sort command arranges alignments by coordinate or query name. The index command creates an index for coordinate-sorted BAM or CRAM files. The flagstat command produces summary statistics based on alignment flags, while idxstats reports alignment counts for reference sequences.
- The following command converts a SAM file into BAM format:
samtools view -b -o aligned.bam aligned.sam
- The -b option requests BAM output, and -o specifies the output filename. To sort the BAM file by genomic coordinates, use:
- samtools sort -o aligned.sorted.bam aligned.bam
- The sorted BAM file can then be indexed:
samtools index aligned.sorted.bam
- This creates an index file that allows rapid access to alignments from selected genomic regions. Depending on the SAMtools version and the reference sequence lengths, the index may be created in BAI or CSI format. CSI supports larger reference coordinate ranges than the traditional BAI index.
- Alignments from a particular chromosome or genomic region can be retrieved using:
samtools view aligned.sorted.bam chr1:100000-200000
- The command extracts alignments overlapping the specified region. The BAM index must be available, and the chromosome name must match the reference sequence names in the file.
- A basic alignment summary can be generated using:
samtools flagstat aligned.sorted.bam
- This command reports statistics such as the total number of records, mapped reads, properly paired reads, and duplicate records where relevant flags are present. It is useful for assessing alignment results, although a complete quality assessment requires additional metrics and an understanding of the sequencing experiment.
- CRAM files can be generated from a coordinate-sorted BAM file using a suitable reference genome:
samtools view \
-C \
-T reference.fa \
-o aligned.cram \
aligned.sorted.bam
The -C option requests CRAM output, and -T supplies the reference genome. A CRAM index can be generated with:
samtools index aligned.cram
- When reading a CRAM file, the appropriate reference genome must be available unless the file contains sufficient reference information for decoding. The reference assembly and sequence identifiers should match those used during CRAM generation.
- Read filtering is another common operation in alignment processing. For example, researchers may want to exclude unmapped reads, secondary alignments, supplementary alignments, or low-quality mappings. SAMtools provides flag-based filtering options for these purposes.
# Exclude unmapped reads
samtools view -b -F 4 \
aligned.sorted.bam \
-o mapped.bam
# Retain reads with mapping quality of at least 30
samtools view -b -q 30 \
aligned.sorted.bam \
-o high_quality.bam
# Exclude unmapped, secondary, and supplementary alignments
samtools view -b -F 2308 \
aligned.sorted.bam \
-o primary_mapped.bam
- The value 2308 combines the FLAG bits for unmapped reads (4), secondary alignments (256), and supplementary alignments (2048). Filtering decisions should be based on the analytical objective. For example, supplementary alignments may be important when studying structural variants, while secondary alignments may provide useful information about reads that map to multiple genomic locations.
- In Python, the pysam package provides an interface to SAMtools and HTSlib functionality. It supports reading, writing, converting, sorting, indexing, and querying SAM, BAM, and CRAM files. The following example opens a BAM file and displays selected alignment information.
pip install pysam
import pysam
with pysam.AlignmentFile(
“aligned.sorted.bam”,
“rb”
) as bam:
for read in bam.fetch(“chr1”, 100000, 200000):
print(
read.query_name,
read.reference_name,
read.reference_start,
read.mapping_quality,
read.cigarstring
)
- The fetch method retrieves alignments overlapping a specified genomic region. In this Python interface, genomic region arguments use zero-based, half-open coordinates, even though SAM alignment records store POS using one-based coordinates. An index is required for efficient regional retrieval.
- The following example converts a SAM file to BAM and creates a sorted, indexed BAM file using pysam.
import pysam
pysam.view(
“-b”,
“-o”, “aligned.bam”,
“aligned.sam”,
catch_stdout=False
)
pysam.sort(
“-o”,
“aligned.sorted.bam”,
“aligned.bam”
)
pysam.index(“aligned.sorted.bam”)
- The pysam.AlignmentFile interface can also be used to create alignment summaries and inspect individual records. For example, the following code counts mapped and unmapped records:
import pysam
mapped = 0
unmapped = 0
with pysam.AlignmentFile(
“aligned.sorted.bam”,
“rb”
) as bam:
for read in bam.fetch(until_eof=True):
if read.is_unmapped:
unmapped += 1
else:
mapped += 1
print(“Mapped records:”, mapped)
print(“Unmapped records:”, unmapped)
- This counts alignment records rather than necessarily counting distinct original sequencing fragments. Paired-end reads, secondary alignments, and supplementary alignments can affect the relationship between record counts and the number of sequenced DNA fragments.
- In R, Bioconductor packages such as Rsamtools, GenomicAlignments, and GenomicRanges provide tools for reading, filtering, and analyzing alignment data. Rsamtools supports access to SAM, BAM, and CRAM files, while GenomicAlignments provides structures and functions for working with aligned sequencing reads. GenomicRanges supports genomic interval operations and can be used to connect alignments with gene annotations.
- The following example installs and loads the required Bioconductor packages:
if (!requireNamespace(“BiocManager”, quietly = TRUE)) {
install.packages(“BiocManager”)
}
BiocManager::install(c(
“Rsamtools”,
“GenomicAlignments”,
“GenomicRanges”
))
A BAM file can be inspected using Rsamtools:
library(Rsamtools)
bam_file <- “aligned.sorted.bam”
bam_header <- scanBamHeader(bam_file)
print(bam_header)
- The ScanBamParam function can be used to specify which genomic regions and alignment fields should be retrieved. The following example reads alignments from a selected region:
library(Rsamtools)
param <- ScanBamParam(
which = GRanges(
“chr1”,
IRanges(100000, 200000)
)
)
reads <- scanBam(
“aligned.sorted.bam”,
param = param
)
print(reads)
The GenomicAlignments package can import alignment records into a GAlignments object:
library(GenomicAlignments)
alignments <- readGAlignments(
“aligned.sorted.bam”
)
head(alignments)
- These tools allow researchers to integrate sequencing alignments with gene annotations, genomic ranges, and other biological datasets. For large files, regional retrieval and selective import are generally more efficient than loading every alignment into memory.
- Alignment sorting and indexing are essential for many downstream applications. Coordinate-sorted BAM and CRAM files are required by numerous genome browsers and variant-analysis tools because they enable efficient access to reads from particular genomic regions. Query-name sorting, by contrast, groups records by read name and is useful for workflows that process paired reads together. The appropriate sorting order depends on the downstream application, and an index should only be used with a file sorted in a compatible order.
- Duplicate marking is another important alignment-processing step. PCR amplification can generate multiple sequencing reads originating from the same original DNA fragment. Optical duplicates can also arise from sequencing instrument imaging processes. These duplicate reads may bias variant detection and other analyses if they are counted as independent observations. Tools such as Picard MarkDuplicates and SAMtools markdup can identify and mark duplicate records using alignment positions and other information. Duplicate marking generally sets the duplicate FLAG bit rather than necessarily deleting the reads. Whether duplicates should be excluded or retained depends on the experiment and analytical objective.
- Read groups are important when multiple sequencing libraries or samples are combined. They preserve information about the sequencing platform, library, sample, and read group. Incorrect or missing read-group information can affect downstream analysis, particularly in workflows that model sequencing batches, recalibrate base quality scores, or combine multiple datasets. Researchers should ensure that each read group has an appropriate identifier and that its metadata accurately reflects the source of the reads.
- SAM, BAM, and CRAM files are used in many areas of bioinformatics. In whole-genome and whole-exome sequencing, aligned reads are processed to identify single-nucleotide variants, insertions, deletions, and structural variants. In RNA sequencing, alignment files help identify exon junctions, quantify gene expression, and investigate alternative splicing. In ChIP-seq and ATAC-seq, aligned reads are used to identify enriched genomic regions and accessible chromatin. In metagenomics, alignment files can support the identification and quantification of reads matching reference genomes. In genome assembly and long-read sequencing, alignment formats are used to compare reads with reference sequences, evaluate assemblies, and investigate structural differences.
- Several quality-control measures are important when evaluating alignment files. Researchers should examine the proportion of mapped reads, mapping-quality distributions, mismatch rates, coverage depth, insert-size distributions, duplicate rates, and properly paired reads where relevant. RNA-seq analyses should also examine splice-junction alignment and the distribution of reads across exonic, intronic, and intergenic regions. Tools such as samtools, Picard, Qualimap, and MultiQC can help summarize alignment quality. No single statistic is sufficient to establish that an alignment is biologically reliable.
- The reference genome is a critical part of alignment interpretation. The chromosome names and coordinates in a SAM, BAM, or CRAM file refer to particular reference sequences. A file aligned against one genome assembly should not be treated as if it were aligned against another assembly. The reference sequence identifiers and lengths in the SAM header should be checked against the intended genome. When transferring alignments between genome assemblies, specialized remapping or coordinate-conversion methods may be required. Simply changing chromosome names or coordinates without a valid transformation can produce incorrect results.
- Another important consideration is the difference between alignment records and sequencing reads. A single read can produce more than one alignment record when it maps to multiple genomic locations or has supplementary alignments. Paired-end sequencing produces records for individual reads, and some files also contain secondary or supplementary records. Consequently, the number of SAM or BAM records is not always equal to the number of original sequencing reads or DNA fragments. Downstream analysis should use the appropriate flags and counting methods to avoid double-counting.
- For long-term data management, BAM and CRAM are generally more practical than uncompressed SAM because of their smaller file sizes and indexing capabilities. CRAM can provide substantial storage savings, particularly for large human sequencing datasets, but reference management becomes important. The reference assembly, software versions, compression settings, and any required reference files should be documented. Checksums can be used to verify file integrity, and the original sequencing files should be retained according to the project’s data-management requirements.
- SAM, BAM, and CRAM are standardized alignment formats that support the exchange and analysis of sequencing data across bioinformatics software. SAM provides a readable representation of alignment records, BAM offers compressed binary storage and efficient access, and CRAM provides advanced compression for large sequencing datasets. Understanding their headers, alignment fields, flags, CIGAR operations, mapping quality, sorting, indexing, and reference requirements is essential for reliable sequencing analysis. Their integration with tools such as SAMtools, HTSlib, pysam, Rsamtools, and GenomicAlignments forms an important part of modern bioinformatics workflows.