# 17.1.1.1.1.9. cobra.core.reaction¶

Define the Reaction class.

## 17.1.1.1.1.9.1. Module Contents¶

### 17.1.1.1.1.9.1.1. Classes¶

 Reaction Define the cobra.Reaction class.
cobra.core.reaction.config[source]
cobra.core.reaction.compartment_finder[source]
cobra.core.reaction._reversible_arrow_finder[source]
cobra.core.reaction._forward_arrow_finder[source]
cobra.core.reaction._reverse_arrow_finder[source]
class cobra.core.reaction.Reaction(id: Optional[str] = None, name: str = '', subsystem: str = '', lower_bound: float = 0.0, upper_bound: Optional[float] = None, **kwargs)[source]

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.

__radd__[source]
_set_id_with_model(self, 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(self) → str[source]

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

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

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

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

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

Copy the Reaction.

Returns

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

Return type

Reaction

__deepcopy__(self, 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(self) → 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.

optlang.interface.set_bounds()

property lower_bound(self) → float[source]

Get the lower bound.

Returns

The lower bound of the reaction.

Return type

float

property upper_bound(self) → float[source]

Get the upper bound.

Returns

The upper bound of the reaction.

Return type

float

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

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

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
>>> solution = model.optimize()
>>> model.reactions.PFK.flux
7.477381962160283
>>> solution.fluxes.PFK
7.4773819621602833

property reduced_cost(self) → float[source]

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
>>> solution = model.optimize()
>>> model.reactions.PFK.reduced_cost
-8.673617379884035e-18
>>> solution.reduced_costs.PFK
-8.6736173798840355e-18

property metabolites(self) → Dict[Metabolite, float][source]

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

Return the genes of the reaction.

Returns

genes

Return type

FrozenSet

update_genes_from_gpr(self) → 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(self) → str[source]

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

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

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

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

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

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

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

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

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[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(self, 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(self, 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).

__setstate__(self, state: Dict) → None[source]

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

Copy a reaction.

The referenced metabolites and genes are also copied.

Returns

A copy of the Reaction.

Return type

cobra.Reaction

__add__(self, 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.

Returns

Return type

Reaction - new reaction with the added properties.

__iadd__(self, 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.

Returns

Return type

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

__sub__(self, 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.

Returns

Return type

Reaction - new reaction with the added properties.

__isub__(self, 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.

Returns

Return type

Reaction - self with the subtracted metabolites.

__imul__(self, 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__(self, 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(self) → List[Metabolite][source]

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

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

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

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[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(self, metabolites: Dict[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(self) → str[source]

Returns

The reaction in a human readble str.

Return type

str

build_reaction_string(self, 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

Return type

str

check_mass_balance(self) → 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(self) → Set[source]

Return set of compartments the metabolites are in.

Returns

A set of compartments the metabolites are in.

Return type

set

get_compartments(self) → list[source]

List compartments the metabolites are in.

Returns

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

• .. deprecated ::

_associate_gene(self, cobra_gene: Gene) → None[source]

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

Parameters

cobra_gene (cobra.core.Gene.Gene) –

_dissociate_gene(self, cobra_gene: Gene) → None[source]

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

Parameters

cobra_gene (cobra.core.Gene.Gene) –

knock_out(self) → None[source]

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[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(self, solution: Optional['Solution'] = None, fva: Optional[Union[float, 'pd.DataFrame']] = None) → '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).

Returns

Return type

cobra.summary.ReactionSummary

Metabolite.summary(), Model.summary()

__str__(self) → str[source]

Return reaction id and reaction as str.

Returns

A string comprised out of reaction id and reaction.

Return type

str

_repr_html_(self) → str[source]

Generate html representation of reaction.

Returns

HTML representation of the reaction.

Return type

str