COBRApy

raw JSON →
0.31.1 verified Fri May 01 auth: no python

COBRApy (0.31.1) is a Python package for constraint-based modeling of metabolic networks. It enables building, simulating, and analyzing genome-scale metabolic models using flux balance analysis (FBA) and related methods. Releases occur several times a year, with a focus on stability and new features.

pip install cobra
error ModuleNotFoundError: No module named 'cobra'
cause cobra is not installed or virtual environment not activated.
fix
Run 'pip install cobra' in your terminal.
error ValueError: objective must be a scalar (reaction) or dict of reactions to coefficients
cause Setting model.objective = ['R1', 'R2'] incorrectly (list instead of dict or single reaction).
fix
Use model.objective = 'R1' for a single reaction or model.objective = {'R1': 1, 'R2': 0.5} for multiple.
error No solver interface found
cause optlang not installed and no solver (e.g., GLPK, CPLEX) available.
fix
Install optlang: 'pip install cobra[optlang]' or install a solver like GLPK.
breaking In cobra 0.31, the default solver interface changed to optlang. If you rely on the older glpk interface directly, your code may break.
fix Install cobra[optlang] and use optlang.glpk_interface (or other solver interfaces).
gotcha Setting model.objective = reaction_object does not automatically change the objective coefficient; you must set coefficient explicitly via model.objective = {reaction: 1} or reaction.objective_coefficient = 1.
fix Use model.objective = {reaction: 1} or reaction.objective_coefficient = 1 for a single reaction.
deprecated The method 'cobra.io.sbml.write_sbml' is deprecated; use 'cobra.io.write_sbml_model' instead.
fix Replace cobra.io.sbml.write_sbml with cobra.io.write_sbml_model.
gotcha Flux balance analysis results are stored in cobra.Solution which is not subscriptable; use solution.fluxes (pandas Series) to access individual fluxes.
fix Use solution.fluxes['REACTION_ID'] instead of solution['REACTION_ID'].
pip install cobra[optlang]

Create a simple model, add a reaction, set objective, and solve using FBA.

from cobra import Model, Reaction, Metabolite
model = Model('example')
# Add reaction: A -> B
reaction = Reaction('R1')
reaction.name = 'A to B'
reaction.subsystem = 'Exchange'
reaction.lower_bound = 0.  # irreversible
reaction.upper_bound = 1000.
metabolite_a = Metabolite('A_c', compartment='c')
metabolite_b = Metabolite('B_c', compartment='c')
reaction.add_metabolites({metabolite_a: -1, metabolite_b: 1})
model.add_reactions([reaction])
model.objective = 'R1'  # maximize flux through R1
solution = model.optimize()
print(solution.objective_value)