Communitygithub.com

biopython

包括的な分子生物学ツールキット。配列操作、FASTA/GenBank/PDB のファイル解析、系統解析、プログラムによる NCBI/PubMed アクセス (Bio.Entrez) に使用します。バッチ処理、カスタムバイオインフォマティクスパイプライン、BLAST 自動化に最適です。簡単な検索には gget、複数サービス統合には bioservices を推奨します。

biopython とは?

Biopython は、Python を使用した生物学的計算のための包括的なツールキットです。DNA、RNA、タンパク質配列の操作、FASTA や GenBank などのファイル形式の入出力、NCBI データベースへのアクセス、BLAST 検索の実行と結果解析、系統樹の構築と可視化、タンパク質構造解析など、分子生物学の幅広いタスクをサポートします。特に、Bio.Entrez モジュールを使用した NCBI データベースへのプログラム的アクセスや、Bio.Blast モジュールを使用した BLAST 自動化ワークフローに強みを持ち、バッチ処理やカスタムパイプラインの構築に最適です。Biopython 1.87 以降は Python 3.10-3.14 と PyPy3.10 をサポートし、NumPy を必要とします。また、悪意のあるファイルからの保護のために、外部の Entrez XML をパースするワークフローでは 1.87 以降のバージョンが推奨されます。本スキルは、各機能領域ごとの詳細なリファレンス (references/ ディレクトリ内のファイル) に依存しており、ユーザーは特定のタスクに応じて適切なリファレンスを参照します。

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

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

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

ドキュメント

Biopython: Pythonにおける計算分子生物学

概要

Biopython は、生物学的情報処理のための、無料で利用可能な Python ツールの包括的なセットです。配列操作、ファイル I/O、データベースアクセス、構造バイオインフォマティクス、系統解析、およびその他多くのバイオインフォマティクスタスクのための機能を提供します。現在のバージョンは Biopython 1.87 (2026年3月30日リリース) です。Python 3.10-3.14 および PyPy3.10 をサポートし、NumPy が必要です。Biopython 1.87 は、信頼できないファイルをパースする際の Bio.Entrez.Parser における CVE-2025-68463 にも対応しているため、外部提供の Entrez XML をパースするワークフローでは 1.87 以降を推奨します。

このスキルを使用するタイミング

以下の場合にこのスキルを使用します:

  • 生物学的配列(DNA、RNA、またはタンパク質)を扱う場合
  • 生物学的ファイル形式(FASTA、GenBank、FASTQ、PDB、mmCIF など)の読み取り、書き込み、または変換を行う場合
  • Entrez を介して NCBI データベース(GenBank、PubMed、Protein、Gene など)にアクセスする場合
  • BLAST 検索を実行するか、BLAST 結果を解析する場合
  • 配列アラインメント(ペアワイズまたはマルチプル配列アラインメント)を実行する場合
  • PDB ファイルからタンパク質構造を解析する場合
  • 系統樹を作成、操作、または可視化する場合
  • 配列モチーフを見つけるか、モチーフパターンを解析する場合
  • 配列統計(GC含量、分子量、融解温度など)を計算する場合
  • 構造バイオインフォマティクスタスクを実行する場合
  • 集団遺伝学データを扱う場合
  • その他の計算分子生物学タスク

コア機能

Biopython はモジュール式のサブパッケージに編成されており、それぞれが特定のバイオインフォマティクス領域を扱います:

  1. 配列処理 - Bio.Seq と Bio.SeqIO による配列操作とファイル I/O
  2. アラインメント解析 - Bio.Align と Bio.AlignIO によるペアワイズおよびマルチプル配列アラインメント
  3. データベースアクセス - Bio.Entrez による NCBI データベースへのプログラム的アクセス
  4. BLAST 操作 - Bio.Blast による BLAST 検索の実行と解析
  5. 構造バイオインフォマティクス - Bio.PDB による 3D タンパク質構造の操作
  6. 系統解析 - Bio.Phylo による系統樹の操作と可視化
  7. 高度な機能 - モチーフ、集団遺伝学、配列ユーティリティなど

インストールとセットアップ

再現性のためにバージョンを明示的に指定して、現在の安定版 Biopython リリースをインストールします:

uv pip install "biopython==1.87"

NCBI データベースにアクセスする場合は、必ずメールアドレスを設定してください(NCBI 必須)。再利用可能なソフトウェアの場合は、安定した Entrez.tool 値を設定し、ツールとメールを NCBI に登録します。より高いレート制限(3 req/s の代わりに 10 req/s)を得るには、NCBI_API_KEY のみを環境から読み取ります。キーをハードコードしたり、無関係な環境変数をロードしたりしないでください:

import os
from Bio import Entrez

Entrez.email = "[email protected]"  # 必須 — 実際のメールを使用してください
Entrez.tool = "your_tool_name"  # オプションですが、再利用可能なソフトウェアには推奨

# オプション: https://www.ncbi.nlm.nih.gov/account/settings/ に登録
if api_key := os.environ.get("NCBI_API_KEY"):
    Entrez.api_key = api_key

このスキルの使用方法

このスキルは、機能領域ごとに編成された包括的なドキュメンテーションを提供します。タスクに取り組む際は、関連するリファレンスドキュメンテーションを参照してください:

1. 配列処理 (Bio.Seq & Bio.SeqIO)

リファレンス: references/sequence_io.md

以下の場合に使用:

  • 生物学的配列の作成と操作
  • 配列ファイルの読み取りと書き込み(FASTA、GenBank、FASTQ など)
  • ファイル形式間の変換
  • 大きなファイルからの配列抽出
  • 配列の翻訳、転写、および逆相補配列の取得
  • SeqRecord オブジェクトの操作

簡単な例:

from Bio import SeqIO

# FASTA ファイルから配列を読み取る
for record in SeqIO.parse("sequences.fasta", "fasta"):
    print(f"{record.id}: {len(record.seq)} bp")

# GenBank を FASTA に変換
SeqIO.convert("input.gb", "genbank", "output.fasta", "fasta")

2. アラインメント解析 (Bio.Align & Bio.AlignIO)

リファレンス: references/alignment.md

以下の場合に使用:

  • ペアワイズ配列アラインメント(グローバルおよびローカル)
  • マルチプル配列アラインメントの読み取りと書き込み
  • 置換行列(BLOSUM、PAM)の使用
  • アラインメント統計の計算
  • アラインメントパラメータのカスタマイズ

簡単な例:

from Bio import Align

# ペアワイズアラインメント
aligner = Align.PairwiseAligner()
aligner.mode = 'global'
alignments = aligner.align("ACCGGT", "ACGGT")
print(alignments[0])

3. データベースアクセス (Bio.Entrez)

リファレンス: references/databases.md

以下の場合に使用:

  • NCBI データベースの検索(PubMed、GenBank、Protein、Gene など)
  • 配列とレコードのダウンロード
  • 出版情報の取得
  • データベース間での関連レコードの検索
  • 適切なレート制限を用いたバッチダウンロード

簡単な例:

from Bio import Entrez
Entrez.email = "[email protected]"

# PubMed を検索
handle = Entrez.esearch(db="pubmed", term="biopython", retmax=10)
results = Entrez.read(handle)
handle.close()
print(f"Found {results['Count']} results")

4. BLAST 操作 (Bio.Blast)

リファレンス: references/blast.md

以下の場合に使用:

  • NCBI Web サービスを介した BLAST 検索の実行
  • ローカル BLAST 検索の実行
  • BLAST XML 出力の解析
  • E 値または同一性による結果のフィルタリング
  • ヒット配列の抽出

簡単な例:

from Bio.Blast import NCBIWWW, NCBIXML

# BLAST 検索を実行
result_handle = NCBIWWW.qblast("blastn", "nt", "ATCGATCGATCG")
blast_record = NCBIXML.read(result_handle)

# トップヒットを表示
for alignment in blast_record.alignments[:5]:
    print(f"{alignment.title}: E-value={alignment.hsps[0].expect}")

5. 構造バイオインフォマティクス (Bio.PDB)

リファレンス: references/structure.md

以下の場合に使用:

  • PDB および mmCIF 構造ファイルの解析
  • タンパク質構造階層の操作(SMCRA: Structure/Model/Chain/Residue/Atom)
  • 距離、角度、二面角の計算
  • 二次構造の割り当て(DSSP)
  • 構造の重ね合わせと RMSD 計算
  • 構造からの配列抽出

簡単な例:

from Bio.PDB import PDBParser

# 構造を解析
parser = PDBParser(QUIET=True)
structure = parser.get_structure("1crn", "1crn.pdb")

# アルファ炭素間の距離を計算
chain = structure[0]["A"]
distance = chain[10]["CA"] - chain[20]["CA"]
print(f"Distance: {distance:.2f} Å")

6. 系統解析 (Bio.Phylo)

リファレンス: references/phylogenetics.md

以下の場合に使用:

  • 系統樹の読み取りと書き込み(Newick、NEXUS、phyloXML)
  • 距離行列またはアラインメントからの樹の構築
  • 樹の操作(剪定、根の付け替え、ラダー化)
  • 系統距離の計算
  • コンセンサス樹の作成
  • 樹の可視化

簡単な例:

from Bio import Phylo

# 樹の読み取りと可視化
tree = Phylo.read("tree.nwk", "newick")
Phylo.draw_ascii(tree)

# 距離の計算
distance = tree.distance("Species_A", "Species_B")
print(f"Distance: {distance:.3f}")

7. 高度な機能

リファレンス: references/advanced.md

以下の場合に使用:

  • 配列モチーフ (Bio.motifs) - モチーフパターンの発見と解析
  • 集団遺伝学 (Bio.PopGen) - GenePop ファイル、Fst 計算、Hardy-Weinberg 検定
  • 配列ユーティリティ (Bio.SeqUtils) - GC含量、融解温度、分子量、タンパク質解析
  • 制限酵素解析 (Bio.Restriction) - 制限酵素サイトの発見
  • クラスタリング (Bio.Cluster) - K-means および階層的クラスタリング
  • ゲノムダイアグラム (GenomeDiagram) - ゲノム特徴の可視化

簡単な例:

from Bio.SeqUtils import gc_fraction, molecular_weight
from Bio.Seq import Seq

seq = Seq("ATCGATCGATCG")
print(f"GC content: {gc_fraction(seq):.2%}")
print(f"Molecular weight: {molecular_weight(seq, seq_type='DNA'):.2f} g/mol")

一般的なワークフローガイドライン

ドキュメンテーションの読み方

ユーザーが特定の Biopython タスクについて質問した場合:

  1. タスクの説明に基づいて適切なモジュールを特定します
  2. Read ツールを使用して適切なリファレンスファイルを読み取ります
  3. 関連するコードパターンを抽出し、ユーザーの特定のニーズに適合させます
  4. タスクに必要な場合は複数のモジュールを組み合わせます

リファレンスファイルの検索パターンの例:

# 特定の関数に関する情報を見つける
rg -n "SeqIO.parse" references/sequence_io.md

# 特定のタスクの例を見つける
rg -n "BLAST" references/blast.md

# 特定の概念に関する情報を見つける
rg -n "alignment" references/alignment.md

Biopython コードの記述

Biopython コードを記述する際は、以下の原則に従ってください:

  1. モジュールを明示的にインポートする

    from Bio import SeqIO, Entrez
    from Bio.Seq import Seq
    
  2. NCBI データベースを使用する場合は Entrez メールを設定し、存在する場合は環境から NCBI_API_KEY のみをロードする

    import os
    from Bio import Entrez
    
    Entrez.email = "[email protected]"
    Entrez.tool = "your_tool_name"
    if api_key := os.environ.get("NCBI_API_KEY"):
        Entrez.api_key = api_key
    
  3. 適切なファイル形式を使用する - タスクに最も適した形式を確認する

    # 一般的な形式: "fasta", "genbank", "fastq", "clustal", "phylip"
    
  4. ファイルを適切に処理する - 使用後はハンドルを閉じるか、コンテキストマネージャーを使用する

    with open("file.fasta") as handle:
        records = SeqIO.parse(handle, "fasta")
    
  5. 大きなファイルにはイテレータを使用する - すべてをメモリにロードしない

    for record in SeqIO.parse("large_file.fasta", "fasta"):
        # 一度に1レコードずつ処理
    
  6. エラーを適切に処理する - ネットワーク操作やファイル解析は失敗する可能性がある

    from urllib.error import HTTPError
    
    try:
        handle = Entrez.efetch(db="nucleotide", id=accession)
    except HTTPError as e:
        print(f"Error: {e}")
    

一般的なパターン

パターン 1: GenBank から配列を取得

from Bio import Entrez, SeqIO

Entrez.email = "[email protected]"

# 配列を取得
handle = Entrez.efetch(db="nucleotide", id="EU490707", rettype="gb", retmode="text")
record = SeqIO.read(handle, "genbank")
handle.close()

print(f"Description: {record.description}")
print(f"Sequence length: {len(record.seq)}")

パターン 2: 配列解析パイプライン

from Bio import SeqIO
from Bio.SeqUtils import gc_fraction

for record in SeqIO.parse("sequences.fasta", "fasta"):
    # 統計量を計算
    gc = gc_fraction(record.seq)
    length = len(record.seq)

    # ORF を見つけ、翻訳などを行う
    protein = record.seq.translate()

    print(f"{record.id}: {length} bp, GC={gc:.2%}")

パターン 3: BLAST とトップヒットの取得

from Bio.Blast import NCBIWWW, NCBIXML
from Bio import Entrez, SeqIO

Entrez.email = "[email protected]"

# BLAST を実行
result_handle = NCBIWWW.qblast("blastn", "nt", sequence)
blast_record = NCBIXML.read(result_handle)

# トップヒットのアクセッション番号を取得
accessions = [aln.accession for aln in blast_record.alignments[:5]]

# 配列を取得
for acc in accessions:
    handle = Entrez.efetch(db="nucleotide", id=acc, rettype="fasta", retmode="text")
    record = SeqIO.read(handle, "fasta")
    handle.close()
    print(f">{record.description}")

パターン 4: 配列から系統樹を構築

from Bio import AlignIO, Phylo
from Bio.Phylo.TreeConstruction import DistanceCalculator, DistanceTreeConstructor

# アラインメントを読み取る
alignment = AlignIO.read("alignment.fasta", "fasta")

# 距離を計算
calculator = DistanceCalculator("identity")
dm = calculator.get_distance(alignment)

# 樹を構築
constructor = DistanceTreeConstructor()
tree = constructor.nj(dm)

# 可視化
Phylo.draw_ascii(tree)

ベストプラクティス

  1. コードを書く前に関連するリファレンスドキュメンテーションを常に読む
  2. grep を使用してリファレンスファイル内の特定の関数や例を検索する
  3. 解析前にファイル形式を検証する
  4. 欠損データを適切に処理する - すべてのレコードがすべてのフィールドを持つわけではない
  5. ダウンロードしたデータをキャッシュする - 同じ配列を繰り返しダウンロードしない
  6. NCBI のレート制限を尊重する - 再利用可能なソフトウェアには API キー、登録済みのツール/メール値、大規模ジョブには Entrez の履歴/バッチ処理機能を使用する
  7. 大きなファイルを処理する前に小さなデータセットでテストする
  8. Biopython を最新バージョンに保つ - 最新機能とバグ修正を利用するため
  9. 翻訳には適切な遺伝コードテーブルを使用する
  10. 再現性のために解析パラメータを文書化する

一般的な問題のトラブルシューティング

問題: "No handlers could be found for logger 'Bio.Entrez'"

解決策: これは単なる警告です。Entrez.email を設定して抑制します。

問題: NCBI からの "HTTP Error 400"

解決策: ID/アクセッション番号が有効で、適切にフォーマットされていることを確認します。

問題: ファイル解析時の "ValueError: EOF"

解決策: ファイル形式が指定された形式文字列と一致していることを確認します。

問題: アラインメントが "sequences are not the same length" で失敗する

解決策: AlignIO または MultipleSeqAlignment を使用する前に、配列がアラインメント済みであることを確認します。

問題: BLAST 検索が遅い

解決策: 大規模な検索にはローカル BLAST を使用するか、結果をキャッシュします。

問題: PDB パーサーの警告

解決策: PDBParser(QUIET=True) を使用して警告を抑制するか、構造の品質を調査します。

問題: Bio.HMM、Bio.MarkovModel、または Bio.Application の ImportError

解決策: これらのモジュールは Biopython 1.86 で削除されました。HMM には hmmlearn を、Bio.Application CLI ラッパーの代わりには標準ライブラリの subprocess モジュールを使用してください。

問題: 1.86 以降にアップグレード後、PairwiseAligner が返すアラインメント数が減少した

解決策: デフォルトのギャップスコアが 1.86 で 0 から -1 に変更され、自明なタイアラインメントが排除されました。必要に応じて aligner.gap_score = 0 を設定して古い動作を復元します(references/alignment.md を参照)。

追加リソース

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

>

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.

cobrapy

Constraint-based metabolic modeling (COBRA). FBA, FVA, gene knockouts, flux sampling, SBML models, for systems biology and metabolic engineering analysis.

関連スキル