_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q234000
Content.change_format
train
def change_format(self, new_format): """Change the format label of this content. Note that this does NOT actually alter the format of the content, only the label. """ self._load_raw_content() self._format = new_format self.get_filename(renew=True) self.ge...
python
{ "resource": "" }
q234001
Content.get_text
train
def get_text(self): """Get the loaded, decompressed, and decoded text of this content.""" 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.deco...
python
{ "resource": "" }
q234002
Content.get_filename
train
def get_filename(self, renew=False): """Get the filename of this content. If the file name doesn't already exist, we created it as {id}.{format}. """ if self._fname is None or renew: self._fname = '%s.%s' % (self._id, self._format) return self._fname
python
{ "resource": "" }
q234003
Content.get_filepath
train
def get_filepath(self, renew=False): """Get the file path, joining the name and location for this file. If no location is given, it is assumed to be "here", e.g. ".". """ if self._location is None or renew: self._location = '.' return path.join(self._location, self.g...
python
{ "resource": "" }
q234004
ReadingData.get_statements
train
def get_statements(self, reprocess=False): """General method to create statements.""" if self._statements is None or reprocess: # Handle the case that there is no content. if self.content is None: self._statements = [] return [] # Map ...
python
{ "resource": "" }
q234005
Reader.add_result
train
def add_result(self, content_id, content, **kwargs): """"Add a result to the list of results.""" result_object = self.ResultClass(content_id, self.name, self.version, formats.JSON, content, **kwargs) self.results.append(result_object) return
python
{ "resource": "" }
q234006
Reader._check_content
train
def _check_content(self, content_str): """Check if the content is likely to be successfully read.""" 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" % (spac...
python
{ "resource": "" }
q234007
ReachReader._check_reach_env
train
def _check_reach_env(): """Check that the environment supports runnig reach.""" # 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...
python
{ "resource": "" }
q234008
ReachReader.prep_input
train
def prep_input(self, read_list): """Apply the readers to the content.""" 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()) ...
python
{ "resource": "" }
q234009
ReachReader.get_output
train
def get_output(self): """Get the output of a reading job as a list of filenames.""" 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...
python
{ "resource": "" }
q234010
ReachReader.read
train
def read(self, read_list, verbose=False, log=False): """Read the content, returning a list of ReadingData objects.""" 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 t...
python
{ "resource": "" }
q234011
SparserReader.prep_input
train
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.get_text()) if quality_issue is ...
python
{ "resource": "" }
q234012
SparserReader.get_output
train
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 value None. Skipping.") continue ...
python
{ "resource": "" }
q234013
SparserReader.read_some
train
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: outpath_list.append(output) return outpa...
python
{ "resource": "" }
q234014
SparserReader.read
train
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 sparser.") output_file_list = [] ...
python
{ "resource": "" }
q234015
process_text
train
def process_text(text, pmid=None, cleanup=True, add_grounding=True): """Process a string using the ISI reader and extract INDRA statements. Parameters ---------- text : str A text string to process pmid : Optional[str] The PMID associated with this text (or None if not specified) ...
python
{ "resource": "" }
q234016
process_nxml
train
def process_nxml(nxml_filename, pmid=None, extra_annotations=None, cleanup=True, add_grounding=True): """Process an NXML file using the ISI reader First converts NXML to plain text and preprocesses it, then runs the ISI reader, and processes the output to extract INDRA Statements. Par...
python
{ "resource": "" }
q234017
process_output_folder
train
def process_output_folder(folder_path, pmids=None, extra_annotations=None, add_grounding=True): """Recursively extracts statements from all ISI output files in the given directory and subdirectories. Parameters ---------- folder_path : str The directory to traverse...
python
{ "resource": "" }
q234018
process_json_file
train
def process_json_file(file_path, pmid=None, extra_annotations=None, add_grounding=True): """Extracts statements from the given ISI output file. Parameters ---------- file_path : str The ISI output file from which to extract statements pmid : int The PMID of the...
python
{ "resource": "" }
q234019
process_text
train
def process_text(text, save_xml='cwms_output.xml'): """Processes text using the CWMS web service. Parameters ---------- text : str Text to process Returns ------- cp : indra.sources.cwms.CWMSProcessor A CWMSProcessor, which contains a list of INDRA statements in its ...
python
{ "resource": "" }
q234020
process_ekb_file
train
def process_ekb_file(fname): """Processes an EKB file produced by CWMS. Parameters ---------- fname : str Path to the EKB file to process. Returns ------- cp : indra.sources.cwms.CWMSProcessor A CWMSProcessor, which contains a list of INDRA statements in its stateme...
python
{ "resource": "" }
q234021
im_json_to_graph
train
def im_json_to_graph(im_json): """Return networkx graph from Kappy's influence map JSON. Parameters ---------- im_json : dict A JSON dict which contains an influence map generated by Kappy. Returns ------- graph : networkx.MultiDiGraph A graph representing the influence map...
python
{ "resource": "" }
q234022
cm_json_to_graph
train
def cm_json_to_graph(im_json): """Return pygraphviz Agraph from Kappy's contact map JSON. Parameters ---------- im_json : dict A JSON dict which contains a contact map generated by Kappy. Returns ------- graph : pygraphviz.Agraph A graph representing the contact map. ""...
python
{ "resource": "" }
q234023
fetch_email
train
def fetch_email(M, msg_id): """Returns the given email message as a unicode string.""" 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 th...
python
{ "resource": "" }
q234024
get_headers
train
def get_headers(msg): """Takes email.message.Message object initialized from unicode string, returns dict with header fields.""" 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'...
python
{ "resource": "" }
q234025
populate_config_dict
train
def populate_config_dict(config_path): """Load the configuration file into the config_file dictionary A ConfigParser-style configuration file can have multiple sections, but we ignore the section distinction and load the key/value pairs from all sections into a single key/value list. """ try: ...
python
{ "resource": "" }
q234026
get_config
train
def get_config(key, failure_ok=True): """Get value by key from config file or environment. Returns the configuration value, first checking the environment variables and then, if it's not present there, checking the configuration file. Parameters ---------- key : str The key for the...
python
{ "resource": "" }
q234027
read_unicode_csv_fileobj
train
def read_unicode_csv_fileobj(fileobj, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL, lineterminator='\n', encoding='utf-8', skiprows=0): """fileobj can be a StringIO in Py3, but should be a BytesIO in Py2.""" # Python 3 version if sys.versi...
python
{ "resource": "" }
q234028
fast_deepcopy
train
def fast_deepcopy(obj): """This is a faster implementation of deepcopy via pickle. It is meant primarily for sets of Statements with complex hierarchies but can be used for any object. """ with BytesIO() as buf: pickle.dump(obj, buf) buf.seek(0) obj_new = pickle.load(buf) ...
python
{ "resource": "" }
q234029
batch_iter
train
def batch_iter(iterator, batch_size, return_func=None, padding=None): """Break an iterable into batches of size batch_size Note that `padding` should be set to something (anything) which is NOT a valid member of the iterator. For example, None works for [0,1,2,...10], but not for ['a', None, 'c', 'd']....
python
{ "resource": "" }
q234030
read_pmid_sentences
train
def read_pmid_sentences(pmid_sentences, **drum_args): """Read sentences from a PMID-keyed dictonary and return all Statements Parameters ---------- pmid_sentences : dict[str, list[str]] A dictonary where each key is a PMID pointing to a list of sentences to be read. **drum_args ...
python
{ "resource": "" }
q234031
graph_query
train
def graph_query(kind, source, target=None, neighbor_limit=1, database_filter=None): """Perform a graph query on PathwayCommons. For more information on these queries, see http://www.pathwaycommons.org/pc2/#graph Parameters ---------- kind : str The kind of graph query t...
python
{ "resource": "" }
q234032
owl_str_to_model
train
def owl_str_to_model(owl_str): """Return a BioPAX model object from an OWL string. Parameters ---------- owl_str : str The model as an OWL string. Returns ------- biopax_model : org.biopax.paxtools.model.Model A BioPAX model object (java object). """ io_class = auto...
python
{ "resource": "" }
q234033
owl_to_model
train
def owl_to_model(fname): """Return a BioPAX model object from an OWL file. Parameters ---------- fname : str The name of the OWL file containing the model. Returns ------- biopax_model : org.biopax.paxtools.model.Model A BioPAX model object (java object). """ io_cla...
python
{ "resource": "" }
q234034
model_to_owl
train
def model_to_owl(model, fname): """Save a BioPAX model object as an OWL file. Parameters ---------- model : org.biopax.paxtools.model.Model A BioPAX model object (java object). fname : str The name of the OWL file to save the model in. """ io_class = autoclass('org.biopax.pa...
python
{ "resource": "" }
q234035
CyJSAssembler.make_model
train
def make_model(self, *args, **kwargs): """Assemble a Cytoscape JS network from INDRA Statements. This method assembles a Cytoscape JS network from the set of INDRA Statements added to the assembler. Parameters ---------- grouping : bool If True, the nodes wi...
python
{ "resource": "" }
q234036
CyJSAssembler.get_gene_names
train
def get_gene_names(self): """Gather gene names of all nodes and node members""" # 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()) ...
python
{ "resource": "" }
q234037
CyJSAssembler.set_CCLE_context
train
def set_CCLE_context(self, cell_types): """Set context of all nodes and node members from CCLE.""" 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 =...
python
{ "resource": "" }
q234038
CyJSAssembler.print_cyjs_graph
train
def print_cyjs_graph(self): """Return the assembled Cytoscape JS network as a json string. Returns ------- cyjs_str : str A json string representation of the Cytoscape JS network. """ cyjs_dict = {'edges': self._edges, 'nodes': self._nodes} cyjs_str =...
python
{ "resource": "" }
q234039
CyJSAssembler.print_cyjs_context
train
def print_cyjs_context(self): """Return a list of node names and their respective context. Returns ------- cyjs_str_context : str A json string of the context dictionary. e.g. - {'CCLE' : {'bin_expression' : {'cell_line1' : {'gene1':'val1'} }, 'bin_ex...
python
{ "resource": "" }
q234040
CyJSAssembler.save_json
train
def save_json(self, fname_prefix='model'): """Save the assembled Cytoscape JS network in a json file. This method saves two files based on the file name prefix given. It saves one json file with the graph itself, and another json file with the context. Parameters ------...
python
{ "resource": "" }
q234041
CyJSAssembler.save_model
train
def save_model(self, fname='model.js'): """Save the assembled Cytoscape JS network in a js file. Parameters ---------- file_name : Optional[str] The name of the file to save the Cytoscape JS network to. Default: model.js """ exp_colorscale_str = j...
python
{ "resource": "" }
q234042
CyJSAssembler._get_edge_dict
train
def _get_edge_dict(self): """Return a dict of edges. Keyed tuples of (i, source, target, polarity) with lists of edge ids [id1, id2, ...] """ edge_dict = collections.defaultdict(lambda: []) if len(self._edges) > 0: for e in self._edges: data =...
python
{ "resource": "" }
q234043
CyJSAssembler._get_node_key
train
def _get_node_key(self, node_dict_item): """Return a tuple of sorted sources and targets given a node dict.""" s = tuple(sorted(node_dict_item['sources'])) t = tuple(sorted(node_dict_item['targets'])) return (s, t)
python
{ "resource": "" }
q234044
CyJSAssembler._get_node_groups
train
def _get_node_groups(self): """Return a list of node id lists that are topologically identical. First construct a node_dict which is keyed to the node id and has a value which is a dict with keys 'sources' and 'targets'. The 'sources' and 'targets' each contain a list of tuples ...
python
{ "resource": "" }
q234045
CyJSAssembler._group_edges
train
def _group_edges(self): """Group all edges that are topologically identical. This means that (i, source, target, polarity) are the same, then sets edges on parent (i.e. - group) nodes to 'Virtual' and creates a new edge to represent all of them. """ # edit edges on paren...
python
{ "resource": "" }
q234046
make_stmt
train
def make_stmt(stmt_cls, tf_agent, target_agent, pmid): """Return a Statement based on its type, agents, and PMID.""" ev = Evidence(source_api='trrust', pmid=pmid) return stmt_cls(deepcopy(tf_agent), deepcopy(target_agent), evidence=[ev])
python
{ "resource": "" }
q234047
get_grounded_agent
train
def get_grounded_agent(gene_name): """Return a grounded Agent based on an HGNC symbol.""" 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_cl...
python
{ "resource": "" }
q234048
TrrustProcessor.extract_statements
train
def extract_statements(self): """Process the table to extract Statements.""" 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 = Incr...
python
{ "resource": "" }
q234049
process_paper
train
def process_paper(model_name, pmid): """Process a paper with the given pubmed identifier Parameters ---------- model_name : str The directory for the INDRA machine pmid : str The PMID to process. Returns ------- rp : ReachProcessor A ReachProcessor containing th...
python
{ "resource": "" }
q234050
process_paper_helper
train
def process_paper_helper(model_name, pmid, start_time_local): """Wraps processing a paper by either a local or remote service and caches any uncaught exceptions""" try: if not aws_available: rp, txt_format = process_paper(model_name, pmid) else: rp, txt_format = proce...
python
{ "resource": "" }
q234051
_load_data
train
def _load_data(): """Load the data from the csv in data. The "gene_id" is the Entrez gene id, and the "approved_symbol" is the standard gene symbol. The "hms_id" is the LINCS ID for the drug. Returns ------- data : list[dict] A list of dicts of row values keyed by the column headers ex...
python
{ "resource": "" }
q234052
run_eidos
train
def run_eidos(endpoint, *args): """Run a given enpoint of Eidos through the command line. Parameters ---------- endpoint : str The class within the Eidos package to run, for instance 'apps.ExtractFromDirectory' will run 'org.clulab.wm.eidos.apps.ExtractFromDirectory' *args ...
python
{ "resource": "" }
q234053
extract_from_directory
train
def extract_from_directory(path_in, path_out): """Run Eidos on a set of text files in a folder. The output is produced in the specified output folder but the output files aren't processed by this function. Parameters ---------- path_in : str Path to an input folder with some text files...
python
{ "resource": "" }
q234054
extract_and_process
train
def extract_and_process(path_in, path_out): """Run Eidos on a set of text files and process output with INDRA. The output is produced in the specified output folder but the output files aren't processed by this function. Parameters ---------- path_in : str Path to an input folder with ...
python
{ "resource": "" }
q234055
get_statements
train
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): """Get a processor for the INDRA DB web API matching gi...
python
{ "resource": "" }
q234056
get_statements_by_hash
train
def get_statements_by_hash(hash_list, ev_limit=100, best_first=True, tries=2): """Get fully formed statements from a list of hashes. Parameters ---------- hash_list : list[int or str] A list of statement hashes. ev_limit : int or None Limit the amount of evidence returned per Statem...
python
{ "resource": "" }
q234057
get_statements_for_paper
train
def get_statements_for_paper(ids, ev_limit=10, best_first=True, tries=2, max_stmts=None): """Get the set of raw Statements extracted from a paper given by the id. Parameters ---------- ids : list[(<id type>, <id value>)] A list of tuples with ids and their type. The...
python
{ "resource": "" }
q234058
submit_curation
train
def submit_curation(hash_val, tag, curator, text=None, source='indra_rest_client', ev_hash=None, is_test=False): """Submit a curation for the given statement at the relevant level. Parameters ---------- hash_val : int The hash corresponding to the statement. tag : str ...
python
{ "resource": "" }
q234059
get_statement_queries
train
def get_statement_queries(stmts, **params): """Get queries used to search based on a statement. In addition to the stmts, you can enter any parameters standard to the query. See https://github.com/indralab/indra_db/rest_api for a full list. Parameters ---------- stmts : list[Statement] ...
python
{ "resource": "" }
q234060
IncrementalModel.save
train
def save(self, model_fname='model.pkl'): """Save the state of the IncrementalModel in a pickle file. Parameters ---------- model_fname : Optional[str] The name of the pickle file to save the state of the IncrementalModel in. Default: model.pkl """ ...
python
{ "resource": "" }
q234061
IncrementalModel.add_statements
train
def add_statements(self, pmid, stmts): """Add INDRA Statements to the incremental model indexed by PMID. Parameters ---------- pmid : str The PMID of the paper from which statements were extracted. stmts : list[indra.statements.Statement] A list of INDRA ...
python
{ "resource": "" }
q234062
IncrementalModel.preassemble
train
def preassemble(self, filters=None, grounding_map=None): """Preassemble the Statements collected in the model. Use INDRA's GroundingMapper, Preassembler and BeliefEngine on the IncrementalModel and save the unique statements and the top level statements in class attributes. Cur...
python
{ "resource": "" }
q234063
IncrementalModel.get_model_agents
train
def get_model_agents(self): """Return a list of all Agents from all Statements. Returns ------- agents : list[indra.statements.Agent] A list of Agents that are in the model. """ model_stmts = self.get_statements() agents = [] for stmt in model_...
python
{ "resource": "" }
q234064
IncrementalModel.get_statements
train
def get_statements(self): """Return a list of all Statements in a single list. Returns ------- stmts : list[indra.statements.Statement] A list of all the INDRA Statements in the model. """ stmt_lists = [v for k, v in self.stmts.items()] stmts = [] ...
python
{ "resource": "" }
q234065
IncrementalModel.get_statements_noprior
train
def get_statements_noprior(self): """Return a list of all non-prior Statements in a single list. Returns ------- stmts : list[indra.statements.Statement] A list of all the INDRA Statements in the model (excluding the prior). """ stmt_lists = [v fo...
python
{ "resource": "" }
q234066
process_ndex_neighborhood
train
def process_ndex_neighborhood(gene_names, network_id=None, rdf_out='bel_output.rdf', print_output=True): """Return a BelRdfProcessor for an NDEx network neighborhood. Parameters ---------- gene_names : list A list of HGNC gene symbols to search the neighborhood of....
python
{ "resource": "" }
q234067
process_pybel_neighborhood
train
def process_pybel_neighborhood(gene_names, network_file=None, network_type='belscript', **kwargs): """Return PybelProcessor around neighborhood of given genes in a network. This function processes the given network file and filters the returned Statements to ones that contain...
python
{ "resource": "" }
q234068
process_pybel_graph
train
def process_pybel_graph(graph): """Return a PybelProcessor by processing a PyBEL graph. Parameters ---------- graph : pybel.struct.BELGraph A PyBEL graph to process Returns ------- bp : PybelProcessor A PybelProcessor object which contains INDRA Statements in bp.sta...
python
{ "resource": "" }
q234069
process_belscript
train
def process_belscript(file_name, **kwargs): """Return a PybelProcessor by processing a BEL script file. Key word arguments are passed directly to pybel.from_path, for further information, see pybel.readthedocs.io/en/latest/io.html#pybel.from_path Some keyword arguments we use here differ from the d...
python
{ "resource": "" }
q234070
process_json_file
train
def process_json_file(file_name): """Return a PybelProcessor by processing a Node-Link JSON file. For more information on this format, see: http://pybel.readthedocs.io/en/latest/io.html#node-link-json Parameters ---------- file_name : str The path to a Node-Link JSON file. Returns...
python
{ "resource": "" }
q234071
process_cbn_jgif_file
train
def process_cbn_jgif_file(file_name): """Return a PybelProcessor by processing a CBN JGIF JSON file. Parameters ---------- file_name : str The path to a CBN JGIF JSON file. Returns ------- bp : PybelProcessor A PybelProcessor object which contains INDRA Statements in ...
python
{ "resource": "" }
q234072
update_famplex
train
def update_famplex(): """Update all the CSV files that form the FamPlex resource.""" famplex_url_pattern = \ 'https://raw.githubusercontent.com/sorgerlab/famplex/master/%s.csv' csv_names = ['entities', 'equivalences', 'gene_prefixes', 'grounding_map', 'relations'] for csv_name i...
python
{ "resource": "" }
q234073
update_lincs_small_molecules
train
def update_lincs_small_molecules(): """Load the csv of LINCS small molecule metadata into a dict. Produces a dict keyed by HMS LINCS small molecule ids, with the metadata contained in a dict of row values keyed by the column headers extracted from the csv. """ url = 'http://lincs.hms.harvard.ed...
python
{ "resource": "" }
q234074
update_lincs_proteins
train
def update_lincs_proteins(): """Load the csv of LINCS protein metadata into a dict. Produces a dict keyed by HMS LINCS protein ids, with the metadata contained in a dict of row values keyed by the column headers extracted from the csv. """ url = 'http://lincs.hms.harvard.edu/db/proteins/' p...
python
{ "resource": "" }
q234075
_get_is_direct
train
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 for the interaction being indirect then we...
python
{ "resource": "" }
q234076
IndexCardAssembler.make_model
train
def make_model(self): """Assemble statements into index cards.""" for stmt in self.statements: if isinstance(stmt, Modification): card = assemble_modification(stmt) elif isinstance(stmt, SelfModification): card = assemble_selfmodification(stmt) ...
python
{ "resource": "" }
q234077
IndexCardAssembler.print_model
train
def print_model(self): """Return the assembled cards as a JSON string. Returns ------- cards_json : str The JSON string representing the assembled cards. """ cards = [c.card for c in self.cards] # If there is only one card, print it as a single ...
python
{ "resource": "" }
q234078
geneways_action_to_indra_statement_type
train
def geneways_action_to_indra_statement_type(actiontype, plo): """Return INDRA Statement corresponding to Geneways action type. Parameters ---------- actiontype : str The verb extracted by the Geneways processor plo : str A one character string designating whether Geneways classifies...
python
{ "resource": "" }
q234079
GenewaysProcessor.make_statement
train
def make_statement(self, action, mention): """Makes an INDRA statement from a Geneways action and action mention. Parameters ---------- action : GenewaysAction The mechanism that the Geneways mention maps to. Note that several text mentions can correspond to the ...
python
{ "resource": "" }
q234080
HierarchyManager.load_from_rdf_file
train
def load_from_rdf_file(self, rdf_file): """Initialize given an RDF input file representing the hierarchy." Parameters ---------- rdf_file : str Path to an RDF file. """ self.graph = rdflib.Graph() self.graph.parse(os.path.abspath(rdf_file), format='nt...
python
{ "resource": "" }
q234081
HierarchyManager.load_from_rdf_string
train
def load_from_rdf_string(self, rdf_str): """Initialize given an RDF string representing the hierarchy." Parameters ---------- rdf_str : str An RDF string. """ self.graph = rdflib.Graph() self.graph.parse(data=rdf_str, format='nt') self.initial...
python
{ "resource": "" }
q234082
HierarchyManager.extend_with
train
def extend_with(self, rdf_file): """Extend the RDF graph of this HierarchyManager with another RDF file. Parameters ---------- rdf_file : str An RDF file which is parsed such that the current graph and the graph described by the file are merged. """ ...
python
{ "resource": "" }
q234083
HierarchyManager.build_transitive_closures
train
def build_transitive_closures(self): """Build the transitive closures of the hierarchy. This method constructs dictionaries which contain terms in the hierarchy as keys and either all the "isa+" or "partof+" related terms as values. """ self.component_counter = 0 ...
python
{ "resource": "" }
q234084
HierarchyManager.build_transitive_closure
train
def build_transitive_closure(self, rel, tc_dict): """Build a transitive closure for a given relation in a given 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.transi...
python
{ "resource": "" }
q234085
HierarchyManager.directly_or_indirectly_related
train
def directly_or_indirectly_related(self, ns1, id1, ns2, id2, closure_dict, relation_func): """Return True if two entities have the speicified relationship. This relation is constructed possibly through multiple links connecting the two entities directly or...
python
{ "resource": "" }
q234086
HierarchyManager.isa
train
def isa(self, ns1, id1, ns2, id2): """Return True if one entity has an "isa" relationship to another. Parameters ---------- ns1 : str Namespace code for an entity. id1 : string URI for an entity. ns2 : str Namespace code for an entity....
python
{ "resource": "" }
q234087
HierarchyManager.partof
train
def partof(self, ns1, id1, ns2, id2): """Return True if one entity is "partof" another. Parameters ---------- ns1 : str Namespace code for an entity. id1 : str URI for an entity. ns2 : str Namespace code for an entity. id2 : st...
python
{ "resource": "" }
q234088
HierarchyManager.isa_or_partof
train
def isa_or_partof(self, ns1, id1, ns2, id2): """Return True if two entities are in an "isa" or "partof" relationship Parameters ---------- ns1 : str Namespace code for an entity. id1 : str URI for an entity. ns2 : str Namespace code fo...
python
{ "resource": "" }
q234089
HierarchyManager.is_opposite
train
def is_opposite(self, ns1, id1, ns2, id2): """Return True if two entities are in an "is_opposite" relationship Parameters ---------- ns1 : str Namespace code for an entity. id1 : str URI for an entity. ns2 : str Namespace code for an e...
python
{ "resource": "" }
q234090
HierarchyManager.get_parents
train
def get_parents(self, uri, type='all'): """Return parents of a given entry. Parameters ---------- uri : str The URI of the entry whose parents are to be returned. See the get_uri method to construct this URI from a name space and id. type : str ...
python
{ "resource": "" }
q234091
_get_perf
train
def _get_perf(text, msg_id): """Return a request message for a given text.""" 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
python
{ "resource": "" }
q234092
DrumReader.read_pmc
train
def read_pmc(self, pmcid): """Read a given PMC article. Parameters ---------- pmcid : str The PMC ID of the article to read. Note that only articles in the open-access subset of PMC will work. """ msg = KQMLPerformative('REQUEST') msg.set(...
python
{ "resource": "" }
q234093
DrumReader.read_text
train
def read_text(self, text): """Read a given text phrase. Parameters ---------- text : str The text to read. Typically a sentence or a paragraph. """ logger.info('Reading: "%s"' % text) msg_id = 'RT000%s' % self.msg_counter kqml_perf = _get_perf...
python
{ "resource": "" }
q234094
DrumReader.receive_reply
train
def receive_reply(self, msg, content): """Handle replies with reading results.""" reply_head = content.head() if reply_head == 'error': comment = content.gets('comment') logger.error('Got error reply: "%s"' % comment) else: extractions = content.gets('...
python
{ "resource": "" }
q234095
split_long_sentence
train
def split_long_sentence(sentence, words_per_line): """Takes a sentence and adds a newline every "words_per_line" words. Parameters ---------- sentence: str Sentene to split words_per_line: double Add a newline every this many words """ words = sentence.split(' ') split_s...
python
{ "resource": "" }
q234096
shorter_name
train
def shorter_name(key): """Return a shorter name for an id. Does this by only taking the last part of the URI, after the last / and the last #. Also replaces - and . with _. Parameters ---------- key: str Some URI Returns ------- key_short: str A shortened, but more...
python
{ "resource": "" }
q234097
add_event_property_edges
train
def add_event_property_edges(event_entity, entries): """Adds edges to the graph for event properties.""" 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] ...
python
{ "resource": "" }
q234098
get_sourced_from
train
def get_sourced_from(entry): """Get a list of values from the source_from attribute""" 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
python
{ "resource": "" }
q234099
get_entry_compact_text_repr
train
def get_entry_compact_text_repr(entry, entries): """If the entry has a text value, return that. If the entry has a source_from value, return the text value of the source. Otherwise, return None.""" text = get_shortest_text_value(entry) if text is not None: return text else: sourc...
python
{ "resource": "" }