Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def make_stmt(stmt_cls, tf_agent, target_agent, pmid): ev = Evidence(source_api='trrust', pmid=pmid) return stmt_cls(deepcopy(tf_agent), deepcopy(target_agent), evidence=[ev])
[ "Return a Statement based on its type, agents, and PMID." ]
Please provide a description of the function:def get_grounded_agent(gene_name): db_refs = {'TEXT': gene_name} if gene_name in hgnc_map: gene_name = hgnc_map[gene_name] hgnc_id = hgnc_client.get_hgnc_id(gene_name) if hgnc_id: db_refs['HGNC'] = hgnc_id up_id = hgnc_client.get_...
[ "Return a grounded Agent based on an HGNC symbol." ]
Please provide a description of the function:def extract_statements(self): for _, (tf, target, effect, refs) in self.df.iterrows(): tf_agent = get_grounded_agent(tf) target_agent = get_grounded_agent(target) if effect == 'Activation': stmt_cls = Incre...
[ "Process the table to extract Statements." ]
Please provide a description of the function:def process_paper(model_name, pmid): json_directory = os.path.join(model_name, 'jsons') json_path = os.path.join(json_directory, 'PMID%s.json' % pmid) if pmid.startswith('api') or pmid.startswith('PMID'): logger.warning('Invalid PMID: %s' % pmid) ...
[ "Process a paper with the given pubmed identifier\n\n Parameters\n ----------\n model_name : str\n The directory for the INDRA machine\n pmid : str\n The PMID to process.\n\n Returns\n -------\n rp : ReachProcessor\n A ReachProcessor containing the extracted INDRA Statement...
Please provide a description of the function:def process_paper_helper(model_name, pmid, start_time_local): try: if not aws_available: rp, txt_format = process_paper(model_name, pmid) else: rp, txt_format = process_paper_aws(pmid, start_time_local) except: log...
[ "Wraps processing a paper by either a local or remote service\n and caches any uncaught exceptions" ]
Please provide a description of the function:def run_with_search_helper(model_path, config, num_days=None): logger.info('-------------------------') logger.info(time.strftime('%c')) if not os.path.isdir(model_path): logger.error('%s is not a directory', model_path) sys.exit() default_c...
[]
Please provide a description of the function:def _load_data(): # Get the cwv reader object. csv_path = path.join(HERE, path.pardir, path.pardir, 'resources', DATAFILE_NAME) data_iter = list(read_unicode_csv(csv_path)) # Get the headers. headers = data_iter[0] # Fo...
[ "Load the data from the csv in data.\n\n The \"gene_id\" is the Entrez gene id, and the \"approved_symbol\" is the\n standard gene symbol. The \"hms_id\" is the LINCS ID for the drug.\n\n Returns\n -------\n data : list[dict]\n A list of dicts of row values keyed by the column headers extracte...
Please provide a description of the function:def run_eidos(endpoint, *args): # Make the full path to the class that should be used call_class = '%s.%s' % (eidos_package, endpoint) # Assemble the command line command and append optonal args cmd = ['java', '-Xmx12G', '-cp', eip, call_class] + list(ar...
[ "Run a given enpoint of Eidos through the command line.\n\n Parameters\n ----------\n endpoint : str\n The class within the Eidos package to run, for instance\n 'apps.ExtractFromDirectory' will run\n 'org.clulab.wm.eidos.apps.ExtractFromDirectory'\n *args\n Any further argume...
Please provide a description of the function:def extract_from_directory(path_in, path_out): path_in = os.path.realpath(os.path.expanduser(path_in)) path_out = os.path.realpath(os.path.expanduser(path_out)) logger.info('Running Eidos on input folder %s' % path_in) run_eidos('apps.ExtractFromDirector...
[ "Run Eidos on a set of text files in a folder.\n\n The output is produced in the specified output folder but\n the output files aren't processed by this function.\n\n Parameters\n ----------\n path_in : str\n Path to an input folder with some text files\n path_out : str\n Path to an ...
Please provide a description of the function:def extract_and_process(path_in, path_out): path_in = os.path.realpath(os.path.expanduser(path_in)) path_out = os.path.realpath(os.path.expanduser(path_out)) extract_from_directory(path_in, path_out) jsons = glob.glob(os.path.join(path_out, '*.jsonld')) ...
[ "Run Eidos on a set of text files and process output with INDRA.\n\n The output is produced in the specified output folder but\n the output files aren't processed by this function.\n\n Parameters\n ----------\n path_in : str\n Path to an input folder with some text files\n path_out : str\n ...
Please provide a description of the function:def get_statements(subject=None, object=None, agents=None, stmt_type=None, use_exact_type=False, persist=True, timeout=None, simple_response=False, ev_limit=10, best_first=True, tries=2, max_stmts=None): proce...
[ "Get a processor for the INDRA DB web API matching given agents and type.\n\n There are two types of responses available. You can just get a list of\n INDRA Statements, or you can get an IndraDBRestProcessor object, which allow\n Statements to be loaded in a background thread, providing a sample of the\n ...
Please provide a description of the function:def get_statements_by_hash(hash_list, ev_limit=100, best_first=True, tries=2): if not isinstance(hash_list, list): raise ValueError("The `hash_list` input is a list, not %s." % type(hash_list)) if not hash_list: return []...
[ "Get fully formed statements from a list of hashes.\n\n Parameters\n ----------\n hash_list : list[int or str]\n A list of statement hashes.\n ev_limit : int or None\n Limit the amount of evidence returned per Statement. Default is 100.\n best_first : bool\n If True, the preassem...
Please provide a description of the function:def get_statements_for_paper(ids, ev_limit=10, best_first=True, tries=2, max_stmts=None): id_l = [{'id': id_val, 'type': id_type} for id_type, id_val in ids] resp = submit_statement_request('post', 'from_papers', data={'ids': id_l}, ...
[ "Get the set of raw Statements extracted from a paper given by the id.\n\n Parameters\n ----------\n ids : list[(<id type>, <id value>)]\n A list of tuples with ids and their type. The type can be any one of\n 'pmid', 'pmcid', 'doi', 'pii', 'manuscript id', or 'trid', which is the\n pr...
Please provide a description of the function:def submit_curation(hash_val, tag, curator, text=None, source='indra_rest_client', ev_hash=None, is_test=False): data = {'tag': tag, 'text': text, 'curator': curator, 'source': source, 'ev_hash': ev_hash} url = 'curation/submit/%s...
[ "Submit a curation for the given statement at the relevant level.\n\n Parameters\n ----------\n hash_val : int\n The hash corresponding to the statement.\n tag : str\n A very short phrase categorizing the error or type of curation,\n e.g. \"grounding\" for a grounding error, or \"co...
Please provide a description of the function:def get_statement_queries(stmts, **params): def pick_ns(ag): for ns in ['HGNC', 'FPLX', 'CHEMBL', 'CHEBI', 'GO', 'MESH']: if ns in ag.db_refs.keys(): dbid = ag.db_refs[ns] break else: ns = 'TEX...
[ "Get queries used to search based on a statement.\n\n In addition to the stmts, you can enter any parameters standard to the\n query. See https://github.com/indralab/indra_db/rest_api for a full list.\n\n Parameters\n ----------\n stmts : list[Statement]\n A list of INDRA statements.\n " ]
Please provide a description of the function:def save(self, model_fname='model.pkl'): with open(model_fname, 'wb') as fh: pickle.dump(self.stmts, fh, protocol=4)
[ "Save the state of the IncrementalModel in a pickle file.\n\n Parameters\n ----------\n model_fname : Optional[str]\n The name of the pickle file to save the state of the\n IncrementalModel in. Default: model.pkl\n " ]
Please provide a description of the function:def add_statements(self, pmid, stmts): if pmid not in self.stmts: self.stmts[pmid] = stmts else: self.stmts[pmid] += stmts
[ "Add INDRA Statements to the incremental model indexed by PMID.\n\n Parameters\n ----------\n pmid : str\n The PMID of the paper from which statements were extracted.\n stmts : list[indra.statements.Statement]\n A list of INDRA Statements to be added to the model.\n...
Please provide a description of the function:def preassemble(self, filters=None, grounding_map=None): stmts = self.get_statements() # Filter out hypotheses stmts = ac.filter_no_hypothesis(stmts) # Fix grounding if grounding_map is not None: stmts = ac.map_g...
[ "Preassemble the Statements collected in the model.\n\n Use INDRA's GroundingMapper, Preassembler and BeliefEngine\n on the IncrementalModel and save the unique statements and\n the top level statements in class attributes.\n\n Currently the following filter options are implemented:\n ...
Please provide a description of the function:def get_model_agents(self): model_stmts = self.get_statements() agents = [] for stmt in model_stmts: for a in stmt.agent_list(): if a is not None: agents.append(a) return agents
[ "Return a list of all Agents from all Statements.\n\n Returns\n -------\n agents : list[indra.statements.Agent]\n A list of Agents that are in the model.\n " ]
Please provide a description of the function:def get_statements(self): stmt_lists = [v for k, v in self.stmts.items()] stmts = [] for s in stmt_lists: stmts += s return stmts
[ "Return a list of all Statements in a single list.\n\n Returns\n -------\n stmts : list[indra.statements.Statement]\n A list of all the INDRA Statements in the model.\n " ]
Please provide a description of the function:def get_statements_noprior(self): stmt_lists = [v for k, v in self.stmts.items() if k != 'prior'] stmts = [] for s in stmt_lists: stmts += s return stmts
[ "Return a list of all non-prior Statements in a single list.\n\n Returns\n -------\n stmts : list[indra.statements.Statement]\n A list of all the INDRA Statements in the model (excluding\n the prior).\n " ]
Please provide a description of the function:def process_ndex_neighborhood(gene_names, network_id=None, rdf_out='bel_output.rdf', print_output=True): logger.warning('This method is deprecated and the results are not ' 'guaranteed to be correct. Please use ' ...
[ "Return a BelRdfProcessor for an NDEx network neighborhood.\n\n Parameters\n ----------\n gene_names : list\n A list of HGNC gene symbols to search the neighborhood of.\n Example: ['BRAF', 'MAP2K1']\n network_id : Optional[str]\n The UUID of the network in NDEx. By default, the BEL ...
Please provide a description of the function:def process_pybel_neighborhood(gene_names, network_file=None, network_type='belscript', **kwargs): if network_file is None: # Use large corpus as base network network_file = os.path.join(os.path.dirname(os.path.abspath(...
[ "Return PybelProcessor around neighborhood of given genes in a network.\n\n This function processes the given network file and filters the returned\n Statements to ones that contain genes in the given list.\n\n Parameters\n ----------\n network_file : Optional[str]\n Path to the network file t...
Please provide a description of the function:def process_belrdf(rdf_str, print_output=True): g = rdflib.Graph() try: g.parse(data=rdf_str, format='nt') except ParseError as e: logger.error('Could not parse rdf: %s' % e) return None # Build INDRA statements from RDF bp = ...
[ "Return a BelRdfProcessor for a BEL/RDF string.\n\n Parameters\n ----------\n rdf_str : str\n A BEL/RDF string to be processed. This will usually come from reading\n a .rdf file.\n\n Returns\n -------\n bp : BelRdfProcessor\n A BelRdfProcessor object which contains INDRA State...
Please provide a description of the function:def process_pybel_graph(graph): bp = PybelProcessor(graph) bp.get_statements() if bp.annot_manager.failures: logger.warning('missing %d annotation pairs', sum(len(v) for v in bp.annot_manager.failures...
[ "Return a PybelProcessor by processing a PyBEL graph.\n\n Parameters\n ----------\n graph : pybel.struct.BELGraph\n A PyBEL graph to process\n\n Returns\n -------\n bp : PybelProcessor\n A PybelProcessor object which contains INDRA Statements in\n bp.statements.\n " ]
Please provide a description of the function:def process_belscript(file_name, **kwargs): if 'citation_clearing' not in kwargs: kwargs['citation_clearing'] = False if 'no_identifier_validation' not in kwargs: kwargs['no_identifier_validation'] = True pybel_graph = pybel.from_path(file_na...
[ "Return a PybelProcessor by processing a BEL script file.\n\n Key word arguments are passed directly to pybel.from_path,\n for further information, see\n pybel.readthedocs.io/en/latest/io.html#pybel.from_path\n Some keyword arguments we use here differ from the defaults\n of PyBEL, namely we set `cit...
Please provide a description of the function:def process_json_file(file_name): with open(file_name, 'rt') as fh: pybel_graph = pybel.from_json_file(fh, False) return process_pybel_graph(pybel_graph)
[ "Return a PybelProcessor by processing a Node-Link JSON file.\n\n For more information on this format, see:\n http://pybel.readthedocs.io/en/latest/io.html#node-link-json\n\n Parameters\n ----------\n file_name : str\n The path to a Node-Link JSON file.\n\n Returns\n -------\n bp : Py...
Please provide a description of the function:def process_cbn_jgif_file(file_name): with open(file_name, 'r') as jgf: return process_pybel_graph(pybel.from_cbn_jgif(json.load(jgf)))
[ "Return a PybelProcessor by processing a CBN JGIF JSON file.\n\n Parameters\n ----------\n file_name : str\n The path to a CBN JGIF JSON file.\n\n Returns\n -------\n bp : PybelProcessor\n A PybelProcessor object which contains INDRA Statements in\n bp.statements.\n " ]
Please provide a description of the function:def update_famplex(): famplex_url_pattern = \ 'https://raw.githubusercontent.com/sorgerlab/famplex/master/%s.csv' csv_names = ['entities', 'equivalences', 'gene_prefixes', 'grounding_map', 'relations'] for csv_name in csv_names: ...
[ "Update all the CSV files that form the FamPlex resource." ]
Please provide a description of the function:def update_lincs_small_molecules(): url = 'http://lincs.hms.harvard.edu/db/sm/' sm_data = load_lincs_csv(url) sm_dict = {d['HMS LINCS ID']: d.copy() for d in sm_data} assert len(sm_dict) == len(sm_data), "We lost data." fname = os.path.join(path, 'li...
[ "Load the csv of LINCS small molecule metadata into a dict.\n\n Produces a dict keyed by HMS LINCS small molecule ids, with the metadata\n contained in a dict of row values keyed by the column headers extracted\n from the csv.\n " ]
Please provide a description of the function:def update_lincs_proteins(): url = 'http://lincs.hms.harvard.edu/db/proteins/' prot_data = load_lincs_csv(url) prot_dict = {d['HMS LINCS ID']: d.copy() for d in prot_data} assert len(prot_dict) == len(prot_data), "We lost data." fname = os.path.join(...
[ "Load the csv of LINCS protein metadata into a dict.\n\n Produces a dict keyed by HMS LINCS protein ids, with the metadata\n contained in a dict of row values keyed by the column headers extracted\n from the csv.\n " ]
Please provide a description of the function:def _get_is_direct(stmt): '''Returns true if there is evidence that the statement is a direct interaction. If any of the evidences associated with the statement indicates a direct interatcion then we assume the interaction is direct. If there is no evidence f...
[]
Please provide a description of the function:def make_model(self): for stmt in self.statements: if isinstance(stmt, Modification): card = assemble_modification(stmt) elif isinstance(stmt, SelfModification): card = assemble_selfmodification(stmt) ...
[ "Assemble statements into index cards." ]
Please provide a description of the function:def print_model(self): cards = [c.card for c in self.cards] # If there is only one card, print it as a single # card not as a list if len(cards) == 1: cards = cards[0] cards_json = json.dumps(cards, indent=1) ...
[ "Return the assembled cards as a JSON string.\n\n Returns\n -------\n cards_json : str\n The JSON string representing the assembled cards.\n " ]
Please provide a description of the function:def geneways_action_to_indra_statement_type(actiontype, plo): actiontype = actiontype.lower() statement_generator = None is_direct = (plo == 'P') if actiontype == 'bind': statement_generator = lambda substance1, substance2, evidence: \ ...
[ "Return INDRA Statement corresponding to Geneways action type.\n\n Parameters\n ----------\n actiontype : str\n The verb extracted by the Geneways processor\n plo : str\n A one character string designating whether Geneways classifies\n this verb as a physical, logical, or other inte...
Please provide a description of the function:def make_statement(self, action, mention): (statement_generator, is_direct) = \ geneways_action_to_indra_statement_type(mention.actiontype, action.plo) if statement_generator is None: ...
[ "Makes an INDRA statement from a Geneways action and action mention.\n\n Parameters\n ----------\n action : GenewaysAction\n The mechanism that the Geneways mention maps to. Note that\n several text mentions can correspond to the same action if they are\n referr...
Please provide a description of the function:def load_from_rdf_file(self, rdf_file): self.graph = rdflib.Graph() self.graph.parse(os.path.abspath(rdf_file), format='nt') self.initialize()
[ "Initialize given an RDF input file representing the hierarchy.\"\n\n Parameters\n ----------\n rdf_file : str\n Path to an RDF file.\n " ]
Please provide a description of the function:def load_from_rdf_string(self, rdf_str): self.graph = rdflib.Graph() self.graph.parse(data=rdf_str, format='nt') self.initialize()
[ "Initialize given an RDF string representing the hierarchy.\"\n\n Parameters\n ----------\n rdf_str : str\n An RDF string.\n " ]
Please provide a description of the function:def extend_with(self, rdf_file): self.graph.parse(os.path.abspath(rdf_file), format='nt') self.initialize()
[ "Extend the RDF graph of this HierarchyManager with another RDF file.\n\n Parameters\n ----------\n rdf_file : str\n An RDF file which is parsed such that the current graph and the\n graph described by the file are merged.\n " ]
Please provide a description of the function:def build_transitive_closures(self): self.component_counter = 0 for rel, tc_dict in ((self.isa_objects, self.isa_closure), (self.partof_objects, self.partof_closure), (self.isa_or_partof_objec...
[ "Build the transitive closures of the hierarchy.\n\n This method constructs dictionaries which contain terms in the\n hierarchy as keys and either all the \"isa+\" or \"partof+\" related terms\n as values.\n " ]
Please provide a description of the function:def build_transitive_closure(self, rel, tc_dict): # Make a function with the righ argument structure rel_fun = lambda node, graph: rel(node) for x in self.graph.all_nodes(): rel_closure = self.graph.transitiveClosure(rel_fun, x) ...
[ "Build a transitive closure for a given relation in a given dict." ]
Please provide a description of the function:def find_entity(self, x): qstr = self.prefixes + .format(x) res = self.graph.query(qstr) if list(res): en = list(res)[0][0].toPython() return en else: return None
[ "\n Get the entity that has the specified name (or synonym).\n\n Parameters\n ----------\n x : string\n Name or synonym for the target entity.\n ", "\n SELECT ?x WHERE {{\n ?x rn:hasName \"{0}\" .\n }}\n " ]
Please provide a description of the function:def directly_or_indirectly_related(self, ns1, id1, ns2, id2, closure_dict, relation_func): # if id2 is None, or both are None, then it's by definition isa: if id2 is None or (id2 is None and id1 is None): ...
[ "Return True if two entities have the speicified relationship.\n\n This relation is constructed possibly through multiple links connecting\n the two entities directly or indirectly.\n\n Parameters\n ----------\n ns1 : str\n Namespace code for an entity.\n id1 : s...
Please provide a description of the function:def isa(self, ns1, id1, ns2, id2): rel_fun = lambda node, graph: self.isa_objects(node) return self.directly_or_indirectly_related(ns1, id1, ns2, id2, self.isa_closure, ...
[ "Return True if one entity has an \"isa\" relationship to another.\n\n Parameters\n ----------\n ns1 : str\n Namespace code for an entity.\n id1 : string\n URI for an entity.\n ns2 : str\n Namespace code for an entity.\n id2 : str\n ...
Please provide a description of the function:def partof(self, ns1, id1, ns2, id2): rel_fun = lambda node, graph: self.partof_objects(node) return self.directly_or_indirectly_related(ns1, id1, ns2, id2, self.partof_closure, ...
[ "Return True if one entity is \"partof\" another.\n\n Parameters\n ----------\n ns1 : str\n Namespace code for an entity.\n id1 : str\n URI for an entity.\n ns2 : str\n Namespace code for an entity.\n id2 : str\n URI for an entity...
Please provide a description of the function:def isa_or_partof(self, ns1, id1, ns2, id2): rel_fun = lambda node, graph: self.isa_or_partof_objects(node) return self.directly_or_indirectly_related(ns1, id1, ns2, id2, self.isa_or_partof_closure, ...
[ "Return True if two entities are in an \"isa\" or \"partof\" relationship\n\n Parameters\n ----------\n ns1 : str\n Namespace code for an entity.\n id1 : str\n URI for an entity.\n ns2 : str\n Namespace code for an entity.\n id2 : str\n ...
Please provide a description of the function:def is_opposite(self, ns1, id1, ns2, id2): u1 = self.get_uri(ns1, id1) u2 = self.get_uri(ns2, id2) t1 = rdflib.term.URIRef(u1) t2 = rdflib.term.URIRef(u2) rel = rdflib.term.URIRef(self.relations_prefix + 'is_opposite') ...
[ "Return True if two entities are in an \"is_opposite\" relationship\n\n Parameters\n ----------\n ns1 : str\n Namespace code for an entity.\n id1 : str\n URI for an entity.\n ns2 : str\n Namespace code for an entity.\n id2 : str\n ...
Please provide a description of the function:def get_parents(self, uri, type='all'): # First do a quick dict lookup to see if there are any parents all_parents = set(self.isa_or_partof_closure.get(uri, [])) # If there are no parents or we are looking for all, we can return here ...
[ "Return parents of a given entry.\n\n Parameters\n ----------\n uri : str\n The URI of the entry whose parents are to be returned. See the\n get_uri method to construct this URI from a name space and id.\n type : str\n 'all': return all parents irrespecti...
Please provide a description of the function:def _get_perf(text, msg_id): msg = KQMLPerformative('REQUEST') msg.set('receiver', 'READER') content = KQMLList('run-text') content.sets('text', text) msg.set('content', content) msg.set('reply-with', msg_id) return msg
[ "Return a request message for a given text." ]
Please provide a description of the function:def read_pmc(self, pmcid): msg = KQMLPerformative('REQUEST') msg.set('receiver', 'READER') content = KQMLList('run-pmcid') content.sets('pmcid', pmcid) content.set('reply-when-done', 'true') msg.set('content', content)...
[ "Read a given PMC article.\n\n Parameters\n ----------\n pmcid : str\n The PMC ID of the article to read. Note that only\n articles in the open-access subset of PMC will work.\n " ]
Please provide a description of the function:def read_text(self, text): logger.info('Reading: "%s"' % text) msg_id = 'RT000%s' % self.msg_counter kqml_perf = _get_perf(text, msg_id) self.reply_counter += 1 self.msg_counter += 1 self.send(kqml_perf)
[ "Read a given text phrase.\n\n Parameters\n ----------\n text : str\n The text to read. Typically a sentence or a paragraph.\n " ]
Please provide a description of the function:def receive_reply(self, msg, content): reply_head = content.head() if reply_head == 'error': comment = content.gets('comment') logger.error('Got error reply: "%s"' % comment) else: extractions = content.get...
[ "Handle replies with reading results." ]
Please provide a description of the function:def split_long_sentence(sentence, words_per_line): words = sentence.split(' ') split_sentence = '' for i in range(len(words)): split_sentence = split_sentence + words[i] if (i+1) % words_per_line == 0: split_sentence = split_sente...
[ "Takes a sentence and adds a newline every \"words_per_line\" words.\n\n Parameters\n ----------\n sentence: str\n Sentene to split\n words_per_line: double\n Add a newline every this many words\n " ]
Please provide a description of the function:def shorter_name(key): key_short = key for sep in ['#', '/']: ind = key_short.rfind(sep) if ind is not None: key_short = key_short[ind+1:] else: key_short = key_short return key_short.replace('-', '_').replace(...
[ "Return a shorter name for an id.\n\n Does this by only taking the last part of the URI,\n after the last / and the last #. Also replaces - and . with _.\n\n Parameters\n ----------\n key: str\n Some URI\n\n Returns\n -------\n key_short: str\n A shortened, but more ambiguous, ...
Please provide a description of the function:def add_event_property_edges(event_entity, entries): do_not_log = ['@type', '@id', 'http://worldmodelers.com/DataProvenance#sourced_from'] for prop in event_entity: if prop not in do_not_log: value = event_entity[prop] ...
[ "Adds edges to the graph for event properties." ]
Please provide a description of the function:def get_sourced_from(entry): sourced_from = 'http://worldmodelers.com/DataProvenance#sourced_from' if sourced_from in entry: values = entry[sourced_from] values = [i['@id'] for i in values] return values
[ "Get a list of values from the source_from attribute" ]
Please provide a description of the function:def get_entry_compact_text_repr(entry, entries): text = get_shortest_text_value(entry) if text is not None: return text else: sources = get_sourced_from(entry) # There are a lot of references to this entity, each of which refer ...
[ "If the entry has a text value, return that.\n If the entry has a source_from value, return the text value of the source.\n Otherwise, return None." ]
Please provide a description of the function:def get_entity_type(entry): entry_type = entry['@type'] entry_type = [shorter_name(t) for t in entry_type] entry_type = repr(entry_type) return entry_type
[ "Given a JSON-LD entry, returns the abbreviated @type and the\n text attribute that has the shortest length.\n\n Parameters\n ----------\n entry: dict\n A JSON-LD entry parsed into a nested python dictionary via the json\n module\n\n Returns\n -------\n short_type: str\n Th...
Please provide a description of the function:def process_text(text, output_fmt='json', outbuf=None, cleanup=True, key='', **kwargs): nxml_str = make_nxml_from_text(text) return process_nxml_str(nxml_str, output_fmt, outbuf, cleanup, key, **kwargs)
[ "Return processor with Statements extracted by reading text with Sparser.\n\n Parameters\n ----------\n text : str\n The text to be processed\n output_fmt: Optional[str]\n The output format to obtain from Sparser, with the two options being\n 'json' and 'xml'. Default: 'json'\n o...
Please provide a description of the function:def process_nxml_str(nxml_str, output_fmt='json', outbuf=None, cleanup=True, key='', **kwargs): tmp_fname = 'PMC%s_%d.nxml' % (key, mp.current_process().pid) with open(tmp_fname, 'wb') as fh: fh.write(nxml_str.encode('utf-8')) tr...
[ "Return processor with Statements extracted by reading an NXML string.\n\n Parameters\n ----------\n nxml_str : str\n The string value of the NXML-formatted paper to be read.\n output_fmt: Optional[str]\n The output format to obtain from Sparser, with the two options being\n 'json' ...
Please provide a description of the function:def process_nxml_file(fname, output_fmt='json', outbuf=None, cleanup=True, **kwargs): sp = None out_fname = None try: out_fname = run_sparser(fname, output_fmt, outbuf, **kwargs) sp = process_sparser_output(out_fname, ou...
[ "Return processor with Statements extracted by reading an NXML file.\n\n Parameters\n ----------\n fname : str\n The path to the NXML file to be read.\n output_fmt: Optional[str]\n The output format to obtain from Sparser, with the two options being\n 'json' and 'xml'. Default: 'jso...
Please provide a description of the function:def process_sparser_output(output_fname, output_fmt='json'): if output_fmt not in ['json', 'xml']: logger.error("Unrecognized output format '%s'." % output_fmt) return None sp = None with open(output_fname, 'rt') as fh: if output_fmt...
[ "Return a processor with Statements extracted from Sparser XML or JSON\n\n Parameters\n ----------\n output_fname : str\n The path to the Sparser output file to be processed. The file can\n either be JSON or XML output from Sparser, with the output_fmt\n parameter defining what format ...
Please provide a description of the function:def process_xml(xml_str): try: tree = ET.XML(xml_str, parser=UTB()) except ET.ParseError as e: logger.error('Could not parse XML string') logger.error(e) return None sp = _process_elementtree(tree) return sp
[ "Return processor with Statements extracted from a Sparser XML.\n\n Parameters\n ----------\n xml_str : str\n The XML string obtained by reading content with Sparser, using the\n 'xml' output mode.\n\n Returns\n -------\n sp : SparserXMLProcessor\n A SparserXMLProcessor which ...
Please provide a description of the function:def run_sparser(fname, output_fmt, outbuf=None, timeout=600): if not sparser_path or not os.path.exists(sparser_path): logger.error('Sparser executable not set in %s' % sparser_path_var) return None if output_fmt == 'xml': format_flag = '...
[ "Return the path to reading output after running Sparser reading.\n\n Parameters\n ----------\n fname : str\n The path to an input file to be processed. Due to the Spaser\n executable's assumptions, the file name needs to start with PMC\n and should be an NXML formatted file.\n outp...
Please provide a description of the function:def get_version(): assert sparser_path is not None, "Sparser path is not defined." with open(os.path.join(sparser_path, 'version.txt'), 'r') as f: version = f.read().strip() return version
[ "Return the version of the Sparser executable on the path.\n\n Returns\n -------\n version : str\n The version of Sparser that is found on the Sparser path.\n " ]
Please provide a description of the function:def make_nxml_from_text(text): text = _escape_xml(text) header = '<?xml version="1.0" encoding="UTF-8" ?>' + \ '<OAI-PMH><article><body><sec id="s1"><p>' footer = '</p></sec></body></article></OAI-PMH>' nxml_str = header + text + footer retur...
[ "Return raw text wrapped in NXML structure.\n\n Parameters\n ----------\n text : str\n The raw text content to be wrapped in an NXML structure.\n\n Returns\n -------\n nxml_str : str\n The NXML string wrapping the raw text input.\n " ]
Please provide a description of the function:def get_hgnc_name(hgnc_id): try: hgnc_name = hgnc_names[hgnc_id] except KeyError: xml_tree = get_hgnc_entry(hgnc_id) if xml_tree is None: return None hgnc_name_tag =\ xml_tree.find("result/doc/str[@name='sy...
[ "Return the HGNC symbol corresponding to the given HGNC ID.\n\n Parameters\n ----------\n hgnc_id : str\n The HGNC ID to be converted.\n\n Returns\n -------\n hgnc_name : str\n The HGNC symbol corresponding to the given HGNC ID.\n " ]
Please provide a description of the function:def get_current_hgnc_id(hgnc_name): hgnc_id = get_hgnc_id(hgnc_name) if hgnc_id: return hgnc_id hgnc_id = prev_sym_map.get(hgnc_name) return hgnc_id
[ "Return the HGNC ID(s) corresponding to a current or outdate HGNC symbol.\n\n Parameters\n ----------\n hgnc_name : str\n The HGNC symbol to be converted, possibly an outdated symbol.\n\n Returns\n -------\n str or list of str or None\n If there is a single HGNC ID corresponding to t...
Please provide a description of the function:def get_hgnc_entry(hgnc_id): url = hgnc_url + 'hgnc_id/%s' % hgnc_id headers = {'Accept': '*/*'} res = requests.get(url, headers=headers) if not res.status_code == 200: return None xml_tree = ET.XML(res.content, parser=UTB()) return xml_t...
[ "Return the HGNC entry for the given HGNC ID from the web service.\n\n Parameters\n ----------\n hgnc_id : str\n The HGNC ID to be converted.\n\n Returns\n -------\n xml_tree : ElementTree\n The XML ElementTree corresponding to the entry for the\n given HGNC ID.\n " ]
Please provide a description of the function:def analyze_reach_log(log_fname=None, log_str=None): assert bool(log_fname) ^ bool(log_str), 'Must specify log_fname OR log_str' started_patt = re.compile('Starting ([\d]+)') # TODO: it might be interesting to get the time it took to read # each paper he...
[ "Return unifinished PMIDs given a log file name." ]
Please provide a description of the function:def get_logs_from_db_reading(job_prefix, reading_queue='run_db_reading_queue'): s3 = boto3.client('s3') gen_prefix = 'reading_results/%s/logs/%s' % (job_prefix, reading_queue) job_log_data = s3.list_objects_v2(Bucket='bigmech', ...
[ "Get the logs stashed on s3 for a particular reading." ]
Please provide a description of the function:def separate_reach_logs(log_str): log_lines = log_str.splitlines() reach_logs = [] reach_lines = [] adding_reach_lines = False for l in log_lines[:]: if not adding_reach_lines and 'Beginning reach' in l: adding_reach_lines = True ...
[ "Get the list of reach logs from the overall logs." ]
Please provide a description of the function:def get_unyielding_tcids(log_str): tcid_strs = re.findall('INFO: \[.*?\].*? - Got no statements for (\d+).*', log_str) return {int(tcid_str) for tcid_str in tcid_strs}
[ "Extract the set of tcids for which no statements were created." ]
Please provide a description of the function:def analyze_db_reading(job_prefix, reading_queue='run_db_reading_queue'): # Analyze reach failures log_strs = get_logs_from_db_reading(job_prefix, reading_queue) indra_log_strs = [] all_reach_logs = [] log_stats = [] for log_str in log_strs: ...
[ "Run various analysis on a particular reading job." ]
Please provide a description of the function:def process_pc_neighborhood(gene_names, neighbor_limit=1, database_filter=None): model = pcc.graph_query('neighborhood', gene_names, neighbor_limit=neighbor_limit, database_filter=da...
[ "Returns a BiopaxProcessor for a PathwayCommons neighborhood query.\n\n The neighborhood query finds the neighborhood around a set of source genes.\n\n http://www.pathwaycommons.org/pc2/#graph\n\n http://www.pathwaycommons.org/pc2/#graph_kind\n\n Parameters\n ----------\n gene_names : list\n ...
Please provide a description of the function:def process_pc_pathsbetween(gene_names, neighbor_limit=1, database_filter=None, block_size=None): if not block_size: model = pcc.graph_query('pathsbetween', gene_names, neighbor_limit=neighbor_limit...
[ "Returns a BiopaxProcessor for a PathwayCommons paths-between query.\n\n The paths-between query finds the paths between a set of genes. Here\n source gene names are given in a single list and all directions of paths\n between these genes are considered.\n\n http://www.pathwaycommons.org/pc2/#graph\n\n ...
Please provide a description of the function:def process_pc_pathsfromto(source_genes, target_genes, neighbor_limit=1, database_filter=None): model = pcc.graph_query('pathsfromto', source_genes, target_genes, neighbor_limit=neighbor_limit, ...
[ "Returns a BiopaxProcessor for a PathwayCommons paths-from-to query.\n\n The paths-from-to query finds the paths from a set of source genes to\n a set of target genes.\n\n http://www.pathwaycommons.org/pc2/#graph\n\n http://www.pathwaycommons.org/pc2/#graph_kind\n\n Parameters\n ----------\n so...
Please provide a description of the function:def process_model(model): bp = BiopaxProcessor(model) bp.get_modifications() bp.get_regulate_activities() bp.get_regulate_amounts() bp.get_activity_modification() bp.get_gef() bp.get_gap() bp.get_conversions() # bp.get_complexes() ...
[ "Returns a BiopaxProcessor for a BioPAX model object.\n\n Parameters\n ----------\n model : org.biopax.paxtools.model.Model\n A BioPAX model object.\n\n Returns\n -------\n bp : BiopaxProcessor\n A BiopaxProcessor containing the obtained BioPAX model in bp.model.\n " ]
Please provide a description of the function:def is_protein_or_chemical(agent): '''Return True if the agent is a protein/protein family or chemical.''' # Default is True if agent is None if agent is None: return True dbs = set(['UP', 'HGNC', 'CHEBI', 'PFAM-DEF', 'IP', 'INDRA', 'PUBCHEM', ...
[]
Please provide a description of the function:def is_background_knowledge(stmt): '''Return True if Statement is only supported by background knowledge.''' any_background = False # Iterate over all evidence for the statement for ev in stmt.evidence: epi = ev.epistemics if epi is not None: ...
[]
Please provide a description of the function:def multiple_sources(stmt): '''Return True if statement is supported by multiple sources. Note: this is currently not used and replaced by BeliefEngine score cutoff ''' sources = list(set([e.source_api for e in stmt.evidence])) if len(sources) > 1: ...
[]
Please provide a description of the function:def run_assembly(stmts, folder, pmcid, background_assertions=None): '''Run assembly on a list of statements, for a given PMCID.''' # Folder for index card output (scored submission) indexcard_prefix = folder + '/index_cards/' + pmcid # Folder for other output...
[]
Please provide a description of the function:def symbol_to_id(self, symbol): if symbol not in self.symbols_to_ids: m = 'Could not look up Entrez ID for Geneways symbol ' + symbol raise Exception(m) return self.symbols_to_ids[symbol]
[ "Returns the list of Entrez IDs for a given Geneways symbol\n (there may be more than one)" ]
Please provide a description of the function:def id_to_symbol(self, entrez_id): entrez_id = str(entrez_id) if entrez_id not in self.ids_to_symbols: m = 'Could not look up symbol for Entrez ID ' + entrez_id raise Exception(m) return self.ids_to_symbols[entrez_id]
[ "Gives the symbol for a given entrez id)" ]
Please provide a description of the function:def _format_id(ns, id): label = '%s:%s' % (ns, id) label = label.replace(' ', '_') url = get_identifiers_url(ns, id) return (label, url)
[ "Format a namespace/ID pair for display and curation." ]
Please provide a description of the function:def make_model(self, output_file, add_curation_cols=False, up_only=False): stmt_header = ['INDEX', 'UUID', 'TYPE', 'STR', 'AG_A_TEXT', 'AG_A_LINKS', 'AG_A_STR', 'AG_B_TEXT', 'AG_B_LINKS', 'AG_B_STR', ...
[ "Export the statements into a tab-separated text file.\n\n Parameters\n ----------\n output_file : str\n Name of the output file.\n add_curation_cols : bool\n Whether to add columns to facilitate statement curation. Default\n is False (no additional colum...
Please provide a description of the function:def get_create_base_agent(self, agent): try: base_agent = self.agents[_n(agent.name)] except KeyError: base_agent = BaseAgent(_n(agent.name)) self.agents[_n(agent.name)] = base_agent # If it's a molecular ...
[ "Return base agent with given name, creating it if needed." ]
Please provide a description of the function:def create_site(self, site, states=None): if site not in self.sites: self.sites.append(site) if states is not None: self.site_states.setdefault(site, []) try: states = list(states) excep...
[ "Create a new site on an agent if it doesn't already exist." ]
Please provide a description of the function:def create_mod_site(self, mc): site_name = get_mod_site_name(mc) (unmod_site_state, mod_site_state) = states[mc.mod_type] self.create_site(site_name, (unmod_site_state, mod_site_state)) site_anns = [Annotation((site_name, mod_site_sta...
[ "Create modification site for the BaseAgent from a ModCondition." ]
Please provide a description of the function:def add_site_states(self, site, states): for state in states: if state not in self.site_states[site]: self.site_states[site].append(state)
[ "Create new states on an agent site if the state doesn't exist." ]
Please provide a description of the function:def add_activity_form(self, activity_pattern, is_active): if is_active: if activity_pattern not in self.active_forms: self.active_forms.append(activity_pattern) else: if activity_pattern not in self.inactive_fo...
[ "Adds the pattern as an active or inactive form to an Agent.\n\n Parameters\n ----------\n activity_pattern : dict\n A dictionary of site names and their states.\n is_active : bool\n Is True if the given pattern corresponds to an active state.\n " ]
Please provide a description of the function:def add_activity_type(self, activity_type): if activity_type not in self.activity_types: self.activity_types.append(activity_type)
[ "Adds an activity type to an Agent.\n\n Parameters\n ----------\n activity_type : str\n The type of activity to add such as 'activity', 'kinase',\n 'gtpbound'\n " ]
Please provide a description of the function:def make_annotation(self): annotation = dict() # Put all properties of the action object into the annotation for item in dir(self): if len(item) > 0 and item[0] != '_' and \ not inspect.ismethod(getattr(self, ...
[ "Returns a dictionary with all properties of the action\n and each of its action mentions." ]
Please provide a description of the function:def _search_path(self, directory_name, filename): full_path = path.join(directory_name, filename) if path.exists(full_path): return full_path # Could not find the requested file in any of the directories return None
[ "Searches for a given file in the specified directory." ]
Please provide a description of the function:def _init_action_list(self, action_filename): self.actions = list() self.hiid_to_action_index = dict() f = codecs.open(action_filename, 'r', encoding='latin-1') first_line = True for line in f: line = line.rstrip...
[ "Parses the file and populates the data." ]
Please provide a description of the function:def _link_to_action_mentions(self, actionmention_filename): parser = GenewaysActionMentionParser(actionmention_filename) self.action_mentions = parser.action_mentions for action_mention in self.action_mentions: hiid = action_ment...
[ "Add action mentions" ]
Please provide a description of the function:def _lookup_symbols(self, symbols_filename): symbol_lookup = GenewaysSymbols(symbols_filename) for action in self.actions: action.up_symbol = symbol_lookup.id_to_symbol(action.up) action.dn_symbol = symbol_lookup.id_to_symbol(...
[ "Look up symbols for actions and action mentions" ]
Please provide a description of the function:def get_top_n_action_types(self, top_n): # Count action types action_type_to_counts = dict() for action in self.actions: actiontype = action.actiontype if actiontype not in action_type_to_counts: action...
[ "Returns the top N actions by count." ]
Please provide a description of the function:def make_model(self): # Assemble in two stages. # First, create the nodes of the graph for stmt in self.statements: # Skip SelfModification (self loops) -- has one node if isinstance(stmt, SelfModification) or \ ...
[ "Assemble the graph from the assembler's list of INDRA Statements." ]
Please provide a description of the function:def get_string(self): graph_string = self.graph.to_string() graph_string = graph_string.replace('\\N', '\\n') return graph_string
[ "Return the assembled graph as a string.\n\n Returns\n -------\n graph_string : str\n The assembled graph as a string.\n " ]