Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def add_reverse_effects(self): # TODO: generalize to other modification sites pos_mod_sites = {} neg_mod_sites = {} syntheses = [] degradations = [] for stmt in self.statements: if isinstance(stmt, Phosphor...
[ "Add Statements for the reverse effects of some Statements.\n\n For instance, if a protein is phosphorylated but never dephosphorylated\n in the model, we add a generic dephosphorylation here. This step is\n usually optional in the assembly process.\n " ]
Please provide a description of the function:def _get_uniprot_id(agent): up_id = agent.db_refs.get('UP') hgnc_id = agent.db_refs.get('HGNC') if up_id is None: if hgnc_id is None: # If both UniProt and HGNC refs are missing we can't # sequence check and so don't report a ...
[ "Return the UniProt ID for an agent, looking up in HGNC if necessary.\n\n If the UniProt ID is a list then return the first ID by default.\n " ]
Please provide a description of the function:def map_sites(self, stmts): valid_statements = [] mapped_statements = [] for stmt in stmts: mapped_stmt = self.map_stmt_sites(stmt) # If we got a MappedStatement as a return value, we add that to the # lis...
[ "Check a set of statements for invalid modification sites.\n\n Statements are checked against Uniprot reference sequences to determine\n if residues referred to by post-translational modifications exist at\n the given positions.\n\n If there is nothing amiss with a statement (modificatio...
Please provide a description of the function:def _map_agent_sites(self, agent): # If there are no modifications on this agent, then we can return the # copy of the agent if agent is None or not agent.mods: return [], agent new_agent = deepcopy(agent) mapped_s...
[ "Check an agent for invalid sites and update if necessary.\n\n Parameters\n ----------\n agent : :py:class:`indra.statements.Agent`\n Agent to check for invalid modification sites.\n\n Returns\n -------\n tuple\n The first element is a list of MappedSi...
Please provide a description of the function:def _map_agent_mod(self, agent, mod_condition): # Get the UniProt ID of the agent, if not found, return up_id = _get_uniprot_id(agent) if not up_id: logger.debug("No uniprot ID for %s" % agent.name) return None ...
[ "Map a single modification condition on an agent.\n\n Parameters\n ----------\n agent : :py:class:`indra.statements.Agent`\n Agent to check for invalid modification sites.\n mod_condition : :py:class:`indra.statements.ModCondition`\n Modification to check for validi...
Please provide a description of the function:def _get_graph_reductions(graph): def frontier(g, nd): if g.out_degree(nd) == 0: return set([nd]) else: frontiers = set() for n in g.successors(nd): frontiers = frontiers.union(frontier(gra...
[ "Return transitive reductions on a DAG.\n\n This is used to reduce the set of activities of a BaseAgent to the most\n specific one(s) possible. For instance, if a BaseAgent is know to have\n 'activity', 'catalytic' and 'kinase' activity, then this function will\n return {'activity': 'kinase', 'catalytic...
Please provide a description of the function:def gather_explicit_activities(self): for stmt in self.statements: agents = stmt.agent_list() # Activity types given as ActivityConditions for agent in agents: if agent is not None and agent.activity is not...
[ "Aggregate all explicit activities and active forms of Agents.\n\n This function iterates over self.statements and extracts explicitly\n stated activity types and active forms for Agents.\n " ]
Please provide a description of the function:def gather_implicit_activities(self): for stmt in self.statements: if isinstance(stmt, Phosphorylation) or \ isinstance(stmt, Transphosphorylation) or \ isinstance(stmt, Autophosphorylation): if stm...
[ "Aggregate all implicit activities and active forms of Agents.\n\n Iterate over self.statements and collect the implied activities\n and active forms of Agents that appear in the Statements.\n\n Note that using this function to collect implied Agent activities can\n be risky. Assume, for...
Please provide a description of the function:def require_active_forms(self): logger.info('Setting required active forms on %d statements...' % len(self.statements)) new_stmts = [] for stmt in self.statements: if isinstance(stmt, Modification): ...
[ "Rewrites Statements with Agents' active forms in active positions.\n\n As an example, the enzyme in a Modification Statement can be expected\n to be in an active state. Similarly, subjects of RegulateAmount and\n RegulateActivity Statements can be expected to be in an active form.\n Thi...
Please provide a description of the function:def reduce_activities(self): for stmt in self.statements: agents = stmt.agent_list() for agent in agents: if agent is not None and agent.activity is not None: agent_base = self._get_base(agent) ...
[ "Rewrite the activity types referenced in Statements for consistency.\n\n Activity types are reduced to the most specific form whenever possible.\n For instance, if 'kinase' is the only specific activity type known\n for the BaseAgent of BRAF, its generic 'activity' forms are rewritten\n ...
Please provide a description of the function:def infer_complexes(stmts): interact_stmts = _get_statements_by_type(stmts, Modification) linked_stmts = [] for mstmt in interact_stmts: if mstmt.enz is None: continue st = Complex([mstmt.enz, mstmt.sub...
[ "Return inferred Complex from Statements implying physical interaction.\n\n Parameters\n ----------\n stmts : list[indra.statements.Statement]\n A list of Statements to infer Complexes from.\n\n Returns\n -------\n linked_stmts : list[indra.mechlinker.LinkedState...
Please provide a description of the function:def infer_activations(stmts): linked_stmts = [] af_stmts = _get_statements_by_type(stmts, ActiveForm) mod_stmts = _get_statements_by_type(stmts, Modification) for af_stmt, mod_stmt in itertools.product(*(af_stmts, mod_stmts)): ...
[ "Return inferred RegulateActivity from Modification + ActiveForm.\n\n This function looks for combinations of Modification and ActiveForm\n Statements and infers Activation/Inhibition Statements from them.\n For example, if we know that A phosphorylates B, and the\n phosphorylated form o...
Please provide a description of the function:def infer_active_forms(stmts): linked_stmts = [] for act_stmt in _get_statements_by_type(stmts, RegulateActivity): # TODO: revise the conditions here if not (act_stmt.subj.activity is not None and act_stmt.subj...
[ "Return inferred ActiveForm from RegulateActivity + Modification.\n\n This function looks for combinations of Activation/Inhibition\n Statements and Modification Statements, and infers an ActiveForm\n from them. For example, if we know that A activates B and\n A phosphorylates B, then we...
Please provide a description of the function:def infer_modifications(stmts): linked_stmts = [] for act_stmt in _get_statements_by_type(stmts, RegulateActivity): for af_stmt in _get_statements_by_type(stmts, ActiveForm): if not af_stmt.agent.entity_matches(act_stmt.ob...
[ "Return inferred Modification from RegulateActivity + ActiveForm.\n\n This function looks for combinations of Activation/Inhibition Statements\n and ActiveForm Statements that imply a Modification Statement.\n For example, if we know that A activates B, and phosphorylated B is\n active, ...
Please provide a description of the function:def replace_complexes(self, linked_stmts=None): if linked_stmts is None: linked_stmts = self.infer_complexes(self.statements) new_stmts = [] for stmt in self.statements: if not isinstance(stmt, Complex): ...
[ "Remove Complex Statements that can be inferred out.\n\n This function iterates over self.statements and looks for Complex\n Statements that either match or are refined by inferred Complex\n Statements that were linked (provided as the linked_stmts argument).\n It removes Complex Stateme...
Please provide a description of the function:def replace_activations(self, linked_stmts=None): if linked_stmts is None: linked_stmts = self.infer_activations(self.statements) new_stmts = [] for stmt in self.statements: if not isinstance(stmt, RegulateActivity): ...
[ "Remove RegulateActivity Statements that can be inferred out.\n\n This function iterates over self.statements and looks for\n RegulateActivity Statements that either match or are refined by\n inferred RegulateActivity Statements that were linked\n (provided as the linked_stmts argument)....
Please provide a description of the function:def get_create_base_agent(self, agent): try: base_agent = self.agents[agent.name] except KeyError: base_agent = BaseAgent(agent.name) self.agents[agent.name] = base_agent return base_agent
[ "Return BaseAgent from an Agent, creating it if needed.\n\n Parameters\n ----------\n agent : indra.statements.Agent\n\n Returns\n -------\n base_agent : indra.mechlinker.BaseAgent\n " ]
Please provide a description of the function:def apply_to(self, agent): agent.bound_conditions = self.bound_conditions agent.mods = self.mods agent.mutations = self.mutations agent.location = self.location return self.evidence
[ "Apply this object's state to an Agent.\n\n Parameters\n ----------\n agent : indra.statements.Agent\n The agent to which the state should be applied\n " ]
Please provide a description of the function:def submit_curation(): if request.json is None: abort(Response('Missing application/json header.', 415)) # Get input parameters corpus_id = request.json.get('corpus_id') curations = request.json.get('curations', {}) try: curator.submi...
[ "Submit curations for a given corpus.\n\n The submitted curations are handled to update the probability model but\n there is no return value here. The update_belief function can be called\n separately to calculate update belief scores.\n\n Parameters\n ----------\n corpus_id : str\n The ID ...
Please provide a description of the function:def update_beliefs(): if request.json is None: abort(Response('Missing application/json header.', 415)) # Get input parameters corpus_id = request.json.get('corpus_id') try: belief_dict = curator.update_beliefs(corpus_id) except Inval...
[ "Return updated beliefs based on current probability model." ]
Please provide a description of the function:def reset_scorer(self): self.scorer = get_eidos_bayesian_scorer() for corpus_id, corpus in self.corpora.items(): corpus.curations = {}
[ "Reset the scorer used for couration." ]
Please provide a description of the function:def get_corpus(self, corpus_id): try: corpus = self.corpora[corpus_id] return corpus except KeyError: raise InvalidCorpusError
[ "Return a corpus given an ID.\n\n If the corpus ID cannot be found, an InvalidCorpusError is raised.\n\n Parameters\n ----------\n corpus_id : str\n The ID of the corpus to return.\n\n Returns\n -------\n Corpus\n The corpus with the given ID.\n...
Please provide a description of the function:def submit_curation(self, corpus_id, curations): corpus = self.get_corpus(corpus_id) # Start tabulating the curation counts prior_counts = {} subtype_counts = {} # Take each curation from the input for uuid, correct in...
[ "Submit correct/incorrect curations fo a given corpus.\n\n Parameters\n ----------\n corpus_id : str\n The ID of the corpus to which the curations apply.\n curations : dict\n A dict of curations with keys corresponding to Statement UUIDs and\n values corr...
Please provide a description of the function:def update_beliefs(self, corpus_id): corpus = self.get_corpus(corpus_id) be = BeliefEngine(self.scorer) stmts = list(corpus.statements.values()) be.set_prior_probs(stmts) # Here we set beliefs based on actual curation ...
[ "Return updated belief scores for a given corpus.\n\n Parameters\n ----------\n corpus_id : str\n The ID of the corpus for which beliefs are to be updated.\n\n Returns\n -------\n dict\n A dictionary of belief scores with keys corresponding to Statemen...
Please provide a description of the function:def get_python_list(scala_list): python_list = [] for i in range(scala_list.length()): python_list.append(scala_list.apply(i)) return python_list
[ "Return list from elements of scala.collection.immutable.List" ]
Please provide a description of the function:def get_python_dict(scala_map): python_dict = {} keys = get_python_list(scala_map.keys().toList()) for key in keys: python_dict[key] = scala_map.apply(key) return python_dict
[ "Return a dict from entries in a scala.collection.immutable.Map" ]
Please provide a description of the function:def get_python_json(scala_json): def convert_node(node): if node.__class__.__name__ in ('org.json4s.JsonAST$JValue', 'org.json4s.JsonAST$JObject'): # Make a dictionary and then convert each value ...
[ "Return a JSON dict from a org.json4s.JsonAST" ]
Please provide a description of the function:def get_heat_kernel(network_id): url = ndex_relevance + '/%s/generate_ndex_heat_kernel' % network_id res = ndex_client.send_request(url, {}, is_json=True, use_get=True) if res is None: logger.error('Could not get heat kernel for network %s.' % networ...
[ "Return the identifier of a heat kernel calculated for a given network.\n\n Parameters\n ----------\n network_id : str\n The UUID of the network in NDEx.\n\n Returns\n -------\n kernel_id : str\n The identifier of the heat kernel calculated for the given network.\n " ]
Please provide a description of the function:def get_relevant_nodes(network_id, query_nodes): url = ndex_relevance + '/rank_entities' kernel_id = get_heat_kernel(network_id) if kernel_id is None: return None if isinstance(query_nodes, basestring): query_nodes = [query_nodes] par...
[ "Return a set of network nodes relevant to a given query set.\n\n A heat diffusion algorithm is used on a pre-computed heat kernel for the\n given network which starts from the given query nodes. The nodes\n in the network are ranked according to heat score which is a measure\n of relevance with respect...
Please provide a description of the function:def _get_belief_package(stmt): # This list will contain the belief packages for the given statement belief_packages = [] # Iterate over all the support parents for st in stmt.supports: # Recursively get all the belief packages of the parent ...
[ "Return the belief packages of a given statement recursively." ]
Please provide a description of the function:def sample_statements(stmts, seed=None): if seed: numpy.random.seed(seed) new_stmts = [] r = numpy.random.rand(len(stmts)) for i, stmt in enumerate(stmts): if r[i] < stmt.belief: new_stmts.append(stmt) return new_stmts
[ "Return statements sampled according to belief.\n\n Statements are sampled independently according to their\n belief scores. For instance, a Staement with a belief\n score of 0.7 will end up in the returned Statement list\n with probability 0.7.\n\n Parameters\n ----------\n stmts : list[indra....
Please provide a description of the function:def evidence_random_noise_prior(evidence, type_probs, subtype_probs): (stype, subtype) = tag_evidence_subtype(evidence) # Get the subtype, if available # Return the subtype random noise prior, if available if subtype_probs is not None: if stype ...
[ "Determines the random-noise prior probability for this evidence.\n\n If the evidence corresponds to a subtype, and that subtype has a curated\n prior noise probability, use that.\n\n Otherwise, gives the random-noise prior for the overall rule type.\n " ]
Please provide a description of the function:def score_evidence_list(self, evidences): def _score(evidences): if not evidences: return 0 # Collect all unique sources sources = [ev.source_api for ev in evidences] uniq_sources = numpy.unique...
[ "Return belief score given a list of supporting evidences." ]
Please provide a description of the function:def score_statement(self, st, extra_evidence=None): if extra_evidence is None: extra_evidence = [] all_evidence = st.evidence + extra_evidence return self.score_evidence_list(all_evidence)
[ "Computes the prior belief probability for an INDRA Statement.\n\n The Statement is assumed to be de-duplicated. In other words,\n the Statement is assumed to have\n a list of Evidence objects that supports it. The prior probability of\n the Statement is calculated based on the number of...
Please provide a description of the function:def check_prior_probs(self, statements): sources = set() for stmt in statements: sources |= set([ev.source_api for ev in stmt.evidence]) for err_type in ('rand', 'syst'): for source in sources: if sourc...
[ "Throw Exception if BeliefEngine parameter is missing.\n\n Make sure the scorer has all the information needed to compute\n belief scores of each statement in the provided list, and raises an\n exception otherwise.\n\n Parameters\n ----------\n statements : list[indra.state...
Please provide a description of the function:def update_probs(self): # We deal with the prior probsfirst # This is a fixed assumed value for systematic error syst_error = 0.05 prior_probs = {'syst': {}, 'rand': {}} for source, (p, n) in self.prior_counts.items(): ...
[ "Update the internal probability values given the counts." ]
Please provide a description of the function:def update_counts(self, prior_counts, subtype_counts): for source, (pos, neg) in prior_counts.items(): if source not in self.prior_counts: self.prior_counts[source] = [0, 0] self.prior_counts[source][0] += pos ...
[ "Update the internal counts based on given new counts.\n\n Parameters\n ----------\n prior_counts : dict\n A dictionary of counts of the form [pos, neg] for\n each source.\n subtype_counts : dict\n A dictionary of counts of the form [pos, neg] for\n ...
Please provide a description of the function:def set_prior_probs(self, statements): self.scorer.check_prior_probs(statements) for st in statements: st.belief = self.scorer.score_statement(st)
[ "Sets the prior belief probabilities for a list of INDRA Statements.\n\n The Statements are assumed to be de-duplicated. In other words,\n each Statement in the list passed to this function is assumed to have\n a list of Evidence objects that support it. The prior probability of\n each S...
Please provide a description of the function:def set_hierarchy_probs(self, statements): def build_hierarchy_graph(stmts): g = networkx.DiGraph() for st1 in stmts: g.add_node(st1.matches_key(), stmt=st1) for st2 in st1.supported_by: ...
[ "Sets hierarchical belief probabilities for INDRA Statements.\n\n The Statements are assumed to be in a hierarchical relation graph with\n the supports and supported_by attribute of each Statement object having\n been set.\n The hierarchical belief probability of each Statement is calcul...
Please provide a description of the function:def set_linked_probs(self, linked_statements): for st in linked_statements: source_probs = [s.belief for s in st.source_stmts] st.inferred_stmt.belief = numpy.prod(source_probs)
[ "Sets the belief probabilities for a list of linked INDRA Statements.\n\n The list of LinkedStatement objects is assumed to come from the\n MechanismLinker. The belief probability of the inferred Statement is\n assigned the joint probability of its source Statements.\n\n Parameters\n ...
Please provide a description of the function:def get_agent_from_entity_info(entity_info): # This will be the default name. If we get a gene name, it will # override this rawtext name. raw_text = entity_info['entityText'] name = raw_text # Get the db refs. refs = {'TEXT': raw_text} ref...
[ "Return an INDRA Agent by processing an entity_info dict." ]
Please provide a description of the function:def extract_statements(self): for p_info in self._json: para = RlimspParagraph(p_info, self.doc_id_type) self.statements.extend(para.get_statements()) return
[ "Extract the statements from the json." ]
Please provide a description of the function:def _get_agent(self, entity_id): if entity_id is None: return None entity_info = self._entity_dict.get(entity_id) if entity_info is None: logger.warning("Entity key did not resolve to entity.") return None...
[ "Convert the entity dictionary into an INDRA Agent." ]
Please provide a description of the function:def _get_evidence(self, trigger_id, args, agent_coords, site_coords): trigger_info = self._entity_dict[trigger_id] # Get the sentence index from the trigger word. s_idx_set = {self._entity_dict[eid]['sentenceIndex'] for ...
[ "Get the evidence using the info in the trigger entity." ]
Please provide a description of the function:def get_reader_classes(parent=Reader): children = parent.__subclasses__() descendants = children[:] for child in children: grandchildren = get_reader_classes(child) if grandchildren: descendants.remove(child) descendan...
[ "Get all childless the descendants of a parent class, recursively." ]
Please provide a description of the function:def get_reader_class(reader_name): for reader_class in get_reader_classes(): if reader_class.name.lower() == reader_name.lower(): return reader_class else: logger.error("No such reader: %s" % reader_name) return None
[ "Get a particular reader class by name." ]
Please provide a description of the function:def from_file(cls, file_path, compressed=False, encoded=False): file_id = '.'.join(path.basename(file_path).split('.')[:-1]) file_format = file_path.split('.')[-1] content = cls(file_id, file_format, compressed, encoded) content.file_...
[ "Create a content object from a file path." ]
Please provide a description of the function:def from_string(cls, id, format, raw_content, compressed=False, encoded=False): content = cls(id, format, compressed, encoded) content._raw_content = raw_content return content
[ "Create a Content object from string/bytes content." ]
Please provide a description of the function:def change_id(self, new_id): self._load_raw_content() self._id = new_id self.get_filename(renew=True) self.get_filepath(renew=True) return
[ "Change the id of this content." ]
Please provide a description of the function:def change_format(self, new_format): self._load_raw_content() self._format = new_format self.get_filename(renew=True) self.get_filepath(renew=True) return
[ "Change the format label of this content.\n\n Note that this does NOT actually alter the format of the content, only\n the label.\n " ]
Please provide a description of the function:def set_location(self, new_location): self._load_raw_content() self._location = new_location self.get_filepath(renew=True) return
[ "Set/change the location of this content.\n\n Note that this does NOT change the actual location of the file. To do\n so, use the `copy_to` method.\n " ]
Please provide a description of the function:def get_text(self): self._load_raw_content() if self._text is None: assert self._raw_content is not None ret_cont = self._raw_content if self.compressed: ret_cont = zlib.decompress(ret_cont, zlib.MA...
[ "Get the loaded, decompressed, and decoded text of this content." ]
Please provide a description of the function:def get_filename(self, renew=False): if self._fname is None or renew: self._fname = '%s.%s' % (self._id, self._format) return self._fname
[ "Get the filename of this content.\n\n If the file name doesn't already exist, we created it as {id}.{format}.\n " ]
Please provide a description of the function:def get_filepath(self, renew=False): if self._location is None or renew: self._location = '.' return path.join(self._location, self.get_filename())
[ "Get the file path, joining the name and location for this file.\n\n If no location is given, it is assumed to be \"here\", e.g. \".\".\n " ]
Please provide a description of the function:def get_statements(self, reprocess=False): if self._statements is None or reprocess: # Handle the case that there is no content. if self.content is None: self._statements = [] return [] # M...
[ "General method to create statements." ]
Please provide a description of the function:def add_result(self, content_id, content, **kwargs): result_object = self.ResultClass(content_id, self.name, self.version, formats.JSON, content, **kwargs) self.results.append(result_object) return
[ "\"Add a result to the list of results." ]
Please provide a description of the function:def _check_content(self, content_str): if self.do_content_check: space_ratio = float(content_str.count(' '))/len(content_str) if space_ratio > self.max_space_ratio: return "space-ratio: %f > %f" % (space_ratio, ...
[ "Check if the content is likely to be successfully read." ]
Please provide a description of the function:def _join_json_files(cls, prefix, clear=False): filetype_list = ['entities', 'events', 'sentences'] json_dict = {} try: for filetype in filetype_list: fname = prefix + '.uaz.' + filetype + '.json' w...
[ "Join different REACH output JSON files into a single JSON object.\n\n The output of REACH is broken into three files that need to be joined\n before processing. Specifically, there will be three files of the form:\n `<prefix>.uaz.<subcategory>.json`.\n\n Parameters\n ----------\n...
Please provide a description of the function:def _check_reach_env(): # Get the path to the REACH JAR path_to_reach = get_config('REACHPATH') if path_to_reach is None: path_to_reach = environ.get('REACHPATH', None) if path_to_reach is None or not path.exists(path_to_r...
[ "Check that the environment supports runnig reach." ]
Please provide a description of the function:def prep_input(self, read_list): logger.info("Prepping input.") i = 0 for content in read_list: # Check the quality of the text, and skip if there are any issues. quality_issue = self._check_content(content.get_text())...
[ "Apply the readers to the content." ]
Please provide a description of the function:def get_output(self): logger.info("Getting outputs.") # Get the set of prefixes (each will correspond to three json files.) json_files = glob.glob(path.join(self.output_dir, '*.json')) json_prefixes = set() for json_file in js...
[ "Get the output of a reading job as a list of filenames." ]
Please provide a description of the function:def clear_input(self): for item in listdir(self.input_dir): item_path = path.join(self.input_dir, item) if path.isfile(item_path): remove(item_path) logger.debug('Removed input %s.' % item_path) ...
[ "Remove all the input files (at the end of a reading)." ]
Please provide a description of the function:def read(self, read_list, verbose=False, log=False): ret = [] mem_tot = _get_mem_total() if mem_tot is not None and mem_tot <= self.REACH_MEM + self.MEM_BUFFER: logger.error( "Too little memory to run reach. At lea...
[ "Read the content, returning a list of ReadingData objects." ]
Please provide a description of the function:def prep_input(self, read_list): "Prepare the list of files or text content objects to be read." logger.info('Prepping input for sparser.') self.file_list = [] for content in read_list: quality_issue = self._check_content(content...
[]
Please provide a description of the function:def get_output(self, output_files, clear=True): "Get the output files as an id indexed dict." patt = re.compile(r'(.*?)-semantics.*?') for outpath in output_files: if outpath is None: logger.warning("Found outpath with valu...
[]
Please provide a description of the function:def read_some(self, fpath_list, outbuf=None, verbose=False): "Perform a few readings." outpath_list = [] for fpath in fpath_list: output, outbuf = self.read_one(fpath, outbuf, verbose) if output is not None: out...
[]
Please provide a description of the function:def read(self, read_list, verbose=False, log=False, n_per_proc=None): "Perform the actual reading." ret = [] self.prep_input(read_list) L = len(self.file_list) if L == 0: return ret logger.info("Beginning to run sp...
[]
Please provide a description of the function:def process_text(text, pmid=None, cleanup=True, add_grounding=True): # Create a temporary directory to store the proprocessed input pp_dir = tempfile.mkdtemp('indra_isi_pp_output') pp = IsiPreprocessor(pp_dir) extra_annotations = {} pp.preprocess_pl...
[ "Process a string using the ISI reader and extract INDRA statements.\n\n Parameters\n ----------\n text : str\n A text string to process\n pmid : Optional[str]\n The PMID associated with this text (or None if not specified)\n cleanup : Optional[bool]\n If True, the temporary fold...
Please provide a description of the function:def process_nxml(nxml_filename, pmid=None, extra_annotations=None, cleanup=True, add_grounding=True): if extra_annotations is None: extra_annotations = {} # Create a temporary directory to store the proprocessed input pp_dir = tempf...
[ "Process an NXML file using the ISI reader\n\n First converts NXML to plain text and preprocesses it, then runs the ISI\n reader, and processes the output to extract INDRA Statements.\n\n Parameters\n ----------\n nxml_filename : str\n nxml file to process\n pmid : Optional[str]\n pm...
Please provide a description of the function:def process_preprocessed(isi_preprocessor, num_processes=1, output_dir=None, cleanup=True, add_grounding=True): # Create a temporary directory to store the output if output_dir is None: output_dir = tempfile.mkdtemp('indra_isi_p...
[ "Process a directory of abstracts and/or papers preprocessed using the\n specified IsiPreprocessor, to produce a list of extracted INDRA statements.\n\n Parameters\n ----------\n isi_preprocessor : indra.sources.isi.preprocessor.IsiPreprocessor\n Preprocessor object that has already preprocessed ...
Please provide a description of the function:def process_output_folder(folder_path, pmids=None, extra_annotations=None, add_grounding=True): pmids = pmids if pmids is not None else {} extra_annotations = extra_annotations if \ extra_annotations is not None else {} ips ...
[ "Recursively extracts statements from all ISI output files in the\n given directory and subdirectories.\n\n Parameters\n ----------\n folder_path : str\n The directory to traverse\n pmids : Optional[str]\n PMID mapping to be added to the Evidence of the extracted INDRA\n Statemen...
Please provide a description of the function:def process_json_file(file_path, pmid=None, extra_annotations=None, add_grounding=True): logger.info('Extracting from %s' % file_path) with open(file_path, 'rb') as fh: jd = json.load(fh) ip = IsiProcessor(jd, pmid, extra_an...
[ "Extracts statements from the given ISI output file.\n\n Parameters\n ----------\n file_path : str\n The ISI output file from which to extract statements\n pmid : int\n The PMID of the document being preprocessed, or None if not\n specified\n extra_annotations : dict\n Ext...
Please provide a description of the function:def process_text(text, save_xml='cwms_output.xml'): xml = client.send_query(text, 'cwmsreader') # There are actually two EKBs in the xml document. Extract the second. first_end = xml.find('</ekb>') # End of first EKB second_start = xml.find('<ekb', fir...
[ "Processes text using the CWMS web service.\n\n Parameters\n ----------\n text : str\n Text to process\n\n Returns\n -------\n cp : indra.sources.cwms.CWMSProcessor\n A CWMSProcessor, which contains a list of INDRA statements in its\n statements attribute.\n " ]
Please provide a description of the function:def process_ekb_file(fname): # Process EKB XML file into statements with open(fname, 'rb') as fh: ekb_str = fh.read().decode('utf-8') return process_ekb(ekb_str)
[ "Processes an EKB file produced by CWMS.\n\n Parameters\n ----------\n fname : str\n Path to the EKB file to process.\n\n Returns\n -------\n cp : indra.sources.cwms.CWMSProcessor\n A CWMSProcessor, which contains a list of INDRA statements in its\n statements attribute.\n ...
Please provide a description of the function:def im_json_to_graph(im_json): imap_data = im_json['influence map']['map'] # Initialize the graph graph = MultiDiGraph() id_node_dict = {} # Add each node to the graph for node_dict in imap_data['nodes']: # There is always just one entr...
[ "Return networkx graph from Kappy's influence map JSON.\n\n Parameters\n ----------\n im_json : dict\n A JSON dict which contains an influence map generated by Kappy.\n\n Returns\n -------\n graph : networkx.MultiDiGraph\n A graph representing the influence map.\n " ]
Please provide a description of the function:def cm_json_to_graph(im_json): cmap_data = im_json['contact map']['map'] # Initialize the graph graph = AGraph() # In this loop we add sites as nodes and clusters around sites to the # graph. We also collect edges to be added between sites later. ...
[ "Return pygraphviz Agraph from Kappy's contact map JSON.\n\n Parameters\n ----------\n im_json : dict\n A JSON dict which contains a contact map generated by Kappy.\n\n Returns\n -------\n graph : pygraphviz.Agraph\n A graph representing the contact map.\n " ]
Please provide a description of the function:def fetch_email(M, msg_id): res, data = M.fetch(msg_id, '(RFC822)') if res == 'OK': # Data here is a list with 1 element containing a tuple # whose 2nd element is a long string containing the email # The content is a bytes that must be de...
[ "Returns the given email message as a unicode string." ]
Please provide a description of the function:def get_headers(msg): headers = {} for k in msg.keys(): # decode_header decodes header but does not convert charset, so these # may still be bytes, even in Python 3. However, if it's ASCII # only (hence unambiguous encoding), the header f...
[ "Takes email.message.Message object initialized from unicode string,\n returns dict with header fields." ]
Please provide a description of the function:def populate_config_dict(config_path): try: config_dict = {} parser = RawConfigParser() parser.optionxform = lambda x: x parser.read(config_path) sections = parser.sections() for section in sections: option...
[ "Load the configuration file into the config_file dictionary\n\n A ConfigParser-style configuration file can have multiple sections, but\n we ignore the section distinction and load the key/value pairs from all\n sections into a single key/value list.\n " ]
Please provide a description of the function:def get_config(key, failure_ok=True): err_msg = "Key %s not in environment or config file." % key if key in os.environ: return os.environ[key] elif key in CONFIG_DICT: val = CONFIG_DICT[key] # We interpret an empty value in the config...
[ "Get value by key from config file or environment.\n\n Returns the configuration value, first checking the environment\n variables and then, if it's not present there, checking the configuration\n file.\n\n Parameters\n ----------\n key : str\n The key for the configuration value to fetch\n...
Please provide a description of the function:def read_unicode_csv_fileobj(fileobj, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL, lineterminator='\n', encoding='utf-8', skiprows=0): # Python 3 version if sys.version_info[0] >= 3: #...
[ "fileobj can be a StringIO in Py3, but should be a BytesIO in Py2." ]
Please provide a description of the function:def fast_deepcopy(obj): with BytesIO() as buf: pickle.dump(obj, buf) buf.seek(0) obj_new = pickle.load(buf) return obj_new
[ "This is a faster implementation of deepcopy via pickle.\n\n It is meant primarily for sets of Statements with complex hierarchies\n but can be used for any object.\n " ]
Please provide a description of the function:def flatten(l): return sum(map(flatten, l), []) \ if isinstance(l, list) or isinstance(l, tuple) else [l]
[ "Flatten a nested list." ]
Please provide a description of the function:def batch_iter(iterator, batch_size, return_func=None, padding=None): for batch in zip_longest(*[iter(iterator)]*batch_size, fillvalue=padding): gen = (thing for thing in batch if thing is not padding) if return_func is None: yield gen ...
[ "Break an iterable into batches of size batch_size\n\n Note that `padding` should be set to something (anything) which is NOT a\n valid member of the iterator. For example, None works for [0,1,2,...10], but\n not for ['a', None, 'c', 'd'].\n\n Parameters\n ----------\n iterator : iterable\n ...
Please provide a description of the function:def read_pmid_sentences(pmid_sentences, **drum_args): def _set_pmid(statements, pmid): for stmt in statements: for evidence in stmt.evidence: evidence.pmid = pmid # See if we need to start DRUM as a subprocess run_drum = ...
[ "Read sentences from a PMID-keyed dictonary and return all Statements\n\n Parameters\n ----------\n pmid_sentences : dict[str, list[str]]\n A dictonary where each key is a PMID pointing to a list of sentences\n to be read.\n\n **drum_args\n Keyword arguments passed directly to the D...
Please provide a description of the function:def graph_query(kind, source, target=None, neighbor_limit=1, database_filter=None): default_databases = ['wp', 'smpdb', 'reconx', 'reactome', 'psp', 'pid', 'panther', 'netpath', 'msigdb', 'mirtarbase', 'kegg', ...
[ "Perform a graph query on PathwayCommons.\n\n For more information on these queries, see\n http://www.pathwaycommons.org/pc2/#graph\n\n Parameters\n ----------\n kind : str\n The kind of graph query to perform. Currently 3 options are\n implemented, 'neighborhood', 'pathsbetween' and 'p...
Please provide a description of the function:def owl_str_to_model(owl_str): io_class = autoclass('org.biopax.paxtools.io.SimpleIOHandler') io = io_class(autoclass('org.biopax.paxtools.model.BioPAXLevel').L3) bais = autoclass('java.io.ByteArrayInputStream') scs = autoclass('java.nio.charset.Standard...
[ "Return a BioPAX model object from an OWL string.\n\n Parameters\n ----------\n owl_str : str\n The model as an OWL string.\n\n Returns\n -------\n biopax_model : org.biopax.paxtools.model.Model\n A BioPAX model object (java object).\n " ]
Please provide a description of the function:def owl_to_model(fname): io_class = autoclass('org.biopax.paxtools.io.SimpleIOHandler') io = io_class(autoclass('org.biopax.paxtools.model.BioPAXLevel').L3) try: file_is = autoclass('java.io.FileInputStream')(fname) except JavaException: ...
[ "Return a BioPAX model object from an OWL file.\n\n Parameters\n ----------\n fname : str\n The name of the OWL file containing the model.\n\n Returns\n -------\n biopax_model : org.biopax.paxtools.model.Model\n A BioPAX model object (java object).\n " ]
Please provide a description of the function:def model_to_owl(model, fname): io_class = autoclass('org.biopax.paxtools.io.SimpleIOHandler') io = io_class(autoclass('org.biopax.paxtools.model.BioPAXLevel').L3) try: fileOS = autoclass('java.io.FileOutputStream')(fname) except JavaException: ...
[ "Save a BioPAX model object as an OWL file.\n\n Parameters\n ----------\n model : org.biopax.paxtools.model.Model\n A BioPAX model object (java object).\n fname : str\n The name of the OWL file to save the model in.\n " ]
Please provide a description of the function:def make_model(self, *args, **kwargs): for stmt in self.statements: if isinstance(stmt, RegulateActivity): self._add_regulate_activity(stmt) elif isinstance(stmt, RegulateAmount): self._add_regulate_amo...
[ "Assemble a Cytoscape JS network from INDRA Statements.\n\n This method assembles a Cytoscape JS network from the set of INDRA\n Statements added to the assembler.\n\n Parameters\n ----------\n grouping : bool\n If True, the nodes with identical incoming and outgoing ed...
Please provide a description of the function:def get_gene_names(self): # Collect all gene names in network gene_names = [] for node in self._nodes: members = node['data'].get('members') if members: gene_names += list(members.keys()) el...
[ "Gather gene names of all nodes and node members" ]
Please provide a description of the function:def set_CCLE_context(self, cell_types): self.get_gene_names() # Get expression and mutations from context client exp_values = \ context_client.get_protein_expression(self._gene_names, cell_types) mut_values = \ ...
[ "Set context of all nodes and node members from CCLE." ]
Please provide a description of the function:def print_cyjs_graph(self): cyjs_dict = {'edges': self._edges, 'nodes': self._nodes} cyjs_str = json.dumps(cyjs_dict, indent=1, sort_keys=True) return cyjs_str
[ "Return the assembled Cytoscape JS network as a json string.\n\n Returns\n -------\n cyjs_str : str\n A json string representation of the Cytoscape JS network.\n " ]
Please provide a description of the function:def print_cyjs_context(self): context = self._context context_str = json.dumps(context, indent=1, sort_keys=True) return context_str
[ "Return a list of node names and their respective context.\n\n Returns\n -------\n cyjs_str_context : str\n A json string of the context dictionary. e.g. -\n {'CCLE' : {'bin_expression' : {'cell_line1' : {'gene1':'val1'} },\n 'bin_expression' : {'cell_line' : {'...
Please provide a description of the function:def save_json(self, fname_prefix='model'): cyjs_str = self.print_cyjs_graph() # outputs the graph with open(fname_prefix + '.json', 'wb') as fh: fh.write(cyjs_str.encode('utf-8')) # outputs the context of graph nodes ...
[ "Save the assembled Cytoscape JS network in a json file.\n\n This method saves two files based on the file name prefix given.\n It saves one json file with the graph itself, and another json\n file with the context.\n\n Parameters\n ----------\n fname_prefix : Optional[str]...
Please provide a description of the function:def save_model(self, fname='model.js'): exp_colorscale_str = json.dumps(self._exp_colorscale) mut_colorscale_str = json.dumps(self._mut_colorscale) cyjs_dict = {'edges': self._edges, 'nodes': self._nodes} model_str = json.dumps(cyjs_d...
[ "Save the assembled Cytoscape JS network in a js file.\n\n Parameters\n ----------\n file_name : Optional[str]\n The name of the file to save the Cytoscape JS network to.\n Default: model.js\n " ]
Please provide a description of the function:def _get_edge_dict(self): edge_dict = collections.defaultdict(lambda: []) if len(self._edges) > 0: for e in self._edges: data = e['data'] key = tuple([data['i'], data['source'], ...
[ "Return a dict of edges.\n\n Keyed tuples of (i, source, target, polarity)\n with lists of edge ids [id1, id2, ...]\n " ]
Please provide a description of the function:def _get_node_key(self, node_dict_item): s = tuple(sorted(node_dict_item['sources'])) t = tuple(sorted(node_dict_item['targets'])) return (s, t)
[ "Return a tuple of sorted sources and targets given a node dict." ]
Please provide a description of the function:def _get_node_groups(self): node_dict = {node['data']['id']: {'sources': [], 'targets': []} for node in self._nodes} for edge in self._edges: # Add edge as a source for its target node edge_data = (edge['d...
[ "Return a list of node id lists that are topologically identical.\n\n First construct a node_dict which is keyed to the node id and\n has a value which is a dict with keys 'sources' and 'targets'.\n The 'sources' and 'targets' each contain a list of tuples\n (i, polarity, source) edge of...
Please provide a description of the function:def _group_edges(self): # edit edges on parent nodes and make new edges for them edges_to_add = [[], []] # [group_edges, uuid_lists] for e in self._edges: new_edge = deepcopy(e) new_edge['data'].pop('id', None) ...
[ "Group all edges that are topologically identical.\n\n This means that (i, source, target, polarity) are the same, then sets\n edges on parent (i.e. - group) nodes to 'Virtual' and creates a new\n edge to represent all of them.\n " ]