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.4---567# scikit-bio89## Overview1011scikit-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.1213## When to Use This Skill1415This skill should be used when the user:16- Works with biological sequences (DNA, RNA, protein)17- Needs to read/write biological file formats (FASTA, FASTQ, GenBank, Newick, BIOM, etc.)18- Performs sequence alignments or searches for motifs19- Constructs or analyzes phylogenetic trees20- Calculates diversity metrics (alpha/beta diversity, UniFrac distances)21- Performs ordination analysis (PCoA, CCA, RDA)22- Runs statistical tests on biological/ecological data (PERMANOVA, ANOSIM, Mantel)23- Analyzes microbiome or community ecology data24- Works with protein embeddings from language models25- Needs to manipulate biological data tables2627## Core Capabilities2829### 1. Sequence Manipulation3031Work with biological sequences using specialized classes for DNA, RNA, and protein data.3233**Key operations:**34- Read/write sequences from FASTA, FASTQ, GenBank, EMBL formats35- Sequence slicing, concatenation, and searching36- Reverse complement, transcription (DNA→RNA), and translation (RNA→protein)37- Find motifs and patterns using regex38- Calculate distances (Hamming, k-mer based)39- Handle sequence quality scores and metadata4041**Common patterns:**42```python43import skbio4445# Read sequences from file46seq = skbio.DNA.read('input.fasta')4748# Sequence operations49rc = seq.reverse_complement()50rna = seq.transcribe()51protein = rna.translate()5253# Find motifs54motif_positions = seq.find_with_regex('ATG[ACGT]{3}')5556# Check for properties57has_degens = seq.has_degenerates()58seq_no_gaps = seq.degap()59```6061**Important notes:**62- Use `DNA`, `RNA`, `Protein` classes for grammared sequences with validation63- Use `Sequence` class for generic sequences without alphabet restrictions64- Quality scores automatically loaded from FASTQ files into positional metadata65- Metadata types: sequence-level (ID, description), positional (per-base), interval (regions/features)6667### 2. Sequence Alignment6869Perform pairwise and multiple sequence alignments using the `pair_align` engine (introduced in scikit-bio 0.7.0), a versatile and efficient dynamic-programming aligner.7071**Key capabilities:**72- Global, local, and semi-global alignment (free ends configurable) in one function73- Convenience wrappers `pair_align_nucl` (BLASTN-like) and `pair_align_prot` (BLASTP-like)74- Configurable scoring: match/mismatch tuple or named substitution matrix; linear or affine gap penalties75- `PairAlignPath` results carry CIGAR strings and convert to aligned sequences76- Multiple sequence alignment storage and manipulation with `TabularMSA`7778**Common patterns:**79```python80from skbio import DNA, Protein81from skbio.alignment import pair_align_nucl, pair_align_prot, pair_align, TabularMSA8283# Nucleotide alignment with BLASTN-like defaults84seq1, seq2 = DNA('ACTACCAGATTACTTACGGATCAGG'), DNA('CGAAACTACTAGATTACGGATCTTA')85aln = pair_align_nucl(seq1, seq2)86aln.score # alignment score (float)87path = aln.paths[0] # PairAlignPath (repr shows CIGAR)88aligned_seqs = path.to_aligned((seq1, seq2)) # list of gapped strings8990# Build a TabularMSA from the alignment path + original sequences91msa = TabularMSA.from_path_seqs(path, (seq1, seq2))9293# Customize the algorithm via pair_align (default mode='global')94aln = pair_align(seq1, seq2, mode='local') # Smith-Waterman95aln = pair_align(seq1, seq2, sub_score=(2, -3), gap_cost=(5, 2)) # affine gaps96aln = pair_align(seq1, seq2, sub_score='NUC.4.4', gap_cost=3) # substitution matrix, linear gap9798# Protein alignment (BLASTP-like, BLOSUM62)99aln = pair_align_prot(Protein('HEAGAWGHEE'), Protein('PAWHEAE'))100101# Read a multiple alignment from file and summarize102msa = TabularMSA.read('alignment.fasta', constructor=DNA)103consensus = msa.consensus()104```105106**Important notes:**107- `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.)108- The result is a `PairAlignResult` that also unpacks as `score, paths, matrices` (use `keep_matrices=True` to retain the DP matrix)109- `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)110- 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(...)`111112### 3. Phylogenetic Trees113114Construct, manipulate, and analyze phylogenetic trees representing evolutionary relationships.115116**Key capabilities:**117- Tree construction from distance matrices (UPGMA/WPGMA, Neighbor Joining, GME, BME)118- Tree rearrangement with nearest neighbor interchange (`nni`)119- Tree manipulation (pruning, rerooting, traversal)120- Distance calculations (patristic via `cophenet`, Robinson-Foulds via `compare_rfd`)121- ASCII visualization122- Newick format I/O123124**Common patterns:**125```python126from skbio import TreeNode127from skbio.tree import nj, upgma, gme, bme, rf_dists128129# Read tree from file130tree = TreeNode.read('tree.nwk')131132# Construct tree from distance matrix133tree = nj(distance_matrix)134135# Tree operations136subtree = tree.shear(['taxon1', 'taxon2', 'taxon3'])137tips = [node for node in tree.tips()]138lca = tree.lca(['taxon1', 'taxon2'])139140# Calculate distances141patristic_dist = tree.find('taxon1').distance(tree.find('taxon2'))142cophenetic_dm = tree.cophenet() # patristic distance matrix among tips143144# Compare two trees (Robinson-Foulds)145rf_distance = tree.compare_rfd(other_tree)146# Pairwise RF distances among many trees -> DistanceMatrix147rf_dm = rf_dists([tree, other_tree, third_tree])148```149150**Important notes:**151- Use `nj()` for neighbor joining (classic phylogenetic method)152- Use `upgma()` for UPGMA/WPGMA (assumes molecular clock)153- GME and BME are highly scalable for large trees; refine topology with `nni()`154- `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)155- `lca()` is the lowest common ancestor; `lowest_common_ancestor` remains as an alias156- Trees can be rooted or unrooted; some metrics require specific rooting157158### 4. Diversity Analysis159160Calculate alpha and beta diversity metrics for microbial ecology and community analysis.161162**Key capabilities:**163- Alpha diversity: richness (`sobs`, `observed_features`, `chao1`, `ace`), Shannon, Simpson, Hill numbers (`hill`), Faith's PD (`faith_pd`), generalized PD (`phydiv`), Pielou's evenness164- Beta diversity: Bray-Curtis, Jaccard, weighted/unweighted UniFrac, Euclidean distances165- Phylogenetic diversity metrics (require tree input)166- Rarefaction and subsampling167- Integration with ordination and statistical tests168169**Common patterns:**170```python171from skbio.diversity import alpha_diversity, beta_diversity172173# Alpha diversity (phylogenetic metrics take taxa= for tip-name mapping)174alpha = alpha_diversity('shannon', counts_matrix, ids=sample_ids)175faith_pd = alpha_diversity('faith_pd', counts_matrix, ids=sample_ids,176 tree=tree, taxa=feature_ids)177178# Beta diversity179bc_dm = beta_diversity('braycurtis', counts_matrix, ids=sample_ids)180unifrac_dm = beta_diversity('unweighted_unifrac', counts_matrix,181 ids=sample_ids, tree=tree, taxa=feature_ids)182183# Get available metrics184from skbio.diversity import get_alpha_diversity_metrics185print(get_alpha_diversity_metrics())186```187188**Important notes:**189- Counts must be integers representing abundances, not relative frequencies190- 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`)191- `counts_matrix` may be any table-like input (NumPy array, pandas/polars DataFrame, BIOM `Table`, or AnnData) via the dispatch system192- Phylogenetic metrics (Faith's PD, UniFrac) require tree and taxa-to-tip mapping193- Use `partial_beta_diversity()` for specific sample pairs, or `block_beta_diversity()` for large block-decomposed calculations194- Alpha diversity returns a `pandas.Series`, beta diversity returns a `DistanceMatrix`195196### 5. Ordination Methods197198Reduce high-dimensional biological data to visualizable lower-dimensional spaces.199200**Key capabilities:**201- PCoA (Principal Coordinate Analysis) from distance matrices202- CA (Correspondence Analysis) for contingency tables203- CCA (Canonical Correspondence Analysis) with environmental constraints204- RDA (Redundancy Analysis) for linear relationships205- Biplot projection for feature interpretation206207**Common patterns:**208```python209from skbio.stats.ordination import pcoa, cca210import skbio211212# PCoA from distance matrix (limit dimensions for large matrices)213pcoa_results = pcoa(distance_matrix, dimensions=3)214pc1 = pcoa_results.samples['PC1']215pc2 = pcoa_results.samples['PC2']216217# Built-in scatter plot colored by a metadata column218fig = pcoa_results.plot(sample_metadata, column='bodysite')219220# CCA with environmental variables221cca_results = cca(species_matrix, environmental_matrix)222223# Save/load ordination results224pcoa_results.write('ordination.txt')225results = skbio.OrdinationResults.read('ordination.txt')226```227228**Important notes:**229- 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)230- `OrdinationResults` exposes pandas-based attributes: `samples`, `features`, `eigvals`, `proportion_explained`, `biplot_scores`, `sample_constraints`231- CCA reveals environmental drivers of community composition232- `OrdinationResults.plot()` produces a matplotlib figure; results also integrate with seaborn/plotly233234### 6. Statistical Testing235236Perform hypothesis tests specific to ecological and biological data.237238**Key capabilities:**239- PERMANOVA: test group differences using distance matrices240- ANOSIM: alternative test for group differences241- PERMDISP: test homogeneity of group dispersions242- Mantel test: correlation between distance matrices243- Bioenv: find environmental variables correlated with distances244- Differential abundance: `ancom`, `dirmult_ttest`, and `dirmult_lme` (longitudinal mixed-effects) in `skbio.stats.composition`245246**Common patterns:**247```python248from skbio.stats.distance import permanova, anosim, mantel249250# Test if groups differ significantly251permanova_results = permanova(distance_matrix, grouping, permutations=999)252print(f"p-value: {permanova_results['p-value']}")253254# ANOSIM test255anosim_results = anosim(distance_matrix, grouping, permutations=999)256257# Mantel test between two distance matrices258mantel_results = mantel(dm1, dm2, method='pearson', permutations=999)259print(f"Correlation: {mantel_results[0]}, p-value: {mantel_results[1]}")260261# Differential abundance on a feature table (raw counts recommended)262from skbio.stats.composition import dirmult_ttest263da = dirmult_ttest(counts_table, grouping, treatment='caseA', reference='control')264```265266**Important notes:**267- Permutation tests provide non-parametric significance testing268- Use 999+ permutations for robust p-values269- PERMANOVA sensitive to dispersion differences; pair with PERMDISP270- Mantel tests assess matrix correlation (e.g., geographic vs genetic distance)271- Supply differential-abundance tests with raw counts, not pre-normalized proportions, to preserve magnitude information272273### 7. File I/O and Format Conversion274275Read and write 19+ biological file formats with automatic format detection.276277**Supported formats:**278- Sequences: FASTA, FASTQ, GenBank, EMBL, QSeq279- Alignments: Clustal, PHYLIP, Stockholm280- Trees: Newick281- Tables: BIOM (HDF5 and JSON)282- Distances: delimited square matrices283- Analysis: BLAST+6/7, GFF3, Ordination results284- Metadata: TSV/CSV with validation285286**Common patterns:**287```python288import skbio289290# Read with automatic format detection291seq = skbio.DNA.read('file.fasta', format='fasta')292tree = skbio.TreeNode.read('tree.nwk')293294# Write to file295seq.write('output.fasta', format='fasta')296297# Generator for large files (memory efficient)298for seq in skbio.io.read('large.fasta', format='fasta', constructor=skbio.DNA):299 process(seq)300301# Convert formats302seqs = list(skbio.io.read('input.fastq', format='fastq', constructor=skbio.DNA))303skbio.io.write(seqs, format='fasta', into='output.fasta')304```305306**Important notes:**307- Use generators for large files to avoid memory issues308- Format can be auto-detected when `into` parameter specified309- Some objects can be written to multiple formats310- Support for stdin/stdout piping with `verify=False`311312### 8. Distance Matrices313314Create and manipulate distance/dissimilarity matrices with statistical methods.315316**Key capabilities:**317- Store symmetric (`DistanceMatrix`, hollow diagonal) or general pairwise (`PairwiseMatrix`) data318- ID-based indexing and slicing319- Integration with diversity, ordination, and statistical tests320- Read/write delimited text format321322**Common patterns:**323```python324from skbio import DistanceMatrix325import numpy as np326327# Create from array328data = np.array([[0, 1, 2], [1, 0, 3], [2, 3, 0]])329dm = DistanceMatrix(data, ids=['A', 'B', 'C'])330331# Access distances332dist_ab = dm['A', 'B']333row_a = dm['A']334335# Read from file336dm = DistanceMatrix.read('distances.txt')337338# Use in downstream analyses339pcoa_results = pcoa(dm)340permanova_results = permanova(dm, grouping)341```342343**Important notes:**344- `DistanceMatrix` enforces symmetry and a zero (hollow) diagonal; it is a subclass of `SymmetricMatrix`345- `PairwiseMatrix` (renamed from `DissimilarityMatrix`, which is kept as a deprecated alias) allows general/asymmetric values346- IDs enable integration with metadata and biological knowledge347- Compatible with pandas, numpy, and scikit-learn348349### 9. Biological Tables350351Work with feature tables (OTU/ASV tables) common in microbiome research.352353**Key capabilities:**354- BIOM format I/O (HDF5 and JSON) via the native `Table` class355- Table dispatch system (0.7.0+): functions accept any `table_like` input — BIOM `Table`, pandas/polars DataFrame, NumPy array, or AnnData — without explicit conversion356- Data augmentation techniques (`phylomix`, `mixup`, `aitchison_mixup`, `compos_cutmix`)357- Sample/feature filtering and normalization358- Metadata integration359360**Common patterns:**361```python362from skbio import Table363from skbio.diversity import beta_diversity364365# Read BIOM table366table = Table.read('table.biom')367368# Access data369sample_ids = table.ids(axis='sample')370feature_ids = table.ids(axis='observation')371counts = table.matrix_data372373# Filter374filtered = table.filter(sample_ids_to_keep, axis='sample')375376# Pass table-like objects directly to scikit-bio drivers (dispatch system)377import pandas as pd378df = pd.read_table('data.tsv', index_col=0) # samples x features379bdiv = beta_diversity('braycurtis', df) # no manual conversion needed380```381382**Important notes:**383- BIOM tables are standard in QIIME 2 workflows384- Rows typically represent samples, columns represent features (OTUs/ASVs)385- Supports sparse and dense representations386- With the dispatch system, functions return the same format as their input, or a user-specified output format387388### 10. Protein Embeddings389390Work with protein language model embeddings for downstream analysis.391392**Key capabilities:**393- Store embeddings from protein language models (ESM, ProtTrans, etc.)394- Convert embeddings to distance matrices395- Generate ordination objects for visualization396- Export to numpy/pandas for ML workflows397398**Common patterns:**399```python400from skbio.embedding import ProteinEmbedding, ProteinVector401402# Create embedding from array403embedding = ProteinEmbedding(embedding_array, sequence_ids)404405# Convert to distance matrix for analysis406dm = embedding.to_distances(metric='euclidean')407408# PCoA visualization of embedding space409pcoa_results = embedding.to_ordination(metric='euclidean', method='pcoa')410411# Export for machine learning412array = embedding.to_array()413df = embedding.to_dataframe()414```415416**Important notes:**417- Embeddings bridge protein language models with traditional bioinformatics418- Compatible with scikit-bio's distance/ordination/statistics ecosystem419- SequenceEmbedding and ProteinEmbedding provide specialized functionality420- Useful for sequence clustering, classification, and visualization421422## Best Practices423424### Installation425```bash426uv pip install scikit-bio427```428Requires 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`.429430### Performance Considerations431- Use generators for large sequence files to minimize memory usage432- For massive phylogenetic trees, prefer GME or BME over NJ433- Beta diversity calculations can be parallelized with `partial_beta_diversity()`434- BIOM format (HDF5) more efficient than JSON for large tables435436### Integration with Ecosystem437- Sequences interoperate with Biopython via standard formats438- Tables integrate with pandas, polars, and AnnData439- Distance matrices compatible with scikit-learn440- Ordination results visualizable with matplotlib/seaborn/plotly441- Works seamlessly with QIIME 2 artifacts (BIOM, trees, distance matrices)442443### Common Workflows4441. **Microbiome diversity analysis**: Read BIOM table → Calculate alpha/beta diversity → Ordination (PCoA) → Statistical testing (PERMANOVA)4452. **Phylogenetic analysis**: Read sequences → Align → Build distance matrix → Construct tree → Calculate phylogenetic distances4463. **Sequence processing**: Read FASTQ → Quality filter → Trim/clean → Find motifs → Translate → Write FASTA4474. **Comparative genomics**: Read sequences → Pairwise alignment → Calculate distances → Build tree → Analyze clades448449## Reference Documentation450451For detailed API information, parameter specifications, and advanced usage examples, refer to `references/api_reference.md` which contains comprehensive documentation on:452- Complete method signatures and parameters for all capabilities453- Extended code examples for complex workflows454- Troubleshooting common issues455- Performance optimization tips456- Integration patterns with other libraries457458## Additional Resources459460- Official documentation: https://scikit.bio/docs/latest/461- GitHub repository: https://github.com/scikit-bio/scikit-bio462- Changelog: https://github.com/scikit-bio/scikit-bio/blob/main/CHANGELOG.md463- Reference paper: "scikit-bio: a fundamental Python library for biological omic data," *Nature Methods* (2025), https://www.nature.com/articles/s41592-025-02981-z464- Forum support: https://forum.qiime2.org (scikit-bio is part of QIIME 2 ecosystem)465466---467468**Source:** [`K-Dense-AI/scientific-agent-skills`](https://github.com/K-Dense-AI/scientific-agent-skills) → `skills/scikit-bio/SKILL.md`