Sort alignment files by coordinate or read name using samtools and pysam. Use when preparing BAM files for indexing, variant calling, or paired-end analysis.
Instalar com Codex ou Claude Copie este prompt, cole no Codex, Claude ou outro assistente e deixe que ele revise a página da skill e instale para você.
Um comando direto ignora o prompt de revisão. Verifique a origem antes de executá-lo.
Sort alignment files by coordinate or read name using samtools and pysam. Use when preparing BAM files for indexing, variant calling, or paired-end analysis.
Before using code patterns, verify installed versions match. If versions differ:
Python: pip show <package> then help(module.function) to check signatures
CLI: <tool> --version then <tool> --help to confirm flags
If code throws ImportError, AttributeError, or TypeError, introspect the installed
package and adapt the example to match the actual API rather than retrying.
Alignment Sorting
Sort alignment files by coordinate or read name using samtools and pysam.
"Sort a BAM file" -> Reorder reads by genomic coordinate (for indexing/variant calling) or by name (for paired-end processing).
bwa mem ref.fa reads.fq | samtools sort -o aligned.bam
samtools collate vs sort -n
Tool
Algorithm
Speed
Memory
Output guarantee
sort -n
Full lexicographic sort by QNAME
Slowest
Spills to -T
Strict total order by name
collate
Hash-bucket grouping
~3-10x faster
Bounded
Mates adjacent; between-mate order undefined
Use collate when extracting paired FASTQ, re-aligning, or streaming through markdup. Use sort -n only when a tool requires true lexicographic name order (e.g. RSEM, Salmon alignment-mode).
any order accepted (template-coordinate recommended to avoid an internal re-sort)
fgbio CallMolecularConsensusReads
grouped by MI tag (consumes GroupReadsByUmi output)
Sniffles, cuteSV, Manta, Delly
coordinate (need SA tags)
Salmon alignment-mode
name
RSEM (with STAR --quantMode TranscriptomeSAM)
name (hard requirement)
Check Sort Order
From Header
samtools view -H input.bam | grep "^@HD"# SO:coordinate = coordinate sorted# SO:queryname = name sorted# SO:unsorted = not sorted
Verify Sorted
# Check if coordinate sorted (returns 0 if sorted). Reset the position tracker# on each new contig, else the POS reset at every chromosome boundary of a# correctly sorted multi-contig BAM would falsely report "unsorted".
samtools view input.bam | awk '$3!=c {c=$3; prev=0} $4<prev {exit 1} {prev=$4}'# Simpler and authoritative: trust the @HD SO: header shown above.
Do not load BAM records into a list and call sorted(). pysam.sort() calls samtools' external-merge sort which spills to disk; loading reads into memory blows up around ~30M reads (~10 GB human BAM). Always delegate to pysam.sort():
Combine multiple BAM files into one. samtools merge does NOT validate sort-order consistency across inputs; mismatched inputs silently produce a malformed output.
Verify Sort Order Consistency First
for f in *.bam; do samtools view -H "$f" | head -1; done | sort -u
# Should print exactly ONE line, e.g. "@HD VN:1.6 SO:coordinate"
When merging BAMs from different lanes / machines / aligners, RG IDs may collide. -c and -p deduplicate header records, but RG IDs that genuinely refer to different lane-level read groups must be made unique upstream (samtools addreplacerg) before merge -- otherwise GATK BQSR (which keys models by RGID/PU) silently produces wrong recalibration.
Merge with Threads / from File List
samtools merge -@ 4 merged.bam sample1.bam sample2.bam sample3.bam
samtools merge -b files.txt merged.bam # one BAM path per line