17.1. cobra

17.1.1. Subpackages

17.1.2. Submodules

17.1.3. Package Contents

17.1.3.1. Classes

Configuration

Define a global configuration object.

DictList

A combined dict and list

Gene

A Gene in a cobra model

Metabolite

Metabolite is a class for holding information regarding

Model

Class representation for a cobra model

Object

Defines common behavior of object in cobra.core

Reaction

Reaction is a class for holding information regarding

Solution

A unified interface to a cobra.Model optimization solution.

Species

Species is a class for holding information regarding

17.1.3.2. Functions

show_versions() → None

Print dependency information.

cobra.__author__ = The cobrapy core development team.[source]
cobra.__version__ = 0.21.0[source]
class cobra.Configuration(**kwargs)

Define a global configuration object.

The attributes of this singleton object are used as default values by cobra functions.

solver

The default solver for new models. The solver choices are the ones provided by optlang and depend on solvers installed in your environment.

Type

{“glpk”, “cplex”, “gurobi”, “glpk_exact”}

tolerance

The default tolerance for the solver being used (default 1E-07).

Type

float

lower_bound

The standard lower bound for reversible reactions (default -1000).

Type

float, optional

upper_bound

The standard upper bound for all reactions (default 1000).

Type

float, optional

bounds

The default reaction bounds for newly created reactions. The bounds are in the form of lower_bound, upper_bound (default -1000.0, 1000.0).

Type

tuple of floats

processes

A default number of processes to use where multiprocessing is possible. The default number corresponds to the number of available cores (hyperthreads) minus one.

Type

int

cache_directory

A path where the model cache should reside if caching is desired. The default directory depends on the operating system.

Type

pathlib.Path or str, optional

max_cache_size

The allowed maximum size of the model cache in bytes (default 1 GB).

Type

int, optional

cache_expiration

The expiration time in seconds for the model cache if any (default None).

Type

int, optional

_set_default_solver(self) → None

Set the default solver from a preferred order.

_set_default_processes(self) → None

Set the default number of processes.

_set_default_cache_directory(self) → None

Set the platform-dependent default cache directory.

property solver(self) → types.ModuleType

Return the optlang solver interface.

property bounds(self) → Tuple[Optional[Number], Optional[Number]]

Return the lower, upper reaction bound pair.

property cache_directory(self) → pathlib.Path

Return the model cache directory.

__repr__(self) → str

Return a string representation of the current configuration values.

_repr_html_(self) → str

Return a rich HTML representation of the current configuration values.

Notes

This special method is used automatically in Jupyter notebooks to display a result from a cell.

class cobra.DictList(*args)

Bases: list

A combined dict and list

This object behaves like a list, but has the O(1) speed benefits of a dict when looking up elements by their id.

has_id(self, id)
_check(self, id)

make sure duplicate id’s are not added. This function is called before adding in elements.

_generate_index(self)

rebuild the _dict index

get_by_id(self, id)

return the element with a matching id

list_attr(self, attribute)

return a list of the given attribute for every object

get_by_any(self, iterable)

Get a list of members using several different ways of indexing

Parameters

iterable (list (if not, turned into single element list)) – list where each element is either int (referring to an index in in this DictList), string (a id of a member in this DictList) or member of this DictList for pass-through

Returns

a list of members

Return type

list

query(self, search_function, attribute=None)

Query the list

Parameters
  • search_function (a string, regular expression or function) – Used to find the matching elements in the list. - a regular expression (possibly compiled), in which case the given attribute of the object should match the regular expression. - a function which takes one argument and returns True for desired values

  • attribute (string or None) – the name attribute of the object to passed as argument to the search_function. If this is None, the object itself is used.

Returns

a new list of objects which match the query

Return type

DictList

Examples

>>> import cobra.test
>>> model = cobra.test.create_test_model('textbook')
>>> model.reactions.query(lambda x: x.boundary)
>>> import re
>>> regex = re.compile('^g', flags=re.IGNORECASE)
>>> model.metabolites.query(regex, attribute='name')
_replace_on_id(self, new_object)

Replace an object by another with the same id.

append(self, object)

append object to end

union(self, iterable)

adds elements with id’s not already in the model

extend(self, iterable)

extend list by appending elements from the iterable

_extend_nocheck(self, iterable)

extends without checking for uniqueness

This function should only be used internally by DictList when it can guarantee elements are already unique (as in when coming from self or other DictList). It will be faster because it skips these checks.

__sub__(self, other)

x.__sub__(y) <==> x - y

Parameters

other (iterable) – other must contain only unique id’s present in the list

__isub__(self, other)

x.__sub__(y) <==> x -= y

Parameters

other (iterable) – other must contain only unique id’s present in the list

__add__(self, other)

x.__add__(y) <==> x + y

Parameters

other (iterable) – other must contain only unique id’s which do not intersect with self

__iadd__(self, other)

x.__iadd__(y) <==> x += y

Parameters

other (iterable) – other must contain only unique id’s whcih do not intersect with self

__reduce__(self)

Helper for pickle.

__getstate__(self)

gets internal state

This is only provided for backwards compatibility so older versions of cobrapy can load pickles generated with cobrapy. In reality, the “_dict” state is ignored when loading a pickle

__setstate__(self, state)

sets internal state

Ignore the passed in state and recalculate it. This is only for compatibility with older pickles which did not correctly specify the initialization class

index(self, id, *args)

Determine the position in the list

id: A string or a Object

__contains__(self, object)

DictList.__contains__(object) <==> object in DictList

object: str or Object

__copy__(self)
insert(self, index, object)

insert object before index

pop(self, *args)

remove and return item at index (default last).

add(self, x)

Opposite of remove. Mirrors set.add

remove(self, x)

Warning

Internal use only

reverse(self)

reverse IN PLACE

sort(self, cmp=None, key=None, reverse=False)

stable sort IN PLACE

cmp(x, y) -> -1, 0, 1

__getitem__(self, i)

x.__getitem__(y) <==> x[y]

__setitem__(self, i, y)

Set self[key] to value.

__delitem__(self, index)

Delete self[key].

__getslice__(self, i, j)
__setslice__(self, i, j, y)
__delslice__(self, i, j)
__getattr__(self, attr)
__dir__(self)

Default dir() implementation.

class cobra.Gene(id=None, name='', functional=True)

Bases: cobra.core.species.Species

A Gene in a cobra model

Parameters
  • id (string) – The identifier to associate the gene with

  • name (string) – A longer human readable name for the gene

  • functional (bool) – Indicates whether the gene is functional. If it is not functional then it cannot be used in an enzyme complex nor can its products be used.

property functional(self)

A flag indicating if the gene is functional.

Changing the flag is reverted upon exit if executed within the model as context.

knock_out(self)

Knockout gene by marking it as non-functional and setting all associated reactions bounds to zero.

The change is reverted upon exit if executed within the model as context.

remove_from_model(self, model=None, make_dependent_reactions_nonfunctional=True)

Removes the association

Parameters
  • model (cobra model) – The model to remove the gene from

  • make_dependent_reactions_nonfunctional (bool) – If True then replace the gene with ‘False’ in the gene association, else replace the gene with ‘True’

Deprecated since version 0.4: Use cobra.manipulation.delete_model_genes to simulate knockouts and cobra.manipulation.remove_genes to remove genes from the model.

_repr_html_(self)
class cobra.Metabolite(id=None, formula=None, name='', charge=None, compartment=None)

Bases: cobra.core.species.Species

Metabolite is a class for holding information regarding a metabolite in a cobra.Reaction object.

Parameters
  • id (str) – the identifier to associate with the metabolite

  • formula (str) – Chemical formula (e.g. H2O)

  • name (str) – A human readable name.

  • charge (float) – The charge number of the metabolite

  • compartment (str or None) – Compartment of the metabolite.

_set_id_with_model(self, value)
property constraint(self)

Get the constraints associated with this metabolite from the solve

Returns

the optlang constraint for this metabolite

Return type

optlang.<interface>.Constraint

property elements(self)

Dictionary of elements as keys and their count in the metabolite as integer. When set, the formula property is update accordingly

property formula_weight(self)

Calculate the formula weight

property y(self)

The shadow price for the metabolite in the most recent solution

Shadow prices are computed from the dual values of the bounds in the solution.

property shadow_price(self)

The shadow price in the most recent solution.

Shadow price is the dual value of the corresponding constraint in the model.

Warning

  • Accessing shadow prices through a Solution object is the safer, preferred, and only guaranteed to be correct way. You can see how to do so easily in the examples.

  • Shadow price is retrieved from the currently defined self._model.solver. The solver status is checked but there are no guarantees that the current solver state is the one you are looking for.

  • If you modify the underlying model after an optimization, you will retrieve the old optimization values.

Raises
  • RuntimeError – If the underlying model was never optimized beforehand or the metabolite is not part of a model.

  • OptimizationError – If the solver status is anything other than ‘optimal’.

Examples

>>> import cobra
>>> import cobra.test
>>> model = cobra.test.create_test_model("textbook")
>>> solution = model.optimize()
>>> model.metabolites.glc__D_e.shadow_price
-0.09166474637510488
>>> solution.shadow_prices.glc__D_e
-0.091664746375104883
remove_from_model(self, destructive=False)

Removes the association from self.model

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

Parameters

destructive (bool) – If False then the metabolite is removed from all associated reactions. If True then all associated reactions are removed from the Model.

summary(self, solution=None, fva=None)

Create a summary of the producing and consuming fluxes.

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.summary.MetaboliteSummary

_repr_html_(self)
class cobra.Model(id_or_model=None, name=None)

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)

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

__getstate__(self)

Get state for serialization.

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

property solver(self)

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)
property description(self)
get_metabolite_compartments(self)

Return all metabolites’ compartments.

property compartments(self)
property medium(self)
__add__(self, other_model)

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)

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)

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)

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)

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)

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)

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.

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)

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)

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)

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)

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)

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)

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)

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)

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)

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)

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)

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

property exchanges(self)

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)

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

property sinks(self)

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)

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

slim_optimize(self, error_value=float('nan'), message=None)

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)

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)

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)

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)

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)

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

__enter__(self)

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

__exit__(self, type, value, traceback)

Pop the top context manager and trigger the undo functions

merge(self, right, prefix_existing=None, inplace=True, objective='left')

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)
class cobra.Object(id=None, name='')

Bases: object

Defines common behavior of object in cobra.core

property id(self)
_set_id_with_model(self, value)
property annotation(self)
__getstate__(self)

To prevent excessive replication during deepcopy.

__repr__(self)

Return repr(self).

__str__(self)

Return str(self).

class cobra.Reaction(id=None, name='', subsystem='', lower_bound=0.0, upper_bound=None)

Bases: cobra.core.object.Object

Reaction is a class for holding information regarding a biochemical reaction in a cobra.Model object.

Reactions are by default irreversible with bounds (0.0, cobra.Configuration().upper_bound) if no bounds are provided on creation. To create an irreversible reaction use lower_bound=None, resulting in reaction bounds of (cobra.Configuration().lower_bound, cobra.Configuration().upper_bound).

Parameters
  • id (string) – The identifier to associate with this reaction

  • name (string) – A human readable name for the reaction

  • subsystem (string) – Subsystem where the reaction is meant to occur

  • lower_bound (float) – The lower flux bound

  • upper_bound (float) – The upper flux bound

__radd__
_set_id_with_model(self, value)
property reverse_id(self)

Generate the id of reverse_variable from the reaction’s id.

property flux_expression(self)

Forward flux expression

Returns

The expression representing the the forward flux (if associated with model), otherwise None. Representing the net flux if model.reversible_encoding == ‘unsplit’ or None if reaction is not associated with a model

Return type

sympy expression

property forward_variable(self)

An optlang variable representing the forward flux

Returns

An optlang variable for the forward flux or None if reaction is not associated with a model.

Return type

optlang.interface.Variable

property reverse_variable(self)

An optlang variable representing the reverse flux

Returns

An optlang variable for the reverse flux or None if reaction is not associated with a model.

Return type

optlang.interface.Variable

property objective_coefficient(self)

Get the coefficient for this reaction in a linear objective (float)

Assuming that the objective of the associated model is summation of fluxes from a set of reactions, the coefficient for each reaction can be obtained individually using this property. A more general way is to use the model.objective property directly.

__copy__(self)
__deepcopy__(self, memo)
static _check_bounds(lb, ub)
update_variable_bounds(self)
property lower_bound(self)

Get or set the lower bound

Setting the lower bound (float) will also adjust the associated optlang variables associated with the reaction. Infeasible combinations, such as a lower bound higher than the current upper bound will update the other bound.

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

property upper_bound(self)

Get or set the upper bound

Setting the upper bound (float) will also adjust the associated optlang variables associated with the reaction. Infeasible combinations, such as a upper bound lower than the current lower bound will update the other bound.

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

property bounds(self)

Get or set the bounds directly from a tuple

Convenience method for setting upper and lower bounds in one line using a tuple of lower and upper bound. Invalid bounds will raise an AssertionError.

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

property flux(self)

The flux value in the most recent solution.

Flux is the primal value of the corresponding variable in the model.

Warning

  • Accessing reaction fluxes through a Solution object is the safer, preferred, and only guaranteed to be correct way. You can see how to do so easily in the examples.

  • Reaction flux is retrieved from the currently defined self._model.solver. The solver status is checked but there are no guarantees that the current solver state is the one you are looking for.

  • If you modify the underlying model after an optimization, you will retrieve the old optimization values.

Raises
  • RuntimeError – If the underlying model was never optimized beforehand or the reaction is not part of a model.

  • OptimizationError – If the solver status is anything other than ‘optimal’.

  • AssertionError – If the flux value is not within the bounds.

Examples

>>> import cobra.test
>>> model = cobra.test.create_test_model("textbook")
>>> solution = model.optimize()
>>> model.reactions.PFK.flux
7.477381962160283
>>> solution.fluxes.PFK
7.4773819621602833
property reduced_cost(self)

The reduced cost in the most recent solution.

Reduced cost is the dual value of the corresponding variable in the model.

Warning

  • Accessing reduced costs through a Solution object is the safer, preferred, and only guaranteed to be correct way. You can see how to do so easily in the examples.

  • Reduced cost is retrieved from the currently defined self._model.solver. The solver status is checked but there are no guarantees that the current solver state is the one you are looking for.

  • If you modify the underlying model after an optimization, you will retrieve the old optimization values.

Raises
  • RuntimeError – If the underlying model was never optimized beforehand or the reaction is not part of a model.

  • OptimizationError – If the solver status is anything other than ‘optimal’.

Examples

>>> import cobra.test
>>> model = cobra.test.create_test_model("textbook")
>>> solution = model.optimize()
>>> model.reactions.PFK.reduced_cost
-8.673617379884035e-18
>>> solution.reduced_costs.PFK
-8.6736173798840355e-18
property metabolites(self)
property genes(self)
property gene_reaction_rule(self)
property gene_name_reaction_rule(self)

Display gene_reaction_rule with names intead.

Do NOT use this string for computation. It is intended to give a representation of the rule using more familiar gene names instead of the often cryptic ids.

property functional(self)

All required enzymes for reaction are functional.

Returns

True if the gene-protein-reaction (GPR) rule is fulfilled for this reaction, or if reaction is not associated to a model, otherwise False.

Return type

bool

property x(self)

The flux through the reaction in the most recent solution.

Flux values are computed from the primal values of the variables in the solution.

property y(self)

The reduced cost of the reaction in the most recent solution.

Reduced costs are computed from the dual values of the variables in the solution.

property reversibility(self)

Whether the reaction can proceed in both directions (reversible)

This is computed from the current upper and lower bounds.

property boundary(self)

Whether or not this reaction is an exchange reaction.

Returns True if the reaction has either no products or reactants.

property model(self)

returns the model the reaction is a part of

_update_awareness(self)

Make sure all metabolites and genes that are associated with this reaction are aware of it.

remove_from_model(self, remove_orphans=False)

Removes the reaction from a model.

This removes all associations between a reaction the associated model, metabolites and genes.

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

Parameters

remove_orphans (bool) – Remove orphaned genes and metabolites from the model as well

delete(self, remove_orphans=False)

Removes the reaction from a model.

This removes all associations between a reaction the associated model, metabolites and genes.

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

Deprecated, use reaction.remove_from_model instead.

Parameters

remove_orphans (bool) – Remove orphaned genes and metabolites from the model as well

__setstate__(self, state)

Probably not necessary to set _model as the cobra.Model that contains self sets the _model attribute for all metabolites and genes in the reaction.

However, to increase performance speed we do want to let the metabolite and gene know that they are employed in this reaction

copy(self)

Copy a reaction

The referenced metabolites and genes are also copied.

__add__(self, other)

Add two reactions

The stoichiometry will be the combined stoichiometry of the two reactions, and the gene reaction rule will be both rules combined by an and. All other attributes (i.e. reaction bounds) will match those of the first reaction

__iadd__(self, other)
__sub__(self, other)
__isub__(self, other)
__imul__(self, coefficient)

Scale coefficients in a reaction by a given value

E.g. A -> B becomes 2A -> 2B.

If coefficient is less than zero, the reaction is reversed and the bounds are swapped.

__mul__(self, coefficient)
property reactants(self)

Return a list of reactants for the reaction.

property products(self)

Return a list of products for the reaction

get_coefficient(self, metabolite_id)

Return the stoichiometric coefficient of a metabolite.

Parameters

metabolite_id (str or cobra.Metabolite) –

get_coefficients(self, metabolite_ids)

Return the stoichiometric coefficients for a list of metabolites.

Parameters

metabolite_ids (iterable) – Containing str or ``cobra.Metabolite``s.

add_metabolites(self, metabolites_to_add, combine=True, reversibly=True)

Add metabolites and stoichiometric coefficients to the reaction. If the final coefficient for a metabolite is 0 then it is removed from the reaction.

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

Parameters
  • metabolites_to_add (dict) – Dictionary with metabolite objects or metabolite identifiers as keys and coefficients as values. If keys are strings (name of a metabolite) the reaction must already be part of a model and a metabolite with the given name must exist in the model.

  • combine (bool) – Describes behavior a metabolite already exists in the reaction. True causes the coefficients to be added. False causes the coefficient to be replaced.

  • reversibly (bool) – Whether to add the change to the context to make the change reversibly or not (primarily intended for internal use).

subtract_metabolites(self, metabolites, combine=True, reversibly=True)

Subtract metabolites from a reaction.

That means add the metabolites with -1*coefficient. If the final coefficient for a metabolite is 0 then the metabolite is removed from the reaction.

Notes

  • A final coefficient < 0 implies a reactant.

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

Parameters
  • metabolites (dict) – Dictionary where the keys are of class Metabolite and the values are the coefficients. These metabolites will be added to the reaction.

  • combine (bool) – Describes behavior a metabolite already exists in the reaction. True causes the coefficients to be added. False causes the coefficient to be replaced.

  • reversibly (bool) – Whether to add the change to the context to make the change reversibly or not (primarily intended for internal use).

property reaction(self)

Human readable reaction string

build_reaction_string(self, use_metabolite_names=False)

Generate a human readable reaction string

check_mass_balance(self)

Compute mass and charge balance for the reaction

returns a dict of {element: amount} for unbalanced elements. “charge” is treated as an element in this dict This should be empty for balanced reactions.

property compartments(self)

lists compartments the metabolites are in

get_compartments(self)

lists compartments the metabolites are in

_associate_gene(self, cobra_gene)

Associates a cobra.Gene object with a cobra.Reaction.

Parameters

cobra_gene (cobra.core.Gene.Gene) –

_dissociate_gene(self, cobra_gene)

Dissociates a cobra.Gene object with a cobra.Reaction.

Parameters

cobra_gene (cobra.core.Gene.Gene) –

knock_out(self)

Knockout reaction by setting its bounds to zero.

build_reaction_from_string(self, reaction_str, verbose=True, fwd_arrow=None, rev_arrow=None, reversible_arrow=None, term_split='+')

Builds reaction from reaction equation reaction_str using parser

Takes a string and using the specifications supplied in the optional arguments infers a set of metabolites, metabolite compartments and stoichiometries for the reaction. It also infers the reversibility of the reaction from the reaction arrow.

Changes to the associated model are reverted upon exit when using the model as a context.

Parameters
  • reaction_str (string) – a string containing a reaction formula (equation)

  • verbose (bool) – setting verbosity of function

  • fwd_arrow (re.compile) – for forward irreversible reaction arrows

  • rev_arrow (re.compile) – for backward irreversible reaction arrows

  • reversible_arrow (re.compile) – for reversible reaction arrows

  • term_split (string) – dividing individual metabolite entries

summary(self, solution=None, fva=None)

Create a summary of the reaction flux.

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.summary.ReactionSummary

__str__(self)

Return str(self).

_repr_html_(self)
class cobra.Solution(objective_value, status, fluxes, reduced_costs=None, shadow_prices=None, **kwargs)

Bases: object

A unified interface to a cobra.Model optimization solution.

Notes

Solution is meant to be constructed by get_solution please look at that function to fully understand the Solution class.

objective_value

The (optimal) value for the objective function.

Type

float

status

The solver status related to the solution.

Type

str

fluxes

Contains the reaction fluxes (primal values of variables).

Type

pandas.Series

reduced_costs

Contains reaction reduced costs (dual values of variables).

Type

pandas.Series

shadow_prices

Contains metabolite shadow prices (dual values of constraints).

Type

pandas.Series

get_primal_by_id
__repr__(self)

String representation of the solution instance.

_repr_html_(self)
__getitem__(self, reaction_id)

Return the flux of a reaction.

Parameters

reaction (str) – A model reaction ID.

to_frame(self)

Return the fluxes and reduced costs as a data frame

class cobra.Species(id=None, name=None)

Bases: cobra.core.object.Object

Species is a class for holding information regarding a chemical Species

Parameters
  • id (string) – An identifier for the chemical species

  • name (string) – A human readable name.

property reactions(self)
__getstate__(self)

Remove the references to container reactions when serializing to avoid problems associated with recursion.

copy(self)

When copying a reaction, it is necessary to deepcopy the components so the list references aren’t carried over.

Additionally, a copy of a reaction is no longer in a cobra.Model.

This should be fixed with self.__deepcopy__ if possible

property model(self)
cobra.show_versions() → None

Print dependency information.