cobra

Contents

17. cobra#

17.1. Submodules#

17.2. Attributes#

17.3. Classes#

Configuration

Define a global configuration object.

DictList

Define a combined dict and list.

Gene

A Gene in a cobra model.

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.

Solution

A unified interface to a cobra.Model optimization solution.

Species

Species is a base class in Cobrapy.

17.4. Functions#

show_versions(→ None)

Print dependency information.

17.5. Package Contents#

cobra.__author__ = 'The cobrapy core development team.'#
cobra.__version__ = '0.31.1'#
class cobra.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, optional

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

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

_solver = None#
tolerance = 1e-07#
lower_bound = None#
upper_bound = None#
processes = None#
_cache_directory = None#
max_cache_size = 104857600#
cache_expiration = None#
property bounds: Tuple[numbers.Number | None, numbers.Number | None]#

Return the lower, upper reaction bound pair.

Returns:

The lower and upper bounds for new reactions.

Return type:

tuple of number and number or None and None

_set_default_solver() None[source]#

Set the default solver from a preferred order.

_set_default_processes() None[source]#

Set the default number of processes.

_set_default_cache_directory() None[source]#

Set the platform-dependent default cache directory.

property solver: types.ModuleType#

Return the optlang solver interface.

property cache_directory: pathlib.Path#

Return the model cache directory.

__repr__() str[source]#

Return a string representation of the current configuration values.

_repr_html_() str[source]#

Return a rich HTML representation of the current configuration values.

Notes

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

class cobra.DictList(*args)[source]#

Bases: List[CobraObject]

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

_dict#
has_id(id: CobraObject | str) bool[source]#

Check if id is in DictList.

_check(id: CobraObject | str) None[source]#

Make sure duplicate id’s are not added.

This function is called before adding in elements.

_generate_index() None[source]#

Rebuild the _dict index.

get_by_id(id: CobraObject | str) CobraObject[source]#

Return the element with a matching id.

list_attr(attribute: str) list[source]#

Return a list of the given attribute for every object.

get_by_any(iterable: List[str | CobraObject | int]) List[CobraObject][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

query(search_function: str | Pattern | Callable, attribute: str | None = None) DictList[CobraObject][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

>>> from cobra.io import load_model
>>> model = load_model('textbook')
>>> model.reactions.query(lambda x: x.boundary)
>>> import re
>>> regex = re.compile('^g', flags=re.IGNORECASE)
>>> model.metabolites.query(regex, attribute='name')
_replace_on_id(new_object: CobraObject) None[source]#

Replace an object by another with the same id.

append(entity: CobraObject) None[source]#

Append object to end.

union(iterable: Iterable[CobraObject]) None[source]#

Add elements with id’s not already in the model.

extend(iterable: Iterable[CobraObject]) None[source]#

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(iterable: Iterable[CobraObject]) None[source]#

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__(other: Iterable[CobraObject]) DictList[CobraObject][source]#

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__(other: Iterable[CobraObject]) DictList[CobraObject][source]#

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__(other: Iterable[CobraObject]) DictList[CobraObject][source]#

Add item while returning a new DictList.

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

Parameters:

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

__iadd__(other: Iterable[CobraObject]) DictList[CobraObject][source]#

Add item while returning the same DictList.

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

Parameters:

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

__reduce__() Tuple[Type[DictList], Tuple, dict, Iterator[CobraObject]][source]#

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__() dict[source]#

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__(state: dict) None[source]#

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(id: str | CobraObject, *args) int[source]#

Determine the position in the list.

Parameters:

id (A string or a Object)

__contains__(entity: str | CobraObject) bool[source]#

Ask if the DictList contain an entity.

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

Parameters:

entity (str or Object)

__copy__() DictList[CobraObject][source]#

Copy the DictList into a new one.

insert(index: int, entity: CobraObject) None[source]#

Insert entity before index.

pop(*args) CobraObject[source]#

Remove and return item at index (default last).

add(x: CobraObject) None[source]#

Opposite of remove. Mirrors set.add.

remove(x: str | CobraObject) None[source]#

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() None[source]#

Reverse IN PLACE.

sort(cmp: Callable = None, key: Callable = None, reverse: bool = False) None[source]#

Stable sort IN PLACE.

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

__getitem__(i: int | slice | Iterable | CobraObject | DictList[CobraObject]) DictList[CobraObject] | CobraObject[source]#

Get item from DictList.

__setitem__(i: slice | int, y: List[CobraObject] | CobraObject) None[source]#

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__(index: int) None[source]#

Remove item from DictList.

__getslice__(i: int, j: int) DictList[CobraObject][source]#

Get a slice from it to j of DictList.

__setslice__(i: int, j: int, y: List[CobraObject] | CobraObject) None[source]#

Set slice, where y is an iterable.

__delslice__(i: int, j: int) None[source]#

Remove slice.

__getattr__(attr: Any) CobraObject[source]#

Get an attribute by id.

__dir__() list[source]#

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.Gene(id: str = None, name: str = '', functional: bool = 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 = True#
property functional: bool#

Flag indicating if the gene is functional.

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

knock_out() None[source]#

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_()[source]#
class cobra.Metabolite(id: str | None = None, formula: str | None = None, name: str | None = '', charge: float | None = None, compartment: str | None = None)[source]#

Bases: cobra.core.species.Species

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.

formula = None#
compartment = None#
charge = None#
_bound = 0.0#
_set_id_with_model(value: str) None[source]#

Set id with value.

Parameters:

value (str)

property constraint: optlang.interface.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: Dict[str, int | float] | None#

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

float, int

property y: 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:

Float representing the shadow price.

Return type:

float

property shadow_price: 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:

shadow_price

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

>>> from cobra.io import load_model
>>> model = load_model("textbook")
>>> solution = model.optimize()
>>> model.metabolites.glc__D_e.shadow_price
-0.09166474637510488
>>> solution.shadow_prices.glc__D_e
-0.091664746375104883
remove_from_model(destructive: bool = False) None[source]#

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(solution: cobra.core.Solution | None = None, fva: float | pandas.DataFrame | None = None) cobra.summary.MetaboliteSummary[source]#

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

Return type:

cobra.summary.MetaboliteSummary

_repr_html_() str[source]#

Return the metabolite as an HTML string.

class cobra.Model(id_or_model: str | Model | None = None, name: str | None = None)[source]#

Bases: cobra.core.object.Object

Class representation for a cobra model.

Parameters:
  • id_or_model (str or Model, optional) – String to use as model id, or actual model to base new model one. If string, it is used as id. If model, a new model object is instantiated with the same properties as the original model (default None).

  • name (str, optional) – Human readable string to be model description (default None).

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

__setstate__(state: Dict) None[source]#

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

Parameters:

state (dict)

__getstate__() Dict[source]#

Get state for serialization.

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

Returns:

odict – A dictionary of state, based on self.__dict__.

Return type:

Dict

property solver: optlang.interface.Model#

Get 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

>>> from cobra.io import load_model
>>> model = load_model("textbook")
>>> new = model.problem.Constraint(model.objective.expression, lb=0.99)
>>> model.solver.add(new)
property tolerance: float#

Get the tolerance.

Returns:

The tolerance of the mdoel.

Return type:

float

property compartments: Dict#

Return all metabolites’ compartments.

Returns:

A dictionary of metabolite compartments, where the keys are the short version (one letter version) of the compartments, and the values are the full names (if they exist).

Return type:

dict

property medium: Dict[str, float]#

Get the constraints on the model exchanges.

model.medium returns a dictionary of the bounds for each of the boundary reactions, in the form of {rxn_id: bound}, where bound specifies the absolute value of the bound in direction of metabolite creation (i.e., lower_bound for met <–, upper_bound for met –>)

Returns:

A dictionary with rxn.id (str) as key, bound (float) as value.

Return type:

Dict[str, float]

copy() Model[source]#

Provide a partial ‘deepcopy’ of the Model.

All the Metabolite, Gene, and Reaction objects are created anew but in a faster fashion than deepcopy.

Returns:

cobra.Model

Return type:

new model copy

add_metabolites(metabolite_list: List | cobra.core.metabolite.Metabolite) None[source]#

Add new metabolites to a model.

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 (list or Metabolite.) – A list of cobra.core.Metabolite objects. If it isn’t an iterable container, the metabolite will be placed into a list.

remove_metabolites(metabolite_list: List | cobra.core.metabolite.Metabolite, destructive: bool = False) None[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 or Metaoblite) – A list of cobra.core.Metabolite objects. If it isn’t an iterable container, the metabolite will be placed into a list.

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

add_boundary(metabolite: cobra.core.metabolite.Metabolite, type: str = 'exchange', reaction_id: str | None = None, lb: float | None = None, ub: float | None = None, sbo_term: str | None = None) cobra.core.reaction.Reaction[source]#

Add a boundary reaction for a given metabolite.

There are three different types of pre-defined boundary reactions: exchange, demand, and sink reactions. An exchange reaction is a reversible, unbalanced reaction that adds to or removes an extracellular metabolite from the extracellular compartment. A demand reaction is an irreversible reaction that consumes an intracellular metabolite. A sink is similar to an exchange but specifically for intracellular metabolites, i.e., a reversible reaction that adds or removes an intracellular metabolite.

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

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

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 ({"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’ (default “exchange”).

  • 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. (default None).

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

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

  • 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 (default None).

Returns:

The created boundary reaction.

Return type:

cobra.Reaction

Examples

>>> from cobra.io load_model
>>> model = load_model("textbook")
>>> demand = model.add_boundary(model.metabolites.atp_c, type="demand")
>>> demand.id
'DM_atp_c'
>>> demand.name
'ATP demand'
>>> demand.bounds
(0, 1000.0)
>>> demand.build_reaction_string()
'atp_c --> '
add_reactions(reaction_list: Iterable[cobra.core.reaction.Reaction]) None[source]#

Add reactions to the model.

Reactions with identifiers identical to a reaction already in the model are ignored.

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

Parameters:

reaction_list (list) – A list of cobra.Reaction objects

remove_reactions(reactions: str | cobra.core.reaction.Reaction | List[str | cobra.core.reaction.Reaction], remove_orphans: bool = False) None[source]#

Remove reactions from the model.

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

Parameters:
  • reactions (list or reaction or str) – A list with reactions (cobra.Reaction), or their id’s, to remove. Reaction will be placed in a list. Str will be placed in a list and used to find the reaction in the model.

  • remove_orphans (bool, optional) – Remove orphaned genes and metabolites from the model as well (default False).

add_groups(group_list: str | cobra.core.group.Group | List[cobra.core.group.Group]) None[source]#

Add groups to the model.

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

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

Parameters:

group_list (list or str or Group) – A list of cobra.Group objects to add to the model. Can also be a single group or a string representing group id. If the input is not a list, a warning is raised.

remove_groups(group_list: str | cobra.core.group.Group | List[cobra.core.group.Group]) None[source]#

Remove groups from the model.

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

Parameters:

group_list (list or str or Group) –

A list of cobra.Group objects to remove from the model. Can also be a single group or a string representing group id. If the input is not a list,

a warning is raised.

get_associated_groups(element: cobra.core.reaction.Reaction | cobra.core.gene.Gene | cobra.core.metabolite.Metabolite) List[cobra.core.group.Group][source]#

Get list of groups for element.

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

Parameters:

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

Returns:

All groups that the provided object is a member of

Return type:

list of cobra.Group

add_cons_vars(what: List[cobra.util.solver.CONS_VARS] | Tuple[cobra.util.solver.CONS_VARS], **kwargs) None[source]#

Add constraints and variables to the model’s mathematical problem.

Useful for variables and constraints that can not be expressed with reactions and simple lower and upper bounds.

Additions are reversed upon exit if the model itself is used as context.

Parameters:
  • what (list or tuple of optlang variables or constraints.) – The variables or constraints to add to the model. Must be of class optlang.interface.Variable or optlang.interface.Constraint.

  • **kwargs (keyword arguments) – Passed to solver.add()

remove_cons_vars(what: List[cobra.util.solver.CONS_VARS] | Tuple[cobra.util.solver.CONS_VARS]) None[source]#

Remove variables and constraints from problem.

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: optlang.interface#

Get 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: optlang.container.Container#

Get 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: optlang.container.Container#

Get 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: List[cobra.core.reaction.Reaction]#

Boundary reactions in the model.

Reactions that either have no substrate or product.

Returns:

A list of reactions that either have no substrate or product and only one metabolite overall.

Return type:

list

property exchanges: List[cobra.core.reaction.Reaction]#

Exchange reactions in model.

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

Returns:

A list of reactions that satisfy the conditions for exchange reactions.

Return type:

list

property demands: List[cobra.core.reaction.Reaction]#

Demand reactions in model.

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

Returns:

A list of reactions that are demand reactions (reactions that accumulate/consume a metabolite irreversibly).

Return type:

list

property sinks: List[cobra.core.reaction.Reaction]#

Sink reactions in model.

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

Returns:

A list of reactions that are demand reactions (reactions that accumulate/consume a metabolite reversibly).

Return type:

list

_populate_solver(reaction_list: List[cobra.core.reaction.Reaction], metabolite_list: List[cobra.core.metabolite.Metabolite] | None = None) None[source]#

Populate attached solver with constraints and variables.

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

Parameters:
  • reaction_list (list) – A list of cobra.Reaction to add to the solver. This list will be constrained.

  • metabolite_list (list, optional) – A list of cobra.Metabolite to add to the solver. This list will be constrained (default None).

slim_optimize(error_value: float | None = float('nan'), message: str | None = None) float[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 (default float(“nan”)).

  • message (str, optional) – Error message to use if the model optimization did not succeed (default None).

Returns:

The objective value. Returns the error value if optimization failed and error_value was not None.

Return type:

float

Raises:

OptimizationError – If error_value was set as None and the optimization fails.

optimize(objective_sense: str | None = None, raise_error: bool = False) cobra.Solution[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 (default None).

  • raise_error (bool) –

    If true, raise an OptimizationError if solver status is not

    optimal (default False).

Return type:

Solution

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(rebuild_index: bool = True, rebuild_relationships: bool = True) None[source]#

Update all indexes and pointers in a model.

Parameters:
  • rebuild_index (bool) – rebuild the indices kept in reactions, metabolites and genes

  • rebuild_relationships (bool) – reset all associations between genes, metabolites, model and then re-add them.

property objective: optlang.Objective#

Get the solver objective.

With optlang, the objective is not limited to a simple linear summation of individual reaction fluxes, making the 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).

property objective_direction: str#

Get the objective direction.

Returns:

Objective direction as string. Should be “max” or “min”.

Return type:

str

summary(solution: cobra.Solution | None = None, fva: pandas.DataFrame | float | None = None) cobra.summary.ModelSummary[source]#

Create a summary of the exchange fluxes of the model.

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

  • fva (pd.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).

Return type:

cobra.ModelSummary

__enter__() Model[source]#

Record future changes to the model.

Record all future changes to the model, undoing them when a call to __exit__ is received. Creates a new context and adds it to the stack.

Returns:

Returns the model with context added.

Return type:

cobra.Model

__exit__(type, value, traceback) None[source]#

Pop the top context manager and trigger the undo functions.

merge(right: Model, prefix_existing: str | None = None, inplace: bool = True, objective: str = 'left') Model[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.

Parameters:
  • right (cobra.Model) – The model to add reactions from

  • prefix_existing (string or optional) – Prefix the reaction identifier in the right that already exist in the left model with this string (default None).

  • 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 (default True).

  • objective ({"left", "right", "sum"}) – 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 (default “left”).

Returns:

The merged model.

Return type:

cobra.Model

_repr_html_() str[source]#

Get HTML represenation of the model.

Returns:

Model representation as HTML string.

Return type:

str

class cobra.Object(id: str | None = None, name: str = '')[source]#

Defines common behavior of object in cobra.core.

_id = None#
name = ''#
notes#
_annotation#
property id: str#

Get the Object id.

Returns:

id

Return type:

str

_set_id_with_model(value) None[source]#

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

Get annotation dictionary.

Returns:

_annotation – Returns _annotation as a dictionary.

Return type:

dict

__getstate__() dict[source]#

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__() str[source]#

Return string representation of Object, with class.

Returns:

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

Return type:

str

__str__() str[source]#

Return string representation of object.

Returns:

Object.id as string.

Return type:

str

class cobra.Reaction(id: str | None = None, name: str = '', subsystem: str = '', lower_bound: float = 0.0, upper_bound: float | None = 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.

_gpr#
subsystem = ''#
_genes#
_metabolites#
_model = None#
_lower_bound = 0.0#
_upper_bound#
_set_id_with_model(value: str) None[source]#

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: 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: optlang.interface.Variable | None#

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: optlang.interface.Variable | None#

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: optlang.interface.Variable | None#

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: 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__() Reaction[source]#

Copy the Reaction.

Returns:

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

Return type:

Reaction

__deepcopy__(memo: dict) Reaction[source]#

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[source]#

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() None[source]#

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.

See also

optlang.interface.set_bounds

property lower_bound: float#

Get the lower bound.

Returns:

The lower bound of the reaction.

Return type:

float

property upper_bound: float#

Get the upper bound.

Returns:

The upper bound of the reaction.

Return type:

float

property bounds: 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: 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

>>> from cobra.io import load_model
>>> model = load_model("textbook")
>>> solution = model.optimize()
>>> model.reactions.PFK.flux
7.477381962160283
>>> solution.fluxes.PFK
7.4773819621602833
property reduced_cost: 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

>>> from cobra.io import load_model
>>> model = load_model("textbook")
>>> solution = model.optimize()
>>> model.reactions.PFK.reduced_cost
-8.673617379884035e-18
>>> solution.reduced_costs.PFK
-8.6736173798840355e-18
property metabolites: Dict[cobra.core.metabolite.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: FrozenSet#

Return the genes of the reaction.

Returns:

genes

Return type:

FrozenSet

update_genes_from_gpr() None[source]#

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

See gene reaction rule as str.

Uses the to_string() method of the GPR class

Return type:

str

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

property gpr: cobra.core.gene.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: 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: 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 ::

  • Use reaction.flux instead.

property y: 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 ::

  • Use reaction.reduced_cost instead.

property reversibility: 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: 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: cobra.Model | None#

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() None[source]#

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(remove_orphans: bool = False) None[source]#

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(remove_orphans: bool = False) None[source]#

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.

use reaction.remove_from_model instead.

Parameters:

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

__getstate__() Dict[source]#

Get state for reaction.

This serializes the reaction object. The GPR will be converted to a string to avoid unneccessary copies due to interdependencies of used objects.

Returns:

The state/attributes of the reaction in serilized form.

Return type:

dict

__setstate__(state: Dict) None[source]#

Set state for 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() Reaction[source]#

Copy a reaction.

The referenced metabolites and genes are also copied.

Returns:

A copy of the Reaction.

Return type:

cobra.Reaction

__add__(other: Reaction) Reaction[source]#

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.

Return type:

Reaction - new reaction with the added properties.

__radd__#
__iadd__(other: Reaction) Reaction[source]#

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.

Return type:

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

__sub__(other: Reaction) Reaction[source]#

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.

Return type:

Reaction - new reaction with the added properties.

__isub__(other: Reaction) Reaction[source]#

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.

Return type:

Reaction - self with the subtracted metabolites.

__imul__(coefficient: float) Reaction[source]#

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__(coefficient: float) Reaction[source]#

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: List[cobra.core.metabolite.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: List[cobra.core.metabolite.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(metabolite_id: str | cobra.core.metabolite.Metabolite) float[source]#

Return the stoichiometric coefficient of a metabolite.

Parameters:

metabolite_id (str or cobra.Metabolite)

get_coefficients(metabolite_ids: Iterable[str | cobra.core.metabolite.Metabolite]) Iterator[float][source]#

Return the stoichiometric coefficients for a list of metabolites.

Parameters:

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

Returns:

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

Return type:

Iterable

add_metabolites(metabolites_to_add: Dict[cobra.core.metabolite.Metabolite, float], combine: bool = True, reversibly: bool = True) None[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 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(metabolites: Dict[cobra.core.metabolite.Metabolite, float], combine: bool = True, reversibly: bool = True) None[source]#

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

Return Human readable reaction str.

Returns:

The reaction in a human readble str.

Return type:

str

build_reaction_string(use_metabolite_names: bool = False) str[source]#

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:

A human readable str.

Return type:

str

check_mass_balance() Dict[str, float][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.

Return type:

dict

Raises:

ValueError – No elements were found in metabolite.

property compartments: Set#

Return set of compartments the metabolites are in.

Returns:

A set of compartments the metabolites are in.

Return type:

set

get_compartments() list[source]#

List compartments the metabolites are in.

Returns:

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

  • .. deprecated ::

  • Use reaction.compartments() instead.

_associate_gene(cobra_gene: cobra.core.gene.Gene) None[source]#

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

Parameters:

cobra_gene (cobra.core.Gene.Gene)

_dissociate_gene(cobra_gene: cobra.core.gene.Gene) None[source]#

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

Parameters:

cobra_gene (cobra.core.Gene.Gene)

knock_out() None[source]#

Knockout reaction by setting its bounds to zero.

build_reaction_from_string(reaction_str: str, verbose: bool = True, fwd_arrow: AnyStr | None = None, rev_arrow: AnyStr | None = None, reversible_arrow: AnyStr | None = None, term_split: str = '+') None[source]#

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(solution: cobra.Solution | None = None, fva: float | pandas.DataFrame | None = None) cobra.summary.ReactionSummary[source]#

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

Return type:

cobra.summary.ReactionSummary

__str__() str[source]#

Return reaction id and reaction as str.

Returns:

A string comprised out of reaction id and reaction.

Return type:

str

_repr_html_() str[source]#

Generate html representation of reaction.

Returns:

HTML representation of the reaction.

Return type:

str

class cobra.Solution(objective_value: float, status: str, fluxes: pandas.Series, reduced_costs: pandas.Series | None = None, shadow_prices: pandas.Series | None = None, **kwargs)[source]#

A unified interface to a cobra.Model optimization solution.

Parameters:
  • 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) (default None).

  • shadow_prices (pandas.Series) – Contains metabolite shadow prices (dual values of constraints) (default None).

objective_value#

The (optimal) value for the objective function.

Type:

float

status#

The solver status related to the solution.

Type:

str

fluxes#

Contains the reaction fluxes (primal values of variables).

Type:

pandas.Series

reduced_costs#

Contains reaction reduced costs (dual values of variables).

Type:

pandas.Series

shadow_prices#

Contains metabolite shadow prices (dual values of constraints).

Type:

pandas.Series

Notes

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

objective_value#
status#
fluxes#
reduced_costs = None#
shadow_prices = None#
__repr__() str[source]#

Return a string representation of the solution instance.

_repr_html_() str[source]#

Return a rich HTML representation of the solution.

__getitem__(reaction_id: str) float[source]#

Return the flux of a reaction.

Parameters:

reaction_id (str) – A model reaction ID.

Returns:

The flux of the reaction with ID reaction_id.

Return type:

float

get_primal_by_id#
to_frame() pandas.DataFrame[source]#

Return the fluxes and reduced costs as a pandas DataFrame.

Returns:

The fluxes and reduced cost.

Return type:

pandas.DataFrame

class cobra.Species(id: str | None = None, name: str | None = 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.

_model = None#
_reaction#
property reactions: FrozenSet#

Return a frozenset of reactions.

Returns:

A frozenset that includes the reactions of the species.

Return type:

FrozenSet

__getstate__() dict[source]#

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() Species[source]#

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: cobra.Model | None#

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

cobra.show_versions() None[source]#

Print dependency information.