cobra.core.reaction
===================

.. py:module:: cobra.core.reaction

.. autoapi-nested-parse::

   Define the Reaction class.



Attributes
----------

.. autoapisummary::

   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


Classes
-------

.. autoapisummary::

   cobra.core.reaction.Reaction


Module Contents
---------------

.. py:data:: config

.. py:data:: compartment_finder

.. py:data:: _reversible_arrow_finder

.. py:data:: _forward_arrow_finder

.. py:data:: _reverse_arrow_finder

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

   Bases: :py:obj:`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)`.

   :param id: The identifier to associate with this reaction (default None).
   :type id: str, optional
   :param name: A human readable name for the reaction (default "").
   :type name: str, optional
   :param subsystem: Subsystem where the reaction is meant to occur (default "").
   :type subsystem: str, optional
   :param lower_bound: The lower flux bound (default 0.0).
   :type lower_bound: float
   :param upper_bound: The upper flux bound (default None).
   :type upper_bound: float, optional
   :param \*\*kwargs: Further keyword arguments are passed on to the parent class.


   .. py:attribute:: _gpr


   .. py:attribute:: subsystem
      :value: ''



   .. py:attribute:: _genes


   .. py:attribute:: _metabolites


   .. py:attribute:: _model
      :value: None



   .. py:attribute:: _lower_bound
      :value: 0.0



   .. py:attribute:: _upper_bound


   .. py:method:: _set_id_with_model(value: str) -> None

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

      The function will rebuild the model reaction index.

      :param value: A string that represents the id.
      :type value: str

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



   .. py:property:: reverse_id
      :type: 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.
      :rtype: str


   .. py:property:: flux_expression
      :type: Optional[optlang.interface.Variable]


      Get Forward flux expression.

      :returns: **flux_expression** -- The expression representing the the forward flux (if associated
                with model), otherwise None. Representing the net flux if
                model.reversible_encoding == 'unsplit' or None if reaction is
                not associated with a model
      :rtype: optlang.interface.Variable, optional


   .. py:property:: forward_variable
      :type: Optional[optlang.interface.Variable]


      Get an optlang variable representing the forward flux.

      :returns: An optlang variable for the forward flux or None if reaction is
                not associated with a model.
      :rtype: optlang.interface.Variable, optional


   .. py:property:: reverse_variable
      :type: Optional[optlang.interface.Variable]


      Get an optlang variable representing the reverse flux.

      :returns: An optlang variable for the reverse flux or None if reaction is
                not associated with a model.
      :rtype: optlang.interface.Variable, optional


   .. py:property:: objective_coefficient
      :type: 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.
      :rtype: float

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


   .. py:method:: __copy__() -> Reaction

      Copy the Reaction.

      :returns: A new reaction that is a copy of the original reaction.
      :rtype: Reaction



   .. py:method:: __deepcopy__(memo: dict) -> Reaction

      Copy the reaction with memo.

      :param memo: Automatically passed parameter.
      :type memo: dict

      :returns: A new reaction that is a deep copy of the original reaction with memo.
      :rtype: Reaction



   .. py:method:: _check_bounds(lb: float, ub: float) -> None
      :staticmethod:


      Check if the lower and upper bounds are valid.

      :param lb: The lower bound.
      :type lb: float
      :param ub: The upper bound.
      :type ub: float

      :raises ValueError: If the lower bound is higher than upper bound.



   .. py:method:: update_variable_bounds() -> None

      Update and correct variable bounds.

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

      .. seealso:: :py:obj:`optlang.interface.set_bounds`



   .. py:property:: lower_bound
      :type: float


      Get the lower bound.

      :returns: The lower bound of the reaction.
      :rtype: float


   .. py:property:: upper_bound
      :type: float


      Get the upper bound.

      :returns: The upper bound of the reaction.
      :rtype: float


   .. py:property:: bounds
      :type: Tuple[float, float]


      Get or the bounds.

      :returns: **tuple** -- A tuple of floats, representing the lower and upper bound.
      :rtype: lower_bound, upper_bound


   .. py:property:: flux
      :type: 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.
      :rtype: 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.
      :raises OptimizationError: If the solver status is anything other than 'optimal'.
      :raises AssertionError: If the flux value is not within the bounds.

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


   .. py:property:: reduced_cost
      :type: 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.
      :rtype: 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.
      :raises OptimizationError: If the solver status is anything other than 'optimal'.

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


   .. py:property:: metabolites
      :type: 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.
      :rtype: Dict[Metabolite, float]


   .. py:property:: genes
      :type: FrozenSet


      Return the genes of the reaction.

      :returns: **genes**
      :rtype: FrozenSet


   .. py:method:: update_genes_from_gpr() -> None

      Update genes of reation based on GPR.

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

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



   .. py:property:: gene_reaction_rule
      :type: str


      See gene reaction rule as str.

      Uses the to_string() method of the GPR class

      :rtype: str


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


   .. py:property:: gpr
      :type: cobra.core.gene.GPR


      Return the GPR associated with the reaction.

      :returns: **gpr** -- The GPR class, see cobra.core.gene.GPR() for details.
      :rtype: GPR


   .. py:property:: functional
      :type: 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.
      :rtype: bool


   .. py:property:: x
      :type: 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.*


   .. py:property:: y
      :type: 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.*


   .. py:property:: reversibility
      :type: 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).
      :rtype: bool


   .. py:property:: boundary
      :type: bool


      Whether or not this reaction is an exchange reaction.

      :returns: **bool**
      :rtype: `True` if the reaction has either no products or reactants.


   .. py:property:: model
      :type: Optional[cobra.Model]


      Return the model the reaction is a part of.

      :returns: **model** -- The model this reaction belongs to. None if there is no model associated
                with this reaction.
      :rtype: cobra.Model, optional


   .. py:method:: _update_awareness() -> None

      Update awareness for genes and metaoblites of the reaction.

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




   .. py:method:: remove_from_model(remove_orphans: bool = False) -> None

      Remove the reaction from a model.

      This removes all associations between a reaction the associated
      model, metabolites and genes.

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

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



   .. py:method:: delete(remove_orphans: bool = False) -> None

      Remove the reaction from a model.

      This removes all associations between a reaction the associated
      model, metabolites and genes.

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

      .. deprecated ::
      use `reaction.remove_from_model` instead.

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



   .. py:method:: __getstate__() -> Dict

      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.
      :rtype: dict



   .. py:method:: __setstate__(state: Dict) -> None

      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

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



   .. py:method:: copy() -> Reaction

      Copy a reaction.

      The referenced metabolites and genes are also copied.

      :returns: A copy of the Reaction.
      :rtype: cobra.Reaction



   .. py:method:: __add__(other: Reaction) -> Reaction

      Add two reactions and return a new one.

      The stoichiometry will be the combined stoichiometry of the two
      reactions, and the gene reaction rule will be both rules combined by an
      and. All other attributes (i.e. reaction bounds) will match those of
      the first reaction.

      Does not modify in place.

      :param other: Another reaction to add to the current one.
      :type other: cobra.Reaction

      :rtype: Reaction - new reaction with the added properties.



   .. py:attribute:: __radd__


   .. py:method:: __iadd__(other: Reaction) -> Reaction

      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.

      :param other: Another reaction to add to the current one.
      :type other: cobra.Reaction

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



   .. py:method:: __sub__(other: Reaction) -> Reaction

      Subtract two reactions and return a new one.

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

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

      :param other: The reaction to subtract from self.
      :type other: Reaction

      :rtype: Reaction - new reaction with the added properties.



   .. py:method:: __isub__(other: Reaction) -> Reaction

      Subtract metabolites of one reaction from another in place.

      The stoichiometry will be the metabolites of self minus the metabolites
       of the other. All other attributes including gene_reaction_rule
       (i.e. reaction bounds) will match those of
      the first reaction.

      Modifies in place and changes the original reaction.

      :param other: The reaction to subtract from self.
      :type other: Reaction

      :rtype: Reaction - self with the subtracted metabolites.



   .. py:method:: __imul__(coefficient: float) -> Reaction

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

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

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

      :param coefficient: Value to scale coefficients of metabolites by. If less than zero, reverses
                          the reaction.
      :type coefficient: float

      :returns: Returns the same reaction modified in place.
      :rtype: Reaction



   .. py:method:: __mul__(coefficient: float) -> Reaction

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

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

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

      :param coefficient: Value to scale coefficients of metabolites by. If less than zero, reverses
                          the reaction.
      :type coefficient: float

      :returns: Returns a new reaction, identical to the original except coefficients.
      :rtype: Reaction



   .. py:property:: reactants
      :type: 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.
      :rtype: list


   .. py:property:: products
      :type: 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.
      :rtype: list


   .. py:method:: get_coefficient(metabolite_id: Union[str, cobra.core.metabolite.Metabolite]) -> float

      Return the stoichiometric coefficient of a metabolite.

      :param metabolite_id:
      :type metabolite_id: str or cobra.Metabolite



   .. py:method:: get_coefficients(metabolite_ids: Iterable[Union[str, cobra.core.metabolite.Metabolite]]) -> Iterator[float]

      Return the stoichiometric coefficients for a list of metabolites.

      :param metabolite_ids: Containing ``str`` or ``cobra.Metabolite``s.
      :type metabolite_ids: iterable

      :returns: **map** -- Returns the result of map function, which is a map object (an Iterable).
      :rtype: Iterable



   .. py:method:: add_metabolites(metabolites_to_add: Dict[cobra.core.metabolite.Metabolite, float], combine: bool = True, reversibly: bool = True) -> None

      Add metabolites and stoichiometric coefficients to the reaction.

      If the final coefficient for a metabolite is 0 then it is removed
      from the reaction.

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

      :param metabolites_to_add: 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.
      :type metabolites_to_add: dict
      :param combine: 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.
      :type combine: bool
      :param reversibly: Whether to add the change to the context to make the change
                         reversibly or not (primarily intended for internal use). Default is True.
      :type reversibly: bool

      :raises KeyError: If the metabolite string id is not in the model.
      :raises ValueError: If the metabolite key in the dictionary is a string, and there is no model
          for the reaction.



   .. py:method:: subtract_metabolites(metabolites: Dict[cobra.core.metabolite.Metabolite, float], combine: bool = True, reversibly: bool = True) -> None

      Subtract metabolites from a reaction.

      That means add the metabolites with -1*coefficient. If the final
      coefficient for a metabolite is 0 then the metabolite is removed from
      the reaction.

      .. rubric:: Notes

      * A final coefficient < 0 implies a reactant.
      * The change is reverted upon exit when using the model as a context.

      :param metabolites: Dictionary where the keys are of class Metabolite and the values
                          are the coefficients. These metabolites will be added to the
                          reaction.
      :type metabolites: dict
      :param combine: 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.
      :type combine: bool
      :param reversibly: Whether to add the change to the context to make the change
                         reversibly or not ,primarily intended for internal use (default True).
      :type reversibly: bool



   .. py:property:: reaction
      :type: str


      Return Human readable reaction str.

      :returns: The reaction in a human readble str.
      :rtype: str


   .. py:method:: build_reaction_string(use_metabolite_names: bool = False) -> str

      Generate a human readable reaction str.

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

      :returns: A human readable str.
      :rtype: str



   .. py:method:: check_mass_balance() -> Dict[str, float]

      Compute mass and charge balance for the reaction.

      :returns: a dict of {element: amount} for unbalanced elements.
                "charge" is treated as an element in this dict
                This should be empty for balanced reactions.
      :rtype: dict

      :raises ValueError: No elements were found in metabolite.



   .. py:property:: compartments
      :type: Set


      Return set of compartments the metabolites are in.

      :returns: A set of compartments the metabolites are in.
      :rtype: set


   .. py:method:: get_compartments() -> list

      List compartments the metabolites are in.

      :returns: * *list* -- A list of compartments the metabolites are in.
                * *.. deprecated ::*
                * *Use reaction.compartments() instead.*



   .. py:method:: _associate_gene(cobra_gene: cobra.core.gene.Gene) -> None

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

      :param cobra_gene:
      :type cobra_gene: cobra.core.Gene.Gene



   .. py:method:: _dissociate_gene(cobra_gene: cobra.core.gene.Gene) -> None

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

      :param cobra_gene:
      :type cobra_gene: cobra.core.Gene.Gene



   .. py:method:: knock_out() -> None

      Knockout reaction by setting its bounds to zero.



   .. py:method:: build_reaction_from_string(reaction_str: str, verbose: bool = True, fwd_arrow: Optional[AnyStr] = None, rev_arrow: Optional[AnyStr] = None, reversible_arrow: Optional[AnyStr] = None, term_split: str = '+') -> None

      Build reaction from reaction equation reaction_str using parser.

      Takes a string and using the specifications supplied in the optional
      arguments infers a set of metabolites, metabolite compartments and
      stoichiometries for the reaction.  It also infers the reversibility
      of the reaction from the reaction arrow.

      Changes to the associated model are reverted upon exit when using
      the model as a context.

      :param reaction_str: a string containing a reaction formula (equation)
      :type reaction_str: str
      :param verbose: setting verbosity of function (default True)
      :type verbose: bool
      :param fwd_arrow: Str or bytes that encode forward irreversible reaction arrows (default
                        None).
      :type fwd_arrow: AnyStr, optional
      :param rev_arrow: Str or bytes that encode backward irreversible reaction arrows (default
                        None).
      :type rev_arrow: AnyStr, optional
      :param reversible_arrow: Str or bytes that encode reversible reaction arrows (default None).
      :type reversible_arrow: AnyStr, optional
      :param term_split: dividing individual metabolite entries (default "+")".
      :type term_split: str

      :raises ValueError: No arrow found in reaction string.



   .. py:method:: summary(solution: Optional[cobra.Solution] = None, fva: Optional[Union[float, pandas.DataFrame]] = None) -> cobra.summary.ReactionSummary

      Create a summary of the reaction flux.

      :param solution: A previous model solution to use for generating the summary. If
                       ``None``, the summary method will generate a parsimonious flux
                       distribution (default None).
      :type solution: cobra.Solution, optional
      :param fva: 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).
      :type fva: pandas.DataFrame or float, optional

      :rtype: cobra.summary.ReactionSummary

      .. seealso:: :py:obj:`Metabolite.summary`, :py:obj:`Model.summary`



   .. py:method:: __str__() -> str

      Return reaction id and reaction as str.

      :returns: A string comprised out of reaction id and reaction.
      :rtype: str



   .. py:method:: _repr_html_() -> str

      Generate html representation of reaction.

      :returns: HTML representation of the reaction.
      :rtype: str



