Return list of reactions that are constrained to zero flux.
11286
def find_zero_constrained_reactions(model):
    """"""
    return [rxn for rxn in model.reactions if
            rxn.lower_bound == 0 and
            rxn.upper_bound == 0]
990224
def maximize(self, reaction):
        

        self._prob.set_objective(self.flux_expr(reaction))
        self._solve()
278400
def _solve(self):
        """"""

        # Remove temporary constraints
        while len(self._remove_constr) > 0:
            self._remove_constr.pop().delete()

        try:
            self._prob.solve(lp.ObjectiveSense.Maximize)
        except lp.SolverError as e:
            raise_from(FluxBalanceError('Failed to solve: {}'.format(
                e), result=self._prob.result), e)
        finally:
            # Set temporary constraints to be removed on next solve call
            self._remove_constr = self._temp_constr
            self._temp_constr = []
541788
def run_fba_minimized(self, reaction):
        """"""

        epsilon = self._args.epsilon
        solver = self._get_solver()

        p = fluxanalysis.FluxBalanceProblem(self._mm, solver)

        start_time = time.time()

        # Maximize reaction flux
        try:
            p.maximize(reaction)
        except fluxanalysis.FluxBalanceError as e:
            self.report_flux_balance_error(e)

        fluxes = {r: p.get_flux(r) for r in self._mm.reactions}

        # Run flux minimization
        flux_var = p.get_flux_var(reaction)
        p.prob.add_linear_constraints(flux_var == p.get_flux(reaction))
        p.minimize_l1()

        logger.info('Solving took {:.2f} seconds'.format(
            time.time() - start_time))

        count = 0
        for reaction_id in self._mm.reactions:
            flux = p.get_flux(reaction_id)
            if abs(flux - fluxes[reaction_id]) > epsilon:
                count += 1
            yield reaction_id, flux
        logger.info('Minimized reactions: {}'.format(count))
971180
def run(self):
        """"""

        # Load compound information
        def compound_name(id):
            if id not in self._model.compounds:
                return id
            return self._model.compounds[id].properties.get('name', id)

        # Calculate penalty if penalty file exists
        penalties = {}
        if self._args.penalty is not None:
            for line in self._args.penalty:
                line, _, comment = line.partition('#')
                line = line.strip()
                if line == '':
                    continue
                rxnid, penalty = line.split(None, 1)
                penalties[rxnid] = float(penalty)

        core = set(self._mm.reactions)

        solver = self._get_solver(integer=True)
        default_comp = self._model.default_compartment
        epsilon = self._args.epsilon
        v_max = float(self._model.default_flux_limit)

        blocked = set()
        for compound in self._args.compound:
            if compound.compartment is None:
                compound = compound.in_compartment(default_comp)
            blocked.add(compound)

        if len(blocked) > 0:
            logger.info('Unblocking compounds: {}...'.format(
                ', '.join(text_type(c) for c in sorted(blocked))))
        else:
            logger.info(
                'Unblocking all compounds in model. Use --compound option to'
                ' unblock specific compounds.')
            blocked = set(self._mm.compounds)

        exclude = set()
        if self._model.biomass_reaction is not None:
            exclude.add(self._model.biomass_reaction)

        # Add exchange and transport reactions to database
        model_complete, weights = create_extended_model(
            self._model,
            db_penalty=self._args.db_penalty,
            ex_penalty=self._args.ex_penalty,
            tp_penalty=self._args.tp_penalty,
            penalties=penalties)

        implicit_sinks = not self._args.no_implicit_sinks

        logger.info('Searching for reactions to fill gaps')
        try:
            added_reactions, no_bounds_reactions = gapfill(
                model_complete, core, blocked, exclude, solver=solver,
                epsilon=epsilon, v_max=v_max, weights=weights,
                implicit_sinks=implicit_sinks,
                allow_bounds_expansion=self._args.allow_bounds_expansion)
        except GapFillError as e:
            self._log_epsilon_and_fail(epsilon, e)

        for reaction_id in sorted(self._mm.reactions):
            rx = self._mm.get_reaction(reaction_id)
            rxt = rx.translated_compounds(compound_name)
            print('{}\t{}\t{}\t{}'.format(reaction_id, 'Model', 0, rxt))

        for rxnid in sorted(added_reactions):
            rx = model_complete.get_reaction(rxnid)
            rxt = rx.translated_compounds(compound_name)
            print('{}\t{}\t{}\t{}'.format(
                rxnid, 'Add', weights.get(rxnid, 1), rxt))

        for rxnid in sorted(no_bounds_reactions):
            rx = model_complete.get_reaction(rxnid)
            rxt = rx.translated_compounds(compound_name)
            print('{}\t{}\t{}\t{}'.format(
                rxnid, 'Remove bounds', weights.get(rxnid, 1), rxt))
1252865
def reactions(columns, n_results, write_db, queries):
    """"""
    if not isinstance(queries, dict):
        query_dict = {}
        for q in queries:
            key, value = q.split('=')
            if key == 'distinct':
                if value in ['True', 'true']:
                    query_dict.update({key: True})
                    continue
            try:
                value = int(value)
                query_dict.update({key: value})
            except BaseException:
                query_dict.update({key: '{0}'.format(value)})
                # Keep {0} in string.format for python2.6 compatibility
    if write_db and n_results > 1000:
        print("""Warning: You're attempting to write more than a 1000 rows
        with geometries. This could take some time""")
    data = query.get_reactions(columns=columns,
                               n_results=n_results,
                               write_db=write_db,
                               **query_dict)

    if write_db:
        return
    table = []
    headers = []
    for row in data['reactions']['edges']:
        table += [list(row['node'].values())]

    headers = list(row['node'].keys())

    print(tabulate(table, headers) + '\n')
427406
def infer_compartment_entries(model):
    """"""
    compartment_ids = set()
    for reaction in model.reactions:
        equation = reaction.equation
        if equation is None:
            continue

        for compound, _ in equation.compounds:
            compartment = compound.compartment
            if compartment is None:
                compartment = model.default_compartment

            if compartment is not None:
                compartment_ids.add(compartment)

    for compartment in compartment_ids:
        if compartment in model.compartments:
            continue

        entry = DictCompartmentEntry(dict(id=compartment))
        model.compartments.add_entry(entry)
486514
def constrained_by(self):
        
        if self._is_constraint is None:
            return []
        params = []
        for var in self.is_constraint._vars:
            param = var.get_parameter()
            if param.uniqueid != self.uniqueid:
                params.append(param)
        return params
1242132
@Override
    public Iterable<IReaction> reactions() {
        return new Iterable<IReaction>() {

            @Override
            public Iterator<IReaction> iterator() {
                return new ReactionIterator();
            }
        };
    }
11925
def model_reaction_limits(model):
    """"""
    for reaction in sorted(model.reactions, key=lambda r: r.id):
        equation = reaction.properties.get('equation')
        if equation is None:
            continue

        # Determine the default flux limits. If the value is already at the
        # default it does not need to be included in the output.
        lower_default, upper_default = None, None
        if model.default_flux_limit is not None:
            if equation.direction.reverse:
                lower_default = -model.default_flux_limit
            else:
                lower_default = 0.0

            if equation.direction.forward:
                upper_default = model.default_flux_limit
            else:
                upper_default = 0.0

        lower_flux, upper_flux = None, None
        if reaction.id in model.limits:
            _, lower, upper = model.limits[reaction.id]
            lower_flux = _get_output_limit(lower, lower_default)
            upper_flux = _get_output_limit(upper, upper_default)

        if lower_flux is not None or upper_flux is not None:
            d = OrderedDict([('reaction', reaction.id)])
            d.update(_generate_limit_items(lower_flux, upper_flux))

            yield d
70614
def invariants(mol):
    """"""
    atom_ids = {}
    for a in mol.atoms:
        components = []
        components.append(a.number)
        components.append(len(a.oatoms))
        components.append(a.hcount)
        components.append(a.charge)
        components.append(a.mass)
        if len(a.rings) > 0:
            components.append(1)

        atom_ids[a.index] = gen_hash(components)

    return atom_ids
1324121
def get_residuals(ds, m):
    
    model_spectra = get_model_spectra(ds, m)
    resid = ds.test_flux - model_spectra
    return resid
848629
def remove_reaction(self, reaction):
        """"""

        if reaction not in self._reaction_set:
            return

        self._reaction_set.remove(reaction)
        self._limits_lower.pop(reaction, None)
        self._limits_upper.pop(reaction, None)

        # Remove compound from compound_set if it is not referenced
        # by any other reactions in the model.
        for compound, value in self._database.get_reaction_values(reaction):
            reactions = frozenset(
                self._database.get_compound_reactions(compound))
            if all(other_reaction not in self._reaction_set
                   for other_reaction in reactions):
                self._compound_set.remove(compound)
1277576
def run(self):
        """"""

        # Create solver
        solver = self._get_solver()

        # Load compound information
        def compound_name(id):
            if id not in self._model.compounds:
                return id
            return self._model.compounds[id].properties.get('name', id)

        # TODO: The exchange and transport reactions have tuple names. This
        # means that in Python 3 the reactions can no longer be directly
        # compared (e.g. while sorting) so define this helper function as a
        # workaround.
        def reaction_key(r):
            return r if isinstance(r, tuple) else (r,)

        # Calculate penalty if penalty file exists
        penalties = {}
        if self._args.penalty is not None:
            for line in self._args.penalty:
                line, _, comment = line.partition('#')
                line = line.strip()
                if line == '':
                    continue
                rxnid, penalty = line.split(None, 1)
                penalties[rxnid] = float(penalty)

        model_extended, weights = create_extended_model(
            self._model,
            db_penalty=self._args.db_penalty,
            ex_penalty=self._args.ex_penalty,
            tp_penalty=self._args.tp_penalty,
            penalties=penalties)

        epsilon = self._args.epsilon
        core = set()
        if self._args.subset is None:
            for r in self._mm.reactions:
                if not self._mm.is_exchange(r):
                    core.add(r)
        else:
            for line in self._args.subset:
                line = line.strip()
                if line == '':
                    continue
                core.add(line)
        induced = fastgapfill(model_extended, core, weights=weights,
                              epsilon=epsilon, solver=solver)

        for reaction_id in sorted(self._mm.reactions):
            rx = self._mm.get_reaction(reaction_id)
            rxt = rx.translated_compounds(compound_name)
            print('{}\t{}\t{}\t{}'.format(reaction_id, 'Model', 0, rxt))

        for rxnid in sorted(induced, key=reaction_key):
            if self._mm.has_reaction(rxnid):
                continue
            rx = model_extended.get_reaction(rxnid)
            rxt = rx.translated_compounds(compound_name)
            print('{}\t{}\t{}\t{}'.format(
                rxnid, 'Add', weights.get(rxnid, 1), rxt))
81851
def unique_reactions(df):
    
    reaction_list =[]
    for idx, entry in enumerate(df['reactants']):
        reaction = []
        for x in entry:
            reaction.append(x)
        reaction.append('-->')
        for y in df['products'][idx]:
            reaction.append(y)
        reaction_list.append(reaction)
    string_list = [str(reaction) for reaction in reaction_list]
    string_list = sorted(list(set(string_list)))
    reaction_list = [ast.literal_eval(entry) for entry in string_list]
    return(reaction_list)
608711
def flux(self) -> ErrorValue:
        """"""
        try:
            return ErrorValue(self._data['Flux'], self._data.setdefault('FluxError',0.0))
        except KeyError:
            return 1 / self.pixelsizex / self.pixelsizey / ErrorValue(self._data['NormFactor'],
                                                                      self._data.setdefault('NormFactorError',0.0))
1131283
def run_sink_check(self, model, solver, threshold, implicit_sinks=True):
        """"""
        prob = solver.create_problem()

        # Create flux variables
        v = prob.namespace()
        for reaction_id in model.reactions:
            lower, upper = model.limits[reaction_id]
            v.define([reaction_id], lower=lower, upper=upper)

        # Build mass balance constraints
        massbalance_lhs = {compound: 0 for compound in model.compounds}
        for spec, value in iteritems(model.matrix):
            compound, reaction_id = spec
            massbalance_lhs[compound] += v(reaction_id) * value

        mass_balance_constrs = {}
        for compound, lhs in iteritems(massbalance_lhs):
            if implicit_sinks:
                # The constraint is merely >0 meaning that we have implicit
                # sinks for all compounds.
                prob.add_linear_constraints(lhs >= 0)
            else:
                # Save these constraints so we can temporarily remove them
                # to create a sink.
                c, = prob.add_linear_constraints(lhs == 0)
                mass_balance_constrs[compound] = c

        for compound, lhs in sorted(iteritems(massbalance_lhs)):
            if not implicit_sinks:
                mass_balance_constrs[compound].delete()

            prob.set_objective(lhs)
            try:
                result = prob.solve(lp.ObjectiveSense.Maximize)
            except lp.SolverError as e:
                logger.warning('Failed to solve for compound: {} ({})'.format(
                    compound, e))

            if result.get_value(lhs) < threshold:
                yield compound

            if not implicit_sinks:
                # Restore mass balance constraint.
                c, = prob.add_linear_constraints(lhs == 0)
                mass_balance_constrs[compound] = c