cobra.core.reaction#
Define the Reaction class.
Attributes#
Classes#
Define the cobra.Reaction class. |
Module Contents#
- cobra.core.reaction.config#
- cobra.core.reaction.compartment_finder#
- cobra.core.reaction._reversible_arrow_finder#
- cobra.core.reaction._forward_arrow_finder#
- cobra.core.reaction._reverse_arrow_finder#
- class cobra.core.reaction.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.ObjectDefine 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:
- 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:
- 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:
- static _check_bounds(lb: float, ub: float) None[source]#
Check if the lower and upper bounds are valid.
- Parameters:
- 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:
- property upper_bound: float#
Get the upper bound.
- Returns:
The upper bound of the reaction.
- Return type:
- property bounds: Tuple[float, float]#
Get or the bounds.
- Returns:
tuple – A tuple of floats, representing the lower and upper bound.
- Return type:
- 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:
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:
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:
- 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:
- 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:
- 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:
- 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:
- __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:
- __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.
- __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.
- 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:
- 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:
- 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
stror ``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:
- build_reaction_string(use_metabolite_names: bool = False) str[source]#
Generate a human readable reaction 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:
- 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:
- 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)
- 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:
See also
Metabolite.summary,Model.summary