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 -----...
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, ...
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 Optimization...
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 statu...
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 : c...
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 ...
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 : boolea...
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 bou...
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 ...
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...
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 c...
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.s...
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(...
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 Th...
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...
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: c...
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...
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_...
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` ...
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 c...
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} remo...
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 p...
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 ---------- ...
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.ind...
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.mod...
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 ...
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 ...
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", "dem...
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". exte...
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 " ...
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) ...
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 ...
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...
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 ge...
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...
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: ...
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 ...
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. Th...
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 an...
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)...
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 o...
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. Return...
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' a...
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...
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 specif...
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 T...
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"...
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"...
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 t...
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)...
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 ...
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 ...
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", ...
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.Metab...
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` obj...
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. ...
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 :...
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 re...
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 g...
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 ---------- ...
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.Gro...
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 meta...
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 tim...
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, ...
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...
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 u...
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 var...
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, esca...
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()...
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 # becaus...
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...
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 ...
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...
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...
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 ...
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 ...
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 med...
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 :...
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...
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. ...
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 --------...
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 ...
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()]) excep...
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 ------- ...
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, fo...
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]: ...
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 = "{...
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 : ...
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_lis...
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 ...
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 d...
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 ---------- ...
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 co...
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...