return linear_reaction_coefficients(self.model, [self]).get(self, <NUM_LIT:0>)<EOL>

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.


return self._lower_bound<EOL>

Get or set the lower bound

        Setting the lower bound (float) will also adjust the associated optlang
        variables associated with the reaction. Infeasible combinations,
        such as a lower bound higher than the current upper bound will
        update the other bound.

        When using a `HistoryManager` context, this attribute can be set
        temporarily, reversed when the exiting the context.


return self._upper_bound<EOL>

Get or set the upper bound

        Setting the upper bound (float) will also adjust the associated optlang
        variables associated with the reaction. Infeasible combinations,
        such as a upper bound lower than the current lower bound will
        update the other bound.

        When using a `HistoryManager` context, this attribute can be set
        temporarily, reversed when the exiting the context.


return self.lower_bound, self.upper_bound<EOL>

Get or set the bounds directly from a tuple

        Convenience method for setting upper and lower bounds in one line
        using a tuple of lower and upper bound. Invalid bounds will raise an
        AssertionError.

        When using a `HistoryManager` context, this attribute can be set
        temporarily, reversed when the exiting the context.


try:<EOL><INDENT>check_solver_status(self._model.solver.status)<EOL>return self.forward_variable.primal - self.reverse_variable.primal<EOL><DEDENT>except AttributeError:<EOL><INDENT>raise RuntimeError(<EOL>"<STR_LIT>".format(self.id))<EOL><DEDENT>except (RuntimeError, OptimizationError) as err:<EOL><INDENT>raise_with_traceback(err)<EOL><DEDENT>except Exception as err:<EOL><INDENT>raise_from(OptimizationError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(str(err))), err)<EOL><DEDENT>

The flux value in the most recent solution.

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

Warnings
--------
* 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
--------
>>> import cobra.test
>>> model = cobra.test.create_test_model("textbook")
>>> solution = model.optimize()
>>> model.reactions.PFK.flux
7.477381962160283
>>> solution.fluxes.PFK
7.4773819621602833


try:<EOL><INDENT>check_solver_status(self._model.solver.status)<EOL>return self.forward_variable.dual - self.reverse_variable.dual<EOL><DEDENT>except AttributeError:<EOL><INDENT>raise RuntimeError(<EOL>"<STR_LIT>".format(self.id))<EOL><DEDENT>except (RuntimeError, OptimizationError) as err:<EOL><INDENT>raise_with_traceback(err)<EOL><DEDENT>except Exception as err:<EOL><INDENT>raise_from(OptimizationError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(str(err))), err)<EOL><DEDENT>

The reduced cost in the most recent solution.

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

Warnings
--------
* 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
--------
>>> import cobra.test
>>> model = cobra.test.create_test_model("textbook")
>>> solution = model.optimize()
>>> model.reactions.PFK.reduced_cost
-8.673617379884035e-18
>>> solution.reduced_costs.PFK
-8.6736173798840355e-18


names = {i.id: i.name for i in self._genes}<EOL>ast = parse_gpr(self._gene_reaction_rule)[<NUM_LIT:0>]<EOL>return ast2str(ast, names=names)<EOL>

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.


if self._model:<EOL><INDENT>tree, _ = parse_gpr(self.gene_reaction_rule)<EOL>return eval_gpr(tree, {gene.id for gene in self.genes if<EOL>not gene.functional})<EOL><DEDENT>return True<EOL>

All required enzymes for reaction are functional.

        Returns
        -------
        bool
            True if the gene-protein-reaction (GPR) rule is fulfilled for
            this reaction, or if reaction is not associated to a model,
            otherwise False.


warn("<STR_LIT>", DeprecationWarning)<EOL>return self.flux<EOL>

The flux through the reaction in the most recent solution.

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


warn("<STR_LIT>", DeprecationWarning)<EOL>return self.reduced_cost<EOL>

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.


return self._lower_bound < <NUM_LIT:0> < self._upper_bound<EOL>

Whether the reaction can proceed in both directions (reversible)

        This is computed from the current upper and lower bounds.


return (len(self.metabolites) == <NUM_LIT:1> and<EOL>not (self.reactants and self.products))<EOL>

Whether or not this reaction is an exchange reaction.

        Returns `True` if the reaction has either no products or reactants.


return self._model<EOL>

returns the model the reaction is a part of


for x in self._metabolites:<EOL><INDENT>x._reaction.add(self)<EOL><DEDENT>for x in self._genes:<EOL><INDENT>x._reaction.add(self)<EOL><DEDENT>

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


self._model.remove_reactions([self], remove_orphans=remove_orphans)<EOL>

Removes 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


warn("<STR_LIT>",<EOL>DeprecationWarning)<EOL>self.remove_from_model(remove_orphans=remove_orphans)<EOL>

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

        Parameters
        ----------
        remove_orphans : bool
            Remove orphaned genes and metabolites from the model as well


<EOL>if "<STR_LIT>" in state:<EOL><INDENT>state.pop("<STR_LIT>")<EOL><DEDENT>if "<STR_LIT>" in state:<EOL><INDENT>state["<STR_LIT>"] = state.pop("<STR_LIT>")<EOL><DEDENT>if "<STR_LIT>" in state:<EOL><INDENT>state['<STR_LIT>'] = state.pop('<STR_LIT>')<EOL><DEDENT>if "<STR_LIT>" in state:<EOL><INDENT>state['<STR_LIT>'] = state.pop('<STR_LIT>')<EOL><DEDENT>self.__dict__.update(state)<EOL>for x in state['<STR_LIT>']:<EOL><INDENT>setattr(x, '<STR_LIT>', self._model)<EOL>x._reaction.add(self)<EOL><DEDENT>for x in state['<STR_LIT>']:<EOL><INDENT>setattr(x, '<STR_LIT>', self._model)<EOL>x._reaction.add(self)<EOL><DEDENT>

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


<EOL>model = self._model<EOL>self._model = None<EOL>for i in self._metabolites:<EOL><INDENT>i._model = None<EOL><DEDENT>for i in self._genes:<EOL><INDENT>i._model = None<EOL><DEDENT>new_reaction = deepcopy(self)<EOL>self._model = model<EOL>for i in self._metabolites:<EOL><INDENT>i._model = model<EOL><DEDENT>for i in self._genes:<EOL><INDENT>i._model = model<EOL><DEDENT>return new_reaction<EOL>

Copy a reaction

        The referenced metabolites and genes are also copied.


new_reaction = self.copy()<EOL>if other == <NUM_LIT:0>:<EOL><INDENT>return new_reaction<EOL><DEDENT>else:<EOL><INDENT>new_reaction += other<EOL><DEDENT>return new_reaction<EOL>

Add two reactions

        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


self._metabolites = {<EOL>met: value * coefficient<EOL>for met, value in iteritems(self._metabolites)}<EOL>if coefficient < <NUM_LIT:0>:<EOL><INDENT>self.bounds = (-self.upper_bound, -self.lower_bound)<EOL><DEDENT>if self._model:<EOL><INDENT>self._model._populate_solver([self])<EOL><DEDENT>context = get_context(self)<EOL>if context:<EOL><INDENT>context(partial(self._model._populate_solver, [self]))<EOL>context(partial(self.__imul__, <NUM_LIT:1.>/coefficient))<EOL><DEDENT>return self<EOL>

Scale coefficients in a reaction by a given value

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

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


return [k for k, v in iteritems(self._metabolites) if v < <NUM_LIT:0>]<EOL>

Return a list of reactants for the reaction.


return [k for k, v in iteritems(self._metabolites) if v >= <NUM_LIT:0>]<EOL>

Return a list of products for the reaction


if isinstance(metabolite_id, Metabolite):<EOL><INDENT>return self._metabolites[metabolite_id]<EOL><DEDENT>_id_to_metabolites = {m.id: m for m in self._metabolites}<EOL>return self._metabolites[_id_to_metabolites[metabolite_id]]<EOL>

Return the stoichiometric coefficient of a metabolite.

Parameters
----------
metabolite_id : str or cobra.Metabolite


return map(self.get_coefficient, metabolite_ids)<EOL>

Return the stoichiometric coefficients for a list of metabolites.

Parameters
----------
metabolite_ids : iterable
    Containing ``str`` or ``cobra.Metabolite``s.


def add_metabolites(self, metabolites_to_add, combine=True,<EOL>reversibly=True):

old_coefficients = self.metabolites<EOL>new_metabolites = []<EOL>_id_to_metabolites = dict([(x.id, x) for x in self._metabolites])<EOL>for metabolite, coefficient in iteritems(metabolites_to_add):<EOL><INDENT>if isinstance(metabolite, Metabolite):<EOL><INDENT>if ((metabolite.model is not None) and<EOL>(metabolite.model is not self._model)):<EOL><INDENT>metabolite = metabolite.copy()<EOL><DEDENT><DEDENT>met_id = str(metabolite)<EOL>if met_id in _id_to_metabolites:<EOL><INDENT>reaction_metabolite = _id_to_metabolites[met_id]<EOL>if combine:<EOL><INDENT>self._metabolites[reaction_metabolite] += coefficient<EOL><DEDENT>else:<EOL><INDENT>self._metabolites[reaction_metabolite] = coefficient<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if self._model:<EOL><INDENT>try:<EOL><INDENT>metabolite =self._model.metabolites.get_by_id(met_id)<EOL><DEDENT>except KeyError as e:<EOL><INDENT>if isinstance(metabolite, Metabolite):<EOL><INDENT>new_metabolites.append(metabolite)<EOL><DEDENT>else:<EOL><INDENT>raise e<EOL><DEDENT><DEDENT><DEDENT>elif isinstance(metabolite, string_types):<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>% self.id)<EOL><DEDENT>self._metabolites[metabolite] = coefficient<EOL>metabolite._reaction.add(self)<EOL><DEDENT><DEDENT>model = self.model<EOL>if model is not None:<EOL><INDENT>model.add_metabolites(new_metabolites)<EOL>for metabolite, coefficient in self._metabolites.items():<EOL><INDENT>model.constraints[<EOL>metabolite.id].set_linear_coefficients(<EOL>{self.forward_variable: coefficient,<EOL>self.reverse_variable: -coefficient<EOL>})<EOL><DEDENT><DEDENT>for metabolite, the_coefficient in list(self._metabolites.items()):<EOL><INDENT>if the_coefficient == <NUM_LIT:0>:<EOL><INDENT>metabolite._reaction.remove(self)<EOL>self._metabolites.pop(metabolite)<EOL><DEDENT><DEDENT>context = get_context(self)<EOL>if context and reversibly:<EOL><INDENT>if combine:<EOL><INDENT>context(partial(<EOL>self.subtract_metabolites, metabolites_to_add,<EOL>combine=True, reversibly=False))<EOL><DEDENT>else:<EOL><INDENT>mets_to_reset = {<EOL>key: old_coefficients[model.metabolites.get_by_any(key)[<NUM_LIT:0>]]<EOL>for key in iterkeys(metabolites_to_add)}<EOL>context(partial(<EOL>self.add_metabolites, mets_to_reset,<EOL>combine=False, reversibly=False))<EOL><DEDENT><DEDENT>

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


def subtract_metabolites(self, metabolites, combine=True, reversibly=True):

self.add_metabolites({<EOL>k: -v for k, v in iteritems(metabolites)},<EOL>combine=combine, reversibly=reversibly)<EOL>

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


return self.build_reaction_string()<EOL>


def format(number):<EOL><INDENT>return "<STR_LIT>" if number == <NUM_LIT:1> else str(number).rstrip("<STR_LIT:.>") + "<STR_LIT:U+0020>"<EOL><DEDENT>id_type = '<STR_LIT:id>'<EOL>if use_metabolite_names:<EOL><INDENT>id_type = '<STR_LIT:name>'<EOL><DEDENT>reactant_bits = []<EOL>product_bits = []<EOL>for met in sorted(self._metabolites, key=attrgetter("<STR_LIT:id>")):<EOL><INDENT>coefficient = self._metabolites[met]<EOL>name = str(getattr(met, id_type))<EOL>if coefficient >= <NUM_LIT:0>:<EOL><INDENT>product_bits.append(format(coefficient) + name)<EOL><DEDENT>else:<EOL><INDENT>reactant_bits.append(format(abs(coefficient)) + name)<EOL><DEDENT><DEDENT>reaction_string = '<STR_LIT>'.join(reactant_bits)<EOL>if not self.reversibility:<EOL><INDENT>if self.lower_bound < <NUM_LIT:0> and self.upper_bound <= <NUM_LIT:0>:<EOL><INDENT>reaction_string += '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>reaction_string += '<STR_LIT>'<EOL><DEDENT><DEDENT>else:<EOL><INDENT>reaction_string += '<STR_LIT>'<EOL><DEDENT>reaction_string += '<STR_LIT>'.join(product_bits)<EOL>return reaction_string<EOL>

Generate a human readable reaction string


reaction_element_dict = defaultdict(int)<EOL>for metabolite, coefficient in iteritems(self._metabolites):<EOL><INDENT>if metabolite.charge is not None:<EOL><INDENT>reaction_element_dict["<STR_LIT>"] +=coefficient * metabolite.charge<EOL><DEDENT>if metabolite.elements is None:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>% metabolite.id)<EOL><DEDENT>for element, amount in iteritems(metabolite.elements):<EOL><INDENT>reaction_element_dict[element] += coefficient * amount<EOL><DEDENT><DEDENT>return {k: v for k, v in iteritems(reaction_element_dict) if v != <NUM_LIT:0>}<EOL>

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.


if self._compartments is None:<EOL><INDENT>self._compartments = {met.compartment for met in self._metabolites<EOL>if met.compartment is not None}<EOL><DEDENT>return self._compartments<EOL>

lists compartments the metabolites are in


warn('<STR_LIT>', DeprecationWarning)<EOL>return list(self.compartments)<EOL>


self._genes.add(cobra_gene)<EOL>cobra_gene._reaction.add(self)<EOL>cobra_gene._model = self._model<EOL>

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

        Parameters
        ----------
        cobra_gene : cobra.core.Gene.Gene


self._genes.discard(cobra_gene)<EOL>cobra_gene._reaction.discard(self)<EOL>

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

        Parameters
        ----------
        cobra_gene : cobra.core.Gene.Gene


self.bounds = (<NUM_LIT:0>, <NUM_LIT:0>)<EOL>

Knockout reaction by setting its bounds to zero.


def build_reaction_from_string(self, reaction_str, verbose=True,<EOL>fwd_arrow=None, rev_arrow=None,<EOL>reversible_arrow=None, term_split="<STR_LIT:+>"):

<EOL>forward_arrow_finder = _forward_arrow_finder if fwd_arrow is Noneelse re.compile(re.escape(fwd_arrow))<EOL>reverse_arrow_finder = _reverse_arrow_finder if rev_arrow is Noneelse re.compile(re.escape(rev_arrow))<EOL>reversible_arrow_finder = _reversible_arrow_finderif reversible_arrow is Noneelse re.compile(re.escape(reversible_arrow))<EOL>if self._model is None:<EOL><INDENT>warn("<STR_LIT>")<EOL>model = None<EOL><DEDENT>else:<EOL><INDENT>model = self._model<EOL><DEDENT>found_compartments = compartment_finder.findall(reaction_str)<EOL>if len(found_compartments) == <NUM_LIT:1>:<EOL><INDENT>compartment = found_compartments[<NUM_LIT:0>]<EOL>reaction_str = compartment_finder.sub("<STR_LIT>", reaction_str)<EOL><DEDENT>else:<EOL><INDENT>compartment = "<STR_LIT>"<EOL><DEDENT>arrow_match = reversible_arrow_finder.search(reaction_str)<EOL>if arrow_match is not None:<EOL><INDENT>self.lower_bound = -<NUM_LIT:1000><EOL>self.upper_bound = <NUM_LIT:1000><EOL><DEDENT>else:  <EOL><INDENT>arrow_match = forward_arrow_finder.search(reaction_str)<EOL>if arrow_match is not None:<EOL><INDENT>self.upper_bound = <NUM_LIT:1000><EOL>self.lower_bound = <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>arrow_match = reverse_arrow_finder.search(reaction_str)<EOL>if arrow_match is None:<EOL><INDENT>raise ValueError("<STR_LIT>" %<EOL>reaction_str)<EOL><DEDENT>else:<EOL><INDENT>self.upper_bound = <NUM_LIT:0><EOL>self.lower_bound = -<NUM_LIT:1000><EOL><DEDENT><DEDENT><DEDENT>reactant_str = reaction_str[:arrow_match.start()].strip()<EOL>product_str = reaction_str[arrow_match.end():].strip()<EOL>self.subtract_metabolites(self.metabolites, combine=True)<EOL>for substr, factor in ((reactant_str, -<NUM_LIT:1>), (product_str, <NUM_LIT:1>)):<EOL><INDENT>if len(substr) == <NUM_LIT:0>:<EOL><INDENT>continue<EOL><DEDENT>for term in substr.split(term_split):<EOL><INDENT>term = term.strip()<EOL>if term.lower() == "<STR_LIT>":<EOL><INDENT>continue<EOL><DEDENT>if "<STR_LIT:U+0020>" in term:<EOL><INDENT>num_str, met_id = term.split()<EOL>num = float(num_str.lstrip("<STR_LIT:(>").rstrip("<STR_LIT:)>")) * factor<EOL><DEDENT>else:<EOL><INDENT>met_id = term<EOL>num = factor<EOL><DEDENT>met_id += compartment<EOL>try:<EOL><INDENT>met = model.metabolites.get_by_id(met_id)<EOL><DEDENT>except KeyError:<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % met_id)<EOL><DEDENT>met = Metabolite(met_id)<EOL><DEDENT>self.add_metabolites({met: num})<EOL><DEDENT><DEDENT>

Builds 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 : string
            a string containing a reaction formula (equation)
        verbose: bool
            setting verbosity of function
        fwd_arrow : re.compile
            for forward irreversible reaction arrows
        rev_arrow : re.compile
            for backward irreversible reaction arrows
        reversible_arrow : re.compile
            for reversible reaction arrows
        term_split : string
            dividing individual metabolite entries


return Formula(self.formula + other_formula.formula)<EOL>

Combine two molecular formulas.

        Parameters
        ----------
        other_formula : Formula, str
            string for a chemical formula

        Returns
        -------
        Formula
           The combined formula


tmp_formula = self.formula<EOL>if "<STR_LIT:*>" in tmp_formula:<EOL><INDENT>warn("<STR_LIT>" % self.formula)<EOL>tmp_formula = self.formula.replace("<STR_LIT:*>", "<STR_LIT>")<EOL><DEDENT>if "<STR_LIT:(>" in tmp_formula or "<STR_LIT:)>" in tmp_formula:<EOL><INDENT>warn("<STR_LIT>" % self.formula)<EOL>return<EOL><DEDENT>composition = {}<EOL>parsed = element_re.findall(tmp_formula)<EOL>for (element, count) in parsed:<EOL><INDENT>if count == '<STR_LIT>':<EOL><INDENT>count = <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>count = float(count)<EOL>int_count = int(count)<EOL>if count == int_count:<EOL><INDENT>count = int_count<EOL><DEDENT>else:<EOL><INDENT>warn("<STR_LIT>" %<EOL>(count, self.formula))<EOL><DEDENT><DEDENT>except ValueError:<EOL><INDENT>warn("<STR_LIT>" %<EOL>(count, self.formula))<EOL>self.elements = {}<EOL>return<EOL><DEDENT><DEDENT>if element in composition:<EOL><INDENT>composition[element] += count<EOL><DEDENT>else:<EOL><INDENT>composition[element] = count<EOL><DEDENT><DEDENT>self.elements = composition<EOL>

Breaks the chemical formula down by element.


try:<EOL><INDENT>return sum([count * elements_and_molecular_weights[element]<EOL>for element, count in self.elements.items()])<EOL><DEDENT>except KeyError as e:<EOL><INDENT>warn("<STR_LIT>" % e)<EOL><DEDENT>

Calculate the mol mass of the compound

        Returns
        -------
        float
            the mol mass


self.__dict__.update(state)<EOL>for y in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>for x in getattr(self, y):<EOL><INDENT>x._model = self<EOL><DEDENT><DEDENT>if not hasattr(self, "<STR_LIT:name>"):<EOL><INDENT>self.name = None<EOL><DEDENT>

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


odict = self.__dict__.copy()<EOL>odict['<STR_LIT>'] = []<EOL>return odict<EOL>

Get state for serialization.

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


return self._solver<EOL>

Get or set the attached solver instance.

        The associated the solver object, which manages the interaction with
        the associated solver, e.g. glpk.

        This property is useful for accessing the optimization problem
        directly and to define additional non-metabolic constraints.

        Examples
        --------
        >>> import cobra.test
        >>> model = cobra.test.create_test_model("textbook")
        >>> new = model.problem.Constraint(model.objective.expression,
        >>> lb=0.99)
        >>> model.solver.add(new)


warn('<STR_LIT>', DeprecationWarning)<EOL>return {met.compartment for met in self.metabolites<EOL>if met.compartment is not None}<EOL>


Get or set the dictionary of current compartment descriptions.

        Assigning a dictionary to this property updates the model's
        dictionary of compartment descriptions with the new values.

        Parameters
        ----------
        value : dict
            Dictionary mapping compartments abbreviations to full names.

        Examples
        --------
        >>> import cobra.test
        >>> model = cobra.test.create_test_model("textbook")
        >>> model.compartments = {'c': 'the cytosol'}
        {'c': 'the cytosol', 'e': 'extracellular'}


def set_active_bound(reaction, bound):<EOL><INDENT>if reaction.reactants:<EOL><INDENT>reaction.lower_bound = -bound<EOL><DEDENT>elif reaction.products:<EOL><INDENT>reaction.upper_bound = bound<EOL><DEDENT><DEDENT>media_rxns = list()<EOL>exchange_rxns = frozenset(self.exchanges)<EOL>for rxn_id, bound in iteritems(medium):<EOL><INDENT>rxn = self.reactions.get_by_id(rxn_id)<EOL>if rxn not in exchange_rxns:<EOL><INDENT>LOGGER.warn("<STR_LIT>"<EOL>"<STR_LIT>",<EOL>rxn.id)<EOL><DEDENT>media_rxns.append(rxn)<EOL>set_active_bound(rxn, bound)<EOL><DEDENT>media_rxns = frozenset(media_rxns)<EOL>for rxn in (exchange_rxns - media_rxns):<EOL><INDENT>set_active_bound(rxn, <NUM_LIT:0>)<EOL><DEDENT>

Get or set 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 -->`)

        Parameters
        ----------
        medium: dictionary-like
            The medium to initialize. medium should be a dictionary defining
            `{rxn_id: bound}` pairs.


warn('<STR_LIT>', DeprecationWarning)<EOL>return self.merge(other_model, objective='<STR_LIT>', inplace=False)<EOL>

Add the content of another model to this model (+).

        The model is copied as a new object, with a new model identifier,
        and copies of all the reactions in the other model are added to this
        model. The objective is the sum of the objective expressions for the
        two models.


warn('<STR_LIT>', DeprecationWarning)<EOL>return self.merge(other_model, objective='<STR_LIT>', inplace=True)<EOL>

Incrementally add the content of another model to this model (+=).

        Copies of all the reactions in the other model are added to this
        model. The objective is the sum of the objective expressions for the
        two models.


new = self.__class__()<EOL>do_not_copy_by_ref = {"<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>",<EOL>"<STR_LIT>", "<STR_LIT>"}<EOL>for attr in self.__dict__:<EOL><INDENT>if attr not in do_not_copy_by_ref:<EOL><INDENT>new.__dict__[attr] = self.__dict__[attr]<EOL><DEDENT><DEDENT>new.notes = deepcopy(self.notes)<EOL>new.annotation = deepcopy(self.annotation)<EOL>new.metabolites = DictList()<EOL>do_not_copy_by_ref = {"<STR_LIT>", "<STR_LIT>"}<EOL>for metabolite in self.metabolites:<EOL><INDENT>new_met = metabolite.__class__()<EOL>for attr, value in iteritems(metabolite.__dict__):<EOL><INDENT>if attr not in do_not_copy_by_ref:<EOL><INDENT>new_met.__dict__[attr] = copy(<EOL>value) if attr == "<STR_LIT>" else value<EOL><DEDENT><DEDENT>new_met._model = new<EOL>new.metabolites.append(new_met)<EOL><DEDENT>new.genes = DictList()<EOL>for gene in self.genes:<EOL><INDENT>new_gene = gene.__class__(None)<EOL>for attr, value in iteritems(gene.__dict__):<EOL><INDENT>if attr not in do_not_copy_by_ref:<EOL><INDENT>new_gene.__dict__[attr] = copy(<EOL>value) if attr == "<STR_LIT>" else value<EOL><DEDENT><DEDENT>new_gene._model = new<EOL>new.genes.append(new_gene)<EOL><DEDENT>new.reactions = DictList()<EOL>do_not_copy_by_ref = {"<STR_LIT>", "<STR_LIT>", "<STR_LIT>"}<EOL>for reaction in self.reactions:<EOL><INDENT>new_reaction = reaction.__class__()<EOL>for attr, value in iteritems(reaction.__dict__):<EOL><INDENT>if attr not in do_not_copy_by_ref:<EOL><INDENT>new_reaction.__dict__[attr] = copy(value)<EOL><DEDENT><DEDENT>new_reaction._model = new<EOL>new.reactions.append(new_reaction)<EOL>for metabolite, stoic in iteritems(reaction._metabolites):<EOL><INDENT>new_met = new.metabolites.get_by_id(metabolite.id)<EOL>new_reaction._metabolites[new_met] = stoic<EOL>new_met._reaction.add(new_reaction)<EOL><DEDENT>for gene in reaction._genes:<EOL><INDENT>new_gene = new.genes.get_by_id(gene.id)<EOL>new_reaction._genes.add(new_gene)<EOL>new_gene._reaction.add(new_reaction)<EOL><DEDENT><DEDENT>new.groups = DictList()<EOL>do_not_copy_by_ref = {"<STR_LIT>", "<STR_LIT>"}<EOL>for group in self.groups:<EOL><INDENT>new_group = group.__class__(group.id)<EOL>for attr, value in iteritems(group.__dict__):<EOL><INDENT>if attr not in do_not_copy_by_ref:<EOL><INDENT>new_group.__dict__[attr] = copy(value)<EOL><DEDENT><DEDENT>new_group._model = new<EOL>new.groups.append(new_group)<EOL><DEDENT>for group in self.groups:<EOL><INDENT>new_group = new.groups.get_by_id(group.id)<EOL>new_objects = []<EOL>for member in group.members:<EOL><INDENT>if isinstance(member, Metabolite):<EOL><INDENT>new_object = new.metabolites.get_by_id(member.id)<EOL><DEDENT>elif isinstance(member, Reaction):<EOL><INDENT>new_object = new.reactions.get_by_id(member.id)<EOL><DEDENT>elif isinstance(member, Gene):<EOL><INDENT>new_object = new.genes.get_by_id(member.id)<EOL><DEDENT>elif isinstance(member, Group):<EOL><INDENT>new_object = new.genes.get_by_id(member.id)<EOL><DEDENT>else:<EOL><INDENT>raise TypeError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(member))<EOL><DEDENT>new_objects.append(new_object)<EOL><DEDENT>new_group.add_members(new_objects)<EOL><DEDENT>try:<EOL><INDENT>new._solver = deepcopy(self.solver)<EOL><DEDENT>except Exception:  <EOL><INDENT>new._solver = copy(self.solver)  <EOL><DEDENT>new._contexts = list()<EOL>return new<EOL>

Provides a partial 'deepcopy' of the Model.  All of the Metabolite,
        Gene, and Reaction objects are created anew but in a faster fashion
        than deepcopy


if not hasattr(metabolite_list, '<STR_LIT>'):<EOL><INDENT>metabolite_list = [metabolite_list]<EOL><DEDENT>if len(metabolite_list) == <NUM_LIT:0>:<EOL><INDENT>return None<EOL><DEDENT>metabolite_list = [x for x in metabolite_list<EOL>if x.id not in self.metabolites]<EOL>bad_ids = [m for m in metabolite_list<EOL>if not isinstance(m.id, string_types) or len(m.id) < <NUM_LIT:1>]<EOL>if len(bad_ids) != <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>'.format(repr(bad_ids)))<EOL><DEDENT>for x in metabolite_list:<EOL><INDENT>x._model = self<EOL><DEDENT>self.metabolites += metabolite_list<EOL>to_add = []<EOL>for met in metabolite_list:<EOL><INDENT>if met.id not in self.constraints:<EOL><INDENT>constraint = self.problem.Constraint(<EOL>Zero, name=met.id, lb=<NUM_LIT:0>, ub=<NUM_LIT:0>)<EOL>to_add += [constraint]<EOL><DEDENT><DEDENT>self.add_cons_vars(to_add)<EOL>context = get_context(self)<EOL>if context:<EOL><INDENT>context(partial(self.metabolites.__isub__, metabolite_list))<EOL>for x in metabolite_list:<EOL><INDENT>context(partial(setattr, x, '<STR_LIT>', None))<EOL><DEDENT><DEDENT>

Will add a list of metabolites to the model object and add new
        constraints accordingly.

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

        Parameters
        ----------
        metabolite_list : A list of `cobra.core.Metabolite` objects


def remove_metabolites(self, metabolite_list, destructive=False):

if not hasattr(metabolite_list, '<STR_LIT>'):<EOL><INDENT>metabolite_list = [metabolite_list]<EOL><DEDENT>metabolite_list = [x for x in metabolite_list<EOL>if x.id in self.metabolites]<EOL>for x in metabolite_list:<EOL><INDENT>x._model = None<EOL>associated_groups = self.get_associated_groups(x)<EOL>for group in associated_groups:<EOL><INDENT>group.remove_members(x)<EOL><DEDENT>if not destructive:<EOL><INDENT>for the_reaction in list(x._reaction):<EOL><INDENT>the_coefficient = the_reaction._metabolites[x]<EOL>the_reaction.subtract_metabolites({x: the_coefficient})<EOL><DEDENT><DEDENT>else:<EOL><INDENT>for x in list(x._reaction):<EOL><INDENT>x.remove_from_model()<EOL><DEDENT><DEDENT><DEDENT>self.metabolites -= metabolite_list<EOL>to_remove = [self.solver.constraints[m.id] for m in metabolite_list]<EOL>self.remove_cons_vars(to_remove)<EOL>context = get_context(self)<EOL>if context:<EOL><INDENT>context(partial(self.metabolites.__iadd__, metabolite_list))<EOL>for x in metabolite_list:<EOL><INDENT>context(partial(setattr, x, '<STR_LIT>', self))<EOL><DEDENT><DEDENT>

Remove a list of metabolites from the the object.

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

        Parameters
        ----------
        metabolite_list : list
            A list with `cobra.Metabolite` objects as elements.

        destructive : bool
            If False then the metabolite is removed from all
            associated reactions.  If True then all associated
            reactions are removed from the Model.


warn("<STR_LIT>",<EOL>DeprecationWarning)<EOL>self.add_reactions([reaction])<EOL>

Will add a cobra.Reaction object to the model, if
        reaction.id is not in self.reactions.

        Parameters
        ----------
        reaction : cobra.Reaction
            The reaction to add

        Deprecated (0.6). Use `~cobra.Model.add_reactions` instead


def add_boundary(self, metabolite, type="<STR_LIT>", reaction_id=None,<EOL>lb=None, ub=None, sbo_term=None):

ub = CONFIGURATION.upper_bound if ub is None else ub<EOL>lb = CONFIGURATION.lower_bound if lb is None else lb<EOL>types = {<EOL>"<STR_LIT>": ("<STR_LIT>", lb, ub, sbo_terms["<STR_LIT>"]),<EOL>"<STR_LIT>": ("<STR_LIT>", <NUM_LIT:0>, ub, sbo_terms["<STR_LIT>"]),<EOL>"<STR_LIT>": ("<STR_LIT>", lb, ub, sbo_terms["<STR_LIT>"])<EOL>}<EOL>if type == "<STR_LIT>":<EOL><INDENT>external = find_external_compartment(self)<EOL>if metabolite.compartment != external:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" %<EOL>(metabolite.compartment, external))<EOL><DEDENT><DEDENT>if type in types:<EOL><INDENT>prefix, lb, ub, default_term = types[type]<EOL>if reaction_id is None:<EOL><INDENT>reaction_id = "<STR_LIT>".format(prefix, metabolite.id)<EOL><DEDENT>if sbo_term is None:<EOL><INDENT>sbo_term = default_term<EOL><DEDENT><DEDENT>if reaction_id is None:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if reaction_id in self.reactions:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>".format(reaction_id))<EOL><DEDENT>name = "<STR_LIT>".format(metabolite.name, type)<EOL>rxn = Reaction(id=reaction_id, name=name, lower_bound=lb,<EOL>upper_bound=ub)<EOL>rxn.add_metabolites({metabolite: -<NUM_LIT:1>})<EOL>if sbo_term:<EOL><INDENT>rxn.annotation["<STR_LIT>"] = sbo_term<EOL><DEDENT>self.add_reactions([rxn])<EOL>return rxn<EOL>

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.

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

Parameters
----------
metabolite : cobra.Metabolite
    Any given metabolite. The compartment is not checked but you are
    encouraged to stick to the definition of exchanges and sinks.
type : str, {"exchange", "demand", "sink"}
    Using one of the pre-defined reaction types is easiest. If you
    want to create your own kind of boundary reaction choose
    any other string, e.g., 'my-boundary'.
reaction_id : str, optional
    The ID of the resulting reaction. This takes precedence over the
    auto-generated identifiers but beware that it might make boundary
    reactions harder to identify afterwards when using `model.boundary`
    or specifically `model.exchanges` etc.
lb : float, optional
    The lower bound of the resulting reaction.
ub : float, optional
    The upper bound of the resulting reaction.
sbo_term : str, optional
    A correct SBO term is set for the available types. If a custom
    type is chosen, a suitable SBO term should also be set.

Returns
-------
cobra.Reaction
    The created boundary reaction.

Examples
--------
>>> import cobra.test
>>> model = cobra.test.create_test_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 --> '


def existing_filter(rxn):<EOL><INDENT>if rxn.id in self.reactions:<EOL><INDENT>LOGGER.warning(<EOL>"<STR_LIT>", rxn.id)<EOL>return False<EOL><DEDENT>return True<EOL><DEDENT>pruned = DictList(filter(existing_filter, reaction_list))<EOL>context = get_context(self)<EOL>for reaction in pruned:<EOL><INDENT>reaction._model = self<EOL>for metabolite in list(reaction.metabolites):<EOL><INDENT>if metabolite not in self.metabolites:<EOL><INDENT>self.add_metabolites(metabolite)<EOL><DEDENT>else:<EOL><INDENT>stoichiometry = reaction._metabolites.pop(metabolite)<EOL>model_metabolite = self.metabolites.get_by_id(<EOL>metabolite.id)<EOL>reaction._metabolites[model_metabolite] = stoichiometry<EOL>model_metabolite._reaction.add(reaction)<EOL>if context:<EOL><INDENT>context(partial(<EOL>model_metabolite._reaction.remove, reaction))<EOL><DEDENT><DEDENT><DEDENT>for gene in list(reaction._genes):<EOL><INDENT>if not self.genes.has_id(gene.id):<EOL><INDENT>self.genes += [gene]<EOL>gene._model = self<EOL>if context:<EOL><INDENT>context(partial(self.genes.__isub__, [gene]))<EOL>context(partial(setattr, gene, '<STR_LIT>', None))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>model_gene = self.genes.get_by_id(gene.id)<EOL>if model_gene is not gene:<EOL><INDENT>reaction._dissociate_gene(gene)<EOL>reaction._associate_gene(model_gene)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>self.reactions += pruned<EOL>if context:<EOL><INDENT>context(partial(self.reactions.__isub__, pruned))<EOL><DEDENT>self._populate_solver(pruned)<EOL>

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


def remove_reactions(self, reactions, remove_orphans=False):

if isinstance(reactions, string_types) or hasattr(reactions, "<STR_LIT:id>"):<EOL><INDENT>warn("<STR_LIT>")<EOL>reactions = [reactions]<EOL><DEDENT>context = get_context(self)<EOL>for reaction in reactions:<EOL><INDENT>try:<EOL><INDENT>reaction = self.reactions[self.reactions.index(reaction)]<EOL><DEDENT>except ValueError:<EOL><INDENT>warn('<STR_LIT>' % (reaction, self))<EOL><DEDENT>else:<EOL><INDENT>forward = reaction.forward_variable<EOL>reverse = reaction.reverse_variable<EOL>if context:<EOL><INDENT>obj_coef = reaction.objective_coefficient<EOL>if obj_coef != <NUM_LIT:0>:<EOL><INDENT>context(partial(<EOL>self.solver.objective.set_linear_coefficients,<EOL>{forward: obj_coef, reverse: -obj_coef}))<EOL><DEDENT>context(partial(self._populate_solver, [reaction]))<EOL>context(partial(setattr, reaction, '<STR_LIT>', self))<EOL>context(partial(self.reactions.add, reaction))<EOL><DEDENT>self.remove_cons_vars([forward, reverse])<EOL>self.reactions.remove(reaction)<EOL>reaction._model = None<EOL>for met in reaction._metabolites:<EOL><INDENT>if reaction in met._reaction:<EOL><INDENT>met._reaction.remove(reaction)<EOL>if context:<EOL><INDENT>context(partial(met._reaction.add, reaction))<EOL><DEDENT>if remove_orphans and len(met._reaction) == <NUM_LIT:0>:<EOL><INDENT>self.remove_metabolites(met)<EOL><DEDENT><DEDENT><DEDENT>for gene in reaction._genes:<EOL><INDENT>if reaction in gene._reaction:<EOL><INDENT>gene._reaction.remove(reaction)<EOL>if context:<EOL><INDENT>context(partial(gene._reaction.add, reaction))<EOL><DEDENT>if remove_orphans and len(gene._reaction) == <NUM_LIT:0>:<EOL><INDENT>self.genes.remove(gene)<EOL>if context:<EOL><INDENT>context(partial(self.genes.add, gene))<EOL><DEDENT><DEDENT><DEDENT><DEDENT>associated_groups = self.get_associated_groups(reaction)<EOL>for group in associated_groups:<EOL><INDENT>group.remove_members(reaction)<EOL><DEDENT><DEDENT><DEDENT>

Remove reactions from the model.

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

        Parameters
        ----------
        reactions : list
            A list with reactions (`cobra.Reaction`), or their id's, to remove

        remove_orphans : bool
            Remove orphaned genes and metabolites from the model as well


def existing_filter(group):<EOL><INDENT>if group.id in self.groups:<EOL><INDENT>LOGGER.warning(<EOL>"<STR_LIT>", group.id)<EOL>return False<EOL><DEDENT>return True<EOL><DEDENT>if isinstance(group_list, string_types) orhasattr(group_list, "<STR_LIT:id>"):<EOL><INDENT>warn("<STR_LIT>")<EOL>group_list = [group_list]<EOL><DEDENT>pruned = DictList(filter(existing_filter, group_list))<EOL>for group in pruned:<EOL><INDENT>group._model = self<EOL>for member in group.members:<EOL><INDENT>if isinstance(member, Metabolite):<EOL><INDENT>if member not in self.metabolites:<EOL><INDENT>self.add_metabolites([member])<EOL><DEDENT><DEDENT>if isinstance(member, Reaction):<EOL><INDENT>if member not in self.reactions:<EOL><INDENT>self.add_reactions([member])<EOL><DEDENT><DEDENT><DEDENT>self.groups += [group]<EOL><DEDENT>

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
            A list of `cobra.Group` objects to add to the model.


if isinstance(group_list, string_types) orhasattr(group_list, "<STR_LIT:id>"):<EOL><INDENT>warn("<STR_LIT>")<EOL>group_list = [group_list]<EOL><DEDENT>for group in group_list:<EOL><INDENT>if group.id not in self.groups:<EOL><INDENT>LOGGER.warning("<STR_LIT>", group, self)<EOL><DEDENT>else:<EOL><INDENT>self.groups.remove(group)<EOL>group._model = None<EOL><DEDENT><DEDENT>

Remove groups from the model.

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

        Parameters
        ----------
        group_list : list
            A list of `cobra.Group` objects to remove from the model.


<EOL>return [g for g in self.groups if element in g.members]<EOL>

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

        Parameters
        ----------
        element: `cobra.Reaction`, `cobra.Metabolite`, or `cobra.Gene`

        Returns
        -------
        list of `cobra.Group`
            All groups that the provided object is a member of


def add_cons_vars(self, what, **kwargs):

add_cons_vars_to_problem(self, what, **kwargs)<EOL>

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_from_problem(self, what)<EOL>

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


return self.solver.interface<EOL>

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
        -------
        optlang.interface
            The problem interface that defines methods for interacting with
            the problem and associated solver directly.


return self.solver.variables<EOL>

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
        -------
        optlang.container.Container
            A container with all associated variables.


return self.solver.constraints<EOL>

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
        -------
        optlang.container.Container
            A container with all associated constraints.


return [rxn for rxn in self.reactions if rxn.boundary]<EOL>

Boundary reactions in the model.
        Reactions that either have no substrate or product.


return find_boundary_types(self, "<STR_LIT>", None)<EOL>

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


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


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


def _populate_solver(self, reaction_list, metabolite_list=None):

constraint_terms = AutoVivification()<EOL>to_add = []<EOL>if metabolite_list is not None:<EOL><INDENT>for met in metabolite_list:<EOL><INDENT>to_add += [self.problem.Constraint(<EOL>Zero, name=met.id, lb=<NUM_LIT:0>, ub=<NUM_LIT:0>)]<EOL><DEDENT><DEDENT>self.add_cons_vars(to_add)<EOL>for reaction in reaction_list:<EOL><INDENT>if reaction.id not in self.variables:<EOL><INDENT>forward_variable = self.problem.Variable(reaction.id)<EOL>reverse_variable = self.problem.Variable(reaction.reverse_id)<EOL>self.add_cons_vars([forward_variable, reverse_variable])<EOL><DEDENT>else:<EOL><INDENT>reaction = self.reactions.get_by_id(reaction.id)<EOL>forward_variable = reaction.forward_variable<EOL>reverse_variable = reaction.reverse_variable<EOL><DEDENT>for metabolite, coeff in six.iteritems(reaction.metabolites):<EOL><INDENT>if metabolite.id in self.constraints:<EOL><INDENT>constraint = self.constraints[metabolite.id]<EOL><DEDENT>else:<EOL><INDENT>constraint = self.problem.Constraint(<EOL>Zero,<EOL>name=metabolite.id,<EOL>lb=<NUM_LIT:0>, ub=<NUM_LIT:0>)<EOL>self.add_cons_vars(constraint, sloppy=True)<EOL><DEDENT>constraint_terms[constraint][forward_variable] = coeff<EOL>constraint_terms[constraint][reverse_variable] = -coeff<EOL><DEDENT><DEDENT>self.solver.update()<EOL>for reaction in reaction_list:<EOL><INDENT>reaction = self.reactions.get_by_id(reaction.id)<EOL>reaction.update_variable_bounds()<EOL><DEDENT>for constraint, terms in six.iteritems(constraint_terms):<EOL><INDENT>constraint.set_linear_coefficients(terms)<EOL><DEDENT>

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


def slim_optimize(self, error_value=float('<STR_LIT>'), message=None):

self.solver.optimize()<EOL>if self.solver.status == optlang.interface.OPTIMAL:<EOL><INDENT>return self.solver.objective.value<EOL><DEDENT>elif error_value is not None:<EOL><INDENT>return error_value<EOL><DEDENT>else:<EOL><INDENT>assert_optimal(self, message)<EOL><DEDENT>

Optimize model without creating a solution object.

        Creating a full solution object implies fetching shadow prices and
        flux values for all reactions and metabolites from the solver
        object. This necessarily takes some time and in cases where only one
        or two values are of interest, it is recommended to instead use this
        function which does not create a solution object returning only the
        value of the objective. Note however that the `optimize()` function
        uses efficient means to fetch values so if you need fluxes/shadow
        prices for more than say 4 reactions/metabolites, then the total
        speed increase of `slim_optimize` versus `optimize` is  expected to
        be small or even negative depending on how you fetch the values
        after optimization.

        Parameters
        ----------
        error_value : float, None
           The value to return if optimization failed due to e.g.
           infeasibility. If None, raise `OptimizationError` if the
           optimization fails.
        message : string
           Error message to use if the model optimization did not succeed.

        Returns
        -------
        float
            The objective value.


def optimize(self, objective_sense=None, raise_error=False):

original_direction = self.objective.direction<EOL>self.objective.direction ={"<STR_LIT>": "<STR_LIT>", "<STR_LIT>": "<STR_LIT>"}.get(<EOL>objective_sense, original_direction)<EOL>self.slim_optimize()<EOL>solution = get_solution(self, raise_error=raise_error)<EOL>self.objective.direction = original_direction<EOL>return solution<EOL>

Optimize the model using flux balance analysis.

Parameters
----------
objective_sense : {None, 'maximize' 'minimize'}, optional
    Whether fluxes should be maximized or minimized. In case of None,
    the previous direction is used.
raise_error : bool
    If true, raise an OptimizationError if solver status is not
     optimal.

Notes
-----
Only the most commonly used parameters are presented here.  Additional
parameters for cobra.solvers may be available and specified with the
appropriate keyword argument.


def repair(self, rebuild_index=True, rebuild_relationships=True):

if rebuild_index:  <EOL><INDENT>self.reactions._generate_index()<EOL>self.metabolites._generate_index()<EOL>self.genes._generate_index()<EOL>self.groups._generate_index()<EOL><DEDENT>if rebuild_relationships:<EOL><INDENT>for met in self.metabolites:<EOL><INDENT>met._reaction.clear()<EOL><DEDENT>for gene in self.genes:<EOL><INDENT>gene._reaction.clear()<EOL><DEDENT>for rxn in self.reactions:<EOL><INDENT>for met in rxn._metabolites:<EOL><INDENT>met._reaction.add(rxn)<EOL><DEDENT>for gene in rxn._genes:<EOL><INDENT>gene._reaction.add(rxn)<EOL><DEDENT><DEDENT><DEDENT>for l in (self.reactions, self.genes, self.metabolites, self.groups):<EOL><INDENT>for e in l:<EOL><INDENT>e._model = self<EOL><DEDENT><DEDENT>

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.


return self.solver.objective<EOL>

Get or set the solver objective

        Before introduction of the optlang based problems,
        this function returned the objective reactions as a list. With
        optlang, the objective is not limited a simple linear summation of
        individual reaction fluxes, making that return value ambiguous.
        Henceforth, use `cobra.util.solver.linear_reaction_coefficients` to
        get a dictionary of reactions with their linear coefficients (empty
        if there are none)

        The set value can be dictionary (reactions as keys, linear
        coefficients as values), string (reaction identifier), int (reaction
        index), Reaction or problem.Objective or sympy expression
        directly interpreted as objectives.

        When using a `HistoryManager` context, this attribute can be set
        temporarily, reversed when the exiting the context.


return self.solver.objective.direction<EOL>

Get or set the objective direction.

When using a `HistoryManager` context, this attribute can be set
temporarily, reversed when exiting the context.


def summary(self, solution=None, threshold=<NUM_LIT>, fva=None, names=False,<EOL>floatfmt='<STR_LIT>'):

from cobra.flux_analysis.summary import model_summary<EOL>return model_summary(self, solution=solution, threshold=threshold,<EOL>fva=fva, names=names, floatfmt=floatfmt)<EOL>

Print a summary of the input and output fluxes of the model.

Parameters
----------
solution: cobra.Solution, optional
    A previously solved model solution to use for generating the
    summary. If none provided (default), the summary method will
    resolve the model. Note that the solution object must match the
    model, i.e., changes to the model such as changed bounds,
    added or removed reactions are not taken into account by this
    method.
threshold : float, optional
    Threshold below which fluxes are not reported.
fva : pandas.DataFrame, float or None, 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.
names : bool, optional
    Emit reaction and metabolite names rather than identifiers (default
    False).
floatfmt : string, optional
    Format string for floats (default '.3g').


<EOL>try:<EOL><INDENT>self._contexts.append(HistoryManager())<EOL><DEDENT>except AttributeError:<EOL><INDENT>self._contexts = [HistoryManager()]<EOL><DEDENT>return self<EOL>

Record all future changes to the model, undoing them when a call to
        __exit__ is received


def __exit__(self, type, value, traceback):

context = self._contexts.pop()<EOL>context.reset()<EOL>

Pop the top context manager and trigger the undo functions


def merge(self, right, prefix_existing=None, inplace=True,<EOL>objective='<STR_LIT:left>'):

if inplace:<EOL><INDENT>new_model = self<EOL><DEDENT>else:<EOL><INDENT>new_model = self.copy()<EOL>new_model.id = '<STR_LIT>'.format(self.id, right.id)<EOL><DEDENT>new_reactions = deepcopy(right.reactions)<EOL>if prefix_existing is not None:<EOL><INDENT>existing = new_reactions.query(<EOL>lambda rxn: rxn.id in self.reactions)<EOL>for reaction in existing:<EOL><INDENT>reaction.id = '<STR_LIT>'.format(prefix_existing, reaction.id)<EOL><DEDENT><DEDENT>new_model.add_reactions(new_reactions)<EOL>interface = new_model.problem<EOL>new_vars = [interface.Variable.clone(v) for v in right.variables if<EOL>v.name not in new_model.variables]<EOL>new_model.add_cons_vars(new_vars)<EOL>new_cons = [interface.Constraint.clone(c, model=new_model.solver)<EOL>for c in right.constraints if<EOL>c.name not in new_model.constraints]<EOL>new_model.add_cons_vars(new_cons, sloppy=True)<EOL>new_model.objective = dict(<EOL>left=self.objective,<EOL>right=right.objective,<EOL>sum=self.objective.expression + right.objective.expression<EOL>)[objective]<EOL>return new_model<EOL>

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.

        right : cobra.Model
            The model to add reactions from
        prefix_existing : string
            Prefix the reaction identifier in the right that already exist
            in the left model with this string.
        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.
        objective : string
            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.


def __init__(self, id=None, name="<STR_LIT>"):

self._id = id<EOL>self.name = name<EOL>self.notes = {}<EOL>self.annotation = {}<EOL>

A simple object with an identifier

        Parameters
        ----------
        id: None or a string
            the identifier to associate with the object


state = self.__dict__.copy()<EOL>if '<STR_LIT>' in state:<EOL><INDENT>state['<STR_LIT>'] = None<EOL><DEDENT>return state<EOL>

To prevent excessive replication during deepcopy.


if self.model is not None:<EOL><INDENT>return self.model.constraints[self.id]<EOL><DEDENT>

Get the constraints associated with this metabolite from the solve

        Returns
        -------
        optlang.<interface>.Constraint
            the optlang constraint for this metabolite


tmp_formula = self.formula<EOL>if tmp_formula is None:<EOL><INDENT>return {}<EOL><DEDENT>tmp_formula = str(self.formula)<EOL>if "<STR_LIT:*>" in tmp_formula:<EOL><INDENT>warn("<STR_LIT>" % self.formula)<EOL>tmp_formula = tmp_formula.replace("<STR_LIT:*>", "<STR_LIT>")<EOL><DEDENT>if "<STR_LIT:(>" in tmp_formula or "<STR_LIT:)>" in tmp_formula:<EOL><INDENT>warn("<STR_LIT>" % self.formula)<EOL>return None<EOL><DEDENT>composition = {}<EOL>parsed = element_re.findall(tmp_formula)<EOL>for (element, count) in parsed:<EOL><INDENT>if count == '<STR_LIT>':<EOL><INDENT>count = <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>count = float(count)<EOL>int_count = int(count)<EOL>if count == int_count:<EOL><INDENT>count = int_count<EOL><DEDENT>else:<EOL><INDENT>warn("<STR_LIT>" %<EOL>(count, self.formula))<EOL><DEDENT><DEDENT>except ValueError:<EOL><INDENT>warn("<STR_LIT>" %<EOL>(count, self.formula))<EOL>return None<EOL><DEDENT><DEDENT>if element in composition:<EOL><INDENT>composition[element] += count<EOL><DEDENT>else:<EOL><INDENT>composition[element] = count<EOL><DEDENT><DEDENT>return composition<EOL>

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


try:<EOL><INDENT>return sum([count * elements_and_molecular_weights[element]<EOL>for element, count in self.elements.items()])<EOL><DEDENT>except KeyError as e:<EOL><INDENT>warn("<STR_LIT>" % e)<EOL><DEDENT>


warn("<STR_LIT>", DeprecationWarning)<EOL>return self.shadow_price<EOL>

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.


try:<EOL><INDENT>check_solver_status(self._model.solver.status)<EOL>return self._model.constraints[self.id].dual<EOL><DEDENT>except AttributeError:<EOL><INDENT>raise RuntimeError(<EOL>"<STR_LIT>".format(self.id))<EOL><DEDENT>except (RuntimeError, OptimizationError) as err:<EOL><INDENT>raise_with_traceback(err)<EOL><DEDENT>except Exception as err:<EOL><INDENT>raise_from(OptimizationError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(str(err))), err)<EOL><DEDENT>

The shadow price in the most recent solution.

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

Warnings
--------
* 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
--------
>>> import cobra
>>> import cobra.test
>>> model = cobra.test.create_test_model("textbook")
>>> solution = model.optimize()
>>> model.metabolites.glc__D_e.shadow_price
-0.09166474637510488
>>> solution.shadow_prices.glc__D_e
-0.091664746375104883


self._model.remove_metabolites(self, destructive)<EOL>

Removes the association from self.model

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

        Parameters
        ----------
        destructive : bool
            If False then the metabolite is removed from all
            associated reactions.  If True then all associated
            reactions are removed from the Model.


from cobra.flux_analysis.summary import metabolite_summary<EOL>return metabolite_summary(self, solution=solution, threshold=threshold,<EOL>fva=fva, names=names, floatfmt=floatfmt)<EOL>

Print a summary of the production and consumption fluxes.

This method requires the model for which this metabolite is a part
to be solved.

Parameters
----------
solution : cobra.Solution, optional
    A previously solved model solution to use for generating the
    summary. If none provided (default), the summary method will
    resolve the model. Note that the solution object must match the
    model, i.e., changes to the model such as changed bounds,
    added or removed reactions are not taken into account by this
    method.
threshold : float, optional
    Threshold below which fluxes are not reported.
fva : pandas.DataFrame, float or None, 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.
names : bool, optional
    Emit reaction and metabolite names rather than identifiers (default
    False).
floatfmt : string, optional
    Format string for floats (default '.3g').


if cls not in cls._instances:<EOL><INDENT>cls._instances[cls] = super(Singleton, cls).__call__(*args,<EOL>**kwargs)<EOL><DEDENT>return cls._instances[cls]<EOL>


state = Object.__getstate__(self)<EOL>state['<STR_LIT>'] = set()<EOL>return state<EOL>

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


return deepcopy(self)<EOL>

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


def ast2str(expr, level=<NUM_LIT:0>, names=None):

if isinstance(expr, Expression):<EOL><INDENT>return ast2str(expr.body, <NUM_LIT:0>, names)if hasattr(expr, "<STR_LIT:body>") else "<STR_LIT>"<EOL><DEDENT>elif isinstance(expr, Name):<EOL><INDENT>return names.get(expr.id, expr.id) if names else expr.id<EOL><DEDENT>elif isinstance(expr, BoolOp):<EOL><INDENT>op = expr.op<EOL>if isinstance(op, Or):<EOL><INDENT>str_exp = "<STR_LIT>".join(ast2str(i, level + <NUM_LIT:1>, names)<EOL>for i in expr.values)<EOL><DEDENT>elif isinstance(op, And):<EOL><INDENT>str_exp = "<STR_LIT>".join(ast2str(i, level + <NUM_LIT:1>, names)<EOL>for i in expr.values)<EOL><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>" + op.__class__.__name)<EOL><DEDENT>return "<STR_LIT:(>" + str_exp + "<STR_LIT:)>" if level else str_exp<EOL><DEDENT>elif expr is None:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>" + repr(expr))<EOL><DEDENT>

convert compiled ast to gene_reaction_rule str

    Parameters
    ----------
    expr : str
        string for a gene reaction rule, e.g "a and b"
    level : int
        internal use only
    names : dict
        Dict where each element id a gene identifier and the value is the
        gene name. Use this to get a rule str which uses names instead. This
        should be done for display purposes only. All gene_reaction_rule
        strings which are computed with should use the id.

    Returns
    ------
    string
        The gene reaction rule


if isinstance(expr, Expression):<EOL><INDENT>return eval_gpr(expr.body, knockouts)<EOL><DEDENT>elif isinstance(expr, Name):<EOL><INDENT>return expr.id not in knockouts<EOL><DEDENT>elif isinstance(expr, BoolOp):<EOL><INDENT>op = expr.op<EOL>if isinstance(op, Or):<EOL><INDENT>return any(eval_gpr(i, knockouts) for i in expr.values)<EOL><DEDENT>elif isinstance(op, And):<EOL><INDENT>return all(eval_gpr(i, knockouts) for i in expr.values)<EOL><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>" + op.__class__.__name__)<EOL><DEDENT><DEDENT>elif expr is None:<EOL><INDENT>return True<EOL><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>" + repr(expr))<EOL><DEDENT>

evaluate compiled ast of gene_reaction_rule with knockouts

    Parameters
    ----------
    expr : Expression
        The ast of the gene reaction rule
    knockouts : DictList, set
        Set of genes that are knocked out

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


str_expr = str_expr.strip()<EOL>if len(str_expr) == <NUM_LIT:0>:<EOL><INDENT>return None, set()<EOL><DEDENT>for char, escaped in replacements:<EOL><INDENT>if char in str_expr:<EOL><INDENT>str_expr = str_expr.replace(char, escaped)<EOL><DEDENT><DEDENT>escaped_str = keyword_re.sub("<STR_LIT>", str_expr)<EOL>escaped_str = number_start_re.sub("<STR_LIT>", escaped_str)<EOL>tree = ast_parse(escaped_str, "<STR_LIT>", "<STR_LIT>")<EOL>cleaner = GPRCleaner()<EOL>cleaner.visit(tree)<EOL>eval_gpr(tree, set())  <EOL>return tree, cleaner.gene_set<EOL>

parse gpr into AST

    Parameters
    ----------
    str_expr : string
        string with the gene reaction rule to parse

    Returns
    -------
    tuple
        elements ast_tree and gene_ids as a set


return self._functional<EOL>

A flag indicating if the gene is functional.

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


self.functional = False<EOL>for reaction in self.reactions:<EOL><INDENT>if not reaction.functional:<EOL><INDENT>reaction.bounds = (<NUM_LIT:0>, <NUM_LIT:0>)<EOL><DEDENT><DEDENT>

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.


warn("<STR_LIT>")<EOL>if model is not None:<EOL><INDENT>if model != self._model:<EOL><INDENT>raise Exception("<STR_LIT>" %<EOL>(repr(self), repr(self._model), repr(model)))<EOL><DEDENT><DEDENT>if self._model is None:<EOL><INDENT>raise Exception('<STR_LIT>' % repr(self))<EOL><DEDENT>if make_dependent_reactions_nonfunctional:<EOL><INDENT>gene_state = '<STR_LIT:False>'<EOL><DEDENT>else:<EOL><INDENT>gene_state = '<STR_LIT:True>'<EOL><DEDENT>the_gene_re = re.compile('<STR_LIT>' %<EOL>re.escape(self.id))<EOL>associated_groups = self._model.get_associated_groups(self)<EOL>for group in associated_groups:<EOL><INDENT>group.remove_members(self)<EOL><DEDENT>self._model.genes.remove(self)<EOL>self._model = None<EOL>for the_reaction in list(self._reaction):<EOL><INDENT>the_reaction._gene_reaction_rule = the_gene_re.sub(<EOL>gene_state, the_reaction.gene_reaction_rule)<EOL>the_reaction._genes.remove(self)<EOL>the_gene_reaction_relation = the_reaction.gene_reaction_rule<EOL>for other_gene in the_reaction._genes:<EOL><INDENT>other_gene_re = re.compile('<STR_LIT>' %<EOL>re.escape(other_gene.id))<EOL>the_gene_reaction_relation = other_gene_re.sub(<EOL>'<STR_LIT:True>',<EOL>the_gene_reaction_relation)<EOL><DEDENT>if not eval(the_gene_reaction_relation):<EOL><INDENT>the_reaction.lower_bound = <NUM_LIT:0><EOL>the_reaction.upper_bound = <NUM_LIT:0><EOL><DEDENT><DEDENT>self._reaction.clear()<EOL>

Removes the association

        Parameters
        ----------
        model : cobra model
           The model to remove the gene from
        make_dependent_reactions_nonfunctional : bool
           If True then replace the gene with 'False' in the gene
           association, else replace the gene with 'True'

        .. deprecated :: 0.4
            Use cobra.manipulation.delete_model_genes to simulate knockouts
            and cobra.manipulation.remove_genes to remove genes from
            the model.


def get_solution(model, reactions=None, metabolites=None, raise_error=False):

check_solver_status(model.solver.status, raise_error=raise_error)<EOL>if reactions is None:<EOL><INDENT>reactions = model.reactions<EOL><DEDENT>if metabolites is None:<EOL><INDENT>metabolites = model.metabolites<EOL><DEDENT>rxn_index = list()<EOL>fluxes = empty(len(reactions))<EOL>reduced = empty(len(reactions))<EOL>var_primals = model.solver.primal_values<EOL>shadow = empty(len(metabolites))<EOL>if model.solver.is_integer:<EOL><INDENT>reduced.fill(nan)<EOL>shadow.fill(nan)<EOL>for (i, rxn) in enumerate(reactions):<EOL><INDENT>rxn_index.append(rxn.id)<EOL>fluxes[i] = var_primals[rxn.id] - var_primals[rxn.reverse_id]<EOL><DEDENT>met_index = [met.id for met in metabolites]<EOL><DEDENT>else:<EOL><INDENT>var_duals = model.solver.reduced_costs<EOL>for (i, rxn) in enumerate(reactions):<EOL><INDENT>forward = rxn.id<EOL>reverse = rxn.reverse_id<EOL>rxn_index.append(forward)<EOL>fluxes[i] = var_primals[forward] - var_primals[reverse]<EOL>reduced[i] = var_duals[forward] - var_duals[reverse]<EOL><DEDENT>met_index = list()<EOL>constr_duals = model.solver.shadow_prices<EOL>for (i, met) in enumerate(metabolites):<EOL><INDENT>met_index.append(met.id)<EOL>shadow[i] = constr_duals[met.id]<EOL><DEDENT><DEDENT>return Solution(model.solver.objective.value, model.solver.status,<EOL>Series(index=rxn_index, data=fluxes, name="<STR_LIT>"),<EOL>Series(index=rxn_index, data=reduced,<EOL>name="<STR_LIT>"),<EOL>Series(index=met_index, data=shadow, name="<STR_LIT>"))<EOL>

Generate a solution representation of the current solver state.

Parameters
---------
model : cobra.Model
    The model whose reactions to retrieve values for.
reactions : list, optional
    An iterable of `cobra.Reaction` objects. Uses `model.reactions` by
    default.
metabolites : list, optional
    An iterable of `cobra.Metabolite` objects. Uses `model.metabolites` by
    default.
raise_error : bool
    If true, raise an OptimizationError if solver status is not optimal.

Returns
-------
cobra.Solution

Note
----
This is only intended for the `optlang` solver interfaces and not the
legacy solvers.


def __init__(self, objective_value, status, fluxes, reduced_costs=None,<EOL>shadow_prices=None, **kwargs):

super(Solution, self).__init__(**kwargs)<EOL>self.objective_value = objective_value<EOL>self.status = status<EOL>self.fluxes = fluxes<EOL>self.reduced_costs = reduced_costs<EOL>self.shadow_prices = shadow_prices<EOL>

Initialize a `Solution` from its components.

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).
shadow_prices : pandas.Series
    Contains metabolite shadow prices (dual values of constraints).


if self.status != OPTIMAL:<EOL><INDENT>return "<STR_LIT>".format(self.status, id(self))<EOL><DEDENT>return "<STR_LIT>".format(self.objective_value,<EOL>id(self))<EOL>

String representation of the solution instance.


return self.fluxes[reaction_id]<EOL>

Return the flux of a reaction.

Parameters
----------
reaction : str
    A model reaction ID.


return DataFrame({'<STR_LIT>': self.fluxes,<EOL>'<STR_LIT>': self.reduced_costs})<EOL>

Return the fluxes and reduced costs as a data frame


def __init__(self, f, x=None, x_dict=None, y=None, y_dict=None,<EOL>solver=None, the_time=<NUM_LIT:0>, status='<STR_LIT>', **kwargs):

super(LegacySolution, self).__init__(**kwargs)<EOL>self.solver = solver<EOL>self.f = f<EOL>self.x = x<EOL>self.x_dict = x_dict<EOL>self.status = status<EOL>self.y = y<EOL>self.y_dict = y_dict<EOL>

Initialize a `LegacySolution` from an objective value.

Parameters
----------
f : float
    Objective value.
solver : str, optional
    A string indicating which solver package was used.
x : iterable, optional
    List or Array of the fluxes (primal values).
x_dict : dict, optional
    A dictionary of reaction IDs that maps to the respective primal
    values.
y : iterable, optional
    List or Array of the dual values.
y_dict : dict, optional
    A dictionary of reaction IDs that maps to the respective dual
    values.
the_time : int, optional
status : str, optional

.. warning :: deprecated


if self.status != "<STR_LIT>":<EOL><INDENT>return "<STR_LIT>".format(<EOL>self.status, id(self))<EOL><DEDENT>return "<STR_LIT>".format(<EOL>self.f, id(self))<EOL>


return self.x_dict[reaction_id]<EOL>

Return the flux of a reaction.

Parameters
----------
reaction_id : str
    A reaction ID.


warn("<STR_LIT>",<EOL>DeprecationWarning)<EOL>

Method could be intended as a decorator.

.. warning :: deprecated


new_out, new_err = StringIO(), StringIO()<EOL>old_out, old_err = sys.stdout, sys.stderr<EOL>try:<EOL><INDENT>sys.stdout, sys.stderr = new_out, new_err<EOL>yield sys.stdout, sys.stderr<EOL><DEDENT>finally:<EOL><INDENT>sys.stdout, sys.stderr = old_out, old_err<EOL><DEDENT>

A context manager to test the IO summary methods.


output_set = set(<EOL>pattern.sub("<STR_LIT>", line) for line in output.splitlines())<EOL>for elem in expected_entries:<EOL><INDENT>assert pattern.sub("<STR_LIT>", elem) in output_set<EOL><DEDENT>

Ensure each expected entry is in the output.


output_strip = [pattern.sub("<STR_LIT>", line) for line in<EOL>output.splitlines()]<EOL>for elem in expected_entries:<EOL><INDENT>assert any(<EOL>pattern.sub("<STR_LIT>", elem) in line for line in output_strip),"<STR_LIT>".format(pattern.sub("<STR_LIT>", elem),<EOL>"<STR_LIT:\n>".join(output_strip))<EOL><DEDENT>

Ensure each expected entry is contained in the output.


return ex1.simplify() == ex2.simplify()<EOL>

Compare to expressions for mathematical equality.


assert len(model_1.reactions) == len(model_2.reactions)<EOL>assert len(model_1.metabolites) == len(model_2.metabolites)<EOL>assert len(model_1.genes) == len(model_2.genes)<EOL>assert model_1.objective.direction == model_2.objective.direction<EOL>for attr in ("<STR_LIT:id>", "<STR_LIT:name>", "<STR_LIT>", "<STR_LIT>",<EOL>"<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>assert getattr(model_1.reactions[<NUM_LIT:0>], attr) == getattr(<EOL>model_2.reactions[<NUM_LIT:0>], attr)<EOL>assert getattr(model_1.reactions[<NUM_LIT:5>], attr) == getattr(<EOL>model_2.reactions[<NUM_LIT:5>], attr)<EOL>assert getattr(model_1.reactions[-<NUM_LIT:1>], attr) == getattr(<EOL>model_2.reactions[-<NUM_LIT:1>], attr)<EOL><DEDENT>for attr in ("<STR_LIT:id>", "<STR_LIT:name>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>assert getattr(model_1.metabolites[<NUM_LIT:0>], attr) == getattr(<EOL>model_2.metabolites[<NUM_LIT:0>], attr)<EOL>assert getattr(model_1.metabolites[<NUM_LIT:5>], attr) == getattr(<EOL>model_2.metabolites[<NUM_LIT:5>], attr)<EOL>assert getattr(model_1.metabolites[-<NUM_LIT:1>], attr) == getattr(<EOL>model_2.metabolites[-<NUM_LIT:1>], attr)<EOL>assert len(model_1.reactions[<NUM_LIT:0>].metabolites) == len(<EOL>model_2.reactions[<NUM_LIT:0>].metabolites)<EOL><DEDENT>assert len(model_1.reactions[<NUM_LIT:8>].metabolites) == len(<EOL>model_2.reactions[<NUM_LIT:8>].metabolites)<EOL>assert len(model_1.reactions[-<NUM_LIT:1>].metabolites) == len(<EOL>model_2.reactions[-<NUM_LIT:1>].metabolites)<EOL>assert len(model_1.genes) == len(model_2.genes)<EOL>solution_1 = model_1.optimize()<EOL>solution_2 = model_2.optimize()<EOL>assert abs(solution_1.objective_value -<EOL>solution_2.objective_value) == pytest.approx(<NUM_LIT:0.0>)<EOL>assert model_1.metabolites[<NUM_LIT:0>]._model is model_1<EOL>assert model_2.metabolites[<NUM_LIT:0>]._model is model_2<EOL>assert model_1.reactions[<NUM_LIT:0>]._model is model_1<EOL>assert model_2.reactions[<NUM_LIT:0>]._model is model_2<EOL>assert model_1.genes[<NUM_LIT:0>]._model is model_1<EOL>assert model_2.genes[<NUM_LIT:0>]._model is model_2<EOL>

Compare two models (only for testing purposes).


assert model is not None<EOL>annotation = model.annotation<EOL>assert annotation is not None<EOL>assert len(annotation) == <NUM_LIT:3><EOL>for key in ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>"]:<EOL><INDENT>assert key in annotation<EOL><DEDENT>assert annotation["<STR_LIT>"] == "<STR_LIT>"<EOL>assert annotation["<STR_LIT>"] == "<STR_LIT>"<EOL>assert annotation["<STR_LIT>"] == "<STR_LIT>"<EOL>annotation = model.genes.G1.annotation<EOL>assert len(annotation) == <NUM_LIT:5><EOL>for key in ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"]:<EOL><INDENT>assert key in annotation<EOL><DEDENT>assert annotation["<STR_LIT>"] == "<STR_LIT>"<EOL>assert annotation["<STR_LIT>"] == "<STR_LIT>"<EOL>assert annotation["<STR_LIT>"] == "<STR_LIT>"<EOL>assert annotation["<STR_LIT>"] == "<STR_LIT>"<EOL>assert annotation["<STR_LIT>"] == "<STR_LIT>"<EOL>annotation = model.metabolites.A.annotation<EOL>for key in ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>",<EOL>"<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"]:<EOL><INDENT>assert key in annotation<EOL><DEDENT>assert annotation[<EOL>"<STR_LIT>"] == "<STR_LIT>"  <EOL>annotation = model.reactions.R1.annotation<EOL>for key in ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>",<EOL>"<STR_LIT>", "<STR_LIT>", "<STR_LIT>"]:<EOL><INDENT>assert key in annotation<EOL><DEDENT>assert annotation["<STR_LIT>"] == '<STR_LIT>'<EOL>

Checks the annotations from the annotation.xml.


def production_envelope(model, reactions, objective=None, carbon_sources=None,<EOL>points=<NUM_LIT:20>, threshold=None):

reactions = model.reactions.get_by_any(reactions)<EOL>objective = model.solver.objective if objective is None else objective<EOL>data = dict()<EOL>if carbon_sources is None:<EOL><INDENT>c_input = find_carbon_sources(model)<EOL><DEDENT>else:<EOL><INDENT>c_input = model.reactions.get_by_any(carbon_sources)<EOL><DEDENT>if c_input is None:<EOL><INDENT>data['<STR_LIT>'] = None<EOL><DEDENT>elif hasattr(c_input, '<STR_LIT:id>'):<EOL><INDENT>data['<STR_LIT>'] = c_input.id<EOL><DEDENT>else:<EOL><INDENT>data['<STR_LIT>'] = '<STR_LIT:U+002CU+0020>'.join(rxn.id for rxn in c_input)<EOL><DEDENT>threshold = normalize_cutoff(model, threshold)<EOL>size = points ** len(reactions)<EOL>for direction in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>data['<STR_LIT>'.format(direction)] = full(size, nan, dtype=float)<EOL>data['<STR_LIT>'.format(direction)] = full(<EOL>size, nan, dtype=float)<EOL>data['<STR_LIT>'.format(direction)] = full(<EOL>size, nan, dtype=float)<EOL><DEDENT>grid = pd.DataFrame(data)<EOL>with model:<EOL><INDENT>model.objective = objective<EOL>objective_reactions = list(sutil.linear_reaction_coefficients(model))<EOL>if len(objective_reactions) != <NUM_LIT:1>:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>c_output = objective_reactions[<NUM_LIT:0>]<EOL>min_max = fva(model, reactions, fraction_of_optimum=<NUM_LIT:0>)<EOL>min_max[min_max.abs() < threshold] = <NUM_LIT:0.0><EOL>points = list(product(*[<EOL>linspace(min_max.at[rxn.id, "<STR_LIT>"],<EOL>min_max.at[rxn.id, "<STR_LIT>"],<EOL>points, endpoint=True) for rxn in reactions]))<EOL>tmp = pd.DataFrame(points, columns=[rxn.id for rxn in reactions])<EOL>grid = pd.concat([grid, tmp], axis=<NUM_LIT:1>, copy=False)<EOL>add_envelope(model, reactions, grid, c_input, c_output, threshold)<EOL><DEDENT>return grid<EOL>

Calculate the objective value conditioned on all combinations of
    fluxes for a set of chosen reactions

    The production envelope can be used to analyze a model's ability to
    produce a given compound conditional on the fluxes for another set of
    reactions, such as the uptake rates. The model is alternately optimized
    with respect to minimizing and maximizing the objective and the
    obtained fluxes are recorded. Ranges to compute production is set to the
    effective
    bounds, i.e., the minimum / maximum fluxes that can be obtained given
    current reaction bounds.

    Parameters
    ----------
    model : cobra.Model
        The model to compute the production envelope for.
    reactions : list or string
        A list of reactions, reaction identifiers or a single reaction.
    objective : string, dict, model.solver.interface.Objective, optional
        The objective (reaction) to use for the production envelope. Use the
        model's current objective if left missing.
    carbon_sources : list or string, optional
       One or more reactions or reaction identifiers that are the source of
       carbon for computing carbon (mol carbon in output over mol carbon in
       input) and mass yield (gram product over gram output). Only objectives
       with a carbon containing input and output metabolite is supported.
       Will identify active carbon sources in the medium if none are specified.
    points : int, optional
       The number of points to calculate production for.
    threshold : float, optional
        A cut-off under which flux values will be considered to be zero
        (default model.tolerance).

    Returns
    -------
    pandas.DataFrame
        A data frame with one row per evaluated point and

        - reaction id : one column per input reaction indicating the flux at
          each given point,
        - carbon_source: identifiers of carbon exchange reactions

        A column for the maximum and minimum each for the following types:

        - flux: the objective flux
        - carbon_yield: if carbon source is defined and the product is a
          single metabolite (mol carbon product per mol carbon feeding source)
        - mass_yield: if carbon source is defined and the product is a
          single metabolite (gram product per 1 g of feeding source)

    Examples
    --------
    >>> import cobra.test
    >>> from cobra.flux_analysis import production_envelope
    >>> model = cobra.test.create_test_model("textbook")
    >>> production_envelope(model, ["EX_glc__D_e", "EX_o2_e"])


def total_yield(input_fluxes, input_elements, output_flux, output_elements):

carbon_input_flux = sum(<EOL>total_components_flux(flux, components, consumption=True)<EOL>for flux, components in zip(input_fluxes, input_elements))<EOL>carbon_output_flux = total_components_flux(<EOL>output_flux, output_elements, consumption=False)<EOL>try:<EOL><INDENT>return carbon_output_flux / carbon_input_flux<EOL><DEDENT>except ZeroDivisionError:<EOL><INDENT>return nan<EOL><DEDENT>

Compute total output per input unit.

Units are typically mol carbon atoms or gram of source and product.

Parameters
----------
input_fluxes : list
    A list of input reaction fluxes in the same order as the
    ``input_components``.
input_elements : list
    A list of reaction components which are in turn list of numbers.
output_flux : float
    The output flux value.
output_elements : list
    A list of stoichiometrically weighted output reaction components.

Returns
-------
float
    The ratio between output (mol carbon atoms or grams of product) and
    input (mol carbon atoms or grams of source compounds).


c_elements = [coeff * met.elements.get('<STR_LIT:C>', <NUM_LIT:0>)<EOL>for met, coeff in iteritems(reaction.metabolites)]<EOL>return [elem for elem in c_elements if elem != <NUM_LIT:0>]<EOL>

Split metabolites into the atoms times their stoichiometric coefficients.

Parameters
----------
reaction : Reaction
    The metabolic reaction whose components are desired.

Returns
-------
list
    Each of the reaction's metabolites' desired carbon elements (if any)
    times that metabolite's stoichiometric coefficient.


if len(reaction.metabolites) != <NUM_LIT:1>:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>met, coeff = next(iteritems(reaction.metabolites))<EOL>return [coeff * met.formula_weight]<EOL>

Return the metabolite weight times its stoichiometric coefficient.


def total_components_flux(flux, components, consumption=True):

direction = <NUM_LIT:1> if consumption else -<NUM_LIT:1><EOL>c_flux = [elem * flux * direction for elem in components]<EOL>return sum([flux for flux in c_flux if flux > <NUM_LIT:0>])<EOL>

Compute the total components consumption or production flux.

Parameters
----------
flux : float
    The reaction flux for the components.
components : list
    List of stoichiometrically weighted components.
consumption : bool, optional
    Whether to sum up consumption or production fluxes.


try:<EOL><INDENT>model.slim_optimize(error_value=None)<EOL><DEDENT>except OptimizationError:<EOL><INDENT>return []<EOL><DEDENT>reactions = model.reactions.get_by_any(list(model.medium))<EOL>reactions_fluxes = [<EOL>(rxn, total_components_flux(rxn.flux, reaction_elements(rxn),<EOL>consumption=True)) for rxn in reactions]<EOL>return [rxn for rxn, c_flux in reactions_fluxes if c_flux > <NUM_LIT:0>]<EOL>

Find all active carbon source reactions.

Parameters
----------
model : Model
    A genome-scale metabolic model.

Returns
-------
list
   The medium reactions with carbon input flux.


def assess(model, reaction, flux_coefficient_cutoff=<NUM_LIT>, solver=None):

reaction = model.reactions.get_by_any(reaction)[<NUM_LIT:0>]<EOL>with model as m:<EOL><INDENT>m.objective = reaction<EOL>if _optimize_or_value(m, solver=solver) >= flux_coefficient_cutoff:<EOL><INDENT>return True<EOL><DEDENT>else:<EOL><INDENT>results = dict()<EOL>results['<STR_LIT>'] = assess_component(<EOL>model, reaction, '<STR_LIT>', flux_coefficient_cutoff)<EOL>results['<STR_LIT>'] = assess_component(<EOL>model, reaction, '<STR_LIT>', flux_coefficient_cutoff)<EOL>return results<EOL><DEDENT><DEDENT>

Assesses production capacity.

    Assesses the capacity of the model to produce the precursors for the
    reaction and absorb the production of the reaction while the reaction is
    operating at, or above, the specified cutoff.

    Parameters
    ----------
    model : cobra.Model
        The cobra model to assess production capacity for

    reaction : reaction identifier or cobra.Reaction
        The reaction to assess

    flux_coefficient_cutoff :  float
        The minimum flux that reaction must carry to be considered active.

    solver : basestring
        Solver name. If None, the default solver will be used.

    Returns
    -------
    bool or dict
        True if the model can produce the precursors and absorb the products
        for the reaction operating at, or above, flux_coefficient_cutoff.
        Otherwise, a dictionary of {'precursor': Status, 'product': Status}.
        Where Status is the results from assess_precursors and
        assess_products, respectively.


def assess_component(model, reaction, side, flux_coefficient_cutoff=<NUM_LIT>,<EOL>solver=None):

reaction = model.reactions.get_by_any(reaction)[<NUM_LIT:0>]<EOL>result_key = dict(reactants='<STR_LIT>', products='<STR_LIT>')[side]<EOL>get_components = attrgetter(side)<EOL>with model as m:<EOL><INDENT>m.objective = reaction<EOL>if _optimize_or_value(m, solver=solver) >= flux_coefficient_cutoff:<EOL><INDENT>return True<EOL><DEDENT>simulation_results = {}<EOL>demand_reactions = {}<EOL>for component in get_components(reaction):<EOL><INDENT>coeff = reaction.metabolites[component]<EOL>demand = m.add_boundary(component, type='<STR_LIT>')<EOL>demand.metabolites[component] = coeff<EOL>demand_reactions[demand] = (component, coeff)<EOL><DEDENT>joint_demand = Reaction("<STR_LIT>")<EOL>for demand_reaction in demand_reactions:<EOL><INDENT>joint_demand += demand_reaction<EOL><DEDENT>m.add_reactions([joint_demand])<EOL>m.objective = joint_demand<EOL>if _optimize_or_value(m, solver=solver) >= flux_coefficient_cutoff:<EOL><INDENT>return True<EOL><DEDENT>for demand_reaction, (component, coeff) in iteritems(demand_reactions):<EOL><INDENT>with m:<EOL><INDENT>m.objective = demand_reaction<EOL>flux = _optimize_or_value(m, solver=solver)<EOL><DEDENT>if flux_coefficient_cutoff > flux:<EOL><INDENT>simulation_results.update({<EOL>component: {<EOL>'<STR_LIT>': flux_coefficient_cutoff / abs(coeff),<EOL>result_key: flux / abs(coeff)<EOL>}})<EOL><DEDENT><DEDENT>if len(simulation_results) == <NUM_LIT:0>:<EOL><INDENT>simulation_results = False<EOL><DEDENT>return simulation_results<EOL><DEDENT>

Assesses the ability of the model to provide sufficient precursors,
    or absorb products, for a reaction operating at, or beyond,
    the specified cutoff.

    Parameters
    ----------
    model : cobra.Model
        The cobra model to assess production capacity for

    reaction : reaction identifier or cobra.Reaction
        The reaction to assess

    side : basestring
        Side of the reaction, 'products' or 'reactants'

    flux_coefficient_cutoff :  float
        The minimum flux that reaction must carry to be considered active.

    solver : basestring
        Solver name. If None, the default solver will be used.

    Returns
    -------
    bool or dict
        True if the precursors can be simultaneously produced at the
        specified cutoff. False, if the model has the capacity to produce
        each individual precursor at the specified threshold  but not all
        precursors at the required level simultaneously. Otherwise a
        dictionary of the required and the produced fluxes for each reactant
        that is not produced in sufficient quantities.


def assess_precursors(model, reaction, flux_coefficient_cutoff=<NUM_LIT>,<EOL>solver=None):

warn('<STR_LIT>', DeprecationWarning)<EOL>return assess_component(model, reaction, '<STR_LIT>',<EOL>flux_coefficient_cutoff, solver)<EOL>

Assesses the ability of the model to provide sufficient precursors for
    a reaction operating at, or beyond, the specified cutoff.

    Deprecated: use assess_component instead

    Parameters
    ----------
    model : cobra.Model
        The cobra model to assess production capacity for

    reaction : reaction identifier or cobra.Reaction
        The reaction to assess

    flux_coefficient_cutoff :  float
        The minimum flux that reaction must carry to be considered active.

    solver : basestring
        Solver name. If None, the default solver will be used.

    Returns
    -------
    bool or dict
        True if the precursors can be simultaneously produced at the
        specified cutoff. False, if the model has the capacity to produce
        each individual precursor at the specified threshold  but not all
        precursors at the required level simultaneously. Otherwise a
        dictionary of the required and the produced fluxes for each reactant
        that is not produced in sufficient quantities.


def assess_products(model, reaction, flux_coefficient_cutoff=<NUM_LIT>,<EOL>solver=None):

Assesses whether the model has the capacity to absorb the products of
    a reaction at a given flux rate.

    Useful for identifying which components might be blocking a reaction
    from achieving a specific flux rate.

    Deprecated: use assess_component instead

    Parameters
    ----------
    model : cobra.Model
        The cobra model to assess production capacity for

    reaction : reaction identifier or cobra.Reaction
        The reaction to assess

    flux_coefficient_cutoff :  float
        The minimum flux that reaction must carry to be considered active.

    solver : basestring
        Solver name. If None, the default solver will be used.

    Returns
    -------
    bool or dict
        True if the model has the capacity to absorb all the reaction
        products being simultaneously given the specified cutoff.   False,
        if the model has the capacity to absorb each individual product but
        not all products at the required level simultaneously.   Otherwise a
        dictionary of the required and the capacity fluxes for each product
        that is not absorbed in sufficient quantities.


def geometric_fba(model, epsilon=<NUM_LIT>, max_tries=<NUM_LIT:200>, processes=None):

with model:<EOL><INDENT>consts = []<EOL>obj_vars = []<EOL>updating_vars_cons = []<EOL>prob = model.problem<EOL>add_pfba(model)  <EOL>model.optimize()<EOL>fva_sol = flux_variability_analysis(model, processes=processes)<EOL>mean_flux = (fva_sol["<STR_LIT>"] + fva_sol["<STR_LIT>"]).abs() / <NUM_LIT:2><EOL>for rxn in model.reactions:<EOL><INDENT>var = prob.Variable("<STR_LIT>" + rxn.id,<EOL>lb=<NUM_LIT:0>,<EOL>ub=mean_flux[rxn.id])<EOL>upper_const = prob.Constraint(rxn.flux_expression - var,<EOL>ub=mean_flux[rxn.id],<EOL>name="<STR_LIT>" +<EOL>rxn.id)<EOL>lower_const = prob.Constraint(rxn.flux_expression + var,<EOL>lb=fva_sol.at[rxn.id, "<STR_LIT>"],<EOL>name="<STR_LIT>" +<EOL>rxn.id)<EOL>updating_vars_cons.append((rxn.id, var, upper_const, lower_const))<EOL>consts.extend([var, upper_const, lower_const])<EOL>obj_vars.append(var)<EOL><DEDENT>model.add_cons_vars(consts)<EOL>model.objective = prob.Objective(Zero, sloppy=True, direction="<STR_LIT>")<EOL>model.objective.set_linear_coefficients({v: <NUM_LIT:1.0> for v in obj_vars})<EOL>sol = model.optimize()<EOL>fva_sol = flux_variability_analysis(model, processes=processes)<EOL>mean_flux = (fva_sol["<STR_LIT>"] + fva_sol["<STR_LIT>"]).abs() / <NUM_LIT:2><EOL>delta = (fva_sol["<STR_LIT>"] - fva_sol["<STR_LIT>"]).max()<EOL>count = <NUM_LIT:1><EOL>LOGGER.debug("<STR_LIT>",<EOL>count, delta, sol.status)<EOL>while delta > epsilon and count < max_tries:<EOL><INDENT>for rxn_id, var, u_c, l_c in updating_vars_cons:<EOL><INDENT>var.ub = mean_flux[rxn_id]<EOL>u_c.ub = mean_flux[rxn_id]<EOL>l_c.lb = fva_sol.at[rxn_id, "<STR_LIT>"]<EOL><DEDENT>sol = model.optimize()<EOL>fva_sol = flux_variability_analysis(model, processes=processes)<EOL>mean_flux = (fva_sol["<STR_LIT>"] + fva_sol["<STR_LIT>"]).abs() / <NUM_LIT:2><EOL>delta = (fva_sol["<STR_LIT>"] - fva_sol["<STR_LIT>"]).max()<EOL>count += <NUM_LIT:1><EOL>LOGGER.debug("<STR_LIT>",<EOL>count, delta, sol.status)<EOL><DEDENT>if count == max_tries:<EOL><INDENT>raise RuntimeError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(max_tries)<EOL>)<EOL><DEDENT><DEDENT>return sol<EOL>

Perform geometric FBA to obtain a unique, centered flux distribution.

Geometric FBA [1]_ formulates the problem as a polyhedron and
then solves it by bounding the convex hull of the polyhedron.
The bounding forms a box around the convex hull which reduces
with every iteration and extracts a unique solution in this way.

Parameters
----------
model: cobra.Model
    The model to perform geometric FBA on.
epsilon: float, optional
    The convergence tolerance of the model (default 1E-06).
max_tries: int, optional
    Maximum number of iterations (default 200).
processes : int, optional
    The number of parallel processes to run. If not explicitly passed,
    will be set from the global configuration singleton.

Returns
-------
cobra.Solution
    The solution object containing all the constraints required
    for geometric FBA.

References
----------
.. [1] Smallbone, Kieran & Simeonidis, Vangelis. (2009).
       Flux balance analysis: A geometric perspective.
       Journal of theoretical biology.258. 311-5.
       10.1016/j.jtbi.2009.01.027.


def _init_worker(model, loopless, sense):

global _model<EOL>global _loopless<EOL>_model = model<EOL>_model.solver.objective.direction = sense<EOL>_loopless = loopless<EOL>

Initialize a global model object for multiprocessing.