Create and use indices for random access to BAM and CRAM files, enabling fast region queries without reading entire files.
# samtools
conda install -c bioconda samtools
# pysam
pip install pysam
Tell your AI agent what you want to do: - "Index my BAM file for random access" - "Get per-chromosome read counts from the index" - "Check if my BAM file has an index" - "Create a CSI index for large chromosomes"
"Create an index for sample.bam"
"Index my BAM file using 8 threads"
"Create CSI index for my genome with large chromosomes"
"Count reads per chromosome using idxstats"
"Extract reads from chr1:1000000-2000000"
"Get reads overlapping regions in my BED file"
"Index my reference FASTA for random access"
"Extract sequence for chr1:1000-2000 from reference"
"Show per-chromosome read distribution"
"Calculate mitochondrial contamination percentage"
"Check X/Y ratio for sex determination"
Standard index for BAM files. Chromosomes must be < 537 Mbp (2^29 bp).
samtools index input.bam # Creates input.bam.bai
For genomes with large chromosomes (> 537 Mbp).
samtools index -c input.bam # Creates input.bam.csi
Index for CRAM files.
samtools index input.cram # Creates input.cram.crai
samtools index sample.bam # Basic indexing
samtools index -@ 8 large.bam # Multi-threaded
samtools index -c input.bam # CSI for large chromosomes
for bam in *.bam; do
if [ ! -f "${bam}.bai" ]; then
samtools index "$bam"
fi
done
samtools view input.bam chr1:1000000-2000000 # Single region
samtools view input.bam chr1:1000-2000 chr2:3000-4000 # Multiple regions
samtools view -L targets.bed input.bam # From BED file
samtools view -c input.bam chr1:1000000-2000000 # Count in region
samtools idxstats input.bam # Per-chromosome counts
# Total mapped reads
samtools idxstats input.bam | awk '{sum += $3} END {print sum}'
# Mitochondrial fraction
samtools idxstats input.bam | awk '/^chrM/ {mt=$3} {total+=$3} END {printf "MT: %.2f%%\n", mt/total*100}'
samtools faidx reference.fa # Create index
samtools faidx reference.fa chr1:1000-2000 # Extract region
import pysam
with pysam.AlignmentFile('input.bam', 'rb') as bam:
for read in bam.fetch('chr1', 1000000, 2000000):
print(f'{read.query_name}: {read.reference_start}-{read.reference_end}')
count = bam.count('chr1', 1000000, 2000000)
print(f'Total reads: {count}')
import pysam
with pysam.AlignmentFile('input.bam', 'rb') as bam:
stats = bam.get_index_statistics()
total_mapped = sum(s.mapped for s in stats)
for stat in stats:
pct = stat.mapped / total_mapped * 100 if total_mapped > 0 else 0
print(f'{stat.contig}: {stat.mapped:,} ({pct:.1f}%)')
import pysam
with pysam.FastaFile('reference.fa') as ref:
seq = ref.fetch('chr1', 999, 2000) # 0-based coordinates
length = ref.get_reference_length('chr1')
BAM file lacks an index:
samtools index input.bam
BAM must be sorted before indexing:
samtools sort -o sorted.bam unsorted.bam
samtools index sorted.bam
Index file is missing or in wrong location:
ls -la input.bam* # Should see input.bam and input.bam.bai
Names must match exactly between query and BAM:
samtools view -H input.bam | grep "^@SQ" # Check names
# If BAM uses "chr1", query must use "chr1", not "1"
-@ 8) significantly speeds up large file indexing