Communitygithub.com

scikit-bio

生物学的データツールキット。配列解析、アラインメント、系統樹、多様性指標(α/β多様性、UniFrac)、順序付け(PCoA)、PERMANOVA、FASTA/Newick入出力、マイクロバイオーム解析に対応。

scikit-bio とは?

scikit-bioは、生物学データの解析のための包括的なPythonライブラリです。このスキルは、生物学的配列(DNA、RNA、タンパク質)の操作、ペアワイズアラインメントや多重配列アラインメント、系統樹の構築・操作、微生物生態学におけるα多様性やβ多様性(UniFracなど)の計算、PCoAやCCAといった順序付け解析、PERMANOVAやMantel検定などの統計的仮説検定をサポートします。さらに、FASTA、FASTQ、GenBank、Newick、BIOMなど19以上の生物学的ファイル形式の読み書きが自動フォーマット検出機能を備えて可能です。このスキルは、Claude CodeやCursorなどの多様なAIエージェントプラットフォームで動作し、開発者や研究者が複雑なバイオインフォマティクスワークフローを効率的に実行するのに役立ちます。

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

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

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. 配列アラインメント

scikit-bio 0.7.0で導入されたpair_alignエンジンを使用して、ペアワイズおよび多重配列アラインメントを実行します。これは多用途で効率的な動的計画法アライナーです。

主な機能:

  • 1つの関数でグローバル、ローカル、セミグローバルアラインメント(自由端設定可能)
  • 便利なラッパー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                                  # アラインメントスコア (float)
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としてアンパックも可能です(DP行列を保持するにはkeep_matrices=Trueを使用)
  • sub_scoreは(match, mismatch)タプルまたは行列名(例:'NUC.4.4'、'BLOSUM62')を受け入れます。gap_costは単一の数値(線形)または(open, extend)タプル(アフィン)を受け入れます
  • 外部CIGAR文字列はPairAlignPath.from_cigar('1I8M2D5M2I')で解析、既存のアラインメントはalign_score(...)でスコアリング、MSAから距離行列はalign_dists(...)で構築

3. 系統樹

進化的関係を表す系統樹を構築、操作、解析します。

主な機能:

  • 距離行列からの系統樹構築(UPGMA/WPGMA、Neighbor Joining、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()           # 先端間のパトリステック距離行列

# 2つの系統樹を比較(Robinson-Foulds)
rf_distance = tree.compare_rfd(other_tree)
# 多数の系統樹間のペアワイズRF距離 -> DistanceMatrix
rf_dm = rf_dists([tree, other_tree, third_tree])

重要な注意点:

  • Neighbor Joining(古典的な系統学的手法)にはnj()を使用
  • UPGMA/WPGMA(分子時計を仮定)にはupgma()を使用
  • 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)、Shannon、Simpson、Hill数(hill)、Faithの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の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:距離と相関する環境変数の検出
  • 差的存在量(Differential abundance):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-value: {permanova_results['p-value']}")

# ANOSIM検定
anosim_results = anosim(distance_matrix, grouping, permutations=999)

# 2つの距離行列間のMantel検定
mantel_results = mantel(dm1, dm2, method='pearson', permutations=999)
print(f"相関: {mantel_results[0]}, p-value: {mantel_results[1]}")

# フィーチャーテーブルの差的存在量(生カウント推奨)
from skbio.stats.composition import dirmult_ttest
da = dirmult_ttest(counts_table, grouping, treatment='caseA', reference='control')

重要な注意点:

  • 順列検定はノンパラメトリックな有意性検定を提供します
  • ロバストなp値には999回以上の順列を使用
  • PERMANOVAはばらつきの差に敏感。PERMDISPと組み合わせて使用
  • Mantel検定は行列相関を評価します(例:地理的距離と遺伝的距離)
  • 差的存在量検定には、事前正規化された比率ではなく生カウントを供給して、大きさの情報を保持

7. ファイルI/Oと形式変換

自動フォーマット検出により、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によりメタデータや生物学的知識との統合が可能

9. サブパッケージ

scikit-bioにはさらに多くの専門機能が含まれています:

  • skbio.stats.composition:組成データ解析(中心対数比変換、不足値補完、差的存在量)
  • skbio.stats.power:統計的検出力とサンプルサイズ計算
  • skbio.stats.isotonic:単調回帰
  • skbio.util:ユーティリティとテストヘルパー

10. ベストプラクティス

  • データ検証:DNA、RNA、Proteinタイプは割り当て時に有効な文字を自動検証
  • メモリ管理:大規模ファイルにはストリーミングI/Oジェネレータを使用
  • ID一貫性:距離、順序付け、統計検定間でIDが一致することを確認
  • 生カウントの使用:可能な場合は生カウントを維持し、正規化後に解析
  • 順列の数:精度の高いp値には999回以上の順列
  • 距離行列の選択:距離の選択は解釈と結果に影響

トラブルシューティング

  • インポートエラー:pip install scikit-bioで最新バージョンがインストールされていることを確認
  • メモリ不足:大規模ファイルにはストリーミングI/Oを使用
  • IDの不一致:距離、主座標、統計手順間でIDが一致していることを確認
  • 非推奨の警告:推奨される代替を確認(例:pair_align、PairAlignPath、observed_features、taxa=、pairwiseはpair_alignに置き換えられました)
  • 可視化の問題:matplotlibがインストールされていることを確認。pip install matplotlib

詳細情報

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.

関連スキル