SAM, BAM, and CRAM Files

  • SAM, BAM, and CRAM are widely used file formats in bioinformatics for storing and managing sequence alignment information. They are essential in genome sequencing, RNA sequencing, variant calling, genome assembly evaluation, epigenomics, and other genomic analyses. These formats describe how sequencing reads align to a reference genome, including their genomic positions, orientations, alignment characteristics, mapping quality, and relationships with paired reads. SAM is a human-readable text format, BAM is its compressed binary counterpart, and CRAM is a reference-based compressed format designed to reduce storage requirements while preserving alignment information.
  • During DNA or RNA sequencing, sequencing platforms generate millions or billions of reads. These reads are usually stored initially in FASTQ files, which contain nucleotide sequences and their associated base quality scores. Before many downstream analyses can be performed, the reads are aligned to a reference genome or another reference sequence. Alignment programs such as BWA-MEM, Bowtie2, STAR, HISAT2, and minimap2 generate alignment records that describe where each read maps. SAM, BAM, and CRAM provide standardized ways to store these records so that different bioinformatics programs can exchange and process alignment data.
  • The SAM format, which stands for Sequence Alignment/Map, is a tab-delimited text format designed to represent sequence alignment information. It can be opened and inspected using ordinary text editors or command-line tools. A SAM file contains a header section followed by alignment records. The header provides information about the reference sequences, alignment software, and other metadata, while the alignment records describe individual reads and their mapped positions.
  • A SAM file usually contains several header record types. The @HD record describes the format version and sorting order. The @SQ record identifies reference sequences, including their names and lengths. The @RG record provides read-group information, such as sequencing sample, library, platform, and sequencing unit. The @PG record describes the program used to generate or process the alignment. The @CO record can contain comments. These header records help downstream software interpret the alignment data correctly.
  • A simplified SAM header may look 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:bwa PN:bwa VN:0.7.17

  • In this example, the header specifies SAM format version 1.6 and indicates that the alignment records are sorted by reference coordinate. The @SQ records define two reference sequences and their lengths. The read-group record identifies the sample and sequencing platform, while the program record identifies the alignment software. The reference names and lengths should correspond to the reference genome used during alignment.
  • Each SAM alignment record contains eleven mandatory fields, followed by optional fields when available. These fields provide information about the read, its alignment location, mapping quality, alignment structure, mate position, and sequence quality. Understanding these fields is important for interpreting genomic alignments and using downstream bioinformatics tools.
  • The eleven mandatory SAM fields are:

QNAME: Query template name, identifying the read or sequencing template.

FLAG: A numerical bitwise value describing alignment and read properties.

RNAME: Reference sequence name to which the read is aligned.

POS: One-based leftmost mapping position on the reference sequence.

MAPQ: Mapping quality, estimating confidence in the reported alignment position.

CIGAR: A string describing how the read aligns to the reference.

RNEXT: Reference sequence containing the mate alignment for paired reads.

PNEXT: One-based position of the mate alignment.

TLEN: Observed template length for paired reads, according to SAM conventions.

SEQ: Nucleotide sequence of the read, when stored.

QUAL: Base quality string corresponding to the sequence, when stored.

  • A simplified SAM alignment record may look like this:

read001 0 chr1 1050 60 50M * 0 0 ATGCTAGCTAGCTAGCTAGCTAGCTAGCTAGCTAGCTAGCTAGCTAGC IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII

  • This record describes a read named read001 aligned to chromosome 1 at position 1050. The FLAG value is 0, indicating that none of the listed bitwise alignment conditions are set. The MAPQ value is 60, indicating high reported mapping confidence under the aligner’s convention. The CIGAR string 50M indicates that 50 read positions are aligned to the reference. The asterisk symbols in the mate-related fields indicate that mate information is unavailable or not applicable. The sequence and quality fields contain the read bases and their corresponding quality characters.
  • The FLAG field is particularly important because it uses a bitwise system to describe alignment properties. Different bits can be combined to represent whether a read is paired, whether it is mapped, whether its mate is mapped, whether it is properly paired, and whether it represents a primary, secondary, or supplementary alignment. Common flag values include 0x1 for a paired template, 0x2 for a properly aligned pair according to the aligner’s criteria, 0x4 for an unmapped read, 0x8 for an unmapped mate, 0x10 for a read aligned to the reverse strand, 0x40 for the first segment, 0x80 for the last segment, 0x100 for a secondary alignment, and 0x800 for a supplementary alignment. These flags are useful for filtering and interpreting alignment records.
  • The CIGAR field describes the relationship between the read sequence and the reference genome. Its operations include M for alignment match or mismatch, I for insertion relative to the reference, D for deletion from the reference, N for a skipped reference region, S for soft clipping, H for hard clipping, P for padding, = for exact match, and X for mismatch. For example, the CIGAR string 20M2I28M indicates that 20 read positions align, two bases are inserted relative to the reference, and another 28 positions align. In RNA-seq alignments, the N operation commonly represents an intron skipped between two aligned exons.
  • SAM files may also contain optional tags that provide additional information. The NM tag commonly represents the edit distance between the read and reference alignment, while AS commonly stores an alignment score. The MD tag can describe mismatches and deletions relative to the reference, and the RG tag identifies the read group. Other tags may store alternative alignment scores, transcript strand information, or aligner-specific metadata. Their exact meaning and availability depend on the software that generated the file.
  • Although SAM is easy to inspect, it can require substantial storage space because it stores alignment records as text. Large sequencing projects may contain billions of alignment records, making plain-text storage inefficient. BAM was developed as a compressed binary representation of SAM. It preserves the essential alignment information but stores records in a compact format that is more efficient for computer processing and storage.
  • BAM files are generally much smaller than their equivalent uncompressed SAM files. They also support indexing, which allows software to retrieve alignments from particular genomic regions without reading the entire file. This is especially useful for genome browsers, variant callers, and regional coverage analysis. BAM files are usually compressed using BGZF, a block-based form of gzip compression that supports efficient random access.
  • Unlike SAM files, BAM files are not directly readable in ordinary text editors. They should be inspected and processed using suitable bioinformatics software, such as SAMtools, Picard, GATK, or genome browsers. SAMtools provides a comprehensive collection of command-line tools for viewing, sorting, indexing, filtering, and summarizing SAM and BAM files.
  • A SAM file can be converted into BAM format using:

samtools view -b -o alignments.bam alignments.sam

  • The -b option requests BAM output, while -o specifies the output filename. The resulting BAM file contains the alignment records in compressed binary form. For most downstream analyses, BAM files should be sorted by genomic coordinate and indexed.
  • Coordinate sorting arranges alignment records according to their reference sequence and genomic positions. This makes it possible to access alignments from specific genomic regions efficiently. The following command sorts a BAM file:

samtools sort -@ 4 -o alignments.sorted.bam alignments.bam

  • The -@ option specifies the number of additional computational threads used by SAMtools. The -o option defines the output file. The resulting file is coordinate-sorted and can be indexed.
  • A BAM index allows programs to retrieve alignments from particular genomic regions without scanning the complete file. An index can be generated using:

samtools index alignments.sorted.bam

  • SAMtools normally creates a .bai index file for BAM files, although CSI indexing is also available and may be necessary for very large references or coordinate ranges. A coordinate-sorted BAM file and its index are commonly used together in genome browsers and downstream genomic analysis.
  • CRAM is another alignment file format designed to reduce storage requirements. It uses reference-based compression, which means that it can use the reference genome sequence to encode information efficiently. Instead of storing every aligned nucleotide independently, CRAM can represent many bases in relation to the corresponding reference sequence and store differences and other information needed to reconstruct the read data. This approach can produce substantially smaller files than BAM, particularly for large sequencing datasets with high mapping rates.
  • CRAM is especially useful for large-scale genome projects, population sequencing studies, clinical sequencing archives, and long-term storage. It can preserve the alignment information needed for downstream analysis while reducing disk-space requirements. CRAM also supports indexing and regional access, allowing software to retrieve selected genomic regions without decompressing the entire file.
  • Because CRAM relies on reference information for efficient reconstruction, the correct reference genome must be available when reading the file. The reference must correspond to the one used during CRAM creation. A mismatch in reference sequence can cause decoding problems or incorrect reconstruction. For long-term data preservation, the reference genome accession, assembly version, and preferably the exact reference sequence or a reliable retrieval location should be recorded. Some CRAM workflows embed reference information or use reference checksums and external reference retrieval mechanisms, but users should not assume that every CRAM file is independently self-contained.
  • A BAM file can be converted into CRAM using SAMtools:

samtools view -C -T reference_genome.fa \

    -o alignments.cram alignments.sorted.bam

  • The -C option requests CRAM output, while -T specifies the reference FASTA file. The input BAM should generally be coordinate-sorted before conversion when regional access is required. The resulting CRAM file can be indexed:

samtools index alignments.cram

  • A CRAM file can be converted back into BAM format when needed:

samtools view -b -T reference_genome.fa \

    -o restored_alignments.bam alignments.cram

  • The reference sequence supplied during decoding must be compatible with the reference used to create the CRAM file. It is good practice to preserve the reference assembly information and verify file integrity after conversion.
  • SAM, BAM, and CRAM differ in readability, storage efficiency, and reference requirements. SAM is a text-based format that is convenient for inspection and debugging but generally requires more storage. BAM is a compressed binary format that supports efficient processing and indexing. CRAM is a reference-based compressed format designed to reduce storage requirements while retaining the information needed for reconstruction and analysis. The choice depends on the purpose of the workflow, available storage, software compatibility, and data-retention requirements.
FeatureSAMBAMCRAM
FormatTextBinaryBinary
CompressionUsually uncompressedBGZF compressionReference-based compression
Human readabilityReadableNot directly readableNot directly readable
Storage efficiencyLowerHigher than SAMOften higher than BAM
Reference required for basic decodingNoNoReference-dependent for many decoding operations
IndexingNot commonly used for random accessSupportedSupported
Common useInspection and exchangeRoutine analysisStorage and large-scale data management
  • SAM, BAM, and CRAM files are used throughout genomic analysis pipelines. After sequencing, reads are commonly aligned to a reference genome and stored in BAM or CRAM format. These files are then processed for variant calling, gene expression analysis, structural-variant detection, coverage assessment, genome assembly evaluation, and other applications.
  • In whole-genome sequencing, alignment files are used to identify single-nucleotide variants, insertions, deletions, and structural variants. Variant callers examine the mapped reads and their supporting evidence to determine whether a sample differs from the reference genome. Mapping quality, base quality, read depth, and alignment characteristics are important when evaluating candidate variants. BAM and CRAM files allow variant-calling tools to retrieve reads from specific genomic regions efficiently.
  • In RNA-seq analysis, alignment files contain information about exon–exon junctions and transcriptomic read placement. Splice-aware aligners such as STAR and HISAT2 produce SAM or BAM output that can be used for gene expression quantification, alternative splicing analysis, and transcript assembly. The CIGAR string and alignment tags provide information about intron-spanning reads, while read-group and library metadata can help organize multi-sample experiments.
  • SAM, BAM, and CRAM files are also important in genome browsers. Programs such as the Integrative Genomics Viewer (IGV), UCSC Genome Browser, and Ensembl Genome Browser can display alignment records across genomic regions. These visualizations help researchers inspect read coverage, mismatches, insertions, deletions, splice junctions, and structural rearrangements. Indexed BAM and CRAM files make it possible to retrieve and visualize reads from selected genomic coordinates.
  • Several quality-control metrics can be calculated from alignment files. These include the number of mapped reads, properly paired reads, duplicate reads, mapping-quality distributions, sequencing depth, coverage uniformity, and mismatch rates. SAMtools provides several commands for generating alignment statistics.
  • The following commands can be used to summarize a BAM file:

samtools flagstat alignments.sorted.bam

samtools stats alignments.sorted.bam > alignment_statistics.txt

samtools coverage alignments.sorted.bam

  • The flagstat command provides a summary of alignment records and mapping categories. The stats command generates more detailed statistics, while coverage summarizes coverage information for reference sequences. These results can help identify poor mapping performance, contamination, low sequencing depth, and other potential problems.
  • Alignment files can also be filtered according to mapping quality, read flags, genomic regions, and other properties. For example, the following command retains alignments with mapping quality of at least 20:

samtools view -b -q 20 \

    -o high_quality_alignments.bam \

    alignments.sorted.bam

Reads can be selected from a particular genomic region using:

samtools view alignments.sorted.bam chr1:100000-200000

  • This command retrieves alignment records overlapping the specified chromosome 1 interval, provided that the BAM file is indexed. Such regional retrieval is useful for inspecting candidate variants, gene expression, and genomic features.
  • Duplicate marking is another important operation in many sequencing workflows. PCR amplification can generate multiple copies of the same original DNA fragment, potentially causing some regions or variants to appear more strongly supported than they actually are. Tools such as Picard MarkDuplicates and SAMtools markdup can identify and mark potential duplicate alignments. Duplicate handling should be appropriate to the sequencing protocol because not all identical reads represent PCR duplicates. For example, high-depth amplicon sequencing and some RNA-seq workflows require different duplicate-handling strategies from conventional whole-genome sequencing.
  • Read groups are important metadata records in SAM, BAM, and CRAM files. They can identify the sequencing sample, library, platform, and sequencing run associated with each read. When data from multiple sequencing lanes or libraries are combined, read-group information helps downstream software distinguish their origins. Some variant-calling workflows require correctly defined read groups because they are used to model sequencing batches and organize sample-level information.
  • Sorting and indexing are essential for efficient access to alignment data. Coordinate-sorted files are generally used for genome browsers and regional queries, while query-name-sorted files group records by read name and can be useful in certain processing workflows. Sorting by read name is not interchangeable with coordinate sorting, and some downstream tools require a particular ordering. The sorting requirement should therefore be checked for each analysis program.
  • File validation is also important when working with SAM, BAM, and CRAM data. Truncated files, missing indexes, incompatible reference sequences, incorrect sorting, and incomplete headers can cause processing errors. SAMtools provides commands such as quickcheck for basic file validation:

samtools quickcheck -v alignments.sorted.bam

  • For CRAM files, the correct reference should be supplied when validation or decoding requires it. File checksums can also be generated to verify that files have not changed during transfer or storage. For example:

sha256sum alignments.sorted.bam

sha256sum alignments.cram

  • The resulting checksums can be stored with project metadata and used to verify file integrity after copying or downloading.
  • When converting between SAM, BAM, and CRAM, users should verify that essential alignment information is retained. Conversion settings may affect compression and the preservation of optional tags or original sequence and quality information. Some workflows intentionally omit or alter information to reduce storage requirements. This may be appropriate for specific archival or analysis purposes, but it should be documented because it can limit future processing. Reference-dependent CRAM files should be accompanied by sufficient reference information to support future reconstruction.
  • Reproducibility is essential when storing and exchanging alignment files. Researchers should record the reference genome assembly, aligner name and version, alignment parameters, sorting method, compression settings, and software versions used for file conversion. Read-group information, sample identifiers, sequencing technology, and library preparation details should also be preserved. For CRAM archives, the exact reference sequence or a reliable accession and version should be documented. These practices help ensure that alignment files can be interpreted and reused correctly in future analyses.
  • SAM, BAM, and CRAM are fundamental formats in modern bioinformatics because they provide standardized representations of sequence alignments. SAM offers a readable text representation, BAM provides compressed binary storage suitable for routine analysis, and CRAM offers efficient reference-based compression for large datasets. Understanding their structures, fields, compression methods, indexing requirements, and applications enables researchers to manage sequencing data efficiently and maintain reliable genomic analysis workflows.
Author:

Leave a Reply

Your email address will not be published. Required fields are marked *