# 15.1.1.1.1.5. cobra.core.model¶

## 15.1.1.1.1.5.1. Module Contents¶

class cobra.core.model.Model(id_or_model=None, name=None)[source]

Class representation for a cobra model

Parameters: id_or_model (Model, string) – Either an existing Model object in which case a new model object is instantiated with the same properties as the original model, or a the identifier to associate with the model as a string. name (string) – Human readable name for the model
reactions

DictList – A DictList where the key is the reaction identifier and the value a Reaction

metabolites

DictList – A DictList where the key is the metabolite identifier and the value a Metabolite

genes

DictList – A DictList where the key is the gene identifier and the value a Gene

solution

Solution – The last obtained solution from optimizing the model.

__setstate__(state)[source]

Make sure all cobra.Objects in the model point to the model.

__getstate__()[source]

Get state for serialization.

Ensures that the context stack is cleared prior to serialization, since partial functions cannot be pickled reliably.

__init__(id_or_model=None, name=None)[source]
solver()

Get or set the attached solver instance.

The associated the solver object, which manages the interaction with the associated solver, e.g. glpk.

This property is useful for accessing the optimization problem directly and to define additional non-metabolic constraints.

Examples

>>> import cobra.test
>>> model = cobra.test.create_test_model("textbook")
>>> new = model.problem.Constraint(model.objective.expression,
>>> lb=0.99)

solver(value)
description()
description(value)
get_metabolite_compartments()[source]

Return all metabolites’ compartments.

compartments()
compartments(value)

Get or set the dictionary of current compartment descriptions.

Assigning a dictionary to this property updates the model’s dictionary of compartment descriptions with the new values.

Parameters: value (dict) – Dictionary mapping compartments abbreviations to full names.

Examples

>>> import cobra.test
>>> model = cobra.test.create_test_model("textbook")
>>> model.compartments = {'c': 'the cytosol'}
{'c': 'the cytosol', 'e': 'extracellular'}

medium()
medium(medium)

Get or set the constraints on the model exchanges.

model.medium returns a dictionary of the bounds for each of the boundary reactions, in the form of {rxn_id: bound}, where bound specifies the absolute value of the bound in direction of metabolite creation (i.e., lower_bound for met <–, upper_bound for met –>)

Parameters: medium (dictionary-like) – The medium to initialize. medium should be a dictionary defining {rxn_id: bound} pairs.
__add__(other_model)[source]

Add the content of another model to this model (+).

The model is copied as a new object, with a new model identifier, and copies of all the reactions in the other model are added to this model. The objective is the sum of the objective expressions for the two models.

__iadd__(other_model)[source]

Incrementally add the content of another model to this model (+=).

Copies of all the reactions in the other model are added to this model. The objective is the sum of the objective expressions for the two models.

copy()[source]

Provides a partial ‘deepcopy’ of the Model. All of the Metabolite, Gene, and Reaction objects are created anew but in a faster fashion than deepcopy

add_metabolites(metabolite_list)[source]

Will add a list of metabolites to the model object and add new constraints accordingly.

The change is reverted upon exit when using the model as a context.

Parameters: metabolite_list (A list of cobra.core.Metabolite objects) –
remove_metabolites(metabolite_list, destructive=False)[source]

Remove a list of metabolites from the the object.

The change is reverted upon exit when using the model as a context.

Parameters: metabolite_list (list) – A list with cobra.Metabolite objects as elements. destructive (bool) – If False then the metabolite is removed from all associated reactions. If True then all associated reactions are removed from the Model.
add_reaction(reaction)[source]

Will add a cobra.Reaction object to the model, if reaction.id is not in self.reactions.

add_boundary(metabolite, type="exchange", reaction_id=None, lb=None, ub=1000.0)[source]

Add a boundary reaction for a given metabolite.

There are three different types of pre-defined boundary reactions: exchange, demand, and sink reactions. An exchange reaction is a reversible, imbalanced reaction that adds to or removes an extracellular metabolite from the extracellular compartment. A demand reaction is an irreversible reaction that consumes an intracellular metabolite. A sink is similar to an exchange but specifically for intracellular metabolites.

If you set the reaction type to something else, you must specify the desired identifier of the created reaction along with its upper and lower bound. The name will be given by the metabolite name and the given type.

Parameters: metabolite (cobra.Metabolite) – Any given metabolite. The compartment is not checked but you are encouraged to stick to the definition of exchanges and sinks. type (str, {"exchange", "demand", "sink"}) – Using one of the pre-defined reaction types is easiest. If you want to create your own kind of boundary reaction choose any other string, e.g., ‘my-boundary’. reaction_id (str, optional) – The ID of the resulting reaction. Only used for custom reactions. lb (float, optional) – The lower bound of the resulting reaction. Only used for custom reactions. ub (float, optional) – The upper bound of the resulting reaction. For the pre-defined reactions this default value determines all bounds. The created boundary reaction. cobra.Reaction

Examples

>>> import cobra.test
>>> model = cobra.test.create_test_model("textbook")
>>> demand.id
'DM_atp_c'
>>> demand.name
'ATP demand'
>>> demand.bounds
(0, 1000.0)
>>> demand.build_reaction_string()
'atp_c --> '

add_reactions(reaction_list)[source]

Reactions with identifiers identical to a reaction already in the model are ignored.

The change is reverted upon exit when using the model as a context.

Parameters: reaction_list (list) – A list of cobra.Reaction objects
remove_reactions(reactions, remove_orphans=False)[source]

Remove reactions from the model.

The change is reverted upon exit when using the model as a context.

Parameters: reactions (list) – A list with reactions (cobra.Reaction), or their id’s, to remove remove_orphans (bool) – Remove orphaned genes and metabolites from the model as well
add_cons_vars(what, **kwargs)[source]

Add constraints and variables to the model’s mathematical problem.

Useful for variables and constraints that can not be expressed with reactions and simple lower and upper bounds.

Additions are reversed upon exit if the model itself is used as context.

Parameters: what (list or tuple of optlang variables or constraints.) – The variables or constraints to add to the model. Must be of class optlang.interface.Variable or optlang.interface.Constraint. **kwargs (keyword arguments) – Passed to solver.add()
remove_cons_vars(what)[source]

Remove variables and constraints from the model’s mathematical problem.

Remove variables and constraints that were added directly to the model’s underlying mathematical problem. Removals are reversed upon exit if the model itself is used as context.

Parameters: what (list or tuple of optlang variables or constraints.) – The variables or constraints to add to the model. Must be of class optlang.interface.Variable or optlang.interface.Constraint.
problem()

The interface to the model’s underlying mathematical problem.

Solutions to cobra models are obtained by formulating a mathematical problem and solving it. Cobrapy uses the optlang package to accomplish that and with this property you can get access to the problem interface directly.

Returns: The problem interface that defines methods for interacting with the problem and associated solver directly. optlang.interface
variables()

The mathematical variables in the cobra model.

In a cobra model, most variables are reactions. However, for specific use cases, it may also be useful to have other types of variables. This property defines all variables currently associated with the model’s problem.

Returns: A container with all associated variables. optlang.container.Container
constraints()

The constraints in the cobra model.

In a cobra model, most constraints are metabolites and their stoichiometries. However, for specific use cases, it may also be useful to have other types of constraints. This property defines all constraints currently associated with the model’s problem.

Returns: A container with all associated constraints. optlang.container.Container
boundary()

Boundary reactions in the model. Reactions that either have no substrate or product.

exchanges()

Exchange reactions in model. Reactions that exchange mass with the exterior. Uses annotations and heuristics to exclude non-exchanges such as sink reactions.

demands()

Demand reactions in model. Irreversible reactions that accumulate or consume a metabolite in the inside of the model.

sinks()

Sink reactions in model. Reversible reactions that accumulate or consume a metabolite in the inside of the model.

_populate_solver(reaction_list, metabolite_list=None)[source]

Populate attached solver with constraints and variables that model the provided reactions.

slim_optimize(error_value=float, message=None)[source]

Optimize model without creating a solution object.

Creating a full solution object implies fetching shadow prices and flux values for all reactions and metabolites from the solver object. This necessarily takes some time and in cases where only one or two values are of interest, it is recommended to instead use this function which does not create a solution object returning only the value of the objective. Note however that the optimize() function uses efficient means to fetch values so if you need fluxes/shadow prices for more than say 4 reactions/metabolites, then the total speed increase of slim_optimize versus optimize is expected to be small or even negative depending on how you fetch the values after optimization.

Parameters: error_value (float, None) – The value to return if optimization failed due to e.g. infeasibility. If None, raise OptimizationError if the optimization fails. message (string) – Error message to use if the model optimization did not succeed. The objective value. float
optimize(objective_sense=None, raise_error=False)[source]

Optimize the model using flux balance analysis.

Parameters: objective_sense ({None, 'maximize' 'minimize'}, optional) – Whether fluxes should be maximized or minimized. In case of None, the previous direction is used. raise_error (bool) – If true, raise an OptimizationError if solver status is not optimal.

Notes

Only the most commonly used parameters are presented here. Additional parameters for cobra.solvers may be available and specified with the appropriate keyword argument.

repair(rebuild_index=True, rebuild_relationships=True)[source]

Update all indexes and pointers in a model

Parameters: rebuild_index (bool) – rebuild the indices kept in reactions, metabolites and genes rebuild_relationships (bool) – reset all associations between genes, metabolites, model and then re-add them.
objective()

Get or set the solver objective

Before introduction of the optlang based problems, this function returned the objective reactions as a list. With optlang, the objective is not limited a simple linear summation of individual reaction fluxes, making that return value ambiguous. Henceforth, use cobra.util.solver.linear_reaction_coefficients to get a dictionary of reactions with their linear coefficients (empty if there are none)

The set value can be dictionary (reactions as keys, linear coefficients as values), string (reaction identifier), int (reaction index), Reaction or problem.Objective or sympy expression directly interpreted as objectives.

When using a HistoryManager context, this attribute can be set temporarily, reversed when the exiting the context.

objective(value)
objective_direction()

Get or set the objective direction.

When using a HistoryManager context, this attribute can be set temporarily, reversed when exiting the context.

objective_direction(value)
summary(solution=None, threshold=1e-06, fva=None, names=False, floatfmt=".3g")[source]

Print a summary of the input and output fluxes of the model.

Parameters: solution (cobra.Solution, optional) – A previously solved model solution to use for generating the summary. If none provided (default), the summary method will resolve the model. Note that the solution object must match the model, i.e., changes to the model such as changed bounds, added or removed reactions are not taken into account by this method. threshold (float, optional) – Threshold below which fluxes are not reported. fva (pandas.DataFrame, float or None, optional) – Whether or not to include flux variability analysis in the output. If given, fva should either be a previous FVA solution matching the model or a float between 0 and 1 representing the fraction of the optimum objective to be searched. names (bool, optional) – Emit reaction and metabolite names rather than identifiers (default False). floatfmt (string, optional) – Format string for floats (default ‘.3g’).
__enter__()[source]

Record all future changes to the model, undoing them when a call to __exit__ is received

__exit__(type, value, traceback)[source]

Pop the top context manager and trigger the undo functions

merge(right, prefix_existing=None, inplace=True, objective="left")[source]

Merge two models to create a model with the reactions from both models.

Custom constraints and variables from right models are also copied to left model, however note that, constraints and variables are assumed to be the same if they have the same name.

right : cobra.Model
The model to add reactions from
prefix_existing : string
Prefix the reaction identifier in the right that already exist in the left model with this string.
inplace : bool
Add reactions from right directly to left model object. Otherwise, create a new model leaving the left model untouched. When done within the model as context, changes to the models are reverted upon exit.
objective : string
One of ‘left’, ‘right’ or ‘sum’ for setting the objective of the resulting model to that of the corresponding model or the sum of both.
_repr_html_()[source]