14.1.1. cobra.core package

14.1.1.1. Submodules

14.1.1.2. cobra.core.arraybasedmodel module

class cobra.core.arraybasedmodel.ArrayBasedModel(description=None, deepcopy_model=False, matrix_type='scipy.lil_matrix')[source]

Bases: cobra.core.model.Model

ArrayBasedModel is a class that adds arrays and vectors to a cobra.Model to make it easier to perform linear algebra operations.

S

Stoichiometric matrix of the model

This will be formatted as either lil_matrix or dok_matrix

add_metabolites(metabolite_list, expand_stoichiometric_matrix=True)[source]

Will add a list of metabolites to the the object, if they do not exist and then expand the stochiometric matrix

metabolite_list: A list of Metabolite objects

expand_stoichimetric_matrix: Boolean. If True and self.S is not None then it will add rows to self.S. self.S must be created after adding reactions and metabolites to self before it can be expanded. Trying to expand self.S when self only contains metabolites is ludacris.

add_reactions(reaction_list, update_matrices=True)[source]

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

reaction_list: A Reaction object or a list of them

update_matrices: Boolean. If true populate / update matrices S, lower_bounds, upper_bounds, .... Note this is slow to run for very large models and using this option with repeated calls will degrade performance. Better to call self.update() after adding all reactions.

If the stoichiometric matrix is initially empty then initialize a 1x1 sparse matrix and add more rows as needed in the self.add_metabolites function
b

bounds for metabolites as numpy.ndarray

constraint_sense
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

lower_bounds
objective_coefficients
remove_reactions(reactions, update_matrices=True, **kwargs)[source]

remove reactions from the model

See cobra.core.Model.Model.remove_reactions()

update_matrices: Boolean
If true populate / update matrices S, lower_bounds, upper_bounds. Note that this is slow to run for very large models, and using this option with repeated calls will degrade performance.
update()[source]

Regenerates the stoichiometric matrix and vectors

upper_bounds

14.1.1.3. cobra.core.dictlist module

class cobra.core.dictlist.DictList(*args)[source]

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.

Parameters:*args (iterable) – iterable as single argument to create new DictList from
add(x)[source]

Opposite of remove. Mirrors set.add

append(object)[source]

append object to end

extend(iterable)[source]

extend list by appending elements from the iterable

get_by_any(iterable)[source]

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
get_by_id(id)[source]

return the element with a matching id

has_id(id)[source]
index(id, *args)[source]

Determine the position in the list

id: A string or a Object

insert(index, object)[source]

insert object before index

list_attr(attribute)[source]

return a list of the given attribute for every object

pop(*args)[source]

remove and return item at index (default last).

query(search_function, attribute=None)[source]

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')
remove(x)[source]

Warning

Internal use only

reverse()[source]

reverse IN PLACE

sort(cmp=None, key=None, reverse=False)[source]

stable sort IN PLACE

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

union(iterable)[source]

adds elements with id’s not already in the model

14.1.1.4. cobra.core.formula module

class cobra.core.formula.Formula(formula=None)[source]

Bases: cobra.core.object.Object

Describes a Chemical Formula

Parameters:formula (string) – A legal formula string contains only letters and numbers.
parse_composition()[source]

Breaks the chemical formula down by element.

weight

Calculate the mol mass of the compound

Returns:the mol mass
Return type:float

14.1.1.5. cobra.core.gene module

class cobra.core.gene.GPRCleaner[source]

Bases: ast.NodeTransformer

Parses compiled ast of a gene_reaction_rule and identifies genes

Parts of the tree are rewritten to allow periods in gene ID’s and bitwise boolean operations

visit_BinOp(node)[source]
visit_Name(node)[source]
class cobra.core.gene.Gene(id=None, name='', functional=True)[source]

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.
functional

A flag indicating if the gene is functional.

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

knock_out()[source]

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(model=None, make_dependent_reactions_nonfunctional=True)[source]

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.

cobra.core.gene.ast2str(expr, level=0, names=None)[source]

convert compiled ast to gene_reaction_rule str

Parameters:
  • expr (str) – string for a gene reaction rule, e.g “a and b”
  • level (int) – internal use only
  • names (dict) – Dict where each element id a gene identifier and the value is the gene name. Use this to get a rule str which uses names instead. This should be done for display purposes only. All gene_reaction_rule strings which are computed with should use the id.
Returns:

The gene reaction rule

Return type:

string

cobra.core.gene.eval_gpr(expr, knockouts)[source]

evaluate compiled ast of gene_reaction_rule with knockouts

Parameters:
  • expr (Expression) – The ast of the gene reaction rule
  • knockouts (DictList, set) – Set of genes that are knocked out
Returns:

True if the gene reaction rule is true with the given knockouts otherwise false

Return type:

bool

cobra.core.gene.parse_gpr(str_expr)[source]

parse gpr into AST

Parameters:str_expr (string) – string with the gene reaction rule to parse
Returns:elements ast_tree and gene_ids as a set
Return type:tuple

14.1.1.6. cobra.core.metabolite module

class cobra.core.metabolite.Metabolite(id=None, formula=None, name='', charge=None, compartment=None)[source]

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.
constraint

Get the constraints associated with this metabolite from the solve

Returns:the optlang constraint for this metabolite
Return type:optlang.<interface>.Constraint
elements

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

formula_weight

Calculate the formula weight

remove_from_model(destructive=False)[source]

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.
shadow_price

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
summary(solution=None, threshold=0.01, fva=False, floatfmt='.3g')[source]

Print a summary of the reactions which produce and consume this metabolite.

This method requires the model for which this metabolite is a part to be solved.

Parameters:
  • solution (cobra.core.Solution) – 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) – a value below which to ignore reaction fluxes
  • fva (float (0->1), or None) – Whether or not to include flux variability analysis in the output. If given, fva should be a float between 0 and 1, representing the fraction of the optimum objective to be searched.
  • floatfmt (string) – format method for floats, passed to tabulate. Default is ‘.3g’.
y

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.

14.1.1.7. cobra.core.model module

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

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.
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_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()
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) –
add_reaction(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_reactions(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
compartments
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.
Return type:optlang.container.Container
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

description
exchanges

Exchange reactions in model.

Reactions that either don’t have products or substrates.

get_metabolite_compartments()[source]

Return all metabolites’ compartments.

medium
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.
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_direction

Get or set the objective direction.

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

optimize(objective_sense=None, raise_error=False, **kwargs)[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.
  • solver ({None, 'glpk', 'cglpk', 'gurobi', 'cplex'}, optional) – If unspecified will use the currently defined self.solver otherwise it will use the given solver and update the attribute.
  • quadratic_component ({None, scipy.sparse.dok_matrix}, optional) – The dimensions should be (n, n) where n is the number of reactions. This sets the quadratic component (Q) of the objective coefficient, adding \(\frac{1}{2} v^T \cdot Q \cdot v\) to the objective. Ignored for optlang based solvers.
  • tolerance_feasibility (float) – Solver tolerance for feasibility. Ignored for optlang based solvers
  • tolerance_markowitz (float) – Solver threshold during pivot. Ignored for optlang based solvers
  • time_limit (float) – Maximum solver time (in seconds). Ignored for optlang based solvers

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.

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.
Return type:optlang.interface
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.
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.
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
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.
slim_optimize(error_value=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

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)
>>> model.solver.add(new)
summary(solution=None, threshold=1e-08, fva=None, floatfmt='.3g')[source]

Print a summary of the input and output fluxes of the model. This method requires the model to have been previously solved.

Parameters:
  • solution (cobra.core.Solution) – 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) – tolerance for determining if a flux is zero (not printed)
  • fva (int or None) – Whether or not to calculate and report flux variability in the output summary
  • floatfmt (string) – format method for floats, passed to tabulate. Default is ‘.3g’.
to_array_based_model(deepcopy_model=False, **kwargs)[source]

Makes a cobra.core.ArrayBasedModel from a cobra.Model which may be used to perform linear algebra operations with the stoichiometric matrix.

Deprecated (0.6). Use cobra.util.array.create_stoichiometric_matrix instead.

Parameters:deepcopy_model (bool) – If False then the ArrayBasedModel points to the Model
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.
Return type:optlang.container.Container

14.1.1.8. cobra.core.object module

class cobra.core.object.Object(id=None, name='')[source]

Bases: object

Defines common behavior of object in cobra.core

id

14.1.1.9. cobra.core.reaction module

class cobra.core.reaction.Reaction(id=None, name='', subsystem='', lower_bound=0.0, upper_bound=1000.0, objective_coefficient=0.0)[source]

Bases: cobra.core.object.Object

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

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
add_metabolites(metabolites_to_add, combine=True, reversibly=True)[source]

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).
boundary

Whether or not this reaction is an exchange reaction.

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

bounds

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.

build_reaction_from_string(reaction_str, verbose=True, fwd_arrow=None, rev_arrow=None, reversible_arrow=None, term_split='+')[source]

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
build_reaction_string(use_metabolite_names=False)[source]

Generate a human readable reaction string

check_mass_balance()[source]

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.

compartments

lists compartments the metabolites are in

copy()[source]

Copy a reaction

The referenced metabolites and genes are also copied.

delete(remove_orphans=False)[source]

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
flux

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
flux_expression

Forward flux expression

Returns:The expression represeenting 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
forward_variable

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
functional

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
gene_name_reaction_rule

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.

gene_reaction_rule
genes
get_coefficient(metabolite_id)[source]

Return the stoichiometric coefficient of a metabolite.

Parameters:metabolite_id (str or cobra.Metabolite) –
get_coefficients(metabolite_ids)[source]

Return the stoichiometric coefficients for a list of metabolites in the reaction.

Parameters:metabolite_ids (iterable) – Containing str or ``cobra.Metabolite``s.
get_compartments()[source]

lists compartments the metabolites are in

knock_out()[source]

Knockout reaction by setting its bounds to zero.

lower_bound

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.

metabolites
model

returns the model the reaction is a part of

objective_coefficient

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.

products

Return a list of products for the reaction

reactants

Return a list of reactants for the reaction.

reaction

Human readable reaction string

reduced_cost

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
remove_from_model(remove_orphans=False)[source]

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
reverse_id

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

reverse_variable

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
reversibility

Whether the reaction can proceed in both directions (reversible)

This is computed from the current upper and lower bounds.

subtract_metabolites(metabolites, combine=True, reversibly=True)[source]

This function will ‘subtract’ metabolites from a reaction, which means add the metabolites with -1*coefficient. If the final coefficient for a metabolite is 0 then the metabolite is removed from the reaction.

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).

:param .. note:: A final coefficient < 0 implies a reactant.:

upper_bound

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.

x

The flux through the reaction in the most recent solution.

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

y

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.

cobra.core.reaction.separate_forward_and_reverse_bounds(lower_bound, upper_bound)[source]

Split a given (lower_bound, upper_bound) interval into a negative component and a positive component. Negative components are negated (returns positive ranges) and flipped for usage with forward and reverse reactions bounds

Parameters:
  • lower_bound (float) – The lower flux bound
  • upper_bound (float) – The upper flux bound
cobra.core.reaction.update_forward_and_reverse_bounds(reaction, direction='both')[source]

For the given reaction, update the bounds in the forward and reverse variable bounds.

Parameters:
  • reaction (cobra.Reaction) – The reaction to operate on
  • direction (string) – Either ‘both’, ‘upper’ or ‘lower’ for updating the corresponding flux bounds.

14.1.1.10. cobra.core.solution module

Provide unified interfaces to optimization solutions.

class cobra.core.solution.Solution(objective_value, status, fluxes, reduced_costs=None, shadow_prices=None, **kwargs)[source]

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

float – The (optimal) value for the objective function.

status

str – The solver status related to the solution.

fluxes

pandas.Series – Contains the reaction fluxes (primal values of variables).

reduced_costs

pandas.Series – Contains reaction reduced costs (dual values of variables).

shadow_prices

pandas.Series – Contains metabolite shadow prices (dual values of constraints).

Deprecated Attributes
---------------------
f

float – Use objective_value instead.

x

list – Use fluxes.values instead.

x_dict

pandas.Series – Use fluxes instead.

y

list – Use reduced_costs.values instead.

y_dict

pandas.Series – Use reduced_costs instead.

f

Deprecated property for getting the objective value.

get_primal_by_id(reaction_id)

Return the flux of a reaction.

Parameters:reaction (str) – A model reaction ID.
to_frame()[source]

Return the fluxes and reduced costs as a data frame

x

Deprecated property for getting flux values.

x_dict

Deprecated property for getting fluxes.

y

Deprecated property for getting reduced cost values.

y_dict

Deprecated property for getting reduced costs.

class cobra.core.solution.LegacySolution(f, x=None, x_dict=None, y=None, y_dict=None, solver=None, the_time=0, status='NA', **kwargs)[source]

Bases: object

Legacy support for an interface to a cobra.Model optimization solution.

f

float – The objective value

solver

str – A string indicating which solver package was used.

x

iterable – List or Array of the fluxes (primal values).

x_dict

dict – A dictionary of reaction IDs that maps to the respective primal values.

y

iterable – List or Array of the dual values.

y_dict

dict – A dictionary of reaction IDs that maps to the respective dual values.

Warning

The LegacySolution class and its interface is deprecated.

dress_results(model)[source]

Method could be intended as a decorator.

Warning

deprecated

cobra.core.solution.get_solution(model, reactions=None, metabolites=None, raise_error=False)[source]

Generate a solution representation of the current solver state.

Parameters:
  • model (cobra.Model) – The model whose reactions to retrieve values for.
  • reactions (list, optional) – An iterable of cobra.Reaction objects. Uses model.reactions by default.
  • metabolites (list, optional) – An iterable of cobra.Metabolite objects. Uses model.metabolites by default.
  • raise_error (bool) – If true, raise an OptimizationError if solver status is not optimal.
Returns:

Return type:

cobra.Solution

Note

This is only intended for the optlang solver interfaces and not the legacy solvers.

14.1.1.11. cobra.core.species module

class cobra.core.species.Species(id=None, name=None)[source]

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.
copy()[source]

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

model
reactions

14.1.1.12. Module contents