# 14.1.1. cobra.core package¶

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

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.

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

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.

other: iterable
other must contain only unique id’s which do not intersect with self
__contains__(object)[source]

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

object: str or Object

__getstate__()[source]

gets internal state

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

other: iterable
other must contain only unique id’s whcih do not intersect with self
__setstate__(state)[source]

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

append(object)[source]

append object to end

extend(iterable)[source]

extend list by appending elements from the iterable

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='id')[source]

query the list

search_function: used to select which objects to return
• a string, in which case any object.attribute containing the string will be returned
• a compiled regular expression
• a function which takes one argument and returns True for desired values
attribute: the attribute to be searched for (default is ‘id’).
If this is None, the object itself is used.

returns: a list of objects which match the query

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]

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

A legal formula string contains only letters and numbers.

Combine two molecular formulas.

other_formula: cobra.Formula or str of a chemical Formula.

parse_composition()[source]

Breaks the chemical formula down by element.

weight

Calculate the formula weight

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

Removes the association

make_dependent_reactions_nonfunctional: Boolean. 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

expr: str of a gene reaction rule

level: internal use only

names: optional dict of {Gene.id: 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.
cobra.core.Gene.eval_gpr(expr, knockouts)[source]

evaluate compiled ast of gene_reaction_rule with knockouts

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

parse gpr into AST

returns: (ast_tree, {gene_ids})

## 14.1.1.6. cobra.core.Metabolite module¶

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

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

elements
formula_weight

Calculate the formula weight

remove_from_model(method='subtractive', **kwargs)[source]

Removes the association from self.model

method: ‘subtractive’ or ‘destructive’.
If ‘subtractive’ then the metabolite is removed from all associated reactions. If ‘destructive’ then all associated reactions are removed from the Model.
summary(**kwargs)[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.

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

Metabolic Model

Refers to Metabolite, Reaction, and Gene Objects.

The issue of reactions being able to exists in multiple Models now arises, the same for metabolites and such. This might be a little difficult as a reaction with the same name / id in two models might have different coefficients for their metabolites due to pH and whatnot making them different reactions.

Adds a Model to this model +=

The issue of reactions being able to exists in multiple Models now arises, the same for metabolites and such. This might be a little difficult as a reaction with the same name / id in two models might have different coefficients for their metabolites due to pH and whatnot making them different reactions.

__setstate__(state)[source]

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

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

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

reaction: A Reaction object

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

reaction_list: A list of Reaction objects

change_objective(objectives)[source]

Change the model objective

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
objective
optimize(objective_sense='maximize', **kwargs)[source]

Optimize model using flux balance analysis

objective_sense: ‘maximize’ or ‘minimize’

solver: ‘glpk’, ‘cglpk’, ‘gurobi’, ‘cplex’ or None

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.

tolerance_feasibility: Solver tolerance for feasibility.

tolerance_markowitz: Solver threshold during pivot

time_limit: Maximum solver time (in seconds)

Note

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

remove_reactions(reactions, delete=True, remove_orphans=False)[source]

remove reactions from the model

reactions: [Reaction] or [str]
The reactions (or their id’s) to remove
delete: Boolean
Whether or not the reactions should be deleted after removal. If the reactions are not deleted, those objects will be recreated with new metabolite and gene objects.
remove_orphans: Boolean
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

summary(**kwargs)[source]

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

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 ArrayBasedModel from a cobra.Model which may be used to perform linear algebra operations with the stoichiomatric matrix.

deepcopy_model: Boolean. If False then the ArrayBasedModel points to the Model

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

__getstate__()[source]

To prevent excessive replication during deepcopy.

## 14.1.1.9. cobra.core.Reaction module¶

class cobra.core.Reaction.Frozendict[source]

Bases: dict

pop(key, value)[source]
popitem()[source]
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

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

__imul__(coefficient)[source]

Scale coefficients in a reaction

__setstate__(state)[source]

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

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

metabolites: dict
{str or Metabolite: coefficient}
combine: Boolean.
Describes behavior a metabolite already exists in the reaction. True causes the coefficients to be added. False causes the coefficient to be replaced. True and a metabolite already exists in the
Add the metabolite to the Model the reaction is associated with (i.e. self.model)
boundary
bounds

A more convienient bounds structure than seperate upper and lower bounds

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.

Parameters: reaction_str – a string containing a reaction formula (equation) verbose – Boolean setting verbosity of function (optional, default=True) fwd_arrow – re.compile for forward irreversible reaction arrows (optional, default=_forward_arrow_finder) reverse_arrow – re.compile for backward irreversible reaction arrows (optional, default=_reverse_arrow_finder) fwd_arrow – re.compile for reversible reaction arrows (optional, default=_reversible_arrow_finder) term_split – String dividing individual metabolite entries (optional, default=’+’)
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.

clear_metabolites()[source]

Remove all metabolites from the reaction

copy()[source]

Copy a reaction

The referenced metabolites and genes are also copied.

delete(remove_orphans=False)[source]

Completely delete a reaction

This removes all associations between a reaction the associated model, metabolites and genes (unlike remove_from_model which only dissociates the reaction from the model).

remove_orphans: Boolean
Remove orphaned genes and metabolites from the model as well
gene_name_reaction_rule

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 for a metabolite in the reaction.

metabolite_id: str or Metabolite

get_coefficients(metabolite_ids)[source]

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

metabolite_ids: iterable
Containing str or Metabolite
get_compartments()[source]

lists compartments the metabolites are in

knock_out()[source]

Change the upper and lower bounds of the reaction to 0.

metabolites
model

returns the model the reaction is a part of

pop(metabolite_id)[source]

Remove a metabolite from the reaction and return the stoichiometric coefficient.

metabolite_id: str or Metabolite

products

Return a list of products for the reaction

reactants

Return a list of reactants for the reaction.

reaction

remove_from_model(model=None, remove_orphans=False)[source]

Removes the reaction from the model while keeping it intact

remove_orphans: Boolean
Remove orphaned genes and metabolites from the model as well

model: deprecated argument, must be None

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

metabolites: dict of {Metabolite: coefficient}
These metabolites will be added to the reaction

Note

A final coefficient < 0 implies a reactant.

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.

## 14.1.1.10. cobra.core.Solution module¶

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

Bases: object

Stores the solution from optimizing a cobra.Model. This is used to provide a single interface to results from different solvers that store their values in different ways.

f: The objective value

solver: A string indicating which solver package was used.

x: List or Array of the values from the primal.

x_dict: A dictionary of reaction ids that maps to the primal values.

y: List or Array of the values from the dual.

y_dict: A dictionary of reaction ids that maps to the dual values.

dress_results(model)[source]

Warning

deprecated

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

__getstate__()[source]

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

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.__deecopy__ if possible

model
reactions