cobrapy

K-Dense-AI/scientific-agent-skills · updated Jun 4, 2026

MDX-style export adds YAML metadata + attribution linking explainx.ai and this canonical listing URL.

$npx skills add https://github.com/K-Dense-AI/scientific-agent-skills --skill cobrapy
0 commentsdiscussion
summary

### Cobrapy

  • name: "cobrapy"
  • description: "Constraint-based metabolic modeling (COBRA). FBA, FVA, gene knockouts, flux sampling, SBML models, for systems biology and metabolic engineering analysis."
  • allowed-tools: "Read Write Edit Bash"
skill.md
name
cobrapy
description
Constraint-based metabolic modeling (COBRA). FBA, FVA, gene knockouts, flux sampling, SBML models, for systems biology and metabolic engineering analysis.
license
GPL-2.0 license
allowed-tools
Read Write Edit Bash
compatibility
Requires Python 3.9+ (cobra 0.30+ dropped 3.8). Install with uv pip install. GLPK (swiglpk) is the default solver; CPLEX/Gurobi optional. load_model fetches from bundled data, BiGG, or BioModels (network required for remote models).
metadata
version: "1.1" skill-author: K-Dense Inc.

COBRApy - Constraint-Based Reconstruction and Analysis

Overview

COBRApy 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.

Version note: Examples target cobra 0.31.1 on PyPI (import cobra). Docs: cobrapy.readthedocs.io. Repo: opencobra/cobrapy.

When to Use This Skill

Use this skill when:

  • Loading, building, or exporting genome-scale metabolic models (SBML, JSON, YAML)
  • Running FBA, pFBA, FVA, or flux sampling on COBRA models
  • Performing gene or reaction knockout screens and production envelope analysis
  • Designing or optimizing growth media and exchange constraints
  • Gap-filling infeasible models or validating model consistency

Installation

uv pip install "cobra==0.31.1"

MATLAB model I/O (optional):

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

COBRApy uses optlang 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.

Core Capabilities

COBRApy provides comprehensive tools organized into several key areas:

1. Model Management

Load existing models from repositories or files:

from cobra.io import load_model

# Bundled locally (no network): textbook, iJO1366, salmonella
model = load_model("textbook")      # alias for e_coli_core (95 reactions)
model = load_model("e_coli_core")   # same core E. coli model
model = load_model("iJO1366")       # genome-scale E. coli (bundled)
model = load_model("salmonella")    # Salmonella iYS1720 (bundled)

# Remote (BiGG / BioModels; requires network, cached after first fetch)
model = load_model("iML1515")       # E. coli genome-scale on BiGG

# Load from files
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")

Save models in various formats:

from cobra.io import write_sbml_model, save_json_model, save_yaml_model
write_sbml_model(model, "output.xml")  # Preferred format
save_json_model(model, "output.json")  # For Escher compatibility
save_yaml_model(model, "output.yml")   # Human-readable

2. Model Structure and Components

Access and inspect model components:

# Access components
model.reactions      # DictList of all reactions
model.metabolites    # DictList of all metabolites
model.genes          # DictList of all genes

# Get specific items by ID or index
reaction = model.reactions.get_by_id("PFK")
metabolite = model.metabolites[0]

# Inspect properties
print(reaction.reaction)        # Stoichiometric equation
print(reaction.bounds)          # Flux constraints
print(reaction.gene_reaction_rule)  # GPR logic
print(metabolite.formula)       # Chemical formula
print(metabolite.compartment)   # Cellular location

3. Flux Balance Analysis (FBA)

Perform standard FBA simulation:

# Basic optimization
solution = model.optimize()
print(f"Objective value: {solution.objective_value}")
print(f"Status: {solution.status}")

# Access fluxes
print(solution.fluxes["PFK"])
print(solution.fluxes.head())

# Fast optimization (objective value only)
objective_value = model.slim_optimize()

# Change objective
model.objective = "ATPM"
solution = model.optimize()

Parsimonious FBA (minimize total flux):

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

Geometric FBA (find central solution):

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

4. Flux Variability Analysis (FVA)

Determine flux ranges for all reactions:

from cobra.flux_analysis import flux_variability_analysis

# Standard FVA
fva_result = flux_variability_analysis(model)

# FVA at 90% optimality
fva_result = flux_variability_analysis(model, fraction_of_optimum=0.9)

# Loopless FVA (eliminates thermodynamically infeasible loops)
fva_result = flux_variability_analysis(model, loopless=True)

# FVA for specific reactions
fva_result = flux_variability_analysis(
    model,
    reaction_list=["PFK", "FBA", "PGI"]
)

5. Gene and Reaction Deletion Studies

Perform knockout analyses:

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

# Single deletions
gene_results = single_gene_deletion(model)
reaction_results = single_reaction_deletion(model)

# Double deletions (uses multiprocessing)
double_gene_results = double_gene_deletion(
    model,
    processes=4  # Number of CPU cores
)

# Manual knockout using context manager
with model:
    model.genes.get_by_id("b0008").knock_out()
    solution = model.optimize()
    print(f"Growth after knockout: {solution.objective_value}")
# Model automatically reverts after context exit

6. Growth Media and Minimal Media

Manage growth medium:

# View current medium
print(model.medium)

# Modify medium (must reassign entire dict)
medium = model.medium
medium["EX_glc__D_e"] = 10.0  # Set glucose uptake
medium["EX_o2_e"] = 0.0       # Anaerobic conditions
model.medium = medium

# Calculate minimal media
from cobra.medium import minimal_medium

# Minimize total import flux
min_medium = minimal_medium(model, minimize_components=False)

# Minimize number of components (uses MILP, slower)
min_medium = minimal_medium(
    model,
    minimize_components=True,
    open_exchanges=True
)

7. Flux Sampling

Sample the feasible flux space:

from cobra.sampling import sample

# Sample using OptGP (default, supports parallel processing)
samples = sample(model, n=1000, method="optgp", processes=4)

# Sample using ACHR
samples = sample(model, n=1000, method="achr")

# Validate samples
from cobra.sampling import OptGPSampler
sampler = OptGPSampler(model, processes=4)
sampler.sample(1000)
validation = sampler.validate(sampler.samples)
print(validation.value_counts())  # Should be all 'v' for valid

8. Production Envelopes

Calculate phenotype phase planes:

from cobra.flux_analysis import production_envelope

# Standard production envelope
envelope = production_envelope(
    model,
    reactions=["EX_glc__D_e", "EX_o2_e"],
    objective="EX_ac_e"  # Acetate production
)

# With carbon yield
envelope = production_envelope(
    model,
    reactions=["EX_glc__D_e", "EX_o2_e"],
    carbon_sources="EX_glc__D_e"
)

# Visualize (use matplotlib or pandas plotting)
import matplotlib.pyplot as plt
envelope.plot(x="EX_glc__D_e", y="EX_o2_e", kind="scatter")
plt.show()

9. Gapfilling

Add reactions to make models feasible:

from cobra.flux_analysis import gapfill

# Provide a universal reaction database (SBML/JSON); not bundled in cobra 0.31+
from cobra.io import read_sbml_model
universal = read_sbml_model("path/to/universal_reactions.xml")

# Perform gapfilling
with model:
    # Remove reactions to create gaps for demonstration
    model.remove_reactions([model.reactions.PGI])

    # Find reactions needed
    solution = gapfill(model, universal)
    print(f"Reactions to add: {solution}")

10. Model Building

Build models from scratch:

from cobra import Model, Reaction, Metabolite

# Create model
model = Model("my_model")

# Create metabolites
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")

# Create reaction
reaction = Reaction("ATPASE")
reaction.name = "ATP hydrolysis"
reaction.subsystem = "Energy"
reaction.lower_bound = 0.0
reaction.upper_bound = 1000.0

# Add metabolites with stoichiometry
reaction.add_metabolites({
    atp_c: -1.0,
    adp_c: 1.0,
    pi_c: 1.0
})

# Add gene-reaction rule
reaction.gene_reaction_rule = "(gene1 and gene2) or gene3"

# Add to model
model.add_reactions([reaction])

# Add boundary reactions
model.add_boundary(atp_c, type="exchange")
model.add_boundary(adp_c, type="demand")

# Set objective
model.objective = "ATPASE"

Common Workflows

Workflow 1: Load Model and Predict Growth

from cobra.io import load_model

# Load model (textbook = fast tutorial; iJO1366 / iML1515 for genome-scale)
model = load_model("textbook")

# Run FBA
solution = model.optimize()
print(f"Growth rate: {solution.objective_value:.3f} /h")

# Show active pathways
print(solution.fluxes[solution.fluxes.abs() > 1e-6])

Workflow 2: Gene Knockout Screen

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

# Load model
model = load_model("textbook")
baseline = model.slim_optimize()

# Perform single gene deletions
results = single_gene_deletion(model)

# Find essential genes (growth < threshold)
essential_genes = results[results["growth"] < 0.01]
print(f"Found {len(essential_genes)} essential genes")

# Find genes with minimal impact
neutral_genes = results[results["growth"] > 0.9 * baseline]

Workflow 3: Media Optimization

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

# Load model
model = load_model("textbook")

# Calculate minimal medium for 50% of max growth
target_growth = model.slim_optimize() * 0.5
min_medium = minimal_medium(
    model,
    target_growth,
    minimize_components=True
)

print(f"Minimal medium components: {len(min_medium)}")
print(min_medium)

Workflow 4: Flux Uncertainty Analysis

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

# Load model
model = load_model("textbook")

# First check flux ranges at optimality
fva = flux_variability_analysis(model, fraction_of_optimum=1.0)

# For reactions with large ranges, sample to understand distribution
samples = sample(model, n=1000)

# Analyze specific reaction
reaction_id = "PFK"
import matplotlib.pyplot as plt
samples[reaction_id].hist(bins=50)
plt.xlabel(f"Flux through {reaction_id}")
plt.ylabel("Frequency")
plt.show()

Workflow 5: Context Manager for Temporary Changes

Use context managers to make temporary modifications:

# Model remains unchanged outside context
with model:
    # Temporarily change objective
    model.objective = "ATPM"

    # Temporarily modify bounds
    model.reactions.EX_glc__D_e.lower_bound = -5.0

    # Temporarily knock out genes
    model.genes.b0008.knock_out()

    # Optimize with changes
    solution = model.optimize()
    print(f"Modified growth: {solution.objective_value}")

# All changes automatically reverted
solution = model.optimize()
print(f"Original growth: {solution.objective_value}")

Key Concepts

DictList Objects

Models use DictList objects for reactions, metabolites, and genes - behaving like both lists and dictionaries:

# Access by index
first_reaction = model.reactions[0]

# Access by ID
pfk = model.reactions.get_by_id("PFK")

# Query methods
atp_reactions = model.reactions.query("atp")

Flux Constraints

Reaction bounds define feasible flux ranges:

  • Irreversible: lower_bound = 0, upper_bound > 0
  • Reversible: lower_bound < 0, upper_bound > 0
  • Set both bounds simultaneously with .bounds to avoid inconsistencies

Gene-Reaction Rules (GPR)

Boolean logic linking genes to reactions:

# AND logic (both required)
reaction.gene_reaction_rule = "gene1 and gene2"

# OR logic (either sufficient)
reaction.gene_reaction_rule = "gene1 or gene2"

# Complex logic
reaction.gene_reaction_rule = "(gene1 and gene2) or (gene3 and gene4)"

Exchange Reactions

Special reactions representing metabolite import/export:

  • Named with prefix EX_ by convention
  • Positive flux = secretion, negative flux = uptake
  • Managed through model.medium dictionary

Best Practices

  1. Use context managers for temporary modifications to avoid state management issues
  2. Validate models before analysis using model.slim_optimize() to ensure feasibility
  3. Check solution status after optimization - optimal indicates successful solve
  4. Use loopless FVA when thermodynamic feasibility matters
  5. Set fraction_of_optimum appropriately in FVA to explore suboptimal space
  6. Parallelize computationally expensive operations (sampling, double deletions) — start with small n and processes=1 on genome-scale models
  7. Prefer SBML format for model exchange and long-term storage
  8. Use slim_optimize() when only objective value needed for performance
  9. Validate flux samples to ensure numerical stability
  10. Confirm output paths before writing CSV/PNG files from workflow examples

Troubleshooting

Infeasible solutions: Check medium constraints, reaction bounds, and model consistency Slow optimization: Try different solvers (GLPK, CPLEX, Gurobi) via model.solver Unbounded solutions: Verify exchange reactions have appropriate upper bounds Import errors: Ensure correct file format and valid SBML identifiers

References

For detailed workflows and API patterns, refer to:

  • references/workflows.md - Comprehensive step-by-step workflow examples
  • references/api_quick_reference.md - Common function signatures and patterns

Official documentation: https://cobrapy.readthedocs.io/en/latest/

how to use cobrapy

How to use cobrapy on Cursor

AI-first code editor with Composer

1

Prerequisites

Before installing skills in Cursor, ensure your development environment meets these requirements:

  • Cursor installed and configured on your development machine
  • Node.js version 16.0+ with npm package manager (verify with node --version)
  • Active project directory or workspace where you want to add cobrapy
2

Execute installation command

Execute the skills CLI command in your project's root directory to begin installation:

$npx skills add https://github.com/K-Dense-AI/scientific-agent-skills --skill cobrapy

The skills CLI fetches cobrapy from GitHub repository K-Dense-AI/scientific-agent-skills and configures it for Cursor.

3

Select Cursor when prompted

The CLI will show a list of available agents. Use arrow keys to navigate and space to select Cursor:

◆ Which agents do you want to install to?
│ ── Universal (.agents/skills) ── always included ────
│ • Amp
│ • Antigravity
│ • Cline
│ • Codex
│ ●Cursor(selected)
│ • Cursor
│ • Windsurf
4

Verify installation

Confirm successful installation by checking the skill directory location:

.cursor/skills/cobrapy

Reload or restart Cursor to activate cobrapy. Access the skill through slash commands (e.g., /cobrapy) or your agent's skill management interface.

Security & Verification Notice

We perform automated surface-level scans (Gen AI Scanner, Socket, Snyk) during installation. These checks detect common vulnerabilities but do not guarantee complete security. Always review skill source code and verify the publisher's reputation before production use.

Skills execute code in your development environment. Always verify the publisher's identity, review recent commits, and test in isolated environments before production deployment.

List & Monetize Your Skill

Submit your Claude Code skill and start earning

GET_STARTED →

Use Cases

Task Automation & Efficiency

Automate repetitive workflows and reduce manual effort

Example

Generate reports, summarize documents, draft communications

Save 3-5 hours per week on routine tasks

Knowledge Enhancement

Learn new skills, understand complex topics, get expert guidance

Example

Explain concepts, provide examples, suggest learning resources

Accelerate learning and skill development by 2x

Quality Improvement

Enhance output quality through reviews, suggestions, and refinements

Example

Review drafts, suggest improvements, catch errors

Improve work quality by 30-40% with less effort

Implementation Guide

Prerequisites

  • Claude Desktop or compatible AI client with skill support
  • Clear understanding of task or problem to solve
  • Willingness to iterate and refine outputs

Time Estimate

15-45 minutes depending on use case complexity

Installation Steps

  1. 1.Install skill using provided installation command
  2. 2.Test with simple use case relevant to your work
  3. 3.Evaluate output quality and relevance
  4. 4.Iterate on prompts to improve results
  5. 5.Integrate into regular workflow if valuable

Common Pitfalls

  • Expecting perfect results without iteration
  • Not providing enough context in prompts
  • Using skill for tasks outside its intended scope
  • Accepting outputs without review and validation

Best Practices

✓ Do

  • +Start with clear, specific prompts
  • +Provide relevant context and constraints
  • +Review and refine all outputs before using
  • +Iterate to improve output quality
  • +Document successful prompt patterns

✗ Don't

  • Don't use without understanding skill limitations
  • Don't skip validation of outputs
  • Don't share sensitive information in prompts
  • Don't expect skill to replace human judgment

💡 Pro Tips

  • Be specific about desired format and style
  • Ask for multiple options to choose from
  • Request explanations to understand reasoning
  • Combine AI efficiency with human expertise

When to Use This

✓ Use When

Use when skill capabilities match your task, clear ROI on time saved, and you can validate outputs. Best for repetitive tasks, learning, and quality improvement.

✗ Avoid When

Avoid when task requires deep expertise you can't validate, involves sensitive decisions, or when learning process is more valuable than speed of completion.

Learning Path

  1. 1Familiarize yourself with skill capabilities and limitations
  2. 2Start with low-risk, non-critical tasks
  3. 3Progress to more complex and valuable use cases
  4. 4Build expertise through regular use and experimentation

Discussion

Product Hunt–style comments (not star reviews)
  • No comments yet — start the thread.
general reviews

Ratings

4.732 reviews
  • Kabir Thomas· Dec 28, 2024

    cobrapy reduced setup friction for our internal harness; good balance of opinion and flexibility.

  • Emma Chawla· Dec 24, 2024

    cobrapy has been reliable in day-to-day use. Documentation quality is above average for community skills.

  • Pratham Ware· Dec 16, 2024

    I recommend cobrapy for anyone iterating fast on agent tooling; clear intent and a small, reviewable surface area.

  • Diya Lopez· Nov 15, 2024

    cobrapy reduced setup friction for our internal harness; good balance of opinion and flexibility.

  • Sakshi Patil· Nov 7, 2024

    Useful defaults in cobrapy — fewer surprises than typical one-off scripts, and it plays nicely with `npx skills` flows.

  • Chaitanya Patil· Oct 26, 2024

    cobrapy has been reliable in day-to-day use. Documentation quality is above average for community skills.

  • Chinedu Okafor· Oct 6, 2024

    I recommend cobrapy for anyone iterating fast on agent tooling; clear intent and a small, reviewable surface area.

  • Kabir Mehta· Sep 25, 2024

    cobrapy has been reliable in day-to-day use. Documentation quality is above average for community skills.

  • Oshnikdeep· Sep 9, 2024

    Keeps context tight: cobrapy is the kind of skill you can hand to a new teammate without a long onboarding doc.

  • Piyush G· Sep 5, 2024

    Solid pick for teams standardizing on skills: cobrapy is focused, and the summary matches what you get after install.

showing 1-10 of 32

1 / 4