Bio Alignment Sorting logo

Bio Alignment Sorting

Organization
PKU-YuanGroup
bio-alignment-sorting

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.

Overview

PublisherPKU-YuanGroup
RepositoryOpenAI4S
Skill namebio-alignment-sorting
Stars
622
Forks
72
Bundled files
2
LicenseMIT
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • 2 bundled files

    Scripts, templates, and references the model can read while it works. Files are read-only and never executed.

  • Open source

    Published by PKU-YuanGroup on GitHub. Read the source before you install it.

Installation

Install the Bio Alignment Sorting AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
    https://github.com/PKU-YuanGroup/OpenAI4S/tree/main/skills/bioskills/bio-alignment-files-alignment-sorting
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/PKU-YuanGroup/OpenAI4S.git /tmp/OpenAI4S
mkdir -p .claude/skills
cp -r /tmp/OpenAI4S/skills/bioskills/bio-alignment-files-alignment-sorting .claude/skills/bio-alignment-sorting
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Bio Alignment Sorting in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Bio Alignment Sorting on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Bio Alignment Sorting is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

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> 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).

  • CLI: samtools sort -o sorted.bam input.bam
  • Python: pysam.sort('-o', 'sorted.bam', 'input.bam')

Sort Orders

OrderFlagUse Case
CoordinatedefaultIndexing, visualization, variant calling
Name-nPaired-end processing, fixmate, markdup
Tag-t TAGSort 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

ToolAlgorithmSpeedMemoryOutput guarantee
sort -nFull lexicographic sort by QNAMESlowestSpills to -TStrict total order by name
collateHash-bucket grouping~3-10x fasterBoundedMates 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

OperationRequired sort
samtools indexcoordinate (hard requirement)
samtools fixmate -mname (or collate; needs mates adjacent)
samtools markdupcoordinate (after fixmate)
GATK MarkDuplicatesSparkcoordinate or queryname
samtools mpileup / bcftools mpileupcoordinate
GATK HaplotypeCaller, Mutect2coordinate
featureCounts / HTSeqcoordinate or name (-p for paired)
umi_tools dedupcoordinate (with index)
fgbio GroupReadsByUmiany order accepted (template-coordinate recommended to avoid an internal re-sort)
fgbio CallMolecularConsensusReadsgrouped by MI tag (consumes GroupReadsByUmi output)
Sniffles, cuteSV, Manta, Dellycoordinate (need SA tags)
Salmon alignment-modename
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<prev {exit 1} {prev=$4}'
# Simpler and authoritative: trust the @HD SO: header shown above.

pysam Python Alternative

Sort with pysam

python
import pysam

pysam.sort('-o', 'sorted.bam', 'input.bam')

Sort by Name

python
pysam.sort('-n', '-o', 'namesorted.bam', 'input.bam')

Sort with Options

python
pysam.sort('-@', '4', '-m', '2G', '-o', 'sorted.bam', 'input.bam')

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():

python
import pysam

pysam.sort('-@', '4', '-m', '2G', '-T', '/tmp/sortpfx',
           '-o', 'sorted.bam', 'input.bam')

Check Sort Order in pysam

python
import pysam

with pysam.AlignmentFile('input.bam', 'rb') as bam:
    hd = bam.header.get('HD', {})
    sort_order = hd.get('SO', 'unknown')
    print(f'Sort order: {sort_order}')

Stream Sort from Aligner

For streaming from aligners, use shell pipes (simpler and more reliable):

python
import subprocess

subprocess.run(
    'bwa mem ref.fa reads.fq | samtools sort -o aligned.bam',
    shell=True, check=True
)

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

bash
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"

Safe Merge (dedup @RG and @PG)

bash
# -c deduplicates @RG records; -p deduplicates @PG records (samtools-merge(1))
samtools merge -c -p -@ 8 merged.bam sample1.bam sample2.bam sample3.bam

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

bash
samtools merge -@ 4 merged.bam sample1.bam sample2.bam sample3.bam
samtools merge -b files.txt merged.bam   # one BAM path per line

Force Overwrite

bash
samtools merge -f merged.bam sample1.bam sample2.bam

Merge Specific Region

bash
samtools merge -R chr1:1000000-2000000 merged_region.bam sample1.bam sample2.bam

pysam Merge

python
import pysam

pysam.merge('-c', '-p', '-f', 'merged.bam', 'sample1.bam', 'sample2.bam', 'sample3.bam')

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

bash
bwa mem -t 8 ref.fa R1.fq R2.fq | samtools sort -@ 4 -o aligned.bam
samtools index aligned.bam

Re-sort by Name for Duplicate Marking

bash
# Full workflow: sort by name, fixmate, sort by coord, markdup
samtools sort -n -o namesorted.bam input.bam
samtools fixmate -m namesorted.bam fixmate.bam
samtools sort -o sorted.bam fixmate.bam
samtools markdup sorted.bam marked.bam

Convert Name-sorted to Coordinate-sorted

bash
samtools sort -o coord_sorted.bam name_sorted.bam
samtools index coord_sorted.bam

Extract FASTQ from Sorted BAM

bash
# Collate first to group pairs
samtools collate -u -O input.bam /tmp/collate | \
    samtools fastq -1 R1.fq -2 R2.fq -0 /dev/null -s /dev/null -

Performance Tips

ParameterEffect
-@ NUse N additional threads
-m SIZEMemory per thread (e.g., 4G)
-T PREFIXTemp file location (use fast SSD scratch)
-l LEVELCompression level (1-9, default 6)

Compression Level Decision

LevelUseWall-time vs defaultSize vs default
-l 0 / -uPipe between samtools tools0% (skips BGZF)+200-400%
-l 1Final output if disk is cheap~+10%~+30%
-l 6Defaultbaselinebaseline
-l 9Archival, write-once~+50-100%~-2-5%
bash
# WRONG -- pipe re-compresses then decompresses every step
samtools fixmate -m in.bam - | samtools sort -o out.bam

# RIGHT -- uncompressed (-u) between piped samtools commands
samtools fixmate -m -u in.bam - | samtools sort -o out.bam

Optimal Settings for Large Files

bash
# 8 threads, 2GB per thread, low compression for output written to fast disk
samtools sort -@ 8 -m 2G -l 1 -T /scratch/sortpfx -o sorted.bam input.bam

Quick Reference

TaskCommand
Sort by coordinatesamtools sort -o out.bam in.bam
Sort by namesamtools sort -n -o out.bam in.bam
Sort with threadssamtools sort -@ 8 -o out.bam in.bam
Collate pairssamtools collate -o out.bam in.bam
Merge BAMssamtools merge out.bam in1.bam in2.bam
Check sort ordersamtools view -H in.bam | grep "^@HD"
Sort + indexsamtools sort -o out.bam in.bam && samtools index out.bam

Common Errors

ErrorCauseSolution
out of memoryInsufficient RAMUse -m to limit per-thread memory
disk fullTemp files filling diskUse -T to specify different location
truncated fileInterrupted sortRe-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

Bundled files

The model reads these on demand while the skill is loaded. They are exposed as readable files and are never executed.

Frequently asked questions

What does the Bio Alignment Sorting AI skill do?

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.

Why use Bio Alignment Sorting on TypingMind?

Because you install it once and use it with any model. Bio Alignment Sorting is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Bio Alignment Sorting in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/PKU-YuanGroup/OpenAI4S/tree/main/skills/bioskills/bio-alignment-files-alignment-sorting. TypingMind reads its SKILL.md and bundles its files and installs it as a skill you can enable per chat.

Which AI models can use Bio Alignment Sorting?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Bio Alignment Sorting?

As many as you like. As long as a model supports skills, you can use Bio Alignment Sorting with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Bio Alignment Sorting AI skill free?

Yes. It is published on GitHub by PKU-YuanGroup under the MIT license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇