What Is COBRApy?
COBRApy is a free, open-source Python package for constraint-based reconstruction and analysis of metabolic networks. It provides bioprocess engineers with computational tools to predict growth rates, metabolic fluxes, gene essentiality, and theoretical maximum yields without running a single experiment. Published by Ebrahim et al. in 2013, COBRApy has accumulated over 1,280 citations and remains the most widely used Python library for flux balance analysis (FBA).
If you have ever asked "what happens if I knock out this gene?" or "what is the theoretical maximum yield of my product on glucose?", COBRApy can answer those questions in seconds. It works by loading a genome-scale metabolic model (GEM), a mathematical representation of every known metabolic reaction in an organism, and solving a linear program to find the optimal flux distribution through the network.
This COBRApy tutorial walks you through everything you need to go from zero to running FBA, gene knockouts, and flux variability analysis on the E. coli iML1515 model in under one hour. No prior experience with constraint-based modeling is required.
Installation and Setup
COBRApy installs from PyPI in a single command and requires no compilation or external solver configuration. The package bundles the GLPK linear programming solver through the optlang abstraction layer, so FBA works immediately after installation.
# Install COBRApy (includes GLPK solver) pip install cobra # Verify the installation import cobra print(cobra.__version__) # 0.31.1 as of July 2026
Python 3.8 or later is required. For genome-scale models with thousands of reactions, the bundled GLPK solver handles most analyses in under a second. If you need faster performance for large-scale knockout screening or sampling, install the Gurobi (free for academics) or CPLEX solver separately.
# Optional: install Gurobi for 5-10x faster LP solving pip install gurobipy # COBRApy auto-detects the fastest available solver import cobra model = cobra.io.load_model("textbook") print(model.solver.interface) # shows which solver is active
The entire installation takes under 60 seconds on a standard internet connection. No MATLAB license is needed, which is a significant advantage over the original COBRA Toolbox.
Loading Your First Genome-Scale Model
COBRApy loads curated genome-scale models directly from the BiGG Models database, which hosts over 100 quality-checked reconstructions covering bacteria, yeast, mammalian cells, and human metabolism. For this tutorial, start with the E. coli "textbook" core model (95 reactions) to learn the API, then graduate to iML1515 (2,719 reactions, 1,515 genes) for real analysis.
import cobra # Load the E. coli textbook model (95 reactions, cached locally) model = cobra.io.load_model("textbook") # Inspect the model print(f"Reactions: {len(model.reactions)}") # 95 print(f"Metabolites: {len(model.metabolites)}") # 72 print(f"Genes: {len(model.genes)}") # 137
To load the full genome-scale E. coli model for production strain design:
# Load iML1515 — the gold-standard E. coli GEM ecoli = cobra.io.load_model("iML1515") print(f"Reactions: {len(ecoli.reactions)}") # 2,719 print(f"Metabolites: {len(ecoli.metabolites)}") # 1,877 print(f"Genes: {len(ecoli.genes)}") # 1,515
| Organism | Model ID | Reactions | Metabolites | Genes | Use Case |
|---|---|---|---|---|---|
| E. coli K-12 | e_coli_core | 95 | 72 | 137 | Learning, quick tests |
| E. coli K-12 | iML1515 | 2,719 | 1,877 | 1,515 | Strain design, yield prediction |
| S. cerevisiae | iMM904 | 1,228 | 1,226 | 904 | Ethanol, organic acids |
| P. putida | iJN1463 | 2,927 | 1,757 | 1,463 | Aromatic compound degradation |
| B. subtilis | iYO844 | 1,020 | 988 | 844 | Enzyme production |
| Human | Recon3D | 13,543 | 4,140 | 3,288 | Disease modeling |
Every model object has three key collections: model.reactions, model.metabolites, and model.genes. Each reaction stores its stoichiometry, flux bounds, and gene-protein-reaction (GPR) associations. You can inspect any reaction by ID:
# Inspect the glucose exchange reaction rxn = model.reactions.get_by_id("EX_glc__D_e") print(rxn.reaction) # glc__D_e --> print(rxn.bounds) # (-10.0, 1000.0) — uptake rate up to 10 mmol/gDW/h
Running Flux Balance Analysis
FBA predicts the optimal distribution of metabolic fluxes by maximizing an objective function (typically biomass growth rate) subject to stoichiometric and capacity constraints. In COBRApy, running FBA takes a single function call.
# Run FBA on the textbook model model = cobra.io.load_model("textbook") solution = model.optimize() # Key results print(f"Growth rate: {solution.objective_value:.4f} h⁻¹") # 0.8739 print(f"Status: {solution.status}") # optimal # View the full solution summary model.summary()
The model.summary() method prints a formatted table showing uptake and secretion fluxes. Under the default glucose-limited aerobic conditions, the E. coli textbook model predicts a growth rate of 0.874 h-1 with glucose uptake of 10 mmol/gDW/h and oxygen uptake of 21.8 mmol/gDW/h. The main byproduct secretion is CO2 at 22.8 mmol/gDW/h.
Worked Example: Aerobic vs Anaerobic Growth
Compare E. coli growth under aerobic and anaerobic conditions:
import cobra model = cobra.io.load_model("textbook") # Aerobic: default O2 uptake is unconstrained aero = model.optimize() print(f"Aerobic growth: {aero.objective_value:.3f} h⁻¹") # 0.874 # Anaerobic: block O2 uptake model.reactions.get_by_id("EX_o2_e").lower_bound = 0 anaero = model.optimize() print(f"Anaerobic growth: {anaero.objective_value:.3f} h⁻¹") # 0.212 # Anaerobic secretion products for rxn in model.exchanges: flux = anaero.fluxes[rxn.id] if flux > 0.1: print(f" {rxn.id}: {flux:.2f}") # EX_ac_e: 8.06, EX_etoh_e: 8.28, EX_for_e: 16.34
The predicted anaerobic growth rate (0.212 h-1) is 76% lower than aerobic (0.874 h-1), with acetate, ethanol, and formate as mixed-acid fermentation products. These predictions match the known E. coli mixed-acid fermentation profile.
Access individual reaction fluxes from the solution object:
# Check flux through the TCA cycle print(solution.fluxes["CS"]) # Citrate synthase: ~6.0 mmol/gDW/h print(solution.fluxes["PFK"]) # Phosphofructokinase: ~7.5 mmol/gDW/h print(solution.fluxes["G6PDH2r"]) # Pentose phosphate entry: ~4.96
Gene Knockout Screening
COBRApy can systematically delete every gene in a model and predict the growth phenotype, identifying which genes are essential, growth-reducing, or dispensable. This in silico screen takes about 30 seconds for iML1515's 1,515 genes, compared to months of wet-lab work for a transposon library.
from cobra.flux_analysis import single_gene_deletion # Screen all genes (textbook model for speed) model = cobra.io.load_model("textbook") ko_results = single_gene_deletion(model) # Classify by growth phenotype wt_growth = model.optimize().objective_value essential = ko_results[ko_results["growth"] < 0.01] reduced = ko_results[(ko_results["growth"] >= 0.01) & (ko_results["growth"] < wt_growth * 0.95)] neutral = ko_results[ko_results["growth"] >= wt_growth * 0.95] print(f"Essential: {len(essential)}") # genes whose deletion is lethal print(f"Reduced: {len(reduced)}") print(f"Neutral: {len(neutral)}")
For production strain design, combine knockout screening with product secretion flux analysis. Delete genes that reduce growth minimally but redirect carbon toward your target metabolite:
from cobra.flux_analysis import single_gene_deletion model = cobra.io.load_model("textbook") # Track succinate production after each knockout ko_results = single_gene_deletion( model, processes=1 # single process for reproducibility ) # Find knockouts that increase succinate secretion for idx, row in ko_results.iterrows(): if row["growth"] > 0.01: gene_ids = list(idx)[0] if isinstance(idx, frozenset) else idx # Simulate the knockout and check succinate flux with model: gene = model.genes.get_by_id(gene_ids) gene.knock_out() sol = model.optimize() succ = sol.fluxes.get("EX_succ_e", 0) if succ > 1.0: print(f"{gene_ids}: growth={sol.objective_value:.3f}, succ={succ:.2f}")
Flux Variability Analysis
Flux variability analysis (FVA) determines the minimum and maximum flux each reaction can carry while maintaining at least a specified fraction of the optimal growth rate. Reactions with narrow flux ranges are tightly constrained by the network topology, while reactions with wide ranges are metabolically flexible and represent potential engineering targets.
from cobra.flux_analysis import flux_variability_analysis model = cobra.io.load_model("textbook") # FVA at 90% of optimal growth fva = flux_variability_analysis( model, fraction_of_optimum=0.9 ) # Show reactions with the widest flux ranges fva["range"] = fva["maximum"] - fva["minimum"] wide = fva.nlargest(10, "range") print(wide[["minimum", "maximum", "range"]])
Reactions with a flux range of zero at 90% optimality are essential for near-optimal growth and cannot be redirected without a growth penalty. Reactions with wide ranges (e.g., alternative NADH regeneration pathways) offer flexibility for metabolic engineering.
| Reaction | Full Name | Min Flux | Max Flux | Range | Interpretation |
|---|---|---|---|---|---|
| PFK | Phosphofructokinase | 6.3 | 7.5 | 1.2 | Tightly constrained |
| CS | Citrate synthase | 4.1 | 6.5 | 2.4 | Moderate flexibility |
| ICDHyr | Isocitrate dehydrogenase | 3.8 | 6.5 | 2.7 | TCA cycle branch point |
| G6PDH2r | Glucose-6-P dehydrogenase | 1.8 | 5.5 | 3.7 | PPP entry (flexible) |
| FRD7 | Fumarate reductase | 0.0 | 980.0 | 980.0 | Highly flexible (bypass) |
| SUCDi | Succinate dehydrogenase | 0.0 | 985.0 | 985.0 | Reversible with FRD7 |
Practical Bioprocess Applications
COBRApy is most valuable to bioprocess engineers when applied to three common questions: "What is my theoretical maximum yield?", "Which knockouts improve production?", and "What happens if I change the carbon source?" All three are answered in seconds without wet-lab resources.
Theoretical Maximum Yield
Calculate the stoichiometric maximum yield by maximizing product secretion while setting the growth rate to zero:
import cobra model = cobra.io.load_model("textbook") # Maximum ethanol yield on glucose (anaerobic) model.reactions.get_by_id("EX_o2_e").lower_bound = 0 model.objective = "EX_etoh_e" # maximize ethanol secretion sol = model.optimize() glc_uptake = -sol.fluxes["EX_glc__D_e"] eth_secretion = sol.fluxes["EX_etoh_e"] print(f"Max ethanol yield: {eth_secretion/glc_uptake:.2f} mol/mol glucose") # 2.00 mol/mol — matches the Gay-Lussac equation
The predicted maximum of 2.0 mol ethanol per mol glucose matches the theoretical stoichiometry (C6H12O6 → 2 C2H5OH + 2 CO2), or 0.511 g/g on a mass basis. Industrial S. cerevisiae achieves 90-95% of this theoretical maximum.
Carbon Source Comparison
Screen multiple carbon sources to identify the best substrate for your organism:
import cobra model = cobra.io.load_model("textbook") substrates = { "EX_glc__D_e": "Glucose", "EX_fru_e": "Fructose", "EX_ac_e": "Acetate", "EX_succ_e": "Succinate", } for rxn_id, name in substrates.items(): with model: # Block all carbon sources, then enable one for sid in substrates: model.reactions.get_by_id(sid).lower_bound = 0 model.reactions.get_by_id(rxn_id).lower_bound = -10 sol = model.optimize() print(f"{name:12s}: µ = {sol.objective_value:.3f} h⁻¹")
Using Context Managers for Reversible Changes
The with model: context manager is one of COBRApy's most practical features for bioprocess engineers. Any changes made inside the block (knockouts, bound changes, objective switches) are automatically reverted when the block exits. This means you can test hundreds of conditions in a loop without manually resetting the model each time.
Frequently Asked Questions
What is COBRApy and what can it do?
COBRApy is a free, open-source Python package for constraint-based metabolic modeling. It provides flux balance analysis (FBA), flux variability analysis (FVA), gene deletion screening, and parsimonious FBA. It loads genome-scale models from the BiGG database and can predict growth rates, metabolic fluxes, gene essentiality, and theoretical maximum yields for organisms including E. coli, S. cerevisiae, and CHO cells.
How do I install COBRApy?
Install COBRApy with pip install cobra. This installs the package along with the GLPK solver via the optlang abstraction layer. Python 3.8 or later is required. For faster performance on large models, install the Gurobi or CPLEX solver separately. The installation takes under one minute and no compilation is needed.
Which genome-scale model should I start with?
Start with the E. coli textbook model (e_coli_core, 95 reactions) to learn the API, then move to iML1515 (2,719 reactions, 1,515 genes) for real strain design. COBRApy can load models directly from the BiGG database with cobra.io.load_model(). BiGG hosts over 100 curated models covering E. coli, S. cerevisiae, P. putida, CHO cells, and human metabolism.
How accurate are COBRApy FBA predictions?
Under glucose-limited aerobic growth, FBA predictions of E. coli growth rate agree with experimental measurements within 5-10%. Lewis et al. (2010) showed that over 98% of active reactions in the optimal FBA solution are supported by transcriptomic data. Accuracy decreases under overflow metabolism, regulatory effects, or stress conditions not captured by stoichiometric constraints alone.
Can I use COBRApy for CHO cell or yeast modeling?
Yes. BiGG hosts curated models for S. cerevisiae (iMM904, 1,228 reactions) and a CHO-cell GEM (iCHO2441, 6,663 reactions) is available from the CHO consortium. Load any SBML model with cobra.io.read_sbml_model(). The same FBA, FVA, and gene deletion methods work regardless of organism, though model size affects computation time.
E. coli Expression Optimizer
Optimize your E. coli expression conditions. COBRApy identifies the gene targets; this calculator helps you execute with the right promoter, inducer, and temperature.
Fed-Batch Calculator
After predicting yield coefficients with FBA, design your fed-batch feeding strategy to match the optimal glucose uptake rate.
Related Tools
- Fermentation Economics Calculator — Estimate COGS from the yield predictions you generate with FBA
- OTR/kLa Estimator — Match your oxygen transfer rate to the OUR predicted by COBRApy off-gas analysis
- Media Estimator — Convert FBA-predicted uptake rates into practical media component concentrations
References
- Ebrahim A, Lerman JA, Palsson BO, Hyduke DR. COBRApy: COnstraints-Based Reconstruction and Analysis for Python. BMC Systems Biology. 2013;7:74. doi:10.1186/1752-0509-7-74
- Monk JM, Lloyd CJ, Brunk E, et al. iML1515, a knowledgebase that computes Escherichia coli traits. Nature Biotechnology. 2017;35(10):904-908. doi:10.1038/nbt.3956
- Orth JD, Thiele I, Palsson BO. What is flux balance analysis? Nature Biotechnology. 2010;28(3):245-248. doi:10.1038/nbt.1614
- Lewis NE, Nagarajan H, Palsson BO. Constraining the metabolic genotype-phenotype relationship using a phylogeny of in silico methods. Nature Reviews Microbiology. 2012;10(4):291-305. doi:10.1038/nrmicro2737
- Heirendt L, Arreckx S, Pfau T, et al. Creation and analysis of biochemical constraint-based models using the COBRA Toolbox v.3.0. Nature Protocols. 2019;14:639-702. doi:10.1038/s41596-018-0098-2