17.1.1.1.1.7. cobra.core.model

Define the Model class.

17.1.1.1.1.7.1. Module Contents

17.1.1.1.1.7.1.1. Classes

Model

Class representation for a cobra model

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

Bases: cobra.core.object.Object

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 an identifier to associate with the model as a string.

  • name (string) – Human readable name for the model

reactions

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

Type

DictList

metabolites

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

Type

DictList

genes

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

Type

DictList

groups

A DictList where the key is the group identifier and the value a Group

Type

DictList

solution

The last obtained solution from optimizing the model.

Type

Solution

__setstate__(self, state)[source]

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

__getstate__(self)[source]

Get state for serialization.

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

property solver(self)[source]

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)
>>> model.solver.add(new)
property tolerance(self)[source]
property description(self)[source]
get_metabolite_compartments(self)[source]

Return all metabolites’ compartments.

property compartments(self)[source]
property medium(self)[source]
__add__(self, 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__(self, 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(self)[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(self, 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(self, 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(self, reaction)[source]

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

Parameters
  • reaction (cobra.Reaction) – The reaction to add

  • (0.6) Use ~cobra.Model.add_reactions instead (Deprecated) –

add_boundary(self, metabolite, type='exchange', reaction_id=None, lb=None, ub=None, sbo_term=None)[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, unbalanced 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, i.e., a reversible reaction that adds or removes an intracellular metabolite.

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. This takes precedence over the auto-generated identifiers but beware that it might make boundary reactions harder to identify afterwards when using model.boundary or specifically model.exchanges etc.

  • lb (float, optional) – The lower bound of the resulting reaction.

  • ub (float, optional) – The upper bound of the resulting reaction.

  • sbo_term (str, optional) – A correct SBO term is set for the available types. If a custom type is chosen, a suitable SBO term should also be set.

Returns

The created boundary reaction.

Return type

cobra.Reaction

Examples

>>> import cobra.test
>>> model = cobra.test.create_test_model("textbook")
>>> demand = model.add_boundary(model.metabolites.atp_c, type="demand")
>>> demand.id
'DM_atp_c'
>>> demand.name
'ATP demand'
>>> demand.bounds
(0, 1000.0)
>>> demand.build_reaction_string()
'atp_c --> '
add_reactions(self, reaction_list)[source]

Add reactions to the model.

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(self, 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_groups(self, group_list)[source]

Add groups to the model.

Groups with identifiers identical to a group already in the model are ignored.

If any group contains members that are not in the model, these members are added to the model as well. Only metabolites, reactions, and genes can have groups.

Parameters

group_list (list) – A list of cobra.Group objects to add to the model.

remove_groups(self, group_list)[source]

Remove groups from the model.

Members of each group are not removed from the model (i.e. metabolites, reactions, and genes in the group stay in the model after any groups containing them are removed).

Parameters

group_list (list) – A list of cobra.Group objects to remove from the model.

get_associated_groups(self, element)[source]

Returns a list of groups that an element (reaction, metabolite, gene) is associated with.

Parameters

element (cobra.Reaction, cobra.Metabolite, or cobra.Gene) –

Returns

All groups that the provided object is a member of

Return type

list of cobra.Group

add_cons_vars(self, 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(self, 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.

property problem(self)[source]

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.

Return type

optlang.interface

property variables(self)[source]

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.

Return type

optlang.container.Container

property constraints(self)[source]

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.

Return type

optlang.container.Container

property boundary(self)[source]

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

property exchanges(self)[source]

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

property demands(self)[source]

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

property sinks(self)[source]

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

_populate_solver(self, reaction_list, metabolite_list=None)[source]

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

slim_optimize(self, error_value=float('nan'), 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.

Returns

The objective value.

Return type

float

optimize(self, 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(self, 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.

property objective(self)[source]

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.

property objective_direction(self)[source]

Get or set the objective direction.

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

summary(self, solution=None, fva=None)[source]

Create a summary of the exchange fluxes of the model.

Parameters
  • solution (cobra.Solution, optional) – A previous model solution to use for generating the summary. If None, the summary method will generate a parsimonious flux distribution (default None).

  • fva (pandas.DataFrame or float, 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 (default None).

Returns

Return type

cobra.ModelSummary

See also

Reaction.summary(), Metabolite.summary()

__enter__(self)[source]

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

__exit__(self, type, value, traceback)[source]

Pop the top context manager and trigger the undo functions

merge(self, 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.

rightcobra.Model

The model to add reactions from

prefix_existingstring

Prefix the reaction identifier in the right that already exist in the left model with this string.

inplacebool

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.

objectivestring

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_(self)[source]