Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def get_groundings(entity): def get_grounding_entries(grounding): if not grounding: return None entries = [] values = grounding.get('values', []) # Values could still have been a None entry her...
[ "Return groundings as db_refs for an entity." ]
Please provide a description of the function:def get_concept(entity): # Use the canonical name as the name of the Concept name = entity['canonicalName'] db_refs = EidosProcessor.get_groundings(entity) concept = Concept(name, db_refs=db_refs) return concept
[ "Return Concept from an Eidos entity." ]
Please provide a description of the function:def time_context_from_ref(self, timex): # If the timex has a value set, it means that it refers to a DCT or # a TimeExpression e.g. "value": {"@id": "_:DCT_1"} and the parameters # need to be taken from there value = timex.get('value'...
[ "Return a time context object given a timex reference entry." ]
Please provide a description of the function:def geo_context_from_ref(self, ref): value = ref.get('value') if value: # Here we get the RefContext from the stashed geoloc dictionary rc = self.doc.geolocs.get(value['@id']) return rc return None
[ "Return a ref context object given a location reference entry." ]
Please provide a description of the function:def time_context_from_dct(dct): time_text = dct.get('text') start = _get_time_stamp(dct.get('start')) end = _get_time_stamp(dct.get('end')) duration = dct.get('duration') tc = TimeContext(text=time_text, start=start, end=end, ...
[ "Return a time context object given a DCT entry." ]
Please provide a description of the function:def make_hash(s, n_bytes): raw_h = int(md5(s.encode('utf-8')).hexdigest()[:n_bytes], 16) # Make it a signed int. return 16**n_bytes//2 - raw_h
[ "Make the hash from a matches key." ]
Please provide a description of the function:def parse_a1(a1_text): entities = {} for line in a1_text.split('\n'): if len(line) == 0: continue tokens = line.rstrip().split('\t') if len(tokens) != 3: raise Exception('Expected three tab-seperated tokens per li...
[ "Parses an a1 file, the file TEES outputs that lists the entities in\n the extracted events.\n\n Parameters\n ----------\n a1_text : str\n Text of the TEES a1 output file, specifying the entities\n\n Returns\n -------\n entities : Dictionary mapping TEES identifiers to TEESEntity objects...
Please provide a description of the function:def parse_a2(a2_text, entities, tees_sentences): G = nx.DiGraph() event_names = set() # Put entities into the graph for entity_name in entities.keys(): offset0 = entities[entity_name].offsets[0] G.add_node(entity_name, text=entities[enti...
[ "Extracts events from a TEES a2 output into a networkx directed graph.\n\n Parameters\n ----------\n a2_text : str\n Text of the TEES a2 file output, specifying the event graph\n sentences_xml_gz : str\n Filename with the TEES sentence segmentation in a gzipped xml format\n\n Returns\n ...
Please provide a description of the function:def parse_output(a1_text, a2_text, sentence_segmentations): # Parse the sentence segmentation document tees_sentences = TEESSentences(sentence_segmentations) # Parse the a1 (entities) file entities = parse_a1(a1_text) # Parse the a2 (events) file ...
[ "Parses the output of the TEES reader and returns a networkx graph\n with the event information.\n\n Parameters\n ----------\n a1_text : str\n Contents of the TEES a1 output, specifying the entities\n a1_text : str\n Contents of the TEES a2 output, specifying the event graph\n senten...
Please provide a description of the function:def tees_parse_networkx_to_dot(G, output_file, subgraph_nodes): with codecs.open(output_file, 'w', encoding='utf-8') as f: f.write('digraph teesParse {\n') mentioned_nodes = set() for from_node in subgraph_nodes: for edge in G....
[ "Converts TEES extractions stored in a networkx graph into a graphviz\n .dot file.\n\n Parameters\n ----------\n G : networkx.DiGraph\n Graph with TEES extractions returned by run_and_parse_tees\n output_file : str\n Output file to which to write .dot file\n subgraph_nodes : list[str...
Please provide a description of the function:def _get_event(self, event, find_str): # Get the term with the given element id element = event.find(find_str) if element is None: return None element_id = element.attrib.get('id') element_term = self.tree.find("*[...
[ "Get a concept referred from the event by the given string." ]
Please provide a description of the function:def _extract_time_loc(self, term): loc = term.find('location') if loc is None: loc_context = None else: loc_id = loc.attrib.get('id') loc_term = self.tree.find("*[@id='%s']" % loc_id) text = loc...
[ "Get the location from a term (CC or TERM)" ]
Please provide a description of the function:def make_model(self, grounding_ontology='UN', grounding_threshold=None): if grounding_threshold is not None: self.grounding_threshold = grounding_threshold self.grounding_ontology = grounding_ontology # Filter to Influence State...
[ "Return a networkx MultiDiGraph representing a causal analysis graph.\n\n Parameters\n ----------\n grounding_ontology : Optional[str]\n The ontology from which the grounding should be taken\n (e.g. UN, FAO)\n grounding_threshold : Optional[float]\n Minim...
Please provide a description of the function:def export_to_cytoscapejs(self): def _create_edge_data_dict(e): # A hack to get rid of the redundant 'Provenance' label. if e[3].get('provenance'): tooltip = e[3]['provenance'][0] if toolti...
[ "Return CAG in format readable by CytoscapeJS.\n\n Return\n ------\n dict\n A JSON-like dict representing the graph for use with\n CytoscapeJS.\n ", "Return a dict from a MultiDiGraph edge for CytoscapeJS export." ]
Please provide a description of the function:def generate_jupyter_js(self, cyjs_style=None, cyjs_layout=None): # First, export the CAG to CyJS cyjs_elements = self.export_to_cytoscapejs() # Load the Javascript template tempf = os.path.join(os.path.dirname(os.path.abspath(__file_...
[ "Generate Javascript from a template to run in Jupyter notebooks.\n\n Parameters\n ----------\n cyjs_style : Optional[dict]\n A dict that sets CytoscapeJS style as specified in\n https://github.com/cytoscape/cytoscape.js/blob/master/documentation/md/style.md.\n\n cy...
Please provide a description of the function:def _node_name(self, concept): if (# grounding threshold is specified self.grounding_threshold is not None # The particular eidos ontology grounding (un/wdi/fao) is present and concept.db_refs[self.grounding_ontology] ...
[ "Return a standardized name for a node given a Concept." ]
Please provide a description of the function:def namespace_from_uri(uri): patterns = ['http://www.openbel.org/bel/[pragm]_([A-Za-z]+)_.*', 'http://www.openbel.org/bel/[a-z]+_[pr]_([A-Za-z]+)_.*', 'http://www.openbel.org/bel/[a-z]+_complex_([A-Za-z]+)_.*', 'http:/...
[ "Return the entity namespace from the URI. Examples:\n http://www.openbel.org/bel/p_HGNC_RAF1 -> HGNC\n http://www.openbel.org/bel/p_RGD_Raf1 -> RGD\n http://www.openbel.org/bel/p_PFH_MEK1/2_Family -> PFH\n " ]
Please provide a description of the function:def term_from_uri(uri): if uri is None: return None # This insures that if we get a Literal with an integer value (as we # do for modification positions), it will get converted to a string, # not an integer. if isinstance(uri, rdflib.Literal)...
[ "Removes prepended URI information from terms." ]
Please provide a description of the function:def get_modifications(self): # Get statements where the subject is an activity q_phospho1 = prefixes + # Get statements where the subject is a protein abundance q_phospho2 = prefixes + for q_phospho in (q_phospho1, q_phosph...
[ "Extract INDRA Modification Statements from BEL.\n\n Two SPARQL patterns are used for extracting Modifications from BEL:\n\n - q_phospho1 assumes that the subject is an AbundanceActivity, which\n increases/decreases a ModifiedProteinAbundance.\n\n Examples:\n\n kinaseAct...
Please provide a description of the function:def get_activating_mods(self): q_mods = prefixes + # Now make the PySB for the phosphorylation res_mods = self.g.query(q_mods) for stmt in res_mods: evidence = self._get_evidence(stmt[5]) # Parse out the ele...
[ "Extract INDRA ActiveForm Statements with a single mod from BEL.\n\n The SPARQL pattern used for extraction from BEL looks for a\n ModifiedProteinAbundance as subject and an Activiy of a\n ProteinAbundance as object.\n\n Examples:\n\n proteinAbundance(HGNC:INSR,proteinModifica...
Please provide a description of the function:def get_complexes(self): q_cmplx = prefixes + # Run the query res_cmplx = self.g.query(q_cmplx) # Store the members of each complex in a dict of lists, keyed by the # term for the complex cmplx_dict = collections.def...
[ "Extract INDRA Complex Statements from BEL.\n\n The SPARQL query used to extract Complexes looks for ComplexAbundance\n terms and their constituents. This pattern is distinct from other\n patterns in this processor in that it queries for terms, not\n full statements.\n\n Examples:...
Please provide a description of the function:def get_activating_subs(self): q_mods = prefixes + # Now make the PySB for the phosphorylation res_mods = self.g.query(q_mods) for stmt in res_mods: evidence = self._get_evidence(stmt[4]) # Parse out the ele...
[ "Extract INDRA ActiveForm Statements based on a mutation from BEL.\n\n The SPARQL pattern used to extract ActiveForms due to mutations look\n for a ProteinAbundance as a subject which has a child encoding the\n amino acid substitution. The object of the statement is an\n ActivityType of ...
Please provide a description of the function:def get_activation(self): q_stmts = prefixes + res_stmts = self.g.query(q_stmts) for stmt in res_stmts: evidence = self._get_evidence(stmt[5]) subj = self._get_agent(stmt[0], stmt[6]) subj_activity = stmt...
[ "Extract INDRA Inhibition/Activation Statements from BEL.\n\n The SPARQL query used to extract Activation Statements looks for\n patterns in which the subject is is an ActivityType\n (of a ProtainAbundance) or an Abundance (of a small molecule).\n The object has to be the ActivityType (t...
Please provide a description of the function:def get_transcription(self): q_tscript1 = prefixes + q_tscript2 = prefixes + q_tscript3 = prefixes + for q_tscript in (q_tscript1, q_tscript2, q_tscript3): res_tscript = self.g.query(q_tscript) for stmt in r...
[ "Extract Increase/DecreaseAmount INDRA Statements from BEL.\n\n Three distinct SPARQL patterns are used to extract amount\n regulations from BEL.\n\n - q_tscript1 searches for a subject which is a Transcription\n ActivityType of a ProteinAbundance and an object which is\n an R...
Please provide a description of the function:def get_conversions(self): query = prefixes + res = self.g.query(query) # We need to collect all pieces of the same statement so that we can # collect multiple reactants and products stmt_map = collections.defaultdict(list) ...
[ "Extract Conversion INDRA Statements from BEL.\n\n\n The SPARQL query used to extract Conversions searches for\n a subject (controller) which is an AbundanceActivity\n which directlyIncreases a Reaction with a given list of\n Reactants and Products.\n\n Examples:\n\n ca...
Please provide a description of the function:def get_all_direct_statements(self): logger.info("Getting all direct statements...\n") q_stmts = prefixes + res_stmts = self.g.query(q_stmts) self.all_direct_stmts = [strip_statement(stmt[0]) for stmt in res_stmts]
[ "Get all directlyIncreases/Decreases BEL statements.\n\n This method stores the results of the query in self.all_direct_stmts\n as a list of strings. The SPARQL query used to find direct BEL\n statements searches for all statements whose predicate is either\n DirectyIncreases or Directly...
Please provide a description of the function:def get_all_indirect_statements(self): q_stmts = prefixes + res_stmts = self.g.query(q_stmts) self.all_indirect_stmts = [strip_statement(stmt[0]) for stmt in res_stmts]
[ "Get all indirect increases/decreases BEL statements.\n\n This method stores the results of the query in self.all_indirect_stmts\n as a list of strings. The SPARQL query used to find indirect BEL\n statements searches for all statements whose predicate is either\n Increases or Decreases....
Please provide a description of the function:def get_degenerate_statements(self): logger.info("Checking for 'degenerate' statements...\n") # Get rules of type protein X -> activity Y q_stmts = prefixes + res_stmts = self.g.query(q_stmts) logger.info("Protein -> Protein...
[ "Get all degenerate BEL statements.\n\n Stores the results of the query in self.degenerate_stmts.\n ", "\n SELECT ?stmt\n WHERE {\n ?stmt a belvoc:Statement .\n ?stmt belvoc:hasSubject ?subj .\n ?stmt belvoc:hasObject ?obj .\n ...
Please provide a description of the function:def print_statement_coverage(self): if not self.all_direct_stmts: self.get_all_direct_statements() if not self.degenerate_stmts: self.get_degenerate_statements() if not self.all_indirect_stmts: self.get_al...
[ "Display how many of the direct statements have been converted.\n\n Also prints how many are considered 'degenerate' and not converted." ]
Please provide a description of the function:def print_statements(self): logger.info('--- Direct INDRA statements ----------') for i, stmt in enumerate(self.statements): logger.info("%s: %s" % (i, stmt)) logger.info('--- Indirect INDRA statements ----------') for i, ...
[ "Print all extracted INDRA Statements." ]
Please provide a description of the function:def process_directory_statements_sorted_by_pmid(directory_name): s_dict = defaultdict(list) mp = process_directory(directory_name, lazy=True) for statement in mp.iter_statements(): s_dict[statement.evidence[0].pmid].append(statement) return s_di...
[ "Processes a directory filled with CSXML files, first normalizing the\n character encoding to utf-8, and then processing into INDRA statements\n sorted by pmid.\n\n Parameters\n ----------\n directory_name : str\n The name of a directory filled with csxml files to process\n\n Returns\n -...
Please provide a description of the function:def process_directory(directory_name, lazy=False): # Parent Medscan processor containing extractions from all files mp = MedscanProcessor() mp.process_directory(directory_name, lazy) return mp
[ "Processes a directory filled with CSXML files, first normalizing the\n character encodings to utf-8, and then processing into a list of INDRA\n statements.\n\n Parameters\n ----------\n directory_name : str\n The name of a directory filled with csxml files to process\n lazy : bool\n ...
Please provide a description of the function:def process_file_sorted_by_pmid(file_name): s_dict = defaultdict(list) mp = process_file(file_name, lazy=True) for statement in mp.iter_statements(): s_dict[statement.evidence[0].pmid].append(statement) return s_dict
[ "Processes a file and returns a dictionary mapping pmids to a list of\n statements corresponding to that pmid.\n\n Parameters\n ----------\n file_name : str\n A csxml file to process\n\n Returns\n -------\n s_dict : dict\n Dictionary mapping pmids to a list of statements correspon...
Please provide a description of the function:def process_file(filename, interval=None, lazy=False): mp = MedscanProcessor() mp.process_csxml_file(filename, interval, lazy) return mp
[ "Process a CSXML file for its relevant information.\n\n Consider running the fix_csxml_character_encoding.py script in\n indra/sources/medscan to fix any encoding issues in the input file before\n processing.\n\n Attributes\n ----------\n filename : str\n The csxml file, containing Medscan ...
Please provide a description of the function:def stmts_from_path(path, model, stmts): path_stmts = [] for path_rule, sign in path: for rule in model.rules: if rule.name == path_rule: stmt = stmt_from_rule(path_rule, model, stmts) assert stmt is not None ...
[ "Return source Statements corresponding to a path in a model.\n\n Parameters\n ----------\n path : list[tuple[str, int]]\n A list of tuples where the first element of the tuple is the\n name of a rule, and the second is the associated polarity along\n a path.\n model : pysb.core.Mod...
Please provide a description of the function:def extract_context(annotations, annot_manager): def get_annot(annotations, key): val = annotations.pop(key, None) if val: val_list = [v for v, tf in val.items() if tf] if len(val_list) > 1: logger.war...
[ "Return a BioContext object extracted from the annotations.\n\n The entries that are extracted into the BioContext are popped from the\n annotations.\n\n Parameters\n ----------\n annotations : dict\n PyBEL annotations dict\n annot_manager : AnnotationManager\n An annotation manager ...
Please provide a description of the function:def format_axis(ax, label_padding=2, tick_padding=0, yticks_position='left'): ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position(yticks_position) ax.yaxis.set_tick_params(which='both', direction='out', labelsize=fontsize, ...
[ "Set standardized axis formatting for figure." ]
Please provide a description of the function:def tag_text(text, tag_info_list): # Check to tags for overlap and if there is any, return the subsumed # range. Return None if no overlap. def overlap(t1, t2): if range(max(t1[0], t2[0]), min(t1[1]-1, t2[1]-1)+1): if t1[1] - t1[0] >= t2[...
[ "Apply start/end tags to spans of the given text.\n\n\n Parameters\n ----------\n text : str\n Text to be tagged\n tag_info_list : list of tuples\n Each tuple refers to a span of the given text. Fields are `(start_ix,\n end_ix, substring, start_tag, close_tag)`, where substring, sta...
Please provide a description of the function:def make_model(self): stmts_formatted = [] stmt_rows = group_and_sort_statements(self.statements, self.ev_totals if self.ev_totals else None) for key, verb, stmts in stmt_rows: # This ...
[ "Return the assembled HTML content as a string.\n\n Returns\n -------\n str\n The assembled HTML as a string.\n " ]
Please provide a description of the function:def append_warning(self, msg): assert self.model is not None, "You must already have run make_model!" addendum = ('\t<span style="color:red;">(CAUTION: %s occurred when ' 'creating this page.)</span>' % msg) self.model = s...
[ "Append a warning message to the model to expose issues." ]
Please provide a description of the function:def save_model(self, fname): if self.model is None: self.make_model() with open(fname, 'wb') as fh: fh.write(self.model.encode('utf-8'))
[ "Save the assembled HTML into a file.\n\n Parameters\n ----------\n fname : str\n The path to the file to save the HTML into.\n " ]
Please provide a description of the function:def _format_evidence_text(stmt): def get_role(ag_ix): if isinstance(stmt, Complex) or \ isinstance(stmt, SelfModification) or \ isinstance(stmt, ActiveForm) or isinstance(stmt, Conversion) or\ isinstan...
[ "Returns evidence metadata with highlighted evidence text.\n\n Parameters\n ----------\n stmt : indra.Statement\n The Statement with Evidence to be formatted.\n\n Returns\n -------\n list of dicts\n List of dictionaries corresponding to each Evidence o...
Please provide a description of the function:def process_pmc(pmc_id, offline=False, output_fname=default_output_fname): xml_str = pmc_client.get_xml(pmc_id) if xml_str is None: return None fname = pmc_id + '.nxml' with open(fname, 'wb') as fh: fh.write(xml_str.encode('utf-8')) i...
[ "Return a ReachProcessor by processing a paper with a given PMC id.\n\n Uses the PMC client to obtain the full text. If it's not available,\n None is returned.\n\n Parameters\n ----------\n pmc_id : str\n The ID of a PubmedCentral article. The string may start with PMC but\n passing jus...
Please provide a description of the function:def process_pubmed_abstract(pubmed_id, offline=False, output_fname=default_output_fname, **kwargs): abs_txt = pubmed_client.get_abstract(pubmed_id) if abs_txt is None: return None rp = process_text(abs_txt, citation=pubmed...
[ "Return a ReachProcessor by processing an abstract with a given Pubmed id.\n\n Uses the Pubmed client to get the abstract. If that fails, None is\n returned.\n\n Parameters\n ----------\n pubmed_id : str\n The ID of a Pubmed article. The string may start with PMID but\n passing just the...
Please provide a description of the function:def process_text(text, citation=None, offline=False, output_fname=default_output_fname, timeout=None): if offline: if not try_offline: logger.error('Offline reading is not available.') return None try: ...
[ "Return a ReachProcessor by processing the given text.\n\n Parameters\n ----------\n text : str\n The text to be processed.\n citation : Optional[str]\n A PubMed ID passed to be used in the evidence for the extracted INDRA\n Statements. This is used when the text to be processed com...
Please provide a description of the function:def process_nxml_str(nxml_str, citation=None, offline=False, output_fname=default_output_fname): if offline: if not try_offline: logger.error('Offline reading is not available.') return None try: ...
[ "Return a ReachProcessor by processing the given NXML string.\n\n NXML is the format used by PubmedCentral for papers in the open\n access subset.\n\n Parameters\n ----------\n nxml_str : str\n The NXML string to be processed.\n citation : Optional[str]\n A PubMed ID passed to be use...
Please provide a description of the function:def process_nxml_file(file_name, citation=None, offline=False, output_fname=default_output_fname): with open(file_name, 'rb') as f: nxml_str = f.read().decode('utf-8') return process_nxml_str(nxml_str, citation, False, output_fn...
[ "Return a ReachProcessor by processing the given NXML file.\n\n NXML is the format used by PubmedCentral for papers in the open\n access subset.\n\n Parameters\n ----------\n file_name : str\n The name of the NXML file to be processed.\n citation : Optional[str]\n A PubMed ID passed ...
Please provide a description of the function:def process_json_file(file_name, citation=None): try: with open(file_name, 'rb') as fh: json_str = fh.read().decode('utf-8') return process_json_str(json_str, citation) except IOError: logger.error('Could not read file %s....
[ "Return a ReachProcessor by processing the given REACH json file.\n\n The output from the REACH parser is in this json format. This function is\n useful if the output is saved as a file and needs to be processed.\n For more information on the format, see: https://github.com/clulab/reach\n\n Parameters\n...
Please provide a description of the function:def process_json_str(json_str, citation=None): if not isinstance(json_str, basestring): raise TypeError('{} is {} instead of {}'.format(json_str, json_str.__class__, ...
[ "Return a ReachProcessor by processing the given REACH json string.\n\n The output from the REACH parser is in this json format.\n For more information on the format, see: https://github.com/clulab/reach\n\n Parameters\n ----------\n json_str : str\n The json string to be processed.\n citat...
Please provide a description of the function:def make_parser(): parser = ArgumentParser( 'wait_for_complete.py', usage='%(prog)s [-h] queue_name [options]', description=('Wait for a set of batch jobs to complete, and monitor ' 'them as they run.'), epilog=('...
[ "Generate the parser for this script." ]
Please provide a description of the function:def id_lookup(paper_id, idtype): if idtype not in ('pmid', 'pmcid', 'doi'): raise ValueError("Invalid idtype %s; must be 'pmid', 'pmcid', " "or 'doi'." % idtype) ids = {'doi': None, 'pmid': None, 'pmcid': None} pmc_id_result...
[ "Take an ID of type PMID, PMCID, or DOI and lookup the other IDs.\n\n If the DOI is not found in Pubmed, try to obtain the DOI by doing a\n reverse-lookup of the DOI in CrossRef using article metadata.\n\n Parameters\n ----------\n paper_id : str\n ID of the article.\n idtype : str\n ...
Please provide a description of the function:def get_full_text(paper_id, idtype, preferred_content_type='text/xml'): if preferred_content_type not in \ ('text/xml', 'text/plain', 'application/pdf'): raise ValueError("preferred_content_type must be one of 'text/xml', " ...
[ "Return the content and the content type of an article.\n\n This function retreives the content of an article by its PubMed ID,\n PubMed Central ID, or DOI. It prioritizes full text content when available\n and returns an abstract from PubMed as a fallback.\n\n Parameters\n ----------\n paper_id :...
Please provide a description of the function:def get_api_ruler(self): if self.api_ruler is None: try: self.api_ruler = \ autoclass('org.clulab.reach.export.apis.ApiRuler') except JavaException as e: raise ReachOfflineReadingErr...
[ "Return the existing reader if it exists or launch a new one.\n\n Returns\n -------\n api_ruler : org.clulab.reach.apis.ApiRuler\n An instance of the REACH ApiRuler class (java object).\n " ]
Please provide a description of the function:def _download_biogrid_data(url): res = requests.get(biogrid_file_url) if res.status_code != 200: raise Exception('Unable to download Biogrid data: status code %s' % res.status_code) zip_bytes = BytesIO(res.content) zip_fil...
[ "Downloads zipped, tab-separated Biogrid data in .tab2 format.\n\n Parameters:\n -----------\n url : str\n URL of the BioGrid zip file.\n\n Returns\n -------\n csv.reader\n A csv.reader object for iterating over the rows (header has already\n been skipped).\n " ]
Please provide a description of the function:def _make_agent(self, entrez_id, text_id): hgnc_name, db_refs = self._make_db_refs(entrez_id, text_id) if hgnc_name is not None: name = hgnc_name elif text_id is not None: name = text_id # Handle case where the...
[ "Make an Agent object, appropriately grounded.\n\n Parameters\n ----------\n entrez_id : str\n Entrez id number\n text_id : str\n A plain text systematic name, or None if not listed.\n\n Returns\n -------\n agent : indra.statements.Agent\n ...
Please provide a description of the function:def _make_db_refs(self, entrez_id, text_id): db_refs = {} if text_id != '-' and text_id is not None: db_refs['TEXT'] = text_id hgnc_id = hgnc_client.get_hgnc_from_entrez(entrez_id) hgnc_name = hgnc_client.get_hgnc_name(hg...
[ "Looks up the HGNC ID and name, as well as the Uniprot ID.\n\n Parameters\n ----------\n entrez_id : str\n Entrez gene ID.\n text_id : str or None\n A plain text systematic name, or None if not listed in the\n Biogrid data.\n\n Returns\n --...
Please provide a description of the function:def make_model(self, policies=None, initial_conditions=True, reverse_effects=False): self.processed_policies = self.process_policies(policies) ppa = PysbPreassembler(self.statements) ppa.replace_activities() if reve...
[ "Assemble the Kami model from the collected INDRA Statements.\n\n This method assembles a Kami model from the set of INDRA Statements.\n The assembled model is both returned and set as the assembler's\n model argument.\n\n Parameters\n ----------\n policies : Optional[Union...
Please provide a description of the function:def _assemble(self): for stmt in self.statements: if _is_whitelisted(stmt): self._dispatch(stmt, 'assemble', self.model)
[ "Calls the appropriate assemble method based on policies." ]
Please provide a description of the function:def _dispatch(self, stmt, stage, *args): class_name = stmt.__class__.__name__ policy = self.processed_policies[stmt.uuid] func_name = '%s_%s_%s' % (class_name.lower(), stage, policy) func = globals().get(func_name) if func is ...
[ "Construct and call an assembly function.\n\n This function constructs the name of the assembly function based on\n the type of statement, the corresponding policy and the stage\n of assembly. It then calls that function to perform the assembly\n task." ]
Please provide a description of the function:def add_agent(self, agent): agent_id = self.add_node(agent.name) self.add_typing(agent_id, 'agent') # Handle bound conditions for bc in agent.bound_conditions: # Here we make the assumption that the binding site ...
[ "Add an INDRA Agent and its conditions to the Nugget." ]
Please provide a description of the function:def add_node(self, name_base, attrs=None): if name_base not in self.counters: node_id = name_base else: node_id = '%s_%d' % (name_base, self.counters[name_base]) node = {'id': node_id} if attrs: nod...
[ "Add a node with a given base name to the Nugget and return ID." ]
Please provide a description of the function:def get_nugget_dict(self): nugget_dict = \ {'id': self.id, 'graph': { 'nodes': self.nodes, 'edges': self.edges }, 'attrs': { 'name': self.name, ...
[ "Return the Nugget as a dictionary." ]
Please provide a description of the function:def process_text(text, pmid=None, python2_path=None): # Try to locate python2 in one of the directories of the PATH environment # variable if it is not provided if python2_path is None: for path in os.environ["PATH"].split(os.pathsep): ...
[ "Processes the specified plain text with TEES and converts output to\n supported INDRA statements. Check for the TEES installation is the\n TEES_PATH environment variable, and configuration file; if not found,\n checks candidate paths in tees_candidate_paths. Raises an exception if\n TEES cannot be foun...
Please provide a description of the function:def run_on_text(text, python2_path): tees_path = get_config('TEES_PATH') if tees_path is None: # If TEES directory is not specifies, see if any of the candidate paths # exist and contain all of the files expected for a TEES installation. ...
[ "Runs TEES on the given text in a temporary directory and returns a\n temporary directory with TEES output.\n \n The caller should delete this directory when done with it. This function\n runs TEES and produces TEES output files but does not process TEES output\n into INDRA statements.\n\n Paramet...
Please provide a description of the function:def extract_output(output_dir): # Locate the file of sentences segmented by the TEES system, described # in a compressed xml document sentences_glob = os.path.join(output_dir, '*-preprocessed.xml.gz') sentences_filename_candidates = glob.glob(sentences_...
[ "Extract the text of the a1, a2, and sentence segmentation files from the\n TEES output directory. These files are located within a compressed archive.\n\n Parameters\n ----------\n output_dir : str\n Directory containing the output of the TEES system\n\n Returns\n -------\n a1_text : st...
Please provide a description of the function:def _list_to_seq(lst): ml = autoclass('scala.collection.mutable.MutableList')() for element in lst: ml.appendElem(element) return ml
[ "Return a scala.collection.Seq from a Python list." ]
Please provide a description of the function:def process_text(self, text, format='json'): if self.eidos_reader is None: self.initialize_reader() default_arg = lambda x: autoclass('scala.Some')(x) today = datetime.date.today().strftime("%Y-%m-%d") fname = 'default_fil...
[ "Return a mentions JSON object given text.\n\n Parameters\n ----------\n text : str\n Text to be processed.\n format : str\n The format of the output to produce, one of \"json\" or \"json_ld\".\n Default: \"json\"\n\n Returns\n -------\n ...
Please provide a description of the function:def process_text(text, out_format='json_ld', save_json='eidos_output.json', webservice=None): if not webservice: if eidos_reader is None: logger.error('Eidos reader is not available.') return None json_dict = ...
[ "Return an EidosProcessor by processing the given text.\n\n This constructs a reader object via Java and extracts mentions\n from the text. It then serializes the mentions into JSON and\n processes the result with process_json.\n\n Parameters\n ----------\n text : str\n The text to be proce...
Please provide a description of the function:def process_json_file(file_name): try: with open(file_name, 'rb') as fh: json_str = fh.read().decode('utf-8') return process_json_str(json_str) except IOError: logger.exception('Could not read file %s.' % file_name)
[ "Return an EidosProcessor by processing the given Eidos JSON-LD file.\n\n This function is useful if the output from Eidos is saved as a file and\n needs to be processed.\n\n Parameters\n ----------\n file_name : str\n The name of the JSON-LD file to be processed.\n\n Returns\n -------\n...
Please provide a description of the function:def process_json(json_dict): ep = EidosProcessor(json_dict) ep.extract_causal_relations() ep.extract_correlations() ep.extract_events() return ep
[ "Return an EidosProcessor by processing a Eidos JSON-LD dict.\n\n Parameters\n ----------\n json_dict : dict\n The JSON-LD dict to be processed.\n\n Returns\n -------\n ep : EidosProcessor\n A EidosProcessor containing the extracted INDRA Statements\n in its statements attribu...
Please provide a description of the function:def get_drug_inhibition_stmts(drug): chebi_id = drug.db_refs.get('CHEBI') mesh_id = drug.db_refs.get('MESH') if chebi_id: drug_chembl_id = chebi_client.get_chembl_id(chebi_id) elif mesh_id: drug_chembl_id = get_chembl_id(mesh_id) else...
[ "Query ChEMBL for kinetics data given drug as Agent get back statements\n\n Parameters\n ----------\n drug : Agent\n Agent representing drug with MESH or CHEBI grounding\n\n Returns\n -------\n stmts : list of INDRA statements\n INDRA statements generated by querying ChEMBL for all k...
Please provide a description of the function:def send_query(query_dict): query = query_dict['query'] params = query_dict['params'] url = 'https://www.ebi.ac.uk/chembl/api/data/' + query + '.json' r = requests.get(url, params=params) r.raise_for_status() js = r.json() return js
[ "Query ChEMBL API\n\n Parameters\n ----------\n query_dict : dict\n 'query' : string of the endpoint to query\n 'params' : dict of params for the query\n\n Returns\n -------\n js : dict\n dict parsed from json that is unique to the submitted query\n " ]
Please provide a description of the function:def query_target(target_chembl_id): query_dict = {'query': 'target', 'params': {'target_chembl_id': target_chembl_id, 'limit': 1}} res = send_query(query_dict) target = res['targets'][0] return target
[ "Query ChEMBL API target by id\n\n Parameters\n ----------\n target_chembl_id : str\n\n Returns\n -------\n target : dict\n dict parsed from json that is unique for the target\n " ]
Please provide a description of the function:def activities_by_target(activities): targ_act_dict = defaultdict(lambda: []) for activity in activities: target_chembl_id = activity['target_chembl_id'] activity_id = activity['activity_id'] targ_act_dict[target_chembl_id].append(activit...
[ "Get back lists of activities in a dict keyed by ChEMBL target id\n\n Parameters\n ----------\n activities : list\n response from a query returning activities for a drug\n\n Returns\n -------\n targ_act_dict : dict\n dictionary keyed to ChEMBL target ids with lists of activity ids\n ...
Please provide a description of the function:def get_protein_targets_only(target_chembl_ids): protein_targets = {} for target_chembl_id in target_chembl_ids: target = query_target(target_chembl_id) if 'SINGLE PROTEIN' in target['target_type']: protein_targets[target_chembl_id] =...
[ "Given list of ChEMBL target ids, return dict of SINGLE PROTEIN targets\n\n Parameters\n ----------\n target_chembl_ids : list\n list of chembl_ids as strings\n\n Returns\n -------\n protein_targets : dict\n dictionary keyed to ChEMBL target ids with lists of activity ids\n " ]
Please provide a description of the function:def get_evidence(assay): kin = get_kinetics(assay) source_id = assay.get('assay_chembl_id') if not kin: return None annotations = {'kinetics': kin} chembl_doc_id = str(assay.get('document_chembl_id')) pmid = get_pmid(chembl_doc_id) ev...
[ "Given an activity, return an INDRA Evidence object.\n\n Parameters\n ----------\n assay : dict\n an activity from the activities list returned by a query to the API\n\n Returns\n -------\n ev : :py:class:`Evidence`\n an :py:class:`Evidence` object containing the kinetics of the\n ...
Please provide a description of the function:def get_kinetics(assay): try: val = float(assay.get('standard_value')) except TypeError: logger.warning('Invalid assay value: %s' % assay.get('standard_value')) return None unit = assay.get('standard_units') if unit == 'nM': ...
[ "Given an activity, return its kinetics values.\n\n Parameters\n ----------\n assay : dict\n an activity from the activities list returned by a query to the API\n\n Returns\n -------\n kin : dict\n dictionary of values with units keyed to value types 'IC50', 'EC50',\n 'INH', '...
Please provide a description of the function:def get_pmid(doc_id): url_pmid = 'https://www.ebi.ac.uk/chembl/api/data/document.json' params = {'document_chembl_id': doc_id} res = requests.get(url_pmid, params=params) js = res.json() pmid = str(js['documents'][0]['pubmed_id']) return pmid
[ "Get PMID from document_chembl_id\n\n Parameters\n ----------\n doc_id : str\n\n Returns\n -------\n pmid : str\n " ]
Please provide a description of the function:def get_target_chemblid(target_upid): url = 'https://www.ebi.ac.uk/chembl/api/data/target.json' params = {'target_components__accession': target_upid} r = requests.get(url, params=params) r.raise_for_status() js = r.json() target_chemblid = js['t...
[ "Get ChEMBL ID from UniProt upid\n\n Parameters\n ----------\n target_upid : str\n\n Returns\n -------\n target_chembl_id : str\n " ]
Please provide a description of the function:def get_mesh_id(nlm_mesh): url_nlm2mesh = 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi' params = {'db': 'mesh', 'term': nlm_mesh, 'retmode': 'JSON'} r = requests.get(url_nlm2mesh, params=params) res = r.json() mesh_id = res['esearchresu...
[ "Get MESH ID from NLM MESH\n\n Parameters\n ----------\n nlm_mesh : str\n\n Returns\n -------\n mesh_id : str\n " ]
Please provide a description of the function:def get_pcid(mesh_id): url_mesh2pcid = 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/elink.fcgi' params = {'dbfrom': 'mesh', 'id': mesh_id, 'db': 'pccompound', 'retmode': 'JSON'} r = requests.get(url_mesh2pcid, params=params) res = r.json()...
[ "Get PC ID from MESH ID\n\n Parameters\n ----------\n mesh : str\n\n Returns\n -------\n pcid : str\n " ]
Please provide a description of the function:def get_chembl_id(nlm_mesh): mesh_id = get_mesh_id(nlm_mesh) pcid = get_pcid(mesh_id) url_mesh2pcid = 'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/' + \ 'cid/%s/synonyms/JSON' % pcid r = requests.get(url_mesh2pcid) res = r....
[ "Get ChEMBL ID from NLM MESH\n\n Parameters\n ----------\n nlm_mesh : str\n\n Returns\n -------\n chembl_id : str\n " ]
Please provide a description of the function:def get_sentences(self, root_element, block_tags): sentences = [] for element in root_element: if not self.any_ends_with(block_tags, element.tag): # tag not in block_tags if element.text is not None and not...
[ "Returns a list of plain-text sentences by iterating through\n XML tags except for those listed in block_tags." ]
Please provide a description of the function:def any_ends_with(self, string_list, pattern): try: s_base = basestring except: s_base = str is_string = isinstance(pattern, s_base) if not is_string: return False for s in string_list: ...
[ "Returns true iff one of the strings in string_list ends in\n pattern." ]
Please provide a description of the function:def get_tag_names(self): root = etree.fromstring(self.xml_full_text.encode('utf-8')) return self.get_children_tag_names(root)
[ "Returns the set of tag names present in the XML." ]
Please provide a description of the function:def get_children_tag_names(self, xml_element): tags = set() tags.add(self.remove_namespace_from_tag(xml_element.tag)) for element in xml_element.iter(tag=etree.Element): if element != xml_element: new_tags = self....
[ "Returns all tag names of xml element and its children." ]
Please provide a description of the function:def string_matches_sans_whitespace(self, str1, str2_fuzzy_whitespace): str2_fuzzy_whitespace = re.sub('\s+', '\s*', str2_fuzzy_whitespace) return re.search(str2_fuzzy_whitespace, str1) is not None
[ "Check if two strings match, modulo their whitespace." ]
Please provide a description of the function:def sentence_matches(self, sentence_text): has_upstream = False has_downstream = False has_verb = False # Get the first word of the action type and assume this is the verb # (Ex. get depends for depends on) actiontype...
[ "Returns true iff the sentence contains this mention's upstream\n and downstream participants, and if one of the stemmed verbs in\n the sentence is the same as the stemmed action type." ]
Please provide a description of the function:def get_identifiers_url(db_name, db_id): identifiers_url = 'http://identifiers.org/' bel_scai_url = 'https://arty.scai.fraunhofer.de/artifactory/bel/namespace/' if db_name == 'UP': url = identifiers_url + 'uniprot/%s' % db_id elif db_name == 'HGN...
[ "Return an identifiers.org URL for a given database name and ID.\n\n Parameters\n ----------\n db_name : str\n An internal database name: HGNC, UP, CHEBI, etc.\n db_id : str\n An identifier in the given database.\n\n Returns\n -------\n url : str\n An identifiers.org URL co...
Please provide a description of the function:def dump_statements(stmts, fname, protocol=4): logger.info('Dumping %d statements into %s...' % (len(stmts), fname)) with open(fname, 'wb') as fh: pickle.dump(stmts, fh, protocol=protocol)
[ "Dump a list of statements into a pickle file.\n\n Parameters\n ----------\n fname : str\n The name of the pickle file to dump statements into.\n protocol : Optional[int]\n The pickle protocol to use (use 2 for Python 2 compatibility).\n Default: 4\n " ]
Please provide a description of the function:def load_statements(fname, as_dict=False): logger.info('Loading %s...' % fname) with open(fname, 'rb') as fh: # Encoding argument not available in pickle for Python 2 if sys.version_info[0] < 3: stmts = pickle.load(fh) # Encod...
[ "Load statements from a pickle file.\n\n Parameters\n ----------\n fname : str\n The name of the pickle file to load statements from.\n as_dict : Optional[bool]\n If True and the pickle file contains a dictionary of statements, it\n is returned as a dictionary. If False, the stateme...
Please provide a description of the function:def map_grounding(stmts_in, **kwargs): from indra.preassembler.grounding_mapper import GroundingMapper from indra.preassembler.grounding_mapper import gm as grounding_map from indra.preassembler.grounding_mapper import \ default_agent_map as agent_ma...
[ "Map grounding using the GroundingMapper.\n\n Parameters\n ----------\n stmts_in : list[indra.statements.Statement]\n A list of statements to map.\n do_rename : Optional[bool]\n If True, Agents are renamed based on their mapped grounding.\n grounding_map : Optional[dict]\n A user...
Please provide a description of the function:def merge_groundings(stmts_in): def surface_grounding(stmt): # Find the "best" grounding for a given concept and its evidences # and surface that for idx, concept in enumerate(stmt.agent_list()): if concept is None: ...
[ "Gather and merge original grounding information from evidences.\n\n Each Statement's evidences are traversed to find original grounding\n information. These groundings are then merged into an overall consensus\n grounding dict with as much detail as possible.\n\n The current implementation is only appl...
Please provide a description of the function:def merge_deltas(stmts_in): stmts_out = [] for stmt in stmts_in: # This operation is only applicable to Influences if not isinstance(stmt, Influence): stmts_out.append(stmt) continue # At this point this is guarant...
[ "Gather and merge original Influence delta information from evidence.\n\n\n This function is only applicable to Influence Statements that have\n subj and obj deltas. All other statement types are passed through unchanged.\n Polarities and adjectives for subjects and objects respectivey are\n collected a...
Please provide a description of the function:def map_sequence(stmts_in, **kwargs): from indra.preassembler.sitemapper import SiteMapper, default_site_map logger.info('Mapping sites on %d statements...' % len(stmts_in)) kwarg_list = ['do_methionine_offset', 'do_orthology_mapping', 'do_...
[ "Map sequences using the SiteMapper.\n\n Parameters\n ----------\n stmts_in : list[indra.statements.Statement]\n A list of statements to map.\n do_methionine_offset : boolean\n Whether to check for off-by-one errors in site position (possibly)\n attributable to site numbering from m...
Please provide a description of the function:def run_preassembly(stmts_in, **kwargs): dump_pkl_unique = kwargs.get('save_unique') belief_scorer = kwargs.get('belief_scorer') use_hierarchies = kwargs['hierarchies'] if 'hierarchies' in kwargs else \ hierarchies be = BeliefEngine(scorer=belief...
[ "Run preassembly on a list of statements.\n\n Parameters\n ----------\n stmts_in : list[indra.statements.Statement]\n A list of statements to preassemble.\n return_toplevel : Optional[bool]\n If True, only the top-level statements are returned. If False,\n all statements are returne...
Please provide a description of the function:def run_preassembly_duplicate(preassembler, beliefengine, **kwargs): logger.info('Combining duplicates on %d statements...' % len(preassembler.stmts)) dump_pkl = kwargs.get('save') stmts_out = preassembler.combine_duplicates() beliefengin...
[ "Run deduplication stage of preassembly on a list of statements.\n\n Parameters\n ----------\n preassembler : indra.preassembler.Preassembler\n A Preassembler instance\n beliefengine : indra.belief.BeliefEngine\n A BeliefEngine instance.\n save : Optional[str]\n The name of a pic...
Please provide a description of the function:def run_preassembly_related(preassembler, beliefengine, **kwargs): logger.info('Combining related on %d statements...' % len(preassembler.unique_stmts)) return_toplevel = kwargs.get('return_toplevel', True) poolsize = kwargs.get('poolsize', N...
[ "Run related stage of preassembly on a list of statements.\n\n Parameters\n ----------\n preassembler : indra.preassembler.Preassembler\n A Preassembler instance which already has a set of unique statements\n internally.\n beliefengine : indra.belief.BeliefEngine\n A BeliefEngine in...
Please provide a description of the function:def filter_by_type(stmts_in, stmt_type, **kwargs): invert = kwargs.get('invert', False) logger.info('Filtering %d statements for type %s%s...' % (len(stmts_in), 'not ' if invert else '', stmt_type.__name__)) if not invert: ...
[ "Filter to a given statement type.\n\n Parameters\n ----------\n stmts_in : list[indra.statements.Statement]\n A list of statements to filter.\n stmt_type : indra.statements.Statement\n The class of the statement type to filter for.\n Example: indra.statements.Modification\n inve...
Please provide a description of the function:def _remove_bound_conditions(agent, keep_criterion): new_bc = [] for ind in range(len(agent.bound_conditions)): if keep_criterion(agent.bound_conditions[ind].agent): new_bc.append(agent.bound_conditions[ind]) agent.bound_conditions = new_...
[ "Removes bound conditions of agent such that keep_criterion is False.\n\n Parameters\n ----------\n agent: Agent\n The agent whose bound conditions we evaluate\n keep_criterion: function\n Evaluates removal_criterion(a) for each agent a in a bound condition\n and if it evaluates to ...