--- name: bio-alignment-sorting description: 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. tool_type: cli primary_tool: samtools --- ## Version Compatibility Reference examples tested with: pysam 0.22+, samtools 1.19+ Before using code patterns, verify installed versions match. If versions differ: - Python: `pip show ` then `help(module.function)` to check signatures - CLI: ` --version` then ` --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). - CLI: `samtools sort -o sorted.bam input.bam` - Python: `pysam.sort('-o', 'sorted.bam', 'input.bam')` ## Sort Orders | Order | Flag | Use Case | |-------|------|----------| | Coordinate | default | Indexing, visualization, variant calling | | Name | `-n` | Paired-end processing, fixmate, markdup | | Tag | `-t TAG` | Sort by specific tag value | ## samtools sort ### Sort by Coordinate (Default) ```bash samtools sort -o sorted.bam input.bam ``` ### Sort by Read Name ```bash samtools sort -n -o namesorted.bam input.bam ``` ### Multi-threaded Sorting ```bash samtools sort -@ 8 -o sorted.bam input.bam ``` ### Control Memory Usage ```bash samtools sort -m 4G -@ 4 -o sorted.bam input.bam ``` ### Set Temporary Directory ```bash samtools sort -T /tmp/sort_tmp -o sorted.bam input.bam ``` ### Specify Output Format ```bash # Output as BAM (default) samtools sort -O bam -o sorted.bam input.bam # Output as CRAM samtools sort -O cram --reference ref.fa -o sorted.cram input.bam ``` ### Sort by Tag ```bash # Sort by cell barcode (10x Genomics) samtools sort -t CB -o sorted_by_barcode.bam input.bam ``` ### Pipe from Aligner ```bash 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). ```bash # Fast paired FASTQ extraction samtools collate -O -u in.bam tmp_prefix | \ samtools fastq -1 R1.fq.gz -2 R2.fq.gz -0 /dev/null -s /dev/null -n - # Markdup pre-processing (collate beats sort -n here) samtools collate -O -u in.bam tmp_prefix | \ samtools fixmate -m -u - - | \ samtools sort -u - | \ samtools markdup - out.bam ``` ### Sort Order Required by Downstream Tool | Operation | Required sort | |-----------|---------------| | `samtools index` | coordinate (hard requirement) | | `samtools fixmate -m` | name (or collate; needs mates adjacent) | | `samtools markdup` | coordinate (after fixmate) | | GATK MarkDuplicatesSpark | coordinate or queryname | | `samtools mpileup` / `bcftools mpileup` | coordinate | | GATK HaplotypeCaller, Mutect2 | coordinate | | featureCounts / HTSeq | coordinate or name (`-p` for paired) | | umi_tools dedup | coordinate (with index) | | fgbio GroupReadsByUmi | 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 ```bash samtools view -H input.bam | grep "^@HD" # SO:coordinate = coordinate sorted # SO:queryname = name sorted # SO:unsorted = not sorted ``` ### Verify Sorted ```bash # 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