pku-yuangroup/openai4s/bio-alignment-files-alignment-sorting
Claude Code and agent skill by pku-yuangroup/openai4s
- community
Checking that the SKILL.md file is still in the repository.
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.
Install
npx vskill@latest install pku-yuangroup/openai4s/bio-alignment-files-alignment-sortingSKILL.md
The same SKILL.md was published earlier as pku-yuangroup/openai4s/bio-alignment-files-alignment-sorting.
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 <package>thenhelp(module.function)to check signatures - CLI:
<tool> --versionthen<tool> --helpto 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)
Sort by Read Name
Multi-threaded Sorting
Control Memory Usage
Set Temporary Directory
Specify Output Format
Sort by Tag
Pipe from Aligner
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).
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
Verify Sorted
pysam Python Alternative
Sort with pysam
Sort by Name
Sort with Options
Avoid In-Python Sorting
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():
Check Sort Order in pysam
Stream Sort from Aligner
For streaming from aligners, use shell pipes (simpler and more reliable):
samtools merge
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
Safe Merge (dedup @RG and @PG)
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
Force Overwrite
Merge Specific Region
pysam Merge
Common Workflows
Goal: Combine sorting with other alignment processing steps into efficient pipelines.
Approach: Pipe aligner output directly into samtools sort to avoid writing unsorted intermediates, then index for downstream access.
Align and Sort
Re-sort by Name for Duplicate Marking
Convert Name-sorted to Coordinate-sorted
Extract FASTQ from Sorted BAM
Performance Tips
| Parameter | Effect | |
|---|---|---|
-@ N | Use N additional threads | |
-m SIZE | Memory per thread (e.g., 4G) | |
-T PREFIX | Temp file location (use fast SSD scratch) | |
-l LEVEL | Compression level (1-9, default 6) |
Compression Level Decision
| Level | Use | Wall-time vs default | Size vs default | |
|---|---|---|---|---|
-l 0 / -u | Pipe between samtools tools | 0% (skips BGZF) | +200-400% | |
-l 1 | Final output if disk is cheap | ~+10% | ~+30% | |
-l 6 | Default | baseline | baseline | |
-l 9 | Archival, write-once | ~+50-100% | ~-2-5% |
Optimal Settings for Large Files
Quick Reference
| Task | Command | ||
|---|---|---|---|
| Sort by coordinate | samtools sort -o out.bam in.bam | ||
| Sort by name | samtools sort -n -o out.bam in.bam | ||
| Sort with threads | samtools sort -@ 8 -o out.bam in.bam | ||
| Collate pairs | samtools collate -o out.bam in.bam | ||
| Merge BAMs | samtools merge out.bam in1.bam in2.bam | ||
| Check sort order | `samtools view -H in.bam \ | grep "^@HD"` | |
| Sort + index | samtools sort -o out.bam in.bam && samtools index out.bam |
Common Errors
| Error | Cause | Solution | |
|---|---|---|---|
out of memory | Insufficient RAM | Use -m to limit per-thread memory | |
disk full | Temp files filling disk | Use -T to specify different location | |
truncated file | Interrupted sort | Re-run sort from original |
Related Skills
- sam-bam-basics - View and convert alignment files
- alignment-indexing - Index after coordinate sorting
- duplicate-handling - Requires name-sorted input for fixmate
- alignment-filtering - Filter before or after sorting
Security
- Security scanPassed, 90 of 100Pattern checks on the skill's files.
- Model reviewPassed
Quality evaluation
- Task evaluationNot runNo evaluation yet. Run one in Skill Studio.
Source
- SKILL.md in the repositoryCheckingskills/bioskills/bio-alignment-files-alignment-sorting/SKILL.md
Popularity
- 7-day trend score
- 5
Not refreshed yet.
Works with
Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.
- Claude Code
- Grok Build (Cursor)
- GitHub Copilot
- Windsurf
- Codex
- Gemini CLI
- Cline
- Amp
- Roo Code
- Goose
- Continue
- Kilo Code
- Junie
- Trae
- OpenHands
- Qwen Code
- AI Agent
- Tabnine Chat
- Sourcegraph Cody
- Amazon Q
- Firebase Genkit
- Sweep
- Devin
- Phind
- Mentat
- Claude Desktop
- Aider
- GPT Pilot
- Plandex
- bolt.new
- v0
- Replit Agent
- Anse
- TypingMind
- BetterChatGPT
- LibreChat
- Warp AI
- Pieces
- Fig AI
Embed badge
[](https://verified-skill.com/skills/pku-yuangroup/openai4s/bio-alignment-files-alignment-sorting)