Turn any AI agent into an AI Scientist. The #1 Agent Skills library for science, used by 250,000+ scientists worldwide. 177 ready-to-use validated skills plus 100+ scientific databases covering biology, chemistry, medicine, and drug discovery. Compatible with Cursor, Claude Code, Codex, Pi, Antigravity, and the open Agent Skills standard.
Python agent-skillsai-scientistbioinformaticschemoinformaticsclaudeclaude-skillsclaudecodeclinical-researchcomputational-biologydata-analysisdrug-discoverygenomicsmaterials-sciencemetabolomicsproteomicsscientific-computingscientific-visualization
Update scikit-bio
Timothy Kassis450905e71cb8
diff --git a/docs/skills.md b/docs/skills.mdindex 0baee2fa..76da2388 100644--- a/docs/skills.md+++ b/docs/skills.md@@ -61,7 +61,7 @@### Data Management & Infrastructure- **LaminDB** - Open-source data framework for biology that makes data queryable, traceable, reproducible, and FAIR (Findable, Accessible, Interoperable, Reusable). Provides unified platform combining lakehouse architecture, lineage tracking, feature stores, biological ontologies (via Bionty plugin with 20+ ontologies: genes, proteins, cell types, tissues, diseases, pathways), LIMS, and ELN capabilities through a single Python API. Key features include: automatic data lineage tracking (code, inputs, outputs, environment), versioned artifacts (DataFrame, AnnData, SpatialData, Parquet, Zarr), schema validation and data curation with standardization/synonym mapping, queryable metadata with feature-based filtering, cross-registry traversal, and streaming for large datasets. Supports integrations with workflow managers (Nextflow, Snakemake, Redun), MLOps platforms (Weights & Biases, MLflow, HuggingFace, scVI-tools), cloud storage (S3, GCS, S3-compatible), array stores (TileDB-SOMA, DuckDB), and visualization (Vitessce). Deployment options: local SQLite, cloud storage with SQLite, or cloud storage with PostgreSQL for production. Use cases: scRNA-seq standardization and analysis, flow cytometry/spatial data management, multi-modal dataset integration, computational workflow tracking with reproducibility, biological ontology-based annotation, data lakehouse construction for unified queries, ML pipeline integration with experiment tracking, and FAIR-compliant dataset publishing-- **Modal** - Serverless cloud platform for running Python code with minimal configuration, specialized for AI/ML workloads and scientific computing. Execute functions on powerful GPUs (T4, L4, A10, A100, L40S, H100, H200, B200, B200+), scale automatically from zero to thousands of containers, and pay only for compute used. Key features include: declarative container image building with uv (recommended)/pip/apt package management, automatic autoscaling with configurable limits and buffer containers, GPU acceleration with multi-GPU support (up to 8 GPUs per container, up to 1,536 GB VRAM), persistent storage via Volumes (v1 and v2) for model weights and datasets, secret management for API keys and credentials, scheduled jobs with cron expressions, web endpoints for deploying serverless APIs (FastAPI, ASGI, WSGI, WebSockets), parallel execution with `.map()` for batch processing, input concurrency and dynamic batching for I/O-bound workloads, and resource configuration (CPU cores, memory, ephemeral disk up to 3 TiB). Supports custom Docker images, Micromamba/Conda environments, integration with Hugging Face/Weights & Biases, and distributed multi-GPU training. Free tier includes $30/month credits. Use cases: ML model deployment and inference (LLMs, image generation, speech, embeddings), GPU-accelerated training and fine-tuning, batch processing large datasets in parallel, scheduled compute-intensive jobs, serverless API deployment with autoscaling, protein folding and computational biology, scientific computing requiring distributed compute or specialized hardware, and data pipeline automation+- **Modal** - Serverless cloud platform for running Python code with minimal configuration, specialized for AI/ML workloads and scientific computing. Execute functions on powerful GPUs (T4, L4, A10, A100, L40S, H100, H200, B200, B200+), scale automatically from zero to thousands of containers, and pay only for compute used. Key features include: declarative container image building with uv (recommended)/pip/apt package management, automatic autoscaling with configurable limits and buffer containers, GPU acceleration with multi-GPU support (up to 8 GPUs per container, up to 1,536 GB VRAM), persistent storage via Volumes (v1 and v2) for model weights and datasets, secret management for API keys and credentials, scheduled jobs with cron expressions, web endpoints for deploying serverless APIs (FastAPI, ASGI, WSGI, WebSockets), parallel execution with `.map()` for batch processing, input concurrency and dynamic batching for I/O-bound workloads, Sandboxes for isolated execution of untrusted or agent-generated code with network (CIDR) restrictions, and resource configuration (CPU cores, memory, ephemeral disk up to 3 TiB). Supports custom Docker images, Micromamba/Conda environments, integration with Hugging Face/Weights & Biases, and distributed multi-GPU training. Free tier includes $30/month credits. Use cases: ML model deployment and inference (LLMs, image generation, speech, embeddings), GPU-accelerated training and fine-tuning, batch processing large datasets in parallel, scheduled compute-intensive jobs, serverless API deployment with autoscaling, protein folding and computational biology, scientific computing requiring distributed compute or specialized hardware, and data pipeline automation- **Optimize for GPU** - GPU-accelerate Python code using the NVIDIA RAPIDS ecosystem and related libraries for 10x–1000x speedups on suitable workloads. Covers 12 GPU libraries with decision framework for choosing the right tool: CuPy (drop-in NumPy/SciPy replacement for array operations, FFT, linear algebra), Numba CUDA (custom GPU kernels with fine-grained thread/block/shared-memory control), Warp (JIT-compiled simulation kernels with built-in spatial types for physics, mesh ray casting, differentiable programming, and robotics), cuDF (drop-in pandas replacement for dataframe ETL, groupby, joins), cuML (drop-in scikit-learn replacement for classification, regression, clustering, dimensionality reduction, preprocessing), cuGraph (drop-in NetworkX replacement for PageRank, centrality, community detection, shortest paths), KvikIO (GPUDirect Storage for high-performance file IO bypassing CPU memory, S3/HTTP direct-to-GPU reads, Zarr GPU backend), cuxfilter (GPU-accelerated interactive cross-filtering dashboards with Bokeh, Datashader, and Deck.gl), cuCIM (drop-in scikit-image replacement for image filtering, morphology, segmentation, plus fast whole-slide image reading for digital pathology), cuVS (GPU-accelerated vector/similarity search with CAGRA, IVF-Flat, IVF-PQ for RAG and recommender systems), cuSpatial (GPU-accelerated GeoPandas replacement for spatial joins, point-in-polygon, trajectory analysis), and RAFT/pylibraft (sparse eigensolvers, device memory management, multi-GPU communication). All libraries interoperate via CUDA Array Interface for zero-copy data sharing. Includes optimization workflow (profile first, assess GPU suitability, start with drop-in replacements, minimize host-device transfers), code transformation patterns for each library, memory management principles, and common pitfalls. Use cases: accelerating NumPy/pandas/scikit-learn/NetworkX/scikit-image/GeoPandas/Faiss workloads, physics simulation, differentiable rendering, particle systems, vector search for RAG pipelines, GPUDirect Storage file IO, interactive data exploration dashboards, geospatial analysis, medical imaging, and sparse eigenvalue problems### Cheminformatics & Drug Discoverydiff --git a/skills/scikit-bio/SKILL.md b/skills/scikit-bio/SKILL.mdindex 857b770a..c2355c62 100644--- a/skills/scikit-bio/SKILL.md+++ b/skills/scikit-bio/SKILL.md@@ -2,8 +2,10 @@name: scikit-biodescription: Biological data toolkit. Sequence analysis, alignments, phylogenetic trees, diversity metrics (alpha/beta, UniFrac), ordination (PCoA), PERMANOVA, FASTA/Newick I/O, for microbiome analysis.license: BSD-3-Clause license+allowed-tools: Read Write Edit Bash+compatibility: Requires Python 3.10+ and scikit-bio 0.7+ (uv pip install scikit-bio). NumPy 2.0+ is required. Optional matplotlib/seaborn/plotly for plotting; biom-format for BIOM tables; polars/anndata for table interoperability.metadata:- version: "1.0"+ version: "1.1"skill-author: K-Dense Inc.---@@ -69,53 +71,65 @@ seq_no_gaps = seq.degap()### 2. Sequence Alignment-Perform pairwise and multiple sequence alignments using dynamic programming algorithms.+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 alignment (Needleman-Wunsch with semi-global variant)-- Local alignment (Smith-Waterman)-- Configurable scoring schemes (match/mismatch, gap penalties, substitution matrices)-- CIGAR string conversion+- 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:**```python-from skbio.alignment import local_pairwise_align_ssw, TabularMSA+from skbio import DNA, Protein+from skbio.alignment import pair_align_nucl, pair_align_prot, pair_align, TabularMSA-# Pairwise alignment-alignment = local_pairwise_align_ssw(seq1, seq2)+# 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-# Access aligned sequences-msa = alignment.aligned_sequences+# Build a TabularMSA from the alignment path + original sequences+msa = TabularMSA.from_path_seqs(path, (seq1, seq2))-# Read multiple alignment from file-msa = TabularMSA.read('alignment.fasta', constructor=skbio.DNA)+# 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-# Calculate consensus+# 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:**-- Use `local_pairwise_align_ssw` for local alignments (faster, SSW-based)-- Use `StripedSmithWaterman` for protein alignments-- Affine gap penalties recommended for biological sequences-- Can convert between scikit-bio, BioPython, and Biotite alignment formats+- `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 TreesConstruct, manipulate, and analyze phylogenetic trees representing evolutionary relationships.**Key capabilities:**-- Tree construction from distance matrices (UPGMA, WPGMA, Neighbor Joining, GME, BME)+- 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, cophenetic, Robinson-Foulds)+- Distance calculations (patristic via `cophenet`, Robinson-Foulds via `compare_rfd`)- ASCII visualization- Newick format I/O**Common patterns:**```pythonfrom skbio import TreeNode-from skbio.tree import nj+from skbio.tree import nj, upgma, gme, bme, rf_dists# Read tree from filetree = TreeNode.read('tree.nwk')@@ -126,20 +140,24 @@ tree = nj(distance_matrix)# Tree operationssubtree = tree.shear(['taxon1', 'taxon2', 'taxon3'])tips = [node for node in tree.tips()]-lca = tree.lowest_common_ancestor(['taxon1', 'taxon2'])+lca = tree.lca(['taxon1', 'taxon2'])# Calculate distancespatristic_dist = tree.find('taxon1').distance(tree.find('taxon2'))-cophenetic_matrix = tree.cophenetic_matrix()+cophenetic_dm = tree.cophenet() # patristic distance matrix among tips-# Compare trees-rf_distance = tree.robinson_foulds(other_tree)+# 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 (assumes molecular clock)-- GME and BME are highly scalable for large trees+- 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@@ -147,7 +165,7 @@ rf_distance = tree.robinson_foulds(other_tree)Calculate alpha and beta diversity metrics for microbial ecology and community analysis.**Key capabilities:**-- Alpha diversity: richness, Shannon entropy, Simpson index, Faith's PD, Pielou's evenness+- 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@@ -156,17 +174,16 @@ Calculate alpha and beta diversity metrics for microbial ecology and community a**Common patterns:**```pythonfrom skbio.diversity import alpha_diversity, beta_diversity-import skbio-# Alpha 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, otu_ids=feature_ids)+ tree=tree, taxa=feature_ids)# Beta diversitybc_dm = beta_diversity('braycurtis', counts_matrix, ids=sample_ids)unifrac_dm = beta_diversity('unweighted_unifrac', counts_matrix,- ids=sample_ids, tree=tree, otu_ids=feature_ids)+ ids=sample_ids, tree=tree, taxa=feature_ids)# Get available metricsfrom skbio.diversity import get_alpha_diversity_metrics@@ -175,9 +192,11 @@ print(get_alpha_diversity_metrics())**Important notes:**- Counts must be integers representing abundances, not relative frequencies-- Phylogenetic metrics (Faith's PD, UniFrac) require tree and OTU ID mapping-- Use `partial_beta_diversity()` for computing specific sample pairs only-- Alpha diversity returns Series, beta diversity returns DistanceMatrix+- 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@@ -193,12 +212,16 @@ Reduce high-dimensional biological data to visualizable lower-dimensional spaces**Common patterns:**```pythonfrom skbio.stats.ordination import pcoa, cca+import skbio-# PCoA from distance matrix-pcoa_results = pcoa(distance_matrix)+# 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 variablescca_results = cca(species_matrix, environmental_matrix)@@ -208,10 +231,10 @@ results = skbio.OrdinationResults.read('ordination.txt')```**Important notes:**-- PCoA works with any distance/dissimilarity matrix+- 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-- Ordination results include eigenvalues, proportion explained, and sample/feature coordinates-- Results integrate with plotting libraries (matplotlib, seaborn, plotly)+- `OrdinationResults.plot()` produces a matplotlib figure; results also integrate with seaborn/plotly### 6. Statistical Testing@@ -223,6 +246,7 @@ Perform hypothesis tests specific to ecological and biological data.- 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:**```python@@ -238,6 +262,10 @@ anosim_results = anosim(distance_matrix, grouping, permutations=999)# Mantel test between two distance matricesmantel_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:**@@ -245,6 +273,7 @@ print(f"Correlation: {mantel_results[0]}, p-value: {mantel_results[1]}")- 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@@ -290,7 +319,7 @@ skbio.io.write(seqs, format='fasta', into='output.fasta')Create and manipulate distance/dissimilarity matrices with statistical methods.**Key capabilities:**-- Store symmetric (DistanceMatrix) or asymmetric (DissimilarityMatrix) data+- 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@@ -317,8 +346,8 @@ permanova_results = permanova(dm, grouping)```**Important notes:**-- DistanceMatrix enforces symmetry and zero diagonal-- DissimilarityMatrix allows asymmetric values+- `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@@ -327,15 +356,16 @@ permanova_results = permanova(dm, grouping)Work with feature tables (OTU/ASV tables) common in microbiome research.**Key capabilities:**-- BIOM format I/O (HDF5 and JSON)-- Integration with pandas, polars, AnnData, numpy-- Data augmentation techniques (phylomix, mixup, compositional methods)+- 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:**```pythonfrom skbio import Table+from skbio.diversity import beta_diversity# Read BIOM tabletable = Table.read('table.biom')@@ -348,16 +378,17 @@ counts = table.matrix_data# Filterfiltered = table.filter(sample_ids_to_keep, axis='sample')-# Convert to/from pandas-df = table.to_dataframe()-table = Table.from_dataframe(df)+# 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-- Output format configurable (pandas/polars/numpy)+- With the dispatch system, functions return the same format as their input, or a user-specified output format### 10. Protein Embeddings@@ -399,6 +430,7 @@ df = embedding.to_dataframe()```bashuv 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@@ -432,5 +464,7 @@ For detailed API information, parameter specifications, and advanced usage examp- Official documentation: https://scikit.bio/docs/latest/- GitHub repository: https://github.com/scikit-bio/scikit-bio+- Changelog: https://github.com/scikit-bio/scikit-bio/blob/main/CHANGELOG.md+- Reference paper: "scikit-bio: a fundamental Python library for biological omic data," *Nature Methods* (2025), https://www.nature.com/articles/s41592-025-02981-z- Forum support: https://forum.qiime2.org (scikit-bio is part of QIIME 2 ecosystem)diff --git a/skills/scikit-bio/references/api_reference.md b/skills/scikit-bio/references/api_reference.mdindex dbd95bb4..6fbcbad5 100644--- a/skills/scikit-bio/references/api_reference.md+++ b/skills/scikit-bio/references/api_reference.md@@ -87,56 +87,59 @@ dist = seq1.distance(seq2, metric=kmer_distance)### Pairwise Alignment+scikit-bio 0.7.0 introduced `pair_align`, a single fast engine for global, local, and semi-global alignment. The convenience wrappers `pair_align_nucl` and `pair_align_prot` ship with BLASTN/BLASTP-like scoring. The old SSW wrapper (`local_pairwise_align_ssw`, `StripedSmithWaterman`) was removed, and the pure-Python `global_pairwise_align`/`local_pairwise_align_*` functions are deprecated.+```python-from skbio.alignment import local_pairwise_align_ssw, global_pairwise_alignfrom skbio import DNA, Protein+from skbio.alignment import pair_align_nucl, pair_align_prot, pair_align, align_score-# Local alignment (Smith-Waterman via SSW)+# Nucleotide alignment with BLASTN-like defaultsseq1 = DNA('ATCGATCGATCG')seq2 = DNA('ATCGGGGATCG')-alignment = local_pairwise_align_ssw(seq1, seq2)--# Access alignment details-print(f"Score: {alignment.score}")-print(f"Start position: {alignment.target_begin}")-aligned_seqs = alignment.aligned_sequences--# Global alignment with custom scoring-from skbio.alignment import AlignScorer--scorer = AlignScorer(- match_score=2,- mismatch_score=-3,- gap_open_penalty=5,- gap_extend_penalty=2+aln = pair_align_nucl(seq1, seq2)++# Inspect the result (PairAlignResult: score + paths [+ matrices])+print(f"Score: {aln.score}")+path = aln.paths[0] # PairAlignPath; repr shows the CIGAR+aligned_seqs = path.to_aligned((seq1, seq2)) # list of gapped strings++# Global alignment with custom affine scoring via pair_align+aln = pair_align(+ seq1, seq2,+ mode='global', # 'global' (default), 'local', or semi-global via free_ends+ sub_score=(2, -3), # (match, mismatch)+ gap_cost=(5, 2), # (open, extend) -> affine; a single number -> linear)-alignment = global_pairwise_align(seq1, seq2, scorer=scorer)--# Protein alignment with substitution matrix-from skbio.alignment import StripedSmithWaterman+# Use a named substitution matrix instead of match/mismatch scores+aln = pair_align(seq1, seq2, mode='global', sub_score='NUC.4.4', gap_cost=3)+# Protein alignment with BLASTP-like defaults (BLOSUM62)protein_query = Protein('ACDEFGHIKLMNPQRSTVWY')protein_target = Protein('ACDEFMNPQRSTVWY')+aln = pair_align_prot(protein_query, protein_target)-aligner = StripedSmithWaterman(- str(protein_query),- gap_open_penalty=11,- gap_extend_penalty=1,- substitution_matrix='blosum62'-)-alignment = aligner(str(protein_target))+# Re-score an existing alignment with the same parameters+score = align_score((aln.paths[0], (protein_query, protein_target)),+ sub_score='BLOSUM62', gap_cost=(11, 1))++# PairAlignResult also unpacks as a tuple+score, (path,), _ = pair_align_nucl(seq1, seq2)```### Multiple Sequence Alignment```python-from skbio.alignment import TabularMSA+from skbio.alignment import TabularMSA, pair_align_nuclfrom skbio import DNA# Read MSA from filemsa = TabularMSA.read('alignment.fasta', constructor=DNA)+# Build a TabularMSA from a pairwise alignment path + original sequences+score, (path,), _ = pair_align_nucl(DNA('ATCGATCG'), DNA('ATCGGGGATCG'))+msa = TabularMSA.from_path_seqs(path, (DNA('ATCGATCG'), DNA('ATCGGGGATCG')))+# Create MSA manuallyseqs = [DNA('ATCG--'),@@ -163,18 +166,25 @@ degapped_msa = msa.omit_gap_positions(maximum_gap_frequency=0.5)position_entropies = msa.position_entropies()```-### CIGAR String Handling+### CIGAR Strings and Alignment Paths```python-from skbio.alignment import AlignPath+from skbio.alignment import PairAlignPath, AlignPath, pair_align_nucl+from skbio import DNA-# Parse CIGAR string-cigar = "10M2I5M3D10M"-align_path = AlignPath.from_cigar(cigar, target_length=100, query_length=50)+# Parse a CIGAR string into a pairwise alignment path+path = PairAlignPath.from_cigar('10M2I5M3D10M')+print(repr(path)) # <PairAlignPath, ..., CIGAR: '10M2I5M3D10M'>-# Convert alignment to CIGAR-alignment = local_pairwise_align_ssw(seq1, seq2)-cigar_string = alignment.to_cigar()+# A path produced by pair_align already carries its CIGAR+aln = pair_align_nucl(DNA('ATCGATCG'), DNA('ATCGGGGATCG'))+cigar_string = aln.paths[0].cigar++# AlignPath generalizes to >2 sequences (e.g., from aligned strings)+path3 = AlignPath.from_aligned(['CGTCGTGC', 'CA--GT-C', 'CGTCGT-T'])++# Parse CIGAR output from external tools such as parasail+# path = PairAlignPath.from_cigar(res.cigar.decode)```## Phylogenetic Trees@@ -248,22 +258,26 @@ node_to_remove.parent.remove(node_to_remove)### Tree Distances and Comparisons```python-# Patristic distance (branch-length distance)+# Patristic distance (branch-length distance) between two nodesnode1 = tree.find('taxon1')node2 = tree.find('taxon2')patristic = node1.distance(node2)-# Cophenetic matrix (all pairwise distances)-cophenetic_dm = tree.cophenetic_matrix()+# Cophenetic (patristic) distance matrix among all tips+# cophenet() replaces the former tip_tip_distances()+cophenetic_dm = tree.cophenet()-# Robinson-Foulds distance (topology comparison)-rf_dist = tree.robinson_foulds(other_tree)+# Robinson-Foulds distance between two trees (compare_rfd, added in 0.6.3)+rf_dist = tree.compare_rfd(other_tree) # count (float)+rf_prop = tree.compare_rfd(other_tree, proportion=True) # normalized to [0, 1]-# Compare with unweighted RF-rf_dist, max_rf = tree.robinson_foulds(other_tree, proportion=False)+# Weighted Robinson-Foulds and cophenetic-correlation comparisons+wrf = tree.compare_wrfd(other_tree)+coph = tree.compare_cophenet(other_tree)-# Tip-to-tip distances-tip_distances = tree.tip_tip_distances()+# Pairwise RF distances among many trees -> DistanceMatrix+from skbio.tree import rf_dists+rf_dm = rf_dists([tree, other_tree, third_tree])```### Tree Visualization@@ -300,17 +314,18 @@ print(get_alpha_diversity_metrics())# Calculate various alpha diversity metricsshannon = alpha_diversity('shannon', counts, ids=sample_ids)simpson = alpha_diversity('simpson', counts, ids=sample_ids)-observed_otus = alpha_diversity('observed_otus', counts, ids=sample_ids)+observed = alpha_diversity('observed_features', counts, ids=sample_ids) # was 'observed_otus'chao1 = alpha_diversity('chao1', counts, ids=sample_ids)+hill_q2 = alpha_diversity('hill', counts, ids=sample_ids) # effective number of species-# Phylogenetic alpha diversity (requires tree)+# Phylogenetic alpha diversity (requires tree). Note: taxa= replaces otu_ids=from skbio import TreeNodetree = TreeNode.read('tree.nwk')feature_ids = ['OTU1', 'OTU2', 'OTU3', 'OTU4']faith_pd = alpha_diversity('faith_pd', counts, ids=sample_ids,- tree=tree, otu_ids=feature_ids)+ tree=tree, taxa=feature_ids)```### Beta Diversity@@ -324,16 +339,16 @@ bc_dm = beta_diversity('braycurtis', counts, ids=sample_ids)# Jaccard (presence/absence)jaccard_dm = beta_diversity('jaccard', counts, ids=sample_ids)-# Phylogenetic beta diversity+# Phylogenetic beta diversity (taxa= replaces the deprecated otu_ids=)unifrac_dm = beta_diversity('unweighted_unifrac', counts,- ids=sample_ids,- tree=tree,- otu_ids=feature_ids)+ ids=sample_ids,+ tree=tree,+ taxa=feature_ids)weighted_unifrac_dm = beta_diversity('weighted_unifrac', counts,- ids=sample_ids,- tree=tree,- otu_ids=feature_ids)+ ids=sample_ids,+ tree=tree,+ taxa=feature_ids)# Compute only specific pairs (more efficient)pairs = [('Sample1', 'Sample2'), ('Sample1', 'Sample3')]@@ -528,7 +543,8 @@ r_partial, p_value, n = mantel(dm1, dm2, method='pearson',### Creating and Manipulating Distance Matrices```python-from skbio import DistanceMatrix, DissimilarityMatrix+from skbio import DistanceMatrix+from skbio.stats.distance import PairwiseMatriximport numpy as np# Create from array@@ -544,11 +560,12 @@ row_a = dm['A']# Slicingsubset_dm = dm.filter(['A', 'C'])-# Asymmetric dissimilarity matrix+# General/asymmetric matrix: PairwiseMatrix (renamed from DissimilarityMatrix,+# which is kept as a deprecated alias)asym_data = np.array([[0, 1, 2],[3, 0, 4],[5, 6, 0]])-dissim = DissimilarityMatrix(asym_data, ids=['X', 'Y', 'Z'])+pwm = PairwiseMatrix(asym_data, ids=['X', 'Y', 'Z'])# Read/writedm.write('distances.txt')@@ -689,7 +706,7 @@ tree_pruned = tree.shear(feature_ids)# Solution: Degap sequences first or ensure sequences are unalignedseq1_degapped = seq1.degap()seq2_degapped = seq2.degap()-alignment = local_pairwise_align_ssw(seq1_degapped, seq2_degapped)+alignment = pair_align_nucl(seq1_degapped, seq2_degapped)```### Performance Tips