Communitygithub.com

COBRApy - 制約ベース再構成および解析

制約ベース代謝モデリング(COBRA)のためのPythonライブラリです。FBA、FVA、遺伝子ノックアウト、フラックスサンプリング、SBMLモデルを用いたシステム生物学および代謝工学解析を実施します。

COBRApy - 制約ベース再構成および解析 とは?

COBRApyは、システム生物学研究に不可欠な、制約ベースの代謝モデル再構成と解析(COBRA)を行うためのPythonライブラリです。ゲノムスケールの代謝モデルを扱い、細胞代謝の計算機シミュレーション、代謝工学解析、表現型予測を実行できます。FBA、pFBA、FVA、フラックスサンプリング、遺伝子・反応ノックアウトスクリーニング、生産エンベロープ解析、最小培地設計、ギャップフィリングなど、COBRA手法を広範にサポートします。モデルの読み込み・保存はSBML、JSON、YAML形式に対応し、内蔵モデル(e_coli_core、iJO1366など)やBiGG/ BioModelsからのリモートモデルを利用できます。Pythonのコンテキストマネージャによる一時的なモデル改変、並列処理による計算最適化、optlangを介した複数ソルバーの切り替え(GLPK、CPLEX、Gurobi、hybrid)など、実用的なワークフローを提供します。

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

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

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

ドキュメント

COBRApy - 制約ベース再構成および解析 は何をしますか?

概要

COBRApyは、代謝モデルの制約ベース再構成および解析(COBRA)のためのPythonライブラリであり、システム生物学研究に不可欠です。ゲノムスケールの代謝モデルを扱い、細胞代謝の計算機シミュレーション、代謝工学解析、表現型予測を実行できます。

バージョン注意: この例はPyPI上の cobra 0.31.1 を対象としています(import cobra)。ドキュメント: cobrapy.readthedocs.io。リポジトリ: opencobra/cobrapy。

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

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

  • ゲノムスケール代謝モデル(SBML、JSON、YAML)の読み込み、構築、またはエクスポート
  • COBRAモデルでのFBA、pFBA、FVA、フラックスサンプリングの実行
  • 遺伝子または反応ノックアウトスクリーニングおよび生産エンベロープ解析の実行
  • 増殖培地の設計または制限培地の最適化と交換制約の設定
  • 実行不可能なモデルのギャップフィリングまたはモデルの一貫性検証

インストール

uv pip install "cobra==0.31.1"

MATLABモデルの入出力(オプション):

uv pip install "cobra[array]==0.31.1"

COBRApyはソルバーに optlang を使用します。GLPKは swiglpk を介して自動的にインストールされます。大規模MILP/QPの場合、cobra 0.29+ は hybrid ソルバー(HIGHS/OSQP)を追加しました。model.solver = "osqp" は現在hybridを経由するため、将来のリリースでは通常のLPでエラーが発生する可能性があります。利用可能な場合は model.solver = "hybrid" を推奨します。

中核機能

COBRApyは、以下の主要な領域に整理された包括的なツールを提供します:

1. モデル管理

リポジトリまたはファイルから既存のモデルを読み込む:

from cobra.io import load_model

# バンドルされたローカルモデル(ネットワーク不要): textbook, iJO1366, salmonella
model = load_model("textbook")      # e_coli_coreのエイリアス(95反応)
model = load_model("e_coli_core")   # 同一のコア大腸菌モデル
model = load_model("iJO1366")       # ゲノムスケール大腸菌(バンドル)
model = load_model("salmonella")    # サルモネラ iYS1720(バンドル)

# リモートモデル(BiGG / BioModels; ネットワーク必須、初回フェッチ後にキャッシュ)
model = load_model("iML1515")       # BiGG上の大腸菌ゲノムスケールモデル

# ファイルから読み込み
from cobra.io import read_sbml_model, load_json_model, load_yaml_model
model = read_sbml_model("path/to/model.xml")
model = load_json_model("path/to/model.json")
model = load_yaml_model("path/to/model.yml")

モデルを様々な形式で保存:

from cobra.io import write_sbml_model, save_json_model, save_yaml_model
write_sbml_model(model, "output.xml")  # 推奨形式
save_json_model(model, "output.json")  # Escher互換性用
save_yaml_model(model, "output.yml")   # 人間可読

2. モデル構造と構成要素

モデルの構成要素にアクセスして検査:

# 構成要素へのアクセス
model.reactions      # 全反応のDictList
model.metabolites    # 全代謝物のDictList
model.genes          # 全遺伝子のDictList

# IDまたはインデックスで特定のアイテムを取得
reaction = model.reactions.get_by_id("PFK")
metabolite = model.metabolites[0]

# プロパティの検査
print(reaction.reaction)        # 化学量論式
print(reaction.bounds)          # フラックス制約
print(reaction.gene_reaction_rule)  # GPR論理式
print(metabolite.formula)       # 化学式
print(metabolite.compartment)   # 細胞内局在

3. フラックスバランス解析(FBA)

標準的なFBAシミュレーションの実行:

# 基本最適化
solution = model.optimize()
print(f"目的関数値: {solution.objective_value}")
print(f"ステータス: {solution.status}")

# フラックスへのアクセス
print(solution.fluxes["PFK"])
print(solution.fluxes.head())

# 高速最適化(目的関数値のみ)
objective_value = model.slim_optimize()

# 目的関数の変更
model.objective = "ATPM"
solution = model.optimize()

節約的FBA(全フラックス最小化):

from cobra.flux_analysis import pfba
solution = pfba(model)

幾何学的FBA(中央解の探索):

from cobra.flux_analysis import geometric_fba
solution = geometric_fba(model)

4. フラックス可変性解析(FVA)

全反応のフラックス範囲を決定:

from cobra.flux_analysis import flux_variability_analysis

# 標準FVA
fva_result = flux_variability_analysis(model)

# 最適性90%でのFVA
fva_result = flux_variability_analysis(model, fraction_of_optimum=0.9)

# ループレスFVA(熱力学的に不可能なループを排除)
fva_result = flux_variability_analysis(model, loopless=True)

# 特定の反応に対するFVA
fva_result = flux_variability_analysis(
    model,
    reaction_list=["PFK", "FBA", "PGI"]
)

5. 遺伝子および反応欠損研究

ノックアウト解析の実行:

from cobra.flux_analysis import (
    single_gene_deletion,
    single_reaction_deletion,
    double_gene_deletion,
    double_reaction_deletion
)

# 単一欠損
gene_results = single_gene_deletion(model)
reaction_results = single_reaction_deletion(model)

# 二重欠損(マルチプロセッシングを使用)
double_gene_results = double_gene_deletion(
    model,
    processes=4  # CPUコア数
)

# コンテキストマネージャを使用した手動ノックアウト
with model:
    model.genes.get_by_id("b0008").knock_out()
    solution = model.optimize()
    print(f"ノックアウト後の増殖: {solution.objective_value}")
# コンテキスト終了後、モデルは自動的に元に戻る

6. 増殖培地と最小培地

増殖培地の管理:

# 現在の培地を表示
print(model.medium)

# 培地の変更(辞書全体を再割り当てする必要あり)
medium = model.medium
medium["EX_glc__D_e"] = 10.0  # グルコース取り込みを設定
medium["EX_o2_e"] = 0.0       # 嫌気条件
model.medium = medium

# 最小培地の計算
from cobra.medium import minimal_medium

# 全取り込みフラックスを最小化
min_medium = minimal_medium(model, minimize_components=False)

# 構成要素数を最小化(MILPを使用、低速)
min_medium = minimal_medium(
    model,
    minimize_components=True,
    open_exchanges=True
)

7. フラックスサンプリング

実行可能なフラックス空間のサンプリング:

from cobra.sampling import sample

# OptGPを使用したサンプリング(デフォルト、並列処理対応)
samples = sample(model, n=1000, method="optgp", processes=4)

# ACHRを使用したサンプリング
samples = sample(model, n=1000, method="achr")

# サンプルの検証
from cobra.sampling import OptGPSampler
sampler = OptGPSampler(model, processes=4)
sampler.sample(1000)
validation = sampler.validate(sampler.samples)
print(validation.value_counts())  # すべて 'v'(有効)になるはず

8. 生産エンベロープ

表現型フェーズプレーンの計算:

from cobra.flux_analysis import production_envelope

# 標準生産エンベロープ
envelope = production_envelope(
    model,
    reactions=["EX_glc__D_e", "EX_o2_e"],
    objective="EX_ac_e"  # 酢酸生産
)

# 炭素収量を含む
envelope = production_envelope(
    model,
    reactions=["EX_glc__D_e", "EX_o2_e"],
    carbon_sources="EX_glc__D_e"
)

# 可視化(matplotlibまたはpandasプロットを使用)
import matplotlib.pyplot as plt
envelope.plot(x="EX_glc__D_e", y="EX_o2_e", kind="scatter")
plt.show()

9. ギャップフィリング

モデルを実行可能にするための反応の追加:

from cobra.flux_analysis import gapfill

# ユニバーサル反応データベースを提供(SBML/JSON); cobra 0.31+ にはバンドルされていません
from cobra.io import read_sbml_model
universal = read_sbml_model("path/to/universal_reactions.xml")

# ギャップフィリングの実行
with model:
    # デモのためギャップを作成する反応を削除
    model.remove_reactions([model.reactions.PGI])

    # 必要な反応を見つける
    solution = gapfill(model, universal)
    print(f"追加する反応: {solution}")

10. モデル構築

ゼロからモデルを構築:

from cobra import Model, Reaction, Metabolite

# モデルの作成
model = Model("my_model")

# 代謝物の作成
atp_c = Metabolite("atp_c", formula="C10H12N5O13P3",
                   name="ATP", compartment="c")
adp_c = Metabolite("adp_c", formula="C10H12N5O10P2",
                   name="ADP", compartment="c")
pi_c = Metabolite("pi_c", formula="HO4P",
                  name="Phosphate", compartment="c")

# 反応の作成
reaction = Reaction("ATPASE")
reaction.name = "ATP hydrolysis"
reaction.subsystem = "Energy"
reaction.lower_bound = 0.0
reaction.upper_bound = 1000.0

# 化学量論で代謝物を追加
reaction.add_metabolites({
    atp_c: -1.0,
    adp_c: 1.0,
    pi_c: 1.0
})

# 遺伝子-反応ルールの追加
reaction.gene_reaction_rule = "(gene1 and gene2) or gene3"

# モデルに追加
model.add_reactions([reaction])

# 境界反応の追加
model.add_boundary(atp_c, type="exchange")
model.add_boundary(adp_c, type="demand")

# 目的関数の設定
model.objective = "ATPASE"

一般的なワークフロー

ワークフロー1: モデルを読み込み増殖を予測

from cobra.io import load_model

# モデルの読み込み(textbook = 高速チュートリアル; iJO1366 / iML1515 はゲノムスケール)
model = load_model("textbook")

# FBAの実行
solution = model.optimize()
print(f"増殖率: {solution.objective_value:.3f} /h")

# 活性経路の表示
print(solution.fluxes[solution.fluxes.abs() > 1e-6])

ワークフロー2: 遺伝子ノックアウトスクリーニング

from cobra.io import load_model
from cobra.flux_analysis import single_gene_deletion

# モデルの読み込み
model = load_model("textbook")
baseline = model.slim_optimize()

# 単一遺伝子欠損の実行
results = single_gene_deletion(model)

# 必須遺伝子の特定(増殖 < 閾値)
essential_genes = results[results["growth"] < 0.01]
print(f"{len(essential_genes)}個の必須遺伝子が見つかりました")

# 影響が最小の遺伝子を見つける
neutral_genes = results[results["growth"] > 0.9 * baseline]

ワークフロー3: 培地最適化

from cobra.io import load_model
from cobra.medium import minimal_medium

# モデルの読み込み
model = load_model("textbook")

# 最大増殖の50%に対する最小培地を計算
target_growth = model.slim_optimize() * 0.5
min_medium = minimal_medium(
    model,
    target_growth,
    minimize_components=True
)

print(f"最小培地の構成要素数: {len(min_medium)}")
print(min_medium)

ワークフロー4: フラックス不確実性解析

from cobra.io import load_model
from cobra.flux_analysis import flux_variability_analysis
from cobra.sampling import sample

# モデルの読み込み
model = load_model("textbook")

# まず最適時のフラックス範囲を確認
fva = flux_variability_analysis(model, fraction_of_optimum=1.0)

# 範囲が大きい反応については、サンプリングで分布を理解
samples = sample(model, n=1000)

# 特定の反応を分析
reaction_id = "PFK"
import matplotlib.pyplot as plt
samples[reaction_id].hist(bins=50)
plt.xlabel(f"{reaction_id}を通じたフラックス")
plt.ylabel("頻度")
plt.show()

ワークフロー5: 一時的な変更のためのコンテキストマネージャ

コンテキストマネージャを使用して一時的な変更を行う:

# コンテキスト外ではモデルは変更されない
with model:
    # 一時的に目的関数を変更
    model.objective = "ATPM"

    # 一時的に境界を変更
    model.reactions.EX_glc__D_e.lower_bound = -5.0

    # 一時的に遺伝子をノックアウト
    model.genes.b0008.knock_out()

    # 変更を適用して最適化
    solution = model.optimize()
    print(f"変更後の増殖: {solution.objective_value}")

# すべての変更は自動的に元に戻る
solution = model.optimize()
print(f"元の増殖: {solution.objective_value}")

主要な概念

DictList アクセスパターン、フラックス束縛規則、遺伝子-反応ルール(GPR)、および EX_ 交換反応の符号規則については、references/api_quick_reference.md の「主要概念」で説明しています。

ベストプラクティス

  1. 一時的な変更にはコンテキストマネージャ を使用して状態管理の問題を回避する
  2. モデルを検証 してから分析を始める - model.slim_optimize() で実行可能性を確認
  3. 最適化後に解のステータス を確認する - optimal は成功を示す
  4. 熱力学的実現可能性が重要な場合はループレスFVA を使用する
  5. FVAで fraction_of_optimum を適切に設定して準最適空間を探索する
  6. 計算コストの高い操作(サンプリング、二重欠損)は並列化 する - ゲノムスケールモデルでは小さい n と processes=1 から始める
  7. モデル交換と長期保存にはSBML形式 を推奨する
  8. 目的関数値のみ必要な場合は slim_optimize() を使用してパフォーマンスを向上させる
  9. フラックスサンプルを検証 して数値的安定性を確保する
  10. ワークフロー例からCSV/PNGファイルを書き込む前に出力パスを確認 する

トラブルシューティング

実行不可能な解: 培地制約、反応境界、モデルの一貫性を確認する 最適化が遅い: model.solver で異なるソルバー(GLPK、CPLEX、Gurobi)を試す 非有界な解: 交換反応に適切な上限が設定されているか確認する インポートエラー: 正しいファイル形式と有効なSBML識別子を確認する

参考文献

詳細なワークフローとAPIパターンについては、以下を参照:

  • references/workflows.md - 包括的なステップバイステップのワークフロー例
  • references/api_quick_reference.md - 一般的な関数シグネチャとパターン

公式ドキュメント: https://cobrapy.readthedocs.io/en/latest/

サイエンティフィックエージェントスキルの引用

このスキルはK-DenseによるScientific Agent Skillsの一部です。これが原稿、報告書、プレゼンテーション、またはコードリリースに実質的に貢献した場合は、参考文献またはソフトウェアセクションに論文を追加し、その旨をユーザーに伝えてください:

Kassis, T., Agarwal, V., He, Y., Patel, D., & Brueckner, A. M. (2026). Scientific Agent Skills: A Library of Procedural Knowledge for Research Agents. arXiv:2609.00065. https://doi.org/10.48550/arXiv.2609.00065

常に最新バージョンを引用してください。DOIと https://arxiv.org/abs/2609.00065 は最新のarXivバージョンに解決されるため、v1 などのバージョンサフィックスを決して追加しないでください。ネットワークアクセスが利用可能な場合は、参考文献を書く前に https://arxiv.org/abs/2609.00065(または http://export.arxiv.org/api/query?id_list=2609.00065)をフェッチし、そのレコードから著者リスト、年、バージョンを取得してください。レコードにジャーナル参照または出版社DOIが記載されている場合は、代わりに公開版を引用してください。

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.

関連スキル