pku-yuangroup/openai4s/bio-alignment-pairwise-alignment

Claude Code and agent skill by pku-yuangroup/openai4s

Trust tier 3
  • community
Source check pending

Checking that the SKILL.md file is still in the repository.

Perform pairwise sequence alignment using Biopython Bio.Align.PairwiseAligner. Use when comparing two sequences, finding optimal alignments, scoring similarity, and identifying local or global matches between DNA, RNA, or protein sequences.

Install

npx vskill@latest install pku-yuangroup/openai4s/bio-alignment-pairwise-alignment

SKILL.md

The same SKILL.md was published earlier as pku-yuangroup/openai4s/bio-alignment-pairwise-alignment.

Version Compatibility

Reference examples tested with: BioPython 1.83+

Before using code patterns, verify installed versions match. If versions differ:

  • Python: pip show <package> then help(module.function) to check signatures

If code throws ImportError, AttributeError, or TypeError, introspect the installed package and adapt the example to match the actual API rather than retrying.

Pairwise Sequence Alignment

"Align two sequences" -> Compute an optimal alignment between a pair of sequences using dynamic programming.

  • Python: PairwiseAligner() (BioPython Bio.Align)
  • CLI: needle (global) or water (local) from EMBOSS
  • R: pairwiseAlignment() (Biostrings)

Align two sequences using dynamic programming algorithms (Needleman-Wunsch for global, Smith-Waterman for local).

Required Import

Goal: Load modules needed for pairwise alignment operations.

Approach: Import the PairwiseAligner class along with sequence and I/O utilities from Biopython.

python
from Bio.Align import PairwiseAligner
from Bio.Seq import Seq
from Bio import SeqIO

Pairwise Library Selection

Bio.Align.PairwiseAligner is the right default for interactive use, scripting, and pair sizes up to a few thousand residues, but it is not the fastest or most scalable option. For high-throughput screens, very long sequences, or production pipelines, switch to a SIMD-accelerated or specialised library.

LibrarySpeed vs Bio.AlignAlphabetScoringVectorizationWhen to use
Bio.Align.PairwiseAligner (BioPython)1x baselineDNA / RNA / proteinMatrix + affineC-backed GotohDefault, <10 kb pairs, interactive use
parasail (Daily 2016 BMC Bioinf)10-100xDNA / proteinMatrix + affineSSE / AVX SIMDHigh-throughput SW or NW; benchmark loops
edlib (Sosic & Sikic 2017 Bioinf)100-1000xDNA onlyEdit distance onlyBit-parallel MyersRead mapping, k-mer search, primer placement
pywfa / WFA2 (Marco-Sola 2021 Bioinformatics 37:456; BiWFA: Marco-Sola 2023 Bioinformatics 39:btad074)Best for low-divergenceDNAMatrix + affineWavefront, O(s) memoryLong, near-identical sequences (>10 kb, <5% diverged)
mappy / minimap2 (Li 2018 Bioinf)Production reads-to-genomeDNAChain + base-levelk-mer chainLong-read mapping, splice-aware DNA
Bio.pairwise2DEPRECATED------Migrate to PairwiseAligner (deprecated in BioPython 1.80; not yet removed; migrate proactively)
EMBOSS needle / water~Bio.AlignDNA / proteinMatrix + affineNoneReproducibility, audit trails (fixed, documented default parameters)

Speed numbers in the table are rough; benchmark on representative inputs before committing. Critical caveats:

  • WFA / BiWFA: 10-100x faster than Gotoh below 5% divergence; above ~10% it converges to Gotoh complexity. Right tool for PacBio HiFi self-similarity or assembly-vs-reference; not for distant homologs.
  • edlib: 100-1000x faster than Gotoh at low divergence (<5% errors); above ~50% divergence the effective speedup drops to ~64x. For high-divergence DNA (<70% nucleotide identity), prefer parasail's SIMD score-only mode.
  • parasail: SIMD only realises its advantage on long sequences in amortised batch loops.

When uncertain which algorithm Biopython's aligner selected internally, inspect aligner.algorithm after configuration -- it returns the resolved variant ("Needleman-Wunsch", "Smith-Waterman", "Gotoh global alignment algorithm", "Gotoh local alignment algorithm", "Waterman-Smith-Beyer global alignment algorithm", "Waterman-Smith-Beyer local alignment algorithm") for deterministic auditing.

Core Concepts

ModeAlgorithmUse Case
globalNeedleman-WunschFull-length alignment, similar-length sequences
localSmith-WatermanFind best matching regions, different-length sequences
global + free end gapsSemi-globalOverlap detection, fragment-to-reference alignment
Choosing the Right Mode
  • Global: Both sequences are expected to be homologous over their full length (e.g., two orthologs of similar size). Forces end-to-end alignment.
  • Local: Conserved domains or motifs within otherwise dissimilar sequences. BLAST uses local alignment internally. Preferred when protein termini are highly divergent (termini accumulate mutations faster than core regions).
  • Semi-global: One sequence is a fragment or subsequence of the other (e.g., primer to template, read to reference, detecting overlap between shotgun reads). Free end gaps prevent penalizing unaligned flanking regions.

Common mistake: Global alignment of sequences with very different lengths forces biologically meaningless terminal gaps. If sequences differ substantially in length, use local or semi-global instead.

DNA vs Protein Alignment
ScenarioAlign AsRationale
Nucleotide identity >70%DNASufficient signal at nucleotide level
Nucleotide identity <70%ProteinCodon degeneracy masks signal at DNA level; protein alignment is ~3x more sensitive
Noncoding sequences (UTRs, intergenic)DNANo protein translation possible
Coding sequences for dN/dS analysisProtein first, then back-translate codons (PAL2NAL)Preserves reading frame for selection analysis

When in doubt, align at the protein level. It captures functional constraint better because 20 amino acids provide richer signal than 4 nucleotides.

Creating an Aligner

Goal: Configure a PairwiseAligner with appropriate scoring for the sequence type.

Approach: Instantiate PairwiseAligner with mode, scoring parameters, or a substitution matrix depending on DNA vs protein input.

python
# Basic aligner with defaults
aligner = PairwiseAligner()
# Configure mode and scoring
aligner = PairwiseAligner(mode='global', match_score=2, mismatch_score=-1, open_gap_score=-10, extend_gap_score=-0.5)
# For protein alignment with substitution matrix
from Bio.Align import substitution_matrices
aligner = PairwiseAligner(mode='global', substitution_matrix=substitution_matrices.load('BLOSUM62'))

Performing Alignments

"Align two sequences" -> Compute optimal alignment(s) between a pair of sequences, returning alignment objects or a score.

Goal: Align two sequences and retrieve the optimal alignment(s) or score.

Approach: Call aligner.align() for full alignment objects or aligner.score() for score-only (faster for large sequences).

python
seq1 = Seq('ACCGGTAACGTAG')
seq2 = Seq('ACCGTTAACGAAG')
# Get all optimal alignments
alignments = aligner.align(seq1, seq2)
print(f'Found {len(alignments)} optimal alignments')
print(alignments[0]) # Print first alignment
# Get score only (faster for large sequences)
score = aligner.score(seq1, seq2)

Alignment Output Format

target 0 ACCGGTAACGTAG 13
0 |||||.||||.|| 13
query 0 ACCGTTAACGAAG 13

Accessing Alignment Data

Goal: Extract alignment properties including score, shape, aligned sequences, and coordinate mappings.

Approach: Access alignment object attributes and indexing to retrieve per-sequence aligned strings and coordinate arrays.

python
alignment = alignments[0]
# Basic properties
print(alignment.score) # Alignment score
print(alignment.shape) # (num_seqs, alignment_length)
print(len(alignment)) # Alignment length
# Get aligned sequences with gaps
target_aligned = alignment[0, :] # First sequence (target) with gaps
query_aligned = alignment[1, :] # Second sequence (query) with gaps
# Get coordinate mapping
print(alignment.aligned) # Array of aligned segment coordinates
print(alignment.coordinates) # Full coordinate array

Alignment Counts (Identities, Mismatches, Gaps)

Goal: Quantify identities, mismatches, and gaps in an alignment to calculate percent identity.

Approach: Use the .counts() method on the alignment object and derive percent identity from identity and mismatch totals.

python
alignment = alignments[0]
counts = alignment.counts()
print(f'Identities: {counts.identities}')
print(f'Mismatches: {counts.mismatches}')
print(f'Gaps: {counts.gaps}')
# Calculate percent identity
total_aligned = counts.identities + counts.mismatches
percent_identity = counts.identities / total_aligned * 100
print(f'Percent identity: {percent_identity:.1f}%')

Common Scoring Configurations

PairwiseAligner Default Gap Penalties Are 0

PairwiseAligner() with no arguments uses match_score=1, mismatch_score=0, open_gap_score=0, extend_gap_score=0. Combined with a positive-scoring substitution matrix (BLOSUM62), this produces alignments with arbitrarily many short gaps -- gaps cost nothing while matches pay positive score. Always specify gap penalties explicitly when using a substitution matrix. BLASTP defaults: open=-11, extend=-1 with BLOSUM62; Smith-Waterman EMBOSS water defaults: open=-10, extend=-0.5. Inspect with print(aligner) after configuration to verify the resolved parameter set.

DNA/RNA Alignment
python
aligner = PairwiseAligner(mode='global', match_score=2, mismatch_score=-1, open_gap_score=-10, extend_gap_score=-0.5)
Protein Alignment
python
from Bio.Align import substitution_matrices
blosum62 = substitution_matrices.load('BLOSUM62')
aligner = PairwiseAligner(mode='global', substitution_matrix=blosum62, open_gap_score=-11, extend_gap_score=-1)
Local Alignment (Find Best Region)
python
aligner = PairwiseAligner(mode='local', match_score=2, mismatch_score=-1, open_gap_score=-10, extend_gap_score=-0.5)
Semiglobal (Overlap/Fragment Alignment)
python
# Free end gaps on query -- for aligning a fragment against a full-length reference
# or detecting overlap between reads
aligner = PairwiseAligner(mode='global')
aligner.query_left_open_gap_score = 0
aligner.query_left_extend_gap_score = 0
aligner.query_right_open_gap_score = 0
aligner.query_right_extend_gap_score = 0
# Free end gaps on BOTH sequences -- for overlap detection between two reads
aligner = PairwiseAligner(mode='global')
aligner.end_gap_score = 0.0

Substitution Matrix Selection

Goal: Select the appropriate substitution matrix based on expected sequence divergence.

Approach: Match matrix to divergence level. BLOSUM and PAM number in opposite directions: higher BLOSUM = closer sequences; higher PAM = more distant sequences.

Divergence LevelBLOSUMPAMWhen To Use
Very close (<20% divergence)BLOSUM80, BLOSUM90PAM30Recently duplicated genes, strain comparison
ModerateBLOSUM62 (default)PAM120General-purpose, most analyses
Distant (>50% divergence)BLOSUM45, BLOSUM50PAM250Remote homology detection

BLOSUM62 is the universal default (used by BLAST, most alignment tools). When in doubt, use BLOSUM62. Switch to BLOSUM80 for very similar proteins or BLOSUM45 for distant homologs.

DNA matrices: NUC.4.4 (match=+5, mismatch=-4) handles IUPAC ambiguity codes. HOXD70 is tuned for human-mouse whole-genome alignment from noncoding regions.

python
from Bio.Align import substitution_matrices
print(substitution_matrices.load()) # List all 30 available matrices
blosum62 = substitution_matrices.load('BLOSUM62') # General protein (default)
blosum80 = substitution_matrices.load('BLOSUM80') # Close homologs
blosum45 = substitution_matrices.load('BLOSUM45') # Distant homologs
nuc44 = substitution_matrices.load('NUC.4.4') # DNA with IUPAC support
Affine Gap Penalties: Biological Rationale

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 95 of 100Pattern checks on the skill's files.
  • Model reviewPassed

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

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
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/pku-yuangroup/openai4s/bio-alignment-pairwise-alignment/badge)](https://verified-skill.com/skills/pku-yuangroup/openai4s/bio-alignment-pairwise-alignment)

Something wrong with this skill or its page? Tell us.