Search is not available for this dataset
text
stringlengths
75
104k
def add_absolute_expression(model, expression, name="abs_var", ub=None, difference=0, add=True): """Add the absolute value of an expression to the model. Also defines a variable for the absolute value that can be used in other objectives or constraints. Parameters ---------- model : a cobra model The model to which to add the absolute expression. expression : A sympy expression Must be a valid expression within the Model's solver object. The absolute value is applied automatically on the expression. name : string The name of the newly created variable. ub : positive float The upper bound for the variable. difference : positive float The difference between the expression and the variable. add : bool Whether to add the variable to the model at once. Returns ------- namedtuple A named tuple with variable and two constraints (upper_constraint, lower_constraint) describing the new variable and the constraints that assign the absolute value of the expression to it. """ Components = namedtuple('Components', ['variable', 'upper_constraint', 'lower_constraint']) variable = model.problem.Variable(name, lb=0, ub=ub) # The following constraints enforce variable > expression and # variable > -expression upper_constraint = model.problem.Constraint(expression - variable, ub=difference, name="abs_pos_" + name), lower_constraint = model.problem.Constraint(expression + variable, lb=difference, name="abs_neg_" + name) to_add = Components(variable, upper_constraint, lower_constraint) if add: add_cons_vars_to_problem(model, to_add) return to_add
def fix_objective_as_constraint(model, fraction=1, bound=None, name='fixed_objective_{}'): """Fix current objective as an additional constraint. When adding constraints to a model, such as done in pFBA which minimizes total flux, these constraints can become too powerful, resulting in solutions that satisfy optimality but sacrifices too much for the original objective function. To avoid that, we can fix the current objective value as a constraint to ignore solutions that give a lower (or higher depending on the optimization direction) objective value than the original model. When done with the model as a context, the modification to the objective will be reverted when exiting that context. Parameters ---------- model : cobra.Model The model to operate on fraction : float The fraction of the optimum the objective is allowed to reach. bound : float, None The bound to use instead of fraction of maximum optimal value. If not None, fraction is ignored. name : str Name of the objective. May contain one `{}` placeholder which is filled with the name of the old objective. Returns ------- The value of the optimized objective * fraction """ fix_objective_name = name.format(model.objective.name) if fix_objective_name in model.constraints: model.solver.remove(fix_objective_name) if bound is None: bound = model.slim_optimize(error_value=None) * fraction if model.objective.direction == 'max': ub, lb = None, bound else: ub, lb = bound, None constraint = model.problem.Constraint( model.objective.expression, name=fix_objective_name, ub=ub, lb=lb) add_cons_vars_to_problem(model, constraint, sloppy=True) return bound
def check_solver_status(status, raise_error=False): """Perform standard checks on a solver's status.""" if status == OPTIMAL: return elif (status in has_primals) and not raise_error: warn("solver status is '{}'".format(status), UserWarning) elif status is None: raise OptimizationError( "model was not optimized yet or solver context switched") else: raise OptimizationError("solver status is '{}'".format(status))
def assert_optimal(model, message='optimization failed'): """Assert model solver status is optimal. Do nothing if model solver status is optimal, otherwise throw appropriate exception depending on the status. Parameters ---------- model : cobra.Model The model to check the solver status for. message : str (optional) Message to for the exception if solver status was not optimal. """ status = model.solver.status if status != OPTIMAL: exception_cls = OPTLANG_TO_EXCEPTIONS_DICT.get( status, OptimizationError) raise exception_cls("{} ({})".format(message, status))
def add_lp_feasibility(model): """ Add a new objective and variables to ensure a feasible solution. The optimized objective will be zero for a feasible solution and otherwise represent the distance from feasibility (please see [1]_ for more information). Parameters ---------- model : cobra.Model The model whose feasibility is to be tested. References ---------- .. [1] Gomez, Jose A., Kai Höffner, and Paul I. Barton. “DFBAlab: A Fast and Reliable MATLAB Code for Dynamic Flux Balance Analysis.” BMC Bioinformatics 15, no. 1 (December 18, 2014): 409. https://doi.org/10.1186/s12859-014-0409-8. """ obj_vars = [] prob = model.problem for met in model.metabolites: s_plus = prob.Variable("s_plus_" + met.id, lb=0) s_minus = prob.Variable("s_minus_" + met.id, lb=0) model.add_cons_vars([s_plus, s_minus]) model.constraints[met.id].set_linear_coefficients( {s_plus: 1.0, s_minus: -1.0}) obj_vars.append(s_plus) obj_vars.append(s_minus) model.objective = prob.Objective(Zero, sloppy=True, direction="min") model.objective.set_linear_coefficients({v: 1.0 for v in obj_vars})
def add_lexicographic_constraints(model, objectives, objective_direction='max'): """ Successively optimize separate targets in a specific order. For each objective, optimize the model and set the optimal value as a constraint. Proceed in the order of the objectives given. Due to the specific order this is called lexicographic FBA [1]_. This procedure is useful for returning unique solutions for a set of important fluxes. Typically this is applied to exchange fluxes. Parameters ---------- model : cobra.Model The model to be optimized. objectives : list A list of reactions (or objectives) in the model for which unique fluxes are to be determined. objective_direction : str or list, optional The desired objective direction for each reaction (if a list) or the objective direction to use for all reactions (default maximize). Returns ------- optimized_fluxes : pandas.Series A vector containing the optimized fluxes for each of the given reactions in `objectives`. References ---------- .. [1] Gomez, Jose A., Kai Höffner, and Paul I. Barton. “DFBAlab: A Fast and Reliable MATLAB Code for Dynamic Flux Balance Analysis.” BMC Bioinformatics 15, no. 1 (December 18, 2014): 409. https://doi.org/10.1186/s12859-014-0409-8. """ if type(objective_direction) is not list: objective_direction = [objective_direction] * len(objectives) constraints = [] for rxn_id, obj_dir in zip(objectives, objective_direction): model.objective = model.reactions.get_by_id(rxn_id) model.objective_direction = obj_dir constraints.append(fix_objective_as_constraint(model)) return pd.Series(constraints, index=objectives)
def shared_np_array(shape, data=None, integer=False): """Create a new numpy array that resides in shared memory. Parameters ---------- shape : tuple of ints The shape of the new array. data : numpy.array Data to copy to the new array. Has to have the same shape. integer : boolean Whether to use an integer array. Defaults to False which means float array. """ size = np.prod(shape) if integer: array = Array(ctypes.c_int64, int(size)) np_array = np.frombuffer(array.get_obj(), dtype="int64") else: array = Array(ctypes.c_double, int(size)) np_array = np.frombuffer(array.get_obj()) np_array = np_array.reshape(shape) if data is not None: if len(shape) != len(data.shape): raise ValueError("`data` must have the same dimensions" "as the created array.") same = all(x == y for x, y in zip(shape, data.shape)) if not same: raise ValueError("`data` must have the same shape" "as the created array.") np_array[:] = data return np_array
def step(sampler, x, delta, fraction=None, tries=0): """Sample a new feasible point from the point `x` in direction `delta`.""" prob = sampler.problem valid = ((np.abs(delta) > sampler.feasibility_tol) & np.logical_not(prob.variable_fixed)) # permissible alphas for staying in variable bounds valphas = ((1.0 - sampler.bounds_tol) * prob.variable_bounds - x)[:, valid] valphas = (valphas / delta[valid]).flatten() if prob.bounds.shape[0] > 0: # permissible alphas for staying in constraint bounds ineqs = prob.inequalities.dot(delta) valid = np.abs(ineqs) > sampler.feasibility_tol balphas = ((1.0 - sampler.bounds_tol) * prob.bounds - prob.inequalities.dot(x))[:, valid] balphas = (balphas / ineqs[valid]).flatten() # combined alphas alphas = np.hstack([valphas, balphas]) else: alphas = valphas pos_alphas = alphas[alphas > 0.0] neg_alphas = alphas[alphas <= 0.0] alpha_range = np.array([neg_alphas.max() if len(neg_alphas) > 0 else 0, pos_alphas.min() if len(pos_alphas) > 0 else 0]) if fraction: alpha = alpha_range[0] + fraction * (alpha_range[1] - alpha_range[0]) else: alpha = np.random.uniform(alpha_range[0], alpha_range[1]) p = x + alpha * delta # Numerical instabilities may cause bounds invalidation # reset sampler and sample from one of the original warmup directions # if that occurs. Also reset if we got stuck. if (np.any(sampler._bounds_dist(p) < -sampler.bounds_tol) or np.abs(np.abs(alpha_range).max() * delta).max() < sampler.bounds_tol): if tries > MAX_TRIES: raise RuntimeError("Can not escape sampling region, model seems" " numerically unstable :( Reporting the " "model to " "https://github.com/opencobra/cobrapy/issues " "will help us to fix this :)") LOGGER.info("found bounds infeasibility in sample, " "resetting to center") newdir = sampler.warmup[np.random.randint(sampler.n_warmup)] sampler.retries += 1 return step(sampler, sampler.center, newdir - sampler.center, None, tries + 1) return p
def __build_problem(self): """Build the matrix representation of the sampling problem.""" # Set up the mathematical problem prob = constraint_matrices(self.model, zero_tol=self.feasibility_tol) # check if there any non-zero equality constraints equalities = prob.equalities b = prob.b bounds = np.atleast_2d(prob.bounds).T var_bounds = np.atleast_2d(prob.variable_bounds).T homogeneous = all(np.abs(b) < self.feasibility_tol) fixed_non_zero = np.abs(prob.variable_bounds[:, 1]) > \ self.feasibility_tol fixed_non_zero &= prob.variable_fixed # check if there are any non-zero fixed variables, add them as # equalities to the stoichiometric matrix if any(fixed_non_zero): n_fixed = fixed_non_zero.sum() rows = np.zeros((n_fixed, prob.equalities.shape[1])) rows[range(n_fixed), np.where(fixed_non_zero)] = 1.0 equalities = np.vstack([equalities, rows]) var_b = prob.variable_bounds[:, 1] b = np.hstack([b, var_b[fixed_non_zero]]) homogeneous = False # Set up a projection that can cast point into the nullspace nulls = nullspace(equalities) # convert bounds to a matrix and add variable bounds as well return Problem( equalities=shared_np_array(equalities.shape, equalities), b=shared_np_array(b.shape, b), inequalities=shared_np_array(prob.inequalities.shape, prob.inequalities), bounds=shared_np_array(bounds.shape, bounds), variable_fixed=shared_np_array(prob.variable_fixed.shape, prob.variable_fixed, integer=True), variable_bounds=shared_np_array(var_bounds.shape, var_bounds), nullspace=shared_np_array(nulls.shape, nulls), homogeneous=homogeneous )
def generate_fva_warmup(self): """Generate the warmup points for the sampler. Generates warmup points by setting each flux as the sole objective and minimizing/maximizing it. Also caches the projection of the warmup points into the nullspace for non-homogeneous problems (only if necessary). """ self.n_warmup = 0 reactions = self.model.reactions self.warmup = np.zeros((2 * len(reactions), len(self.model.variables))) self.model.objective = Zero for sense in ("min", "max"): self.model.objective_direction = sense for i, r in enumerate(reactions): variables = (self.model.variables[self.fwd_idx[i]], self.model.variables[self.rev_idx[i]]) # Omit fixed reactions if they are non-homogeneous if r.upper_bound - r.lower_bound < self.bounds_tol: LOGGER.info("skipping fixed reaction %s" % r.id) continue self.model.objective.set_linear_coefficients( {variables[0]: 1, variables[1]: -1}) self.model.slim_optimize() if not self.model.solver.status == OPTIMAL: LOGGER.info("can not maximize reaction %s, skipping it" % r.id) continue primals = self.model.solver.primal_values sol = [primals[v.name] for v in self.model.variables] self.warmup[self.n_warmup, ] = sol self.n_warmup += 1 # Reset objective self.model.objective.set_linear_coefficients( {variables[0]: 0, variables[1]: 0}) # Shrink to measure self.warmup = self.warmup[0:self.n_warmup, :] # Remove redundant search directions keep = np.logical_not(self._is_redundant(self.warmup)) self.warmup = self.warmup[keep, :] self.n_warmup = self.warmup.shape[0] # Catch some special cases if len(self.warmup.shape) == 1 or self.warmup.shape[0] == 1: raise ValueError("Your flux cone consists only of a single point!") elif self.n_warmup == 2: if not self.problem.homogeneous: raise ValueError("Can not sample from an inhomogenous problem" " with only 2 search directions :(") LOGGER.info("All search directions on a line, adding another one.") newdir = self.warmup.T.dot([0.25, 0.25]) self.warmup = np.vstack([self.warmup, newdir]) self.n_warmup += 1 # Shrink warmup points to measure self.warmup = shared_np_array( (self.n_warmup, len(self.model.variables)), self.warmup)
def _reproject(self, p): """Reproject a point into the feasibility region. This function is guaranteed to return a new feasible point. However, no guarantees in terms of proximity to the original point can be made. Parameters ---------- p : numpy.array The current sample point. Returns ------- numpy.array A new feasible point. If `p` was feasible it wil return p. """ nulls = self.problem.nullspace equalities = self.problem.equalities # don't reproject if point is feasible if np.allclose(equalities.dot(p), self.problem.b, rtol=0, atol=self.feasibility_tol): new = p else: LOGGER.info("feasibility violated in sample" " %d, trying to reproject" % self.n_samples) new = nulls.dot(nulls.T.dot(p)) # Projections may violate bounds # set to random point in space in that case if any(new != p): LOGGER.info("reprojection failed in sample" " %d, using random point in space" % self.n_samples) new = self._random_point() return new
def _random_point(self): """Find an approximately random point in the flux cone.""" idx = np.random.randint(self.n_warmup, size=min(2, np.ceil(np.sqrt(self.n_warmup)))) return self.warmup[idx, :].mean(axis=0)
def _is_redundant(self, matrix, cutoff=None): """Identify rdeundant rows in a matrix that can be removed.""" cutoff = 1.0 - self.feasibility_tol # Avoid zero variances extra_col = matrix[:, 0] + 1 # Avoid zero rows being correlated with constant rows extra_col[matrix.sum(axis=1) == 0] = 2 corr = np.corrcoef(np.c_[matrix, extra_col]) corr = np.tril(corr, -1) return (np.abs(corr) > cutoff).any(axis=1)
def _bounds_dist(self, p): """Get the lower and upper bound distances. Negative is bad.""" prob = self.problem lb_dist = (p - prob.variable_bounds[0, ]).min() ub_dist = (prob.variable_bounds[1, ] - p).min() if prob.bounds.shape[0] > 0: const = prob.inequalities.dot(p) const_lb_dist = (const - prob.bounds[0, ]).min() const_ub_dist = (prob.bounds[1, ] - const).min() lb_dist = min(lb_dist, const_lb_dist) ub_dist = min(ub_dist, const_ub_dist) return np.array([lb_dist, ub_dist])
def batch(self, batch_size, batch_num, fluxes=True): """Create a batch generator. This is useful to generate n batches of m samples each. Parameters ---------- batch_size : int The number of samples contained in each batch (m). batch_num : int The number of batches in the generator (n). fluxes : boolean Whether to return fluxes or the internal solver variables. If set to False will return a variable for each forward and backward flux as well as all additional variables you might have defined in the model. Yields ------ pandas.DataFrame A DataFrame with dimensions (batch_size x n_r) containing a valid flux sample for a total of n_r reactions (or variables if fluxes=False) in each row. """ for i in range(batch_num): yield self.sample(batch_size, fluxes=fluxes)
def validate(self, samples): """Validate a set of samples for equality and inequality feasibility. Can be used to check whether the generated samples and warmup points are feasible. Parameters ---------- samples : numpy.matrix Must be of dimension (n_samples x n_reactions). Contains the samples to be validated. Samples must be from fluxes. Returns ------- numpy.array A one-dimensional numpy array of length containing a code of 1 to 3 letters denoting the validation result: - 'v' means feasible in bounds and equality constraints - 'l' means a lower bound violation - 'u' means a lower bound validation - 'e' means and equality constraint violation """ samples = np.atleast_2d(samples) prob = self.problem if samples.shape[1] == len(self.model.reactions): S = create_stoichiometric_matrix(self.model) b = np.array([self.model.constraints[m.id].lb for m in self.model.metabolites]) bounds = np.array([r.bounds for r in self.model.reactions]).T elif samples.shape[1] == len(self.model.variables): S = prob.equalities b = prob.b bounds = prob.variable_bounds else: raise ValueError("Wrong number of columns. samples must have a " "column for each flux or variable defined in the " "model!") feasibility = np.abs(S.dot(samples.T).T - b).max(axis=1) lb_error = (samples - bounds[0, ]).min(axis=1) ub_error = (bounds[1, ] - samples).min(axis=1) if (samples.shape[1] == len(self.model.variables) and prob.inequalities.shape[0]): consts = prob.inequalities.dot(samples.T) lb_error = np.minimum( lb_error, (consts - prob.bounds[0, ]).min(axis=1)) ub_error = np.minimum( ub_error, (prob.bounds[1, ] - consts).min(axis=1) ) valid = ( (feasibility < self.feasibility_tol) & (lb_error > -self.bounds_tol) & (ub_error > -self.bounds_tol)) codes = np.repeat("", valid.shape[0]).astype(np.dtype((str, 3))) codes[valid] = "v" codes[lb_error <= -self.bounds_tol] = np.char.add( codes[lb_error <= -self.bounds_tol], "l") codes[ub_error <= -self.bounds_tol] = np.char.add( codes[ub_error <= -self.bounds_tol], "u") codes[feasibility > self.feasibility_tol] = np.char.add( codes[feasibility > self.feasibility_tol], "e") return codes
def prune_unused_metabolites(cobra_model): """Remove metabolites that are not involved in any reactions and returns pruned model Parameters ---------- cobra_model: class:`~cobra.core.Model.Model` object the model to remove unused metabolites from Returns ------- output_model: class:`~cobra.core.Model.Model` object input model with unused metabolites removed inactive_metabolites: list of class:`~cobra.core.reaction.Reaction` list of metabolites that were removed """ output_model = cobra_model.copy() inactive_metabolites = [m for m in output_model.metabolites if len(m.reactions) == 0] output_model.remove_metabolites(inactive_metabolites) return output_model, inactive_metabolites
def prune_unused_reactions(cobra_model): """Remove reactions with no assigned metabolites, returns pruned model Parameters ---------- cobra_model: class:`~cobra.core.Model.Model` object the model to remove unused reactions from Returns ------- output_model: class:`~cobra.core.Model.Model` object input model with unused reactions removed reactions_to_prune: list of class:`~cobra.core.reaction.Reaction` list of reactions that were removed """ output_model = cobra_model.copy() reactions_to_prune = [r for r in output_model.reactions if len(r.metabolites) == 0] output_model.remove_reactions(reactions_to_prune) return output_model, reactions_to_prune
def undelete_model_genes(cobra_model): """Undoes the effects of a call to delete_model_genes in place. cobra_model: A cobra.Model which will be modified in place """ if cobra_model._trimmed_genes is not None: for x in cobra_model._trimmed_genes: x.functional = True if cobra_model._trimmed_reactions is not None: for the_reaction, (lower_bound, upper_bound) in \ cobra_model._trimmed_reactions.items(): the_reaction.lower_bound = lower_bound the_reaction.upper_bound = upper_bound cobra_model._trimmed_genes = [] cobra_model._trimmed_reactions = {} cobra_model._trimmed = False
def find_gene_knockout_reactions(cobra_model, gene_list, compiled_gene_reaction_rules=None): """identify reactions which will be disabled when the genes are knocked out cobra_model: :class:`~cobra.core.Model.Model` gene_list: iterable of :class:`~cobra.core.Gene.Gene` compiled_gene_reaction_rules: dict of {reaction_id: compiled_string} If provided, this gives pre-compiled gene_reaction_rule strings. The compiled rule strings can be evaluated much faster. If a rule is not provided, the regular expression evaluation will be used. Because not all gene_reaction_rule strings can be evaluated, this dict must exclude any rules which can not be used with eval. """ potential_reactions = set() for gene in gene_list: if isinstance(gene, string_types): gene = cobra_model.genes.get_by_id(gene) potential_reactions.update(gene._reaction) gene_set = {str(i) for i in gene_list} if compiled_gene_reaction_rules is None: compiled_gene_reaction_rules = {r: parse_gpr(r.gene_reaction_rule)[0] for r in potential_reactions} return [r for r in potential_reactions if not eval_gpr(compiled_gene_reaction_rules[r], gene_set)]
def delete_model_genes(cobra_model, gene_list, cumulative_deletions=True, disable_orphans=False): """delete_model_genes will set the upper and lower bounds for reactions catalysed by the genes in gene_list if deleting the genes means that the reaction cannot proceed according to cobra_model.reactions[:].gene_reaction_rule cumulative_deletions: False or True. If True then any previous deletions will be maintained in the model. """ if disable_orphans: raise NotImplementedError("disable_orphans not implemented") if not hasattr(cobra_model, '_trimmed'): cobra_model._trimmed = False cobra_model._trimmed_genes = [] cobra_model._trimmed_reactions = {} # Store the old bounds in here. # older models have this if cobra_model._trimmed_genes is None: cobra_model._trimmed_genes = [] if cobra_model._trimmed_reactions is None: cobra_model._trimmed_reactions = {} # Allow a single gene to be fed in as a string instead of a list. if not hasattr(gene_list, '__iter__') or \ hasattr(gene_list, 'id'): # cobra.Gene has __iter__ gene_list = [gene_list] if not hasattr(gene_list[0], 'id'): if gene_list[0] in cobra_model.genes: tmp_gene_dict = dict([(x.id, x) for x in cobra_model.genes]) else: # assume we're dealing with names if no match to an id tmp_gene_dict = dict([(x.name, x) for x in cobra_model.genes]) gene_list = [tmp_gene_dict[x] for x in gene_list] # Make the genes non-functional for x in gene_list: x.functional = False if cumulative_deletions: gene_list.extend(cobra_model._trimmed_genes) else: undelete_model_genes(cobra_model) for the_reaction in find_gene_knockout_reactions(cobra_model, gene_list): # Running this on an already deleted reaction will overwrite the # stored reaction bounds. if the_reaction in cobra_model._trimmed_reactions: continue old_lower_bound = the_reaction.lower_bound old_upper_bound = the_reaction.upper_bound cobra_model._trimmed_reactions[the_reaction] = (old_lower_bound, old_upper_bound) the_reaction.lower_bound = 0. the_reaction.upper_bound = 0. cobra_model._trimmed = True cobra_model._trimmed_genes = list(set(cobra_model._trimmed_genes + gene_list))
def remove_genes(cobra_model, gene_list, remove_reactions=True): """remove genes entirely from the model This will also simplify all gene_reaction_rules with this gene inactivated.""" gene_set = {cobra_model.genes.get_by_id(str(i)) for i in gene_list} gene_id_set = {i.id for i in gene_set} remover = _GeneRemover(gene_id_set) ast_rules = get_compiled_gene_reaction_rules(cobra_model) target_reactions = [] for reaction, rule in iteritems(ast_rules): if reaction.gene_reaction_rule is None or \ len(reaction.gene_reaction_rule) == 0: continue # reactions to remove if remove_reactions and not eval_gpr(rule, gene_id_set): target_reactions.append(reaction) else: # if the reaction is not removed, remove the gene # from its gpr remover.visit(rule) new_rule = ast2str(rule) if new_rule != reaction.gene_reaction_rule: reaction.gene_reaction_rule = new_rule for gene in gene_set: cobra_model.genes.remove(gene) # remove reference to the gene in all groups associated_groups = cobra_model.get_associated_groups(gene) for group in associated_groups: group.remove_members(gene) cobra_model.remove_reactions(target_reactions)
def gapfill(model, universal=None, lower_bound=0.05, penalties=None, demand_reactions=True, exchange_reactions=False, iterations=1): """Perform gapfilling on a model. See documentation for the class GapFiller. Parameters ---------- model : cobra.Model The model to perform gap filling on. universal : cobra.Model, None A universal model with reactions that can be used to complete the model. Only gapfill considering demand and exchange reactions if left missing. lower_bound : float The minimally accepted flux for the objective in the filled model. penalties : dict, None A dictionary with keys being 'universal' (all reactions included in the universal model), 'exchange' and 'demand' (all additionally added exchange and demand reactions) for the three reaction types. Can also have reaction identifiers for reaction specific costs. Defaults are 1, 100 and 1 respectively. iterations : int The number of rounds of gapfilling to perform. For every iteration, the penalty for every used reaction increases linearly. This way, the algorithm is encouraged to search for alternative solutions which may include previously used reactions. I.e., with enough iterations pathways including 10 steps will eventually be reported even if the shortest pathway is a single reaction. exchange_reactions : bool Consider adding exchange (uptake) reactions for all metabolites in the model. demand_reactions : bool Consider adding demand reactions for all metabolites. Returns ------- iterable list of lists with on set of reactions that completes the model per requested iteration. Examples -------- >>> import cobra.test as ct >>> from cobra import Model >>> from cobra.flux_analysis import gapfill >>> model = ct.create_test_model("salmonella") >>> universal = Model('universal') >>> universal.add_reactions(model.reactions.GF6PTA.copy()) >>> model.remove_reactions([model.reactions.GF6PTA]) >>> gapfill(model, universal) """ gapfiller = GapFiller(model, universal=universal, lower_bound=lower_bound, penalties=penalties, demand_reactions=demand_reactions, exchange_reactions=exchange_reactions) return gapfiller.fill(iterations=iterations)
def extend_model(self, exchange_reactions=False, demand_reactions=True): """Extend gapfilling model. Add reactions from universal model and optionally exchange and demand reactions for all metabolites in the model to perform gapfilling on. Parameters ---------- exchange_reactions : bool Consider adding exchange (uptake) reactions for all metabolites in the model. demand_reactions : bool Consider adding demand reactions for all metabolites. """ for rxn in self.universal.reactions: rxn.gapfilling_type = 'universal' new_metabolites = self.universal.metabolites.query( lambda metabolite: metabolite not in self.model.metabolites ) self.model.add_metabolites(new_metabolites) existing_exchanges = [] for rxn in self.universal.boundary: existing_exchanges = existing_exchanges + \ [met.id for met in list(rxn.metabolites)] for met in self.model.metabolites: if exchange_reactions: # check for exchange reaction in model already if met.id not in existing_exchanges: rxn = self.universal.add_boundary( met, type='exchange_smiley', lb=-1000, ub=0, reaction_id='EX_{}'.format(met.id)) rxn.gapfilling_type = 'exchange' if demand_reactions: rxn = self.universal.add_boundary( met, type='demand_smiley', lb=0, ub=1000, reaction_id='DM_{}'.format(met.id)) rxn.gapfilling_type = 'demand' new_reactions = self.universal.reactions.query( lambda reaction: reaction not in self.model.reactions ) self.model.add_reactions(new_reactions)
def update_costs(self): """Update the coefficients for the indicator variables in the objective. Done incrementally so that second time the function is called, active indicators in the current solutions gets higher cost than the unused indicators. """ for var in self.indicators: if var not in self.costs: self.costs[var] = var.cost else: if var._get_primal() > self.integer_threshold: self.costs[var] += var.cost self.model.objective.set_linear_coefficients(self.costs)
def add_switches_and_objective(self): """ Update gapfilling model with switches and the indicator objective. """ constraints = list() big_m = max(max(abs(b) for b in r.bounds) for r in self.model.reactions) prob = self.model.problem for rxn in self.model.reactions: if not hasattr(rxn, 'gapfilling_type'): continue indicator = prob.Variable( name='indicator_{}'.format(rxn.id), lb=0, ub=1, type='binary') if rxn.id in self.penalties: indicator.cost = self.penalties[rxn.id] else: indicator.cost = self.penalties[rxn.gapfilling_type] indicator.rxn_id = rxn.id self.indicators.append(indicator) # if z = 1 v_i is allowed non-zero # v_i - Mz <= 0 and v_i + Mz >= 0 constraint_lb = prob.Constraint( rxn.flux_expression - big_m * indicator, ub=0, name='constraint_lb_{}'.format(rxn.id), sloppy=True) constraint_ub = prob.Constraint( rxn.flux_expression + big_m * indicator, lb=0, name='constraint_ub_{}'.format(rxn.id), sloppy=True) constraints.extend([constraint_lb, constraint_ub]) self.model.add_cons_vars(self.indicators) self.model.add_cons_vars(constraints, sloppy=True) self.model.objective = prob.Objective( Zero, direction='min', sloppy=True) self.model.objective.set_linear_coefficients({ i: 1 for i in self.indicators}) self.update_costs()
def fill(self, iterations=1): """Perform the gapfilling by iteratively solving the model, updating the costs and recording the used reactions. Parameters ---------- iterations : int The number of rounds of gapfilling to perform. For every iteration, the penalty for every used reaction increases linearly. This way, the algorithm is encouraged to search for alternative solutions which may include previously used reactions. I.e., with enough iterations pathways including 10 steps will eventually be reported even if the shortest pathway is a single reaction. Returns ------- iterable A list of lists where each element is a list reactions that were used to gapfill the model. Raises ------ RuntimeError If the model fails to be validated (i.e. the original model with the proposed reactions added, still cannot get the required flux through the objective). """ used_reactions = list() for i in range(iterations): self.model.slim_optimize(error_value=None, message='gapfilling optimization failed') solution = [self.model.reactions.get_by_id(ind.rxn_id) for ind in self.indicators if ind._get_primal() > self.integer_threshold] if not self.validate(solution): raise RuntimeError('failed to validate gapfilled model, ' 'try lowering the integer_threshold') used_reactions.append(solution) self.update_costs() return used_reactions
def find_external_compartment(model): """Find the external compartment in the model. Uses a simple heuristic where the external compartment should be the one with the most exchange reactions. Arguments --------- model : cobra.Model A cobra model. Returns ------- str The putative external compartment. """ if model.boundary: counts = pd.Series(tuple(r.compartments)[0] for r in model.boundary) most = counts.value_counts() most = most.index[most == most.max()].to_series() else: most = None like_external = compartment_shortlist["e"] + ["e"] matches = pd.Series([co in like_external for co in model.compartments], index=model.compartments) if matches.sum() == 1: compartment = matches.index[matches][0] LOGGER.info("Compartment `%s` sounds like an external compartment. " "Using this one without counting boundary reactions" % compartment) return compartment elif most is not None and matches.sum() > 1 and matches[most].sum() == 1: compartment = most[matches[most]][0] LOGGER.warning("There are several compartments that look like an " "external compartment but `%s` has the most boundary " "reactions, so using that as the external " "compartment." % compartment) return compartment elif matches.sum() > 1: raise RuntimeError("There are several compartments (%s) that look " "like external compartments but we can't tell " "which one to use. Consider renaming your " "compartments please.") if most is not None: return most[0] LOGGER.warning("Could not identify an external compartment by name and" " choosing one with the most boundary reactions. That " "might be complete nonsense or change suddenly. " "Consider renaming your compartments using " "`Model.compartments` to fix this.") # No info in the model, so give up raise RuntimeError("The heuristic for discovering an external compartment " "relies on names and boundary reactions. Yet, there " "are neither compartments with recognized names nor " "boundary reactions in the model.")
def is_boundary_type(reaction, boundary_type, external_compartment): """Check whether a reaction is an exchange reaction. Arguments --------- reaction : cobra.Reaction The reaction to check. boundary_type : str What boundary type to check for. Must be one of "exchange", "demand", or "sink". external_compartment : str The id for the external compartment. Returns ------- boolean Whether the reaction looks like the requested type. Might be based on a heuristic. """ # Check if the reaction has an annotation. Annotations dominate everything. sbo_term = reaction.annotation.get("sbo", "") if isinstance(sbo_term, list): sbo_term = sbo_term[0] sbo_term = sbo_term.upper() if sbo_term == sbo_terms[boundary_type]: return True if sbo_term in [sbo_terms[k] for k in sbo_terms if k != boundary_type]: return False # Check if the reaction is in the correct compartment (exterior or inside) correct_compartment = external_compartment in reaction.compartments if boundary_type != "exchange": correct_compartment = not correct_compartment # Check if the reaction has the correct reversibility rev_type = True if boundary_type == "demand": rev_type = not reaction.reversibility elif boundary_type == "sink": rev_type = reaction.reversibility return (reaction.boundary and not any(ex in reaction.id for ex in excludes[boundary_type]) and correct_compartment and rev_type)
def find_boundary_types(model, boundary_type, external_compartment=None): """Find specific boundary reactions. Arguments --------- model : cobra.Model A cobra model. boundary_type : str What boundary type to check for. Must be one of "exchange", "demand", or "sink". external_compartment : str or None The id for the external compartment. If None it will be detected automatically. Returns ------- list of cobra.reaction A list of likely boundary reactions of a user defined type. """ if not model.boundary: LOGGER.warning("There are no boundary reactions in this model. " "Therefore specific types of boundary reactions such " "as 'exchanges', 'demands' or 'sinks' cannot be " "identified.") return [] if external_compartment is None: external_compartment = find_external_compartment(model) return model.reactions.query( lambda r: is_boundary_type(r, boundary_type, external_compartment))
def normalize_cutoff(model, zero_cutoff=None): """Return a valid zero cutoff value.""" if zero_cutoff is None: return model.tolerance else: if zero_cutoff < model.tolerance: raise ValueError( "The chosen zero cutoff cannot be less than the model's " "tolerance value." ) else: return zero_cutoff
def _sample_chain(args): """Sample a single chain for OptGPSampler. center and n_samples are updated locally and forgotten afterwards. """ n, idx = args # has to be this way to work in Python 2.7 center = sampler.center np.random.seed((sampler._seed + idx) % np.iinfo(np.int32).max) pi = np.random.randint(sampler.n_warmup) prev = sampler.warmup[pi, ] prev = step(sampler, center, prev - center, 0.95) n_samples = max(sampler.n_samples, 1) samples = np.zeros((n, center.shape[0])) for i in range(1, sampler.thinning * n + 1): pi = np.random.randint(sampler.n_warmup) delta = sampler.warmup[pi, ] - center prev = step(sampler, prev, delta) if sampler.problem.homogeneous and ( n_samples * sampler.thinning % sampler.nproj == 0): prev = sampler._reproject(prev) center = sampler._reproject(center) if i % sampler.thinning == 0: samples[i//sampler.thinning - 1, ] = prev center = ((n_samples * center) / (n_samples + 1) + prev / (n_samples + 1)) n_samples += 1 return (sampler.retries, samples)
def sample(self, n, fluxes=True): """Generate a set of samples. This is the basic sampling function for all hit-and-run samplers. Paramters --------- n : int The minimum number of samples that are generated at once (see Notes). fluxes : boolean Whether to return fluxes or the internal solver variables. If set to False will return a variable for each forward and backward flux as well as all additional variables you might have defined in the model. Returns ------- numpy.matrix Returns a matrix with `n` rows, each containing a flux sample. Notes ----- Performance of this function linearly depends on the number of reactions in your model and the thinning factor. If the number of processes is larger than one, computation is split across as the CPUs of your machine. This may shorten computation time. However, there is also overhead in setting up parallel computation so we recommend to calculate large numbers of samples at once (`n` > 1000). """ if self.processes > 1: n_process = np.ceil(n / self.processes).astype(int) n = n_process * self.processes # The cast to list is weird but not doing it gives recursion # limit errors, something weird going on with multiprocessing args = list(zip( [n_process] * self.processes, range(self.processes))) # No with statement or starmap here since Python 2.x # does not support it :( mp = Pool(self.processes, initializer=mp_init, initargs=(self,)) results = mp.map(_sample_chain, args, chunksize=1) mp.close() mp.join() chains = np.vstack([r[1] for r in results]) self.retries += sum(r[0] for r in results) else: mp_init(self) results = _sample_chain((n, 0)) chains = results[1] # Update the global center self.center = (self.n_samples * self.center + np.atleast_2d(chains).sum(0)) / (self.n_samples + n) self.n_samples += n if fluxes: names = [r.id for r in self.model.reactions] return pandas.DataFrame( chains[:, self.fwd_idx] - chains[:, self.rev_idx], columns=names) else: names = [v.name for v in self.model.variables] return pandas.DataFrame(chains, columns=names)
def ast2str(expr, level=0, names=None): """convert compiled ast to gene_reaction_rule str Parameters ---------- expr : str string for a gene reaction rule, e.g "a and b" level : int internal use only names : dict Dict where each element id a gene identifier and the value is the gene name. Use this to get a rule str which uses names instead. This should be done for display purposes only. All gene_reaction_rule strings which are computed with should use the id. Returns ------ string The gene reaction rule """ if isinstance(expr, Expression): return ast2str(expr.body, 0, names) \ if hasattr(expr, "body") else "" elif isinstance(expr, Name): return names.get(expr.id, expr.id) if names else expr.id elif isinstance(expr, BoolOp): op = expr.op if isinstance(op, Or): str_exp = " or ".join(ast2str(i, level + 1, names) for i in expr.values) elif isinstance(op, And): str_exp = " and ".join(ast2str(i, level + 1, names) for i in expr.values) else: raise TypeError("unsupported operation " + op.__class__.__name) return "(" + str_exp + ")" if level else str_exp elif expr is None: return "" else: raise TypeError("unsupported operation " + repr(expr))
def eval_gpr(expr, knockouts): """evaluate compiled ast of gene_reaction_rule with knockouts Parameters ---------- expr : Expression The ast of the gene reaction rule knockouts : DictList, set Set of genes that are knocked out Returns ------- bool True if the gene reaction rule is true with the given knockouts otherwise false """ if isinstance(expr, Expression): return eval_gpr(expr.body, knockouts) elif isinstance(expr, Name): return expr.id not in knockouts elif isinstance(expr, BoolOp): op = expr.op if isinstance(op, Or): return any(eval_gpr(i, knockouts) for i in expr.values) elif isinstance(op, And): return all(eval_gpr(i, knockouts) for i in expr.values) else: raise TypeError("unsupported operation " + op.__class__.__name__) elif expr is None: return True else: raise TypeError("unsupported operation " + repr(expr))
def parse_gpr(str_expr): """parse gpr into AST Parameters ---------- str_expr : string string with the gene reaction rule to parse Returns ------- tuple elements ast_tree and gene_ids as a set """ str_expr = str_expr.strip() if len(str_expr) == 0: return None, set() for char, escaped in replacements: if char in str_expr: str_expr = str_expr.replace(char, escaped) escaped_str = keyword_re.sub("__cobra_escape__", str_expr) escaped_str = number_start_re.sub("__cobra_escape__", escaped_str) tree = ast_parse(escaped_str, "<string>", "eval") cleaner = GPRCleaner() cleaner.visit(tree) eval_gpr(tree, set()) # ensure the rule can be evaluated return tree, cleaner.gene_set
def knock_out(self): """Knockout gene by marking it as non-functional and setting all associated reactions bounds to zero. The change is reverted upon exit if executed within the model as context. """ self.functional = False for reaction in self.reactions: if not reaction.functional: reaction.bounds = (0, 0)
def remove_from_model(self, model=None, make_dependent_reactions_nonfunctional=True): """Removes the association Parameters ---------- model : cobra model The model to remove the gene from make_dependent_reactions_nonfunctional : bool If True then replace the gene with 'False' in the gene association, else replace the gene with 'True' .. deprecated :: 0.4 Use cobra.manipulation.delete_model_genes to simulate knockouts and cobra.manipulation.remove_genes to remove genes from the model. """ warn("Use cobra.manipulation.remove_genes instead") if model is not None: if model != self._model: raise Exception("%s is a member of %s, not %s" % (repr(self), repr(self._model), repr(model))) if self._model is None: raise Exception('%s is not in a model' % repr(self)) if make_dependent_reactions_nonfunctional: gene_state = 'False' else: gene_state = 'True' the_gene_re = re.compile('(^|(?<=( |\()))%s(?=( |\)|$))' % re.escape(self.id)) # remove reference to the gene in all groups associated_groups = self._model.get_associated_groups(self) for group in associated_groups: group.remove_members(self) self._model.genes.remove(self) self._model = None for the_reaction in list(self._reaction): the_reaction._gene_reaction_rule = the_gene_re.sub( gene_state, the_reaction.gene_reaction_rule) the_reaction._genes.remove(self) # Now, deactivate the reaction if its gene association evaluates # to False the_gene_reaction_relation = the_reaction.gene_reaction_rule for other_gene in the_reaction._genes: other_gene_re = re.compile('(^|(?<=( |\()))%s(?=( |\)|$))' % re.escape(other_gene.id)) the_gene_reaction_relation = other_gene_re.sub( 'True', the_gene_reaction_relation) if not eval(the_gene_reaction_relation): the_reaction.lower_bound = 0 the_reaction.upper_bound = 0 self._reaction.clear()
def moma(model, solution=None, linear=True): """ Compute a single solution based on (linear) MOMA. Compute a new flux distribution that is at a minimal distance to a previous reference solution. Minimization of metabolic adjustment (MOMA) is generally used to assess the impact of knock-outs. Thus the typical usage is to provide a wildtype flux distribution as reference and a model in knock-out state. Parameters ---------- model : cobra.Model The model state to compute a MOMA-based solution for. solution : cobra.Solution, optional A (wildtype) reference solution. linear : bool, optional Whether to use the linear MOMA formulation or not (default True). Returns ------- cobra.Solution A flux distribution that is at a minimal distance compared to the reference solution. See Also -------- add_moma : add MOMA constraints and objective """ with model: add_moma(model=model, solution=solution, linear=linear) solution = model.optimize() return solution
def add_moma(model, solution=None, linear=True): r"""Add constraints and objective representing for MOMA. This adds variables and constraints for the minimization of metabolic adjustment (MOMA) to the model. Parameters ---------- model : cobra.Model The model to add MOMA 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 MOMA formulation or not (default True). Notes ----- In the original MOMA [1]_ specification one looks for the flux distribution of the deletion (v^d) closest to the fluxes without the deletion (v). In math this means: minimize \sum_i (v^d_i - v_i)^2 s.t. Sv^d = 0 lb_i <= v^d_i <= ub_i Here, we use a variable transformation v^t := v^d_i - v_i. Substituting and using the fact that Sv = 0 gives: minimize \sum_i (v^t_i)^2 s.t. Sv^d = 0 v^t = v^d_i - v_i lb_i <= v^d_i <= ub_i So basically we just re-center the flux space at the old solution and then find the flux distribution closest to the new zero (center). This is the same strategy as used in cameo. In the case of linear MOMA [2]_, we instead minimize \sum_i abs(v^t_i). The linear MOMA is typically significantly faster. Also quadratic MOMA tends to give flux distributions in which all fluxes deviate from the reference fluxes a little bit whereas linear MOMA tends to give flux distributions where the majority of fluxes are the same reference with few fluxes deviating a lot (typical effect of L2 norm vs L1 norm). The former objective function is saved in the optlang solver interface as ``"moma_old_objective"`` and this can be used to immediately extract the value of the former objective after MOMA optimization. See Also -------- pfba : parsimonious FBA References ---------- .. [1] Segrè, Daniel, Dennis Vitkup, and George M. Church. “Analysis of Optimality in Natural and Perturbed Metabolic Networks.” Proceedings of the National Academy of Sciences 99, no. 23 (November 12, 2002): 15112. https://doi.org/10.1073/pnas.232349399. .. [2] Becker, Scott A, Adam M Feist, Monica L Mo, Gregory Hannum, Bernhard Ø Palsson, and Markus J Herrgard. “Quantitative Prediction of Cellular Metabolism with Constraint-Based Models: The COBRA Toolbox.” Nature Protocols 2 (March 29, 2007): 727. """ if 'moma_old_objective' in model.solver.variables: raise ValueError('model is already adjusted for MOMA') # Fall back to default QP solver if current one has no QP capability if not linear: model.solver = sutil.choose_solver(model, qp=True) if solution is None: solution = pfba(model) prob = model.problem v = prob.Variable("moma_old_objective") c = prob.Constraint(model.solver.objective.expression - v, lb=0.0, ub=0.0, name="moma_old_objective_constraint") to_add = [v, c] model.objective = prob.Objective(Zero, direction="min", sloppy=True) obj_vars = [] for r in model.reactions: flux = solution.fluxes[r.id] if linear: components = sutil.add_absolute_expression( model, r.flux_expression, name="moma_dist_" + r.id, difference=flux, add=False) to_add.extend(components) obj_vars.append(components.variable) else: dist = prob.Variable("moma_dist_" + r.id) const = prob.Constraint(r.flux_expression - dist, lb=flux, ub=flux, name="moma_constraint_" + r.id) to_add.extend([dist, const]) obj_vars.append(dist ** 2) model.add_cons_vars(to_add) if linear: model.objective.set_linear_coefficients({v: 1.0 for v in obj_vars}) else: model.objective = prob.Objective( add(obj_vars), direction="min", sloppy=True)
def _fix_type(value): """convert possible types to str, float, and bool""" # Because numpy floats can not be pickled to json if isinstance(value, string_types): return str(value) if isinstance(value, float_): return float(value) if isinstance(value, bool_): return bool(value) if isinstance(value, set): return list(value) if isinstance(value, dict): return OrderedDict((key, value[key]) for key in sorted(value)) # handle legacy Formula type if value.__class__.__name__ == "Formula": return str(value) if value is None: return "" return value
def _update_optional(cobra_object, new_dict, optional_attribute_dict, ordered_keys): """update new_dict with optional attributes from cobra_object""" for key in ordered_keys: default = optional_attribute_dict[key] value = getattr(cobra_object, key) if value is None or value == default: continue new_dict[key] = _fix_type(value)
def model_to_dict(model, sort=False): """Convert model to a dict. Parameters ---------- model : cobra.Model The model to reformulate as a dict. sort : bool, optional Whether to sort the metabolites, reactions, and genes or maintain the order defined in the model. Returns ------- OrderedDict A dictionary with elements, 'genes', 'compartments', 'id', 'metabolites', 'notes' and 'reactions'; where 'metabolites', 'genes' and 'metabolites' are in turn lists with dictionaries holding all attributes to form the corresponding object. See Also -------- cobra.io.model_from_dict """ obj = OrderedDict() obj["metabolites"] = list(map(metabolite_to_dict, model.metabolites)) obj["reactions"] = list(map(reaction_to_dict, model.reactions)) obj["genes"] = list(map(gene_to_dict, model.genes)) obj["id"] = model.id _update_optional(model, obj, _OPTIONAL_MODEL_ATTRIBUTES, _ORDERED_OPTIONAL_MODEL_KEYS) if sort: get_id = itemgetter("id") obj["metabolites"].sort(key=get_id) obj["reactions"].sort(key=get_id) obj["genes"].sort(key=get_id) return obj
def model_from_dict(obj): """Build a model from a dict. Models stored in json are first formulated as a dict that can be read to cobra model using this function. Parameters ---------- obj : dict A dictionary with elements, 'genes', 'compartments', 'id', 'metabolites', 'notes' and 'reactions'; where 'metabolites', 'genes' and 'metabolites' are in turn lists with dictionaries holding all attributes to form the corresponding object. Returns ------- cora.core.Model The generated model. See Also -------- cobra.io.model_to_dict """ if 'reactions' not in obj: raise ValueError('Object has no reactions attribute. Cannot load.') model = Model() model.add_metabolites( [metabolite_from_dict(metabolite) for metabolite in obj['metabolites']] ) model.genes.extend([gene_from_dict(gene) for gene in obj['genes']]) model.add_reactions( [reaction_from_dict(reaction, model) for reaction in obj['reactions']] ) objective_reactions = [rxn for rxn in obj['reactions'] if rxn.get('objective_coefficient', 0) != 0] coefficients = { model.reactions.get_by_id(rxn['id']): rxn['objective_coefficient'] for rxn in objective_reactions} set_objective(model, coefficients) for k, v in iteritems(obj): if k in {'id', 'name', 'notes', 'compartments', 'annotation'}: setattr(model, k, v) return model
def _get_id_compartment(id): """extract the compartment from the id string""" bracket_search = _bracket_re.findall(id) if len(bracket_search) == 1: return bracket_search[0][1] underscore_search = _underscore_re.findall(id) if len(underscore_search) == 1: return underscore_search[0][1] return None
def _cell(x): """translate an array x into a MATLAB cell array""" x_no_none = [i if i is not None else "" for i in x] return array(x_no_none, dtype=np_object)
def load_matlab_model(infile_path, variable_name=None, inf=inf): """Load a cobra model stored as a .mat file Parameters ---------- infile_path: str path to the file to to read variable_name: str, optional The variable name of the model in the .mat file. If this is not specified, then the first MATLAB variable which looks like a COBRA model will be used inf: value The value to use for infinite bounds. Some solvers do not handle infinite values so for using those, set this to a high numeric value. Returns ------- cobra.core.Model.Model: The resulting cobra model """ if not scipy_io: raise ImportError('load_matlab_model requires scipy') data = scipy_io.loadmat(infile_path) possible_names = [] if variable_name is None: # skip meta variables meta_vars = {"__globals__", "__header__", "__version__"} possible_names = sorted(i for i in data if i not in meta_vars) if len(possible_names) == 1: variable_name = possible_names[0] if variable_name is not None: return from_mat_struct(data[variable_name], model_id=variable_name, inf=inf) for possible_name in possible_names: try: return from_mat_struct(data[possible_name], model_id=possible_name, inf=inf) except ValueError: pass # If code here is executed, then no model was found. raise IOError("no COBRA model found")
def save_matlab_model(model, file_name, varname=None): """Save the cobra model as a .mat file. This .mat file can be used directly in the MATLAB version of COBRA. Parameters ---------- model : cobra.core.Model.Model object The model to save file_name : str or file-like object The file to save to varname : string The name of the variable within the workspace """ if not scipy_io: raise ImportError('load_matlab_model requires scipy') if varname is None: varname = str(model.id) \ if model.id is not None and len(model.id) > 0 \ else "exported_model" mat = create_mat_dict(model) scipy_io.savemat(file_name, {varname: mat}, appendmat=True, oned_as="column")
def create_mat_dict(model): """create a dict mapping model attributes to arrays""" rxns = model.reactions mets = model.metabolites mat = OrderedDict() mat["mets"] = _cell([met_id for met_id in create_mat_metabolite_id(model)]) mat["metNames"] = _cell(mets.list_attr("name")) mat["metFormulas"] = _cell([str(m.formula) for m in mets]) try: mat["metCharge"] = array(mets.list_attr("charge")) * 1. except TypeError: # can't have any None entries for charge, or this will fail pass mat["genes"] = _cell(model.genes.list_attr("id")) # make a matrix for rxnGeneMat # reactions are rows, genes are columns rxn_gene = scipy_sparse.dok_matrix((len(model.reactions), len(model.genes))) if min(rxn_gene.shape) > 0: for i, reaction in enumerate(model.reactions): for gene in reaction.genes: rxn_gene[i, model.genes.index(gene)] = 1 mat["rxnGeneMat"] = rxn_gene mat["grRules"] = _cell(rxns.list_attr("gene_reaction_rule")) mat["rxns"] = _cell(rxns.list_attr("id")) mat["rxnNames"] = _cell(rxns.list_attr("name")) mat["subSystems"] = _cell(rxns.list_attr("subsystem")) stoich_mat = create_stoichiometric_matrix(model) mat["S"] = stoich_mat if stoich_mat is not None else [[]] # multiply by 1 to convert to float, working around scipy bug # https://github.com/scipy/scipy/issues/4537 mat["lb"] = array(rxns.list_attr("lower_bound")) * 1. mat["ub"] = array(rxns.list_attr("upper_bound")) * 1. mat["b"] = array(mets.list_attr("_bound")) * 1. mat["c"] = array(rxns.list_attr("objective_coefficient")) * 1. mat["rev"] = array(rxns.list_attr("reversibility")) * 1 mat["description"] = str(model.id) return mat
def from_mat_struct(mat_struct, model_id=None, inf=inf): """create a model from the COBRA toolbox struct The struct will be a dict read in by scipy.io.loadmat """ m = mat_struct if m.dtype.names is None: raise ValueError("not a valid mat struct") if not {"rxns", "mets", "S", "lb", "ub"} <= set(m.dtype.names): raise ValueError("not a valid mat struct") if "c" in m.dtype.names: c_vec = m["c"][0, 0] else: c_vec = None warn("objective vector 'c' not found") model = Model() if model_id is not None: model.id = model_id elif "description" in m.dtype.names: description = m["description"][0, 0][0] if not isinstance(description, string_types) and len(description) > 1: model.id = description[0] warn("Several IDs detected, only using the first.") else: model.id = description else: model.id = "imported_model" for i, name in enumerate(m["mets"][0, 0]): new_metabolite = Metabolite() new_metabolite.id = str(name[0][0]) if all(var in m.dtype.names for var in ['metComps', 'comps', 'compNames']): comp_index = m["metComps"][0, 0][i][0] - 1 new_metabolite.compartment = m['comps'][0, 0][comp_index][0][0] if new_metabolite.compartment not in model.compartments: comp_name = m['compNames'][0, 0][comp_index][0][0] model.compartments[new_metabolite.compartment] = comp_name else: new_metabolite.compartment = _get_id_compartment(new_metabolite.id) if new_metabolite.compartment not in model.compartments: model.compartments[ new_metabolite.compartment] = new_metabolite.compartment try: new_metabolite.name = str(m["metNames"][0, 0][i][0][0]) except (IndexError, ValueError): pass try: new_metabolite.formula = str(m["metFormulas"][0][0][i][0][0]) except (IndexError, ValueError): pass try: new_metabolite.charge = float(m["metCharge"][0, 0][i][0]) int_charge = int(new_metabolite.charge) if new_metabolite.charge == int_charge: new_metabolite.charge = int_charge except (IndexError, ValueError): pass model.add_metabolites([new_metabolite]) new_reactions = [] coefficients = {} for i, name in enumerate(m["rxns"][0, 0]): new_reaction = Reaction() new_reaction.id = str(name[0][0]) new_reaction.lower_bound = float(m["lb"][0, 0][i][0]) new_reaction.upper_bound = float(m["ub"][0, 0][i][0]) if isinf(new_reaction.lower_bound) and new_reaction.lower_bound < 0: new_reaction.lower_bound = -inf if isinf(new_reaction.upper_bound) and new_reaction.upper_bound > 0: new_reaction.upper_bound = inf if c_vec is not None: coefficients[new_reaction] = float(c_vec[i][0]) try: new_reaction.gene_reaction_rule = str(m['grRules'][0, 0][i][0][0]) except (IndexError, ValueError): pass try: new_reaction.name = str(m["rxnNames"][0, 0][i][0][0]) except (IndexError, ValueError): pass try: new_reaction.subsystem = str(m['subSystems'][0, 0][i][0][0]) except (IndexError, ValueError): pass new_reactions.append(new_reaction) model.add_reactions(new_reactions) set_objective(model, coefficients) coo = scipy_sparse.coo_matrix(m["S"][0, 0]) for i, j, v in zip(coo.row, coo.col, coo.data): model.reactions[j].add_metabolites({model.metabolites[i]: v}) return model
def model_to_pymatbridge(model, variable_name="model", matlab=None): """send the model to a MATLAB workspace through pymatbridge This model can then be manipulated through the COBRA toolbox Parameters ---------- variable_name : str The variable name to which the model will be assigned in the MATLAB workspace matlab : None or pymatbridge.Matlab instance The MATLAB workspace to which the variable will be sent. If this is None, then this will be sent to the same environment used in IPython magics. """ if scipy_sparse is None: raise ImportError("`model_to_pymatbridge` requires scipy!") if matlab is None: # assumed to be running an IPython magic from IPython import get_ipython matlab = get_ipython().magics_manager.registry["MatlabMagics"].Matlab model_info = create_mat_dict(model) S = model_info["S"].todok() model_info["S"] = 0 temp_S_name = "cobra_pymatbridge_temp_" + uuid4().hex _check(matlab.set_variable(variable_name, model_info)) _check(matlab.set_variable(temp_S_name, S)) _check(matlab.run_code("%s.S = %s;" % (variable_name, temp_S_name))) # all vectors need to be transposed for i in model_info.keys(): if i == "S": continue _check(matlab.run_code("{0}.{1} = {0}.{1}';".format(variable_name, i))) _check(matlab.run_code("clear %s;" % temp_S_name))
def get_context(obj): """Search for a context manager""" try: return obj._contexts[-1] except (AttributeError, IndexError): pass try: return obj._model._contexts[-1] except (AttributeError, IndexError): pass return None
def resettable(f): """A decorator to simplify the context management of simple object attributes. Gets the value of the attribute prior to setting it, and stores a function to set the value to the old value in the HistoryManager. """ def wrapper(self, new_value): context = get_context(self) if context: old_value = getattr(self, f.__name__) # Don't clutter the context with unchanged variables if old_value == new_value: return context(partial(f, self, old_value)) f(self, new_value) return wrapper
def get_solution(model, reactions=None, metabolites=None, raise_error=False): """ Generate a solution representation of the current solver state. Parameters --------- model : cobra.Model The model whose reactions to retrieve values for. reactions : list, optional An iterable of `cobra.Reaction` objects. Uses `model.reactions` by default. metabolites : list, optional An iterable of `cobra.Metabolite` objects. Uses `model.metabolites` by default. raise_error : bool If true, raise an OptimizationError if solver status is not optimal. Returns ------- cobra.Solution Note ---- This is only intended for the `optlang` solver interfaces and not the legacy solvers. """ check_solver_status(model.solver.status, raise_error=raise_error) if reactions is None: reactions = model.reactions if metabolites is None: metabolites = model.metabolites rxn_index = list() fluxes = empty(len(reactions)) reduced = empty(len(reactions)) var_primals = model.solver.primal_values shadow = empty(len(metabolites)) if model.solver.is_integer: reduced.fill(nan) shadow.fill(nan) for (i, rxn) in enumerate(reactions): rxn_index.append(rxn.id) fluxes[i] = var_primals[rxn.id] - var_primals[rxn.reverse_id] met_index = [met.id for met in metabolites] else: var_duals = model.solver.reduced_costs for (i, rxn) in enumerate(reactions): forward = rxn.id reverse = rxn.reverse_id rxn_index.append(forward) fluxes[i] = var_primals[forward] - var_primals[reverse] reduced[i] = var_duals[forward] - var_duals[reverse] met_index = list() constr_duals = model.solver.shadow_prices for (i, met) in enumerate(metabolites): met_index.append(met.id) shadow[i] = constr_duals[met.id] return Solution(model.solver.objective.value, model.solver.status, Series(index=rxn_index, data=fluxes, name="fluxes"), Series(index=rxn_index, data=reduced, name="reduced_costs"), Series(index=met_index, data=shadow, name="shadow_prices"))
def get_metabolite_compartments(self): """Return all metabolites' compartments.""" warn('use Model.compartments instead', DeprecationWarning) return {met.compartment for met in self.metabolites if met.compartment is not None}
def medium(self, medium): """Get or set the constraints on the model exchanges. `model.medium` returns a dictionary of the bounds for each of the boundary reactions, in the form of `{rxn_id: bound}`, where `bound` specifies the absolute value of the bound in direction of metabolite creation (i.e., lower_bound for `met <--`, upper_bound for `met -->`) Parameters ---------- medium: dictionary-like The medium to initialize. medium should be a dictionary defining `{rxn_id: bound}` pairs. """ def set_active_bound(reaction, bound): if reaction.reactants: reaction.lower_bound = -bound elif reaction.products: reaction.upper_bound = bound # Set the given media bounds media_rxns = list() exchange_rxns = frozenset(self.exchanges) for rxn_id, bound in iteritems(medium): rxn = self.reactions.get_by_id(rxn_id) if rxn not in exchange_rxns: LOGGER.warn("%s does not seem to be an" " an exchange reaction. Applying bounds anyway.", rxn.id) media_rxns.append(rxn) set_active_bound(rxn, bound) media_rxns = frozenset(media_rxns) # Turn off reactions not present in media for rxn in (exchange_rxns - media_rxns): set_active_bound(rxn, 0)
def copy(self): """Provides a partial 'deepcopy' of the Model. All of the Metabolite, Gene, and Reaction objects are created anew but in a faster fashion than deepcopy """ new = self.__class__() do_not_copy_by_ref = {"metabolites", "reactions", "genes", "notes", "annotation", "groups"} for attr in self.__dict__: if attr not in do_not_copy_by_ref: new.__dict__[attr] = self.__dict__[attr] new.notes = deepcopy(self.notes) new.annotation = deepcopy(self.annotation) new.metabolites = DictList() do_not_copy_by_ref = {"_reaction", "_model"} for metabolite in self.metabolites: new_met = metabolite.__class__() for attr, value in iteritems(metabolite.__dict__): if attr not in do_not_copy_by_ref: new_met.__dict__[attr] = copy( value) if attr == "formula" else value new_met._model = new new.metabolites.append(new_met) new.genes = DictList() for gene in self.genes: new_gene = gene.__class__(None) for attr, value in iteritems(gene.__dict__): if attr not in do_not_copy_by_ref: new_gene.__dict__[attr] = copy( value) if attr == "formula" else value new_gene._model = new new.genes.append(new_gene) new.reactions = DictList() do_not_copy_by_ref = {"_model", "_metabolites", "_genes"} for reaction in self.reactions: new_reaction = reaction.__class__() for attr, value in iteritems(reaction.__dict__): if attr not in do_not_copy_by_ref: new_reaction.__dict__[attr] = copy(value) new_reaction._model = new new.reactions.append(new_reaction) # update awareness for metabolite, stoic in iteritems(reaction._metabolites): new_met = new.metabolites.get_by_id(metabolite.id) new_reaction._metabolites[new_met] = stoic new_met._reaction.add(new_reaction) for gene in reaction._genes: new_gene = new.genes.get_by_id(gene.id) new_reaction._genes.add(new_gene) new_gene._reaction.add(new_reaction) new.groups = DictList() do_not_copy_by_ref = {"_model", "_members"} # Groups can be members of other groups. We initialize them first and # then update their members. for group in self.groups: new_group = group.__class__(group.id) for attr, value in iteritems(group.__dict__): if attr not in do_not_copy_by_ref: new_group.__dict__[attr] = copy(value) new_group._model = new new.groups.append(new_group) for group in self.groups: new_group = new.groups.get_by_id(group.id) # update awareness, as in the reaction copies new_objects = [] for member in group.members: if isinstance(member, Metabolite): new_object = new.metabolites.get_by_id(member.id) elif isinstance(member, Reaction): new_object = new.reactions.get_by_id(member.id) elif isinstance(member, Gene): new_object = new.genes.get_by_id(member.id) elif isinstance(member, Group): new_object = new.genes.get_by_id(member.id) else: raise TypeError( "The group member {!r} is unexpectedly not a " "metabolite, reaction, gene, nor another " "group.".format(member)) new_objects.append(new_object) new_group.add_members(new_objects) try: new._solver = deepcopy(self.solver) # Cplex has an issue with deep copies except Exception: # pragma: no cover new._solver = copy(self.solver) # pragma: no cover # it doesn't make sense to retain the context of a copied model so # assign a new empty context new._contexts = list() return new
def add_metabolites(self, metabolite_list): """Will add a list of metabolites to the model object and add new constraints accordingly. The change is reverted upon exit when using the model as a context. Parameters ---------- metabolite_list : A list of `cobra.core.Metabolite` objects """ if not hasattr(metabolite_list, '__iter__'): metabolite_list = [metabolite_list] if len(metabolite_list) == 0: return None # First check whether the metabolites exist in the model metabolite_list = [x for x in metabolite_list if x.id not in self.metabolites] bad_ids = [m for m in metabolite_list if not isinstance(m.id, string_types) or len(m.id) < 1] if len(bad_ids) != 0: raise ValueError('invalid identifiers in {}'.format(repr(bad_ids))) for x in metabolite_list: x._model = self self.metabolites += metabolite_list # from cameo ... to_add = [] for met in metabolite_list: if met.id not in self.constraints: constraint = self.problem.Constraint( Zero, name=met.id, lb=0, ub=0) to_add += [constraint] self.add_cons_vars(to_add) context = get_context(self) if context: context(partial(self.metabolites.__isub__, metabolite_list)) for x in metabolite_list: # Do we care? context(partial(setattr, x, '_model', None))
def remove_metabolites(self, metabolite_list, destructive=False): """Remove a list of metabolites from the the object. The change is reverted upon exit when using the model as a context. Parameters ---------- metabolite_list : list A list with `cobra.Metabolite` objects as elements. destructive : bool If False then the metabolite is removed from all associated reactions. If True then all associated reactions are removed from the Model. """ if not hasattr(metabolite_list, '__iter__'): metabolite_list = [metabolite_list] # Make sure metabolites exist in model metabolite_list = [x for x in metabolite_list if x.id in self.metabolites] for x in metabolite_list: x._model = None # remove reference to the metabolite in all groups associated_groups = self.get_associated_groups(x) for group in associated_groups: group.remove_members(x) if not destructive: for the_reaction in list(x._reaction): the_coefficient = the_reaction._metabolites[x] the_reaction.subtract_metabolites({x: the_coefficient}) else: for x in list(x._reaction): x.remove_from_model() self.metabolites -= metabolite_list to_remove = [self.solver.constraints[m.id] for m in metabolite_list] self.remove_cons_vars(to_remove) context = get_context(self) if context: context(partial(self.metabolites.__iadd__, metabolite_list)) for x in metabolite_list: context(partial(setattr, x, '_model', self))
def add_boundary(self, metabolite, type="exchange", reaction_id=None, lb=None, ub=None, sbo_term=None): """ Add a boundary reaction for a given metabolite. There are three different types of pre-defined boundary reactions: exchange, demand, and sink reactions. An exchange reaction is a reversible, unbalanced reaction that adds to or removes an extracellular metabolite from the extracellular compartment. A demand reaction is an irreversible reaction that consumes an intracellular metabolite. A sink is similar to an exchange but specifically for intracellular metabolites. If you set the reaction `type` to something else, you must specify the desired identifier of the created reaction along with its upper and lower bound. The name will be given by the metabolite name and the given `type`. Parameters ---------- metabolite : cobra.Metabolite Any given metabolite. The compartment is not checked but you are encouraged to stick to the definition of exchanges and sinks. type : str, {"exchange", "demand", "sink"} Using one of the pre-defined reaction types is easiest. If you want to create your own kind of boundary reaction choose any other string, e.g., 'my-boundary'. reaction_id : str, optional The ID of the resulting reaction. This takes precedence over the auto-generated identifiers but beware that it might make boundary reactions harder to identify afterwards when using `model.boundary` or specifically `model.exchanges` etc. lb : float, optional The lower bound of the resulting reaction. ub : float, optional The upper bound of the resulting reaction. sbo_term : str, optional A correct SBO term is set for the available types. If a custom type is chosen, a suitable SBO term should also be set. Returns ------- cobra.Reaction The created boundary reaction. Examples -------- >>> import cobra.test >>> model = cobra.test.create_test_model("textbook") >>> demand = model.add_boundary(model.metabolites.atp_c, type="demand") >>> demand.id 'DM_atp_c' >>> demand.name 'ATP demand' >>> demand.bounds (0, 1000.0) >>> demand.build_reaction_string() 'atp_c --> ' """ ub = CONFIGURATION.upper_bound if ub is None else ub lb = CONFIGURATION.lower_bound if lb is None else lb types = { "exchange": ("EX", lb, ub, sbo_terms["exchange"]), "demand": ("DM", 0, ub, sbo_terms["demand"]), "sink": ("SK", lb, ub, sbo_terms["sink"]) } if type == "exchange": external = find_external_compartment(self) if metabolite.compartment != external: raise ValueError("The metabolite is not an external metabolite" " (compartment is `%s` but should be `%s`). " "Did you mean to add a demand or sink? " "If not, either change its compartment or " "rename the model compartments to fix this." % (metabolite.compartment, external)) if type in types: prefix, lb, ub, default_term = types[type] if reaction_id is None: reaction_id = "{}_{}".format(prefix, metabolite.id) if sbo_term is None: sbo_term = default_term if reaction_id is None: raise ValueError( "Custom types of boundary reactions require a custom " "identifier. Please set the `reaction_id`.") if reaction_id in self.reactions: raise ValueError( "Boundary reaction '{}' already exists.".format(reaction_id)) name = "{} {}".format(metabolite.name, type) rxn = Reaction(id=reaction_id, name=name, lower_bound=lb, upper_bound=ub) rxn.add_metabolites({metabolite: -1}) if sbo_term: rxn.annotation["sbo"] = sbo_term self.add_reactions([rxn]) return rxn
def add_reactions(self, reaction_list): """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(rxn): if rxn.id in self.reactions: LOGGER.warning( "Ignoring reaction '%s' since it already exists.", rxn.id) return False return True # First check whether the reactions exist in the model. pruned = DictList(filter(existing_filter, reaction_list)) context = get_context(self) # Add reactions. Also take care of genes and metabolites in the loop. for reaction in pruned: reaction._model = self # Build a `list()` because the dict will be modified in the loop. for metabolite in list(reaction.metabolites): # TODO: Should we add a copy of the metabolite instead? if metabolite not in self.metabolites: self.add_metabolites(metabolite) # 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. stoichiometry = reaction._metabolites.pop(metabolite) model_metabolite = self.metabolites.get_by_id( metabolite.id) reaction._metabolites[model_metabolite] = stoichiometry model_metabolite._reaction.add(reaction) if context: context(partial( model_metabolite._reaction.remove, reaction)) for gene in list(reaction._genes): # If the gene is not in the model, add it if not self.genes.has_id(gene.id): self.genes += [gene] gene._model = self if context: # Remove the gene later context(partial(self.genes.__isub__, [gene])) context(partial(setattr, gene, '_model', None)) # Otherwise, make the gene point to the one in the model else: model_gene = self.genes.get_by_id(gene.id) if model_gene is not gene: reaction._dissociate_gene(gene) reaction._associate_gene(model_gene) self.reactions += pruned if context: context(partial(self.reactions.__isub__, pruned)) # from cameo ... self._populate_solver(pruned)
def remove_reactions(self, reactions, remove_orphans=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(reactions, string_types) or hasattr(reactions, "id"): warn("need to pass in a list") reactions = [reactions] context = get_context(self) for reaction in reactions: # Make sure the reaction is in the model try: reaction = self.reactions[self.reactions.index(reaction)] except ValueError: warn('%s not in %s' % (reaction, self)) else: forward = reaction.forward_variable reverse = reaction.reverse_variable if context: obj_coef = reaction.objective_coefficient if obj_coef != 0: context(partial( self.solver.objective.set_linear_coefficients, {forward: obj_coef, reverse: -obj_coef})) context(partial(self._populate_solver, [reaction])) context(partial(setattr, reaction, '_model', self)) context(partial(self.reactions.add, reaction)) self.remove_cons_vars([forward, reverse]) self.reactions.remove(reaction) reaction._model = None for met in reaction._metabolites: if reaction in met._reaction: met._reaction.remove(reaction) if context: context(partial(met._reaction.add, reaction)) if remove_orphans and len(met._reaction) == 0: self.remove_metabolites(met) for gene in reaction._genes: if reaction in gene._reaction: gene._reaction.remove(reaction) if context: context(partial(gene._reaction.add, reaction)) if remove_orphans and len(gene._reaction) == 0: self.genes.remove(gene) if context: context(partial(self.genes.add, gene)) # remove reference to the reaction in all groups associated_groups = self.get_associated_groups(reaction) for group in associated_groups: group.remove_members(reaction)
def add_groups(self, group_list): """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(group): if group.id in self.groups: LOGGER.warning( "Ignoring group '%s' since it already exists.", group.id) return False return True if isinstance(group_list, string_types) or \ hasattr(group_list, "id"): warn("need to pass in a list") group_list = [group_list] pruned = DictList(filter(existing_filter, group_list)) for group in pruned: group._model = self for member in group.members: # If the member is not associated with the model, add it if isinstance(member, Metabolite): if member not in self.metabolites: self.add_metabolites([member]) if isinstance(member, Reaction): if member not in self.reactions: self.add_reactions([member]) # TODO(midnighter): `add_genes` method does not exist. # if isinstance(member, Gene): # if member not in self.genes: # self.add_genes([member]) self.groups += [group]
def remove_groups(self, group_list): """Remove groups from the model. Members of each group are not removed from the model (i.e. metabolites, reactions, and genes in the group stay in the model after any groups containing them are removed). Parameters ---------- group_list : list A list of `cobra.Group` objects to remove from the model. """ if isinstance(group_list, string_types) or \ hasattr(group_list, "id"): warn("need to pass in a list") group_list = [group_list] for group in group_list: # make sure the group is in the model if group.id not in self.groups: LOGGER.warning("%r not in %r. Ignored.", group, self) else: self.groups.remove(group) group._model = None
def get_associated_groups(self, element): """Returns a list of groups that an element (reaction, metabolite, gene) is associated with. Parameters ---------- element: `cobra.Reaction`, `cobra.Metabolite`, or `cobra.Gene` Returns ------- list of `cobra.Group` All groups that the provided object is a member of """ # check whether the element is associated with the model return [g for g in self.groups if element in g.members]
def _populate_solver(self, reaction_list, metabolite_list=None): """Populate attached solver with constraints and variables that model the provided reactions. """ constraint_terms = AutoVivification() to_add = [] if metabolite_list is not None: for met in metabolite_list: to_add += [self.problem.Constraint( Zero, name=met.id, lb=0, ub=0)] self.add_cons_vars(to_add) for reaction in reaction_list: if reaction.id not in self.variables: forward_variable = self.problem.Variable(reaction.id) reverse_variable = self.problem.Variable(reaction.reverse_id) self.add_cons_vars([forward_variable, reverse_variable]) else: reaction = self.reactions.get_by_id(reaction.id) forward_variable = reaction.forward_variable reverse_variable = reaction.reverse_variable for metabolite, coeff in six.iteritems(reaction.metabolites): if metabolite.id in self.constraints: constraint = self.constraints[metabolite.id] else: constraint = self.problem.Constraint( Zero, name=metabolite.id, lb=0, ub=0) self.add_cons_vars(constraint, sloppy=True) constraint_terms[constraint][forward_variable] = coeff constraint_terms[constraint][reverse_variable] = -coeff self.solver.update() for reaction in reaction_list: reaction = self.reactions.get_by_id(reaction.id) reaction.update_variable_bounds() for constraint, terms in six.iteritems(constraint_terms): constraint.set_linear_coefficients(terms)
def slim_optimize(self, error_value=float('nan'), message=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 `slim_optimize` versus `optimize` is expected to be small or even negative depending on how you fetch the values after optimization. Parameters ---------- error_value : float, None The value to return if optimization failed due to e.g. infeasibility. If None, raise `OptimizationError` if the optimization fails. message : string Error message to use if the model optimization did not succeed. Returns ------- float The objective value. """ self.solver.optimize() if self.solver.status == optlang.interface.OPTIMAL: return self.solver.objective.value elif error_value is not None: return error_value else: assert_optimal(self, message)
def optimize(self, objective_sense=None, raise_error=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. """ original_direction = self.objective.direction self.objective.direction = \ {"maximize": "max", "minimize": "min"}.get( objective_sense, original_direction) self.slim_optimize() solution = get_solution(self, raise_error=raise_error) self.objective.direction = original_direction return solution
def repair(self, rebuild_index=True, rebuild_relationships=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 rebuild_index: # DictList indexes self.reactions._generate_index() self.metabolites._generate_index() self.genes._generate_index() self.groups._generate_index() if rebuild_relationships: for met in self.metabolites: met._reaction.clear() for gene in self.genes: gene._reaction.clear() for rxn in self.reactions: for met in rxn._metabolites: met._reaction.add(rxn) for gene in rxn._genes: gene._reaction.add(rxn) # point _model to self for l in (self.reactions, self.genes, self.metabolites, self.groups): for e in l: e._model = self
def summary(self, solution=None, threshold=1E-06, fva=None, names=False, floatfmt='.3g'): """ Print a summary of the input and output fluxes of the model. Parameters ---------- solution: cobra.Solution, optional A previously solved model solution to use for generating the summary. If none provided (default), the summary method will resolve the model. Note that the solution object must match the model, i.e., changes to the model such as changed bounds, added or removed reactions are not taken into account by this method. threshold : float, optional Threshold below which fluxes are not reported. fva : pandas.DataFrame, float or None, optional Whether or not to include flux variability analysis in the output. If given, fva should either be a previous FVA solution matching the model or a float between 0 and 1 representing the fraction of the optimum objective to be searched. names : bool, optional Emit reaction and metabolite names rather than identifiers (default False). floatfmt : string, optional Format string for floats (default '.3g'). """ from cobra.flux_analysis.summary import model_summary return model_summary(self, solution=solution, threshold=threshold, fva=fva, names=names, floatfmt=floatfmt)
def merge(self, right, prefix_existing=None, inplace=True, objective='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 inplace: new_model = self else: new_model = self.copy() new_model.id = '{}_{}'.format(self.id, right.id) new_reactions = deepcopy(right.reactions) if prefix_existing is not None: existing = new_reactions.query( lambda rxn: rxn.id in self.reactions) for reaction in existing: reaction.id = '{}{}'.format(prefix_existing, reaction.id) new_model.add_reactions(new_reactions) interface = new_model.problem new_vars = [interface.Variable.clone(v) for v in right.variables if v.name not in new_model.variables] new_model.add_cons_vars(new_vars) new_cons = [interface.Constraint.clone(c, model=new_model.solver) for c in right.constraints if c.name not in new_model.constraints] new_model.add_cons_vars(new_cons, sloppy=True) new_model.objective = dict( left=self.objective, right=right.objective, sum=self.objective.expression + right.objective.expression )[objective] return new_model
def _escape_str_id(id_str): """make a single string id SBML compliant""" for c in ("'", '"'): if id_str.startswith(c) and id_str.endswith(c) \ and id_str.count(c) == 2: id_str = id_str.strip(c) for char, escaped_char in _renames: id_str = id_str.replace(char, escaped_char) return id_str
def escape_ID(cobra_model): """makes all ids SBML compliant""" for x in chain([cobra_model], cobra_model.metabolites, cobra_model.reactions, cobra_model.genes): x.id = _escape_str_id(x.id) cobra_model.repair() gene_renamer = _GeneEscaper() for rxn, rule in iteritems(get_compiled_gene_reaction_rules(cobra_model)): if rule is not None: rxn._gene_reaction_rule = ast2str(gene_renamer.visit(rule))
def rename_genes(cobra_model, rename_dict): """renames genes in a model from the rename_dict""" recompute_reactions = set() # need to recomptue related genes remove_genes = [] for old_name, new_name in iteritems(rename_dict): # undefined if there a value matches a different key # because dict is unordered try: gene_index = cobra_model.genes.index(old_name) except ValueError: gene_index = None old_gene_present = gene_index is not None new_gene_present = new_name in cobra_model.genes if old_gene_present and new_gene_present: old_gene = cobra_model.genes.get_by_id(old_name) # Added in case not renaming some genes: if old_gene is not cobra_model.genes.get_by_id(new_name): remove_genes.append(old_gene) recompute_reactions.update(old_gene._reaction) elif old_gene_present and not new_gene_present: # rename old gene to new gene gene = cobra_model.genes[gene_index] # trick DictList into updating index cobra_model.genes._dict.pop(gene.id) # ugh gene.id = new_name cobra_model.genes[gene_index] = gene elif not old_gene_present and new_gene_present: 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 cobra_model.repair() class Renamer(NodeTransformer): def visit_Name(self, node): node.id = rename_dict.get(node.id, node.id) return node gene_renamer = Renamer() for rxn, rule in iteritems(get_compiled_gene_reaction_rules(cobra_model)): if rule is not None: rxn._gene_reaction_rule = ast2str(gene_renamer.visit(rule)) for rxn in recompute_reactions: rxn.gene_reaction_rule = rxn._gene_reaction_rule for i in remove_genes: cobra_model.genes.remove(i)
def to_json(model, sort=False, **kwargs): """ 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. """ obj = model_to_dict(model, sort=sort) obj[u"version"] = JSON_SPEC return json.dumps(obj, allow_nan=False, **kwargs)
def save_json_model(model, filename, sort=False, pretty=False, **kwargs): """ Write the cobra model to a file in JSON format. ``kwargs`` are passed on to ``json.dump``. Parameters ---------- model : cobra.Model The cobra model to represent. filename : str or file-like File path or descriptor that the JSON representation should be written to. sort : bool, optional Whether to sort the metabolites, reactions, and genes or maintain the order defined in the model. pretty : bool, optional Whether to format the JSON more compactly (default) or in a more verbose but easier to read fashion. Can be partially overwritten by the ``kwargs``. See Also -------- to_json : Return a string representation. json.dump : Base function. """ obj = model_to_dict(model, sort=sort) obj[u"version"] = JSON_SPEC if pretty: dump_opts = { "indent": 4, "separators": (",", ": "), "sort_keys": True, "allow_nan": False} else: dump_opts = { "indent": 0, "separators": (",", ":"), "sort_keys": False, "allow_nan": False} dump_opts.update(**kwargs) if isinstance(filename, string_types): with open(filename, "w") as file_handle: json.dump(obj, file_handle, **dump_opts) else: json.dump(obj, filename, **dump_opts)
def load_json_model(filename): """ 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(filename, string_types): with open(filename, "r") as file_handle: return model_from_dict(json.load(file_handle)) else: return model_from_dict(json.load(filename))
def add_linear_obj(model): """Add a linear version of a minimal medium to the model solver. Changes the optimization objective to finding the growth medium requiring the smallest total import flux:: minimize sum |r_i| for r_i in import_reactions Arguments --------- model : cobra.Model The model to modify. """ coefs = {} for rxn in find_boundary_types(model, "exchange"): export = len(rxn.reactants) == 1 if export: coefs[rxn.reverse_variable] = 1 else: coefs[rxn.forward_variable] = 1 model.objective.set_linear_coefficients(coefs) model.objective.direction = "min"
def add_mip_obj(model): """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(model.variables) > 1e4: LOGGER.warning("the MIP version of minimal media is extremely slow for" " models that large :(") exchange_rxns = find_boundary_types(model, "exchange") big_m = max(abs(b) for r in exchange_rxns for b in r.bounds) prob = model.problem coefs = {} to_add = [] for rxn in exchange_rxns: export = len(rxn.reactants) == 1 indicator = prob.Variable("ind_" + rxn.id, lb=0, ub=1, type="binary") if export: vrv = rxn.reverse_variable indicator_const = prob.Constraint( vrv - indicator * big_m, ub=0, name="ind_constraint_" + rxn.id) else: vfw = rxn.forward_variable indicator_const = prob.Constraint( vfw - indicator * big_m, ub=0, name="ind_constraint_" + rxn.id) to_add.extend([indicator, indicator_const]) coefs[indicator] = 1 model.add_cons_vars(to_add) model.solver.update() model.objective.set_linear_coefficients(coefs) model.objective.direction = "min"
def _as_medium(exchanges, tolerance=1e-6, exports=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.") medium = pd.Series() for rxn in exchanges: export = len(rxn.reactants) == 1 flux = rxn.flux if abs(flux) < tolerance: continue if export: medium[rxn.id] = -flux elif not export: medium[rxn.id] = flux if not exports: medium = medium[medium > 0] return medium
def minimal_medium(model, min_objective_value=0.1, exports=False, minimize_components=False, open_exchanges=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. """ exchange_rxns = find_boundary_types(model, "exchange") if isinstance(open_exchanges, bool): open_bound = 1000 else: open_bound = open_exchanges with model as mod: if open_exchanges: LOGGER.debug("Opening exchanges for %d imports.", len(exchange_rxns)) for rxn in exchange_rxns: rxn.bounds = (-open_bound, open_bound) LOGGER.debug("Applying objective value constraints.") obj_const = mod.problem.Constraint( mod.objective.expression, lb=min_objective_value, name="medium_obj_constraint") mod.add_cons_vars([obj_const]) mod.solver.update() mod.objective = Zero LOGGER.debug("Adding new media objective.") tol = mod.solver.configuration.tolerances.feasibility if minimize_components: add_mip_obj(mod) if isinstance(minimize_components, bool): minimize_components = 1 seen = set() best = num_components = mod.slim_optimize() if mod.solver.status != OPTIMAL: LOGGER.warning("Minimization of medium was infeasible.") return None exclusion = mod.problem.Constraint(Zero, ub=0) mod.add_cons_vars([exclusion]) mod.solver.update() media = [] for i in range(minimize_components): LOGGER.info("Finding alternative medium #%d.", (i + 1)) vars = [mod.variables["ind_" + s] for s in seen] if len(seen) > 0: exclusion.set_linear_coefficients( dict.fromkeys(vars, 1)) exclusion.ub = best - 1 num_components = mod.slim_optimize() if mod.solver.status != OPTIMAL or num_components > best: break medium = _as_medium(exchange_rxns, tol, exports=exports) media.append(medium) seen.update(medium[medium > 0].index) if len(media) > 1: medium = pd.concat(media, axis=1, sort=True).fillna(0.0) medium.sort_index(axis=1, inplace=True) else: medium = media[0] else: add_linear_obj(mod) mod.slim_optimize() if mod.solver.status != OPTIMAL: LOGGER.warning("Minimization of medium was infeasible.") return None medium = _as_medium(exchange_rxns, tol, exports=exports) return medium
def _init_worker(model, loopless, sense): """Initialize a global model object for multiprocessing.""" global _model global _loopless _model = model _model.solver.objective.direction = sense _loopless = loopless
def flux_variability_analysis(model, reaction_list=None, loopless=False, fraction_of_optimum=1.0, pfba_factor=None, processes=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 reaction_list is None: reaction_ids = [r.id for r in model.reactions] else: reaction_ids = [r.id for r in model.reactions.get_by_any(reaction_list)] if processes is None: processes = CONFIGURATION.processes num_reactions = len(reaction_ids) processes = min(processes, num_reactions) fva_result = DataFrame({ "minimum": zeros(num_reactions, dtype=float), "maximum": zeros(num_reactions, dtype=float) }, index=reaction_ids) prob = model.problem with model: # Safety check before setting up FVA. model.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 model.solver.objective.direction == "max": fva_old_objective = prob.Variable( "fva_old_objective", lb=fraction_of_optimum * model.solver.objective.value) else: fva_old_objective = prob.Variable( "fva_old_objective", ub=fraction_of_optimum * model.solver.objective.value) fva_old_obj_constraint = prob.Constraint( model.solver.objective.expression - fva_old_objective, lb=0, ub=0, name="fva_old_objective_constraint") model.add_cons_vars([fva_old_objective, fva_old_obj_constraint]) if pfba_factor is not None: if pfba_factor < 1.: warn("The 'pfba_factor' should be larger or equal to 1.", UserWarning) with model: add_pfba(model, fraction_of_optimum=0) ub = model.slim_optimize(error_value=None) flux_sum = prob.Variable("flux_sum", ub=pfba_factor * ub) flux_sum_constraint = prob.Constraint( model.solver.objective.expression - flux_sum, lb=0, ub=0, name="flux_sum_constraint") model.add_cons_vars([flux_sum, flux_sum_constraint]) model.objective = Zero # This will trigger the reset as well for what in ("minimum", "maximum"): if processes > 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. chunk_size = len(reaction_ids) // processes pool = multiprocessing.Pool( processes, initializer=_init_worker, initargs=(model, loopless, what[:3]) ) for rxn_id, value in pool.imap_unordered(_fva_step, reaction_ids, chunksize=chunk_size): fva_result.at[rxn_id, what] = value pool.close() pool.join() else: _init_worker(model, loopless, what[:3]) for rxn_id, value in map(_fva_step, reaction_ids): fva_result.at[rxn_id, what] = value return fva_result[["minimum", "maximum"]]
def find_blocked_reactions(model, reaction_list=None, zero_cutoff=None, open_exchanges=False, processes=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. """ zero_cutoff = normalize_cutoff(model, zero_cutoff) with model: if open_exchanges: for reaction in model.exchanges: reaction.bounds = (min(reaction.lower_bound, -1000), max(reaction.upper_bound, 1000)) if reaction_list is None: reaction_list = model.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. model.slim_optimize() solution = get_solution(model, reactions=reaction_list) reaction_list = solution.fluxes[ solution.fluxes.abs() < zero_cutoff].index.tolist() # Run FVA to find reactions where both the minimal and maximal flux # are zero (below the cut off). flux_span = flux_variability_analysis( model, fraction_of_optimum=0., reaction_list=reaction_list, processes=processes ) return flux_span[ flux_span.abs().max(axis=1) < zero_cutoff].index.tolist()
def find_essential_genes(model, threshold=None, processes=None): """ Return a set of essential genes. A gene is considered essential if restricting the flux of all reactions that depend on it 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 genes 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. If not passed, will be set to the number of CPUs found. 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 genes """ if threshold is None: threshold = model.slim_optimize(error_value=None) * 1E-02 deletions = single_gene_deletion(model, method='fba', processes=processes) essential = deletions.loc[deletions['growth'].isna() | (deletions['growth'] < threshold), :].index return {model.genes.get_by_id(g) for ids in essential for g in ids}
def find_essential_reactions(model, threshold=None, processes=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 threshold is None: threshold = model.slim_optimize(error_value=None) * 1E-02 deletions = single_reaction_deletion( model, method='fba', processes=processes) essential = deletions.loc[deletions['growth'].isna() | (deletions['growth'] < threshold), :].index return {model.reactions.get_by_id(r) for ids in essential for r in ids}
def add_SBO(model): """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 r in model.reactions: # don't annotate already annotated reactions if r.annotation.get("sbo"): continue # only doing exchanges if len(r.metabolites) != 1: continue met_id = list(r._metabolites)[0].id if r.id.startswith("EX_") and r.id == "EX_" + met_id: r.annotation["sbo"] = "SBO:0000627" elif r.id.startswith("DM_") and r.id == "DM_" + met_id: r.annotation["sbo"] = "SBO:0000628"
def weight(self): """Calculate the mol mass of the compound Returns ------- float the mol mass """ try: return sum([count * elements_and_molecular_weights[element] for element, count in self.elements.items()]) except KeyError as e: warn("The element %s does not appear in the periodic table" % e)
def insert_break(lines, break_pos=9): """ Insert a <!--more--> tag for larger release notes. Parameters ---------- lines : list of str The content of the release note. break_pos : int Line number before which a break should approximately be inserted. Returns ------- list of str The text with the inserted tag or no modification if it was sufficiently short. """ def line_filter(line): if len(line) == 0: return True return any(line.startswith(c) for c in "-*+") if len(lines) <= break_pos: return lines newlines = [ i for i, line in enumerate(lines[break_pos:], start=break_pos) if line_filter(line.strip())] if len(newlines) > 0: break_pos = newlines[0] lines.insert(break_pos, "<!--more-->\n") return lines
def build_hugo_md(filename, tag, bump): """ Build the markdown release notes for Hugo. Inserts the required TOML header with specific values and adds a break for long release notes. Parameters ---------- filename : str, path The release notes file. tag : str The tag, following semantic versioning, of the current release. bump : {"major", "minor", "patch", "alpha", "beta"} The type of release. """ header = [ '+++\n', 'date = "{}"\n'.format(date.today().isoformat()), 'title = "{}"\n'.format(tag), 'author = "The COBRApy Team"\n', 'release = "{}"\n'.format(bump), '+++\n', '\n' ] with open(filename, "r") as file_h: content = insert_break(file_h.readlines()) header.extend(content) with open(filename, "w") as file_h: file_h.writelines(header)
def find_bump(target, tag): """Identify the kind of release by comparing to existing ones.""" tmp = tag.split(".") existing = [intify(basename(f)) for f in glob(join(target, "[0-9]*.md"))] latest = max(existing) if int(tmp[0]) > latest[0]: return "major" elif int(tmp[1]) > latest[1]: return "minor" else: return "patch"
def main(argv): """ Identify the release type and create a new target file with TOML header. Requires three arguments. """ source, target, tag = argv if "a" in tag: bump = "alpha" if "b" in tag: bump = "beta" else: bump = find_bump(target, tag) filename = "{}.md".format(tag) destination = copy(join(source, filename), target) build_hugo_md(destination, tag, bump)
def _multi_deletion(model, entity, element_lists, method="fba", solution=None, processes=None, **kwargs): """ Provide a common interface for single or multiple knockouts. Parameters ---------- model : cobra.Model The metabolic model to perform deletions in. entity : 'gene' or 'reaction' The entity to knockout (``cobra.Gene`` or ``cobra.Reaction``). element_lists : list List of iterables ``cobra.Reaction``s or ``cobra.Gene``s (or their IDs) to be deleted. 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 : Passed on to underlying simulation functions. Returns ------- pandas.DataFrame A representation of all combinations of entity deletions. The columns are 'growth' and 'status', where index : frozenset([str]) The gene or reaction identifiers that were knocked out. growth : float The growth rate of the adjusted model. status : str The solution's status. """ solver = sutil.interface_to_str(model.problem.__name__) if method == "moma" and solver not in sutil.qp_solvers: raise RuntimeError( "Cannot use MOMA since '{}' is not QP-capable." "Please choose a different solver or use FBA only.".format(solver)) if processes is None: processes = CONFIGURATION.processes with model: if "moma" in method: add_moma(model, solution=solution, linear="linear" in method) elif "room" in method: add_room(model, solution=solution, linear="linear" in method, **kwargs) args = set([frozenset(comb) for comb in product(*element_lists)]) processes = min(processes, len(args)) def extract_knockout_results(result_iter): result = pd.DataFrame([ (frozenset(ids), growth, status) for (ids, growth, status) in result_iter ], columns=['ids', 'growth', 'status']) result.set_index('ids', inplace=True) return result if processes > 1: worker = dict(gene=_gene_deletion_worker, reaction=_reaction_deletion_worker)[entity] chunk_size = len(args) // processes pool = multiprocessing.Pool( processes, initializer=_init_worker, initargs=(model,) ) results = extract_knockout_results(pool.imap_unordered( worker, args, chunksize=chunk_size )) pool.close() pool.join() else: worker = dict(gene=_gene_deletion, reaction=_reaction_deletion)[entity] results = extract_knockout_results(map( partial(worker, model), args)) return results
def single_reaction_deletion(model, reaction_list=None, method="fba", solution=None, processes=None, **kwargs): """ Knock out each reaction from a given list. Parameters ---------- model : cobra.Model The metabolic model to perform deletions in. reaction_list : iterable, optional ``cobra.Reaction``s to be deleted. If not passed, all the reactions 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 single reaction deletions. The columns are 'growth' and 'status', where index : frozenset([str]) The reaction identifier that was knocked out. growth : float The growth rate of the adjusted model. status : str The solution's status. """ return _multi_deletion( model, 'reaction', element_lists=_element_lists(model.reactions, reaction_list), method=method, solution=solution, processes=processes, **kwargs)
def single_gene_deletion(model, gene_list=None, method="fba", solution=None, processes=None, **kwargs): """ Knock out each gene from a given list. Parameters ---------- model : cobra.Model The metabolic model to perform deletions in. gene_list : iterable ``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 single gene deletions. The columns are 'growth' and 'status', where index : frozenset([str]) The gene identifier that was knocked out. growth : float The growth rate of the adjusted model. status : str The solution's status. """ return _multi_deletion( model, 'gene', element_lists=_element_lists(model.genes, gene_list), method=method, solution=solution, processes=processes, **kwargs)
def double_reaction_deletion(model, reaction_list1=None, reaction_list2=None, method="fba", solution=None, processes=None, **kwargs): """ Knock out each reaction pair from the combinations 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. reaction_list1 : iterable, optional First iterable of ``cobra.Reaction``s to be deleted. If not passed, all the reactions from the model are used. reaction_list2 : iterable, optional Second iterable of ``cobra.Reaction``s to be deleted. If not passed, all the reactions 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 reaction deletions. The columns are 'growth' and 'status', where index : frozenset([str]) The reaction identifiers that were knocked out. growth : float The growth rate of the adjusted model. status : str The solution's status. """ reaction_list1, reaction_list2 = _element_lists(model.reactions, reaction_list1, reaction_list2) return _multi_deletion( model, 'reaction', element_lists=[reaction_list1, reaction_list2], method=method, solution=solution, processes=processes, **kwargs)
def double_gene_deletion(model, gene_list1=None, gene_list2=None, method="fba", solution=None, processes=None, **kwargs): """ 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. """ gene_list1, gene_list2 = _element_lists(model.genes, gene_list1, gene_list2) return _multi_deletion( model, 'gene', element_lists=[gene_list1, gene_list2], method=method, solution=solution, processes=processes, **kwargs)
def reverse_id(self): """Generate the id of reverse_variable from the reaction's id.""" return '_'.join((self.id, 'reverse', hashlib.md5( self.id.encode('utf-8')).hexdigest()[0:5]))
def flux(self): """ The flux value in the most recent solution. Flux is the primal value of the corresponding variable in the model. Warnings -------- * Accessing reaction fluxes through a `Solution` object is the safer, preferred, and only guaranteed to be correct way. You can see how to do so easily in the examples. * Reaction flux is retrieved from the currently defined `self._model.solver`. The solver status is checked but there are no guarantees that the current solver state is the one you are looking for. * If you modify the underlying model after an optimization, you will retrieve the old optimization values. Raises ------ RuntimeError If the underlying model was never optimized beforehand or the reaction is not part of a model. OptimizationError If the solver status is anything other than 'optimal'. AssertionError If the flux value is not within the bounds. Examples -------- >>> import cobra.test >>> model = cobra.test.create_test_model("textbook") >>> solution = model.optimize() >>> model.reactions.PFK.flux 7.477381962160283 >>> solution.fluxes.PFK 7.4773819621602833 """ try: check_solver_status(self._model.solver.status) return self.forward_variable.primal - self.reverse_variable.primal except AttributeError: raise RuntimeError( "reaction '{}' is not part of a model".format(self.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 gene_name_reaction_rule(self): """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. """ names = {i.id: i.name for i in self._genes} ast = parse_gpr(self._gene_reaction_rule)[0] return ast2str(ast, names=names)