Communitygithub.com

scikit-bio

生物数据处理工具包。支持序列分析、比对、系统发育树、多样性指标(α/β多样性、UniFrac)、排序分析(PCoA)、PERMANOVA、FASTA/Newick 文件读写,适用于微生物组分析。

scikit-bio 是什么?

scikit-bio 是一个全面的 Python 库,专为生物数据分析设计,尤其擅长微生物组和生态学数据。它提供了从序列操作(DNA、RNA、蛋白质)到高级统计分析(如 PERMANOVA、ANOSIM)的全套工具。其核心功能包括序列比对(支持全局、局部、半全局模式,并兼容 CIGAR 字符串)、系统发育树构建与比较(如邻接法、UPGMA、Robinson-Foulds 距离)、α/β多样性计算(如 Faith's PD、UniFrac),以及生态学中的排序分析(PCoA、CCA、RDA)。该工具包支持 19 种以上生物文件格式(FASTA、FASTQ、Newick、BIOM 等),并提供了便捷的 I/O 接口,适用于从简单脚本到复杂分析管线的各种场景。它兼容多种数据容器(NumPy 数组、pandas DataFrame、BIOM 表格等),并通过高效的动态规划引擎实现快速比对,是生物信息学和微生物组研究的重要工具。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/K-Dense-AI/scientific-agent-skills/tree/main/skills/scikit-bio

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

scikit-bio 是做什么的?

概述

scikit-bio 是一个全面的 Python 库,用于处理生物数据。应用此技能可进行以下生物信息学分析:序列操作、比对、系统发育学、微生物生态学和多元统计学。

适用场景

当用户遇到以下情况时,应使用本技能:

  • 处理生物序列(DNA、RNA、蛋白质)
  • 需要读写生物文件格式(FASTA、FASTQ、GenBank、Newick、BIOM 等)
  • 执行序列比对或搜索基序
  • 构建或分析系统发育树
  • 计算多样性指标(α/β多样性、UniFrac 距离)
  • 执行排序分析(PCoA、CCA、RDA)
  • 对生物/生态数据进行统计检验(PERMANOVA、ANOSIM、Mantel)
  • 分析微生物组或群落生态学数据
  • 处理来自语言模型的蛋白质嵌入
  • 需要操作生物数据表

核心功能

1. 序列操作

使用针对 DNA、RNA 和蛋白质数据的专门类来处理生物序列。

主要操作:

  • 从 FASTA、FASTQ、GenBank、EMBL 格式读写序列
  • 序列切片、拼接和搜索
  • 反向互补、转录(DNA→RNA)和翻译(RNA→蛋白质)
  • 使用正则表达式查找基序和模式
  • 计算距离(汉明距离、基于 k-mer 的距离)
  • 处理序列质量分数和元数据

常用模式:

import skbio

# 从文件读取序列
seq = skbio.DNA.read('input.fasta')

# 序列操作
rc = seq.reverse_complement()
rna = seq.transcribe()
protein = rna.translate()

# 查找基序
motif_positions = seq.find_with_regex('ATG[ACGT]{3}')

# 检查属性
has_degens = seq.has_degenerates()
seq_no_gaps = seq.degap()

重要说明:

  • 使用 DNA、RNA、Protein 类处理带文法和验证的序列
  • 使用 Sequence 类处理无字母表限制的通用序列
  • 质量分数从 FASTQ 文件自动加载到位置元数据中
  • 元数据类型:序列级(ID、描述)、位置级(每位碱基)、区间级(区域/特征)

2. 序列比对

使用 pair_align 引擎(在 scikit-bio 0.7.0 中引入)执行成对和多序列比对,这是一个多功能高效的动态规划比对器。

主要功能:

  • 在一个函数中实现全局、局部和半局部比对(自由端可配置)
  • 便捷包装器 pair_align_nucl(类似 BLASTN)和 pair_align_prot(类似 BLASTP)
  • 可配置评分:匹配/错配元组或命名替换矩阵;线性或仿射空位罚分
  • PairAlignPath 结果携带 CIGAR 字符串并可转换为对齐序列
  • 使用 TabularMSA 进行多序列比对的存储和操作

常用模式:

from skbio import DNA, Protein
from skbio.alignment import pair_align_nucl, pair_align_prot, pair_align, TabularMSA

# 使用 BLASTN 样默认值的核苷酸比对
seq1, seq2 = DNA('ACTACCAGATTACTTACGGATCAGG'), DNA('CGAAACTACTAGATTACGGATCTTA')
aln = pair_align_nucl(seq1, seq2)
aln.score                                  # 比对分数(浮点数)
path = aln.paths[0]                        # PairAlignPath(repr显示CIGAR)
aligned_seqs = path.to_aligned((seq1, seq2))  # 带空位的字符串列表

# 从比对路径 + 原始序列构建 TabularMSA
msa = TabularMSA.from_path_seqs(path, (seq1, seq2))

# 通过 pair_align 自定义算法(默认 mode='global')
aln = pair_align(seq1, seq2, mode='local')                       # Smith-Waterman
aln = pair_align(seq1, seq2, sub_score=(2, -3), gap_cost=(5, 2)) # 仿射空位
aln = pair_align(seq1, seq2, sub_score='NUC.4.4', gap_cost=3)    # 替换矩阵,线性空位

# 蛋白质比对(类似 BLASTP,BLOSUM62)
aln = pair_align_prot(Protein('HEAGAWGHEE'), Protein('PAWHEAE'))

# 从文件读取多序列比对并汇总
msa = TabularMSA.read('alignment.fasta', constructor=DNA)
consensus = msa.consensus()

重要说明:

  • pair_align 替换了已移除的 SSW 包装器(local_pairwise_align_ssw、StripedSmithWaterman)和已弃用的纯 Python 比对器(global_pairwise_align、local_pairwise_align_nucleotide 等)
  • 结果是 PairAlignResult,也可解包为 score, paths, matrices(使用 keep_matrices=True 保留 DP 矩阵)
  • sub_score 接受 (match, mismatch) 元组或矩阵名称(例如 'NUC.4.4'、'BLOSUM62');gap_cost 接受单个数字(线性)或 (open, extend) 元组(仿射)
  • 使用 PairAlignPath.from_cigar('1I8M2D5M2I') 解析外部 CIGAR 字符串;使用 align_score(...) 为现有比对评分,使用 align_dists(...) 从 MSA 构建距离矩阵

3. 系统发育树

构建、操作和分析表示进化关系的系统发育树。

主要功能:

  • 从距离矩阵构建树(UPGMA/WPGMA、邻接法、GME、BME)
  • 使用最近邻互换(nni)进行树重排
  • 树操作(修剪、重定根、遍历)
  • 距离计算(通过 cophenet 计算系谱距离,通过 compare_rfd 计算 Robinson-Foulds 距离)
  • ASCII 可视化
  • Newick 格式 I/O

常用模式:

from skbio import TreeNode
from skbio.tree import nj, upgma, gme, bme, rf_dists

# 从文件读取树
tree = TreeNode.read('tree.nwk')

# 从距离矩阵构建树
tree = nj(distance_matrix)

# 树操作
subtree = tree.shear(['taxon1', 'taxon2', 'taxon3'])
tips = [node for node in tree.tips()]
lca = tree.lca(['taxon1', 'taxon2'])

# 计算距离
patristic_dist = tree.find('taxon1').distance(tree.find('taxon2'))
cophenetic_dm = tree.cophenet()           # 末端节点间的系谱距离矩阵

# 比较两棵树(Robinson-Foulds)
rf_distance = tree.compare_rfd(other_tree)
# 多棵树间的成对 RF 距离 -> DistanceMatrix
rf_dm = rf_dists([tree, other_tree, third_tree])

重要说明:

  • 使用 nj() 进行邻接法(经典系统发育方法)
  • 使用 upgma() 进行 UPGMA/WPGMA(假设分子钟)
  • GME 和 BME 对大树具有高度可扩展性;使用 nni() 优化拓扑结构
  • cophenet()(以前称为 tip_tip_distances)返回系谱距离矩阵;compare_rfd() 是 Robinson-Foulds 方法(compare_wrfd/compare_cophenet 用于加权/系谱变体)
  • lca() 是最低共同祖先;lowest_common_ancestor 保留作为别名
  • 树可以有根或无根;某些度量需要特定的定根方式

4. 多样性分析

计算微生物生态学和群落分析的 α 和 β 多样性指标。

主要功能:

  • α 多样性:丰富度(sobs、observed_features、chao1、ace)、香农指数、辛普森指数、希尔数(hill)、Faith's PD(faith_pd)、广义 PD(phydiv)、Pielou 均匀度
  • β 多样性:Bray-Curtis、Jaccard、加权/非加权 UniFrac、欧几里得距离
  • 系统发育多样性指标(需要树输入)
  • 稀疏化和子采样
  • 与排序分析和统计检验的集成

常用模式:

from skbio.diversity import alpha_diversity, beta_diversity

# α 多样性(系统发育指标使用 taxa= 进行末端节点名称映射)
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)

# β 多样性
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)

# 获取可用指标
from skbio.diversity import get_alpha_diversity_metrics
print(get_alpha_diversity_metrics())

重要说明:

  • 计数必须是表示丰度的整数,而不是相对频率
  • 系统发育指标参数为 taxa=(在 0.6.0 中从 otu_ids 重命名;旧名称是弃用的别名);observed_otus 现在为 observed_features(或 sobs)
  • counts_matrix 可以是任何类似表格的输入(NumPy 数组、pandas/polars DataFrame、BIOM Table 或 AnnData),通过调度系统实现
  • 系统发育指标(Faith's PD、UniFrac)需要树和分类单元到末端节点的映射
  • 使用 partial_beta_diversity() 处理特定样本对,或使用 block_beta_diversity() 进行大规模块分解计算
  • α 多样性返回 pandas.Series,β 多样性返回 DistanceMatrix

5. 排序方法

将高维生物数据降维到可可视化的低维空间。

主要功能:

  • PCoA(主坐标分析):基于距离矩阵
  • CA(对应分析):用于列联表
  • CCA(典型对应分析):带环境约束
  • RDA(冗余分析):用于线性关系
  • 双标图投影:用于特征解释

常用模式:

from skbio.stats.ordination import pcoa, cca
import skbio

# 从距离矩阵进行 PCoA(大矩阵限制维度)
pcoa_results = pcoa(distance_matrix, dimensions=3)
pc1 = pcoa_results.samples['PC1']
pc2 = pcoa_results.samples['PC2']

# 内置散点图,按元数据列着色
fig = pcoa_results.plot(sample_metadata, column='bodysite')

# 带环境变量的 CCA
cca_results = cca(species_matrix, environmental_matrix)

# 保存/加载排序结果
pcoa_results.write('ordination.txt')
results = skbio.OrdinationResults.read('ordination.txt')

重要说明:

  • PCoA 适用于任何距离/相异度矩阵;将 dimensions 作为整数(计数)或 (0, 1] 范围内的浮点数(保留的累积方差比例)传递
  • OrdinationResults 公开基于 pandas 的属性:samples、features、eigvals、proportion_explained、biplot_scores、sample_constraints
  • CCA 揭示群落组成的环境驱动因素
  • OrdinationResults.plot() 生成 matplotlib 图形;结果也可与 seaborn/plotly 集成

6. 统计检验

执行特定于生态和生物数据的假设检验。

主要功能:

  • PERMANOVA:使用距离矩阵检验组间差异
  • ANOSIM:检验组间差异的替代方法
  • PERMDISP:检验组间离散度的同质性
  • Mantel 检验:距离矩阵间的相关性
  • Bioenv:寻找与距离相关的环境变量
  • 差异丰度:skbio.stats.composition 中的 ancom、dirmult_ttest 和 dirmult_lme(纵向混合效应模型)

常用模式:

from skbio.stats.distance import permanova, anosim, mantel

# 检验组间是否存在显著差异
permanova_results = permanova(distance_matrix, grouping, permutations=999)
print(f"p值: {permanova_results['p-value']}")

# ANOSIM 检验
anosim_results = anosim(distance_matrix, grouping, permutations=999)

# 两个距离矩阵间的 Mantel 检验
mantel_results = mantel(dm1, dm2, method='pearson', permutations=999)
print(f"相关性: {mantel_results[0]}, p值: {mantel_results[1]}")

# 对特征表进行差异丰度分析(建议使用原始计数)
from skbio.stats.composition import dirmult_ttest
da = dirmult_ttest(counts_table, grouping, treatment='caseA', reference='control')

重要说明:

  • 置换检验提供非参数显著性检验
  • 使用 999 次以上置换以获得稳健的 p 值
  • PERMANOVA 对离散度差异敏感;建议与 PERMDISP 结合使用
  • Mantel 检验评估矩阵相关性(例如地理距离与遗传距离)
  • 向差异丰度检验提供原始计数,而非预先归一化的比例,以保留量级信息

7. 文件输入输出和格式转换

读写 19 种以上生物文件格式,并支持自动格式检测。

支持的格式:

  • 序列:FASTA、FASTQ、GenBank、EMBL、QSeq
  • 比对:Clustal、PHYLIP、Stockholm
  • 树:Newick
  • 表格:BIOM(HDF5 和 JSON)
  • 距离:带分隔符的方阵
  • 分析:BLAST+6/7、GFF3、排序结果
  • 元数据:带验证的 TSV/CSV

常用模式:

import skbio

# 自动格式检测读取
seq = skbio.DNA.read('file.fasta', format='fasta')
tree = skbio.TreeNode.read('tree.nwk')

# 写入文件
seq.write('output.fasta', format='fasta')

# 大文件生成器(内存高效)
for seq in skbio.io.read('large.fasta', format='fasta', constructor=skbio.DNA):
    process(seq)

# 格式转换
seqs = list(skbio.io.read('input.fastq', format='fastq', constructor=skbio.DNA))
skbio.io.write(seqs, format='fasta', into='output.fasta')

重要说明:

  • 对大型文件使用生成器以避免内存问题
  • 指定 into 参数时可自动检测格式
  • 某些对象可以写入多种格式
  • 支持通过 verify=False 进行标准输入/输出管道

8. 距离矩阵

创建和操作距离/相异度矩阵,并支持统计方法。

主要功能:

  • 存储对称矩阵(DistanceMatrix,对角线为零)或一般成对矩阵(PairwiseMatrix)数据
  • 基于 ID 的索引和切片
  • 与多样性、排序和统计检验集成
  • 读写带分隔符的文本格式

常用模式:

from skbio import DistanceMatrix
import numpy as np

# 从数组创建
data = np.array([[0, 1, 2], [1, 0, 3], [2, 3, 0]])
dm = DistanceMatrix(data, ids=['A', 'B', 'C'])

# 访问距离
dist_ab = dm['A', 'B']
row_a = dm['A']

# 从文件读取
dm = DistanceMatrix.read('distances.txt')

# 在下游分析中使用
pcoa_results = pcoa(dm)
permanova_results = permanova(dm, grouping)

重要说明:

  • DistanceMatrix 强制执行对称性和零(空)对角线;它是 SymmetricMatrix 的子类
  • PairwiseMatrix(从 DissimilarityMatrix 重命名,后者保留为弃用的别名)允许一般/非对称值
  • ID 支持与元数据和生物学知识的集成

…

[为翻译而截断]

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

adaptyv

How to use the Adaptyv Bio Foundry API and Python SDK for protein experiment design, submission, and results retrieval. Use this skill whenever the user mentions Adaptyv, Foundry API, protein binding assays, protein screening experiments, BLI/SPR assays, thermostability assays, or wants to submit protein sequences for experimental characterization. Also trigger when code imports `adaptyv`, `adaptyv_sdk`, or `FoundryClient`, or references `foundry-api-public.adaptyvbio.com`.

aeon

This skill should be used for time series machine learning tasks including classification, regression, clustering, forecasting, anomaly detection, segmentation, and similarity search. Use when working with temporal data, sequential patterns, or time-indexed observations requiring specialized algorithms beyond standard ML approaches. Particularly suited for univariate and multivariate time series analysis with scikit-learn compatible APIs.

alphagenome

Look up precomputed AlphaGenome Atlas effects for any GRCh38 single-nucleotide variant (AVI score with Phred and 18 SHAP feature attributions, plus raw and quantile scores for RNA-seq, DNase, ATAC, ChIP-TF, ChIP-histone, CAGE, PRO-cap, splicing, polyadenylation and contact-map tracks), score variants or scan windows on demand with the AlphaGenome model for human and mouse (variant scoring, in silico mutagenesis, REF-versus-ALT track prediction), and build Atlas website deep links. Use when the user mentions AlphaGenome, AlphaGenome Atlas, AVI or AlphaGenome Variant Impact, DeepMind variant effect prediction, or wants to prioritise or mechanistically interpret non-coding, regulatory, splicing, enhancer, promoter, or chromatin-accessibility effects of SNVs from a VCF, credible set, or region. Research use only; not a clinical tool.

analytical-method-validation

Plan, execute, and document validation, verification, and transfer of analytical procedures under the governing framework - ICH Q2(R2) and Q14, USP <1220>/<1225>/<1226>, ICH M10 bioanalytical, CLSI EP, or ISO/IEC 17025. Use for HPLC, LC-MS/MS, GC, CE, ICP-MS, dissolution, qNMR, qPCR, NIR, and ligand binding or cell-based assays whenever the question is whether a procedure is fit for its intended purpose. Triggers include

anndata

Data structure for annotated matrices in single-cell analysis. Use when working with .h5ad files or integrating with the scverse ecosystem. This is the data format skill—for analysis workflows use scanpy; for probabilistic models use scvi-tools; for population-scale queries use cellxgene-census.

arbor

Autonomously improve a real artifact (code, training recipe, agent harness, data pipeline, prompt) against an objective and an evaluator, using Hypothesis Tree Refinement (HTR) from the Arbor paper. Use this whenever someone wants to iteratively optimize something over many experiments without overfitting — e.g.

arboreto

Infer gene regulatory networks (GRNs) from gene expression data using scalable algorithms (GRNBoost2, GENIE3). Use when analyzing transcriptomics data (bulk RNA-seq, single-cell RNA-seq) to identify transcription factor-target gene relationships and regulatory interactions. Supports distributed computation for large-scale datasets.

astropy

Core Python library for astronomy and astrophysics workflows that need Astropy APIs, including units/quantities, coordinates, FITS I/O, tables, time systems, WCS, and cosmology. Use when implementing or debugging astronomical data analysis code with Astropy.

autoskill

Observe the user

benchling-integration

Benchling Python SDK and REST API integration for registry entities, inventory, ELN entries, workflows, Benchling Apps, and Data Warehouse queries. Use when automating lab data with benchling-sdk or the v2 API.

bgpt-paper-search

Search scientific papers and retrieve structured experimental data extracted from full-text studies via the BGPT MCP server. Returns 25+ fields per paper including methods, results, sample sizes, quality scores, and conclusions. Use for literature reviews, evidence synthesis, and finding experimental details not available in abstracts alone.

bids

>

biopython

Comprehensive molecular biology toolkit. Use for sequence manipulation, file parsing (FASTA/GenBank/PDB), phylogenetics, and programmatic NCBI/PubMed access (Bio.Entrez). Best for batch processing, custom bioinformatics pipelines, BLAST automation. For quick lookups use gget; for multi-service integration use bioservices.

bioservices

Unified Python interface to 40+ bioinformatics services. Use when querying multiple databases (UniProt, KEGG, ChEMBL, Reactome) in a single workflow with consistent API. Best for cross-database analysis, ID mapping across services. For quick single-database lookups use gget; for sequence/file manipulation use biopython.

bulk-rnaseq

End-to-end bulk RNA-seq orchestrator — takes raw FASTQ reads through QC and trimming (FastQC, fastp/Trim Galore), alignment and quantification (STAR, Salmon, featureCounts), assembles a gene-level counts matrix, then hands off to differential expression (pydeseq2), pathway/GSEA enrichment (pathway-enrichment), and publication figures (scientific-visualization). Use whenever the user has bulk RNA-seq reads or quant output and wants a complete, reproducible differential-expression workflow — e.g.

cellxgene-census

Query the CZ CELLxGENE Census programmatically for versioned public single-cell and spatial transcriptomics data. Use when you need population-scale cell metadata, gene expression slices, Census summary counts, source H5AD URIs/downloads, embeddings, spatial Census data, or reference atlas comparisons across organisms, tissues, diseases, assays, and cell types. For analyzing your own local single-cell data use scanpy, anndata, or scvi-tools.

cirq

Google quantum computing framework. Use when targeting Google Quantum AI hardware, designing noise-aware circuits, or running quantum characterization experiments. Best for Google hardware, noise modeling, and low-level circuit design. For IBM hardware use qiskit; for quantum ML with autodiff use pennylane; for physics simulations use qutip.

citation-management

Comprehensive citation management for academic research. Search OpenAlex, PubMed, and Google Scholar for papers, extract accurate metadata, validate citations, and generate properly formatted BibTeX entries. This skill should be used when you need to find papers, verify citation information, convert DOIs to BibTeX, or ensure reference accuracy in scientific writing.

clinical-decision-support

Prepare and validate research-only clinical decision-support evaluation, evidence-profile, cohort, survival, biomarker/model, privacy, and governance artifacts. Use for aggregate or synthetic research documentation and traceability—not patient care or live clinical operation.

clinical-reports

Create safety-bounded draft structures and run local deterministic checks for clinical case, diagnostic, trial, safety, and aggregate research reports. Use only with synthetic, de-identified, or aggregate inputs and verified source-fact manifests; every output requires qualified review.

相关技能