# 17.1.1.1. cobra.core¶

## 17.1.1.1.2. Package Contents¶

### 17.1.1.1.2.1. Classes¶

 Configuration Define a global configuration object. DictList A combined dict and list. Gene A Gene in a cobra model. GPR A Gene Reaction rule in a cobra model, using AST as base class. Metabolite Class for information about metabolite in cobra.Reaction. Model Class representation for a cobra model Object Defines common behavior of object in cobra.core. Reaction Define the cobra.Reaction class. Group Manage groups via this implementation of the SBML group specification. Solution A unified interface to a cobra.Model optimization solution. LegacySolution Legacy support for an interface to a cobra.Model optimization solution. Species Species is a base class in Cobrapy.

### 17.1.1.1.2.2. Functions¶

 get_solution(model, reactions=None, metabolites=None, raise_error=False) Generate a solution representation of the current solver state.
class cobra.core.Configuration(**kwargs)[source]

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

has_id(self, id: Union[Object, str]) → bool

Check if id is in DictList.

_check(self, id: Union[Object, str]) → None

Make sure duplicate id’s are not added.

This function is called before adding in elements.

_generate_index(self) → None

Rebuild the _dict index.

get_by_id(self, id: Union[Object, str]) → Object

Return the element with a matching id.

list_attr(self, attribute: str) → list

Return a list of the given attribute for every object.

get_by_any(self, iterable: List[Union[str, Object, int]]) → list

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: Union[str, Pattern, Callable], attribute: Union[str, None] = None) → 'DictList'

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

>>> 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: Object) → None

Replace an object by another with the same id.

append(self, entity: Object) → None

Append object to end.

union(self, iterable: Iterable[Object]) → None

extend(self, iterable: Iterable[Object]) → None

Extend list by appending elements from the iterable.

Sometimes during initialization from an older pickle, _dict will not have initialized yet, because the initialization class was left unspecified. This is an issue because unpickling calls DictList.extend, which requires the presence of _dict. Therefore, the issue is caught and addressed here.

Parameters

iterable (Iterable) –

_extend_nocheck(self, iterable: Iterable[Object]) → None

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

Parameters

iterable (Iterable) –

__sub__(self, other: Iterable[Object]) → 'DictList'

Remove a value or values, and returns the new DictList.

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

Parameters

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

Returns

total – new DictList with item(s) removed

Return type

DictList

__isub__(self, other: Iterable[Object]) → 'DictList'

Remove a value or values in place.

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

Parameters

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

Add item while returning a new DictList.

Parameters

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

Add item while returning the same DictList.

Parameters

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

__reduce__(self) → Tuple[Type['DictList'], Tuple, dict, Iterator]

Return a reduced version of DictList.

This reduced version details the class, an empty Tuple, a dictionary of the state and an iterator to go over the DictList.

__getstate__(self) → dict

Get 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: dict) → None

Pretend to set internal state. Actually recalculates.

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: Union[str, Object], *args) → int

Determine the position in the list.

Parameters

id (A string or a Object) –

__contains__(self, entity: Union[str, Object]) → bool

Ask if the DictList contain an entity.

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

Parameters

entity (str or Object) –

__copy__(self) → 'DictList'

Copy the DictList into a new one.

insert(self, index: int, entity: Object) → None

Insert entity before index.

pop(self, *args) → Object

Remove and return item at index (default last).

remove(self, x: Union[str, Object]) → None

Warning

Internal use only.

Each item is unique in the list which allows this It is much faster to do a dict lookup than n string comparisons

reverse(self) → None

Reverse IN PLACE.

sort(self, cmp: Callable = None, key: Callable = None, reverse: bool = False) → None

Stable sort IN PLACE.

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

__getitem__(self, i: Union[int, slice, Iterable, Object, 'DictList']) → Union['DictList', Object]

Get item from DictList.

__setitem__(self, i: Union[slice, int], y: Union[list, Object]) → None

Set an item via index or slice.

Parameters
• i (slice, int) – i can be slice or int. If i is a slice, y needs to be a list

• y (list, Object) – Object to set as

__delitem__(self, index: int) → None

Remove item from DictList.

__getslice__(self, i: int, j: int) → 'DictList'

Get a slice from it to j of DictList.

__setslice__(self, i: int, j: int, y: Union[list, Object]) → None

Set slice, where y is an iterable.

__delslice__(self, i: int, j: int) → None

Remove slice.

__getattr__(self, attr: Any) → Any

Get an attribute by id.

__dir__(self) → list

Directory of the DictList.

Override this to allow tab complete of items by their id.

Returns

attributes – A list of attributes/entities.

Return type

list

class cobra.core.Gene(id: str = None, name: str = '', functional: bool = True)[source]

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) → bool

Flag indicating if the gene is functional.

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

knock_out(self) → None

Knockout gene by marking it as non-functional.

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.

_repr_html_(self)
class cobra.core.GPR(gpr_from: Union[Expression, Module, AST] = None, **kwargs)[source]

Bases: ast.Module

A Gene Reaction rule in a cobra model, using AST as base class.

Parameters

gpr_from (Expression or Module or AST) – A GPR in AST format

classmethod from_string(cls, string_gpr: str) → 'GPR'

Construct a GPR from a string.

Parameters

string_gpr (str) – a string that describes the gene rules, in a format like A & B

Returns

returns a new GPR while setting self.body as Parsed AST tree that has the gene rules This function also sets self._genes with the gene ids in the AST

Return type

GPR

property genes(self) → FrozenSet

To check the genes.

This property updates the genes before returning them, in case the GPR was changed and the genes weren’t.

Returns

genes – All the genes in a frozen set. Do not try to change them with this property.

Return type

frozenset

update_genes(self) → None

Update genes, used after changes in GPR.

Walks along the AST tree of the GPR class, and modifies self._genes

_eval_gpr(self, expr: Union[Expression, list, BoolOp, Name], knockouts: Union[DictList, set]) → bool

Evaluate compiled ast of gene_reaction_rule with knockouts.

Parameters
• expr (Expression or GPR or list or BoolOp or Name) – 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

eval(self, knockouts: Union[DictList, Set, str, Iterable] = None) → bool

Evaluate compiled ast of gene_reaction_rule with knockouts.

This function calls _eval_gpr, but allows more flexibility in input, including name, and list.

Parameters

knockouts – Which gene or genes to knoc out

Returns

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

Return type

bool

_ast2str(self, expr: Union['GPR', Expression, BoolOp, Name, list], level: int = 0, names: dict = None) → str

Convert compiled ast to gene_reaction_rule str.

Parameters
• expr (AST or GPR or list or Name or BoolOp) – 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

to_string(self, names: dict = None) → str

Convert compiled ast to gene_reaction_rule str.

Parameters
• self (GPR) – compiled ast Module describing GPR

• names (dict) – dictionary of gene ids to gene names. If this is empty, returns gene ids

Returns

The gene reaction rule

Return type

string

Notes

Calls _aststr()

copy(self)

Copy a GPR.

__copy__(self) → 'GPR'

Ensure a correct shallow copy.

__repr__(self) → str

Return the GPR with module, class, and code to recreate it.

__str__(self) → str

Convert compiled ast to gene_reaction_rule str.

Parameters

self (GPR) – compiled ast Module describing GPR

Returns

The gene reaction rule

Return type

string

_repr_html_(self) → str
as_symbolic(self, names: dict = None) → Union[spl.Or, spl.And, Symbol]

Convert compiled ast to sympy expression.

Parameters
• self (GPR) – compiled ast Module describing GPR

• names (dict) – dictionary of gene ids to gene names. If this is empty, returns sympy expression using gene ids

Returns

SYMPY expression (Symbol or And or Or). Symbol(“”) if the GPR is empty

Return type

Symbol or BooleanFunction

Notes

Calls _symbolic_gpr()

_symbolic_gpr(self, expr: Union['GPR', Expression, BoolOp, Name, list] = None, GPRGene_dict: dict = None) → Union[spl.Or, spl.And, Symbol]

Parse gpr into SYMPY using ast similar to _ast2str().

Parameters
• expr (AST or GPR or list or Name or BoolOp) – compiled GPR

• GPRGene_dict (dict) – dictionary from gene id to GPRGeneSymbol

Returns

SYMPY expression (Symbol or And or Or). Symbol(“”) if the GPR is empty

Return type

Symbol or BooleanFunction

classmethod from_symbolic(cls, sympy_gpr: Union[spl.BooleanFunction, Symbol]) → 'GPR'

Construct a GPR from a sympy expression.

Parameters

sympy_gpr (sympy) – a sympy that describes the gene rules, being a Symbol for single genes or a BooleanFunction for AND/OR relationships

Returns

returns a new GPR while setting self.body as Parsed AST tree that has the gene rules This function also sets self._genes with the gene ids in the AST

Return type

GPR

__eq__(self, other) → bool

Check equality of GPR via symbolic equality.

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

Class for information about metabolite in cobra.Reaction.

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: str) → None

Set id with value.

Parameters

value (str) –

property constraint(self) → 'Container'

Get the constraints associated with this metabolite from the solver.

Returns

the optlang constraint for this metabolite

Return type

optlang.<interface>.Containter

property elements(self) → Optional[Dict[str, Union[int, float]]]

Get dicitonary of elements and counts.

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

Returns

composition – A dictionary of elements and counts, where count is int unless it is needed to be a float. Returns None in case of error.

Return type

None or Dict

property formula_weight(self) → Union[int, float]

Calculate the formula weight.

Returns

Weight of formula, based on the weight and count of elements. Can be int if the formula weight is a whole number, but unlikely.

Return type
property y(self) → float

Return 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. .. deprecated :: Use metabolite.shadow_price instead.

Returns

Return type

float

Return the shadow price for the metabolite in the most recent solution.

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

Returns

Return type

float

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

>>> solution = model.optimize()
-0.09166474637510488
-0.091664746375104883
remove_from_model(self, destructive: bool = False) → None

Remove the association from self.model.

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

Parameters

destructive (bool, default False) – 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: Optional['Solution'] = None, fva: Optional[Union[float, 'DataFrame']] = None) → 'MetaboliteSummary'

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) → str

Return the metabolite as an HTML string.

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

Bases: cobra.core.object.Object

Class representation for a cobra model

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

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

reactions

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

Type

DictList

metabolites

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

Type

DictList

genes

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

Type

DictList

groups

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

Type

DictList

solution

The last obtained solution from optimizing the model.

Type

Solution

__setstate__(self, state)

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

>>> new = model.problem.Constraint(model.objective.expression, lb=0.99)
property tolerance(self)
property description(self)
get_metabolite_compartments(self)

Return all metabolites’ compartments.

property compartments(self)
property medium(self)

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.

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

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.

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

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, i.e., a reversible reaction that adds or removes an intracellular metabolite.

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

Parameters
• metabolite (cobra.Metabolite) – Any given metabolite. The compartment is not checked but you are encouraged to stick to the definition of exchanges and sinks.

• type (str, {"exchange", "demand", "sink"}) – Using one of the pre-defined reaction types is easiest. If you want to create your own kind of boundary reaction choose any other string, e.g., ‘my-boundary’.

• reaction_id (str, optional) – The ID of the resulting reaction. This takes precedence over the auto-generated identifiers but beware that it might make boundary reactions harder to identify afterwards when using model.boundary or specifically model.exchanges etc.

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

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

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

Returns

The created boundary reaction.

Return type

cobra.Reaction

Examples

>>> demand.id
'DM_atp_c'
>>> demand.name
'ATP demand'
>>> demand.bounds
(0, 1000.0)
>>> demand.build_reaction_string()
'atp_c --> '

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

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 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.core.Object(id: Optional[str] = None, name: str = '')[source]

Defines common behavior of object in cobra.core.

property id(self) → str

Get the Object id.

Returns

id

Return type

str

_set_id_with_model(self, value) → None

Set id with model.

This appears to be a stub so it can be modified in dependant classes.

Parameters

value (str) – The string to set the id to.

property annotation(self) → dict

Get annotation dictionary.

Returns

_annotation – Returns _annotation as a dictionary.

Return type

dict

__getstate__(self) → dict

Get state of annotation.

To prevent excessive replication during deepcopy, ignores _model in state.

Returns

state – Dictionary of state, excluding _model.

Return type

dict

__repr__(self) → str

Return string representation of Object, with class.

Returns

Composed of class.name, id and hexadecimal of id.

Return type

str

__str__(self) → str

Return string representation of object.

Returns

Object.id as string.

Return type

str

class cobra.core.Reaction(id: Optional[str] = None, name: str = '', subsystem: str = '', lower_bound: float = 0.0, upper_bound: Optional[float] = None, **kwargs)[source]

Bases: cobra.core.object.Object

Define the cobra.Reaction class.

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 (str, optional) – The identifier to associate with this reaction (default None).

• name (str, optional) – A human readable name for the reaction (default “”).

• subsystem (str, optional) – Subsystem where the reaction is meant to occur (default “”).

• lower_bound (float) – The lower flux bound (default 0.0).

• upper_bound (float, optional) – The upper flux bound (default None).

• **kwargs – Further keyword arguments are passed on to the parent class.

_set_id_with_model(self, value: str) → None

Set Reaction id in model, check that it doesn’t already exist.

The function will rebuild the model reaction index.

Parameters

value (str) – A string that represents the id.

Raises

ValueError – If the model already contains a reaction with the id value.

property reverse_id(self) → str

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

Returns

The original id, joined to the word reverse and a partial hash of the utf-8 encoded id.

Return type

str

property flux_expression(self) → Optional['Variable']

Get Forward flux expression.

Returns

flux_expression – 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

optlang.interface.Variable, optional

property forward_variable(self) → Optional['Variable']

Get 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, optional

property reverse_variable(self) → Optional['Variable']

Get 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, optional

property objective_coefficient(self) → float

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.

Returns

Linear coefficient if this reaction has any, or 0.0 otherwise.

Return type

float

Raises

AttributeError – If the model of the reaction is missing (None).

__copy__(self) → 'Reaction'

Copy the Reaction.

Returns

A new reaction that is a copy of the original reaction.

Return type

Reaction

__deepcopy__(self, memo: dict) → 'Reaction'

Copy the reaction with memo.

Parameters

memo (dict) – Automatically passed parameter.

Returns

A new reaction that is a deep copy of the original reaction with memo.

Return type

Reaction

static _check_bounds(lb: float, ub: float) → None

Check if the lower and upper bounds are valid.

Parameters
• lb (float) – The lower bound.

• ub (float) – The upper bound.

Raises

ValueError – If the lower bound is higher than upper bound.

update_variable_bounds(self) → None

Update and correct variable bounds.

Sets the forward_variable and reverse_variable bounds based on lower and upper bounds. This function corrects for bounds defined as inf or -inf. This function will also adjust the associated optlang variables associated with the reaction.

optlang.interface.set_bounds()

property lower_bound(self) → float

Get the lower bound.

Returns

The lower bound of the reaction.

Return type

float

property upper_bound(self) → float

Get the upper bound.

Returns

The upper bound of the reaction.

Return type

float

property bounds(self) → Tuple[float, float]

Get or the bounds.

Returns

tuple – A tuple of floats, representing the lower and upper bound.

Return type

lower_bound, upper_bound

property flux(self) → float

Get the flux value in the most recent solution.

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

Returns

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

Return type

float

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

>>> solution = model.optimize()
>>> model.reactions.PFK.flux
7.477381962160283
>>> solution.fluxes.PFK
7.4773819621602833
property reduced_cost(self) → float

Get the reduced cost in the most recent solution.

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

Returns

reducd_cost – A float representing the reduced cost.

Return type

float

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

>>> solution = model.optimize()
>>> model.reactions.PFK.reduced_cost
-8.673617379884035e-18
>>> solution.reduced_costs.PFK
-8.6736173798840355e-18
property metabolites(self) → Dict[Metabolite, float]

Get a dictionary of metabolites and coefficients.

Returns

metaoblites – A copy of self._metabolites, which is a dictionary of cobra.Metabolite for keys and floats for coeffecieints. Positive coefficient means the reaction produces this metabolite, while negative coefficient means the reaction consumes this metabolite.

Return type

Dict[Metabolite, float]

property genes(self) → FrozenSet

Return the genes of the reaction.

Returns

genes

Return type

FrozenSet

update_genes_from_gpr(self) → None

Update genes of reation based on GPR.

If the reaction has a model, and new genes appear in the GPR, they will be created as Gene() entities and added to the model. If the reaction doesn’t have a model, genes will be created without a model.

Genes that no longer appear in the GPR will be removed from the reaction, but not the model. If you want to remove them expliclty, use model.remove_genes().

property gene_reaction_rule(self) → str

See gene reaction rule as str.

Uses the to_string() method of the GPR class

Returns

Return type

str

property gene_name_reaction_rule(self)

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 gpr(self) → GPR

Return the GPR associated with the reaction.

Returns

gpr – The GPR class, see cobra.core.gene.GPR() for details.

Return type

GPR

property functional(self) → bool

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) → float

Get the flux through the reaction in the most recent solution.

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

Returns

• flux (float) – Float representing the flux value.

• .. deprecated ::

property y(self) → float

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

Returns

• flux (float) – Float representing the reduced cost value.

• .. deprecated ::

property reversibility(self) → bool

Whether the reaction can proceed in both directions (reversible).

This is computed from the current upper and lower bounds.

Returns

True if the reaction is reversible (lower bound lower than 0 and upper bound is higher than 0).

Return type

bool

property boundary(self) → bool

Whether or not this reaction is an exchange reaction.

Returns

bool

Return type

True if the reaction has either no products or reactants.

property model(self) → Optional['Model']

Return the model the reaction is a part of.

Returns

model – The model this reaction belongs to. None if there is no model associated with this reaction.

Return type

cobra.Model, optional

_update_awareness(self) → None

Update awareness for genes and metaoblites of the reaction.

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

remove_from_model(self, remove_orphans: bool = False) → None

Remove 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 (default False).

delete(self, remove_orphans: bool = False) → None

Remove 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 (default False).

__setstate__(self, state: Dict) → None

Set state fo reaction.

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

Parameters

state (dict) – A dictionary of state, where keys are attribute names (str). Similar to __dict__.

copy(self) → 'Reaction'

Copy a reaction.

The referenced metabolites and genes are also copied.

Returns

A copy of the Reaction.

Return type

cobra.Reaction

Add two reactions and return a new one.

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.

Does not modify in place.

Parameters

other (cobra.Reaction) – Another reaction to add to the current one.

Returns

Return type

Reaction - new reaction with the added properties.

Add two reactions in place and return the modified first one.

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.

Modifies in place.

Parameters

other (cobra.Reaction) – Another reaction to add to the current one.

Returns

Return type

Reaction - original reaction (self) with the added properties.

__sub__(self, other: Reaction) → 'Reaction'

Subtract two reactions and return a new one.

The stoichiometry will be the subtracted stoichiometry of the two reactions, and the gene_reaction_rule will be the gene_reaction_rule of the first reaction. All other attributes (i.e. reaction bounds) will match those of the first reaction.

Does not modify in place. The name will still be that of the first reaction.

Parameters

other (Reaction) – The reaction to subtract from self.

Returns

Return type

Reaction - new reaction with the added properties.

__isub__(self, other: Reaction) → 'Reaction'

Subtract metabolites of one reaction from another in place.

The stoichiometry will be the metabolites of self minus the metabolites

of the other. All other attributes including gene_reaction_rule (i.e. reaction bounds) will match those of

the first reaction.

Modifies in place and changes the original reaction.

Parameters

other (Reaction) – The reaction to subtract from self.

Returns

Return type

Reaction - self with the subtracted metabolites.

__imul__(self, coefficient: float) → 'Reaction'

Scale coefficients in a reaction by a given value in place.

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

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

Parameters

coefficient (float) – Value to scale coefficients of metabolites by. If less than zero, reverses the reaction.

Returns

Returns the same reaction modified in place.

Return type

Reaction

__mul__(self, coefficient: float) → 'Reaction'

Scale coefficients in a reaction by a given value and return new reaction.

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

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

Parameters

coefficient (float) – Value to scale coefficients of metabolites by. If less than zero, reverses the reaction.

Returns

Returns a new reaction, identical to the original except coefficients.

Return type

Reaction

property reactants(self) → List[Metabolite]

Return a list of reactants for the reaction.

Returns

A list of the metabolites consudmed (coefficient < 0) by the reaction.

Return type

list

property products(self) → List[Metabolite]

Return a list of products for the reaction.

Returns

A list of the metabolites produced (coefficient > 0) by the reaction.

Return type

list

get_coefficient(self, metabolite_id: Union[str, Metabolite]) → float

Return the stoichiometric coefficient of a metabolite.

Parameters

metabolite_id (str or cobra.Metabolite) –

get_coefficients(self, metabolite_ids: Iterable[Union[str, Metabolite]]) → Iterator[float]

Return the stoichiometric coefficients for a list of metabolites.

Parameters

metabolite_ids (iterable) – Containing str or cobra.Metabolites.

Returns

map – Returns the result of map function, which is a map object (an Iterable).

Return type

Iterable

add_metabolites(self, metabolites_to_add: Dict[Metabolite, float], combine: bool = True, reversibly: bool = True) → None

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 if a metabolite already exists in the reaction (default True). 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). Default is True.

Raises
• KeyError – If the metabolite string id is not in the model.

• ValueError – If the metabolite key in the dictionary is a string, and there is no model for the reaction.

subtract_metabolites(self, metabolites: Dict[Metabolite, float], combine: bool = True, reversibly: bool = True) → None

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 if a metabolite already exists in the reaction (default True). 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 (default True).

property reaction(self) → str

Returns

The reaction in a human readble str.

Return type

str

build_reaction_string(self, use_metabolite_names: bool = False) → str

Generate a human readable reaction str.

Parameters

use_metabolite_names (bool) – Whether to use metabolite names (when True) or metabolite ids (when False, default).

Returns

Return type

str

check_mass_balance(self) → Dict[str, float]

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.

Return type

dict

Raises

ValueError – No elements were found in metabolite.

property compartments(self) → Set

Return set of compartments the metabolites are in.

Returns

A set of compartments the metabolites are in.

Return type

set

get_compartments(self) → list

List compartments the metabolites are in.

Returns

• list – A list of compartments the metabolites are in.

• .. deprecated ::

_associate_gene(self, cobra_gene: Gene) → None

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

Parameters

cobra_gene (cobra.core.Gene.Gene) –

_dissociate_gene(self, cobra_gene: Gene) → None

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

Parameters

cobra_gene (cobra.core.Gene.Gene) –

knock_out(self) → None

Knockout reaction by setting its bounds to zero.

build_reaction_from_string(self, reaction_str: str, verbose: bool = True, fwd_arrow: Optional[AnyStr] = None, rev_arrow: Optional[AnyStr] = None, reversible_arrow: Optional[AnyStr] = None, term_split: str = '+') → None

Build 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 (str) – a string containing a reaction formula (equation)

• verbose (bool) – setting verbosity of function (default True)

• fwd_arrow (AnyStr, optional) – Str or bytes that encode forward irreversible reaction arrows (default None).

• rev_arrow (AnyStr, optional) – Str or bytes that encode backward irreversible reaction arrows (default None).

• reversible_arrow (AnyStr, optional) – Str or bytes that encode reversible reaction arrows (default None).

• term_split (str) – dividing individual metabolite entries (default “+”)”.

Raises

ValueError – No arrow found in reaction string.

summary(self, solution: Optional['Solution'] = None, fva: Optional[Union[float, 'pd.DataFrame']] = None) → 'ReactionSummary'

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) → str

Return reaction id and reaction as str.

Returns

A string comprised out of reaction id and reaction.

Return type

str

_repr_html_(self) → str

Generate html representation of reaction.

Returns

HTML representation of the reaction.

Return type

str

class cobra.core.Group(id: str, name: str = '', members: Optional[Iterable] = None, kind: Optional[str] = None)[source]

Bases: cobra.core.object.Object

Manage groups via this implementation of the SBML group specification.

Group is a class for holding information regarding a pathways, subsystems, or other custom groupings of objects within a cobra.Model object.

Parameters
• id (str) – The identifier to associate with this group

• name (str, optional) – A human readable name for the group

• members (iterable, optional) – A DictList containing references to cobra.Model-associated objects that belong to the group.

• kind ({"collection", "classification", "partonomy"}, optional) – The kind of group, as specified for the Groups feature in the SBML level 3 package specification. Can be any of “classification”, “partonomy”, or “collection”. The default is “collection”. Please consult the SBML level 3 package specification to ensure you are using the proper value for kind. In short, members of a “classification” group should have an “is-a” relationship to the group (e.g. member is-a polar compound, or member is-a transporter). Members of a “partonomy” group should have a “part-of” relationship (e.g. member is part-of glycolysis). Members of a “collection” group do not have an implied relationship between the members, so use this value for kind when in doubt (e.g. member is a gap-filled reaction, or member is involved in a disease phenotype).

KIND_TYPES = ['collection', 'classification', 'partonomy']
__len__(self) → int

Get length of group.

Returns

An int with the length of the group.

Return type

int

property members(self) → DictList

Get members of the group.

Returns

A dictlist containing the members of the group.

Return type

DictList

property kind(self) → str

Return the group kind.

Returns

The group kind. Should be one of the three types allowed in SBML.

Return type

str

Parameters

new_members (list) – A list of cobrapy objects to add to the group.

remove_members(self, to_remove: list) → None

Remove objects from the group.

Parameters

to_remove (list) – A list of cobra objects to remove from the group

class cobra.core.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

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

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

The objective value

Type

float

solver

A string indicating which solver package was used.

Type

str

x

List or Array of the fluxes (primal values).

Type

iterable

x_dict

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

Type

dict

y

List or Array of the dual values.

Type

iterable

y_dict

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

Type

dict

Warning

The LegacySolution class and its interface is deprecated.

__repr__(self)

String representation of the solution instance.

__getitem__(self, reaction_id)

Return the flux of a reaction.

Parameters

reaction_id (str) – A reaction ID.

dress_results(self, model)

Method could be intended as a decorator.

Warning

deprecated

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

class cobra.core.Species(id: Optional[str] = None, name: Optional[str] = None, **kwargs)[source]

Bases: cobra.core.object.Object

Species is a base class in Cobrapy.

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) → FrozenSet

Return a frozenset of reactions.

Returns

A frozenset that includes the reactions of the species.

Return type

FrozenSet

__getstate__(self) → dict

Return the state of the species.

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

Returns

A dictionary describing the state, without the self._reaction to avoid recursion.

Return type

dict

copy(self) → 'Species'

Copy a species.

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

Returns

A copy of the species.

Return type

Species

property model(self) → Optional['Model']

Return the model.

Returns

Returns the cobra model that the species is associated with. None if there is no model associated with this species.

Return type

model