def Func(arg_0, arg_1):
        """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 existing_filter(arg_2):
            if arg_2.id in arg_0.reactions:
                LOGGER.warning(
                    "Ignoring reaction '%s' since it already exists.", arg_2.id)
                return False
            return True

        # First check whether the reactions exist in the model.
        arg_3 = DictList(filter(existing_filter, arg_1))

        arg_4 = get_context(arg_0)

        # Add reactions. Also take care of genes and metabolites in the loop.
        for arg_5 in arg_3:
            arg_5._model = arg_0
            # Build a `list()` because the dict will be modified in the loop.
            for arg_7 in list(arg_5.metabolites):
                # TODO: Should we add a copy of the metabolite instead?
                if arg_7 not in arg_0.metabolites:
                    arg_0.add_metabolites(arg_7)
                # A copy of the metabolite exists in the model, the reaction
                # needs to point to the metabolite in the model.
                else:
                    # FIXME: Modifying 'private' attributes is horrible.
                    arg_8 = arg_5._metabolites.pop(arg_7)
                    arg_9 = arg_0.metabolites.get_by_id(
                        arg_7.id)
                    arg_5._metabolites[arg_9] = arg_8
                    arg_9._reaction.add(arg_5)
                    if arg_4:
                        arg_4(partial(
                            arg_9._reaction.remove, arg_5))

            for arg_11 in list(arg_5._genes):
                # If the gene is not in the model, add it
                if not arg_0.genes.has_id(arg_11.id):
                    arg_0.genes += [arg_11]
                    arg_11._model = arg_0

                    if arg_4:
                        # Remove the gene later
                        arg_4(partial(arg_0.genes.__isub__, [arg_11]))
                        arg_4(partial(setattr, arg_11, '_model', None))

                # Otherwise, make the gene point to the one in the model
                else:
                    arg_12 = arg_0.genes.get_by_id(arg_11.id)
                    if arg_12 is not arg_11:
                        arg_5._dissociate_gene(arg_11)
                        arg_5._associate_gene(arg_12)

        arg_0.reactions += arg_3

        if arg_4:
            arg_4(partial(arg_0.reactions.__isub__, arg_3))

        # from cameo ...
        arg_0._populate_solver(arg_3)


def Func(arg_0, arg_1, arg_2=False):
        """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

        """
        if isinstance(arg_1, string_types) or hasattr(arg_1, "id"):
            warn("need to pass in a list")
            arg_1 = [arg_1]

        arg_3 = get_context(arg_0)

        for arg_4 in arg_1:

            # Make sure the reaction is in the model
            try:
                arg_4 = arg_0.reactions[arg_0.reactions.index(arg_4)]
            except ValueError:
                warn('%s not in %s' % (arg_4, arg_0))

            else:
                arg_5 = arg_4.forward_variable
                arg_6 = arg_4.reverse_variable

                if arg_3:

                    arg_7 = arg_4.objective_coefficient

                    if arg_7 != 0:
                        arg_3(partial(
                            arg_0.solver.objective.set_linear_coefficients,
                            {arg_5: arg_7, arg_6: -arg_7}))

                    arg_3(partial(arg_0._populate_solver, [arg_4]))
                    arg_3(partial(setattr, arg_4, '_model', arg_0))
                    arg_3(partial(arg_0.reactions.add, arg_4))

                arg_0.remove_cons_vars([arg_5, arg_6])
                arg_0.reactions.remove(arg_4)
                arg_4._model = None

                for arg_9 in arg_4._metabolites:
                    if arg_4 in arg_9._reaction:
                        arg_9._reaction.remove(arg_4)
                        if arg_3:
                            arg_3(partial(arg_9._reaction.add, arg_4))
                        if arg_2 and len(arg_9._reaction) == 0:
                            arg_0.remove_metabolites(arg_9)

                for arg_10 in arg_4._genes:
                    if arg_4 in arg_10._reaction:
                        arg_10._reaction.remove(arg_4)
                        if arg_3:
                            arg_3(partial(arg_10._reaction.add, arg_4))

                        if arg_2 and len(arg_10._reaction) == 0:
                            arg_0.genes.remove(arg_10)
                            if arg_3:
                                arg_3(partial(arg_0.genes.add, arg_10))

                # remove reference to the reaction in all groups
                arg_11 = arg_0.get_associated_groups(arg_4)
                for arg_12 in arg_11:
                    arg_12.remove_members(arg_4)


def Func(arg_0, arg_1):
        """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.
        """

        def existing_filter(arg_2):
            if arg_2.id in arg_0.groups:
                LOGGER.warning(
                    "Ignoring group '%s' since it already exists.", arg_2.id)
                return False
            return True

        if isinstance(arg_1, string_types) or \
                hasattr(arg_1, "id"):
            warn("need to pass in a list")
            arg_1 = [arg_1]

        arg_3 = DictList(filter(existing_filter, arg_1))

        for arg_2 in arg_3:
            arg_2._model = arg_0
            for arg_5 in arg_2.members:
                # If the member is not associated with the model, add it
                if isinstance(arg_5, Metabolite):
                    if arg_5 not in arg_0.metabolites:
                        arg_0.add_metabolites([arg_5])
                if isinstance(arg_5, Reaction):
                    if arg_5 not in arg_0.reactions:
                        arg_0.add_reactions([arg_5])
                # TODO(midnighter): `add_genes` method does not exist.
                # if isinstance(member, Gene):
                #     if member not in self.genes:
                #         self.add_genes([member])

            arg_0.groups += [arg_2]


def Func(arg_0, arg_1, arg_2=None):
        """Populate attached solver with constraints and variables that
        model the provided reactions.
        """
        arg_3 = AutoVivification()
        arg_4 = []
        if arg_2 is not None:
            for arg_5 in arg_2:
                arg_4 += [arg_0.problem.Constraint(
                    Zero, name=arg_5.id, lb=0, ub=0)]
        arg_0.add_cons_vars(arg_4)

        for arg_6 in arg_1:
            if arg_6.id not in arg_0.variables:
                arg_7 = arg_0.problem.Variable(arg_6.id)
                arg_8 = arg_0.problem.Variable(arg_6.reverse_id)
                arg_0.add_cons_vars([arg_7, arg_8])
            else:
                arg_6 = arg_0.reactions.get_by_id(arg_6.id)
                arg_7 = arg_6.forward_variable
                arg_8 = arg_6.reverse_variable
            for arg_9, arg_10 in six.iteritems(arg_6.metabolites):
                if arg_9.id in arg_0.constraints:
                    arg_11 = arg_0.constraints[arg_9.id]
                else:
                    arg_11 = arg_0.problem.Constraint(
                        Zero,
                        name=arg_9.id,
                        lb=0, ub=0)
                    arg_0.add_cons_vars(arg_11, sloppy=True)
                arg_3[arg_11][arg_7] = arg_10
                arg_3[arg_11][arg_8] = -arg_10

        arg_0.solver.update()
        for arg_6 in arg_1:
            arg_6 = arg_0.reactions.get_by_id(arg_6.id)
            arg_6.update_variable_bounds()
        for arg_11, arg_12 in six.iteritems(arg_3):
            arg_11.set_linear_coefficients(arg_12)


def Func(arg_0, arg_1=arg_2('nan'), arg_3=None):
        """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 `Func` 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.
        """
        arg_0.solver.optimize()
        if arg_0.solver.status == optlang.interface.OPTIMAL:
            return arg_0.solver.objective.value
        elif arg_1 is not None:
            return arg_1
        else:
            assert_optimal(arg_0, arg_3)


def Func(arg_0, arg_1=None, arg_2=False):
        """
        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.

        """
        arg_3 = arg_0.objective.direction
        arg_0.objective.direction = \
            {"maximize": "max", "minimize": "min"}.get(
                arg_1, arg_3)
        arg_0.slim_Func()
        arg_6 = get_solution(arg_0, arg_2=arg_2)
        arg_0.objective.direction = arg_3
        return arg_6


def Func(arg_0, arg_1=True, arg_2=True):
        """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.
        """
        if arg_1:  # DictList indexes
            arg_0.reactions._generate_index()
            arg_0.metabolites._generate_index()
            arg_0.genes._generate_index()
            arg_0.groups._generate_index()
        if arg_2:
            for arg_3 in arg_0.metabolites:
                arg_3._reaction.clear()
            for arg_4 in arg_0.genes:
                arg_4._reaction.clear()
            for arg_5 in arg_0.reactions:
                for arg_3 in arg_5._metabolites:
                    arg_3._reaction.add(arg_5)
                for arg_4 in arg_5._genes:
                    arg_4._reaction.add(arg_5)

        # point _model to self
        for arg_6 in (arg_0.reactions, arg_0.genes, arg_0.metabolites, arg_0.groups):
            for arg_7 in arg_6:
                arg_7._model = arg_0


def Func(arg_0, arg_1, arg_2=None, arg_3=True,
              arg_4='left'):
        """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.
        """
        if arg_3:
            arg_5 = arg_0
        else:
            arg_5 = arg_0.copy()
            arg_5.id = '{}_{}'.format(arg_0.id, arg_1.id)
        arg_7 = deepcopy(arg_1.reactions)
        if arg_2 is not None:
            arg_8 = arg_7.query(
                lambda rxn: rxn.id in arg_0.reactions)
            for arg_9 in arg_8:
                arg_9.id = '{}{}'.format(arg_2, arg_9.id)
        arg_5.add_reactions(arg_7)
        arg_10 = arg_5.problem
        arg_11 = [arg_10.Variable.clone(v) for v in arg_1.variables if
                    v.name not in arg_5.variables]
        arg_5.add_cons_vars(arg_11)
        arg_12 = [arg_10.Constraint.clone(c, model=arg_5.solver)
                    for c in arg_1.constraints if
                    c.name not in arg_5.constraints]
        arg_5.add_cons_vars(arg_12, sloppy=True)
        arg_5.objective = dict(
            left=arg_0.objective,
            arg_1=arg_1.objective,
            sum=arg_0.objective.expression + arg_1.objective.expression
        )[arg_4]
        return arg_5


def Func(arg_0):
    """makes all ids SBML compliant"""
    for arg_1 in chain([arg_0],
                   arg_0.metabolites,
                   arg_0.reactions,
                   arg_0.genes):
        arg_1.id = _escape_str_id(arg_1.id)
    arg_0.repair()
    arg_3 = _GeneEscaper()
    for arg_4, arg_5 in iteritems(get_compiled_gene_reaction_rules(arg_0)):
        if arg_5 is not None:
            arg_4._gene_reaction_rule = ast2str(arg_3.visit(arg_5))


def Func(arg_0, arg_1):
    """renames genes in a model from the rename_dict"""
    arg_2 = set()  # need to recomptue related genes
    arg_3 = []
    for arg_4, arg_5 in iteritems(arg_1):
        # undefined if there a value matches a different key
        # because dict is unordered
        try:
            arg_6 = arg_0.genes.index(arg_4)
        except ValueError:
            arg_6 = None
        arg_7 = arg_6 is not None
        arg_8 = arg_5 in arg_0.genes
        if arg_7 and arg_8:
            arg_9 = arg_0.genes.get_by_id(arg_4)
            # Added in case not renaming some genes:
            if arg_9 is not arg_0.genes.get_by_id(arg_5):
                arg_3.append(arg_9)
                arg_2.update(arg_9._reaction)
        elif arg_7 and not arg_8:
            # rename old gene to new gene
            arg_10 = arg_0.genes[arg_6]
            # trick DictList into updating index
            arg_0.genes._dict.pop(arg_10.id)  # ugh
            arg_10.id = arg_5
            arg_0.genes[arg_6] = arg_10
        elif not arg_7 and arg_8:
            pass
        else:  # if not old gene_present and not new_gene_present
            # the new gene's _model will be set by repair
            # This would add genes from rename_dict
            # that are not associated with a rxn
            # cobra_model.genes.append(Gene(new_name))
            pass
    arg_0.repair()

    class Renamer(NodeTransformer):
        def visit_Name(arg_13, arg_14):
            arg_14.id = arg_1.get(arg_14.id, arg_14.id)
            return arg_14

    arg_15 = Renamer()
    for arg_16, arg_17 in iteritems(get_compiled_gene_reaction_rules(arg_0)):
        if arg_17 is not None:
            arg_16._gene_reaction_rule = ast2str(arg_15.visit(arg_17))

    for arg_16 in arg_2:
        arg_16.gene_reaction_rule = arg_16._gene_reaction_rule
    for arg_20 in arg_3:
        arg_0.genes.remove(arg_20)


def Func(arg_0, arg_1=False, **arg_2):
    """
    Return the model as a JSON document.

    ``kwargs`` are passed on to ``json.dumps``.

    Parameters
    ----------
    model : cobra.Model
        The cobra model to represent.
    sort : bool, optional
        Whether to sort the metabolites, reactions, and genes or maintain the
        order defined in the model.

    Returns
    -------
    str
        String representation of the cobra model as a JSON document.

    See Also
    --------
    save_json_model : Write directly to a file.
    json.dumps : Base function.
    """
    arg_3 = model_to_dict(arg_0, arg_1=arg_1)
    arg_3[u"version"] = JSON_SPEC
    return json.dumps(arg_3, allow_nan=False, **arg_2)


def Func(arg_0):
    """
    Load a cobra model from a file in JSON format.

    Parameters
    ----------
    filename : str or file-like
        File path or descriptor that contains the JSON document describing the
        cobra model.

    Returns
    -------
    cobra.Model
        The cobra model as represented in the JSON document.

    See Also
    --------
    from_json : Load from a string.
    """
    if isinstance(arg_0, string_types):
        with open(arg_0, "r") as file_handle:
            return model_from_dict(json.load(file_handle))
    else:
        return model_from_dict(json.load(arg_0))


def Func(arg_0):
    """Add a mixed-integer version of a minimal medium to the model.

    Changes the optimization objective to finding the medium with the least
    components::

        minimize size(R) where R part of import_reactions

    Arguments
    ---------
    model : cobra.model
        The model to modify.
    """
    if len(arg_0.variables) > 1e4:
        LOGGER.warning("the MIP version of minimal media is extremely slow for"
                       " models that large :(")
    arg_1 = find_boundary_types(arg_0, "exchange")
    arg_2 = max(abs(b) for r in arg_1 for b in r.bounds)
    arg_3 = arg_0.problem
    arg_4 = {}
    arg_5 = []
    for arg_6 in arg_1:
        arg_7 = len(arg_6.reactants) == 1
        arg_8 = arg_3.Variable("ind_" + arg_6.id, lb=0, ub=1, type="binary")
        if arg_7:
            arg_9 = arg_6.reverse_variable
            arg_10 = arg_3.Constraint(
                arg_9 - arg_8 * arg_2, ub=0, name="ind_constraint_" + arg_6.id)
        else:
            arg_11 = arg_6.forward_variable
            arg_10 = arg_3.Constraint(
                arg_11 - arg_8 * arg_2, ub=0, name="ind_constraint_" + arg_6.id)
        arg_5.extend([arg_8, arg_10])
        arg_4[arg_8] = 1
    arg_0.add_cons_vars(arg_5)
    arg_0.solver.update()
    arg_0.objective.set_linear_coefficients(arg_4)
    arg_0.objective.direction = "min"


def Func(arg_0, arg_1=1e-6, arg_2=False):
    """Convert a solution to medium.

    Arguments
    ---------
    exchanges : list of cobra.reaction
        The exchange reactions to consider.
    tolerance : positive double
        The absolute tolerance for fluxes. Fluxes with an absolute value
        smaller than this number will be ignored.
    exports : bool
        Whether to return export fluxes as well.

    Returns
    -------
    pandas.Series
        The "medium", meaning all active import fluxes in the solution.
    """
    LOGGER.debug("Formatting medium.")
    arg_3 = pd.Series()
    for arg_4 in arg_0:
        arg_5 = len(arg_4.reactants) == 1
        arg_6 = arg_4.flux
        if abs(arg_6) < arg_1:
            continue
        if arg_5:
            arg_3[arg_4.id] = -arg_6
        elif not arg_5:
            arg_3[arg_4.id] = arg_6
    if not arg_2:
        arg_3 = arg_3[arg_3 > 0]

    return arg_3


def Func(arg_0, arg_1=0.1, arg_2=False,
                   arg_3=False, arg_4=False):
    """
    Find the minimal growth medium for the model.

    Finds the minimal growth medium for the model which allows for
    model as well as individual growth. Here, a minimal medium can either
    be the medium requiring the smallest total import flux or the medium
    requiring the least components (ergo ingredients), which will be much
    slower due to being a mixed integer problem (MIP).

    Arguments
    ---------
    model : cobra.model
        The model to modify.
    min_objective_value : positive float or array-like object
        The minimum growth rate (objective) that has to be achieved.
    exports : boolean
        Whether to include export fluxes in the returned medium. Defaults to
        False which will only return import fluxes.
    minimize_components : boolean or positive int
        Whether to minimize the number of components instead of the total
        import flux. Might be more intuitive if set to True but may also be
        slow to calculate for large communities. If set to a number `n` will
        return up to `n` alternative solutions all with the same number of
        components.
    open_exchanges : boolean or number
        Whether to ignore currently set bounds and make all exchange reactions
        in the model possible. If set to a number all exchange reactions will
        be opened with (-number, number) as bounds.

    Returns
    -------
    pandas.Series, pandas.DataFrame or None
        A series giving the import flux for each required import
        reaction and (optionally) the associated export fluxes. All exchange
        fluxes are oriented into the import reaction e.g. positive fluxes
        denote imports and negative fluxes exports. If `minimize_components`
        is a number larger 1 may return a DataFrame where each column is a
        minimal medium. Returns None if the minimization is infeasible
        (for instance if min_growth > maximum growth rate).

    Notes
    -----
    Due to numerical issues the `minimize_components` option will usually only
    minimize the number of "large" import fluxes. Specifically, the detection
    limit is given by ``integrality_tolerance * max_bound`` where ``max_bound``
    is the largest bound on an import reaction. Thus, if you are interested
    in small import fluxes as well you may have to adjust the integrality
    tolerance at first with
    `model.solver.configuration.tolerances.integrality = 1e-7` for instance.
    However, this will be *very* slow for large models especially with GLPK.

    """
    arg_5 = find_boundary_types(arg_0, "exchange")
    if isinstance(arg_4, bool):
        arg_6 = 1000
    else:
        arg_6 = arg_4

    with arg_0 as arg_10:
        if arg_4:
            LOGGER.debug("Opening exchanges for %d imports.",
                         len(arg_5))
            for arg_7 in arg_5:
                arg_7.bounds = (-arg_6, arg_6)
        LOGGER.debug("Applying objective value constraints.")
        arg_9 = arg_10.problem.Constraint(
            arg_10.objective.expression, lb=arg_1,
            name="medium_obj_constraint")
        arg_10.add_cons_vars([arg_9])
        arg_10.solver.update()
        arg_10.objective = Zero
        LOGGER.debug("Adding new media objective.")
        arg_12 = arg_10.solver.configuration.tolerances.feasibility

        if arg_3:
            add_mip_obj(arg_10)
            if isinstance(arg_3, bool):
                arg_3 = 1
            arg_13 = set()
            arg_14 = arg_20 = arg_10.slim_optimize()
            if arg_10.solver.status != OPTIMAL:
                LOGGER.warning("Minimization of medium was infeasible.")
                return None
            arg_15 = arg_10.problem.Constraint(Zero, arg_19=0)
            arg_10.add_cons_vars([arg_15])
            arg_10.solver.update()
            arg_16 = []
            for arg_17 in range(arg_3):
                LOGGER.info("Finding alternative medium #%d.", (arg_17 + 1))
                arg_18 = [arg_10.variables["ind_" + s] for s in arg_13]
                if len(arg_13) > 0:
                    arg_15.set_linear_coefficients(
                        dict.fromkeys(arg_18, 1))
                    arg_15.ub = arg_14 - 1
                arg_20 = arg_10.slim_optimize()
                if arg_10.solver.status != OPTIMAL or arg_20 > arg_14:
                    break
                arg_21 = _as_medium(arg_5, arg_12, arg_2=arg_2)
                arg_16.append(arg_21)
                arg_13.update(arg_21[arg_21 > 0].index)
            if len(arg_16) > 1:
                arg_21 = pd.concat(arg_16, axis=1, sort=True).fillna(0.0)
                arg_21.sort_index(axis=1, inplace=True)
            else:
                arg_21 = arg_16[0]
        else:
            add_linear_obj(arg_10)
            arg_10.slim_optimize()
            if arg_10.solver.status != OPTIMAL:
                LOGGER.warning("Minimization of medium was infeasible.")
                return None
            arg_21 = _as_medium(arg_5, arg_12, arg_2=arg_2)

    return arg_21


def Func(arg_0, arg_1, arg_2):
    """Initialize a global model object for multiprocessing."""
    global arg_3
    global arg_7
    arg_3 = arg_0
    arg_3.solver.objective.direction = arg_2
    arg_7 = arg_1


def Func(arg_0, arg_1=None, arg_2=False,
                              arg_3=1.0, arg_4=None,
                              arg_5=None):
    """
    Determine the minimum and maximum possible flux value for each reaction.

    Parameters
    ----------
    model : cobra.Model
        The model for which to run the analysis. It will *not* be modified.
    reaction_list : list of cobra.Reaction or str, optional
        The reactions for which to obtain min/max fluxes. If None will use
        all reactions in the model (default).
    loopless : boolean, optional
        Whether to return only loopless solutions. This is significantly
        slower. Please also refer to the notes.
    fraction_of_optimum : float, optional
        Must be <= 1.0. Requires that the objective value is at least the
        fraction times maximum objective value. A value of 0.85 for instance
        means that the objective has to be at least at 85% percent of its
        maximum.
    pfba_factor : float, optional
        Add an additional constraint to the model that requires the total sum
        of absolute fluxes must not be larger than this value times the
        smallest possible sum of absolute fluxes, i.e., by setting the value
        to 1.1 the total sum of absolute fluxes must not be more than
        10% larger than the pFBA solution. Since the pFBA solution is the
        one that optimally minimizes the total flux sum, the ``pfba_factor``
        should, if set, be larger than one. Setting this value may lead to
        more realistic predictions of the effective flux bounds.
    processes : int, optional
        The number of parallel processes to run. If not explicitly passed,
        will be set from the global configuration singleton.

    Returns
    -------
    pandas.DataFrame
        A data frame with reaction identifiers as the index and two columns:
        - maximum: indicating the highest possible flux
        - minimum: indicating the lowest possible flux

    Notes
    -----
    This implements the fast version as described in [1]_. Please note that
    the flux distribution containing all minimal/maximal fluxes does not have
    to be a feasible solution for the model. Fluxes are minimized/maximized
    individually and a single minimal flux might require all others to be
    suboptimal.

    Using the loopless option will lead to a significant increase in
    computation time (about a factor of 100 for large models). However, the
    algorithm used here (see [2]_) is still more than 1000x faster than the
    "naive" version using ``add_loopless(model)``. Also note that if you have
    included constraints that force a loop (for instance by setting all fluxes
    in a loop to be non-zero) this loop will be included in the solution.

    References
    ----------
    .. [1] Computationally efficient flux variability analysis.
       Gudmundsson S, Thiele I.
       BMC Bioinformatics. 2010 Sep 29;11:489.
       doi: 10.1186/1471-2105-11-489, PMID: 20920235

    .. [2] CycleFreeFlux: efficient removal of thermodynamically infeasible
       loops from flux distributions.
       Desouki AA, Jarre F, Gelius-Dietrich G, Lercher MJ.
       Bioinformatics. 2015 Jul 1;31(13):2159-65.
       doi: 10.1093/bioinformatics/btv096.
    """
    if arg_1 is None:
        arg_6 = [r.id for r in arg_0.reactions]
    else:
        arg_6 = [r.id
                        for r in arg_0.reactions.get_by_any(arg_1)]

    if arg_5 is None:
        arg_5 = CONFIGURATION.processes
    arg_7 = len(arg_6)
    arg_5 = min(arg_5, arg_7)

    arg_8 = DataFrame({
        "minimum": zeros(arg_7, dtype=float),
        "maximum": zeros(arg_7, dtype=float)
    }, index=arg_6)
    arg_9 = arg_0.problem
    with arg_0:
        # Safety check before setting up FVA.
        arg_0.slim_optimize(error_value=None,
                            message="There is no optimal solution for the "
                                    "chosen objective!")
        # Add the previous objective as a variable to the model then set it to
        # zero. This also uses the fraction to create the lower/upper bound for
        # the old objective.
        # TODO: Use utility function here (fix_objective_as_constraint)?
        if arg_0.solver.objective.direction == "max":
            arg_10 = arg_9.Variable(
                "fva_old_objective",
                lb=arg_3 * arg_0.solver.objective.value)
        else:
            arg_10 = arg_9.Variable(
                "fva_old_objective",
                arg_12=arg_3 * arg_0.solver.objective.value)
        arg_11 = arg_9.Constraint(
            arg_0.solver.objective.expression - arg_10, lb=0, arg_12=0,
            name="fva_old_objective_constraint")
        arg_0.add_cons_vars([arg_10, arg_11])

        if arg_4 is not None:
            if arg_4 < 1.:
                warn("The 'pfba_factor' should be larger or equal to 1.",
                     UserWarning)
            with arg_0:
                add_pfba(arg_0, arg_3=0)
                arg_12 = arg_0.slim_optimize(error_value=None)
                arg_13 = arg_9.Variable("flux_sum", arg_12=arg_4 * arg_12)
                arg_14 = arg_9.Constraint(
                    arg_0.solver.objective.expression - arg_13, lb=0, arg_12=0,
                    name="flux_sum_constraint")
            arg_0.add_cons_vars([arg_13, arg_14])

        arg_0.objective = Zero  # This will trigger the reset as well
        for arg_16 in ("minimum", "maximum"):
            if arg_5 > 1:
                # We create and destroy a new pool here in order to set the
                # objective direction for all reactions. This creates a
                # slight overhead but seems the most clean.
                arg_17 = len(arg_6) // arg_5
                arg_18 = multiprocessing.Pool(
                    arg_5,
                    initializer=_init_worker,
                    initargs=(arg_0, arg_2, arg_16[:3])
                )
                for arg_19, arg_20 in arg_18.imap_unordered(_fva_step,
                                                         arg_6,
                                                         chunksize=arg_17):
                    arg_8.at[arg_19, arg_16] = arg_20
                arg_18.close()
                arg_18.join()
            else:
                _init_worker(arg_0, arg_2, arg_16[:3])
                for arg_19, arg_20 in map(_fva_step, arg_6):
                    arg_8.at[arg_19, arg_16] = arg_20

    return arg_8[["minimum", "maximum"]]


def Func(arg_0,
                           arg_1=None,
                           arg_2=None,
                           arg_3=False,
                           arg_4=None):
    """
    Find reactions that cannot carry any flux.

    The question whether or not a reaction is blocked is highly dependent
    on the current exchange reaction settings for a COBRA model. Hence an
    argument is provided to open all exchange reactions.

    Notes
    -----
    Sink and demand reactions are left untouched. Please modify them manually.

    Parameters
    ----------
    model : cobra.Model
        The model to analyze.
    reaction_list : list, optional
        List of reactions to consider, the default includes all model
        reactions.
    zero_cutoff : float, optional
        Flux value which is considered to effectively be zero
        (default model.tolerance).
    open_exchanges : bool, optional
        Whether or not to open all exchange reactions to very high flux ranges.
    processes : int, optional
        The number of parallel processes to run. Can speed up the computations
        if the number of reactions is large. If not explicitly
        passed, it will be set from the global configuration singleton.

    Returns
    -------
    list
        List with the identifiers of blocked reactions.

    """
    arg_2 = normalize_cutoff(arg_0, arg_2)

    with arg_0:
        if arg_3:
            for arg_5 in arg_0.exchanges:
                arg_5.bounds = (min(arg_5.lower_bound, -1000),
                                   max(arg_5.upper_bound, 1000))
        if arg_1 is None:
            arg_1 = arg_0.reactions
        # Limit the search space to reactions which have zero flux. If the
        # reactions already carry flux in this solution,
        # then they cannot be blocked.
        arg_0.slim_optimize()
        arg_7 = get_solution(arg_0, reactions=arg_1)
        arg_1 = arg_7.fluxes[
            arg_7.fluxes.abs() < arg_2].index.tolist()
        # Run FVA to find reactions where both the minimal and maximal flux
        # are zero (below the cut off).
        arg_8 = flux_variability_analysis(
            arg_0, fraction_of_optimum=0., arg_1=arg_1,
            arg_4=arg_4
        )
        return arg_8[
            arg_8.abs().max(axis=1) < arg_2].index.tolist()


def Func(arg_0, arg_1=None, arg_2=None):
    """Return a set of essential reactions.

    A reaction is considered essential if restricting its flux to zero
    causes the objective, e.g., the growth rate, to also be zero, below the
    threshold, or infeasible.

    Parameters
    ----------
    model : cobra.Model
        The model to find the essential reactions for.
    threshold : float, optional
        Minimal objective flux to be considered viable. By default this is
        1% of the maximal objective.
    processes : int, optional
        The number of parallel processes to run. Can speed up the computations
        if the number of knockouts to perform is large. If not explicitly
        passed, it will be set from the global configuration singleton.

    Returns
    -------
    set
        Set of essential reactions
    """
    if arg_1 is None:
        arg_1 = arg_0.slim_optimize(error_value=None) * 1E-02
    arg_3 = single_reaction_deletion(
        arg_0, method='fba', arg_2=arg_2)
    arg_4 = arg_3.loc[arg_3['growth'].isna() |
                              (arg_3['growth'] < arg_1), :].index
    return {arg_0.reactions.get_by_id(arg_6) for arg_5 in arg_4 for arg_6 in arg_5}


def Func(arg_0):
    """adds SBO terms for demands and exchanges

    This works for models which follow the standard convention for
    constructing and naming these reactions.

    The reaction should only contain the single metabolite being exchanged,
    and the id should be EX_metid or DM_metid
    """
    for arg_1 in arg_0.reactions:
        # don't annotate already annotated reactions
        if arg_1.annotation.get("sbo"):
            continue
        # only doing exchanges
        if len(arg_1.metabolites) != 1:
            continue
        arg_2 = list(arg_1._metabolites)[0].id
        if arg_1.id.startswith("EX_") and arg_1.id == "EX_" + arg_2:
            arg_1.annotation["sbo"] = "SBO:0000627"
        elif arg_1.id.startswith("DM_") and arg_1.id == "DM_" + arg_2:
            arg_1.annotation["sbo"] = "SBO:0000628"


def Func(arg_0, arg_1=None, arg_2=None, arg_3="fba",
                         arg_4=None, arg_5=None, **arg_6):
    """
    Knock out each gene pair from the combination of two given lists.

    We say 'pair' here but the order order does not matter.

    Parameters
    ----------
    model : cobra.Model
        The metabolic model to perform deletions in.
    gene_list1 : iterable, optional
        First iterable of ``cobra.Gene``s to be deleted. If not passed,
        all the genes from the model are used.
    gene_list2 : iterable, optional
        Second iterable of ``cobra.Gene``s to be deleted. If not passed,
        all the genes from the model are used.
    method: {"fba", "moma", "linear moma", "room", "linear room"}, optional
        Method used to predict the growth rate.
    solution : cobra.Solution, optional
        A previous solution to use as a reference for (linear) MOMA or ROOM.
    processes : int, optional
        The number of parallel processes to run. Can speed up the computations
        if the number of knockouts to perform is large. If not passed,
        will be set to the number of CPUs found.
    kwargs :
        Keyword arguments are passed on to underlying simulation functions
        such as ``add_room``.

    Returns
    -------
    pandas.DataFrame
        A representation of all combinations of gene deletions. The
        columns are 'growth' and 'status', where

        index : frozenset([str])
            The gene identifiers that were knocked out.
        growth : float
            The growth rate of the adjusted model.
        status : str
            The solution's status.

    """

    arg_1, arg_2 = _element_lists(arg_0.genes, arg_1,
                                            arg_2)
    return _multi_deletion(
        arg_0, 'gene', element_lists=[arg_1, arg_2],
        arg_3=arg_3, arg_4=arg_4, arg_5=arg_5, **arg_6)


def Func(arg_0):
        """Generate the id of reverse_variable from the reaction's id."""
        return '_'.join((arg_0.id, 'reverse',
                         hashlib.md5(
                             arg_0.id.encode('utf-8')).hexdigest()[0:5]))


def Func(arg_0):
        """
        The Func value in the most recent solution.

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

        Warnings
        --------
        * Accessing reaction Funces 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 Func 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 Func value is not within the bounds.

        Examples
        --------
        >>> import cobra.test
        >>> model = cobra.test.create_test_model("textbook")
        >>> solution = model.optimize()
        >>> model.reactions.PFK.Func
        7.477381962160283
        >>> solution.Funces.PFK
        7.4773819621602833
        """
        try:
            check_solver_status(arg_0._model.solver.status)
            return arg_0.forward_variable.primal - arg_0.reverse_variable.primal
        except AttributeError:
            raise RuntimeError(
                "reaction '{}' is not part of a model".format(arg_0.id))
        # Due to below all-catch, which sucks, need to reraise these.
        except (RuntimeError, OptimizationError) as err:
            raise_with_traceback(err)
        # Would love to catch CplexSolverError and GurobiError here.
        except Exception as err:
            raise_from(OptimizationError(
                "Likely no solution exists. Original solver message: {}."
                "".format(str(err))), err)


def Func(arg_0):
        """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.

        """
        arg_1 = {i.id: i.name for i in arg_0._genes}
        arg_2 = parse_gpr(arg_0._gene_reaction_rule)[0]
        return ast2str(arg_2, arg_1=arg_1)


def Func(arg_0):
        """All required enzymes for reaction are Func.

        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.
        """
        if arg_0._model:
            arg_1, arg_2 = parse_gpr(arg_0.gene_reaction_rule)
            return eval_gpr(arg_1, {arg_3.id for arg_3 in arg_0.genes if
                                   not arg_3.Func})
        return True


def Func(arg_0):
        """Make sure all metabolites and genes that are associated with
        this reaction are aware of it.

        """
        for arg_1 in arg_0._metabolites:
            arg_1._reaction.add(arg_0)
        for arg_1 in arg_0._genes:
            arg_1._reaction.add(arg_0)


def Func(arg_0):
        """Copy a reaction

        The referenced metabolites and genes are also copied.

        """
        # no references to model when Funcing
        arg_1 = arg_0._model
        arg_0._model = None
        for arg_3 in arg_0._metabolites:
            arg_3._model = None
        for arg_3 in arg_0._genes:
            arg_3._model = None
        # now we can Func
        arg_4 = deepFunc(arg_0)
        # restore the references
        arg_0._model = arg_1
        for arg_3 in arg_0._metabolites:
            arg_3._model = arg_1
        for arg_3 in arg_0._genes:
            arg_3._model = arg_1
        return arg_4


def Func(arg_0, arg_1, arg_2=True,
                        arg_3=True):
        """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).

        """
        arg_4 = arg_0.metabolites
        arg_5 = []
        arg_6 = dict([(x.id, x) for x in arg_0._metabolites])

        for arg_7, arg_8 in iteritems(arg_1):

            # Make sure metabolites being added belong to the same model, or
            # else copy them.
            if isinstance(arg_7, Metabolite):
                if ((arg_7.model is not None) and
                        (arg_7.model is not arg_0._model)):
                    arg_7 = arg_7.copy()

            arg_9 = str(arg_7)
            # If a metabolite already exists in the reaction then
            # just add them.
            if arg_9 in arg_6:
                arg_10 = arg_6[arg_9]
                if arg_2:
                    arg_0._metabolites[arg_10] += arg_8
                else:
                    arg_0._metabolites[arg_10] = arg_8
            else:
                # If the reaction is in a model, ensure we aren't using
                # a duplicate metabolite.
                if arg_0._model:
                    try:
                        arg_7 = \
                            arg_0._model.metabolites.get_by_id(arg_9)
                    except KeyError as e:
                        if isinstance(arg_7, Metabolite):
                            arg_5.append(arg_7)
                        else:
                            # do we want to handle creation here?
                            raise e
                elif isinstance(arg_7, string_types):
                    # if we want to handle creation, this should be changed
                    raise ValueError("Reaction '%s' does not belong to a "
                                     "model. Either add the reaction to a "
                                     "model or use Metabolite objects instead "
                                     "of strings as keys."
                                     % arg_0.id)
                arg_0._metabolites[arg_7] = arg_8
                # make the metabolite aware that it is involved in this
                # reaction
                arg_7._reaction.add(arg_0)

        # from cameo ...
        arg_12 = arg_0.model
        if arg_12 is not None:
            arg_12.Func(arg_5)

            for arg_7, arg_8 in arg_0._metabolites.items():
                arg_12.constraints[
                    arg_7.id].set_linear_coefficients(
                    {arg_0.forward_variable: arg_8,
                     arg_0.reverse_variable: -arg_8
                     })

        for arg_7, arg_13 in list(arg_0._metabolites.items()):
            if arg_13 == 0:
                # make the metabolite aware that it no longer participates
                # in this reaction
                arg_7._reaction.remove(arg_0)
                arg_0._metabolites.pop(arg_7)

        arg_14 = get_context(arg_0)
        if arg_14 and arg_3:
            if arg_2:
                # Just subtract the metabolites that were added
                arg_14(partial(
                    arg_0.subtract_metabolites, arg_1,
                    arg_2=True, arg_3=False))
            else:
                # Reset them with Func
                arg_15 = {
                    key: arg_4[arg_12.metabolites.get_by_any(key)[0]]
                    for key in iterkeys(arg_1)}

                arg_14(partial(
                    arg_0.Func, arg_15,
                    arg_2=False, arg_3=False))


def Func(arg_0, arg_1=False):
        """Generate a human readable reaction string"""

        def format(arg_2):
            return "" if arg_2 == 1 else str(arg_2).rstrip(".") + " "

        arg_3 = 'id'
        if arg_1:
            arg_3 = 'name'
        arg_4 = []
        arg_5 = []
        for arg_6 in sorted(arg_0._metabolites, key=attrgetter("id")):
            arg_7 = arg_0._metabolites[arg_6]
            arg_8 = str(getattr(arg_6, arg_3))
            if arg_7 >= 0:
                arg_5.append(format(arg_7) + arg_8)
            else:
                arg_4.append(format(abs(arg_7)) + arg_8)

        arg_9 = ' + '.join(arg_4)
        if not arg_0.reversibility:
            if arg_0.lower_bound < 0 and arg_0.upper_bound <= 0:
                arg_9 += ' <-- '
            else:
                arg_9 += ' --> '
        else:
            arg_9 += ' <=> '
        arg_9 += ' + '.join(arg_5)
        return arg_9


def Func(arg_0):
        """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.
        """
        arg_1 = defaultdict(int)
        for arg_2, arg_3 in iteritems(arg_0._metabolites):
            if arg_2.charge is not None:
                arg_1["charge"] += \
                    arg_3 * arg_2.charge
            if arg_2.elements is None:
                raise ValueError("No elements found in metabolite %s"
                                 % arg_2.id)
            for arg_4, arg_5 in iteritems(arg_2.elements):
                arg_1[arg_4] += arg_3 * arg_5
        # filter out 0 values
        return {arg_6: arg_7 for arg_6, arg_7 in iteritems(arg_1) if arg_7 != 0}


def Func(arg_0, arg_1):
        """Dissociates a cobra.Gene object with a cobra.Reaction.

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

        """
        arg_0._genes.discard(arg_1)
        arg_1._reaction.discard(arg_0)


def Func(arg_0, arg_1, arg_2=True,
                                   arg_3=None, arg_4=None,
                                   arg_5=None, arg_6="+"):
        """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

        """
        # set the arrows
        arg_7 = _forward_arrow_finder if arg_3 is None \
            else re.compile(re.escape(arg_3))
        arg_8 = _reverse_arrow_finder if arg_4 is None \
            else re.compile(re.escape(arg_4))
        arg_9 = _reversible_arrow_finder \
            if arg_5 is None \
            else re.compile(re.escape(arg_5))
        if arg_0._model is None:
            warn("no model found")
            arg_10 = None
        else:
            arg_10 = arg_0._model
        arg_11 = compartment_finder.findall(arg_1)
        if len(arg_11) == 1:
            arg_12 = arg_11[0]
            arg_1 = compartment_finder.sub("", arg_1)
        else:
            arg_12 = ""

        # reversible case
        arg_13 = arg_9.search(arg_1)
        if arg_13 is not None:
            arg_0.lower_bound = -1000
            arg_0.upper_bound = 1000
        else:  # irreversible
            # try forward
            arg_13 = arg_7.search(arg_1)
            if arg_13 is not None:
                arg_0.upper_bound = 1000
                arg_0.lower_bound = 0
            else:
                # must be reverse
                arg_13 = arg_8.search(arg_1)
                if arg_13 is None:
                    raise ValueError("no suitable arrow found in '%s'" %
                                     arg_1)
                else:
                    arg_0.upper_bound = 0
                    arg_0.lower_bound = -1000
        arg_16 = arg_1[:arg_13.start()].strip()
        arg_17 = arg_1[arg_13.end():].strip()

        arg_0.subtract_metabolites(arg_0.metabolites, combine=True)

        for arg_18, arg_19 in ((arg_16, -1), (arg_17, 1)):
            if len(arg_18) == 0:
                continue
            for arg_20 in arg_18.split(arg_6):
                arg_20 = arg_20.strip()
                if arg_20.lower() == "nothing":
                    continue
                if " " in arg_20:
                    arg_21, arg_22 = arg_20.split()
                    arg_23 = float(arg_21.lstrip("(").rstrip(")")) * arg_19
                else:
                    arg_22 = arg_20
                    arg_23 = arg_19
                arg_22 += arg_12
                try:
                    arg_24 = arg_10.metabolites.get_by_id(arg_22)
                except KeyError:
                    if arg_2:
                        print("unknown metabolite '%s' created" % arg_22)
                    arg_24 = Metabolite(arg_22)
                arg_0.add_metabolites({arg_24: arg_23})


def Func(arg_0, arg_1=arg_2, arg_3=arg_4,
                    arg_5=False, **arg_6):
    """Reads SBML model from given filename.

    If the given filename ends with the suffix ''.gz'' (for example,
    ''myfile.xml.gz'),' the file is assumed to be compressed in gzip
    format and will be automatically decompressed upon reading. Similarly,
    if the given filename ends with ''.zip'' or ''.bz2',' the file is
    assumed to be compressed in zip or bzip2 format (respectively).  Files
    whose names lack these suffixes will be read uncompressed.  Note that
    if the file is in zip format but the archive contains more than one
    file, only the first file in the archive will be read and the rest
    ignored.

    To read a gzip/zip file, libSBML needs to be configured and linked
    with the zlib library at compile time.  It also needs to be linked
    with the bzip2 library to read files in bzip2 format.  (Both of these
    are the default configurations for libSBML.)

    This function supports SBML with FBC-v1 and FBC-v2. FBC-v1 models
    are converted to FBC-v2 models before reading.

    The parser tries to fall back to information in notes dictionaries
    if information is not available in the FBC packages, e.g.,
    CHARGE, FORMULA on species, or GENE_ASSOCIATION, SUBSYSTEM on reactions.

    Parameters
    ----------
    filename : path to SBML file, or SBML string, or SBML file handle
        SBML which is read into cobra model
    number: data type of stoichiometry: {float, int}
        In which data type should the stoichiometry be parsed.
    f_replace : dict of replacement functions for id replacement
        Dictionary of replacement functions for gene, specie, and reaction.
        By default the following id changes are performed on import:
        clip G_ from genes, clip M_ from species, clip R_ from reactions
        If no replacements should be performed, set f_replace={}, None
    set_missing_bounds : boolean flag to set missing bounds
        Missing bounds are set to default bounds in configuration.

    Returns
    -------
    cobra.core.Model

    Notes
    -----
    Provided file handles cannot be opened in binary mode, i.e., use
        with open(path, "r" as f):
            Func(f)
    File handles to compressed files are not supported yet.
    """
    try:
        arg_7 = _get_doc_from_filename(arg_0)
        return _sbml_to_model(arg_7,
                              arg_1=arg_1,
                              arg_3=arg_3,
                              arg_5=arg_5,
                              **arg_6)
    except IOError as e:
        raise e

    except Exception:
        LOGGER.error(traceback.print_exc())
        raise CobraSBMLError(
            "Something went wrong reading the SBML model. Most likely the SBML"
            " model is not valid. Please check that your model is valid using "
            "the `cobra.io.sbml.validate_sbml_model` function or via the "
            "online validator at http://sbml.org/validator .\n"
            "\t`(model, errors) = validate_sbml_model(filename)`"
            "\nIf the model is valid and cannot be read please open an issue "
            "at https://github.com/opencobra/cobrapy/issues .")


def Func(arg_0):
    """Get SBMLDocument from given filename.

    Parameters
    ----------
    filename : path to SBML, or SBML string, or filehandle

    Returns
    -------
    libsbml.SBMLDocument
    """
    if isinstance(arg_0, string_types):
        if ("win" in platform) and (len(arg_0) < 260) \
                and os.path.exists(arg_0):
            # path (win)
            arg_1 = libsbml.readSBMLFromFile(arg_0)  # noqa: E501 type: libsbml.SBMLDocument
        elif ("win" not in platform) and os.path.exists(arg_0):
            # path other
            arg_1 = libsbml.readSBMLFromFile(arg_0)  # noqa: E501 type: libsbml.SBMLDocument
        else:
            # string representation
            if "<sbml" not in arg_0:
                raise IOError("The file with 'filename' does not exist, "
                              "or is not an SBML string. Provide the path to "
                              "an existing SBML file or a valid SBML string "
                              "representation: \n%s", arg_0)

            arg_1 = libsbml.readSBMLFromString(arg_0)  # noqa: E501 type: libsbml.SBMLDocument

    elif hasattr(arg_0, "read"):
        # file handle
        arg_1 = libsbml.readSBMLFromString(arg_0.read())  # noqa: E501 type: libsbml.SBMLDocument
    else:
        raise CobraSBMLError("Input type '%s' for 'filename' is not supported."
                             " Provide a path, SBML str, "
                             "or file handle.", type(arg_0))

    return arg_1


def Func(arg_0, arg_1, arg_2=arg_3, **arg_4):
    """Writes cobra model to filename.

    The created model is SBML level 3 version 1 (L1V3) with
    fbc package v2 (fbc-v2).

    If the given filename ends with the suffix ".gz" (for example,
    "myfile.xml.gz"), libSBML assumes the caller wants the file to be
    written compressed in gzip format. Similarly, if the given filename
    ends with ".zip" or ".bz2", libSBML assumes the caller wants the
    file to be compressed in zip or bzip2 format (respectively). Files
    whose names lack these suffixes will be written uncompressed. Special
    considerations for the zip format: If the given filename ends with
    ".zip", the file placed in the zip archive will have the suffix
    ".xml" or ".sbml".  For example, the file in the zip archive will
    be named "test.xml" if the given filename is "test.xml.zip" or
    "test.zip". Similarly, the filename in the archive will be
    "test.sbml" if the given filename is "test.sbml.zip".

    Parameters
    ----------
    cobra_model : cobra.core.Model
        Model instance which is written to SBML
    filename : string
        path to which the model is written
    use_fbc_package : boolean {True, False}
        should the fbc package be used
    f_replace: dict of replacement functions for id replacement
    """
    arg_5 = _model_to_sbml(arg_0, arg_2=arg_2, **arg_4)

    if isinstance(arg_1, string_types):
        # write to path
        libsbml.writeSBMLToFile(arg_5, arg_1)

    elif hasattr(arg_1, "write"):
        # write to file handle
        arg_6 = libsbml.writeSBMLToString(arg_5)
        arg_1.write(arg_6)


def Func(arg_0, arg_1, arg_2, arg_3, arg_4=None,
                  arg_5=None):
    """Creates bound in model for given reaction.

    Adds the parameters for the bounds to the SBML model.

    Parameters
    ----------
    model : libsbml.Model
        SBML model instance
    reaction : cobra.core.Reaction
        Cobra reaction instance from which the bounds are read.
    bound_type : {LOWER_BOUND, UPPER_BOUND}
        Type of bound
    f_replace : dict of id replacement functions
    units : flux units

    Returns
    -------
    Id of bound parameter.
    """
    arg_6 = getattr(arg_1, arg_2)
    if arg_6 == config.lower_bound:
        return LOWER_BOUND_ID
    elif arg_6 == 0:
        return ZERO_BOUND_ID
    elif arg_6 == config.upper_bound:
        return UPPER_BOUND_ID
    elif arg_6 == -float("Inf"):
        return BOUND_MINUS_INF
    elif arg_6 == float("Inf"):
        return BOUND_PLUS_INF
    else:
        # new parameter
        arg_7 = arg_1.id
        if arg_3 and F_REACTION_REV in arg_3:
            arg_7 = arg_3[F_REACTION_REV](arg_7)
        arg_8 = arg_7 + "_" + arg_2
        _create_parameter(arg_0, arg_8=arg_8, arg_6=arg_6, sbo=SBO_FLUX_BOUND,
                          arg_4=arg_4, arg_5=arg_5)
        return arg_8


def Func(arg_0, arg_1, arg_2, arg_3=None, arg_4=True, arg_5=None,
                      arg_6=None):
    """Create parameter in SBML model."""
    arg_7 = arg_0.createParameter()  # type: libsbml.Parameter
    arg_7.setId(arg_1)
    arg_7.setValue(arg_2)
    arg_7.setConstant(arg_4)
    if arg_3:
        arg_7.setSBOTerm(arg_3)
    if arg_5:
        arg_7.setUnits(arg_6.getId())


def Func(arg_0, arg_1):
    """
    Checks the libsbml return value and logs error messages.

    If 'value' is None, logs an error message constructed using
      'message' and then exits with status code 1. If 'value' is an integer,
      it assumes it is a libSBML return status code. If the code value is
      LIBSBML_OPERATION_SUCCESS, returns without further action; if it is not,
      prints an error message constructed using 'message' along with text from
      libSBML explaining the meaning of the code, and exits with status code 1.

    """
    if arg_0 is None:
        LOGGER.error('Error: LibSBML returned a null value trying '
                     'to <' + arg_1 + '>.')
    elif type(arg_0) is int:
        if arg_0 == libsbml.LIBSBML_OPERATION_SUCCESS:
            return
        else:
            LOGGER.error('Error encountered trying to <' + arg_1 + '>.')
            LOGGER.error('LibSBML error code {}: {}'.format(str(arg_0),
                         libsbml.OperationReturnValue_toString(arg_0).strip()))
    else:
        return


def Func(arg_0):
    """ Creates dictionary of COBRA notes.

    Parameters
    ----------
    sbase : libsbml.SBase

    Returns
    -------
    dict of notes
    """
    arg_1 = arg_0.getNotesString()
    if arg_1 and len(arg_1) > 0:
        arg_2 = r"<p>\s*(\w+\s*\w*)\s*:\s*([\w|\s]+)<"
        arg_3 = re.findall(arg_2, arg_1)
        arg_4 = {arg_5.strip(): arg_6.strip() for (arg_5, arg_6) in arg_3}
        return {arg_5: arg_6 for arg_5, arg_6 in arg_4.items() if len(arg_6) > 0}
    else:
        return {}


def Func(arg_0, arg_1):
    """Set SBase notes based on dictionary.

    Parameters
    ----------
    sbase : libsbml.SBase
        SBML object to set notes on
    notes : notes object
        notes information from cobra object
    """
    if arg_1 and len(arg_1) > 0:
        arg_2 = [''] + \
            ["
{}: {}
".format(k, v) for (k, v) in arg_1.items()] + \
            [""]
        _check(
            arg_0.setNotes("\n".join(arg_2)),
            "Setting notes on sbase: {}".format(arg_0)
        )


def Func(arg_0):
    """Parses cobra annotations from a given SBase object.

    Annotations are dictionaries with the providers as keys.

    Parameters
    ----------
    sbase : libsbml.SBase
        SBase from which the SBML annotations are read

    Returns
    -------
    dict (annotation dictionary)

    FIXME: annotation format must be updated (this is a big collection of
          fixes) - see: https://github.com/opencobra/cobrapy/issues/684)
    """
    arg_1 = {}

    # SBO term
    if arg_0.isSetSBOTerm():
        # FIXME: correct handling of annotations
        arg_1["sbo"] = arg_0.getSBOTermID()

    # RDF annotation
    arg_2 = arg_0.getCVTerms()
    if arg_2 is None:
        return arg_1

    for arg_3 in arg_2:  # type: libsbml.CVTerm
        for arg_4 in range(arg_3.getNumResources()):
            # FIXME: read and store the qualifier

            arg_5 = arg_3.getResourceURI(arg_4)
            arg_6 = URL_IDENTIFIERS_PATTERN.match(arg_5)
            if not arg_6:
                LOGGER.warning("%s does not conform to "
                               "http(s)://identifiers.org/collection/id", arg_5)
                continue

            arg_7, arg_8 = arg_6.group(1), arg_6.group(2)
            if arg_7 in arg_1:
                if isinstance(arg_1[arg_7], string_types):
                    arg_1[arg_7] = [arg_1[arg_7]]
                # FIXME: use a list
                if arg_8 not in arg_1[arg_7]:
                    arg_1[arg_7].append(arg_8)
            else:
                # FIXME: always in list
                arg_1[arg_7] = arg_8

    return arg_1


def Func(arg_0, arg_1):
    """Set SBase annotations based on cobra annotations.

    Parameters
    ----------
    sbase : libsbml.SBase
        SBML object to annotate
    annotation : cobra annotation structure
        cobra object with annotation information

    FIXME: annotation format must be updated
        (https://github.com/opencobra/cobrapy/issues/684)
    """

    if not arg_1 or len(arg_1) == 0:
        return

    # standardize annotations
    arg_2 = deepcopy(arg_1)

    for arg_3, arg_4 in arg_2.items():
        # handling of non-string annotations (e.g. integers)
        if isinstance(arg_4, (float, int)):
            arg_4 = str(arg_4)
        if isinstance(arg_4, string_types):
            arg_2[arg_3] = [("is", arg_4)]

    for arg_3, arg_4 in arg_2.items():
        for arg_5, arg_6 in enumerate(arg_4):
            if isinstance(arg_6, string_types):
                arg_4[arg_5] = ("is", arg_6)

    # set metaId
    arg_7 = "meta_{}".format(arg_0.getId())
    arg_0.setMetaId(arg_7)

    # rdf_items = []
    for arg_8, arg_9 in iteritems(arg_2):

        # set SBOTerm
        if arg_8 in ["SBO", "sbo"]:
            if arg_8 == "SBO":
                LOGGER.warning("'SBO' provider is deprecated, "
                               "use 'sbo' provider instead")
            arg_10 = arg_9[0][1]
            _check(arg_0.setSBOTerm(arg_10),
                   "Setting SBOTerm: {}".format(arg_10))

            # FIXME: sbo should also be written as CVTerm
            continue

        for arg_6 in arg_9:
            arg_11, arg_12 = arg_6[0], arg_6[1]
            arg_13 = QUALIFIER_TYPES.get(arg_11, None)
            if arg_13 is None:
                arg_13 = libsbml.BQB_IS
                LOGGER.error("Qualifier type is not supported on "
                             "annotation: '{}'".format(arg_11))

            arg_14 = libsbml.BIOLOGICAL_QUALIFIER
            if arg_11.startswith("bqm_"):
                arg_14 = libsbml.MODEL_QUALIFIER

            arg_15 = libsbml.CVTerm()  # type: libsbml.CVTerm
            arg_15.setQualifierType(arg_14)
            if arg_14 == libsbml.BIOLOGICAL_QUALIFIER:
                arg_15.setBiologicalQualifierType(arg_13)
            elif arg_14 == libsbml.MODEL_QUALIFIER:
                arg_15.setModelQualifierType(arg_13)
            else:
                raise CobraSBMLError('Unsupported qualifier: '
                                     '%s' % arg_13)
            arg_16 = "%s/%s/%s" % (URL_IDENTIFIERS_PREFIX, arg_8, arg_12)
            arg_15.addResource(arg_16)
            _check(arg_0.addCVTerm(arg_15),
                   "Setting cvterm: {}, resource: {}".format(arg_15, arg_16))


def Func(arg_0, arg_1=None):
    """String representation of SBMLError.

    Parameters
    ----------
    error : libsbml.SBMLError
    k : index of error

    Returns
    -------
    string representation of error
    """
    arg_2 = arg_0.getPackage()
    if arg_2 == '':
        arg_2 = 'core'

    arg_3 = 'E{} ({}): {} ({}, L{}); {}; {}'
    arg_4 = arg_3.format(arg_1, arg_0.getSeverityAsString(),
                                arg_0.getCategoryAsString(), arg_2,
                                arg_0.getLine(), arg_0.getShortMessage(),
                                arg_0.getMessage())
    return arg_4


def Func(arg_0, arg_1, arg_2=None, arg_3=None,
                        arg_4=20, arg_5=None):
    """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 Func
    >>> model = cobra.test.create_test_model("textbook")
    >>> Func(model, ["EX_glc__D_e", "EX_o2_e"])

    """

    arg_1 = arg_0.reactions.get_by_any(arg_1)
    arg_2 = arg_0.solver.objective if arg_2 is None else arg_2
    arg_6 = dict()

    if arg_3 is None:
        arg_7 = find_carbon_sources(arg_0)
    else:
        arg_7 = arg_0.reactions.get_by_any(arg_3)

    if arg_7 is None:
        arg_6['carbon_source'] = None
    elif hasattr(arg_7, 'id'):
        arg_6['carbon_source'] = arg_7.id
    else:
        arg_6['carbon_source'] = ', '.join(rxn.id for rxn in arg_7)

    arg_5 = normalize_cutoff(arg_0, arg_5)

    arg_8 = arg_4 ** len(arg_1)

    for arg_9 in ('minimum', 'maximum'):
        arg_6['flux_{}'.format(arg_9)] = full(arg_8, nan, dtype=float)
        arg_6['carbon_yield_{}'.format(arg_9)] = full(
            arg_8, nan, dtype=float)
        arg_6['mass_yield_{}'.format(arg_9)] = full(
            arg_8, nan, dtype=float)

    arg_11 = pd.DataFrame(arg_6)

    with arg_0:
        arg_0.objective = arg_2
        arg_12 = list(sutil.linear_reaction_coefficients(arg_0))

        if len(arg_12) != 1:
            raise ValueError('cannot calculate yields for objectives with '
                             'multiple reactions')
        arg_13 = arg_12[0]
        arg_14 = fva(arg_0, arg_1, fraction_of_optimum=0)
        arg_14[arg_14.abs() < arg_5] = 0.0
        arg_4 = list(product(*[
            linspace(arg_14.at[rxn.id, "minimum"],
                     arg_14.at[rxn.id, "maximum"],
                     arg_4, endpoint=True) for rxn in arg_1]))
        arg_16 = pd.DataFrame(arg_4, columns=[rxn.id for rxn in arg_1])
        arg_11 = pd.concat([arg_11, arg_16], axis=1, copy=False)
        add_envelope(arg_0, arg_1, arg_11, arg_7, arg_13, arg_5)

    return arg_11


def Func(arg_0, arg_1, arg_2, arg_3):
    """
    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).
    """

    arg_4 = sum(
        total_components_flux(flux, components, consumption=True)
        for flux, components in zip(arg_0, arg_1))
    arg_5 = total_components_flux(
        arg_2, arg_3, consumption=False)
    try:
        return arg_5 / arg_4
    except ZeroDivisionError:
        return nan


def Func(arg_0):
    """
    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.
    """
    arg_1 = [coeff * met.elements.get('C', 0)
                  for met, coeff in iteritems(arg_0.metabolites)]
    return [arg_2 for arg_2 in arg_1 if arg_2 != 0]


def Func(arg_0):
    """Return the metabolite weight times its stoichiometric coefficient."""

    if len(arg_0.metabolites) != 1:
        raise ValueError('Reaction weight is only defined for single '
                         'metabolite products or educts.')

    arg_1, arg_2 = next(iteritems(arg_0.metabolites))

    return [arg_2 * arg_1.formula_weight]


def Func(arg_0):
    """
    Find all active carbon source reactions.

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

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

    """

    try:
        arg_0.slim_optimize(error_value=None)
    except OptimizationError:
        return []

    arg_1 = arg_0.reactions.get_by_any(list(arg_0.medium))
    arg_2 = [
        (arg_3, total_components_flux(arg_3.flux, reaction_elements(arg_3),
                                    consumption=True)) for arg_3 in arg_1]
    return [arg_3 for arg_3, arg_4 in arg_2 if arg_4 > 0]


def Func(arg_0, arg_1, arg_2=0.001, arg_3=None):
    """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 Func production capacity for

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

    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 Func_precursors and
        Func_products, respectively.

    """
    arg_1 = arg_0.reactions.get_by_any(arg_1)[0]
    with arg_0 as arg_4:
        arg_4.objective = arg_1
        if _optimize_or_value(arg_4, arg_3=arg_3) >= arg_2:
            return True
        else:
            arg_6 = dict()
            arg_6['precursors'] = Func_component(
                arg_0, arg_1, 'reactants', arg_2)
            arg_6['products'] = Func_component(
                arg_0, arg_1, 'products', arg_2)
            return arg_6


def Func(arg_0, arg_1, arg_2=0.001,
                      arg_3=None):
    """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.

    """
    warn('use assess_component instead', DeprecationWarning)
    return assess_component(arg_0, arg_1, 'reactants',
                            arg_2, arg_3)


def Func(arg_0, arg_1=None):
    """Modify a model so all feasible flux distributions are loopless.

    In most cases you probably want to use the much faster `loopless_solution`.
    May be used in cases where you want to add complex constraints and
    objecives (for instance quadratic objectives) to the model afterwards
    or use an approximation of Gibbs free energy directions in you model.
    Adds variables and constraints to a model which will disallow flux
    distributions with loops. The used formulation is described in [1]_.
    This function *will* modify your model.

    Parameters
    ----------
    model : cobra.Model
        The model to which to add the constraints.
    zero_cutoff : positive float, optional
        Cutoff used for null space. Coefficients with an absolute value smaller
        than `zero_cutoff` are considered to be zero (default model.tolerance).

    Returns
    -------
    Nothing

    References
    ----------
    .. [1] Elimination of thermodynamically infeasible loops in steady-state
       metabolic models. Schellenberger J, Lewis NE, Palsson BO. Biophys J.
       2011 Feb 2;100(3):544-53. doi: 10.1016/j.bpj.2010.12.3707. Erratum
       in: Biophys J. 2011 Mar 2;100(5):1381.
    """
    arg_1 = normalize_cutoff(arg_0, arg_1)

    arg_2 = [arg_8 for arg_8, r in enumerate(arg_0.reactions) if not r.boundary]
    arg_3 = create_stoichiometric_matrix(arg_0)[:, numpy.array(arg_2)]
    arg_4 = nullspace(arg_3).T
    arg_5 = max(max(abs(b) for b in r.bounds) for r in arg_0.reactions)
    arg_6 = arg_0.problem

    # Add indicator variables and new constraints
    arg_7 = []
    for arg_8 in arg_2:
        arg_9 = arg_0.reactions[arg_8]
        # indicator variable a_i
        arg_10 = arg_6.Variable("indicator_" + arg_9.id, type="binary")
        # -M*(1 - a_i) <= v_i <= M*a_i
        arg_11 = arg_6.Constraint(
            arg_9.flux_expression - arg_5 * arg_10,
            lb=-arg_5, ub=0, arg_15="on_off_" + arg_9.id)
        # -(max_bound + 1) * a_i + 1 <= G_i <= -(max_bound + 1) * a_i + 1000
        arg_12 = arg_6.Variable("delta_g_" + arg_9.id)
        arg_13 = arg_6.Constraint(
            arg_12 + (arg_5 + 1) * arg_10,
            lb=1, ub=arg_5, arg_15="delta_g_range_" + arg_9.id)
        arg_7.extend([arg_10, arg_11, arg_12, arg_13])

    arg_0.add_cons_vars(arg_7)

    # Add nullspace constraints for G_i
    for arg_8, arg_14 in enumerate(arg_4):
        arg_15 = "nullspace_constraint_" + str(arg_8)
        arg_16 = arg_6.Constraint(Zero, lb=0, ub=0, arg_15=arg_15)
        arg_0.add_cons_vars([arg_16])
        arg_17 = {arg_0.variables[
                 "delta_g_" + arg_0.reactions[ridx].id]: arg_14[arg_8]
                 for arg_8, ridx in enumerate(arg_2) if
                 abs(arg_14[arg_8]) > arg_1}
        arg_0.constraints[arg_15].set_linear_coefficients(arg_17)


def Func(arg_0, arg_1):
    """Add constraints for CycleFreeFlux."""
    arg_0.objective = arg_0.solver.interface.Objective(
        Zero, direction="min", sloppy=True)
    arg_3 = []
    for arg_4 in arg_0.reactions:
        arg_5 = arg_1[arg_4.id]
        if arg_4.boundary:
            arg_4.bounds = (arg_5, arg_5)
            continue
        if arg_5 >= 0:
            arg_4.bounds = max(0, arg_4.lower_bound), max(arg_5, arg_4.upper_bound)
            arg_3.append(arg_4.forward_variable)
        else:
            arg_4.bounds = min(arg_5, arg_4.lower_bound), min(0, arg_4.upper_bound)
            arg_3.append(arg_4.reverse_variable)

    arg_0.objective.set_linear_coefficients({arg_7: 1.0 for arg_7 in arg_3})


def Func(arg_0, arg_1=None):
    """Convert an existing solution to a loopless one.

    Removes as many loops as possible (see Notes).
    Uses the method from CycleFreeFlux [1]_ and is much faster than
    `add_loopless` and should therefore be the preferred option to get loopless
    flux distributions.

    Parameters
    ----------
    model : cobra.Model
        The model to which to add the constraints.
    fluxes : dict
        A dictionary {rxn_id: flux} that assigns a flux to each reaction. If
        not None will use the provided flux values to obtain a close loopless
        solution.

    Returns
    -------
    cobra.Solution
        A solution object containing the fluxes with the least amount of
        loops possible or None if the optimization failed (usually happening
        if the flux distribution in `fluxes` is infeasible).

    Notes
    -----
    The returned flux solution has the following properties:

    - it contains the minimal number of loops possible and no loops at all if
      all flux bounds include zero
    - it has an objective value close to the original one and the same
      objective value id the objective expression can not form a cycle
      (which is usually true since it consumes metabolites)
    - it has the same exact exchange fluxes as the previous solution
    - all fluxes have the same sign (flow in the same direction) as the
      previous solution

    References
    ----------
    .. [1] CycleFreeFlux: efficient removal of thermodynamically infeasible
       loops from flux distributions. Desouki AA, Jarre F, Gelius-Dietrich
       G, Lercher MJ. Bioinformatics. 2015 Jul 1;31(13):2159-65. doi:
       10.1093/bioinformatics/btv096.
    """
    # Need to reoptimize otherwise spurious solution artifacts can cause
    # all kinds of havoc
    # TODO: check solution status
    if arg_1 is None:
        arg_2 = arg_0.optimize(objective_sense=None)
        arg_1 = arg_2.fluxes

    with arg_0:
        arg_3 = arg_0.problem
        # Needs one fixed bound for cplex...
        arg_4 = arg_3.Constraint(
            arg_0.objective.expression,
            lb=-1e32, name="loopless_obj_constraint")
        arg_0.add_cons_vars([arg_4])
        _add_cycle_free(arg_0, arg_1)
        arg_5 = arg_0.optimize(objective_sense=None)
        arg_5.objective_value = arg_4.primal

    return arg_5


def Func(arg_0, arg_1, arg_2=False, arg_3=None):
    """Plugin to get a loopless FVA solution from single FVA iteration.

    Assumes the following about `model` and `reaction`:
    1. the model objective is set to be `reaction`
    2. the model has been optimized and contains the minimum/maximum flux for
       `reaction`
    3. the model contains an auxiliary variable called "fva_old_objective"
       denoting the previous objective

    Parameters
    ----------
    model : cobra.Model
        The model to be used.
    reaction : cobra.Reaction
        The reaction currently minimized/maximized.
    solution : boolean, optional
        Whether to return the entire solution or only the minimum/maximum for
        `reaction`.
    zero_cutoff : positive float, optional
        Cutoff used for loop removal. Fluxes with an absolute value smaller
        than `zero_cutoff` are considered to be zero (default model.tolerance).

    Returns
    -------
    single float or dict
        Returns the minimized/maximized flux through `reaction` if
        all_fluxes == False (default). Otherwise returns a loopless flux
        solution containing the minimum/maximum flux for `reaction`.
    """
    arg_3 = normalize_cutoff(arg_0, arg_3)

    arg_4 = arg_0.objective.value
    arg_5 = get_solution(arg_0)
    arg_6 = arg_0.objective.direction

    # boundary reactions can not be part of cycles
    if arg_1.boundary:
        if arg_2:
            return arg_5
        else:
            return arg_4

    with arg_0:
        _add_cycle_free(arg_0, arg_5.fluxes)
        arg_0.slim_optimize()

        # If the previous optimum is maintained in the loopless solution it was
        # loopless and we are done
        if abs(arg_1.flux - arg_4) < arg_3:
            if arg_2:
                return arg_5
            return arg_4

        # If previous optimum was not in the loopless solution create a new
        # almost loopless solution containing only loops including the current
        # reaction. Than remove all of those loops.
        arg_7 = get_solution(arg_0).fluxes
        arg_1.bounds = (arg_4, arg_4)
        arg_0.slim_optimize()
        arg_9 = get_solution(arg_0).fluxes

    with arg_0:
        # find the reactions with loops using the current reaction and remove
        # the loops
        for arg_10 in arg_0.reactions:
            arg_11 = arg_10.id
            if ((abs(arg_7[arg_11]) < arg_3) and
                    (abs(arg_9[arg_11]) > arg_3)):
                arg_10.bounds = max(0, arg_10.lower_bound), min(0, arg_10.upper_bound)

        if arg_2:
            arg_12 = arg_0.optimize()
        else:
            arg_0.slim_optimize()
            arg_12 = arg_1.flux
    arg_0.objective.direction = arg_6
    return arg_12


def Func(arg_0, arg_1='dense', arg_2=None):
    """Return a stoichiometric array representation of the given model.

    The the columns represent the reactions and rows represent
    metabolites. S[i,j] therefore contains the quantity of metabolite `i`
    produced (negative for consumed) by reaction `j`.

    Parameters
    ----------
    model : cobra.Model
        The cobra model to construct the matrix for.
    array_type : string
        The type of array to construct. if 'dense', return a standard
        numpy.array, 'dok', or 'lil' will construct a sparse array using
        scipy of the corresponding type and 'DataFrame' will give a
        pandas `DataFrame` with metabolite indices and reaction columns
    dtype : data-type
        The desired data-type for the array. If not given, defaults to float.

    Returns
    -------
    matrix of class `dtype`
        The stoichiometric matrix for the given model.
    """
    if arg_1 not in ('DataFrame', 'dense') and not dok_matrix:
        raise ValueError('Sparse matrices require scipy')

    if arg_2 is None:
        arg_2 = np.float64

    arg_3 = {
        'dense': np.zeros, 'dok': dok_matrix, 'lil': lil_matrix,
        'DataFrame': np.zeros,
    }

    arg_4 = len(arg_0.metabolites)
    arg_5 = len(arg_0.reactions)
    arg_6 = arg_3[arg_1]((arg_4, arg_5),
                                          arg_2=arg_2)

    arg_7 = arg_0.metabolites.index
    arg_8 = arg_0.reactions.index

    for arg_9 in arg_0.reactions:
        for arg_10, arg_11 in iteritems(arg_9.metabolites):
            arg_6[arg_7(arg_10), arg_8(arg_9)] = arg_11

    if arg_1 == 'DataFrame':
        arg_12 = [met.id for met in arg_0.metabolites]
        arg_13 = [rxn.id for rxn in arg_0.reactions]
        return pd.DataFrame(arg_6, index=arg_12, columns=arg_13)

    else:
        return arg_6


def Func(arg_0, arg_1=None, arg_2=False, arg_3=0.03, arg_4=1E-03):
    r"""
    Add constraints and objective for ROOM.

    This function adds variables and constraints for applying regulatory
    on/off minimization (ROOM) to the model.

    Parameters
    ----------
    model : cobra.Model
        The model to add ROOM constraints and objective to.
    solution : cobra.Solution, optional
        A previous solution to use as a reference. If no solution is given,
        one will be computed using pFBA.
    linear : bool, optional
        Whether to use the linear ROOM formulation or not (default False).
    delta: float, optional
        The relative tolerance range which is additive in nature
        (default 0.03).
    epsilon: float, optional
        The absolute range of tolerance which is multiplicative
        (default 0.001).

    Notes
    -----
    The formulation used here is the same as stated in the original paper [1]_.
    The mathematical expression is given below:

    minimize \sum_{i=1}^m y^i
    s.t. Sv = 0
         v_min <= v <= v_max
         v_j = 0
         j ∈ A
         for 1 <= i <= m
         v_i - y_i(v_{max,i} - w_i^u) <= w_i^u      (1)
         v_i - y_i(v_{min,i} - w_i^l) <= w_i^l      (2)
         y_i ∈ {0,1}                                (3)
         w_i^u = w_i + \delta|w_i| + \epsilon
         w_i^l = w_i - \delta|w_i| - \epsilon

    So, for the linear version of the ROOM , constraint (3) is relaxed to
    0 <= y_i <= 1.

    See Also
    --------
    pfba : parsimonious FBA

    References
    ----------
    .. [1] Tomer Shlomi, Omer Berkman and Eytan Ruppin, "Regulatory on/off
     minimization of metabolic flux changes after genetic perturbations",
     PNAS 2005 102 (21) 7695-7700; doi:10.1073/pnas.0406346102

    """

    if 'room_old_objective' in arg_0.solver.variables:
        raise ValueError('model is already adjusted for ROOM')

    # optimizes if no reference solution is provided
    if arg_1 is None:
        arg_1 = pfba(arg_0)

    arg_5 = arg_0.problem
    arg_6 = arg_5.Variable("room_old_objective", ub=arg_1.objective_value)
    arg_7 = arg_5.Constraint(
        arg_0.solver.objective.expression - arg_6,
        ub=0.0,
        lb=0.0,
        name="room_old_objective_constraint"
    )
    arg_0.objective = arg_5.Objective(Zero, direction="min", sloppy=True)
    arg_9 = [arg_6, arg_7]
    arg_10 = []

    for arg_11 in arg_0.reactions:
        arg_12 = arg_1.fluxes[arg_11.id]

        if arg_2:
            arg_13 = arg_5.Variable("y_" + arg_11.id, lb=0, ub=1)
            arg_3 = arg_4 = 0.0
        else:
            arg_13 = arg_5.Variable("y_" + arg_11.id, type="binary")

        # upper constraint
        arg_14 = arg_12 + (arg_3 * abs(arg_12)) + arg_4
        arg_15 = arg_5.Constraint(
            arg_11.flux_expression - arg_13 * (arg_11.upper_bound - arg_14),
            ub=arg_14, name="room_constraint_upper_" + arg_11.id)
        # lower constraint
        arg_16 = arg_12 - (arg_3 * abs(arg_12)) - arg_4
        arg_17 = arg_5.Constraint(
            arg_11.flux_expression - arg_13 * (arg_11.lower_bound - arg_16),
            lb=arg_16, name="room_constraint_lower_" + arg_11.id)
        arg_9.extend([arg_13, arg_15, arg_17])
        arg_10.append(arg_13)

    arg_0.add_cons_vars(arg_9)
    arg_0.objective.set_linear_coefficients({arg_18: 1.0 for arg_18 in arg_10})


def Func(arg_0, arg_1, arg_2="optgp", arg_3=100, arg_4=1, arg_5=None):
    """Sample valid flux distributions from a cobra model.

    The function Funcs valid flux distributions from a cobra model.
    Currently we support two methods:

    1. 'optgp' (default) which uses the OptGPSampler that supports parallel
        sampling [1]_. Requires large numbers of Funcs to be performant
        (n < 1000). For smaller Funcs 'achr' might be better suited.

    or

    2. 'achr' which uses artificial centering hit-and-run. This is a single
       process method with good convergence [2]_.

    Parameters
    ----------
    model : cobra.Model
        The model from which to Func flux distributions.
    n : int
        The number of Funcs to obtain. When using 'optgp' this must be a
        multiple of `processes`, otherwise a larger number of Funcs will be
        returned.
    method : str, optional
        The sampling algorithm to use.
    thinning : int, optional
        The thinning factor of the generated sampling chain. A thinning of 10
        means Funcs are returned every 10 steps. Defaults to 100 which in
        benchmarks gives approximately uncorrelated Funcs. If set to one
        will return all iterates.
    processes : int, optional
        Only used for 'optgp'. The number of processes used to generate
        Funcs.
    seed : int > 0, optional
        The random number seed to be used. Initialized to current time stamp
        if None.

    Returns
    -------
    pandas.DataFrame
        The generated flux Funcs. Each row corresponds to a Func of the
        fluxes and the columns are the reactions.

    Notes
    -----
    The Funcrs have a correction method to ensure equality feasibility for
    long-running chains, however this will only work for homogeneous models,
    meaning models with no non-zero fixed variables or constraints (
    right-hand side of the equalities are zero).

    References
    ----------
    .. [1] Megchelenbrink W, Huynen M, Marchiori E (2014)
       optGpSampler: An Improved Tool for Uniformly Sampling the Solution-Space
       of Genome-Scale Metabolic Networks.
       PLoS ONE 9(2): e86587.
    .. [2] Direction Choice for Accelerated Convergence in Hit-and-Run Sampling
       David E. Kaufman Robert L. Smith
       Operations Research 199846:1 , 84-95

    """

    if arg_2 == "optgp":
        arg_6 = OptGPSampler(arg_0, arg_4, arg_3=arg_3, arg_5=arg_5)
    elif arg_2 == "achr":
        arg_6 = ACHRSampler(arg_0, arg_3=arg_3, arg_5=arg_5)
    else:
        raise ValueError("method must be 'optgp' or 'achr'!")

    return pandas.DataFrame(columns=[arg_7.id for arg_7 in arg_0.reactions],
                            data=arg_6.Func(arg_1))


def Func(arg_0, arg_1):
    """
    Optimizely template tag.

    Renders Javascript code to set-up A/B testing.  You must supply
    your Optimizely account number in the ``OPTIMIZELY_ACCOUNT_NUMBER``
    setting.
    """
    arg_2 = arg_1.split_contents()
    if len(arg_2) > 1:
        raise TemplateSyntaxError("'%s' takes no arguments" % arg_2[0])
    return OptimizelyNode()


def Func(arg_0, arg_1):
    """
    Clicky tracking template tag.

    Renders Javascript code to track page visits.  You must supply
    your Clicky Site ID (as a string) in the ``CLICKY_SITE_ID``
    setting.
    """
    arg_2 = arg_1.split_contents()
    if len(arg_2) > 1:
        raise TemplateSyntaxError("'%s' takes no arguments" % arg_2[0])
    return ClickyNode()


def Func(arg_0, arg_1):
    """
    Bottom Chartbeat template tag.

    Render the bottom Javascript code for Chartbeat.  You must supply
    your Chartbeat User ID (as a string) in the ``CHARTBEAT_USER_ID``
    setting.
    """
    arg_2 = arg_1.split_contents()
    if len(arg_2) > 1:
        raise TemplateSyntaxError("'%s' takes no arguments" % arg_2[0])
    return ChartbeatBottomNode()


def Func(arg_0, arg_1):
    """
    Spring Metrics tracking template tag.

    Renders Javascript code to track page visits.  You must supply
    your Spring Metrics Tracking ID in the
    ``SPRING_METRICS_TRACKING_ID`` setting.
    """
    arg_2 = arg_1.split_contents()
    if len(arg_2) > 1:
        raise TemplateSyntaxError("'%s' takes no arguments" % arg_2[0])
    return SpringMetricsNode()


def Func(arg_0, arg_1):
    """
    SnapEngage set-up template tag.

    Renders Javascript code to set-up SnapEngage chat.  You must supply
    your widget ID in the ``SNAPENGAGE_WIDGET_ID`` setting.
    """
    arg_2 = arg_1.split_contents()
    if len(arg_2) > 1:
        raise TemplateSyntaxError("'%s' takes no arguments" % arg_2[0])
    return SnapEngageNode()


def Func(arg_0):
    """
    Coerce strings to hashable bytes.
    """
    if isinstance(arg_0, bytes):
        return arg_0
    elif isinstance(arg_0, str):
        return arg_0.encode('ascii')  # Fail on anything non-ASCII.
    else:
        raise TypeError(arg_0)


def Func(arg_0):
    """
    Return a SHA-256 HMAC `user_hash` as expected by Intercom, if configured.

    Return None if the `INTERCOM_HMAC_SECRET_KEY` setting is not configured.
    """
    if getattr(settings, 'INTERCOM_HMAC_SECRET_KEY', None):
        return hmac.new(
            key=_hashable_bytes(settings.INTERCOM_HMAC_SECRET_KEY),
            msg=_hashable_bytes(arg_0),
            digestmod=hashlib.sha256,
        ).hexdigest()
    else:
        return None


def Func(arg_0, arg_1):
    """
    Intercom.io template tag.

    Renders Javascript code to Func.io testing.  You must supply
    your APP ID account number in the ``INTERCOM_APP_ID``
    setting.
    """
    arg_2 = arg_1.split_contents()
    if len(arg_2) > 1:
        raise TemplateSyntaxError("'%s' takes no arguments" % arg_2[0])
    return IntercomNode()


def Func(arg_0, arg_1):
    """
    UserVoice tracking template tag.

    Renders Javascript code to track page visits.  You must supply
    your UserVoice Widget Key in the ``USERVOICE_WIDGET_KEY``
    setting or the ``Func_widget_key`` template context variable.
    """
    arg_2 = arg_1.split_contents()
    if len(arg_2) > 1:
        raise TemplateSyntaxError("'%s' takes no arguments" % arg_2[0])
    return UserVoiceNode()


def Func(arg_0, arg_1):
    """
    Piwik tracking template tag.

    Renders Javascript code to track page visits.  You must supply
    your Piwik domain (plus optional URI path), and tracked site ID
    in the ``PIWIK_DOMAIN_PATH`` and the ``PIWIK_SITE_ID`` setting.

    Custom variables can be passed in the ``Func_vars`` context
    variable.  It is an iterable of custom variables as tuples like:
    ``(index, name, value[, scope])`` where scope may be ``'page'``
    (default) or ``'visit'``.  Index should be an integer and the
    other parameters should be strings.
    """
    arg_2 = arg_1.split_contents()
    if len(arg_2) > 1:
        raise TemplateSyntaxError("'%s' takes no arguments" % arg_2[0])
    return PiwikNode()


def Func(arg_0, arg_1, arg_2):
    """
    Return a constant from ``django.conf.settings``.  The `setting`
    argument is the constant name, the `value_re` argument is a regular
    expression used to validate the setting value and the `invalid_msg`
    argument is used as exception message if the value is not valid.
    """
    try:
        arg_3 = getattr(settings, arg_0)
    except AttributeError:
        raise AnalyticalException("%s setting: not found" % arg_0)
    if not arg_3:
        raise AnalyticalException("%s setting is not set" % arg_0)
    arg_3 = str(arg_3)
    if not arg_1.search(arg_3):
        raise AnalyticalException("%s setting: %s: '%s'"
                                  % (arg_0, arg_2, arg_3))
    return arg_3