scikit-bio
Overview
scikit-bio is a comprehensive Python library for working with biological data. Apply this skill for bioinformatics analyses spanning sequence manipulation, alignment, phylogenetics, microbial ecology, and multivariate statistics.
When to Use This Skill
This skill should be used when the user:
- Works with biological sequences (DNA, RNA, protein)
- Needs to read/write biological file formats (FASTA, FASTQ, GenBank, Newick, BIOM, etc.)
- Performs sequence alignments or searches for motifs
- Constructs or analyzes phylogenetic trees
- Calculates diversity metrics (alpha/beta diversity, UniFrac distances)
- Performs ordination analysis (PCoA, CCA, RDA)
- Runs statistical tests on biological/ecological data (PERMANOVA, ANOSIM, Mantel)
- Analyzes microbiome or community ecology data
- Works with protein embeddings from language models
- Needs to manipulate biological data tables
Core Capabilities
1. Sequence Manipulation
Work with biological sequences using specialized classes for DNA, RNA, and protein data.
Key operations:
- Read/write sequences from FASTA, FASTQ, GenBank, EMBL formats
- Sequence slicing, concatenation, and searching
- Reverse complement, transcription (DNA→RNA), and translation (RNA→protein)
- Find motifs and patterns using regex
- Calculate distances (Hamming, k-mer based)
- Handle sequence quality scores and metadata
Common patterns:
import skbio
# Read sequences from file
seq = skbio.DNA.read('input.fasta')
# Sequence operations
rc = seq.reverse_complement()
rna = seq.transcribe()
protein = rna.translate()
# Find motifs
motif_positions = seq.find_with_regex('ATG[ACGT]{3}')
# Check for properties
has_degens = seq.has_degenerates()
seq_no_gaps = seq.degap()
Important notes:
- Use
DNA, RNA, Protein classes for grammared sequences with validation
- Use
Sequence class for generic sequences without alphabet restrictions
- Quality scores automatically loaded from FASTQ files into positional metadata
- Metadata types: sequence-level (ID, description), positional (per-base), interval (regions/features)
2. Sequence Alignment
Perform pairwise and multiple sequence alignments using the pair_align engine (introduced in scikit-bio 0.7.0), a versatile and efficient dynamic-programming aligner.
Key capabilities:
- Global, local, and semi-global alignment (free ends configurable) in one function
- Convenience wrappers
pair_align_nucl (BLASTN-like) and pair_align_prot (BLASTP-like)
- Configurable scoring: match/mismatch tuple or named substitution matrix; linear or affine gap penalties
PairAlignPath results carry CIGAR strings and convert to aligned sequences
- Multiple sequence alignment storage and manipulation with
TabularMSA
Common patterns:
from skbio import DNA, Protein
from skbio.alignment import pair_align_nucl, pair_align_prot, pair_align, TabularMSA
# Nucleotide alignment with BLASTN-like defaults
seq1, seq2 = DNA('ACTACCAGATTACTTACGGATCAGG'), DNA('CGAAACTACTAGATTACGGATCTTA')
aln = pair_align_nucl(seq1, seq2)
aln.score # alignment score (float)
path = aln.paths[0] # PairAlignPath (repr shows CIGAR)
aligned_seqs = path.to_aligned((seq1, seq2)) # list of gapped strings
# Build a TabularMSA from the alignment path + original sequences
msa = TabularMSA.from_path_seqs(path, (seq1, seq2))
# Customize the algorithm via pair_align (default mode='global')
aln = pair_align(seq1, seq2, mode='local') # Smith-Waterman
aln = pair_align(seq1, seq2, sub_score=(2, -3), gap_cost=(5, 2)) # affine gaps
aln = pair_align(seq1, seq2, sub_score='NUC.4.4', gap_cost=3) # substitution matrix, linear gap
# Protein alignment (BLASTP-like, BLOSUM62)
aln = pair_align_prot(Protein('HEAGAWGHEE'), Protein('PAWHEAE'))
# Read a multiple alignment from file and summarize
msa = TabularMSA.read('alignment.fasta', constructor=DNA)
consensus = msa.consensus()
Important notes:
pair_align replaces the removed SSW wrapper (local_pairwise_align_ssw, StripedSmithWaterman) and the deprecated pure-Python aligners (global_pairwise_align, local_pairwise_align_nucleotide, etc.)
- The result is a
PairAlignResult that also unpacks as score, paths, matrices (use keep_matrices=True to retain the DP matrix)
sub_score accepts a (match, mismatch) tuple or a matrix name (e.g., 'NUC.4.4', 'BLOSUM62'); gap_cost accepts a single number (linear) or (open, extend) tuple (affine)
- Parse external CIGAR strings with
PairAlignPath.from_cigar('1I8M2D5M2I'); score an existing alignment with align_score(...) and build a distance matrix from an MSA with align_dists(...)
3. Phylogenetic Trees
Construct, manipulate, and analyze phylogenetic trees representing evolutionary relationships.
Key capabilities:
- Tree construction from distance matrices (UPGMA/WPGMA, Neighbor Joining, GME, BME)
- Tree rearrangement with nearest neighbor interchange (
nni)
- Tree manipulation (pruning, rerooting, traversal)
- Distance calculations (patristic via
cophenet, Robinson-Foulds via compare_rfd)
- ASCII visualization
- Newick format I/O
Common patterns:
from skbio import TreeNode
from skbio.tree import nj, upgma, gme, bme, rf_dists
# Read tree from file
tree = TreeNode.read('tree.nwk')
# Construct tree from distance matrix
tree = nj(distance_matrix)
# Tree operations
subtree = tree.shear(['taxon1', 'taxon2', 'taxon3'])
tips = [node for node in tree.tips()]
lca = tree.lca(['taxon1', 'taxon2'])
# Calculate distances
patristic_dist = tree.find('taxon1').distance(tree.find('taxon2'))
cophenetic_dm = tree.cophenet() # patristic distance matrix among tips
# Compare two trees (Robinson-Foulds)
rf_distance = tree.compare_rfd(other_tree)
# Pairwise RF distances among many trees -> DistanceMatrix
rf_dm = rf_dists([tree, other_tree, third_tree])
Important notes:
- Use
nj() for neighbor joining (classic phylogenetic method)
- Use
upgma() for UPGMA/WPGMA (assumes molecular clock)
- GME and BME are highly scalable for large trees; refine topology with
nni()
cophenet() (formerly tip_tip_distances) returns the patristic distance matrix; compare_rfd() is the Robinson-Foulds method (compare_wrfd/compare_cophenet for weighted/cophenetic variants)
lca() is the lowest common ancestor; lowest_common_ancestor remains as an alias
- Trees can be rooted or unrooted; some metrics require specific rooting
4. Diversity Analysis
Calculate alpha and beta diversity metrics for microbial ecology and community analysis.
Key capabilities:
- Alpha diversity: richness (
sobs, observed_features, chao1, ace), Shannon, Simpson, Hill numbers (hill), Faith's PD (faith_pd), generalized PD (phydiv), Pielou's evenness
- Beta diversity: Bray-Curtis, Jaccard, weighted/unweighted UniFrac, Euclidean distances
- Phylogenetic diversity metrics (require tree input)
- Rarefaction and subsampling
- Integration with ordination and statistical tests
Common patterns:
from skbio.diversity import alpha_diversity, beta_diversity
# Alpha diversity (phylogenetic metrics take taxa= for tip-name mapping)
alpha = alpha_diversity('shannon', counts_matrix, ids=sample_ids)
faith_pd = alpha_diversity('faith_pd', counts_matrix, ids=sample_ids,
tree=tree, taxa=feature_ids)
# Beta diversity
bc_dm = beta_diversity('braycurtis', counts_matrix, ids=sample_ids)
unifrac_dm = beta_diversity('unweighted_unifrac', counts_matrix,
ids=sample_ids, tree=tree, taxa=feature_ids)
# Get available metrics
from skbio.diversity import get_alpha_diversity_metrics
print(get_alpha_diversity_metrics())
Important notes:
- Counts must be integers representing abundances, not relative frequencies
- The phylogenetic-metric argument is
taxa= (renamed from otu_ids in 0.6.0; the old name is a deprecated alias); observed_otus is now observed_features (or sobs)
counts_matrix may be any table-like input (NumPy array, pandas/polars DataFrame, BIOM Table, or AnnData) via the dispatch system
- Phylogenetic metrics (Faith's PD, UniFrac) require tree and taxa-to-tip mapping
- Use
partial_beta_diversity() for specific sample pairs, or block_beta_diversity() for large block-decomposed calculations
- Alpha diversity returns a
pandas.Series, beta diversity returns a DistanceMatrix
5. Ordination Methods
Reduce high-dimensional biological data to visualizable lower-dimensional spaces.
Key capabilities:
- PCoA (Principal Coordinate Analysis) from distance matrices
- CA (Correspondence Analysis) for contingency tables
- CCA (Canonical Correspondence Analysis) with environmental constraints
- RDA (Redundancy Analysis) for linear relationships
- Biplot projection for feature interpretation
Common patterns:
from skbio.stats.ordination import pcoa, cca
import skbio
# PCoA from distance matrix (limit dimensions for large matrices)
pcoa_results = pcoa(distance_matrix, dimensions=3)
pc1 = pcoa_results.samples['PC1']
pc2 = pcoa_results.samples['PC2']
# Built-in scatter plot colored by a metadata column
fig = pcoa_results.plot(sample_metadata, column='bodysite')
# CCA with environmental variables
cca_results = cca(species_matrix, environmental_matrix)
# Save/load ordination results
pcoa_results.write('ordination.txt')
results = skbio.OrdinationResults.read('ordination.txt')
Important notes:
- PCoA works with any distance/dissimilarity matrix; pass
dimensions as an int (count) or a float in (0, 1] (fraction of cumulative variance to retain)
OrdinationResults exposes pandas-based attributes: samples, features, eigvals, proportion_explained, biplot_scores, sample_constraints
- CCA reveals environmental drivers of community composition
OrdinationResults.plot() produces a matplotlib figure; results also integrate with seaborn/plotly
6. Statistical Testing
Perform hypothesis tests specific to ecological and biological data.
Key capabilities:
- PERMANOVA: test group differences using distance matrices
- ANOSIM: alternative test for group differences
- PERMDISP: test homogeneity of group dispersions
- Mantel test: correlation between distance matrices
- Bioenv: find environmental variables correlated with distances
- Differential abundance:
ancom, dirmult_ttest, and dirmult_lme (longitudinal mixed-effects) in skbio.stats.composition
Common patterns:
from skbio.stats.distance import permanova, anosim, mantel
# Test if groups differ significantly
permanova_results = permanova(distance_matrix, grouping, permutations=999)
print(f"p-value: {permanova_results['p-value']}")
# ANOSIM test
anosim_results = anosim(distance_matrix, grouping, permutations=999)
# Mantel test between two distance matrices
mantel_results = mantel(dm1, dm2, method='pearson', permutations=999)
print(f"Correlation: {mantel_results[0]}, p-value: {mantel_results[1]}")
# Differential abundance on a feature table (raw counts recommended)
from skbio.stats.composition import dirmult_ttest
da = dirmult_ttest(counts_table, grouping, treatment='caseA', reference='control')
Important notes:
- Permutation tests provide non-parametric significance testing
- Use 999+ permutations for robust p-values
- PERMANOVA sensitive to dispersion differences; pair with PERMDISP
- Mantel tests assess matrix correlation (e.g., geographic vs genetic distance)
- Supply differential-abundance tests with raw counts, not pre-normalized proportions, to preserve magnitude information
7. File I/O and Format Conversion
Read and write 19+ biological file formats with automatic format detection.
Supported formats:
- Sequences: FASTA, FASTQ, GenBank, EMBL, QSeq
- Alignments: Clustal, PHYLIP, Stockholm
- Trees: Newick
- Tables: BIOM (HDF5 and JSON)
- Distances: delimited square matrices
- Analysis: BLAST+6/7, GFF3, Ordination results
- Metadata: TSV/CSV with validation
Common patterns:
import skbio
# Read with automatic format detection
seq = skbio.DNA.read('file.fasta', format='fasta')
tree = skbio.TreeNode.read('tree.nwk')
# Write to file
seq.write('output.fasta', format='fasta')
# Generator for large files (memory efficient)
for seq in skbio.io.read('large.fasta', format='fasta', constructor=skbio.DNA):
process(seq)
# Convert formats
seqs = list(skbio.io.read('input.fastq', format='fastq', constructor=skbio.DNA))
skbio.io.write(seqs, format='fasta', into='output.fasta')
Important notes:
- Use generators for large files to avoid memory issues
- Format can be auto-detected when
into parameter specified
- Some objects can be written to multiple formats
- Support for stdin/stdout piping with
verify=False
8. Distance Matrices
Create and manipulate distance/dissimilarity matrices with statistical methods.
Key capabilities:
- Store symmetric (
DistanceMatrix, hollow diagonal) or general pairwise (PairwiseMatrix) data
- ID-based indexing and slicing
- Integration with diversity, ordination, and statistical tests
- Read/write delimited text format
Common patterns:
from skbio import DistanceMatrix
import numpy as np
# Create from array
data = np.array([[0, 1, 2], [1, 0, 3], [2, 3, 0]])
dm = DistanceMatrix(data, ids=['A', 'B', 'C'])
# Access distances
dist_ab = dm['A', 'B']
row_a = dm['A']
# Read from file
dm = DistanceMatrix.read('distances.txt')
# Use in downstream analyses
pcoa_results = pcoa(dm)
permanova_results = permanova(dm, grouping)
Important notes:
DistanceMatrix enforces symmetry and a zero (hollow) diagonal; it is a subclass of SymmetricMatrix
PairwiseMatrix (renamed from DissimilarityMatrix, which is kept as a deprecated alias) allows general/asymmetric values
- IDs enable integration with metadata and biological knowledge
- Compatible with pandas, numpy, and scikit-learn
9. Biological Tables
Work with feature tables (OTU/ASV tables) common in microbiome research.
Key capabilities:
- BIOM format I/O (HDF5 and JSON) via the native
Table class
- Table dispatch system (0.7.0+): functions accept any
table_like input — BIOM Table, pandas/polars DataFrame, NumPy array, or AnnData — without explicit conversion
- Data augmentation techniques (
phylomix, mixup, aitchison_mixup, compos_cutmix)
- Sample/feature filtering and normalization
- Metadata integration
Common patterns:
from skbio import Table
from skbio.diversity import beta_diversity
# Read BIOM table
table = Table.read('table.biom')
# Access data
sample_ids = table.ids(axis='sample')
feature_ids = table.ids(axis='observation')
counts = table.matrix_data
# Filter
filtered = table.filter(sample_ids_to_keep, axis='sample')
# Pass table-like objects directly to scikit-bio drivers (dispatch system)
import pandas as pd
df = pd.read_table('data.tsv', index_col=0) # samples x features
bdiv = beta_diversity('braycurtis', df) # no manual conversion needed
Important notes:
- BIOM tables are standard in QIIME 2 workflows
- Rows typically represent samples, columns represent features (OTUs/ASVs)
- Supports sparse and dense representations
- With the dispatch system, functions return the same format as their input, or a user-specified output format
10. Protein Embeddings
Work with protein language model embeddings for downstream analysis.
Key capabilities:
- Store embeddings from protein language models (ESM, ProtTrans, etc.)
- Convert embeddings to distance matrices
- Generate ordination objects for visualization
- Export to numpy/pandas for ML workflows
Common patterns:
from skbio.embedding import ProteinEmbedding, ProteinVector
# Create embedding from array
embedding = ProteinEmbedding(embedding_array, sequence_ids)
# Convert to distance matrix for analysis
dm = embedding.to_distances(metric='euclidean')
# PCoA visualization of embedding space
pcoa_results = embedding.to_ordination(metric='euclidean', method='pcoa')
# Export for machine learning
array = embedding.to_array()
df = embedding.to_dataframe()
Important notes:
- Embeddings bridge protein language models with traditional bioinformatics
- Compatible with scikit-bio's distance/ordination/statistics ecosystem
- SequenceEmbedding and ProteinEmbedding provide specialized functionality
- Useful for sequence clustering, classification, and visualization
Best Practices
Installation
uv pip install scikit-bio
Requires Python 3.10+ and NumPy 2.0+. Pre-compiled wheels are published for each release since 0.7.0, so most platforms install without a compiler. Conda users can instead run conda install -c conda-forge scikit-bio.
Performance Considerations
- Use generators for large sequence files to minimize memory usage
- For massive phylogenetic trees, prefer GME or BME over NJ
- Beta diversity calculations can be parallelized with
partial_beta_diversity()
- BIOM format (HDF5) more efficient than JSON for large tables
Integration with Ecosystem
- Sequences interoperate with Biopython via standard formats
- Tables integrate with pandas, polars, and AnnData
- Distance matrices compatible with scikit-learn
- Ordination results visualizable with matplotlib/seaborn/plotly
- Works seamlessly with QIIME 2 artifacts (BIOM, trees, distance matrices)
Common Workflows
- Microbiome diversity analysis: Read BIOM table → Calculate alpha/beta diversity → Ordination (PCoA) → Statistical testing (PERMANOVA)
- Phylogenetic analysis: Read sequences → Align → Build distance matrix → Construct tree → Calculate phylogenetic distances
- Sequence processing: Read FASTQ → Quality filter → Trim/clean → Find motifs → Translate → Write FASTA
- Comparative genomics: Read sequences → Pairwise alignment → Calculate distances → Build tree → Analyze clades
Reference Documentation
For detailed API information, parameter specifications, and advanced usage examples, refer to references/api_reference.md which contains comprehensive documentation on:
- Complete method signatures and parameters for all capabilities
- Extended code examples for complex workflows
- Troubleshooting common issues
- Performance optimization tips
- Integration patterns with other libraries
Additional Resources
Source: K-Dense-AI/scientific-agent-skills → skills/scikit-bio/SKILL.md
1---2name: scikit-bio3description: "Biological data toolkit. Sequence analysis, alignments, phylogenetic trees, diversity metrics (alpha/beta, UniFrac), ordination (PCoA), PERMANOVA, FASTA/Newick I/O, for microbiome analysis."4allowed-tools: "Read Write Edit Bash"5category: general-purpose6source_repo: K-Dense-AI/scientific-agent-skills7source_path: "skills/scikit-bio/SKILL.md"8source_url: https://github.com/K-Dense-AI/scientific-agent-skills/blob/HEAD/skills/scikit-bio/SKILL.md9metadata:10 source: https://skillmd.com/skills/thedixitjain/scikit-bio11---121314# scikit-bio1516## Overview1718scikit-bio is a comprehensive Python library for working with biological data. Apply this skill for bioinformatics analyses spanning sequence manipulation, alignment, phylogenetics, microbial ecology, and multivariate statistics.1920## When to Use This Skill2122This skill should be used when the user:23- Works with biological sequences (DNA, RNA, protein)24- Needs to read/write biological file formats (FASTA, FASTQ, GenBank, Newick, BIOM, etc.)25- Performs sequence alignments or searches for motifs26- Constructs or analyzes phylogenetic trees27- Calculates diversity metrics (alpha/beta diversity, UniFrac distances)28- Performs ordination analysis (PCoA, CCA, RDA)29- Runs statistical tests on biological/ecological data (PERMANOVA, ANOSIM, Mantel)30- Analyzes microbiome or community ecology data31- Works with protein embeddings from language models32- Needs to manipulate biological data tables3334## Core Capabilities3536### 1. Sequence Manipulation3738Work with biological sequences using specialized classes for DNA, RNA, and protein data.3940**Key operations:**41- Read/write sequences from FASTA, FASTQ, GenBank, EMBL formats42- Sequence slicing, concatenation, and searching43- Reverse complement, transcription (DNA→RNA), and translation (RNA→protein)44- Find motifs and patterns using regex45- Calculate distances (Hamming, k-mer based)46- Handle sequence quality scores and metadata4748**Common patterns:**49```python50import skbio5152# Read sequences from file53seq = skbio.DNA.read('input.fasta')5455# Sequence operations56rc = seq.reverse_complement()57rna = seq.transcribe()58protein = rna.translate()5960# Find motifs61motif_positions = seq.find_with_regex('ATG[ACGT]{3}')6263# Check for properties64has_degens = seq.has_degenerates()65seq_no_gaps = seq.degap()66```6768**Important notes:**69- Use `DNA`, `RNA`, `Protein` classes for grammared sequences with validation70- Use `Sequence` class for generic sequences without alphabet restrictions71- Quality scores automatically loaded from FASTQ files into positional metadata72- Metadata types: sequence-level (ID, description), positional (per-base), interval (regions/features)7374### 2. Sequence Alignment7576Perform pairwise and multiple sequence alignments using the `pair_align` engine (introduced in scikit-bio 0.7.0), a versatile and efficient dynamic-programming aligner.7778**Key capabilities:**79- Global, local, and semi-global alignment (free ends configurable) in one function80- Convenience wrappers `pair_align_nucl` (BLASTN-like) and `pair_align_prot` (BLASTP-like)81- Configurable scoring: match/mismatch tuple or named substitution matrix; linear or affine gap penalties82- `PairAlignPath` results carry CIGAR strings and convert to aligned sequences83- Multiple sequence alignment storage and manipulation with `TabularMSA`8485**Common patterns:**86```python87from skbio import DNA, Protein88from skbio.alignment import pair_align_nucl, pair_align_prot, pair_align, TabularMSA8990# Nucleotide alignment with BLASTN-like defaults91seq1, seq2 = DNA('ACTACCAGATTACTTACGGATCAGG'), DNA('CGAAACTACTAGATTACGGATCTTA')92aln = pair_align_nucl(seq1, seq2)93aln.score # alignment score (float)94path = aln.paths[0] # PairAlignPath (repr shows CIGAR)95aligned_seqs = path.to_aligned((seq1, seq2)) # list of gapped strings9697# Build a TabularMSA from the alignment path + original sequences98msa = TabularMSA.from_path_seqs(path, (seq1, seq2))99100# Customize the algorithm via pair_align (default mode='global')101aln = pair_align(seq1, seq2, mode='local') # Smith-Waterman102aln = pair_align(seq1, seq2, sub_score=(2, -3), gap_cost=(5, 2)) # affine gaps103aln = pair_align(seq1, seq2, sub_score='NUC.4.4', gap_cost=3) # substitution matrix, linear gap104105# Protein alignment (BLASTP-like, BLOSUM62)106aln = pair_align_prot(Protein('HEAGAWGHEE'), Protein('PAWHEAE'))107108# Read a multiple alignment from file and summarize109msa = TabularMSA.read('alignment.fasta', constructor=DNA)110consensus = msa.consensus()111```112113**Important notes:**114- `pair_align` replaces the removed SSW wrapper (`local_pairwise_align_ssw`, `StripedSmithWaterman`) and the deprecated pure-Python aligners (`global_pairwise_align`, `local_pairwise_align_nucleotide`, etc.)115- The result is a `PairAlignResult` that also unpacks as `score, paths, matrices` (use `keep_matrices=True` to retain the DP matrix)116- `sub_score` accepts a `(match, mismatch)` tuple or a matrix name (e.g., `'NUC.4.4'`, `'BLOSUM62'`); `gap_cost` accepts a single number (linear) or `(open, extend)` tuple (affine)117- Parse external CIGAR strings with `PairAlignPath.from_cigar('1I8M2D5M2I')`; score an existing alignment with `align_score(...)` and build a distance matrix from an MSA with `align_dists(...)`118119### 3. Phylogenetic Trees120121Construct, manipulate, and analyze phylogenetic trees representing evolutionary relationships.122123**Key capabilities:**124- Tree construction from distance matrices (UPGMA/WPGMA, Neighbor Joining, GME, BME)125- Tree rearrangement with nearest neighbor interchange (`nni`)126- Tree manipulation (pruning, rerooting, traversal)127- Distance calculations (patristic via `cophenet`, Robinson-Foulds via `compare_rfd`)128- ASCII visualization129- Newick format I/O130131**Common patterns:**132```python133from skbio import TreeNode134from skbio.tree import nj, upgma, gme, bme, rf_dists135136# Read tree from file137tree = TreeNode.read('tree.nwk')138139# Construct tree from distance matrix140tree = nj(distance_matrix)141142# Tree operations143subtree = tree.shear(['taxon1', 'taxon2', 'taxon3'])144tips = [node for node in tree.tips()]145lca = tree.lca(['taxon1', 'taxon2'])146147# Calculate distances148patristic_dist = tree.find('taxon1').distance(tree.find('taxon2'))149cophenetic_dm = tree.cophenet() # patristic distance matrix among tips150151# Compare two trees (Robinson-Foulds)152rf_distance = tree.compare_rfd(other_tree)153# Pairwise RF distances among many trees -> DistanceMatrix154rf_dm = rf_dists([tree, other_tree, third_tree])155```156157**Important notes:**158- Use `nj()` for neighbor joining (classic phylogenetic method)159- Use `upgma()` for UPGMA/WPGMA (assumes molecular clock)160- GME and BME are highly scalable for large trees; refine topology with `nni()`161- `cophenet()` (formerly `tip_tip_distances`) returns the patristic distance matrix; `compare_rfd()` is the Robinson-Foulds method (`compare_wrfd`/`compare_cophenet` for weighted/cophenetic variants)162- `lca()` is the lowest common ancestor; `lowest_common_ancestor` remains as an alias163- Trees can be rooted or unrooted; some metrics require specific rooting164165### 4. Diversity Analysis166167Calculate alpha and beta diversity metrics for microbial ecology and community analysis.168169**Key capabilities:**170- Alpha diversity: richness (`sobs`, `observed_features`, `chao1`, `ace`), Shannon, Simpson, Hill numbers (`hill`), Faith's PD (`faith_pd`), generalized PD (`phydiv`), Pielou's evenness171- Beta diversity: Bray-Curtis, Jaccard, weighted/unweighted UniFrac, Euclidean distances172- Phylogenetic diversity metrics (require tree input)173- Rarefaction and subsampling174- Integration with ordination and statistical tests175176**Common patterns:**177```python178from skbio.diversity import alpha_diversity, beta_diversity179180# Alpha diversity (phylogenetic metrics take taxa= for tip-name mapping)181alpha = alpha_diversity('shannon', counts_matrix, ids=sample_ids)182faith_pd = alpha_diversity('faith_pd', counts_matrix, ids=sample_ids,183 tree=tree, taxa=feature_ids)184185# Beta diversity186bc_dm = beta_diversity('braycurtis', counts_matrix, ids=sample_ids)187unifrac_dm = beta_diversity('unweighted_unifrac', counts_matrix,188 ids=sample_ids, tree=tree, taxa=feature_ids)189190# Get available metrics191from skbio.diversity import get_alpha_diversity_metrics192print(get_alpha_diversity_metrics())193```194195**Important notes:**196- Counts must be integers representing abundances, not relative frequencies197- The phylogenetic-metric argument is `taxa=` (renamed from `otu_ids` in 0.6.0; the old name is a deprecated alias); `observed_otus` is now `observed_features` (or `sobs`)198- `counts_matrix` may be any table-like input (NumPy array, pandas/polars DataFrame, BIOM `Table`, or AnnData) via the dispatch system199- Phylogenetic metrics (Faith's PD, UniFrac) require tree and taxa-to-tip mapping200- Use `partial_beta_diversity()` for specific sample pairs, or `block_beta_diversity()` for large block-decomposed calculations201- Alpha diversity returns a `pandas.Series`, beta diversity returns a `DistanceMatrix`202203### 5. Ordination Methods204205Reduce high-dimensional biological data to visualizable lower-dimensional spaces.206207**Key capabilities:**208- PCoA (Principal Coordinate Analysis) from distance matrices209- CA (Correspondence Analysis) for contingency tables210- CCA (Canonical Correspondence Analysis) with environmental constraints211- RDA (Redundancy Analysis) for linear relationships212- Biplot projection for feature interpretation213214**Common patterns:**215```python216from skbio.stats.ordination import pcoa, cca217import skbio218219# PCoA from distance matrix (limit dimensions for large matrices)220pcoa_results = pcoa(distance_matrix, dimensions=3)221pc1 = pcoa_results.samples['PC1']222pc2 = pcoa_results.samples['PC2']223224# Built-in scatter plot colored by a metadata column225fig = pcoa_results.plot(sample_metadata, column='bodysite')226227# CCA with environmental variables228cca_results = cca(species_matrix, environmental_matrix)229230# Save/load ordination results231pcoa_results.write('ordination.txt')232results = skbio.OrdinationResults.read('ordination.txt')233```234235**Important notes:**236- PCoA works with any distance/dissimilarity matrix; pass `dimensions` as an int (count) or a float in (0, 1] (fraction of cumulative variance to retain)237- `OrdinationResults` exposes pandas-based attributes: `samples`, `features`, `eigvals`, `proportion_explained`, `biplot_scores`, `sample_constraints`238- CCA reveals environmental drivers of community composition239- `OrdinationResults.plot()` produces a matplotlib figure; results also integrate with seaborn/plotly240241### 6. Statistical Testing242243Perform hypothesis tests specific to ecological and biological data.244245**Key capabilities:**246- PERMANOVA: test group differences using distance matrices247- ANOSIM: alternative test for group differences248- PERMDISP: test homogeneity of group dispersions249- Mantel test: correlation between distance matrices250- Bioenv: find environmental variables correlated with distances251- Differential abundance: `ancom`, `dirmult_ttest`, and `dirmult_lme` (longitudinal mixed-effects) in `skbio.stats.composition`252253**Common patterns:**254```python255from skbio.stats.distance import permanova, anosim, mantel256257# Test if groups differ significantly258permanova_results = permanova(distance_matrix, grouping, permutations=999)259print(f"p-value: {permanova_results['p-value']}")260261# ANOSIM test262anosim_results = anosim(distance_matrix, grouping, permutations=999)263264# Mantel test between two distance matrices265mantel_results = mantel(dm1, dm2, method='pearson', permutations=999)266print(f"Correlation: {mantel_results[0]}, p-value: {mantel_results[1]}")267268# Differential abundance on a feature table (raw counts recommended)269from skbio.stats.composition import dirmult_ttest270da = dirmult_ttest(counts_table, grouping, treatment='caseA', reference='control')271```272273**Important notes:**274- Permutation tests provide non-parametric significance testing275- Use 999+ permutations for robust p-values276- PERMANOVA sensitive to dispersion differences; pair with PERMDISP277- Mantel tests assess matrix correlation (e.g., geographic vs genetic distance)278- Supply differential-abundance tests with raw counts, not pre-normalized proportions, to preserve magnitude information279280### 7. File I/O and Format Conversion281282Read and write 19+ biological file formats with automatic format detection.283284**Supported formats:**285- Sequences: FASTA, FASTQ, GenBank, EMBL, QSeq286- Alignments: Clustal, PHYLIP, Stockholm287- Trees: Newick288- Tables: BIOM (HDF5 and JSON)289- Distances: delimited square matrices290- Analysis: BLAST+6/7, GFF3, Ordination results291- Metadata: TSV/CSV with validation292293**Common patterns:**294```python295import skbio296297# Read with automatic format detection298seq = skbio.DNA.read('file.fasta', format='fasta')299tree = skbio.TreeNode.read('tree.nwk')300301# Write to file302seq.write('output.fasta', format='fasta')303304# Generator for large files (memory efficient)305for seq in skbio.io.read('large.fasta', format='fasta', constructor=skbio.DNA):306 process(seq)307308# Convert formats309seqs = list(skbio.io.read('input.fastq', format='fastq', constructor=skbio.DNA))310skbio.io.write(seqs, format='fasta', into='output.fasta')311```312313**Important notes:**314- Use generators for large files to avoid memory issues315- Format can be auto-detected when `into` parameter specified316- Some objects can be written to multiple formats317- Support for stdin/stdout piping with `verify=False`318319### 8. Distance Matrices320321Create and manipulate distance/dissimilarity matrices with statistical methods.322323**Key capabilities:**324- Store symmetric (`DistanceMatrix`, hollow diagonal) or general pairwise (`PairwiseMatrix`) data325- ID-based indexing and slicing326- Integration with diversity, ordination, and statistical tests327- Read/write delimited text format328329**Common patterns:**330```python331from skbio import DistanceMatrix332import numpy as np333334# Create from array335data = np.array([[0, 1, 2], [1, 0, 3], [2, 3, 0]])336dm = DistanceMatrix(data, ids=['A', 'B', 'C'])337338# Access distances339dist_ab = dm['A', 'B']340row_a = dm['A']341342# Read from file343dm = DistanceMatrix.read('distances.txt')344345# Use in downstream analyses346pcoa_results = pcoa(dm)347permanova_results = permanova(dm, grouping)348```349350**Important notes:**351- `DistanceMatrix` enforces symmetry and a zero (hollow) diagonal; it is a subclass of `SymmetricMatrix`352- `PairwiseMatrix` (renamed from `DissimilarityMatrix`, which is kept as a deprecated alias) allows general/asymmetric values353- IDs enable integration with metadata and biological knowledge354- Compatible with pandas, numpy, and scikit-learn355356### 9. Biological Tables357358Work with feature tables (OTU/ASV tables) common in microbiome research.359360**Key capabilities:**361- BIOM format I/O (HDF5 and JSON) via the native `Table` class362- Table dispatch system (0.7.0+): functions accept any `table_like` input — BIOM `Table`, pandas/polars DataFrame, NumPy array, or AnnData — without explicit conversion363- Data augmentation techniques (`phylomix`, `mixup`, `aitchison_mixup`, `compos_cutmix`)364- Sample/feature filtering and normalization365- Metadata integration366367**Common patterns:**368```python369from skbio import Table370from skbio.diversity import beta_diversity371372# Read BIOM table373table = Table.read('table.biom')374375# Access data376sample_ids = table.ids(axis='sample')377feature_ids = table.ids(axis='observation')378counts = table.matrix_data379380# Filter381filtered = table.filter(sample_ids_to_keep, axis='sample')382383# Pass table-like objects directly to scikit-bio drivers (dispatch system)384import pandas as pd385df = pd.read_table('data.tsv', index_col=0) # samples x features386bdiv = beta_diversity('braycurtis', df) # no manual conversion needed387```388389**Important notes:**390- BIOM tables are standard in QIIME 2 workflows391- Rows typically represent samples, columns represent features (OTUs/ASVs)392- Supports sparse and dense representations393- With the dispatch system, functions return the same format as their input, or a user-specified output format394395### 10. Protein Embeddings396397Work with protein language model embeddings for downstream analysis.398399**Key capabilities:**400- Store embeddings from protein language models (ESM, ProtTrans, etc.)401- Convert embeddings to distance matrices402- Generate ordination objects for visualization403- Export to numpy/pandas for ML workflows404405**Common patterns:**406```python407from skbio.embedding import ProteinEmbedding, ProteinVector408409# Create embedding from array410embedding = ProteinEmbedding(embedding_array, sequence_ids)411412# Convert to distance matrix for analysis413dm = embedding.to_distances(metric='euclidean')414415# PCoA visualization of embedding space416pcoa_results = embedding.to_ordination(metric='euclidean', method='pcoa')417418# Export for machine learning419array = embedding.to_array()420df = embedding.to_dataframe()421```422423**Important notes:**424- Embeddings bridge protein language models with traditional bioinformatics425- Compatible with scikit-bio's distance/ordination/statistics ecosystem426- SequenceEmbedding and ProteinEmbedding provide specialized functionality427- Useful for sequence clustering, classification, and visualization428429## Best Practices430431### Installation432```bash433uv pip install scikit-bio434```435Requires Python 3.10+ and NumPy 2.0+. Pre-compiled wheels are published for each release since 0.7.0, so most platforms install without a compiler. Conda users can instead run `conda install -c conda-forge scikit-bio`.436437### Performance Considerations438- Use generators for large sequence files to minimize memory usage439- For massive phylogenetic trees, prefer GME or BME over NJ440- Beta diversity calculations can be parallelized with `partial_beta_diversity()`441- BIOM format (HDF5) more efficient than JSON for large tables442443### Integration with Ecosystem444- Sequences interoperate with Biopython via standard formats445- Tables integrate with pandas, polars, and AnnData446- Distance matrices compatible with scikit-learn447- Ordination results visualizable with matplotlib/seaborn/plotly448- Works seamlessly with QIIME 2 artifacts (BIOM, trees, distance matrices)449450### Common Workflows4511. **Microbiome diversity analysis**: Read BIOM table → Calculate alpha/beta diversity → Ordination (PCoA) → Statistical testing (PERMANOVA)4522. **Phylogenetic analysis**: Read sequences → Align → Build distance matrix → Construct tree → Calculate phylogenetic distances4533. **Sequence processing**: Read FASTQ → Quality filter → Trim/clean → Find motifs → Translate → Write FASTA4544. **Comparative genomics**: Read sequences → Pairwise alignment → Calculate distances → Build tree → Analyze clades455456## Reference Documentation457458For detailed API information, parameter specifications, and advanced usage examples, refer to `references/api_reference.md` which contains comprehensive documentation on:459- Complete method signatures and parameters for all capabilities460- Extended code examples for complex workflows461- Troubleshooting common issues462- Performance optimization tips463- Integration patterns with other libraries464465## Additional Resources466467- Official documentation: https://scikit.bio/docs/latest/468- GitHub repository: https://github.com/scikit-bio/scikit-bio469- Changelog: https://github.com/scikit-bio/scikit-bio/blob/main/CHANGELOG.md470- Reference paper: "scikit-bio: a fundamental Python library for biological omic data," *Nature Methods* (2025), https://www.nature.com/articles/s41592-025-02981-z471- Forum support: https://forum.qiime2.org (scikit-bio is part of QIIME 2 ecosystem)472473---474475**Source:** [`K-Dense-AI/scientific-agent-skills`](https://github.com/K-Dense-AI/scientific-agent-skills) → `skills/scikit-bio/SKILL.md`