bio-alignment-io
Read, write, and convert multiple sequence alignment files using Biopython Bio.AlignIO. Supports Clustal, PHYLIP, Stockholm, FASTA, Nexus, and other alignment formats for phylogenetics and conservation analysis. Use when reading, writing, or converting alignment file formats.
What this skill does
## 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.
# Alignment File I/O
Read, write, and convert multiple sequence alignment files in various formats.
## Required Import
**Goal:** Load modules for reading, writing, and manipulating multiple sequence alignments.
**Approach:** Import AlignIO for file I/O and supporting classes for programmatic alignment construction.
```python
from Bio import AlignIO
from Bio.Align import MultipleSeqAlignment
from Bio.SeqRecord import SeqRecord
from Bio.Seq import Seq
```
## Format Coverage Map
Three Python libraries cover the alignment-format space, with overlapping but non-identical support. Pick by what is actually required.
| Format | `Bio.AlignIO` | `Bio.Align` (modern) | `pyhmmer.easel` | Notes |
|--------|---------------|----------------------|-----------------|-------|
| Aligned FASTA | R/W | R/W | R/W | Most portable; loses annotations |
| Clustal | R/W | R/W | R | Clustal conservation marks NOT round-tripped |
| PHYLIP (interleaved/sequential/relaxed) | R/W | R/W | R | Strict 10-char names is silent footgun |
| Stockholm | R/W | R/W | R/W | Only format preserving GS/GR/GC/GF annotations |
| NEXUS | R/W | R/W | -- | MrBayes / PAUP* input |
| MAF (Multiple Alignment Format) | R/W | R/W | -- | UCSC whole-genome alignments |
| A2M / A3M | -- (use `'fasta'` parser then post-process) | -- | R/W | HMMER (a2m), HHsuite/ColabFold (a3m) |
| MSF (GCG) | R | -- | -- | GCG legacy |
| EMBOSS / Mauve XMFA / FASTA-m10 | R | partial | -- | One-way: read-only |
**Formats NOT in BioPython** (use dedicated tools):
| Format | Tool | Why |
|--------|------|-----|
| HAL | progressiveCactus, halTools | HDF5-backed multi-genome alignments at TB scale |
| chain / net | UCSC Kent tools (`liftOver`, `chainNet`) | Pairwise genome alignment |
| AXT | BLASTZ / lastz native | Pairwise alignment blocks |
| PSL | UCSC Kent tools (`pslPretty`, `blat`) | BLAT alignment summary |
| GFA / rGFA | `vg`, `odgi`, `pggb`, gfatools | Pangenome graph |
| GAF | `vg surject`, `vg call` | Graph alignment format (read-to-graph) |
Recommend `Bio.Align` (modern API) over `Bio.AlignIO` (legacy) for new code; it returns `Alignment` objects with built-in `.counts()` and `.substitutions` properties. For multi-gigabyte Stockholm databases such as Pfam-A.full, `pyhmmer.easel.MSAFile` streams record-by-record where `Bio.AlignIO.parse` works but at higher per-record cost.
## Reading Alignments
**"Read an alignment file"** -> Parse an alignment file into an alignment object with sequences and metadata accessible.
**Goal:** Load alignment data from files in various formats (Clustal, PHYLIP, Stockholm, FASTA).
**Approach:** Use `AlignIO.read()` for single-alignment files or `AlignIO.parse()` for files containing multiple alignments.
### Single Alignment File
```python
from Bio import AlignIO
alignment = AlignIO.read('alignment.aln', 'clustal')
print(f'Alignment length: {alignment.get_alignment_length()}')
print(f'Number of sequences: {len(alignment)}')
```
### Multiple Alignments in One File
```python
for alignment in AlignIO.parse('multi_alignment.sto', 'stockholm'):
print(f'Alignment with {len(alignment)} sequences, length {alignment.get_alignment_length()}')
```
### Read as List
```python
alignments = list(AlignIO.parse('alignments.phy', 'phylip'))
print(f'Read {len(alignments)} alignments')
```
## Writing Alignments
**Goal:** Save alignment data to files in standard formats for downstream tools or archival.
**Approach:** Use `AlignIO.write()` with the target format specifier, supporting single or multiple alignments and file handles.
### Write Single Alignment
```python
AlignIO.write(alignment, 'output.fasta', 'fasta')
```
### Write Multiple Alignments
```python
alignments = [alignment1, alignment2, alignment3]
count = AlignIO.write(alignments, 'output.sto', 'stockholm')
print(f'Wrote {count} alignments')
```
### Write to Handle
```python
with open('output.aln', 'w') as handle:
AlignIO.write(alignment, handle, 'clustal')
```
## Format Conversion
**"Convert alignment format"** -> Transform an alignment file from one format to another (e.g., Clustal to PHYLIP).
**Goal:** Convert alignment files between formats for compatibility with different analysis tools.
**Approach:** Use `AlignIO.convert()` for direct one-step conversion, or read-modify-write for cases requiring intermediate manipulation.
### Direct Conversion (Most Efficient)
```python
AlignIO.convert('input.aln', 'clustal', 'output.phy', 'phylip')
```
### With Alphabet Specification
```python
AlignIO.convert('input.sto', 'stockholm', 'output.nex', 'nexus', molecule_type='DNA')
```
### Manual Conversion (When Modification Needed)
```python
alignment = AlignIO.read('input.aln', 'clustal')
# ... modify alignment ...
AlignIO.write(alignment, 'output.fasta', 'fasta')
```
## Accessing Alignment Data
**Goal:** Navigate and extract data from alignment objects including sequences, columns, and slices.
**Approach:** Use iteration, indexing, and column slicing on the alignment object.
```python
alignment = AlignIO.read('alignment.aln', 'clustal')
# Iterate over sequences
for record in alignment:
print(f'{record.id}: {record.seq}')
# Access by index
first_seq = alignment[0]
last_seq = alignment[-1]
# Slice columns
column_slice = alignment[:, 10:20] # Columns 10-19
# Get specific column
column = alignment[:, 5] # Column 5 as string
```
## Working with Alignment Objects
### Get Alignment Properties
```python
alignment = AlignIO.read('alignment.aln', 'clustal')
length = alignment.get_alignment_length()
num_seqs = len(alignment)
seq_ids = [record.id for record in alignment]
```
### Slice Alignments
```python
# Get subset of sequences
subset = alignment[0:5] # First 5 sequences
# Get subset of columns
trimmed = alignment[:, 50:150] # Columns 50-149
# Combine slicing
region = alignment[0:5, 50:150] # 5 sequences, columns 50-149
```
## Creating Alignments Programmatically
**Goal:** Build an alignment object from sequences defined in code rather than read from a file.
**Approach:** Construct SeqRecord objects with gap characters and wrap them in a MultipleSeqAlignment.
```python
from Bio.Align import MultipleSeqAlignment
from Bio.SeqRecord import SeqRecord
from Bio.Seq import Seq
records = [
SeqRecord(Seq('ACTGACTGACTG'), id='seq1'),
SeqRecord(Seq('ACTGACT-ACTG'), id='seq2'),
SeqRecord(Seq('ACTG-CTGACTG'), id='seq3'),
]
alignment = MultipleSeqAlignment(records)
AlignIO.write(alignment, 'new_alignment.fasta', 'fasta')
```
## Format Selection for Downstream Tools
Choosing the output format depends on which downstream tool consumes the alignment:
| Downstream Tool | Required Format | BioPython Format String |
|----------------|-----------------|------------------------|
| RAxML-NG, IQ-TREE | PHYLIP (relaxed) | `'phylip-relaxed'` |
| MrBayes | NEXUS | `'nexus'` |
| PAUP* | NEXUS or PHYLIP | `'nexus'` or `'phylip'` |
| HMMER, Infernal | Stockholm | `'stockholm'` |
| Pfam/Rfam databases | Stockholm | `'stockholm'` |
| PAML/codeml | PHYLIP (sequential) | `'phylip-sequential'` |
| Most tools | FASTA | `'fasta'` |
### Annotation Preservation
Not all formats support annotations. Converting between formats can silently discard metadata:
| Format | Sequence Annotations | Column Annotations | Secondary Structure |
|--------|---------------------|-------------------|-------------------|
| Stockholm | Yes (GS/GR lines) | Yes (GC lines) | Yes (SS_cons) |
| NEXUS | Partial (SETS block) | Via CHARSET | No |
| Clustal | No (conservation marks not parsed) | No | No |
| PHYLIP | No | No | No |
| FASTA | No | No | No |
ConveRelated in Writing & Docs
jax-development
IncludedUse this skill when the user is writing, debugging, profiling, refactoring, reviewing, benchmarking, parallelising, exporting, or explaining JAX code, or when they mention JAX, jax.numpy, jit, grad, value_and_grad, vmap, scan, lax, random keys, pytrees, jax.Array, sharding, Mesh, PartitionSpec, NamedSharding, pmap, shard_map, Pallas, XLA, StableHLO, checkify, profiler, or the JAX repo. It helps turn NumPy or PyTorch-style code into pure functional JAX, fix tracer/control-flow/shape/PRNG bugs, remove recompiles and host-device syncs, choose transforms and sharding strategies, inspect jaxpr/lowering/IR, and benchmark compiled code correctly.
nature-article-writer
IncludedDrafts, rewrites, diagnostically critiques, and style-calibrates primary research manuscripts for Nature and Nature Portfolio journals. Use when the user wants a Nature-style title, summary paragraph or abstract, introduction, results, discussion, methods, figure legends, presubmission enquiry, cover letter, reviewer response, or when a scientific draft sounds generic, jargon-heavy, structurally weak, or AI-ish and needs precise, broad-reader-friendly prose without inventing data, analyses, or references. Best for primary research articles and letters rather than reviews or press releases unless explicitly adapting one.
deckrd
IncludedDocument-driven framework that derives requirements, specifications, implementation plans, and executable tasks from goals through structured AI dialogue. Use when user says "write requirements", "create spec", "plan implementation", "derive tasks", "structure this feature", "break down into tasks", or "document this module". Also use for reverse engineering existing code into docs (/deckrd rev). Do NOT use for direct code writing — use /deckrd-coder after tasks are generated. Do NOT use when the user only wants to run or fix existing code without planning.
clinical-decision-support
IncludedGenerate professional clinical decision support (CDS) documents for pharmaceutical and clinical research settings, including patient cohort analyses (biomarker-stratified with outcomes) and treatment recommendation reports (evidence-based guidelines with decision algorithms). Supports GRADE evidence grading, statistical analysis (hazard ratios, survival curves, waterfall plots), biomarker integration, and regulatory compliance. Outputs publication-ready LaTeX/PDF format optimized for drug development, clinical research, and evidence synthesis.
handling-sf-data
IncludedSalesforce data operations with 130-point scoring. Use this skill to create, update, delete, bulk import/export, generate test data, and clean up org records using sf CLI and anonymous Apex. TRIGGER when: user creates test data, performs bulk import/export, uses sf data CLI commands, needs data factory patterns for Apex tests, or needs to seed/clean records in a Salesforce org. DO NOT TRIGGER when: SOQL query writing only (use querying-soql), Apex test execution (use running-apex-tests), or metadata deployment (use deploying-metadata).
accelint-ac-to-playwright
IncludedConvert and validate acceptance criteria for Playwright test automation. Use when user asks to (1) review/evaluate/check if AC are ready for automation, (2) assess if AC can be converted as-is, (3) validate AC quality for Playwright, (4) turn AC into tests, (5) generate tests from acceptance criteria, (6) convert .md bullets or .feature Gherkin files to Playwright specs, (7) create test automation from requirements. Handles both bullet-style markdown and Gherkin syntax with JSON test plan generation and validation.