{"id":"cobrapy","name":"cobrapy","summary":"制約ベースの代謝モデル(COBRA)。FBA、FVA、遺伝子ノックアウト、フラックスサンプリング、SBMLモデル、システム生物学および代謝工学解析のためのもの。","body":"# COBRApy - Constraint-Based Reconstruction and Analysis\n\n## Overview\n\nCOBRApy is a Python library for constraint-based reconstruction and analysis (COBRA) of metabolic models, essential for systems biology research. Work with genome-scale metabolic models, perform computational simulations of cellular metabolism, conduct metabolic engineering analyses, and predict phenotypic behaviors.\n\n**Version note:** Examples target **cobra 0.31.1** on PyPI (import `cobra`). Docs: [cobrapy.readthedocs.io](https://cobrapy.readthedocs.io/en/latest/). Repo: [opencobra/cobrapy](https://github.com/opencobra/cobrapy).\n\n## When to Use This Skill\n\nUse this skill when:\n- Loading, building, or exporting genome-scale metabolic models (SBML, JSON, YAML)\n- Running FBA, pFBA, FVA, or flux sampling on COBRA models\n- Performing gene or reaction knockout screens and production envelope analysis\n- Designing or optimizing growth media and exchange constraints\n- Gap-filling infeasible models or validating model consistency\n\n## Installation\n\n```bash\nuv pip install \"cobra==0.31.1\"\n```\n\nMATLAB model I/O (optional):\n\n```bash\nuv pip install \"cobra[array]==0.31.1\"\n```\n\nCOBRApy uses [optlang](https://optlang.readthedocs.io/) for solvers. GLPK installs automatically via `swiglpk`. For large MILPs/QPs, cobra 0.29+ adds a **hybrid** solver (HIGHS/OSQP); `model.solver = \"osqp\"` now routes through hybrid and may error on plain LPs in a future release—prefer `model.solver = \"hybrid\"` when available.\n\n## Core Capabilities\n\nCOBRApy provides comprehensive tools organized into several key areas:\n\n### 1. Model Management\n\nLoad existing models from repositories or files:\n```python\nfrom cobra.io import load_model\n\n# Bundled locally (no network): textbook, iJO1366, salmonella\nmodel = load_model(\"textbook\")      # alias for e_coli_core (95 reactions)\nmodel = load_model(\"e_coli_core\")   # same core E. coli model\nmodel = load_model(\"iJO1366\")       # genome-scale E. coli (bundled)\nmodel = load_model(\"salmonella\")    # Salmonella iYS1720 (bundled)\n\n# Remote (BiGG / BioModels; requires network, cached after first fetch)\nmodel = load_model(\"iML1515\")       # E. coli genome-scale on BiGG\n\n# Load from files\nfrom cobra.io import read_sbml_model, load_json_model, load_yaml_model\nmodel = read_sbml_model(\"path/to/model.xml\")\nmodel = load_json_model(\"path/to/model.json\")\nmodel = load_yaml_model(\"path/to/model.yml\")\n```\n\nSave models in various formats:\n```python\nfrom cobra.io import write_sbml_model, save_json_model, save_yaml_model\nwrite_sbml_model(model, \"output.xml\")  # Preferred format\nsave_json_model(model, \"output.json\")  # For Escher compatibility\nsave_yaml_model(model, \"output.yml\")   # Human-readable\n```\n\n### 2. Model Structure and Components\n\nAccess and inspect model components:\n```python\n# Access components\nmodel.reactions      # DictList of all reactions\nmodel.metabolites    # DictList of all metabolites\nmodel.genes          # DictList of all genes\n\n# Get specific items by ID or index\nreaction = model.reactions.get_by_id(\"PFK\")\nmetabolite = model.metabolites[0]\n\n# Inspect properties\nprint(reaction.reaction)        # Stoichiometric equation\nprint(reaction.bounds)          # Flux constraints\nprint(reaction.gene_reaction_rule)  # GPR logic\nprint(metabolite.formula)       # Chemical formula\nprint(metabolite.compartment)   # Cellular location\n```\n\n### 3. Flux Balance Analysis (FBA)\n\nPerform standard FBA simulation:\n```python\n# Basic optimization\nsolution = model.optimize()\nprint(f\"Objective value: {solution.objective_value}\")\nprint(f\"Status: {solution.status}\")\n\n# Access fluxes\nprint(solution.fluxes[\"PFK\"])\nprint(solution.fluxes.head())\n\n# Fast optimization (objective value only)\nobjective_value = model.slim_optimize()\n\n# Change objective\nmodel.objective = \"ATPM\"\nsolution = model.optimize()\n```\n\nParsimonious FBA (minimize total flux):\n```python\nfrom cobra.flux_analysis import pfba\nsolution = pfba(model)\n```\n\nGeometric FBA (find central solution):\n```python\nfrom cobra.flux_analysis import geometric_fba\nsolution = geometric_fba(model)\n```\n\n### 4. Flux Variability Analysis (FVA)\n\nDetermine flux ranges for all reactions:\n```python\nfrom cobra.flux_analysis import flux_variability_analysis\n\n# Standard FVA\nfva_result = flux_variability_analysis(model)\n\n# FVA at 90% optimality\nfva_result = flux_variability_analysis(model, fraction_of_optimum=0.9)\n\n# Loopless FVA (eliminates thermodynamically infeasible loops)\nfva_result = flux_variability_analysis(model, loopless=True)\n\n# FVA for specific reactions\nfva_result = flux_variability_analysis(\n    model,\n    reaction_list=[\"PFK\", \"FBA\", \"PGI\"]\n)\n```\n\n### 5. Gene and Reaction Deletion Studies\n\nPerform knockout analyses:\n```python\nfrom cobra.flux_analysis import (\n    single_gene_deletion,\n    single_reaction_deletion,\n    double_gene_deletion,\n    double_reaction_deletion\n)\n\n# Single deletions\ngene_results = single_gene_deletion(model)\nreaction_results = single_reaction_deletion(model)\n\n# Double deletions (uses multiprocessing)\ndouble_gene_results = double_gene_deletion(\n    model,\n    processes=4  # Number of CPU cores\n)\n\n# Manual knockout using context manager\nwith model:\n    model.genes.get_by_id(\"b0008\").knock_out()\n    solution = model.optimize()\n    print(f\"Growth after knockout: {solution.objective_value}\")\n# Model automatically reverts after context exit\n```\n\n### 6. Growth Media and Minimal Media\n\nManage growth medium:\n```python\n# View current medium\nprint(model.medium)\n\n# Modify medium (must reassign entire dict)\nmedium = model.medium\nmedium[\"EX_glc__D_e\"] = 10.0  # Set glucose uptake\nmedium[\"EX_o2_e\"] = 0.0       # Anaerobic conditions\nmodel.medium = medium\n\n# Calculate minimal media\nfrom cobra.medium import minimal_medium\n\n# Minimize total import flux\nmin_medium = minimal_medium(model, minimize_components=False)\n\n# Minimize number of components (uses MILP, slower)\nmin_medium = minimal_medium(\n    model,\n    minimize_components=True,\n    open_exchanges=True\n)\n```\n\n### 7. Flux Sampling\n\nSample the feasible flux space:\n```python\nfrom cobra.sampling import sample\n\n# Sample using OptGP (default, supports parallel processing)\nsamples = sample(model, n=1000, method=\"optgp\", processes=4)\n\n# Sample using ACHR\nsamples = sample(model, n=1000, method=\"achr\")\n\n# Validate samples\nfrom cobra.sampling import OptGPSampler\nsampler = OptGPSampler(model, processes=4)\nsampler.sample(1000)\nvalidation = sampler.validate(sampler.samples)\nprint(validation.value_counts())  # Should be all 'v' for valid\n```\n\n### 8. Production Envelopes\n\nCalculate phenotype phase planes:\n```python\nfrom cobra.flux_analysis import production_envelope\n\n# Standard production envelope\nenvelope = production_envelope(\n    model,\n    reactions=[\"EX_glc__D_e\", \"EX_o2_e\"],\n    objective=\"EX_ac_e\"  # Acetate production\n)\n\n# With carbon yield\nenvelope = production_envelope(\n    model,\n    reactions=[\"EX_glc__D_e\", \"EX_o2_e\"],\n    carbon_sources=\"EX_glc__D_e\"\n)\n\n# Visualize (use matplotlib or pandas plotting)\nimport matplotlib.pyplot as plt\nenvelope.plot(x=\"EX_glc__D_e\", y=\"EX_o2_e\", kind=\"scatter\")\nplt.show()\n```\n\n### 9. Gapfilling\n\nAdd reactions to make models feasible:\n```python\nfrom cobra.flux_analysis import gapfill\n\n# Provide a universal reaction database (SBML/JSON); not bundled in cobra 0.31+\nfrom cobra.io import read_sbml_model\nuniversal = read_sbml_model(\"path/to/universal_reactions.xml\")\n\n# Perform gapfilling\nwith model:\n    # Remove reactions to create gaps for demonstration\n    model.remove_reactions([model.reactions.PGI])\n\n    # Find reactions needed\n    solution = gapfill(model, universal)\n    print(f\"Reactions to add: {solution}\")\n```\n\n### 10. Model Building\n\nBuild models from scratch:\n```python\nfrom cobra import Model, Reaction, Metabolite\n\n# Create model\nmodel = Model(\"my_model\")\n\n# Create metabolites\natp_c = Metabolite(\"atp_c\", formula=\"C10H12N5O13P3\",\n                   name=\"ATP\", compartment=\"c\")\nadp_c = Metabolite(\"adp_c\", formula=\"C10H12N5O10P2\",\n                   name=\"ADP\", compartment=\"c\")\npi_c = Metabolite(\"pi_c\", formula=\"HO4P\",\n                  name=\"Phosphate\", compartment=\"c\")\n\n# Create reaction\nreaction = Reaction(\"ATPASE\")\nreaction.name = \"ATP hydrolysis\"\nreaction.subsystem = \"Energy\"\nreaction.lower_bound = 0.0\nreaction.upper_bound = 1000.0\n\n# Add metabolites with stoichiometry\nreaction.add_metabolites({\n    atp_c: -1.0,\n    adp_c: 1.0,\n    pi_c: 1.0\n})\n\n# Add gene-reaction rule\nreaction.gene_reaction_rule = \"(gene1 and gene2) or gene3\"\n\n# Add to model\nmodel.add_reactions([reaction])\n\n# Add boundary reactions\nmodel.add_boundary(atp_c, type=\"exchange\")\nmodel.add_boundary(adp_c, type=\"demand\")\n\n# Set objective\nmodel.objective = \"ATPASE\"\n```\n\n## Common Workflows\n\n### Workflow 1: Load Model and Predict Growth\n\n```python\nfrom cobra.io import load_model\n\n# Load model (textbook = fast tutorial; iJO1366 / iML1515 for genome-scale)\nmodel = load_model(\"textbook\")\n\n# Run FBA\nsolution = model.optimize()\nprint(f\"Growth rate: {solution.objective_value:.3f} /h\")\n\n# Show active pathways\nprint(solution.fluxes[solution.fluxes.abs() > 1e-6])\n```\n\n### Workflow 2: Gene Knockout Screen\n\n```python\nfrom cobra.io import load_model\nfrom cobra.flux_analysis import single_gene_deletion\n\n# Load model\nmodel = load_model(\"textbook\")\nbaseline = model.slim_optimize()\n\n# Perform single gene deletions\nresults = single_gene_deletion(model)\n\n# Find essential genes (growth < threshold)\nessential_genes = results[results[\"growth\"] < 0.01]\nprint(f\"Found {len(essential_genes)} essential genes\")\n\n# Find genes with minimal impact\nneutral_genes = results[results[\"growth\"] > 0.9 * baseline]\n```\n\n### Workflow 3: Media Optimization\n\n```python\nfrom cobra.io import load_model\nfrom cobra.medium import minimal_medium\n\n# Load model\nmodel = load_model(\"textbook\")\n\n# Calculate minimal medium for 50% of max growth\ntarget_growth = model.slim_optimize() * 0.5\nmin_medium = minimal_medium(\n    model,\n    target_growth,\n    minimize_components=True\n)\n\nprint(f\"Minimal medium components: {len(min_medium)}\")\nprint(min_medium)\n```\n\n### Workflow 4: Flux Uncertainty Analysis\n\n```python\nfrom cobra.io import load_model\nfrom cobra.flux_analysis import flux_variability_analysis\nfrom cobra.sampling import sample\n\n# Load model\nmodel = load_model(\"textbook\")\n\n# First check flux ranges at optimality\nfva = flux_variability_analysis(model, fraction_of_optimum=1.0)\n\n# For reactions with large ranges, sample to understand distribution\nsamples = sample(model, n=1000)\n\n# Analyze specific reaction\nreaction_id = \"PFK\"\nimport matplotlib.pyplot as plt\nsamples[reaction_id].hist(bins=50)\nplt.xlabel(f\"Flux through {reaction_id}\")\nplt.ylabel(\"Frequency\")\nplt.show()\n```\n\n### Workflow 5: Context Manager for Temporary Changes\n\nUse context managers to make temporary modifications:\n```python\n# Model remains unchanged outside context\nwith model:\n    # Temporarily change objective\n    model.objective = \"ATPM\"\n\n    # Temporarily modify bounds\n    model.reactions.EX_glc__D_e.lower_bound = -5.0\n\n    # Temporarily knock out genes\n    model.genes.b0008.knock_out()\n\n    # Optimize with changes\n    solution = model.optimize()\n    print(f\"Modified growth: {solution.objective_value}\")\n\n# All changes automatically reverted\nsolution = model.optimize()\nprint(f\"Original growth: {solution.objective_value}\")\n```\n\n## Key Concepts\n\n### DictList Objects\nModels use `DictList` objects for reactions, metabolites, and genes - behaving like both lists and dictionaries:\n```python\n# Access by index\nfirst_reaction = model.reactions[0]\n\n# Access by ID\npfk = model.reactions.get_by_id(\"PFK\")\n\n# Query methods\natp_reactions = model.reactions.query(\"atp\")\n```\n\n### Flux Constraints\nReaction bounds define feasible flux ranges:\n- **Irreversible**: `lower_bound = 0, upper_bound > 0`\n- **Reversible**: `lower_bound < 0, upper_bound > 0`\n- Set both bounds simultaneously with `.bounds` to avoid inconsistencies\n\n### Gene-Reaction Rules (GPR)\nBoolean logic linking genes to reactions:\n```python\n# AND logic (both required)\nreaction.gene_reaction_rule = \"gene1 and gene2\"\n\n# OR logic (either sufficient)\nreaction.gene_reaction_rule = \"gene1 or gene2\"\n\n# Complex logic\nreaction.gene_reaction_rule = \"(gene1 and gene2) or (gene3 and gene4)\"\n```\n\n### Exchange Reactions\nSpecial reactions representing metabolite import/export:\n- Named with prefix `EX_` by convention\n- Positive flux = secretion, negative flux = uptake\n- Managed through `model.medium` dictionary\n\n## Best Practices\n\n1. **Use context managers** for temporary modifications to avoid state management issues\n2. **Validate models** before analysis using `model.slim_optimize()` to ensure feasibility\n3. **Check solution status** after optimization - `optimal` indicates successful solve\n4. **Use loopless FVA** when thermodynamic feasibility matters\n5. **Set fraction_of_optimum** appropriately in FVA to explore suboptimal space\n6. **Parallelize** computationally expensive operations (sampling, double deletions) — start with small `n` and `processes=1` on genome-scale models\n7. **Prefer SBML format** for model exchange and long-term storage\n8. **Use slim_optimize()** when only objective value needed for performance\n9. **Validate flux samples** to ensure numerical stability\n10. **Confirm output paths** before writing CSV/PNG files from workflow examples\n\n## Troubleshooting\n\n**Infeasible solutions**: Check medium constraints, reaction bounds, and model consistency\n**Slow optimization**: Try different solvers (GLPK, CPLEX, Gurobi) via `model.solver`\n**Unbounded solutions**: Verify exchange reactions have appropriate upper bounds\n**Import errors**: Ensure correct file format and valid SBML identifiers\n\n## References\n\nFor detailed workflows and API patterns, refer to:\n- `references/workflows.md` - Comprehensive step-by-step workflow examples\n- `references/api_quick_reference.md` - Common function signatures and patterns\n\nOfficial documentation: https://cobrapy.readthedocs.io/en/latest/","author":"@K-Dense-AI","ownerProfile":null,"authorContacts":null,"sourceUrl":"https://github.com/K-Dense-AI/scientific-agent-skills/tree/main/skills/cobrapy","license":"MIT","category":"document","lang":"en","tokens":3440,"stars":0,"calls30d":1,"claimed":false,"visibility":"public","origin":"crawler","version":"0.1.0","createdAt":"2026-08-22","updatedAt":"2026-08-22","files":[{"path":"references/api_quick_reference.md","size":16596,"sha256":"92b29b0fe995715fbb14f82193f61d18e79d6f44ebeac027469ab8d0dd78a84e"},{"path":"references/workflows.md","size":22895,"sha256":"19707c24028f111761e8b01e119a2e807096c0c1aa82cd136aeb8f2c1923dafd"}],"requires":{"mcp":[],"tools":["Read Write Edit Bash"]},"safety":{"flags":[],"scannedAt":"2026-08-22","hasScripts":false,"networkEndpoints":["cobrapy.readthedocs.io","optlang.readthedocs.io"]}}