func_code_string
stringlengths
52
1.94M
func_documentation_string
stringlengths
1
47.2k
def generate_component_annotation_miriam_match(elements, component, db): def is_faulty(annotation, key, pattern): # Ignore missing annotation for this database. if key not in annotation: return False test = annotation[key] if isinstance(test, native_str): ...
Tabulate which MIRIAM databases the element's annotation match. If the relevant MIRIAM identifier is not in an element's annotation it is ignored. Parameters ---------- elements : list Elements of a model, either metabolites or reactions. component : {"metabolites", "reactions"} ...
def generate_component_id_namespace_overview(model, components): patterns = { "metabolites": METABOLITE_ANNOTATIONS, "reactions": REACTION_ANNOTATIONS, "genes": GENE_PRODUCT_ANNOTATIONS }[components] databases = list(patterns) data = list() index = list() for elem in...
Tabulate which MIRIAM databases the component's identifier matches. Parameters ---------- model : cobra.Model A cobrapy metabolic model. components : {"metabolites", "reactions", "genes"} A string denoting `cobra.Model` components. Returns ------- pandas.DataFrame T...
def confusion_matrix(predicted_essential, expected_essential, predicted_nonessential, expected_nonessential): true_positive = predicted_essential & expected_essential tp = len(true_positive) true_negative = predicted_nonessential & expected_nonessential tn = len(true_negative) ...
Compute a representation of the confusion matrix. Parameters ---------- predicted_essential : set expected_essential : set predicted_nonessential : set expected_nonessential : set Returns ------- dict Confusion matrix as different keys of a dictionary. The abbreviated ...
def validate_model(path): notifications = {"warnings": [], "errors": []} model, sbml_ver = val.load_cobra_model(path, notifications) return model, sbml_ver, notifications
Validate a model structurally and optionally store results as JSON. Parameters ---------- path : Path to model file. Returns ------- tuple cobra.Model The metabolic model under investigation. tuple A tuple reporting on the SBML level, version, an...
def snapshot_report(result, config=None, html=True): if config is None: config = ReportConfiguration.load() report = SnapshotReport(result=result, configuration=config) if html: return report.render_html() else: return report.render_json()
Generate a snapshot report from a result set and configuration. Parameters ---------- result : memote.MemoteResult Nested dictionary structure as returned from the test suite. config : dict, optional The final test report configuration (default None). html : bool, optional W...
def history_report(history, config=None, html=True): if config is None: config = ReportConfiguration.load() report = HistoryReport(history=history, configuration=config) if html: return report.render_html() else: return report.render_json()
Test a model and save a history report. Parameters ---------- history : memote.HistoryManager The manager grants access to previous results. config : dict, optional The final test report configuration. html : bool, optional Whether to render the report as full HTML or JSON (...
def diff_report(diff_results, config=None, html=True): if config is None: config = ReportConfiguration.load() report = DiffReport(diff_results=diff_results, configuration=config) if html: return report.render_html() else: return report.render_json()
Generate a diff report from a result set and configuration. Parameters ---------- diff_results : iterable of memote.MemoteResult Nested dictionary structure as returned from the test suite. config : dict, optional The final test report configuration (default None). html : bool, opti...
def validation_report(path, notifications, filename): env = Environment( loader=PackageLoader('memote.suite', 'templates'), autoescape=select_autoescape(['html', 'xml']) ) template = env.get_template('validation_template.html') model = os.path.basename(path) with open(filename, ...
Generate a validation report from a notification object. Parameters ---------- path : string Path to model file. notifications : dict A simple dictionary structure containing a list of errors and warnings.
def load(cls, filename=None): if filename is None: LOGGER.debug("Loading default configuration.") with open_text(templates, "test_config.yml", encoding="utf-8") as file_handle: content = yaml.load(file_handle) else: ...
Load a test report configuration.
def find_top_level_complex(gpr): logger.debug("%r", gpr) conform = logical_and.sub("and", gpr) conform = logical_or.sub("or", conform) conform = escape_chars.sub("_", conform) expression = ast.parse(conform) walker = GPRVisitor() walker.visit(expression) return len(walker.left ^ wal...
Find unique elements of both branches of the top level logical AND. Parameters ---------- gpr : str The gene-protein-reaction association as a string. Returns ------- int The size of the symmetric difference between the set of elements to the left of the top level logic...
def visit_BoolOp(self, node): if self._is_top and isinstance(node.op, ast.And): self._is_top = False self._current = self.left self.visit(node.values[0]) self._current = self.right for successor in node.values[1:]: self.visit(s...
Set up recording of elements with this hook.
def find_nonzero_constrained_reactions(model): lower_bound, upper_bound = helpers.find_bounds(model) return [rxn for rxn in model.reactions if 0 > rxn.lower_bound > lower_bound or 0 < rxn.upper_bound < upper_bound]
Return list of reactions with non-zero, non-maximal bounds.
def find_zero_constrained_reactions(model): return [rxn for rxn in model.reactions if rxn.lower_bound == 0 and rxn.upper_bound == 0]
Return list of reactions that are constrained to zero flux.
def find_unconstrained_reactions(model): lower_bound, upper_bound = helpers.find_bounds(model) return [rxn for rxn in model.reactions if rxn.lower_bound <= lower_bound and rxn.upper_bound >= upper_bound]
Return list of reactions that are not constrained at all.
def find_ngam(model): u atp_adp_conv_rxns = helpers.find_converting_reactions( model, ("MNXM3", "MNXM7") ) id_of_main_compartment = helpers.find_compartment_id_in_model(model, 'c') reactants = { helpers.find_met_in_model(model, "MNXM3", id_of_main_compartment)[0], helpers.fin...
u""" Return all potential non growth-associated maintenance reactions. From the list of all reactions that convert ATP to ADP select the reactions that match a defined reaction string and whose metabolites are situated within the main model compartment. The main model compartment is the cytosol, an...
def calculate_metabolic_coverage(model): u if len(model.reactions) == 0 or len(model.genes) == 0: raise ValueError("The model contains no reactions or genes.") return float(len(model.reactions)) / float(len(model.genes))
u""" Return the ratio of reactions and genes included in the model. Determine whether the amount of reactions and genes in model not equal to zero, then return the ratio. Parameters ---------- model : cobra.Model The metabolic model under investigation. Returns ------- flo...
def find_protein_complexes(model): complexes = [] for rxn in model.reactions: if not rxn.gene_reaction_rule: continue size = find_top_level_complex(rxn.gene_reaction_rule) if size >= 2: complexes.append(rxn) return complexes
Find reactions that are catalyzed by at least a heterodimer. Parameters ---------- model : cobra.Model The metabolic model under investigation. Returns ------- list Reactions whose gene-protein-reaction association contains at least one logical AND combining different g...
def is_constrained_reaction(model, rxn): lower_bound, upper_bound = helpers.find_bounds(model) if rxn.reversibility: return rxn.lower_bound > lower_bound or rxn.upper_bound < upper_bound else: return rxn.lower_bound > 0 or rxn.upper_bound < upper_bound
Return whether a reaction has fixed constraints.
def find_oxygen_reactions(model): o2_in_model = helpers.find_met_in_model(model, "MNXM4") return set([rxn for met in model.metabolites for rxn in met.reactions if met.formula == "O2" or met in o2_in_model])
Return list of oxygen-producing/-consuming reactions.
def find_unique_metabolites(model): unique = set() for met in model.metabolites: is_missing = True for comp in model.compartments: if met.id.endswith("_{}".format(comp)): unique.add(met.id[:-(len(comp) + 1)]) is_missing = False bre...
Return set of metabolite IDs without duplicates from compartments.
def find_duplicate_metabolites_in_compartments(model): unique_identifiers = ["inchikey", "inchi"] duplicates = [] for met_1, met_2 in combinations(model.metabolites, 2): if met_1.compartment == met_2.compartment: for key in unique_identifiers: if key in met_1.annotat...
Return list of metabolites with duplicates in the same compartment. This function identifies duplicate metabolites in each compartment by determining if any two metabolites have identical InChI-key annotations. For instance, this function would find compounds with IDs ATP1 and ATP2 in the cytosolic com...
def find_reactions_with_partially_identical_annotations(model): duplicates = {} rxn_db_identifiers = ["metanetx.reaction", "kegg.reaction", "brenda", "rhea", "biocyc", "bigg.reaction"] # Build a list that associates a reaction with a set of its annotations. ann_rxns = [] ...
Return duplicate reactions based on identical annotation. Identify duplicate reactions globally by checking if any two metabolic reactions have the same entries in their annotation attributes. This can be useful to identify one 'type' of reactions that occurs in several compartments, to curate merged m...
def map_metabolites_to_structures(metabolites, compartments): # TODO (Moritz Beber): Consider SMILES? unique_identifiers = ["inchikey", "inchi"] met2mol = {} molecules = {c: [] for c in compartments} for met in metabolites: ann = [] for key in unique_identifiers: mol...
Map metabolites from the identifier namespace to structural space. Metabolites who lack structural annotation (InChI or InChIKey) are ignored. Parameters ---------- metabolites : iterable The cobra.Metabolites to map. compartments : iterable The different compartments to consider. ...
def find_duplicate_reactions(model): met2mol = map_metabolites_to_structures(model.metabolites, model.compartments) # Build a list associating reactions with their stoichiometry in molecular # structure space. structural = [] for rxn in model.reaction...
Return a list with pairs of reactions that are functionally identical. Identify duplicate reactions globally by checking if any two reactions have the same metabolites, same directionality and are in the same compartment. This can be useful to curate merged models or to clean-up bulk model modific...
def find_reactions_with_identical_genes(model): duplicates = dict() for rxn_a, rxn_b in combinations(model.reactions, 2): if not (rxn_a.genes and rxn_b.genes): continue if rxn_a.genes == rxn_b.genes: # This works because the `genes` are frozen sets. ident...
Return reactions that have identical genes. Identify duplicate reactions globally by checking if any two reactions have the same genes. This can be useful to curate merged models or to clean-up bulk model modifications, but also to identify promiscuous enzymes. The heuristic compares reactions in a...
def find_medium_metabolites(model): return [met.id for rxn in model.medium for met in model.reactions.get_by_id(rxn).metabolites]
Return the list of metabolites ingested/excreted by the model.
def find_external_metabolites(model): ex_comp = find_external_compartment(model) return [met for met in model.metabolites if met.compartment == ex_comp]
Return all metabolites in the external compartment.
def store(self, result, filename, pretty=True): LOGGER.info("Storing result in '%s'.", filename) if filename.endswith(".gz"): with gzip.open(filename, "wb") as file_handle: file_handle.write( jsonify(result, pretty=pretty).encode("utf-8") ...
Write a result to the given file. Parameters ---------- result : memote.MemoteResult The dictionary structure of results. filename : str or pathlib.Path Store results directly to the given filename. pretty : bool, optional Whether (default) or...
def load(self, filename): LOGGER.info("Loading result from '%s'.", filename) if filename.endswith(".gz"): with gzip.open(filename, "rb") as file_handle: result = MemoteResult( json.loads(file_handle.read().decode("utf-8")) ) ...
Load a result from the given JSON file.
def load_cobra_model(path, notifications): doc = libsbml.readSBML(path) fbc = doc.getPlugin("fbc") sbml_ver = doc.getLevel(), doc.getVersion(), fbc if fbc is None else \ fbc.getVersion() with catch_warnings(record=True) as warnings: simplefilter("always") try: mo...
Load a COBRA model with meta information from an SBML document.
def format_failure(failure): return "Line {}, Column {} - #{}: {} - Category: {}, Severity: {}".format( failure.getLine(), failure.getColumn(), failure.getErrorId(), failure.getMessage(), failure.getCategoryAsString(), failure.getSeverity() )
Format how an error or warning should be displayed.
def run_sbml_validation(document, notifications): validator = libsbml.SBMLValidator() validator.validate(document) for i in range(document.getNumErrors()): notifications['errors'].append(format_failure(document.getError(i))) for i in range(validator.getNumFailures()): failure = vali...
Report errors and warnings found in an SBML document.
def store(self, result, commit=None, **kwargs): git_info = self.record_git_info(commit) try: row = self.session.query(Result). \ filter_by(hexsha=git_info.hexsha). \ one() LOGGER.info("Updating result '%s'.", git_info.hexsha) r...
Store a result in a JSON file attaching git meta information. Parameters ---------- result : memote.MemoteResult The dictionary structure of results. commit : str, optional Unique hexsha of the desired commit. kwargs : Passed to parent functio...
def load(self, commit=None): git_info = self.record_git_info(commit) LOGGER.info("Loading result from '%s'.", git_info.hexsha) result = MemoteResult( self.session.query(Result.memote_result). filter_by(hexsha=git_info.hexsha). one().memote_result) ...
Load a result from the database.
def collect_history(self): def format_data(data): # TODO Remove this failsafe once proper error handling is in place. if type == "percent" or data is None: # Return an empty list here to reduce the output file size. # The angular repo...
Build the structure of results in terms of a commit history.
def format_and_score_diff_data(self, diff_results): base = dict() meta = base.setdefault('meta', dict()) tests = base.setdefault('tests', dict()) score = base.setdefault('score', dict()) for model_filename, result in iteritems(diff_results): if meta == dict()...
Reformat the api results to work with the front-end.
def generate_shortlist(mnx_db, shortlist): # Reduce the whole database to targets of interest. xref = mnx_db.loc[mnx_db["MNX_ID"].isin(shortlist["MNX_ID"]), :] # Drop deprecated MetaNetX identifiers. Disabled for now. # xref = xref.loc[~xref["XREF"].str.startswith("deprecated", na=False), :] # ...
Create a condensed cross-references format from data in long form. Both data frames must contain a column 'MNX_ID' and the dump is assumed to also have a column 'XREF'. Parameters ---------- mnx_db : pandas.DataFrame The entire MetaNetX dump as a data frame. shortlist : pandas.DataFram...
def generate(mnx_dump): LOGGER.info("Read shortlist.") targets = pd.read_table(join(dirname(__file__), "shortlist.tsv")) if not exists(mnx_dump): # Download the MetaNetX chemicals dump if it doesn't exists. # Download done as per https://stackoverflow.com/a/16696317. LOGGER.info...
Annotate a shortlist of metabolites with cross-references using MetaNetX. MNX_DUMP : The chemicals dump from MetaNetX usually called 'chem_xref.tsv'. Will be downloaded if it doesn't exist.
def validate(self, model, checks=[]): custom = [ check_partial(gene_id_check, frozenset(g.id for g in model.genes)) ] super(EssentialityExperiment, self).validate( model=model, checks=checks + custom)
Use a defined schema to validate the medium table format.
def evaluate(self, model): with model: if self.medium is not None: self.medium.apply(model) if self.objective is not None: model.objective = self.objective model.add_cons_vars(self.constraints) max_val = model.slim_optimize...
Use the defined parameters to predict single gene essentiality.
def register_with(registry): def decorator(func): registry[func.__name__] = func return func return decorator
Register a passed in object. Intended to be used as a decorator on model building functions with a ``dict`` as a registry. Examples -------- .. code-block:: python REGISTRY = dict() @register_with(REGISTRY) def build_empty(base): return base
def annotate(title, format_type, message=None, data=None, metric=1.0): if format_type not in TYPES: raise ValueError( "Invalid type. Expected one of: {}.".format(", ".join(TYPES))) def decorator(func): func.annotation = dict( title=title, summary=extended...
Annotate a test case with info that should be displayed in the reports. Parameters ---------- title : str A human-readable descriptive title of the test case. format_type : str A string that determines how the result data is formatted in the report. It is expected not to be None...
def truncate(sequence): if len(sequence) > LIST_SLICE: return ", ".join(sequence[:LIST_SLICE] + ["..."]) else: return ", ".join(sequence)
Create a potentially shortened text display of a list. Parameters ---------- sequence : list An indexable sequence of elements. Returns ------- str The list as a formatted string.
def log_json_incompatible_types(obj): keys_to_explore = list(obj) while len(keys_to_explore) > 0: key = keys_to_explore.pop() if not isinstance(key, str): LOGGER.info(type(key)) value = obj[key] if isinstance(value, dict): LOGGER.info("%s:", key) ...
Log types that are not JSON compatible. Explore a nested dictionary structure and log types that are not JSON compatible. Parameters ---------- obj : dict A potentially nested dictionary.
def jsonify(obj, pretty=False): if pretty: params = dict(sort_keys=True, indent=2, allow_nan=False, separators=(",", ": "), ensure_ascii=False) else: params = dict(sort_keys=False, indent=None, allow_nan=False, separators=(",", ":"), ensure_ascii=...
Turn a nested object into a (compressed) JSON string. Parameters ---------- obj : dict Any kind of dictionary structure. pretty : bool, optional Whether to format the resulting JSON in a more legible way ( default False).
def flatten(list_of_lists): flat_list = [] for sublist in list_of_lists: if isinstance(sublist, string_types) or isinstance(sublist, int): flat_list.append(sublist) elif sublist is None: continue elif not isinstance(sublist, string_types) and len(sublist) == ...
Flatten a list of lists but maintain strings and ints as entries.
def stdout_notifications(notifications): for error in notifications["errors"]: LOGGER.error(error) for warn in notifications["warnings"]: LOGGER.warning(warn)
Print each entry of errors and warnings to stdout. Parameters ---------- notifications: dict A simple dictionary structure containing a list of errors and warnings.
def load(self, dtype_conversion=None): self.data = read_tabular(self.filename, dtype_conversion) with open_text(memote.experimental.schemata, self.SCHEMA, encoding="utf-8") as file_handle: self.schema = json.load(file_handle)
Load the data table and corresponding validation schema. Parameters ---------- dtype_conversion : dict Column names as keys and corresponding type for loading the data. Please take a look at the `pandas documentation <https://pandas.pydata.org/pandas-docs/sta...
def validate(self, model, checks=[]): records = self.data.to_dict("records") self.evaluate_report( validate(records, headers=list(records[0]), preset='table', schema=self.schema, order_fields=True, custom_checks=checks))
Use a defined schema to validate the given table.
def evaluate_report(report): if report["valid"]: return for warn in report["warnings"]: LOGGER.warning(warn) # We only ever test one table at a time. for err in report["tables"][0]["errors"]: LOGGER.error(err["message"]) raise ValueErr...
Iterate over validation errors.
def add_reaction_constraints(model, reactions, Constraint): constraints = [] for rxn in reactions: expression = add( [c * model.variables[m.id] for m, c in rxn.metabolites.items()]) constraints.append(Constraint(expression, lb=0, ub=0, name=rxn.id)) model.add(constraints)
Add the stoichiometric coefficients as constraints. Parameters ---------- model : optlang.Model The transposed stoichiometric matrix representation. reactions : iterable Container of `cobra.Reaction` instances. Constraint : optlang.Constraint The constraint class for the spe...
def stoichiometry_matrix(metabolites, reactions): matrix = np.zeros((len(metabolites), len(reactions))) met_index = dict((met, i) for i, met in enumerate(metabolites)) rxn_index = dict() for i, rxn in enumerate(reactions): rxn_index[rxn] = i for met, coef in iteritems(rxn.metabolite...
Return the stoichiometry matrix representation of a set of reactions. The reactions and metabolites order is respected. All metabolites are expected to be contained and complete in terms of the reactions. Parameters ---------- reactions : iterable A somehow ordered list of unique reactions...
def rank(matrix, atol=1e-13, rtol=0): matrix = np.atleast_2d(matrix) sigma = svd(matrix, compute_uv=False) tol = max(atol, rtol * sigma[0]) return int((sigma >= tol).sum())
Estimate the rank, i.e., the dimension of the column space, of a matrix. The algorithm used by this function is based on the singular value decomposition of `stoichiometry_matrix`. Parameters ---------- matrix : ndarray The matrix should be at most 2-D. A 1-D array with length k w...
def nullspace(matrix, atol=1e-13, rtol=0.0): # noqa: D402 matrix = np.atleast_2d(matrix) _, sigma, vh = svd(matrix) tol = max(atol, rtol * sigma[0]) num_nonzero = (sigma >= tol).sum() return vh[num_nonzero:].conj().T
Compute an approximate basis for the null space (kernel) of a matrix. The algorithm used by this function is based on the singular value decomposition of the given matrix. Parameters ---------- matrix : ndarray The matrix should be at most 2-D. A 1-D array with length k will be tr...
def get_interface(model): return ( model.solver.interface.Model, model.solver.interface.Constraint, model.solver.interface.Variable, model.solver.interface.Objective )
Return the interface specific classes. Parameters ---------- model : cobra.Model The metabolic model under investigation.
def get_internals(model): biomass = set(find_biomass_reaction(model)) if len(biomass) == 0: LOGGER.warning("No biomass reaction detected. Consistency test results " "are unreliable if one exists.") return set(model.reactions) - (set(model.boundary) | biomass)
Return non-boundary reactions and their metabolites. Boundary reactions are unbalanced by their nature. They are excluded here and only the metabolites of the others are considered. Parameters ---------- model : cobra.Model The metabolic model under investigation.
def create_milp_problem(kernel, metabolites, Model, Variable, Constraint, Objective): assert len(metabolites) == kernel.shape[0],\ "metabolite vector and first nullspace dimension must be equal" ns_problem = Model() k_vars = list() for met in metabolites: # T...
Create the MILP as defined by equation (13) in [1]_. Parameters ---------- kernel : numpy.array A 2-dimensional array that represents the left nullspace of the stoichiometric matrix which is the nullspace of the transpose of the stoichiometric matrix. metabolites : iterable ...
def add_cut(problem, indicators, bound, Constraint): cut = Constraint(sympy.Add(*indicators), ub=bound) problem.add(cut) return cut
Add an integer cut to the problem. Ensure that the same solution involving these indicator variables cannot be found by enforcing their sum to be less than before. Parameters ---------- problem : optlang.Model Specific optlang interface Model instance. indicators : iterable Bin...
def is_mass_balanced(reaction): balance = defaultdict(int) for metabolite, coefficient in iteritems(reaction.metabolites): if metabolite.elements is None or len(metabolite.elements) == 0: return False for element, amount in iteritems(metabolite.elements): balance[ele...
Confirm that a reaction is mass balanced.
def is_charge_balanced(reaction): charge = 0 for metabolite, coefficient in iteritems(reaction.metabolites): if metabolite.charge is None: return False charge += coefficient * metabolite.charge return charge == 0
Confirm that a reaction is charge balanced.
def check_partial(func, *args, **kwargs): new_func = partial(func, *args, **kwargs) new_func.check = func.check return new_func
Create a partial to be used by goodtables.
def gene_id_check(genes, errors, columns, row_number): message = ("Gene '{value}' in column {col} and row {row} does not " "appear in the metabolic model.") for column in columns: if "gene" in column['header'] and column['value'] not in genes: message = message.format( ...
Validate gene identifiers against a known set. Parameters ---------- genes : set The known set of gene identifiers. errors : Passed by goodtables. columns : Passed by goodtables. row_number : Passed by goodtables.
def reaction_id_check(reactions, errors, columns, row_number): message = ("Reaction '{value}' in column {col} and row {row} does not " "appear in the metabolic model.") for column in columns: if "reaction" in column['header'] and column['value'] not in reactions: message ...
Validate reactions identifiers against a known set. Parameters ---------- reactions : set The known set of reaction identifiers. errors : Passed by goodtables. columns : Passed by goodtables. row_number : Passed by goodtables.
def metabolite_id_check(metabolites, errors, columns, row_number): message = ("Metabolite '{value}' in column {col} and row {row} does not " "appear in the metabolic model.") for column in columns: if "metabolite" in column['header'] and \ column['value'] not in metab...
Validate metabolite identifiers against a known set. Parameters ---------- metabolites : set The known set of metabolite identifiers. errors : Passed by goodtables. columns : Passed by goodtables. row_number : Passed by goodtables.
def run(model, collect, filename, location, ignore_git, pytest_args, exclusive, skip, solver, experimental, custom_tests, deployment, skip_unchanged): def is_verbose(arg): return (arg.startswith("--verbosity") or arg.startswith("-v") or arg.startswith("--verbose") or ...
Run the test suite on a single model and collect results. MODEL: Path to model file. Can also be supplied via the environment variable MEMOTE_MODEL or configured in 'setup.cfg' or 'memote.ini'.
def new(directory, replay): callbacks.git_installed() if directory is None: directory = os.getcwd() cookiecutter("gh:opencobra/cookiecutter-memote", output_dir=directory, replay=replay)
Create a suitable model repository structure from a template. By using a cookiecutter template, memote will ask you a couple of questions and set up a new directory structure that will make your life easier. The new directory will be placed in the current directory or respect the given --directory opti...
def history(model, message, rewrite, solver, location, pytest_args, deployment, commits, skip, exclusive, experimental=None): # noqa: D301 # callbacks.validate_path(model) callbacks.git_installed() if location is None: raise click.BadParameter("No 'location' given or configured.") ...
Re-compute test results for the git branch history. MODEL is the path to the model file. MESSAGE is a commit message in case results were modified or added. [COMMIT] ... It is possible to list out individual commits that should be re-computed or supply a range <oldest commit>..<newest commit>, for ex...
def online(note, github_repository, github_username): callbacks.git_installed() try: repo = git.Repo() except git.InvalidGitRepositoryError: LOGGER.critical( "'memote online' requires a git repository in order to follow " "the current branch's commit history.") ...
Upload the repository to GitHub and enable testing on Travis CI.
def update_mock_repo(): target_file = os.path.abspath( join("tests", "data", "memote-mock-repo.tar.gz") ) temp_dir = mkdtemp(prefix='tmp_mock') previous_wd = os.getcwd() try: LOGGER.info("Cloning repository.") os.chdir(temp_dir) check_output( ['git', ...
Clone and gzip the memote-mock-repo used for CLI and integration tests. The repo is hosted at 'https://github.com/ChristianLieven/memote-mock-repo.git' and maintained separately from
def sum_biomass_weight(reaction): return sum(-coef * met.formula_weight for (met, coef) in iteritems(reaction.metabolites)) / 1000.0
Compute the sum of all reaction compounds. This function expects all metabolites of the biomass reaction to have formula information assigned. Parameters ---------- reaction : cobra.core.reaction.Reaction The biomass reaction of the model under investigation. Returns ------- f...
def find_biomass_precursors(model, reaction): id_of_main_compartment = helpers.find_compartment_id_in_model(model, 'c') gam_reactants = set() try: gam_reactants.update([ helpers.find_met_in_model( model, "MNXM3", id_of_main_compartment)[0]]) except RuntimeError: ...
Return a list of all biomass precursors excluding ATP and H2O. Parameters ---------- reaction : cobra.core.reaction.Reaction The biomass reaction of the model under investigation. model : cobra.Model The metabolic model under investigation. Returns ------- list Meta...
def find_blocked_biomass_precursors(reaction, model): LOGGER.debug("Finding blocked biomass precursors") precursors = find_biomass_precursors(model, reaction) blocked_precursors = list() _, ub = helpers.find_bounds(model) for precursor in precursors: with model: dm_rxn = mod...
Return a list of all biomass precursors that cannot be produced. Parameters ---------- reaction : cobra.core.reaction.Reaction The biomass reaction of the model under investigation. model : cobra.Model The metabolic model under investigation. Returns ------- list Me...
def gam_in_biomass(model, reaction): id_of_main_compartment = helpers.find_compartment_id_in_model(model, 'c') try: left = { helpers.find_met_in_model( model, "MNXM3", id_of_main_compartment)[0], helpers.find_met_in_model( model, "MNXM2", id_o...
Return boolean if biomass reaction includes growth-associated maintenance. Parameters ---------- model : cobra.Model The metabolic model under investigation. reaction : cobra.core.reaction.Reaction The biomass reaction of the model under investigation. Returns ------- boole...
def find_direct_metabolites(model, reaction, tolerance=1E-06): biomass_rxns = set(helpers.find_biomass_reaction(model)) tra_bou_bio_rxns = helpers.find_interchange_biomass_reactions( model, biomass_rxns) try: precursors = find_biomass_precursors(model, reaction) main_comp = help...
Return list of possible direct biomass precursor metabolites. The term direct metabolites describes metabolites that are involved only in either transport and/or boundary reactions, AND the biomass reaction(s), but not in any purely metabolic reactions. Parameters ---------- model : cobra.Mode...
def detect_false_positive_direct_metabolites( candidates, biomass_reactions, cytosol, extra, reaction_fluxes, metabolite_fluxes): for met in candidates: is_internal = met.compartment != extra for rxn in met.reactions: if rxn in biomass_reactions: cont...
Weed out false positive direct metabolites. False positives exists in the extracellular compartment with flux from the cytosolic compartment and are part of the biomass reaction(s). It sums fluxes positively or negatively depending on if direct metabolites in the extracellular compartment are defined a...
def bundle_biomass_components(model, reaction): if len(reaction.metabolites) >= 16: return [reaction] id_of_main_compartment = helpers.find_compartment_id_in_model(model, 'c') gam_mets = ["MNXM3", "MNXM2", "MNXM7", "MNXM1", 'MNXM...
Return bundle biomass component reactions if it is not one lumped reaction. There are two basic ways of specifying the biomass composition. The most common is a single lumped reaction containing all biomass precursors. Alternatively, the biomass equation can be split into several reactions each focusin...
def essential_precursors_not_in_biomass(model, reaction): u main_comp = helpers.find_compartment_id_in_model(model, 'c') biomass_eq = bundle_biomass_components(model, reaction) pooled_precursors = set( [met for rxn in biomass_eq for met in rxn.metabolites]) missing_essential_precursors = [] ...
u""" Return a list of essential precursors missing from the biomass reaction. There are universal components of life that make up the biomass of all known organisms. These include all proteinogenic amino acids, deoxy- and ribonucleotides, water and a range of metabolic cofactors. Parameters --...
def validate_experimental(context, param, value): if value is None: return config = ExperimentConfiguration(value) config.validate() return config
Load and validate an experimental data configuration.
def probe_git(): try: repo = git.Repo() except git.InvalidGitRepositoryError: LOGGER.warning( "We highly recommend keeping your model in a git repository." " It allows you to track changes and to easily collaborate with" " others via online platforms such...
Return a git repository instance if it exists.
def git_installed(): LOGGER.info("Checking `git` installation.") try: check_output(['git', '--version']) except CalledProcessError as e: LOGGER.critical( "The execution of memote was interrupted since no installation of " "`git` could be detected. Please install ...
Interrupt execution of memote if `git` has not been installed.
def record_git_info(self, commit=None): if commit is None: commit = self._repo.head.commit else: commit = self._repo.commit(commit) return GitInfo( hexsha=commit.hexsha, author=commit.author.name, email=commit.author.email, ...
Record git meta information. Parameters ---------- commit : str, optional Unique hexsha of the desired commit. Returns ------- GitInfo Git commit meta information.
def add_git(meta, git_info): meta["hexsha"] = git_info.hexsha meta["author"] = git_info.author meta["email"] = git_info.email meta["authored_on"] = git_info.authored_on.isoformat(" ")
Enrich the result meta information with commit data.
def store(self, result, commit=None, **kwargs): git_info = self.record_git_info(commit) self.add_git(result.meta, git_info) filename = self.get_filename(git_info) super(RepoResultManager, self).store( result, filename=filename, **kwargs)
Store a result in a JSON file attaching git meta information. Parameters ---------- result : memote.MemoteResult The dictionary structure of results. commit : str, optional Unique hexsha of the desired commit. kwargs : Passed to parent functio...
def load(self, commit=None): git_info = self.record_git_info(commit) LOGGER.debug("Loading the result for commit '%s'.", git_info.hexsha) filename = self.get_filename(git_info) LOGGER.debug("Loading the result '%s'.", filename) result = super(RepoResultManager, self).loa...
Load a result from the storage directory.
def normalize(filename): # Default value means we do not resolve a model file. if filename == "default": return filename filename = expanduser(filename) if isabs(filename): return filename else: return join(os.getcwd(), filename)
Return an absolute path of the given file name.
def load(self, dtype_conversion=None): if dtype_conversion is None: dtype_conversion = {"growth": str} super(GrowthExperiment, self).load(dtype_conversion=dtype_conversion) self.data["growth"] = self.data["growth"].isin(self.TRUTHY)
Load the data table and corresponding validation schema. Parameters ---------- dtype_conversion : dict Column names as keys and corresponding type for loading the data. Please take a look at the `pandas documentation <https://pandas.pydata.org/pandas-docs/sta...
def evaluate(self, model, threshold=0.1): with model: if self.medium is not None: self.medium.apply(model) if self.objective is not None: model.objective = self.objective model.add_cons_vars(self.constraints) threshold *= m...
Evaluate in silico growth rates.
def process_bind_param(self, value, dialect): try: with BytesIO() as stream: with GzipFile(fileobj=stream, mode="wb") as file_handle: file_handle.write( jsonify(value, pretty=False).encode("utf-8") ) ...
Convert the value to a JSON encoded string before storing it.
def process_result_value(self, value, dialect): if value is not None: with BytesIO(value) as stream: with GzipFile(fileobj=stream, mode="rb") as file_handle: value = json.loads(file_handle.read().decode("utf-8")) return value
Convert a JSON encoded string to a dictionary structure.
def render(self, name, value, attrs=None, **kwargs): min_score = zxcvbn_min_score() message_title = _('Warning') message_body = _( 'This password would take ' '<em class="password_strength_time"></em> to crack.') strength_markup = strength_markup...
Widget render method.
def render(self, name, value, attrs=None, **kwargs): if self.confirm_with: self.attrs['data-confirm-with'] = 'id_%s' % self.confirm_with confirmation_markup = % (_('Warning'), _("Your passwords don't match.")) try: self.attrs['class'] = '%s password_confirmation...
Widget render method.
def validate(self, password, user=None): user_inputs = [] if user is not None: for attribute in self.user_attributes: if hasattr(user, attribute): user_inputs.append(getattr(user, attribute)) results = zxcvbn(password, user_inputs=user_inp...
Validate method, run zxcvbn and check score.
def _get_html_contents(html): parser = MyHTMLParser() parser.feed(html) if parser.is_code: return ('code', parser.data.strip()) elif parser.is_math: return ('math', parser.data.strip()) else: return '', ''
Process a HTML block and detects whether it is a code block, a math block, or a regular HTML block.
def _is_path(s): if isinstance(s, string_types): try: return op.exists(s) except (OSError, ValueError): return False else: return False
Return whether an object is a path.
def format_manager(cls): if cls._instance is None: # Discover the formats and register them with a new singleton. cls._instance = cls().register_entrypoints() return cls._instance
Return the instance singleton, creating if necessary
def register_entrypoints(self): for spec in iter_entry_points(self.entry_point_group): format_properties = {"name": spec.name} try: format_properties.update(spec.load()) except (DistributionNotFound, ImportError) as err: self.log.info(...
Look through the `setup_tools` `entry_points` and load all of the formats.
def format_from_extension(self, extension): formats = [name for name, format in self._formats.items() if format.get('file_extension', None) == extension] if len(formats) == 0: return None elif len(formats) == 2: raise Runtime...
Find a format from its extension.
def load(self, file, name=None): if name is None: name = self.format_from_extension(op.splitext(file)[1]) file_format = self.file_type(name) if file_format == 'text': return _read_text(file) elif file_format == 'json': return _read_json(file) ...
Load a file. The format name can be specified explicitly or inferred from the file extension.
def save(self, file, contents, name=None, overwrite=False): if name is None: name = self.format_from_extension(op.splitext(file)[1]) file_format = self.file_type(name) if file_format == 'text': _write_text(file, contents) elif file_format == 'json': ...
Save contents into a file. The format name can be specified explicitly or inferred from the file extension.
def create_reader(self, name, *args, **kwargs): self._check_format(name) return self._formats[name]['reader'](*args, **kwargs)
Create a new reader instance for a given format.