[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7EBFC8C0XAXS04N33NA9G27":3,"skill-same:01M7EBFC8C0XAXS04N33NA9G27":62},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":30,"commitSha":31,"skillDirectory":32,"forksCount":14,"repositoryHtmlUrl":33,"repositoryHomepageUrl":33,"ownerHtmlUrl":34,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":35,"install":36,"resources":49},"01M7EBFC8C0XAXS04N33NA9G27","bio-alignment-sorting",null,"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.","Mr-Nobody-Anonymous\u002FAll-skills","Mr-Nobody-Anonymous","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F184253119?v=4","01M7AEXFJHKTYQW5R0ZCQQTWFV","anonymous","01M7C00M3GQR4QKP9GZA42GFAK",0,"MIT","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-alignment-sorting\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: bio-alignment-sorting\ndescription: 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.\ntool_type: cli\nprimary_tool: samtools\nsource: \"https:\u002F\u002Fgithub.com\u002FGPTomics\u002FbioSkills\"\nsource_repository: \"GPTomics\u002FbioSkills\"\nsource_path: \"alignment-files\u002Falignment-sorting\u002FSKILL.md\"\nlicense: \"MIT\"\nimported_at: \"2026-09-20\"\n---\n\n## Version Compatibility\n\nReference examples tested with: pysam 0.22+, samtools 1.19+\n\nBefore using code patterns, verify installed versions match. If versions differ:\n- Python: `pip show \u003Cpackage>` then `help(module.function)` to check signatures\n- CLI: `\u003Ctool> --version` then `\u003Ctool> --help` to confirm flags\n\nIf code throws ImportError, AttributeError, or TypeError, introspect the installed\npackage and adapt the example to match the actual API rather than retrying.\n\n# Alignment Sorting\n\nSort alignment files by coordinate or read name using samtools and pysam.\n\n**\"Sort a BAM file\"** -> Reorder reads by genomic coordinate (for indexing\u002Fvariant calling) or by name (for paired-end processing).\n- CLI: `samtools sort -o sorted.bam input.bam`\n- Python: `pysam.sort('-o', 'sorted.bam', 'input.bam')`\n\n## Sort Orders\n\n| Order | Flag | Use Case |\n|-------|------|----------|\n| Coordinate | default | Indexing, visualization, variant calling |\n| Name | `-n` | Paired-end processing, fixmate, markdup |\n| Tag | `-t TAG` | Sort by specific tag value |\n\n## samtools sort\n\n### Sort by Coordinate (Default)\n```bash\nsamtools sort -o sorted.bam input.bam\n```\n\n### Sort by Read Name\n```bash\nsamtools sort -n -o namesorted.bam input.bam\n```\n\n### Multi-threaded Sorting\n```bash\nsamtools sort -@ 8 -o sorted.bam input.bam\n```\n\n### Control Memory Usage\n```bash\nsamtools sort -m 4G -@ 4 -o sorted.bam input.bam\n```\n\n### Set Temporary Directory\n```bash\nsamtools sort -T \u002Ftmp\u002Fsort_tmp -o sorted.bam input.bam\n```\n\n### Specify Output Format\n```bash\n# Output as BAM (default)\nsamtools sort -O bam -o sorted.bam input.bam\n\n# Output as CRAM\nsamtools sort -O cram --reference ref.fa -o sorted.cram input.bam\n```\n\n### Sort by Tag\n```bash\n# Sort by cell barcode (10x Genomics)\nsamtools sort -t CB -o sorted_by_barcode.bam input.bam\n```\n\n### Pipe from Aligner\n```bash\nbwa mem ref.fa reads.fq | samtools sort -o aligned.bam\n```\n\n## samtools collate vs sort -n\n\n| Tool | Algorithm | Speed | Memory | Output guarantee |\n|------|-----------|-------|--------|------------------|\n| `sort -n` | Full lexicographic sort by QNAME | Slowest | Spills to `-T` | Strict total order by name |\n| `collate` | Hash-bucket grouping | ~3-10x faster | Bounded | Mates adjacent; between-mate order undefined |\n\nUse `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).\n\n```bash\n# Fast paired FASTQ extraction\nsamtools collate -O -u in.bam tmp_prefix | \\\n    samtools fastq -1 R1.fq.gz -2 R2.fq.gz -0 \u002Fdev\u002Fnull -s \u002Fdev\u002Fnull -n -\n\n# Markdup pre-processing (collate beats sort -n here)\nsamtools collate -O -u in.bam tmp_prefix | \\\n    samtools fixmate -m -u - - | \\\n    samtools sort -u - | \\\n    samtools markdup - out.bam\n```\n\n### Sort Order Required by Downstream Tool\n\n| Operation | Required sort |\n|-----------|---------------|\n| `samtools index` | coordinate (hard requirement) |\n| `samtools fixmate -m` | name (or collate; needs mates adjacent) |\n| `samtools markdup` | coordinate (after fixmate) |\n| GATK MarkDuplicatesSpark | coordinate or queryname |\n| `samtools mpileup` \u002F `bcftools mpileup` | coordinate |\n| GATK HaplotypeCaller, Mutect2 | coordinate |\n| featureCounts \u002F HTSeq | coordinate or name (`-p` for paired) |\n| umi_tools dedup | coordinate (with index) |\n| fgbio GroupReadsByUmi | any order accepted (template-coordinate recommended to avoid an internal re-sort) |\n| fgbio CallMolecularConsensusReads | grouped by MI tag (consumes GroupReadsByUmi output) |\n| Sniffles, cuteSV, Manta, Delly | coordinate (need SA tags) |\n| Salmon alignment-mode | name |\n| RSEM (with STAR `--quantMode TranscriptomeSAM`) | name (hard requirement) |\n\n## Check Sort Order\n\n### From Header\n```bash\nsamtools view -H input.bam | grep \"^@HD\"\n# SO:coordinate = coordinate sorted\n# SO:queryname = name sorted\n# SO:unsorted = not sorted\n```\n\n### Verify Sorted\n```bash\n# Check if coordinate sorted (returns 0 if sorted). Reset the position tracker\n# on each new contig, else the POS reset at every chromosome boundary of a\n# correctly sorted multi-contig BAM would falsely report \"unsorted\".\nsamtools view input.bam | awk '$3!=c {c=$3; prev=0} $4\u003Cprev {exit 1} {prev=$4}'\n# Simpler and authoritative: trust the @HD SO: header shown above.\n```\n\n## pysam Python Alternative\n\n### Sort with pysam\n```python\nimport pysam\n\npysam.sort('-o', 'sorted.bam', 'input.bam')\n```\n\n### Sort by Name\n```python\npysam.sort('-n', '-o', 'namesorted.bam', 'input.bam')\n```\n\n### Sort with Options\n```python\npysam.sort('-@', '4', '-m', '2G', '-o', 'sorted.bam', 'input.bam')\n```\n\n### Avoid In-Python Sorting\n\nDo 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()`:\n```python\nimport pysam\n\npysam.sort('-@', '4', '-m', '2G', '-T', '\u002Ftmp\u002Fsortpfx',\n           '-o', 'sorted.bam', 'input.bam')\n```\n\n### Check Sort Order in pysam\n```python\nimport pysam\n\nwith pysam.AlignmentFile('input.bam', 'rb') as bam:\n    hd = bam.header.get('HD', {})\n    sort_order = hd.get('SO', 'unknown')\n    print(f'Sort order: {sort_order}')\n```\n\n### Stream Sort from Aligner\nFor streaming from aligners, use shell pipes (simpler and more reliable):\n```python\nimport subprocess\n\nsubprocess.run(\n    'bwa mem ref.fa reads.fq | samtools sort -o aligned.bam',\n    shell=True, check=True\n)\n```\n\n## samtools merge\n\nCombine multiple BAM files into one. `samtools merge` does NOT validate sort-order consistency across inputs; mismatched inputs silently produce a malformed output.\n\n### Verify Sort Order Consistency First\n```bash\nfor f in *.bam; do samtools view -H \"$f\" | head -1; done | sort -u\n# Should print exactly ONE line, e.g. \"@HD VN:1.6 SO:coordinate\"\n```\n\n### Safe Merge (dedup @RG and @PG)\n```bash\n# -c deduplicates @RG records; -p deduplicates @PG records (samtools-merge(1))\nsamtools merge -c -p -@ 8 merged.bam sample1.bam sample2.bam sample3.bam\n```\n\nWhen merging BAMs from different lanes \u002F machines \u002F 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\u002FPU) silently produces wrong recalibration.\n\n### Merge with Threads \u002F from File List\n```bash\nsamtools merge -@ 4 merged.bam sample1.bam sample2.bam sample3.bam\nsamtools merge -b files.txt merged.bam   # one BAM path per line\n```\n\n### Force Overwrite\n```bash\nsamtools merge -f merged.bam sample1.bam sample2.bam\n```\n\n### Merge Specific Region\n```bash\nsamtools merge -R chr1:1000000-2000000 merged_region.bam sample1.bam sample2.bam\n```\n\n### pysam Merge\n```python\nimport pysam\n\npysam.merge('-c', '-p', '-f', 'merged.bam', 'sample1.bam', 'sample2.bam', 'sample3.bam')\n```\n\n## Common Workflows\n\n**Goal:** Combine sorting with other alignment processing steps into efficient pipelines.\n\n**Approach:** Pipe aligner output directly into `samtools sort` to avoid writing unsorted intermediates, then index for downstream access.\n\n### Align and Sort\n```bash\nbwa mem -t 8 ref.fa R1.fq R2.fq | samtools sort -@ 4 -o aligned.bam\nsamtools index aligned.bam\n```\n\n### Re-sort by Name for Duplicate Marking\n```bash\n# Full workflow: sort by name, fixmate, sort by coord, markdup\nsamtools sort -n -o namesorted.bam input.bam\nsamtools fixmate -m namesorted.bam fixmate.bam\nsamtools sort -o sorted.bam fixmate.bam\nsamtools markdup sorted.bam marked.bam\n```\n\n### Convert Name-sorted to Coordinate-sorted\n```bash\nsamtools sort -o coord_sorted.bam name_sorted.bam\nsamtools index coord_sorted.bam\n```\n\n### Extract FASTQ from Sorted BAM\n```bash\n# Collate first to group pairs\nsamtools collate -u -O input.bam \u002Ftmp\u002Fcollate | \\\n    samtools fastq -1 R1.fq -2 R2.fq -0 \u002Fdev\u002Fnull -s \u002Fdev\u002Fnull -\n```\n\n## Performance Tips\n\n| Parameter | Effect |\n|-----------|--------|\n| `-@ N` | Use N additional threads |\n| `-m SIZE` | Memory per thread (e.g., 4G) |\n| `-T PREFIX` | Temp file location (use fast SSD scratch) |\n| `-l LEVEL` | Compression level (1-9, default 6) |\n\n### Compression Level Decision\n\n| Level | Use | Wall-time vs default | Size vs default |\n|-------|-----|----------------------|------------------|\n| `-l 0` \u002F `-u` | Pipe between samtools tools | 0% (skips BGZF) | +200-400% |\n| `-l 1` | Final output if disk is cheap | ~+10% | ~+30% |\n| `-l 6` | Default | baseline | baseline |\n| `-l 9` | Archival, write-once | ~+50-100% | ~-2-5% |\n\n```bash\n# WRONG -- pipe re-compresses then decompresses every step\nsamtools fixmate -m in.bam - | samtools sort -o out.bam\n\n# RIGHT -- uncompressed (-u) between piped samtools commands\nsamtools fixmate -m -u in.bam - | samtools sort -o out.bam\n```\n\n### Optimal Settings for Large Files\n```bash\n# 8 threads, 2GB per thread, low compression for output written to fast disk\nsamtools sort -@ 8 -m 2G -l 1 -T \u002Fscratch\u002Fsortpfx -o sorted.bam input.bam\n```\n\n## Quick Reference\n\n| Task | Command |\n|------|---------|\n| Sort by coordinate | `samtools sort -o out.bam in.bam` |\n| Sort by name | `samtools sort -n -o out.bam in.bam` |\n| Sort with threads | `samtools sort -@ 8 -o out.bam in.bam` |\n| Collate pairs | `samtools collate -o out.bam in.bam` |\n| Merge BAMs | `samtools merge out.bam in1.bam in2.bam` |\n| Check sort order | `samtools view -H in.bam \\| grep \"^@HD\"` |\n| Sort + index | `samtools sort -o out.bam in.bam && samtools index out.bam` |\n\n## Common Errors\n\n| Error | Cause | Solution |\n|-------|-------|----------|\n| `out of memory` | Insufficient RAM | Use `-m` to limit per-thread memory |\n| `disk full` | Temp files filling disk | Use `-T` to specify different location |\n| `truncated file` | Interrupted sort | Re-run sort from original |\n\n## Related Skills\n\n- sam-bam-basics - View and convert alignment files\n- alignment-indexing - Index after coordinate sorting\n- duplicate-handling - Requires name-sorted input for fixmate\n- alignment-filtering - Filter before or after sorting\n","## Version Compatibility\n\nReference examples tested with: pysam 0.22+, samtools 1.19+\n\nBefore using code patterns, verify installed versions match. If versions differ:\n- Python: `pip show \u003Cpackage>` then `help(module.function)` to check signatures\n- CLI: `\u003Ctool> --version` then `\u003Ctool> --help` to confirm flags\n\nIf code throws ImportError, AttributeError, or TypeError, introspect the installed\npackage and adapt the example to match the actual API rather than retrying.\n\n# Alignment Sorting\n\nSort alignment files by coordinate or read name using samtools and pysam.\n\n**\"Sort a BAM file\"** -> Reorder reads by genomic coordinate (for indexing\u002Fvariant calling) or by name (for paired-end processing).\n- CLI: `samtools sort -o sorted.bam input.bam`\n- Python: `pysam.sort('-o', 'sorted.bam', 'input.bam')`\n\n## Sort Orders\n\n| Order | Flag | Use Case |\n|-------|------|----------|\n| Coordinate | default | Indexing, visualization, variant calling |\n| Name | `-n` | Paired-end processing, fixmate, markdup |\n| Tag | `-t TAG` | Sort by specific tag value |\n\n## samtools sort\n\n### Sort by Coordinate (Default)\n```bash\nsamtools sort -o sorted.bam input.bam\n```\n\n### Sort by Read Name\n```bash\nsamtools sort -n -o namesorted.bam input.bam\n```\n\n### Multi-threaded Sorting\n```bash\nsamtools sort -@ 8 -o sorted.bam input.bam\n```\n\n### Control Memory Usage\n```bash\nsamtools sort -m 4G -@ 4 -o sorted.bam input.bam\n```\n\n### Set Temporary Directory\n```bash\nsamtools sort -T \u002Ftmp\u002Fsort_tmp -o sorted.bam input.bam\n```\n\n### Specify Output Format\n```bash\n# Output as BAM (default)\nsamtools sort -O bam -o sorted.bam input.bam\n\n# Output as CRAM\nsamtools sort -O cram --reference ref.fa -o sorted.cram input.bam\n```\n\n### Sort by Tag\n```bash\n# Sort by cell barcode (10x Genomics)\nsamtools sort -t CB -o sorted_by_barcode.bam input.bam\n```\n\n### Pipe from Aligner\n```bash\nbwa mem ref.fa reads.fq | samtools sort -o aligned.bam\n```\n\n## samtools collate vs sort -n\n\n| Tool | Algorithm | Speed | Memory | Output guarantee |\n|------|-----------|-------|--------|------------------|\n| `sort -n` | Full lexicographic sort by QNAME | Slowest | Spills to `-T` | Strict total order by name |\n| `collate` | Hash-bucket grouping | ~3-10x faster | Bounded | Mates adjacent; between-mate order undefined |\n\nUse `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).\n\n```bash\n# Fast paired FASTQ extraction\nsamtools collate -O -u in.bam tmp_prefix | \\\n    samtools fastq -1 R1.fq.gz -2 R2.fq.gz -0 \u002Fdev\u002Fnull -s \u002Fdev\u002Fnull -n -\n\n# Markdup pre-processing (collate beats sort -n here)\nsamtools collate -O -u in.bam tmp_prefix | \\\n    samtools fixmate -m -u - - | \\\n    samtools sort -u - | \\\n    samtools markdup - out.bam\n```\n\n### Sort Order Required by Downstream Tool\n\n| Operation | Required sort |\n|-----------|---------------|\n| `samtools index` | coordinate (hard requirement) |\n| `samtools fixmate -m` | name (or collate; needs mates adjacent) |\n| `samtools markdup` | coordinate (after fixmate) |\n| GATK MarkDuplicatesSpark | coordinate or queryname |\n| `samtools mpileup` \u002F `bcftools mpileup` | coordinate |\n| GATK HaplotypeCaller, Mutect2 | coordinate |\n| featureCounts \u002F HTSeq | coordinate or name (`-p` for paired) |\n| umi_tools dedup | coordinate (with index) |\n| fgbio GroupReadsByUmi | any order accepted (template-coordinate recommended to avoid an internal re-sort) |\n| fgbio CallMolecularConsensusReads | grouped by MI tag (consumes GroupReadsByUmi output) |\n| Sniffles, cuteSV, Manta, Delly | coordinate (need SA tags) |\n| Salmon alignment-mode | name |\n| RSEM (with STAR `--quantMode TranscriptomeSAM`) | name (hard requirement) |\n\n## Check Sort Order\n\n### From Header\n```bash\nsamtools view -H input.bam | grep \"^@HD\"\n# SO:coordinate = coordinate sorted\n# SO:queryname = name sorted\n# SO:unsorted = not sorted\n```\n\n### Verify Sorted\n```bash\n# Check if coordinate sorted (returns 0 if sorted). Reset the position tracker\n# on each new contig, else the POS reset at every chromosome boundary of a\n# correctly sorted multi-contig BAM would falsely report \"unsorted\".\nsamtools view input.bam | awk '$3!=c {c=$3; prev=0} $4\u003Cprev {exit 1} {prev=$4}'\n# Simpler and authoritative: trust the @HD SO: header shown above.\n```\n\n## pysam Python Alternative\n\n### Sort with pysam\n```python\nimport pysam\n\npysam.sort('-o', 'sorted.bam', 'input.bam')\n```\n\n### Sort by Name\n```python\npysam.sort('-n', '-o', 'namesorted.bam', 'input.bam')\n```\n\n### Sort with Options\n```python\npysam.sort('-@', '4', '-m', '2G', '-o', 'sorted.bam', 'input.bam')\n```\n\n### Avoid In-Python Sorting\n\nDo 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()`:\n```python\nimport pysam\n\npysam.sort('-@', '4', '-m', '2G', '-T', '\u002Ftmp\u002Fsortpfx',\n           '-o', 'sorted.bam', 'input.bam')\n```\n\n### Check Sort Order in pysam\n```python\nimport pysam\n\nwith pysam.AlignmentFile('input.bam', 'rb') as bam:\n    hd = bam.header.get('HD', {})\n    sort_order = hd.get('SO', 'unknown')\n    print(f'Sort order: {sort_order}')\n```\n\n### Stream Sort from Aligner\nFor streaming from aligners, use shell pipes (simpler and more reliable):\n```python\nimport subprocess\n\nsubprocess.run(\n    'bwa mem ref.fa reads.fq | samtools sort -o aligned.bam',\n    shell=True, check=True\n)\n```\n\n## samtools merge\n\nCombine multiple BAM files into one. `samtools merge` does NOT validate sort-order consistency across inputs; mismatched inputs silently produce a malformed output.\n\n### Verify Sort Order Consistency First\n```bash\nfor f in *.bam; do samtools view -H \"$f\" | head -1; done | sort -u\n# Should print exactly ONE line, e.g. \"@HD VN:1.6 SO:coordinate\"\n```\n\n### Safe Merge (dedup @RG and @PG)\n```bash\n# -c deduplicates @RG records; -p deduplicates @PG records (samtools-merge(1))\nsamtools merge -c -p -@ 8 merged.bam sample1.bam sample2.bam sample3.bam\n```\n\nWhen merging BAMs from different lanes \u002F machines \u002F 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\u002FPU) silently produces wrong recalibration.\n\n### Merge with Threads \u002F from File List\n```bash\nsamtools merge -@ 4 merged.bam sample1.bam sample2.bam sample3.bam\nsamtools merge -b files.txt merged.bam   # one BAM path per line\n```\n\n### Force Overwrite\n```bash\nsamtools merge -f merged.bam sample1.bam sample2.bam\n```\n\n### Merge Specific Region\n```bash\nsamtools merge -R chr1:1000000-2000000 merged_region.bam sample1.bam sample2.bam\n```\n\n### pysam Merge\n```python\nimport pysam\n\npysam.merge('-c', '-p', '-f', 'merged.bam', 'sample1.bam', 'sample2.bam', 'sample3.bam')\n```\n\n## Common Workflows\n\n**Goal:** Combine sorting with other alignment processing steps into efficient pipelines.\n\n**Approach:** Pipe aligner output directly into `samtools sort` to avoid writing unsorted intermediates, then index for downstream access.\n\n### Align and Sort\n```bash\nbwa mem -t 8 ref.fa R1.fq R2.fq | samtools sort -@ 4 -o aligned.bam\nsamtools index aligned.bam\n```\n\n### Re-sort by Name for Duplicate Marking\n```bash\n# Full workflow: sort by name, fixmate, sort by coord, markdup\nsamtools sort -n -o namesorted.bam input.bam\nsamtools fixmate -m namesorted.bam fixmate.bam\nsamtools sort -o sorted.bam fixmate.bam\nsamtools markdup sorted.bam marked.bam\n```\n\n### Convert Name-sorted to Coordinate-sorted\n```bash\nsamtools sort -o coord_sorted.bam name_sorted.bam\nsamtools index coord_sorted.bam\n```\n\n### Extract FASTQ from Sorted BAM\n```bash\n# Collate first to group pairs\nsamtools collate -u -O input.bam \u002Ftmp\u002Fcollate | \\\n    samtools fastq -1 R1.fq -2 R2.fq -0 \u002Fdev\u002Fnull -s \u002Fdev\u002Fnull -\n```\n\n## Performance Tips\n\n| Parameter | Effect |\n|-----------|--------|\n| `-@ N` | Use N additional threads |\n| `-m SIZE` | Memory per thread (e.g., 4G) |\n| `-T PREFIX` | Temp file location (use fast SSD scratch) |\n| `-l LEVEL` | Compression level (1-9, default 6) |\n\n### Compression Level Decision\n\n| Level | Use | Wall-time vs default | Size vs default |\n|-------|-----|----------------------|------------------|\n| `-l 0` \u002F `-u` | Pipe between samtools tools | 0% (skips BGZF) | +200-400% |\n| `-l 1` | Final output if disk is cheap | ~+10% | ~+30% |\n| `-l 6` | Default | baseline | baseline |\n| `-l 9` | Archival, write-once | ~+50-100% | ~-2-5% |\n\n```bash\n# WRONG -- pipe re-compresses then decompresses every step\nsamtools fixmate -m in.bam - | samtools sort -o out.bam\n\n# RIGHT -- uncompressed (-u) between piped samtools commands\nsamtools fixmate -m -u in.bam - | samtools sort -o out.bam\n```\n\n### Optimal Settings for Large Files\n```bash\n# 8 threads, 2GB per thread, low compression for output written to fast disk\nsamtools sort -@ 8 -m 2G -l 1 -T \u002Fscratch\u002Fsortpfx -o sorted.bam input.bam\n```\n\n## Quick Reference\n\n| Task | Command |\n|------|---------|\n| Sort by coordinate | `samtools sort -o out.bam in.bam` |\n| Sort by name | `samtools sort -n -o out.bam in.bam` |\n| Sort with threads | `samtools sort -@ 8 -o out.bam in.bam` |\n| Collate pairs | `samtools collate -o out.bam in.bam` |\n| Merge BAMs | `samtools merge out.bam in1.bam in2.bam` |\n| Check sort order | `samtools view -H in.bam \\| grep \"^@HD\"` |\n| Sort + index | `samtools sort -o out.bam in.bam && samtools index out.bam` |\n\n## Common Errors\n\n| Error | Cause | Solution |\n|-------|-------|----------|\n| `out of memory` | Insufficient RAM | Use `-m` to limit per-thread memory |\n| `disk full` | Temp files filling disk | Use `-T` to specify different location |\n| `truncated file` | Interrupted sort | Re-run sort from original |\n\n## Related Skills\n\n- sam-bam-basics - View and convert alignment files\n- alignment-indexing - Index after coordinate sorting\n- duplicate-handling - Requires name-sorted input for fixmate\n- alignment-filtering - Filter before or after sorting\n",{"name":5,"source":24,"license":15,"tool_type":25,"description":7,"imported_at":26,"source_path":27,"primary_tool":28,"source_repository":29},"https:\u002F\u002Fgithub.com\u002FGPTomics\u002FbioSkills","cli","2026-09-20","alignment-files\u002Falignment-sorting\u002FSKILL.md","samtools","GPTomics\u002FbioSkills","main","2d1750717747097b602acf30bd09a7cbd4b4c6ea","awesome_skills\u002Fbiology\u002Fbio-alignment-sorting","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous","2026-11-09 11:45:36",{"source":8,"skillName":5,"commands":37,"prompt":47,"zipAvailable":48},[38,41,44],{"tool":39,"command":40},"npx","npx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill bio-alignment-sorting",{"tool":42,"command":43},"bunx","bunx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill bio-alignment-sorting",{"tool":45,"command":46},"pnpm","pnpm dlx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill bio-alignment-sorting","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-alignment-sorting\u002FSKILL.md",true,[50,56],{"path":51,"resourceType":52,"resourceTypeDesc":53,"sizeBytes":54,"sourceHtmlUrl":55},"examples\u002Fsort_pipeline.sh","SCRIPT","脚本",855,"https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-alignment-sorting\u002Fexamples\u002Fsort_pipeline.sh",{"path":57,"resourceType":58,"resourceTypeDesc":59,"sizeBytes":60,"sourceHtmlUrl":61},"usage-guide.md","REFERENCE","参考文档",4521,"https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-alignment-sorting\u002Fusage-guide.md",[63,71,78,85,92,99],{"skillNo":64,"name":65,"nameZh":6,"description":66,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":67,"categories":68,"keywords":69,"publishedAt":70},"01M7FFFZPC2025JQQHPHDX154J","dei-assessment","Assess diversity, equity, and inclusion with metrics. TRIGGERS - Use when user needs help with dei-assessment related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fdei-assessment\u002FSKILL.md",[],[],"2026-11-16 10:05:34",{"skillNo":72,"name":73,"nameZh":6,"description":74,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":75,"categories":76,"keywords":77,"publishedAt":70},"01M7FFFWN8H4WA7A6Y398QKB6J","dei-action-plan","Create DEI action plans with goals and initiatives. TRIGGERS - Use when user needs help with dei-action-plan related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fdei-action-plan\u002FSKILL.md",[],[],{"skillNo":79,"name":80,"nameZh":6,"description":81,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":82,"categories":83,"keywords":84,"publishedAt":70},"01M7FFFSHTM0QZRVZ2NRJTJ0PY","culture-fit-assessment","Design culture add assessment processes. TRIGGERS - Use when user needs help with culture-fit-assessment related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fculture-fit-assessment\u002FSKILL.md",[],[],{"skillNo":86,"name":87,"nameZh":6,"description":88,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":89,"categories":90,"keywords":91,"publishedAt":70},"01M7FFFMA12RKEQA38KHJSXXPS","cowork-to-code-bridge","Use an already-installed, independently verified cowork-to-code bridge to run narrowly approved actions on the user's own macOS, Linux, or WSL2 machine through a local file queue.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fcowork-to-code-bridge\u002FSKILL.md",[],[],{"skillNo":93,"name":94,"nameZh":6,"description":95,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":96,"categories":97,"keywords":98,"publishedAt":70},"01M7FFFH1F6M8YRGW5V487GH1K","counter-offer-response","Draft counter-offer responses for retention. TRIGGERS - Use when user needs help with counter-offer-response related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fcounter-offer-response\u002FSKILL.md",[],[],{"skillNo":100,"name":101,"nameZh":6,"description":102,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":103,"categories":104,"keywords":105,"publishedAt":70},"01M7FFFDGEHV8Y7J9N40HZXW52","continuous-feedback-system","Design continuous feedback systems. TRIGGERS - Use when user needs help with continuous-feedback-system related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fcontinuous-feedback-system\u002FSKILL.md",[],[]]