id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
18,900 | sorgerlab/indra | indra/tools/reading/readers.py | Content.get_filepath | 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.get_filename()) | python | def get_filepath(self, renew=False):
if self._location is None or renew:
self._location = '.'
return path.join(self._location, self.get_filename()) | [
"def",
"get_filepath",
"(",
"self",
",",
"renew",
"=",
"False",
")",
":",
"if",
"self",
".",
"_location",
"is",
"None",
"or",
"renew",
":",
"self",
".",
"_location",
"=",
"'.'",
"return",
"path",
".",
"join",
"(",
"self",
".",
"_location",
",",
"self... | 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. ".". | [
"Get",
"the",
"file",
"path",
"joining",
"the",
"name",
"and",
"location",
"for",
"this",
"file",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/reading/readers.py#L187-L194 |
18,901 | sorgerlab/indra | indra/tools/reading/readers.py | ReadingData.get_statements | 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 to the different processors.
if self.reader == ReachReader.name:
if self.format == formats.JSON:
# Process the reach json into statements.
json_str = json.dumps(self.content)
processor = reach.process_json_str(json_str)
else:
raise ReadingError("Incorrect format for Reach output: %s."
% self.format)
elif self.reader == SparserReader.name:
if self.format == formats.JSON:
# Process the sparser content into statements
processor = sparser.process_json_dict(self.content)
if processor is not None:
processor.set_statements_pmid(None)
else:
raise ReadingError("Sparser should only ever be JSON, not "
"%s." % self.format)
elif self.reader == TripsReader.name:
processor = trips.process_xml(self.content)
else:
raise ReadingError("Unknown reader: %s." % self.reader)
# Get the statements from the processor, if it was resolved.
if processor is None:
logger.error("Production of statements from %s failed for %s."
% (self.reader, self.content_id))
stmts = []
else:
stmts = processor.statements
self._statements = stmts[:]
else:
stmts = self._statements[:]
return stmts | python | def get_statements(self, reprocess=False):
if self._statements is None or reprocess:
# Handle the case that there is no content.
if self.content is None:
self._statements = []
return []
# Map to the different processors.
if self.reader == ReachReader.name:
if self.format == formats.JSON:
# Process the reach json into statements.
json_str = json.dumps(self.content)
processor = reach.process_json_str(json_str)
else:
raise ReadingError("Incorrect format for Reach output: %s."
% self.format)
elif self.reader == SparserReader.name:
if self.format == formats.JSON:
# Process the sparser content into statements
processor = sparser.process_json_dict(self.content)
if processor is not None:
processor.set_statements_pmid(None)
else:
raise ReadingError("Sparser should only ever be JSON, not "
"%s." % self.format)
elif self.reader == TripsReader.name:
processor = trips.process_xml(self.content)
else:
raise ReadingError("Unknown reader: %s." % self.reader)
# Get the statements from the processor, if it was resolved.
if processor is None:
logger.error("Production of statements from %s failed for %s."
% (self.reader, self.content_id))
stmts = []
else:
stmts = processor.statements
self._statements = stmts[:]
else:
stmts = self._statements[:]
return stmts | [
"def",
"get_statements",
"(",
"self",
",",
"reprocess",
"=",
"False",
")",
":",
"if",
"self",
".",
"_statements",
"is",
"None",
"or",
"reprocess",
":",
"# Handle the case that there is no content.",
"if",
"self",
".",
"content",
"is",
"None",
":",
"self",
".",... | General method to create statements. | [
"General",
"method",
"to",
"create",
"statements",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/reading/readers.py#L241-L282 |
18,902 | sorgerlab/indra | indra/tools/reading/readers.py | Reader.add_result | 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 | def add_result(self, content_id, content, **kwargs):
"result_object = self.ResultClass(content_id, self.name, self.version,
formats.JSON, content, **kwargs)
self.results.append(result_object)
return | [
"def",
"add_result",
"(",
"self",
",",
"content_id",
",",
"content",
",",
"*",
"*",
"kwargs",
")",
":",
"result_object",
"=",
"self",
".",
"ResultClass",
"(",
"content_id",
",",
"self",
".",
"name",
",",
"self",
".",
"version",
",",
"formats",
".",
"JS... | Add a result to the list of results. | [
"Add",
"a",
"result",
"to",
"the",
"list",
"of",
"results",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/reading/readers.py#L316-L321 |
18,903 | sorgerlab/indra | indra/tools/reading/readers.py | Reader._check_content | 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" % (space_ratio,
self.max_space_ratio)
if len(content_str) > self.input_character_limit:
return "too long: %d > %d" % (len(content_str),
self.input_character_limit)
return None | python | def _check_content(self, content_str):
if self.do_content_check:
space_ratio = float(content_str.count(' '))/len(content_str)
if space_ratio > self.max_space_ratio:
return "space-ratio: %f > %f" % (space_ratio,
self.max_space_ratio)
if len(content_str) > self.input_character_limit:
return "too long: %d > %d" % (len(content_str),
self.input_character_limit)
return None | [
"def",
"_check_content",
"(",
"self",
",",
"content_str",
")",
":",
"if",
"self",
".",
"do_content_check",
":",
"space_ratio",
"=",
"float",
"(",
"content_str",
".",
"count",
"(",
"' '",
")",
")",
"/",
"len",
"(",
"content_str",
")",
"if",
"space_ratio",
... | Check if the content is likely to be successfully read. | [
"Check",
"if",
"the",
"content",
"is",
"likely",
"to",
"be",
"successfully",
"read",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/reading/readers.py#L323-L333 |
18,904 | sorgerlab/indra | indra/tools/reading/readers.py | ReachReader._check_reach_env | 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(path_to_reach):
raise ReachError(
'Reach path unset or invalid. Check REACHPATH environment var '
'and/or config file.'
)
logger.debug('Using REACH jar at: %s' % path_to_reach)
# Get the reach version.
reach_version = get_config('REACH_VERSION')
if reach_version is None:
reach_version = environ.get('REACH_VERSION', None)
if reach_version is None:
logger.debug('REACH version not set in REACH_VERSION')
m = re.match('reach-(.*?)\.jar', path.basename(path_to_reach))
reach_version = re.sub('-SNAP.*?$', '', m.groups()[0])
logger.debug('Using REACH version: %s' % reach_version)
return path_to_reach, reach_version | python | def _check_reach_env():
# Get the path to the REACH JAR
path_to_reach = get_config('REACHPATH')
if path_to_reach is None:
path_to_reach = environ.get('REACHPATH', None)
if path_to_reach is None or not path.exists(path_to_reach):
raise ReachError(
'Reach path unset or invalid. Check REACHPATH environment var '
'and/or config file.'
)
logger.debug('Using REACH jar at: %s' % path_to_reach)
# Get the reach version.
reach_version = get_config('REACH_VERSION')
if reach_version is None:
reach_version = environ.get('REACH_VERSION', None)
if reach_version is None:
logger.debug('REACH version not set in REACH_VERSION')
m = re.match('reach-(.*?)\.jar', path.basename(path_to_reach))
reach_version = re.sub('-SNAP.*?$', '', m.groups()[0])
logger.debug('Using REACH version: %s' % reach_version)
return path_to_reach, reach_version | [
"def",
"_check_reach_env",
"(",
")",
":",
"# Get the path to the REACH JAR",
"path_to_reach",
"=",
"get_config",
"(",
"'REACHPATH'",
")",
"if",
"path_to_reach",
"is",
"None",
":",
"path_to_reach",
"=",
"environ",
".",
"get",
"(",
"'REACHPATH'",
",",
"None",
")",
... | Check that the environment supports runnig reach. | [
"Check",
"that",
"the",
"environment",
"supports",
"runnig",
"reach",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/reading/readers.py#L409-L433 |
18,905 | sorgerlab/indra | indra/tools/reading/readers.py | ReachReader.prep_input | 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())
if quality_issue is not None:
logger.warning("Skipping %d due to: %s"
% (content.get_id(), quality_issue))
continue
# Look for things that are more like file names, rather than ids.
cid = content.get_id()
if isinstance(cid, str) and re.match('^\w*?\d+$', cid) is None:
new_id = 'FILE%06d' % i
i += 1
self.id_maps[new_id] = cid
content.change_id(new_id)
new_fpath = content.copy_to(self.input_dir)
else:
# Put the content in the appropriate directory.
new_fpath = content.copy_to(self.input_dir)
self.num_input += 1
logger.debug('%s saved for reading by reach.'
% new_fpath)
return | python | def prep_input(self, read_list):
logger.info("Prepping input.")
i = 0
for content in read_list:
# Check the quality of the text, and skip if there are any issues.
quality_issue = self._check_content(content.get_text())
if quality_issue is not None:
logger.warning("Skipping %d due to: %s"
% (content.get_id(), quality_issue))
continue
# Look for things that are more like file names, rather than ids.
cid = content.get_id()
if isinstance(cid, str) and re.match('^\w*?\d+$', cid) is None:
new_id = 'FILE%06d' % i
i += 1
self.id_maps[new_id] = cid
content.change_id(new_id)
new_fpath = content.copy_to(self.input_dir)
else:
# Put the content in the appropriate directory.
new_fpath = content.copy_to(self.input_dir)
self.num_input += 1
logger.debug('%s saved for reading by reach.'
% new_fpath)
return | [
"def",
"prep_input",
"(",
"self",
",",
"read_list",
")",
":",
"logger",
".",
"info",
"(",
"\"Prepping input.\"",
")",
"i",
"=",
"0",
"for",
"content",
"in",
"read_list",
":",
"# Check the quality of the text, and skip if there are any issues.",
"quality_issue",
"=",
... | Apply the readers to the content. | [
"Apply",
"the",
"readers",
"to",
"the",
"content",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/reading/readers.py#L440-L466 |
18,906 | sorgerlab/indra | indra/tools/reading/readers.py | ReachReader.get_output | 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 json_file in json_files:
# Remove .uaz.<subfile type>.json
prefix = '.'.join(path.basename(json_file).split('.')[:-3])
json_prefixes.add(path.join(self.output_dir, prefix))
# Join each set of json files and store the json dict.
for prefix in json_prefixes:
base_prefix = path.basename(prefix)
if base_prefix.isdecimal():
base_prefix = int(base_prefix)
elif base_prefix in self.id_maps.keys():
base_prefix = self.id_maps[base_prefix]
try:
content = self._join_json_files(prefix, clear=True)
except Exception as e:
logger.exception(e)
logger.error("Could not load result for prefix %s." % prefix)
content = None
self.add_result(base_prefix, content)
logger.debug('Joined files for prefix %s.' % base_prefix)
return self.results | python | def get_output(self):
logger.info("Getting outputs.")
# Get the set of prefixes (each will correspond to three json files.)
json_files = glob.glob(path.join(self.output_dir, '*.json'))
json_prefixes = set()
for json_file in json_files:
# Remove .uaz.<subfile type>.json
prefix = '.'.join(path.basename(json_file).split('.')[:-3])
json_prefixes.add(path.join(self.output_dir, prefix))
# Join each set of json files and store the json dict.
for prefix in json_prefixes:
base_prefix = path.basename(prefix)
if base_prefix.isdecimal():
base_prefix = int(base_prefix)
elif base_prefix in self.id_maps.keys():
base_prefix = self.id_maps[base_prefix]
try:
content = self._join_json_files(prefix, clear=True)
except Exception as e:
logger.exception(e)
logger.error("Could not load result for prefix %s." % prefix)
content = None
self.add_result(base_prefix, content)
logger.debug('Joined files for prefix %s.' % base_prefix)
return self.results | [
"def",
"get_output",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"\"Getting outputs.\"",
")",
"# Get the set of prefixes (each will correspond to three json files.)",
"json_files",
"=",
"glob",
".",
"glob",
"(",
"path",
".",
"join",
"(",
"self",
".",
"output_... | Get the output of a reading job as a list of filenames. | [
"Get",
"the",
"output",
"of",
"a",
"reading",
"job",
"as",
"a",
"list",
"of",
"filenames",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/reading/readers.py#L468-L494 |
18,907 | sorgerlab/indra | indra/tools/reading/readers.py | ReachReader.read | 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 to run reach. At least %s required." %
(self.REACH_MEM + self.MEM_BUFFER)
)
logger.info("REACH not run.")
return ret
# Prep the content
self.prep_input(read_list)
if self.num_input > 0:
# Run REACH!
logger.info("Beginning reach.")
args = [
'java',
'-Dconfig.file=%s' % self.conf_file_path,
'-jar', self.exec_path
]
p = subprocess.Popen(args, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
log_file_str = ''
for line in iter(p.stdout.readline, b''):
log_line = 'REACH: ' + line.strip().decode('utf8')
if verbose:
logger.info(log_line)
if log:
log_file_str += log_line + '\n'
if log:
with open('reach_run.log', 'ab') as f:
f.write(log_file_str.encode('utf8'))
p_out, p_err = p.communicate()
if p.returncode:
logger.error('Problem running REACH:')
logger.error('Stdout: %s' % p_out.decode('utf-8'))
logger.error('Stderr: %s' % p_err.decode('utf-8'))
raise ReachError("Problem running REACH")
logger.info("Reach finished.")
ret = self.get_output()
self.clear_input()
return ret | python | def read(self, read_list, verbose=False, log=False):
ret = []
mem_tot = _get_mem_total()
if mem_tot is not None and mem_tot <= self.REACH_MEM + self.MEM_BUFFER:
logger.error(
"Too little memory to run reach. At least %s required." %
(self.REACH_MEM + self.MEM_BUFFER)
)
logger.info("REACH not run.")
return ret
# Prep the content
self.prep_input(read_list)
if self.num_input > 0:
# Run REACH!
logger.info("Beginning reach.")
args = [
'java',
'-Dconfig.file=%s' % self.conf_file_path,
'-jar', self.exec_path
]
p = subprocess.Popen(args, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
log_file_str = ''
for line in iter(p.stdout.readline, b''):
log_line = 'REACH: ' + line.strip().decode('utf8')
if verbose:
logger.info(log_line)
if log:
log_file_str += log_line + '\n'
if log:
with open('reach_run.log', 'ab') as f:
f.write(log_file_str.encode('utf8'))
p_out, p_err = p.communicate()
if p.returncode:
logger.error('Problem running REACH:')
logger.error('Stdout: %s' % p_out.decode('utf-8'))
logger.error('Stderr: %s' % p_err.decode('utf-8'))
raise ReachError("Problem running REACH")
logger.info("Reach finished.")
ret = self.get_output()
self.clear_input()
return ret | [
"def",
"read",
"(",
"self",
",",
"read_list",
",",
"verbose",
"=",
"False",
",",
"log",
"=",
"False",
")",
":",
"ret",
"=",
"[",
"]",
"mem_tot",
"=",
"_get_mem_total",
"(",
")",
"if",
"mem_tot",
"is",
"not",
"None",
"and",
"mem_tot",
"<=",
"self",
... | Read the content, returning a list of ReadingData objects. | [
"Read",
"the",
"content",
"returning",
"a",
"list",
"of",
"ReadingData",
"objects",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/reading/readers.py#L505-L549 |
18,908 | sorgerlab/indra | indra/tools/reading/readers.py | SparserReader.prep_input | 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 not None:
logger.warning("Skipping %d due to: %s"
% (content.get_id(), quality_issue))
continue
if content.is_format('nxml'):
# If it is already an nxml, we just need to adjust the
# name a bit, if anything.
if not content.get_filename().startswith('PMC'):
content.change_id('PMC' + str(content.get_id()))
fpath = content.copy_to(self.tmp_dir)
self.file_list.append(fpath)
elif content.is_format('txt', 'text'):
# Otherwise we need to frame the content in xml and put it
# in a new file with the appropriate name.
nxml_str = sparser.make_nxml_from_text(content.get_text())
new_content = Content.from_string('PMC' + str(content.get_id()),
'nxml', nxml_str)
fpath = new_content.copy_to(self.tmp_dir)
self.file_list.append(fpath)
else:
raise SparserError("Unrecognized format %s."
% content.format)
return | python | 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 not None:
logger.warning("Skipping %d due to: %s"
% (content.get_id(), quality_issue))
continue
if content.is_format('nxml'):
# If it is already an nxml, we just need to adjust the
# name a bit, if anything.
if not content.get_filename().startswith('PMC'):
content.change_id('PMC' + str(content.get_id()))
fpath = content.copy_to(self.tmp_dir)
self.file_list.append(fpath)
elif content.is_format('txt', 'text'):
# Otherwise we need to frame the content in xml and put it
# in a new file with the appropriate name.
nxml_str = sparser.make_nxml_from_text(content.get_text())
new_content = Content.from_string('PMC' + str(content.get_id()),
'nxml', nxml_str)
fpath = new_content.copy_to(self.tmp_dir)
self.file_list.append(fpath)
else:
raise SparserError("Unrecognized format %s."
% content.format)
return | [
"def",
"prep_input",
"(",
"self",
",",
"read_list",
")",
":",
"logger",
".",
"info",
"(",
"'Prepping input for sparser.'",
")",
"self",
".",
"file_list",
"=",
"[",
"]",
"for",
"content",
"in",
"read_list",
":",
"quality_issue",
"=",
"self",
".",
"_check_cont... | Prepare the list of files or text content objects to be read. | [
"Prepare",
"the",
"list",
"of",
"files",
"or",
"text",
"content",
"objects",
"to",
"be",
"read",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/reading/readers.py#L567-L598 |
18,909 | sorgerlab/indra | indra/tools/reading/readers.py | SparserReader.get_output | 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
re_out = patt.match(path.basename(outpath))
if re_out is None:
raise SparserError("Could not get prefix from output path %s."
% outpath)
prefix = re_out.groups()[0]
if prefix.startswith('PMC'):
prefix = prefix[3:]
if prefix.isdecimal():
# In this case we assume the prefix is a tcid.
prefix = int(prefix)
try:
with open(outpath, 'rt') as f:
content = json.load(f)
except Exception as e:
logger.exception(e)
logger.error("Could not load reading content from %s."
% outpath)
content = None
self.add_result(prefix, content)
if clear:
input_path = outpath.replace('-semantics.json', '.nxml')
try:
remove(outpath)
remove(input_path)
except Exception as e:
logger.exception(e)
logger.error("Could not remove sparser files %s and %s."
% (outpath, input_path))
return self.results | python | 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
re_out = patt.match(path.basename(outpath))
if re_out is None:
raise SparserError("Could not get prefix from output path %s."
% outpath)
prefix = re_out.groups()[0]
if prefix.startswith('PMC'):
prefix = prefix[3:]
if prefix.isdecimal():
# In this case we assume the prefix is a tcid.
prefix = int(prefix)
try:
with open(outpath, 'rt') as f:
content = json.load(f)
except Exception as e:
logger.exception(e)
logger.error("Could not load reading content from %s."
% outpath)
content = None
self.add_result(prefix, content)
if clear:
input_path = outpath.replace('-semantics.json', '.nxml')
try:
remove(outpath)
remove(input_path)
except Exception as e:
logger.exception(e)
logger.error("Could not remove sparser files %s and %s."
% (outpath, input_path))
return self.results | [
"def",
"get_output",
"(",
"self",
",",
"output_files",
",",
"clear",
"=",
"True",
")",
":",
"patt",
"=",
"re",
".",
"compile",
"(",
"r'(.*?)-semantics.*?'",
")",
"for",
"outpath",
"in",
"output_files",
":",
"if",
"outpath",
"is",
"None",
":",
"logger",
"... | Get the output files as an id indexed dict. | [
"Get",
"the",
"output",
"files",
"as",
"an",
"id",
"indexed",
"dict",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/reading/readers.py#L600-L639 |
18,910 | sorgerlab/indra | indra/tools/reading/readers.py | SparserReader.read_some | 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 outpath_list, outbuf | python | 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 outpath_list, outbuf | [
"def",
"read_some",
"(",
"self",
",",
"fpath_list",
",",
"outbuf",
"=",
"None",
",",
"verbose",
"=",
"False",
")",
":",
"outpath_list",
"=",
"[",
"]",
"for",
"fpath",
"in",
"fpath_list",
":",
"output",
",",
"outbuf",
"=",
"self",
".",
"read_one",
"(",
... | Perform a few readings. | [
"Perform",
"a",
"few",
"readings",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/reading/readers.py#L662-L669 |
18,911 | sorgerlab/indra | indra/tools/reading/readers.py | SparserReader.read | 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 = []
if log:
log_name = 'sparser_run_%s.log' % _time_stamp()
outbuf = open(log_name, 'wb')
else:
outbuf = None
try:
if self.n_proc == 1:
for fpath in self.file_list:
outpath, _ = self.read_one(fpath, outbuf, verbose)
if outpath is not None:
output_file_list.append(outpath)
else:
if n_per_proc is None:
n_per_proc = max(1, min(1000, L//self.n_proc//2))
pool = None
try:
pool = Pool(self.n_proc)
if n_per_proc is not 1:
batches = [self.file_list[n*n_per_proc:(n+1)*n_per_proc]
for n in range(L//n_per_proc + 1)]
out_lists_and_buffs = pool.map(self.read_some,
batches)
else:
out_files_and_buffs = pool.map(self.read_one,
self.file_list)
out_lists_and_buffs = [([out_files], buffs)
for out_files, buffs
in out_files_and_buffs]
finally:
if pool is not None:
pool.close()
pool.join()
for i, (out_list, buff) in enumerate(out_lists_and_buffs):
if out_list is not None:
output_file_list += out_list
if log:
outbuf.write(b'Log for producing output %d/%d.\n'
% (i, len(out_lists_and_buffs)))
if buff is not None:
buff.seek(0)
outbuf.write(buff.read() + b'\n')
else:
outbuf.write(b'ERROR: no buffer was None. '
b'No logs available.\n')
outbuf.flush()
finally:
if log:
outbuf.close()
if verbose:
logger.info("Sparser logs may be found at %s." %
log_name)
ret = self.get_output(output_file_list)
return ret | python | 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 = []
if log:
log_name = 'sparser_run_%s.log' % _time_stamp()
outbuf = open(log_name, 'wb')
else:
outbuf = None
try:
if self.n_proc == 1:
for fpath in self.file_list:
outpath, _ = self.read_one(fpath, outbuf, verbose)
if outpath is not None:
output_file_list.append(outpath)
else:
if n_per_proc is None:
n_per_proc = max(1, min(1000, L//self.n_proc//2))
pool = None
try:
pool = Pool(self.n_proc)
if n_per_proc is not 1:
batches = [self.file_list[n*n_per_proc:(n+1)*n_per_proc]
for n in range(L//n_per_proc + 1)]
out_lists_and_buffs = pool.map(self.read_some,
batches)
else:
out_files_and_buffs = pool.map(self.read_one,
self.file_list)
out_lists_and_buffs = [([out_files], buffs)
for out_files, buffs
in out_files_and_buffs]
finally:
if pool is not None:
pool.close()
pool.join()
for i, (out_list, buff) in enumerate(out_lists_and_buffs):
if out_list is not None:
output_file_list += out_list
if log:
outbuf.write(b'Log for producing output %d/%d.\n'
% (i, len(out_lists_and_buffs)))
if buff is not None:
buff.seek(0)
outbuf.write(buff.read() + b'\n')
else:
outbuf.write(b'ERROR: no buffer was None. '
b'No logs available.\n')
outbuf.flush()
finally:
if log:
outbuf.close()
if verbose:
logger.info("Sparser logs may be found at %s." %
log_name)
ret = self.get_output(output_file_list)
return ret | [
"def",
"read",
"(",
"self",
",",
"read_list",
",",
"verbose",
"=",
"False",
",",
"log",
"=",
"False",
",",
"n_per_proc",
"=",
"None",
")",
":",
"ret",
"=",
"[",
"]",
"self",
".",
"prep_input",
"(",
"read_list",
")",
"L",
"=",
"len",
"(",
"self",
... | Perform the actual reading. | [
"Perform",
"the",
"actual",
"reading",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/reading/readers.py#L671-L733 |
18,912 | sorgerlab/indra | indra/sources/isi/api.py | process_text | 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)
cleanup : Optional[bool]
If True, the temporary folders created for preprocessed reading input
and output are removed. Default: True
add_grounding : Optional[bool]
If True the extracted Statements' grounding is mapped
Returns
-------
ip : indra.sources.isi.processor.IsiProcessor
A processor containing statements
"""
# Create a temporary directory to store the proprocessed input
pp_dir = tempfile.mkdtemp('indra_isi_pp_output')
pp = IsiPreprocessor(pp_dir)
extra_annotations = {}
pp.preprocess_plain_text_string(text, pmid, extra_annotations)
# Run the ISI reader and extract statements
ip = process_preprocessed(pp)
if add_grounding:
ip.add_grounding()
if cleanup:
# Remove temporary directory with processed input
shutil.rmtree(pp_dir)
else:
logger.info('Not cleaning up %s' % pp_dir)
return ip | python | def process_text(text, pmid=None, cleanup=True, add_grounding=True):
# Create a temporary directory to store the proprocessed input
pp_dir = tempfile.mkdtemp('indra_isi_pp_output')
pp = IsiPreprocessor(pp_dir)
extra_annotations = {}
pp.preprocess_plain_text_string(text, pmid, extra_annotations)
# Run the ISI reader and extract statements
ip = process_preprocessed(pp)
if add_grounding:
ip.add_grounding()
if cleanup:
# Remove temporary directory with processed input
shutil.rmtree(pp_dir)
else:
logger.info('Not cleaning up %s' % pp_dir)
return ip | [
"def",
"process_text",
"(",
"text",
",",
"pmid",
"=",
"None",
",",
"cleanup",
"=",
"True",
",",
"add_grounding",
"=",
"True",
")",
":",
"# Create a temporary directory to store the proprocessed input",
"pp_dir",
"=",
"tempfile",
".",
"mkdtemp",
"(",
"'indra_isi_pp_o... | 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)
cleanup : Optional[bool]
If True, the temporary folders created for preprocessed reading input
and output are removed. Default: True
add_grounding : Optional[bool]
If True the extracted Statements' grounding is mapped
Returns
-------
ip : indra.sources.isi.processor.IsiProcessor
A processor containing statements | [
"Process",
"a",
"string",
"using",
"the",
"ISI",
"reader",
"and",
"extract",
"INDRA",
"statements",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/isi/api.py#L17-L55 |
18,913 | sorgerlab/indra | indra/sources/isi/api.py | process_nxml | 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.
Parameters
----------
nxml_filename : str
nxml file to process
pmid : Optional[str]
pmid of this nxml file, to be added to the Evidence object of the
extracted INDRA statements
extra_annotations : Optional[dict]
Additional annotations to add to the Evidence object of all extracted
INDRA statements. Extra annotations called 'interaction' are ignored
since this is used by the processor to store the corresponding
raw ISI output.
cleanup : Optional[bool]
If True, the temporary folders created for preprocessed reading input
and output are removed. Default: True
add_grounding : Optional[bool]
If True the extracted Statements' grounding is mapped
Returns
-------
ip : indra.sources.isi.processor.IsiProcessor
A processor containing extracted Statements
"""
if extra_annotations is None:
extra_annotations = {}
# Create a temporary directory to store the proprocessed input
pp_dir = tempfile.mkdtemp('indra_isi_pp_output')
pp = IsiPreprocessor(pp_dir)
extra_annotations = {}
pp.preprocess_nxml_file(nxml_filename, pmid, extra_annotations)
# Run the ISI reader and extract statements
ip = process_preprocessed(pp)
if add_grounding:
ip.add_grounding()
if cleanup:
# Remove temporary directory with processed input
shutil.rmtree(pp_dir)
else:
logger.info('Not cleaning up %s' % pp_dir)
return ip | python | def process_nxml(nxml_filename, pmid=None, extra_annotations=None,
cleanup=True, add_grounding=True):
if extra_annotations is None:
extra_annotations = {}
# Create a temporary directory to store the proprocessed input
pp_dir = tempfile.mkdtemp('indra_isi_pp_output')
pp = IsiPreprocessor(pp_dir)
extra_annotations = {}
pp.preprocess_nxml_file(nxml_filename, pmid, extra_annotations)
# Run the ISI reader and extract statements
ip = process_preprocessed(pp)
if add_grounding:
ip.add_grounding()
if cleanup:
# Remove temporary directory with processed input
shutil.rmtree(pp_dir)
else:
logger.info('Not cleaning up %s' % pp_dir)
return ip | [
"def",
"process_nxml",
"(",
"nxml_filename",
",",
"pmid",
"=",
"None",
",",
"extra_annotations",
"=",
"None",
",",
"cleanup",
"=",
"True",
",",
"add_grounding",
"=",
"True",
")",
":",
"if",
"extra_annotations",
"is",
"None",
":",
"extra_annotations",
"=",
"{... | 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.
Parameters
----------
nxml_filename : str
nxml file to process
pmid : Optional[str]
pmid of this nxml file, to be added to the Evidence object of the
extracted INDRA statements
extra_annotations : Optional[dict]
Additional annotations to add to the Evidence object of all extracted
INDRA statements. Extra annotations called 'interaction' are ignored
since this is used by the processor to store the corresponding
raw ISI output.
cleanup : Optional[bool]
If True, the temporary folders created for preprocessed reading input
and output are removed. Default: True
add_grounding : Optional[bool]
If True the extracted Statements' grounding is mapped
Returns
-------
ip : indra.sources.isi.processor.IsiProcessor
A processor containing extracted Statements | [
"Process",
"an",
"NXML",
"file",
"using",
"the",
"ISI",
"reader"
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/isi/api.py#L58-L109 |
18,914 | sorgerlab/indra | indra/sources/isi/api.py | process_output_folder | 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
pmids : Optional[str]
PMID mapping to be added to the Evidence of the extracted INDRA
Statements
extra_annotations : Optional[dict]
Additional annotations to add to the Evidence object of all extracted
INDRA statements. Extra annotations called 'interaction' are ignored
since this is used by the processor to store the corresponding
raw ISI output.
add_grounding : Optional[bool]
If True the extracted Statements' grounding is mapped
"""
pmids = pmids if pmids is not None else {}
extra_annotations = extra_annotations if \
extra_annotations is not None else {}
ips = []
for entry in glob.glob(os.path.join(folder_path, '*.json')):
entry_key = os.path.splitext(os.path.basename(entry))[0]
# Extract the corresponding file id
pmid = pmids.get(entry_key)
extra_annotation = extra_annotations.get(entry_key)
ip = process_json_file(entry, pmid, extra_annotation, False)
ips.append(ip)
if len(ips) > 1:
for ip in ips[1:]:
ips[0].statements += ip.statements
if ips:
if add_grounding:
ips[0].add_grounding()
return ips[0]
else:
return None | python | def process_output_folder(folder_path, pmids=None, extra_annotations=None,
add_grounding=True):
pmids = pmids if pmids is not None else {}
extra_annotations = extra_annotations if \
extra_annotations is not None else {}
ips = []
for entry in glob.glob(os.path.join(folder_path, '*.json')):
entry_key = os.path.splitext(os.path.basename(entry))[0]
# Extract the corresponding file id
pmid = pmids.get(entry_key)
extra_annotation = extra_annotations.get(entry_key)
ip = process_json_file(entry, pmid, extra_annotation, False)
ips.append(ip)
if len(ips) > 1:
for ip in ips[1:]:
ips[0].statements += ip.statements
if ips:
if add_grounding:
ips[0].add_grounding()
return ips[0]
else:
return None | [
"def",
"process_output_folder",
"(",
"folder_path",
",",
"pmids",
"=",
"None",
",",
"extra_annotations",
"=",
"None",
",",
"add_grounding",
"=",
"True",
")",
":",
"pmids",
"=",
"pmids",
"if",
"pmids",
"is",
"not",
"None",
"else",
"{",
"}",
"extra_annotations... | Recursively extracts statements from all ISI output files in the
given directory and subdirectories.
Parameters
----------
folder_path : str
The directory to traverse
pmids : Optional[str]
PMID mapping to be added to the Evidence of the extracted INDRA
Statements
extra_annotations : Optional[dict]
Additional annotations to add to the Evidence object of all extracted
INDRA statements. Extra annotations called 'interaction' are ignored
since this is used by the processor to store the corresponding
raw ISI output.
add_grounding : Optional[bool]
If True the extracted Statements' grounding is mapped | [
"Recursively",
"extracts",
"statements",
"from",
"all",
"ISI",
"output",
"files",
"in",
"the",
"given",
"directory",
"and",
"subdirectories",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/isi/api.py#L196-L237 |
18,915 | sorgerlab/indra | indra/sources/isi/api.py | process_json_file | 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 document being preprocessed, or None if not
specified
extra_annotations : dict
Extra annotations to be added to each statement from this document
(can be the empty dictionary)
add_grounding : Optional[bool]
If True the extracted Statements' grounding is mapped
"""
logger.info('Extracting from %s' % file_path)
with open(file_path, 'rb') as fh:
jd = json.load(fh)
ip = IsiProcessor(jd, pmid, extra_annotations)
ip.get_statements()
if add_grounding:
ip.add_grounding()
return ip | python | def process_json_file(file_path, pmid=None, extra_annotations=None,
add_grounding=True):
logger.info('Extracting from %s' % file_path)
with open(file_path, 'rb') as fh:
jd = json.load(fh)
ip = IsiProcessor(jd, pmid, extra_annotations)
ip.get_statements()
if add_grounding:
ip.add_grounding()
return ip | [
"def",
"process_json_file",
"(",
"file_path",
",",
"pmid",
"=",
"None",
",",
"extra_annotations",
"=",
"None",
",",
"add_grounding",
"=",
"True",
")",
":",
"logger",
".",
"info",
"(",
"'Extracting from %s'",
"%",
"file_path",
")",
"with",
"open",
"(",
"file_... | 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 document being preprocessed, or None if not
specified
extra_annotations : dict
Extra annotations to be added to each statement from this document
(can be the empty dictionary)
add_grounding : Optional[bool]
If True the extracted Statements' grounding is mapped | [
"Extracts",
"statements",
"from",
"the",
"given",
"ISI",
"output",
"file",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/isi/api.py#L240-L264 |
18,916 | sorgerlab/indra | indra/sources/cwms/api.py | process_text | 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
statements attribute.
"""
xml = client.send_query(text, 'cwmsreader')
# There are actually two EKBs in the xml document. Extract the second.
first_end = xml.find('</ekb>') # End of first EKB
second_start = xml.find('<ekb', first_end) # Start of second EKB
second_end = xml.find('</ekb>', second_start) # End of second EKB
second_ekb = xml[second_start:second_end+len('</ekb>')] # second EKB
if save_xml:
with open(save_xml, 'wb') as fh:
fh.write(second_ekb.encode('utf-8'))
return process_ekb(second_ekb) | python | def process_text(text, save_xml='cwms_output.xml'):
xml = client.send_query(text, 'cwmsreader')
# There are actually two EKBs in the xml document. Extract the second.
first_end = xml.find('</ekb>') # End of first EKB
second_start = xml.find('<ekb', first_end) # Start of second EKB
second_end = xml.find('</ekb>', second_start) # End of second EKB
second_ekb = xml[second_start:second_end+len('</ekb>')] # second EKB
if save_xml:
with open(save_xml, 'wb') as fh:
fh.write(second_ekb.encode('utf-8'))
return process_ekb(second_ekb) | [
"def",
"process_text",
"(",
"text",
",",
"save_xml",
"=",
"'cwms_output.xml'",
")",
":",
"xml",
"=",
"client",
".",
"send_query",
"(",
"text",
",",
"'cwmsreader'",
")",
"# There are actually two EKBs in the xml document. Extract the second.",
"first_end",
"=",
"xml",
... | 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
statements attribute. | [
"Processes",
"text",
"using",
"the",
"CWMS",
"web",
"service",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/cwms/api.py#L11-L35 |
18,917 | sorgerlab/indra | indra/sources/cwms/api.py | process_ekb_file | 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
statements attribute.
"""
# Process EKB XML file into statements
with open(fname, 'rb') as fh:
ekb_str = fh.read().decode('utf-8')
return process_ekb(ekb_str) | python | def process_ekb_file(fname):
# Process EKB XML file into statements
with open(fname, 'rb') as fh:
ekb_str = fh.read().decode('utf-8')
return process_ekb(ekb_str) | [
"def",
"process_ekb_file",
"(",
"fname",
")",
":",
"# Process EKB XML file into statements",
"with",
"open",
"(",
"fname",
",",
"'rb'",
")",
"as",
"fh",
":",
"ekb_str",
"=",
"fh",
".",
"read",
"(",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"return",
"proces... | 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
statements attribute. | [
"Processes",
"an",
"EKB",
"file",
"produced",
"by",
"CWMS",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/cwms/api.py#L38-L55 |
18,918 | sorgerlab/indra | indra/assemblers/pysb/kappa_util.py | im_json_to_graph | 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.
"""
imap_data = im_json['influence map']['map']
# Initialize the graph
graph = MultiDiGraph()
id_node_dict = {}
# Add each node to the graph
for node_dict in imap_data['nodes']:
# There is always just one entry here with the node type e.g. "rule"
# as key, and all the node data as the value
node_type, node = list(node_dict.items())[0]
# Add the node to the graph with its label and type
attrs = {'fillcolor': '#b7d2ff' if node_type == 'rule' else '#cdffc9',
'shape': 'box' if node_type == 'rule' else 'oval',
'style': 'filled'}
graph.add_node(node['label'], node_type=node_type, **attrs)
# Save the key of the node to refer to it later
new_key = '%s%s' % (node_type, node['id'])
id_node_dict[new_key] = node['label']
def add_edges(link_list, edge_sign):
attrs = {'sign': edge_sign,
'color': 'green' if edge_sign == 1 else 'red',
'arrowhead': 'normal' if edge_sign == 1 else 'tee'}
for link_dict in link_list:
source = link_dict['source']
for target_dict in link_dict['target map']:
target = target_dict['target']
src_id = '%s%s' % list(source.items())[0]
tgt_id = '%s%s' % list(target.items())[0]
graph.add_edge(id_node_dict[src_id], id_node_dict[tgt_id],
**attrs)
# Add all the edges from the positive and negative influences
add_edges(imap_data['wake-up map'], 1)
add_edges(imap_data['inhibition map'], -1)
return graph | python | def im_json_to_graph(im_json):
imap_data = im_json['influence map']['map']
# Initialize the graph
graph = MultiDiGraph()
id_node_dict = {}
# Add each node to the graph
for node_dict in imap_data['nodes']:
# There is always just one entry here with the node type e.g. "rule"
# as key, and all the node data as the value
node_type, node = list(node_dict.items())[0]
# Add the node to the graph with its label and type
attrs = {'fillcolor': '#b7d2ff' if node_type == 'rule' else '#cdffc9',
'shape': 'box' if node_type == 'rule' else 'oval',
'style': 'filled'}
graph.add_node(node['label'], node_type=node_type, **attrs)
# Save the key of the node to refer to it later
new_key = '%s%s' % (node_type, node['id'])
id_node_dict[new_key] = node['label']
def add_edges(link_list, edge_sign):
attrs = {'sign': edge_sign,
'color': 'green' if edge_sign == 1 else 'red',
'arrowhead': 'normal' if edge_sign == 1 else 'tee'}
for link_dict in link_list:
source = link_dict['source']
for target_dict in link_dict['target map']:
target = target_dict['target']
src_id = '%s%s' % list(source.items())[0]
tgt_id = '%s%s' % list(target.items())[0]
graph.add_edge(id_node_dict[src_id], id_node_dict[tgt_id],
**attrs)
# Add all the edges from the positive and negative influences
add_edges(imap_data['wake-up map'], 1)
add_edges(imap_data['inhibition map'], -1)
return graph | [
"def",
"im_json_to_graph",
"(",
"im_json",
")",
":",
"imap_data",
"=",
"im_json",
"[",
"'influence map'",
"]",
"[",
"'map'",
"]",
"# Initialize the graph",
"graph",
"=",
"MultiDiGraph",
"(",
")",
"id_node_dict",
"=",
"{",
"}",
"# Add each node to the graph",
"for"... | 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. | [
"Return",
"networkx",
"graph",
"from",
"Kappy",
"s",
"influence",
"map",
"JSON",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/pysb/kappa_util.py#L7-L57 |
18,919 | sorgerlab/indra | indra/assemblers/pysb/kappa_util.py | cm_json_to_graph | 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.
"""
cmap_data = im_json['contact map']['map']
# Initialize the graph
graph = AGraph()
# In this loop we add sites as nodes and clusters around sites to the
# graph. We also collect edges to be added between sites later.
edges = []
for node_idx, node in enumerate(cmap_data):
sites_in_node = []
for site_idx, site in enumerate(node['node_sites']):
# We map the unique ID of the site to its name
site_key = (node_idx, site_idx)
sites_in_node.append(site_key)
graph.add_node(site_key, label=site['site_name'], style='filled',
shape='ellipse')
# Each port link is an edge from the current site to the
# specified site
if not site['site_type'] or not site['site_type'][0] == 'port':
continue
for port_link in site['site_type'][1]['port_links']:
edge = (site_key, tuple(port_link))
edges.append(edge)
graph.add_subgraph(sites_in_node,
name='cluster_%s' % node['node_type'],
label=node['node_type'])
# Finally we add the edges between the sites
for source, target in edges:
graph.add_edge(source, target)
return graph | python | def cm_json_to_graph(im_json):
cmap_data = im_json['contact map']['map']
# Initialize the graph
graph = AGraph()
# In this loop we add sites as nodes and clusters around sites to the
# graph. We also collect edges to be added between sites later.
edges = []
for node_idx, node in enumerate(cmap_data):
sites_in_node = []
for site_idx, site in enumerate(node['node_sites']):
# We map the unique ID of the site to its name
site_key = (node_idx, site_idx)
sites_in_node.append(site_key)
graph.add_node(site_key, label=site['site_name'], style='filled',
shape='ellipse')
# Each port link is an edge from the current site to the
# specified site
if not site['site_type'] or not site['site_type'][0] == 'port':
continue
for port_link in site['site_type'][1]['port_links']:
edge = (site_key, tuple(port_link))
edges.append(edge)
graph.add_subgraph(sites_in_node,
name='cluster_%s' % node['node_type'],
label=node['node_type'])
# Finally we add the edges between the sites
for source, target in edges:
graph.add_edge(source, target)
return graph | [
"def",
"cm_json_to_graph",
"(",
"im_json",
")",
":",
"cmap_data",
"=",
"im_json",
"[",
"'contact map'",
"]",
"[",
"'map'",
"]",
"# Initialize the graph",
"graph",
"=",
"AGraph",
"(",
")",
"# In this loop we add sites as nodes and clusters around sites to the",
"# graph. W... | 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. | [
"Return",
"pygraphviz",
"Agraph",
"from",
"Kappy",
"s",
"contact",
"map",
"JSON",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/pysb/kappa_util.py#L60-L104 |
18,920 | sorgerlab/indra | indra/tools/machine/gmail_client.py | fetch_email | 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 that must be decoded
raw_msg_txt = data[0][1]
# In Python3, we call message_from_bytes, but this function doesn't
# exist in Python 2.
try:
msg = email.message_from_bytes(raw_msg_txt)
except AttributeError:
msg = email.message_from_string(raw_msg_txt)
# At this point, we have a message containing bytes (not unicode)
# fields that will still need to be decoded, ideally according to the
# character set specified in the message.
return msg
else:
return None | python | def fetch_email(M, msg_id):
res, data = M.fetch(msg_id, '(RFC822)')
if res == 'OK':
# Data here is a list with 1 element containing a tuple
# whose 2nd element is a long string containing the email
# The content is a bytes that must be decoded
raw_msg_txt = data[0][1]
# In Python3, we call message_from_bytes, but this function doesn't
# exist in Python 2.
try:
msg = email.message_from_bytes(raw_msg_txt)
except AttributeError:
msg = email.message_from_string(raw_msg_txt)
# At this point, we have a message containing bytes (not unicode)
# fields that will still need to be decoded, ideally according to the
# character set specified in the message.
return msg
else:
return None | [
"def",
"fetch_email",
"(",
"M",
",",
"msg_id",
")",
":",
"res",
",",
"data",
"=",
"M",
".",
"fetch",
"(",
"msg_id",
",",
"'(RFC822)'",
")",
"if",
"res",
"==",
"'OK'",
":",
"# Data here is a list with 1 element containing a tuple",
"# whose 2nd element is a long st... | Returns the given email message as a unicode string. | [
"Returns",
"the",
"given",
"email",
"message",
"as",
"a",
"unicode",
"string",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/machine/gmail_client.py#L28-L47 |
18,921 | sorgerlab/indra | indra/tools/machine/gmail_client.py | get_headers | 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's ASCII
# only (hence unambiguous encoding), the header fields come back
# as str (unicode) in Python 3.
(header_txt, charset) = email.header.decode_header(msg[k])[0]
if charset is not None:
header_txt = header_txt.decode(charset)
headers[k] = header_txt
return headers | python | def get_headers(msg):
headers = {}
for k in msg.keys():
# decode_header decodes header but does not convert charset, so these
# may still be bytes, even in Python 3. However, if it's ASCII
# only (hence unambiguous encoding), the header fields come back
# as str (unicode) in Python 3.
(header_txt, charset) = email.header.decode_header(msg[k])[0]
if charset is not None:
header_txt = header_txt.decode(charset)
headers[k] = header_txt
return headers | [
"def",
"get_headers",
"(",
"msg",
")",
":",
"headers",
"=",
"{",
"}",
"for",
"k",
"in",
"msg",
".",
"keys",
"(",
")",
":",
"# decode_header decodes header but does not convert charset, so these",
"# may still be bytes, even in Python 3. However, if it's ASCII",
"# only (hen... | Takes email.message.Message object initialized from unicode string,
returns dict with header fields. | [
"Takes",
"email",
".",
"message",
".",
"Message",
"object",
"initialized",
"from",
"unicode",
"string",
"returns",
"dict",
"with",
"header",
"fields",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/machine/gmail_client.py#L49-L62 |
18,922 | sorgerlab/indra | indra/config.py | populate_config_dict | 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:
config_dict = {}
parser = RawConfigParser()
parser.optionxform = lambda x: x
parser.read(config_path)
sections = parser.sections()
for section in sections:
options = parser.options(section)
for option in options:
config_dict[option] = str(parser.get(section, option))
except Exception as e:
logger.warning("Could not load configuration file due to exception. "
"Only environment variable equivalents will be used.")
return None
for key in config_dict.keys():
if config_dict[key] == '':
config_dict[key] = None
elif isinstance(config_dict[key], str):
config_dict[key] = os.path.expanduser(config_dict[key])
return config_dict | python | def populate_config_dict(config_path):
try:
config_dict = {}
parser = RawConfigParser()
parser.optionxform = lambda x: x
parser.read(config_path)
sections = parser.sections()
for section in sections:
options = parser.options(section)
for option in options:
config_dict[option] = str(parser.get(section, option))
except Exception as e:
logger.warning("Could not load configuration file due to exception. "
"Only environment variable equivalents will be used.")
return None
for key in config_dict.keys():
if config_dict[key] == '':
config_dict[key] = None
elif isinstance(config_dict[key], str):
config_dict[key] = os.path.expanduser(config_dict[key])
return config_dict | [
"def",
"populate_config_dict",
"(",
"config_path",
")",
":",
"try",
":",
"config_dict",
"=",
"{",
"}",
"parser",
"=",
"RawConfigParser",
"(",
")",
"parser",
".",
"optionxform",
"=",
"lambda",
"x",
":",
"x",
"parser",
".",
"read",
"(",
"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. | [
"Load",
"the",
"configuration",
"file",
"into",
"the",
"config_file",
"dictionary"
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/config.py#L31-L58 |
18,923 | sorgerlab/indra | indra/config.py | get_config | 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 configuration value to fetch
failure_ok : Optional[bool]
If False and the configuration is missing, an IndraConfigError is
raised. If True, None is returned and no error is raised in case
of a missing configuration. Default: True
Returns
-------
value : str or None
The configuration value or None if the configuration value doesn't
exist and failure_ok is set to True.
"""
err_msg = "Key %s not in environment or config file." % key
if key in os.environ:
return os.environ[key]
elif key in CONFIG_DICT:
val = CONFIG_DICT[key]
# We interpret an empty value in the config file as a failure
if val is None and not failure_ok:
msg = 'Key %s is set to an empty value in config file.' % key
raise IndraConfigError(msg)
else:
return val
elif not failure_ok:
raise IndraConfigError(err_msg)
else:
logger.warning(err_msg)
return None | python | def get_config(key, failure_ok=True):
err_msg = "Key %s not in environment or config file." % key
if key in os.environ:
return os.environ[key]
elif key in CONFIG_DICT:
val = CONFIG_DICT[key]
# We interpret an empty value in the config file as a failure
if val is None and not failure_ok:
msg = 'Key %s is set to an empty value in config file.' % key
raise IndraConfigError(msg)
else:
return val
elif not failure_ok:
raise IndraConfigError(err_msg)
else:
logger.warning(err_msg)
return None | [
"def",
"get_config",
"(",
"key",
",",
"failure_ok",
"=",
"True",
")",
":",
"err_msg",
"=",
"\"Key %s not in environment or config file.\"",
"%",
"key",
"if",
"key",
"in",
"os",
".",
"environ",
":",
"return",
"os",
".",
"environ",
"[",
"key",
"]",
"elif",
"... | 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 configuration value to fetch
failure_ok : Optional[bool]
If False and the configuration is missing, an IndraConfigError is
raised. If True, None is returned and no error is raised in case
of a missing configuration. Default: True
Returns
-------
value : str or None
The configuration value or None if the configuration value doesn't
exist and failure_ok is set to True. | [
"Get",
"value",
"by",
"key",
"from",
"config",
"file",
"or",
"environment",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/config.py#L85-L122 |
18,924 | sorgerlab/indra | indra/util/__init__.py | read_unicode_csv_fileobj | 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.version_info[0] >= 3:
# Next, get the csv reader, with unicode delimiter and quotechar
csv_reader = csv.reader(fileobj, delimiter=delimiter,
quotechar=quotechar, quoting=quoting,
lineterminator=lineterminator)
# Now, return the (already decoded) unicode csv_reader generator
# Skip rows if necessary
for skip_ix in range(skiprows):
next(csv_reader)
for row in csv_reader:
yield row
# Python 2 version
else:
# Next, get the csv reader, passing delimiter and quotechar as
# bytestrings rather than unicode
csv_reader = csv.reader(fileobj, delimiter=delimiter.encode(encoding),
quotechar=quotechar.encode(encoding),
quoting=quoting, lineterminator=lineterminator)
# Iterate over the file and decode each string into unicode
# Skip rows if necessary
for skip_ix in range(skiprows):
next(csv_reader)
for row in csv_reader:
yield [cell.decode(encoding) for cell in row] | python | def read_unicode_csv_fileobj(fileobj, delimiter=',', quotechar='"',
quoting=csv.QUOTE_MINIMAL, lineterminator='\n',
encoding='utf-8', skiprows=0):
# Python 3 version
if sys.version_info[0] >= 3:
# Next, get the csv reader, with unicode delimiter and quotechar
csv_reader = csv.reader(fileobj, delimiter=delimiter,
quotechar=quotechar, quoting=quoting,
lineterminator=lineterminator)
# Now, return the (already decoded) unicode csv_reader generator
# Skip rows if necessary
for skip_ix in range(skiprows):
next(csv_reader)
for row in csv_reader:
yield row
# Python 2 version
else:
# Next, get the csv reader, passing delimiter and quotechar as
# bytestrings rather than unicode
csv_reader = csv.reader(fileobj, delimiter=delimiter.encode(encoding),
quotechar=quotechar.encode(encoding),
quoting=quoting, lineterminator=lineterminator)
# Iterate over the file and decode each string into unicode
# Skip rows if necessary
for skip_ix in range(skiprows):
next(csv_reader)
for row in csv_reader:
yield [cell.decode(encoding) for cell in row] | [
"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. | [
"fileobj",
"can",
"be",
"a",
"StringIO",
"in",
"Py3",
"but",
"should",
"be",
"a",
"BytesIO",
"in",
"Py2",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/util/__init__.py#L113-L141 |
18,925 | sorgerlab/indra | indra/util/__init__.py | fast_deepcopy | 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)
return obj_new | python | def fast_deepcopy(obj):
with BytesIO() as buf:
pickle.dump(obj, buf)
buf.seek(0)
obj_new = pickle.load(buf)
return obj_new | [
"def",
"fast_deepcopy",
"(",
"obj",
")",
":",
"with",
"BytesIO",
"(",
")",
"as",
"buf",
":",
"pickle",
".",
"dump",
"(",
"obj",
",",
"buf",
")",
"buf",
".",
"seek",
"(",
"0",
")",
"obj_new",
"=",
"pickle",
".",
"load",
"(",
"buf",
")",
"return",
... | 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. | [
"This",
"is",
"a",
"faster",
"implementation",
"of",
"deepcopy",
"via",
"pickle",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/util/__init__.py#L198-L208 |
18,926 | sorgerlab/indra | indra/util/__init__.py | batch_iter | 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'].
Parameters
----------
iterator : iterable
A python object which is iterable.
batch_size : int
The size of batches you wish to produce from the iterator.
return_func : executable or None
Pass a function that takes a generator and returns an iterable (e.g.
`list` or `set`). If None, a generator will be returned.
padding : anything
This is used internally to ensure that the remainder of the list is
included. This MUST NOT be a valid element of the iterator.
Returns
-------
An iterator over lists or generators, depending on `return_lists`.
"""
for batch in zip_longest(*[iter(iterator)]*batch_size, fillvalue=padding):
gen = (thing for thing in batch if thing is not padding)
if return_func is None:
yield gen
else:
yield return_func(gen) | python | def batch_iter(iterator, batch_size, return_func=None, padding=None):
for batch in zip_longest(*[iter(iterator)]*batch_size, fillvalue=padding):
gen = (thing for thing in batch if thing is not padding)
if return_func is None:
yield gen
else:
yield return_func(gen) | [
"def",
"batch_iter",
"(",
"iterator",
",",
"batch_size",
",",
"return_func",
"=",
"None",
",",
"padding",
"=",
"None",
")",
":",
"for",
"batch",
"in",
"zip_longest",
"(",
"*",
"[",
"iter",
"(",
"iterator",
")",
"]",
"*",
"batch_size",
",",
"fillvalue",
... | 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'].
Parameters
----------
iterator : iterable
A python object which is iterable.
batch_size : int
The size of batches you wish to produce from the iterator.
return_func : executable or None
Pass a function that takes a generator and returns an iterable (e.g.
`list` or `set`). If None, a generator will be returned.
padding : anything
This is used internally to ensure that the remainder of the list is
included. This MUST NOT be a valid element of the iterator.
Returns
-------
An iterator over lists or generators, depending on `return_lists`. | [
"Break",
"an",
"iterable",
"into",
"batches",
"of",
"size",
"batch_size"
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/util/__init__.py#L227-L256 |
18,927 | sorgerlab/indra | indra/tools/reading/run_drum_reading.py | read_pmid_sentences | 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
Keyword arguments passed directly to the DrumReader. Typical
things to specify are `host` and `port`. If `run_drum` is specified
as True, this process will internally run the DRUM reading system
as a subprocess. Otherwise, DRUM is expected to be running
independently.
Returns
-------
all_statements : list[indra.statement.Statement]
A list of INDRA Statements resulting from the reading
"""
def _set_pmid(statements, pmid):
for stmt in statements:
for evidence in stmt.evidence:
evidence.pmid = pmid
# See if we need to start DRUM as a subprocess
run_drum = drum_args.get('run_drum', False)
drum_process = None
all_statements = {}
# Iterate over all the keys and sentences to read
for pmid, sentences in pmid_sentences.items():
logger.info('================================')
logger.info('Processing %d sentences for %s' % (len(sentences), pmid))
ts = time.time()
# Make a DrumReader instance
drum_args['name'] = 'DrumReader%s' % pmid
dr = DrumReader(**drum_args)
time.sleep(3)
# If there is no DRUM process set yet, we get the one that was
# just started by the DrumReader
if run_drum and drum_process is None:
drum_args.pop('run_drum', None)
drum_process = dr.drum_system
# By setting this, we ensuer that the reference to the
# process is passed in to all future DrumReaders
drum_args['drum_system'] = drum_process
# Now read each sentence for this key
for sentence in sentences:
dr.read_text(sentence)
# Start receiving results and exit when done
try:
dr.start()
except SystemExit:
pass
statements = []
# Process all the extractions into INDRA Statements
for extraction in dr.extractions:
# Sometimes we get nothing back
if not extraction:
continue
tp = process_xml(extraction)
statements += tp.statements
# Set the PMIDs for the evidences of the Statements
_set_pmid(statements, pmid)
te = time.time()
logger.info('Reading took %d seconds and produced %d Statements.' %
(te-ts, len(statements)))
all_statements[pmid] = statements
# If we were running a DRUM process, we should kill it
if drum_process and dr.drum_system:
dr._kill_drum()
return all_statements | python | def read_pmid_sentences(pmid_sentences, **drum_args):
def _set_pmid(statements, pmid):
for stmt in statements:
for evidence in stmt.evidence:
evidence.pmid = pmid
# See if we need to start DRUM as a subprocess
run_drum = drum_args.get('run_drum', False)
drum_process = None
all_statements = {}
# Iterate over all the keys and sentences to read
for pmid, sentences in pmid_sentences.items():
logger.info('================================')
logger.info('Processing %d sentences for %s' % (len(sentences), pmid))
ts = time.time()
# Make a DrumReader instance
drum_args['name'] = 'DrumReader%s' % pmid
dr = DrumReader(**drum_args)
time.sleep(3)
# If there is no DRUM process set yet, we get the one that was
# just started by the DrumReader
if run_drum and drum_process is None:
drum_args.pop('run_drum', None)
drum_process = dr.drum_system
# By setting this, we ensuer that the reference to the
# process is passed in to all future DrumReaders
drum_args['drum_system'] = drum_process
# Now read each sentence for this key
for sentence in sentences:
dr.read_text(sentence)
# Start receiving results and exit when done
try:
dr.start()
except SystemExit:
pass
statements = []
# Process all the extractions into INDRA Statements
for extraction in dr.extractions:
# Sometimes we get nothing back
if not extraction:
continue
tp = process_xml(extraction)
statements += tp.statements
# Set the PMIDs for the evidences of the Statements
_set_pmid(statements, pmid)
te = time.time()
logger.info('Reading took %d seconds and produced %d Statements.' %
(te-ts, len(statements)))
all_statements[pmid] = statements
# If we were running a DRUM process, we should kill it
if drum_process and dr.drum_system:
dr._kill_drum()
return all_statements | [
"def",
"read_pmid_sentences",
"(",
"pmid_sentences",
",",
"*",
"*",
"drum_args",
")",
":",
"def",
"_set_pmid",
"(",
"statements",
",",
"pmid",
")",
":",
"for",
"stmt",
"in",
"statements",
":",
"for",
"evidence",
"in",
"stmt",
".",
"evidence",
":",
"evidenc... | 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
Keyword arguments passed directly to the DrumReader. Typical
things to specify are `host` and `port`. If `run_drum` is specified
as True, this process will internally run the DRUM reading system
as a subprocess. Otherwise, DRUM is expected to be running
independently.
Returns
-------
all_statements : list[indra.statement.Statement]
A list of INDRA Statements resulting from the reading | [
"Read",
"sentences",
"from",
"a",
"PMID",
"-",
"keyed",
"dictonary",
"and",
"return",
"all",
"Statements"
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/reading/run_drum_reading.py#L14-L86 |
18,928 | sorgerlab/indra | indra/sources/biopax/pathway_commons_client.py | graph_query | 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 to perform. Currently 3 options are
implemented, 'neighborhood', 'pathsbetween' and 'pathsfromto'.
source : list[str]
A list of gene names which are the source set for the graph query.
target : Optional[list[str]]
A list of gene names which are the target set for the graph query.
Only needed for 'pathsfromto' queries.
neighbor_limit : Optional[int]
This limits the length of the longest path considered in
the graph query. Default: 1
Returns
-------
model : org.biopax.paxtools.model.Model
A BioPAX model (java object).
"""
default_databases = ['wp', 'smpdb', 'reconx', 'reactome', 'psp', 'pid',
'panther', 'netpath', 'msigdb', 'mirtarbase', 'kegg',
'intact', 'inoh', 'humancyc', 'hprd',
'drugbank', 'dip', 'corum']
if not database_filter:
query_databases = default_databases
else:
query_databases = database_filter
# excluded: ctd
params = {}
params['format'] = 'BIOPAX'
params['organism'] = '9606'
params['datasource'] = query_databases
# Get the "kind" string
kind_str = kind.lower()
if kind not in ['neighborhood', 'pathsbetween', 'pathsfromto']:
logger.warn('Invalid query type %s' % kind_str)
return None
params['kind'] = kind_str
# Get the source string
if isinstance(source, basestring):
source_str = source
else:
source_str = ','.join(source)
params['source'] = source_str
try:
neighbor_limit = int(neighbor_limit)
params['limit'] = neighbor_limit
except (TypeError, ValueError):
logger.warn('Invalid neighborhood limit %s' % neighbor_limit)
return None
if target is not None:
if isinstance(target, basestring):
target_str = target
else:
target_str = ','.join(target)
params['target'] = target_str
logger.info('Sending Pathway Commons query with parameters: ')
for k, v in params.items():
logger.info(' %s: %s' % (k, v))
logger.info('Sending Pathway Commons query...')
res = requests.get(pc2_url + 'graph', params=params)
if not res.status_code == 200:
logger.error('Response is HTTP code %d.' % res.status_code)
if res.status_code == 500:
logger.error('Note: HTTP code 500 can mean empty '
'results for a valid query.')
return None
# We don't decode to Unicode here because owl_str_to_model expects
# a byte stream
model = owl_str_to_model(res.content)
if model is not None:
logger.info('Pathway Commons query returned a model...')
return model | python | def graph_query(kind, source, target=None, neighbor_limit=1,
database_filter=None):
default_databases = ['wp', 'smpdb', 'reconx', 'reactome', 'psp', 'pid',
'panther', 'netpath', 'msigdb', 'mirtarbase', 'kegg',
'intact', 'inoh', 'humancyc', 'hprd',
'drugbank', 'dip', 'corum']
if not database_filter:
query_databases = default_databases
else:
query_databases = database_filter
# excluded: ctd
params = {}
params['format'] = 'BIOPAX'
params['organism'] = '9606'
params['datasource'] = query_databases
# Get the "kind" string
kind_str = kind.lower()
if kind not in ['neighborhood', 'pathsbetween', 'pathsfromto']:
logger.warn('Invalid query type %s' % kind_str)
return None
params['kind'] = kind_str
# Get the source string
if isinstance(source, basestring):
source_str = source
else:
source_str = ','.join(source)
params['source'] = source_str
try:
neighbor_limit = int(neighbor_limit)
params['limit'] = neighbor_limit
except (TypeError, ValueError):
logger.warn('Invalid neighborhood limit %s' % neighbor_limit)
return None
if target is not None:
if isinstance(target, basestring):
target_str = target
else:
target_str = ','.join(target)
params['target'] = target_str
logger.info('Sending Pathway Commons query with parameters: ')
for k, v in params.items():
logger.info(' %s: %s' % (k, v))
logger.info('Sending Pathway Commons query...')
res = requests.get(pc2_url + 'graph', params=params)
if not res.status_code == 200:
logger.error('Response is HTTP code %d.' % res.status_code)
if res.status_code == 500:
logger.error('Note: HTTP code 500 can mean empty '
'results for a valid query.')
return None
# We don't decode to Unicode here because owl_str_to_model expects
# a byte stream
model = owl_str_to_model(res.content)
if model is not None:
logger.info('Pathway Commons query returned a model...')
return model | [
"def",
"graph_query",
"(",
"kind",
",",
"source",
",",
"target",
"=",
"None",
",",
"neighbor_limit",
"=",
"1",
",",
"database_filter",
"=",
"None",
")",
":",
"default_databases",
"=",
"[",
"'wp'",
",",
"'smpdb'",
",",
"'reconx'",
",",
"'reactome'",
",",
... | 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 to perform. Currently 3 options are
implemented, 'neighborhood', 'pathsbetween' and 'pathsfromto'.
source : list[str]
A list of gene names which are the source set for the graph query.
target : Optional[list[str]]
A list of gene names which are the target set for the graph query.
Only needed for 'pathsfromto' queries.
neighbor_limit : Optional[int]
This limits the length of the longest path considered in
the graph query. Default: 1
Returns
-------
model : org.biopax.paxtools.model.Model
A BioPAX model (java object). | [
"Perform",
"a",
"graph",
"query",
"on",
"PathwayCommons",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/biopax/pathway_commons_client.py#L17-L99 |
18,929 | sorgerlab/indra | indra/sources/biopax/pathway_commons_client.py | owl_str_to_model | 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 = autoclass('org.biopax.paxtools.io.SimpleIOHandler')
io = io_class(autoclass('org.biopax.paxtools.model.BioPAXLevel').L3)
bais = autoclass('java.io.ByteArrayInputStream')
scs = autoclass('java.nio.charset.StandardCharsets')
jstr = autoclass('java.lang.String')
istream = bais(owl_str)
biopax_model = io.convertFromOWL(istream)
return biopax_model | python | def owl_str_to_model(owl_str):
io_class = autoclass('org.biopax.paxtools.io.SimpleIOHandler')
io = io_class(autoclass('org.biopax.paxtools.model.BioPAXLevel').L3)
bais = autoclass('java.io.ByteArrayInputStream')
scs = autoclass('java.nio.charset.StandardCharsets')
jstr = autoclass('java.lang.String')
istream = bais(owl_str)
biopax_model = io.convertFromOWL(istream)
return biopax_model | [
"def",
"owl_str_to_model",
"(",
"owl_str",
")",
":",
"io_class",
"=",
"autoclass",
"(",
"'org.biopax.paxtools.io.SimpleIOHandler'",
")",
"io",
"=",
"io_class",
"(",
"autoclass",
"(",
"'org.biopax.paxtools.model.BioPAXLevel'",
")",
".",
"L3",
")",
"bais",
"=",
"autoc... | 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). | [
"Return",
"a",
"BioPAX",
"model",
"object",
"from",
"an",
"OWL",
"string",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/biopax/pathway_commons_client.py#L101-L121 |
18,930 | sorgerlab/indra | indra/sources/biopax/pathway_commons_client.py | owl_to_model | 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_class = autoclass('org.biopax.paxtools.io.SimpleIOHandler')
io = io_class(autoclass('org.biopax.paxtools.model.BioPAXLevel').L3)
try:
file_is = autoclass('java.io.FileInputStream')(fname)
except JavaException:
logger.error('Could not open data file %s' % fname)
return
try:
biopax_model = io.convertFromOWL(file_is)
except JavaException as e:
logger.error('Could not convert data file %s to BioPax model' % fname)
logger.error(e)
return
file_is.close()
return biopax_model | python | def owl_to_model(fname):
io_class = autoclass('org.biopax.paxtools.io.SimpleIOHandler')
io = io_class(autoclass('org.biopax.paxtools.model.BioPAXLevel').L3)
try:
file_is = autoclass('java.io.FileInputStream')(fname)
except JavaException:
logger.error('Could not open data file %s' % fname)
return
try:
biopax_model = io.convertFromOWL(file_is)
except JavaException as e:
logger.error('Could not convert data file %s to BioPax model' % fname)
logger.error(e)
return
file_is.close()
return biopax_model | [
"def",
"owl_to_model",
"(",
"fname",
")",
":",
"io_class",
"=",
"autoclass",
"(",
"'org.biopax.paxtools.io.SimpleIOHandler'",
")",
"io",
"=",
"io_class",
"(",
"autoclass",
"(",
"'org.biopax.paxtools.model.BioPAXLevel'",
")",
".",
"L3",
")",
"try",
":",
"file_is",
... | 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). | [
"Return",
"a",
"BioPAX",
"model",
"object",
"from",
"an",
"OWL",
"file",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/biopax/pathway_commons_client.py#L123-L153 |
18,931 | sorgerlab/indra | indra/sources/biopax/pathway_commons_client.py | model_to_owl | 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.paxtools.io.SimpleIOHandler')
io = io_class(autoclass('org.biopax.paxtools.model.BioPAXLevel').L3)
try:
fileOS = autoclass('java.io.FileOutputStream')(fname)
except JavaException:
logger.error('Could not open data file %s' % fname)
return
l3_factory = autoclass('org.biopax.paxtools.model.BioPAXLevel').L3.getDefaultFactory()
model_out = l3_factory.createModel()
for r in model.getObjects().toArray():
model_out.add(r)
io.convertToOWL(model_out, fileOS)
fileOS.close() | python | def model_to_owl(model, fname):
io_class = autoclass('org.biopax.paxtools.io.SimpleIOHandler')
io = io_class(autoclass('org.biopax.paxtools.model.BioPAXLevel').L3)
try:
fileOS = autoclass('java.io.FileOutputStream')(fname)
except JavaException:
logger.error('Could not open data file %s' % fname)
return
l3_factory = autoclass('org.biopax.paxtools.model.BioPAXLevel').L3.getDefaultFactory()
model_out = l3_factory.createModel()
for r in model.getObjects().toArray():
model_out.add(r)
io.convertToOWL(model_out, fileOS)
fileOS.close() | [
"def",
"model_to_owl",
"(",
"model",
",",
"fname",
")",
":",
"io_class",
"=",
"autoclass",
"(",
"'org.biopax.paxtools.io.SimpleIOHandler'",
")",
"io",
"=",
"io_class",
"(",
"autoclass",
"(",
"'org.biopax.paxtools.model.BioPAXLevel'",
")",
".",
"L3",
")",
"try",
":... | 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. | [
"Save",
"a",
"BioPAX",
"model",
"object",
"as",
"an",
"OWL",
"file",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/biopax/pathway_commons_client.py#L155-L179 |
18,932 | sorgerlab/indra | indra/assemblers/cyjs/assembler.py | CyJSAssembler.make_model | 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 with identical incoming and outgoing edges
are grouped and the corresponding edges are merged.
Returns
-------
cyjs_str : str
The json serialized Cytoscape JS model.
"""
for stmt in self.statements:
if isinstance(stmt, RegulateActivity):
self._add_regulate_activity(stmt)
elif isinstance(stmt, RegulateAmount):
self._add_regulate_amount(stmt)
elif isinstance(stmt, Modification):
self._add_modification(stmt)
elif isinstance(stmt, SelfModification):
self._add_selfmodification(stmt)
elif isinstance(stmt, Gef):
self._add_gef(stmt)
elif isinstance(stmt, Gap):
self._add_gap(stmt)
elif isinstance(stmt, Complex):
self._add_complex(stmt)
else:
logger.warning('Unhandled statement type: %s' %
stmt.__class__.__name__)
if kwargs.get('grouping'):
self._group_nodes()
self._group_edges()
return self.print_cyjs_graph() | python | def make_model(self, *args, **kwargs):
for stmt in self.statements:
if isinstance(stmt, RegulateActivity):
self._add_regulate_activity(stmt)
elif isinstance(stmt, RegulateAmount):
self._add_regulate_amount(stmt)
elif isinstance(stmt, Modification):
self._add_modification(stmt)
elif isinstance(stmt, SelfModification):
self._add_selfmodification(stmt)
elif isinstance(stmt, Gef):
self._add_gef(stmt)
elif isinstance(stmt, Gap):
self._add_gap(stmt)
elif isinstance(stmt, Complex):
self._add_complex(stmt)
else:
logger.warning('Unhandled statement type: %s' %
stmt.__class__.__name__)
if kwargs.get('grouping'):
self._group_nodes()
self._group_edges()
return self.print_cyjs_graph() | [
"def",
"make_model",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"stmt",
"in",
"self",
".",
"statements",
":",
"if",
"isinstance",
"(",
"stmt",
",",
"RegulateActivity",
")",
":",
"self",
".",
"_add_regulate_activity",
"(",
... | 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 with identical incoming and outgoing edges
are grouped and the corresponding edges are merged.
Returns
-------
cyjs_str : str
The json serialized Cytoscape JS model. | [
"Assemble",
"a",
"Cytoscape",
"JS",
"network",
"from",
"INDRA",
"Statements",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/cyjs/assembler.py#L69-L107 |
18,933 | sorgerlab/indra | indra/assemblers/cyjs/assembler.py | CyJSAssembler.get_gene_names | 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())
else:
if node['data']['name'].startswith('Group'):
continue
gene_names.append(node['data']['name'])
self._gene_names = gene_names | python | def get_gene_names(self):
# Collect all gene names in network
gene_names = []
for node in self._nodes:
members = node['data'].get('members')
if members:
gene_names += list(members.keys())
else:
if node['data']['name'].startswith('Group'):
continue
gene_names.append(node['data']['name'])
self._gene_names = gene_names | [
"def",
"get_gene_names",
"(",
"self",
")",
":",
"# Collect all gene names in network",
"gene_names",
"=",
"[",
"]",
"for",
"node",
"in",
"self",
".",
"_nodes",
":",
"members",
"=",
"node",
"[",
"'data'",
"]",
".",
"get",
"(",
"'members'",
")",
"if",
"membe... | Gather gene names of all nodes and node members | [
"Gather",
"gene",
"names",
"of",
"all",
"nodes",
"and",
"node",
"members"
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/cyjs/assembler.py#L109-L121 |
18,934 | sorgerlab/indra | indra/assemblers/cyjs/assembler.py | CyJSAssembler.set_CCLE_context | 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 = \
context_client.get_mutations(self._gene_names, cell_types)
# Make a dict of presence/absence of mutations
muts = {cell_line: {} for cell_line in cell_types}
for cell_line, entries in mut_values.items():
if entries is not None:
for gene, mutations in entries.items():
if mutations:
muts[cell_line][gene] = 1
else:
muts[cell_line][gene] = 0
# Create bins for the exp values
# because colorbrewer only does 3-9 bins and I don't feel like
# reinventing color scheme theory, this will only bin 3-9 bins
def bin_exp(expression_dict):
d = expression_dict
exp_values = []
for line in d:
for gene in d[line]:
val = d[line][gene]
if val is not None:
exp_values.append(val)
thr_dict = {}
for n_bins in range(3, 10):
bin_thr = np.histogram(np.log10(exp_values), n_bins)[1][1:]
thr_dict[n_bins] = bin_thr
# this dict isn't yet binned, that happens in the loop
binned_dict = {x: deepcopy(expression_dict) for x in range(3, 10)}
for n_bins in binned_dict:
for line in binned_dict[n_bins]:
for gene in binned_dict[n_bins][line]:
# last bin is reserved for None
if binned_dict[n_bins][line][gene] is None:
binned_dict[n_bins][line][gene] = n_bins
else:
val = np.log10(binned_dict[n_bins][line][gene])
for thr_idx, thr in enumerate(thr_dict[n_bins]):
if val <= thr:
binned_dict[n_bins][line][gene] = thr_idx
break
return binned_dict
binned_exp = bin_exp(exp_values)
context = {'bin_expression': binned_exp,
'mutation': muts}
self._context['CCLE'] = context | python | def set_CCLE_context(self, cell_types):
self.get_gene_names()
# Get expression and mutations from context client
exp_values = \
context_client.get_protein_expression(self._gene_names, cell_types)
mut_values = \
context_client.get_mutations(self._gene_names, cell_types)
# Make a dict of presence/absence of mutations
muts = {cell_line: {} for cell_line in cell_types}
for cell_line, entries in mut_values.items():
if entries is not None:
for gene, mutations in entries.items():
if mutations:
muts[cell_line][gene] = 1
else:
muts[cell_line][gene] = 0
# Create bins for the exp values
# because colorbrewer only does 3-9 bins and I don't feel like
# reinventing color scheme theory, this will only bin 3-9 bins
def bin_exp(expression_dict):
d = expression_dict
exp_values = []
for line in d:
for gene in d[line]:
val = d[line][gene]
if val is not None:
exp_values.append(val)
thr_dict = {}
for n_bins in range(3, 10):
bin_thr = np.histogram(np.log10(exp_values), n_bins)[1][1:]
thr_dict[n_bins] = bin_thr
# this dict isn't yet binned, that happens in the loop
binned_dict = {x: deepcopy(expression_dict) for x in range(3, 10)}
for n_bins in binned_dict:
for line in binned_dict[n_bins]:
for gene in binned_dict[n_bins][line]:
# last bin is reserved for None
if binned_dict[n_bins][line][gene] is None:
binned_dict[n_bins][line][gene] = n_bins
else:
val = np.log10(binned_dict[n_bins][line][gene])
for thr_idx, thr in enumerate(thr_dict[n_bins]):
if val <= thr:
binned_dict[n_bins][line][gene] = thr_idx
break
return binned_dict
binned_exp = bin_exp(exp_values)
context = {'bin_expression': binned_exp,
'mutation': muts}
self._context['CCLE'] = context | [
"def",
"set_CCLE_context",
"(",
"self",
",",
"cell_types",
")",
":",
"self",
".",
"get_gene_names",
"(",
")",
"# Get expression and mutations from context client",
"exp_values",
"=",
"context_client",
".",
"get_protein_expression",
"(",
"self",
".",
"_gene_names",
",",
... | Set context of all nodes and node members from CCLE. | [
"Set",
"context",
"of",
"all",
"nodes",
"and",
"node",
"members",
"from",
"CCLE",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/cyjs/assembler.py#L123-L177 |
18,935 | sorgerlab/indra | indra/assemblers/cyjs/assembler.py | CyJSAssembler.print_cyjs_graph | 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 = json.dumps(cyjs_dict, indent=1, sort_keys=True)
return cyjs_str | python | def print_cyjs_graph(self):
cyjs_dict = {'edges': self._edges, 'nodes': self._nodes}
cyjs_str = json.dumps(cyjs_dict, indent=1, sort_keys=True)
return cyjs_str | [
"def",
"print_cyjs_graph",
"(",
"self",
")",
":",
"cyjs_dict",
"=",
"{",
"'edges'",
":",
"self",
".",
"_edges",
",",
"'nodes'",
":",
"self",
".",
"_nodes",
"}",
"cyjs_str",
"=",
"json",
".",
"dumps",
"(",
"cyjs_dict",
",",
"indent",
"=",
"1",
",",
"s... | Return the assembled Cytoscape JS network as a json string.
Returns
-------
cyjs_str : str
A json string representation of the Cytoscape JS network. | [
"Return",
"the",
"assembled",
"Cytoscape",
"JS",
"network",
"as",
"a",
"json",
"string",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/cyjs/assembler.py#L179-L189 |
18,936 | sorgerlab/indra | indra/assemblers/cyjs/assembler.py | CyJSAssembler.print_cyjs_context | 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_expression' : {'cell_line' : {'gene1':'val1'} }
}}
"""
context = self._context
context_str = json.dumps(context, indent=1, sort_keys=True)
return context_str | python | def print_cyjs_context(self):
context = self._context
context_str = json.dumps(context, indent=1, sort_keys=True)
return context_str | [
"def",
"print_cyjs_context",
"(",
"self",
")",
":",
"context",
"=",
"self",
".",
"_context",
"context_str",
"=",
"json",
".",
"dumps",
"(",
"context",
",",
"indent",
"=",
"1",
",",
"sort_keys",
"=",
"True",
")",
"return",
"context_str"
] | Return a list of node names and their respective context.
Returns
-------
cyjs_str_context : str
A json string of the context dictionary. e.g. -
{'CCLE' : {'bin_expression' : {'cell_line1' : {'gene1':'val1'} },
'bin_expression' : {'cell_line' : {'gene1':'val1'} }
}} | [
"Return",
"a",
"list",
"of",
"node",
"names",
"and",
"their",
"respective",
"context",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/cyjs/assembler.py#L191-L204 |
18,937 | sorgerlab/indra | indra/assemblers/cyjs/assembler.py | CyJSAssembler.save_json | 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
----------
fname_prefix : Optional[str]
The prefix of the files to save the Cytoscape JS network and
context to.
Default: model
"""
cyjs_str = self.print_cyjs_graph()
# outputs the graph
with open(fname_prefix + '.json', 'wb') as fh:
fh.write(cyjs_str.encode('utf-8'))
# outputs the context of graph nodes
context_str = self.print_cyjs_context()
with open(fname_prefix + '_context.json', 'wb') as fh:
fh.write(context_str.encode('utf-8')) | python | def save_json(self, fname_prefix='model'):
cyjs_str = self.print_cyjs_graph()
# outputs the graph
with open(fname_prefix + '.json', 'wb') as fh:
fh.write(cyjs_str.encode('utf-8'))
# outputs the context of graph nodes
context_str = self.print_cyjs_context()
with open(fname_prefix + '_context.json', 'wb') as fh:
fh.write(context_str.encode('utf-8')) | [
"def",
"save_json",
"(",
"self",
",",
"fname_prefix",
"=",
"'model'",
")",
":",
"cyjs_str",
"=",
"self",
".",
"print_cyjs_graph",
"(",
")",
"# outputs the graph",
"with",
"open",
"(",
"fname_prefix",
"+",
"'.json'",
",",
"'wb'",
")",
"as",
"fh",
":",
"fh",... | 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
----------
fname_prefix : Optional[str]
The prefix of the files to save the Cytoscape JS network and
context to.
Default: model | [
"Save",
"the",
"assembled",
"Cytoscape",
"JS",
"network",
"in",
"a",
"json",
"file",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/cyjs/assembler.py#L206-L227 |
18,938 | sorgerlab/indra | indra/assemblers/cyjs/assembler.py | CyJSAssembler.save_model | 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 = json.dumps(self._exp_colorscale)
mut_colorscale_str = json.dumps(self._mut_colorscale)
cyjs_dict = {'edges': self._edges, 'nodes': self._nodes}
model_str = json.dumps(cyjs_dict, indent=1, sort_keys=True)
model_dict = {'exp_colorscale_str': exp_colorscale_str,
'mut_colorscale_str': mut_colorscale_str,
'model_elements_str': model_str}
s = ''
s += 'var exp_colorscale = %s;\n' % model_dict['exp_colorscale_str']
s += 'var mut_colorscale = %s;\n' % model_dict['mut_colorscale_str']
s += 'var model_elements = %s;\n' % model_dict['model_elements_str']
with open(fname, 'wb') as fh:
fh.write(s.encode('utf-8')) | python | def save_model(self, fname='model.js'):
exp_colorscale_str = json.dumps(self._exp_colorscale)
mut_colorscale_str = json.dumps(self._mut_colorscale)
cyjs_dict = {'edges': self._edges, 'nodes': self._nodes}
model_str = json.dumps(cyjs_dict, indent=1, sort_keys=True)
model_dict = {'exp_colorscale_str': exp_colorscale_str,
'mut_colorscale_str': mut_colorscale_str,
'model_elements_str': model_str}
s = ''
s += 'var exp_colorscale = %s;\n' % model_dict['exp_colorscale_str']
s += 'var mut_colorscale = %s;\n' % model_dict['mut_colorscale_str']
s += 'var model_elements = %s;\n' % model_dict['model_elements_str']
with open(fname, 'wb') as fh:
fh.write(s.encode('utf-8')) | [
"def",
"save_model",
"(",
"self",
",",
"fname",
"=",
"'model.js'",
")",
":",
"exp_colorscale_str",
"=",
"json",
".",
"dumps",
"(",
"self",
".",
"_exp_colorscale",
")",
"mut_colorscale_str",
"=",
"json",
".",
"dumps",
"(",
"self",
".",
"_mut_colorscale",
")",... | 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 | [
"Save",
"the",
"assembled",
"Cytoscape",
"JS",
"network",
"in",
"a",
"js",
"file",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/cyjs/assembler.py#L229-L250 |
18,939 | sorgerlab/indra | indra/assemblers/cyjs/assembler.py | CyJSAssembler._get_edge_dict | 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 = e['data']
key = tuple([data['i'], data['source'],
data['target'], data['polarity']])
edge_dict[key] = data['id']
return edge_dict | python | def _get_edge_dict(self):
edge_dict = collections.defaultdict(lambda: [])
if len(self._edges) > 0:
for e in self._edges:
data = e['data']
key = tuple([data['i'], data['source'],
data['target'], data['polarity']])
edge_dict[key] = data['id']
return edge_dict | [
"def",
"_get_edge_dict",
"(",
"self",
")",
":",
"edge_dict",
"=",
"collections",
".",
"defaultdict",
"(",
"lambda",
":",
"[",
"]",
")",
"if",
"len",
"(",
"self",
".",
"_edges",
")",
">",
"0",
":",
"for",
"e",
"in",
"self",
".",
"_edges",
":",
"data... | Return a dict of edges.
Keyed tuples of (i, source, target, polarity)
with lists of edge ids [id1, id2, ...] | [
"Return",
"a",
"dict",
"of",
"edges",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/cyjs/assembler.py#L282-L295 |
18,940 | sorgerlab/indra | indra/assemblers/cyjs/assembler.py | CyJSAssembler._get_node_key | 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 | def _get_node_key(self, node_dict_item):
s = tuple(sorted(node_dict_item['sources']))
t = tuple(sorted(node_dict_item['targets']))
return (s, t) | [
"def",
"_get_node_key",
"(",
"self",
",",
"node_dict_item",
")",
":",
"s",
"=",
"tuple",
"(",
"sorted",
"(",
"node_dict_item",
"[",
"'sources'",
"]",
")",
")",
"t",
"=",
"tuple",
"(",
"sorted",
"(",
"node_dict_item",
"[",
"'targets'",
"]",
")",
")",
"r... | Return a tuple of sorted sources and targets given a node dict. | [
"Return",
"a",
"tuple",
"of",
"sorted",
"sources",
"and",
"targets",
"given",
"a",
"node",
"dict",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/cyjs/assembler.py#L360-L364 |
18,941 | sorgerlab/indra | indra/assemblers/cyjs/assembler.py | CyJSAssembler._get_node_groups | 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
(i, polarity, source) edge of the node. node_dict is then processed
by _get_node_key() which returns a tuple of (s,t) where s,t are
sorted tuples of the ids for the source and target nodes. (s,t) is
then used as a key in node_key_dict where the values are the node
ids. node_groups is restricted to groups greater than 1 node.
"""
node_dict = {node['data']['id']: {'sources': [], 'targets': []}
for node in self._nodes}
for edge in self._edges:
# Add edge as a source for its target node
edge_data = (edge['data']['i'], edge['data']['polarity'],
edge['data']['source'])
node_dict[edge['data']['target']]['sources'].append(edge_data)
# Add edge as target for its source node
edge_data = (edge['data']['i'], edge['data']['polarity'],
edge['data']['target'])
node_dict[edge['data']['source']]['targets'].append(edge_data)
# Make a dictionary of nodes based on source/target as a key
node_key_dict = collections.defaultdict(lambda: [])
for node_id, node_d in node_dict.items():
key = self._get_node_key(node_d)
node_key_dict[key].append(node_id)
# Constrain the groups to ones that have more than 1 member
node_groups = [g for g in node_key_dict.values() if (len(g) > 1)]
return node_groups | python | def _get_node_groups(self):
node_dict = {node['data']['id']: {'sources': [], 'targets': []}
for node in self._nodes}
for edge in self._edges:
# Add edge as a source for its target node
edge_data = (edge['data']['i'], edge['data']['polarity'],
edge['data']['source'])
node_dict[edge['data']['target']]['sources'].append(edge_data)
# Add edge as target for its source node
edge_data = (edge['data']['i'], edge['data']['polarity'],
edge['data']['target'])
node_dict[edge['data']['source']]['targets'].append(edge_data)
# Make a dictionary of nodes based on source/target as a key
node_key_dict = collections.defaultdict(lambda: [])
for node_id, node_d in node_dict.items():
key = self._get_node_key(node_d)
node_key_dict[key].append(node_id)
# Constrain the groups to ones that have more than 1 member
node_groups = [g for g in node_key_dict.values() if (len(g) > 1)]
return node_groups | [
"def",
"_get_node_groups",
"(",
"self",
")",
":",
"node_dict",
"=",
"{",
"node",
"[",
"'data'",
"]",
"[",
"'id'",
"]",
":",
"{",
"'sources'",
":",
"[",
"]",
",",
"'targets'",
":",
"[",
"]",
"}",
"for",
"node",
"in",
"self",
".",
"_nodes",
"}",
"f... | 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
(i, polarity, source) edge of the node. node_dict is then processed
by _get_node_key() which returns a tuple of (s,t) where s,t are
sorted tuples of the ids for the source and target nodes. (s,t) is
then used as a key in node_key_dict where the values are the node
ids. node_groups is restricted to groups greater than 1 node. | [
"Return",
"a",
"list",
"of",
"node",
"id",
"lists",
"that",
"are",
"topologically",
"identical",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/cyjs/assembler.py#L366-L396 |
18,942 | sorgerlab/indra | indra/assemblers/cyjs/assembler.py | CyJSAssembler._group_edges | 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 parent nodes and make new edges for them
edges_to_add = [[], []] # [group_edges, uuid_lists]
for e in self._edges:
new_edge = deepcopy(e)
new_edge['data'].pop('id', None)
uuid_list = new_edge['data'].pop('uuid_list', [])
# Check if edge source or target are contained in a parent
# If source or target in parent edit edge
# Nodes may only point within their container
source = e['data']['source']
target = e['data']['target']
source_node = [x for x in self._nodes if
x['data']['id'] == source][0]
target_node = [x for x in self._nodes if
x['data']['id'] == target][0]
# If the source node is in a group, we change the source of this
# edge to the group
if source_node['data']['parent'] != '':
new_edge['data']['source'] = source_node['data']['parent']
e['data']['i'] = 'Virtual'
# If the targete node is in a group, we change the target of this
# edge to the group
if target_node['data']['parent'] != '':
new_edge['data']['target'] = target_node['data']['parent']
e['data']['i'] = 'Virtual'
if e['data']['i'] == 'Virtual':
if new_edge not in edges_to_add[0]:
edges_to_add[0].append(new_edge)
edges_to_add[1].append(uuid_list)
else:
idx = edges_to_add[0].index(new_edge)
edges_to_add[1][idx] += uuid_list
edges_to_add[1][idx] = list(set(edges_to_add[1][idx]))
for ze in zip(*edges_to_add):
edge = ze[0]
edge['data']['id'] = self._get_new_id()
edge['data']['uuid_list'] = ze[1]
self._edges.append(edge) | python | def _group_edges(self):
# edit edges on parent nodes and make new edges for them
edges_to_add = [[], []] # [group_edges, uuid_lists]
for e in self._edges:
new_edge = deepcopy(e)
new_edge['data'].pop('id', None)
uuid_list = new_edge['data'].pop('uuid_list', [])
# Check if edge source or target are contained in a parent
# If source or target in parent edit edge
# Nodes may only point within their container
source = e['data']['source']
target = e['data']['target']
source_node = [x for x in self._nodes if
x['data']['id'] == source][0]
target_node = [x for x in self._nodes if
x['data']['id'] == target][0]
# If the source node is in a group, we change the source of this
# edge to the group
if source_node['data']['parent'] != '':
new_edge['data']['source'] = source_node['data']['parent']
e['data']['i'] = 'Virtual'
# If the targete node is in a group, we change the target of this
# edge to the group
if target_node['data']['parent'] != '':
new_edge['data']['target'] = target_node['data']['parent']
e['data']['i'] = 'Virtual'
if e['data']['i'] == 'Virtual':
if new_edge not in edges_to_add[0]:
edges_to_add[0].append(new_edge)
edges_to_add[1].append(uuid_list)
else:
idx = edges_to_add[0].index(new_edge)
edges_to_add[1][idx] += uuid_list
edges_to_add[1][idx] = list(set(edges_to_add[1][idx]))
for ze in zip(*edges_to_add):
edge = ze[0]
edge['data']['id'] = self._get_new_id()
edge['data']['uuid_list'] = ze[1]
self._edges.append(edge) | [
"def",
"_group_edges",
"(",
"self",
")",
":",
"# edit edges on parent nodes and make new edges for them",
"edges_to_add",
"=",
"[",
"[",
"]",
",",
"[",
"]",
"]",
"# [group_edges, uuid_lists]",
"for",
"e",
"in",
"self",
".",
"_edges",
":",
"new_edge",
"=",
"deepcop... | 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. | [
"Group",
"all",
"edges",
"that",
"are",
"topologically",
"identical",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/cyjs/assembler.py#L398-L442 |
18,943 | sorgerlab/indra | indra/sources/trrust/processor.py | make_stmt | 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 | 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]) | [
"def",
"make_stmt",
"(",
"stmt_cls",
",",
"tf_agent",
",",
"target_agent",
",",
"pmid",
")",
":",
"ev",
"=",
"Evidence",
"(",
"source_api",
"=",
"'trrust'",
",",
"pmid",
"=",
"pmid",
")",
"return",
"stmt_cls",
"(",
"deepcopy",
"(",
"tf_agent",
")",
",",
... | Return a Statement based on its type, agents, and PMID. | [
"Return",
"a",
"Statement",
"based",
"on",
"its",
"type",
"agents",
"and",
"PMID",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/trrust/processor.py#L37-L41 |
18,944 | sorgerlab/indra | indra/sources/trrust/processor.py | get_grounded_agent | 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_client.get_uniprot_id(hgnc_id)
if up_id:
db_refs['UP'] = up_id
agent = Agent(gene_name, db_refs=db_refs)
return agent | python | 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_uniprot_id(hgnc_id)
if up_id:
db_refs['UP'] = up_id
agent = Agent(gene_name, db_refs=db_refs)
return agent | [
"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",
"... | Return a grounded Agent based on an HGNC symbol. | [
"Return",
"a",
"grounded",
"Agent",
"based",
"on",
"an",
"HGNC",
"symbol",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/trrust/processor.py#L44-L56 |
18,945 | sorgerlab/indra | indra/sources/trrust/processor.py | TrrustProcessor.extract_statements | 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 = IncreaseAmount
elif effect == 'Repression':
stmt_cls = DecreaseAmount
else:
continue
pmids = refs.split(';')
for pmid in pmids:
stmt = make_stmt(stmt_cls, tf_agent, target_agent, pmid)
self.statements.append(stmt) | python | 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 = IncreaseAmount
elif effect == 'Repression':
stmt_cls = DecreaseAmount
else:
continue
pmids = refs.split(';')
for pmid in pmids:
stmt = make_stmt(stmt_cls, tf_agent, target_agent, pmid)
self.statements.append(stmt) | [
"def",
"extract_statements",
"(",
"self",
")",
":",
"for",
"_",
",",
"(",
"tf",
",",
"target",
",",
"effect",
",",
"refs",
")",
"in",
"self",
".",
"df",
".",
"iterrows",
"(",
")",
":",
"tf_agent",
"=",
"get_grounded_agent",
"(",
"tf",
")",
"target_ag... | Process the table to extract Statements. | [
"Process",
"the",
"table",
"to",
"extract",
"Statements",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/trrust/processor.py#L20-L34 |
18,946 | sorgerlab/indra | indra/tools/machine/machine.py | process_paper | 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 the extracted INDRA Statements
in rp.statements.
txt_format : str
A string representing the format of the text
"""
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)
# If the paper has been read, use the json output file
if os.path.exists(json_path):
rp = reach.process_json_file(json_path, citation=pmid)
txt_format = 'existing_json'
# If the paper has not been read, download the text and read
else:
try:
txt, txt_format = get_full_text(pmid, 'pmid')
except Exception:
return None, None
if txt_format == 'pmc_oa_xml':
rp = reach.process_nxml_str(txt, citation=pmid, offline=True,
output_fname=json_path)
elif txt_format == 'elsevier_xml':
# Extract the raw text from the Elsevier XML
txt = elsevier_client.extract_text(txt)
rp = reach.process_text(txt, citation=pmid, offline=True,
output_fname=json_path)
elif txt_format == 'abstract':
rp = reach.process_text(txt, citation=pmid, offline=True,
output_fname=json_path)
else:
rp = None
if rp is not None:
check_pmids(rp.statements)
return rp, txt_format | python | 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)
# If the paper has been read, use the json output file
if os.path.exists(json_path):
rp = reach.process_json_file(json_path, citation=pmid)
txt_format = 'existing_json'
# If the paper has not been read, download the text and read
else:
try:
txt, txt_format = get_full_text(pmid, 'pmid')
except Exception:
return None, None
if txt_format == 'pmc_oa_xml':
rp = reach.process_nxml_str(txt, citation=pmid, offline=True,
output_fname=json_path)
elif txt_format == 'elsevier_xml':
# Extract the raw text from the Elsevier XML
txt = elsevier_client.extract_text(txt)
rp = reach.process_text(txt, citation=pmid, offline=True,
output_fname=json_path)
elif txt_format == 'abstract':
rp = reach.process_text(txt, citation=pmid, offline=True,
output_fname=json_path)
else:
rp = None
if rp is not None:
check_pmids(rp.statements)
return rp, txt_format | [
"def",
"process_paper",
"(",
"model_name",
",",
"pmid",
")",
":",
"json_directory",
"=",
"os",
".",
"path",
".",
"join",
"(",
"model_name",
",",
"'jsons'",
")",
"json_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"json_directory",
",",
"'PMID%s.json'",
... | 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 the extracted INDRA Statements
in rp.statements.
txt_format : str
A string representing the format of the text | [
"Process",
"a",
"paper",
"with",
"the",
"given",
"pubmed",
"identifier"
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/machine/machine.py#L91-L140 |
18,947 | sorgerlab/indra | indra/tools/machine/machine.py | process_paper_helper | 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 = process_paper_aws(pmid, start_time_local)
except:
logger.exception('uncaught exception while processing %s', pmid)
return None, None
return rp, txt_format | python | 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:
logger.exception('uncaught exception while processing %s', pmid)
return None, None
return rp, txt_format | [
"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",
",",
"tx... | Wraps processing a paper by either a local or remote service
and caches any uncaught exceptions | [
"Wraps",
"processing",
"a",
"paper",
"by",
"either",
"a",
"local",
"or",
"remote",
"service",
"and",
"caches",
"any",
"uncaught",
"exceptions"
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/machine/machine.py#L196-L208 |
18,948 | sorgerlab/indra | indra/sources/tas/api.py | _load_data | 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 extracted from
the csv file, described above.
"""
# 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]
# For some reason this heading is oddly formatted and inconsistent with the
# rest, or with the usual key-style for dicts.
headers[headers.index('Approved.Symbol')] = 'approved_symbol'
return [{header: val for header, val in zip(headers, line)}
for line in data_iter[1:]] | python | 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]
# For some reason this heading is oddly formatted and inconsistent with the
# rest, or with the usual key-style for dicts.
headers[headers.index('Approved.Symbol')] = 'approved_symbol'
return [{header: val for header, val in zip(headers, line)}
for line in data_iter[1:]] | [
"def",
"_load_data",
"(",
")",
":",
"# Get the cwv reader object.",
"csv_path",
"=",
"path",
".",
"join",
"(",
"HERE",
",",
"path",
".",
"pardir",
",",
"path",
".",
"pardir",
",",
"'resources'",
",",
"DATAFILE_NAME",
")",
"data_iter",
"=",
"list",
"(",
"re... | 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 extracted from
the csv file, described above. | [
"Load",
"the",
"data",
"from",
"the",
"csv",
"in",
"data",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/tas/api.py#L15-L39 |
18,949 | sorgerlab/indra | indra/sources/eidos/cli.py | run_eidos | 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
Any further arguments to be passed as inputs to the class
being run.
"""
# 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(args)
logger.info('Running Eidos with command "%s"' % (' '.join(cmd)))
subprocess.call(cmd) | python | 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(args)
logger.info('Running Eidos with command "%s"' % (' '.join(cmd)))
subprocess.call(cmd) | [
"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",
"="... | 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
Any further arguments to be passed as inputs to the class
being run. | [
"Run",
"a",
"given",
"enpoint",
"of",
"Eidos",
"through",
"the",
"command",
"line",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/eidos/cli.py#L20-L38 |
18,950 | sorgerlab/indra | indra/sources/eidos/cli.py | extract_from_directory | 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
path_out : str
Path to an output folder in which Eidos places the output
JSON-LD files
"""
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.ExtractFromDirectory', path_in, path_out) | python | 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.ExtractFromDirectory', path_in, path_out) | [
"def",
"extract_from_directory",
"(",
"path_in",
",",
"path_out",
")",
":",
"path_in",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"path_in",
")",
")",
"path_out",
"=",
"os",
".",
"path",
".",
"realpath",
"(... | 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
path_out : str
Path to an output folder in which Eidos places the output
JSON-LD files | [
"Run",
"Eidos",
"on",
"a",
"set",
"of",
"text",
"files",
"in",
"a",
"folder",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/eidos/cli.py#L41-L58 |
18,951 | sorgerlab/indra | indra/sources/eidos/cli.py | extract_and_process | 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 some text files
path_out : str
Path to an output folder in which Eidos places the output
JSON-LD files
Returns
-------
stmts : list[indra.statements.Statements]
A list of INDRA Statements
"""
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'))
logger.info('Found %d JSON-LD files to process in %s' %
(len(jsons), path_out))
stmts = []
for json in jsons:
ep = process_json_file(json)
if ep:
stmts += ep.statements
return stmts | python | 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'))
logger.info('Found %d JSON-LD files to process in %s' %
(len(jsons), path_out))
stmts = []
for json in jsons:
ep = process_json_file(json)
if ep:
stmts += ep.statements
return stmts | [
"def",
"extract_and_process",
"(",
"path_in",
",",
"path_out",
")",
":",
"path_in",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"path_in",
")",
")",
"path_out",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
... | 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 some text files
path_out : str
Path to an output folder in which Eidos places the output
JSON-LD files
Returns
-------
stmts : list[indra.statements.Statements]
A list of INDRA Statements | [
"Run",
"Eidos",
"on",
"a",
"set",
"of",
"text",
"files",
"and",
"process",
"output",
"with",
"INDRA",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/eidos/cli.py#L61-L91 |
18,952 | sorgerlab/indra | indra/sources/indra_db_rest/api.py | get_statements | 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 given agents and type.
There are two types of responses available. You can just get a list of
INDRA Statements, or you can get an IndraDBRestProcessor object, which allow
Statements to be loaded in a background thread, providing a sample of the
best* content available promptly in the sample_statements attribute, and
populates the statements attribute when the paged load is complete.
The latter should be used in all new code, and where convenient the prior
should be converted to use the processor, as this option may be removed in
the future.
* In the sense of having the most supporting evidence.
Parameters
----------
subject/object : str
Optionally specify the subject and/or object of the statements in
you wish to get from the database. By default, the namespace is assumed
to be HGNC gene names, however you may specify another namespace by
including `@<namespace>` at the end of the name string. For example, if
you want to specify an agent by chebi, you could use `CHEBI:6801@CHEBI`,
or if you wanted to use the HGNC id, you could use `6871@HGNC`.
agents : list[str]
A list of agents, specified in the same manner as subject and object,
but without specifying their grammatical position.
stmt_type : str
Specify the types of interactions you are interested in, as indicated
by the sub-classes of INDRA's Statements. This argument is *not* case
sensitive. If the statement class given has sub-classes
(e.g. RegulateAmount has IncreaseAmount and DecreaseAmount), then both
the class itself, and its subclasses, will be queried, by default. If
you do not want this behavior, set use_exact_type=True. Note that if
max_stmts is set, it is possible only the exact statement type will
be returned, as this is the first searched. The processor then cycles
through the types, getting a page of results for each type and adding it
to the quota, until the max number of statements is reached.
use_exact_type : bool
If stmt_type is given, and you only want to search for that specific
statement type, set this to True. Default is False.
persist : bool
Default is True. When False, if a query comes back limited (not all
results returned), just give up and pass along what was returned.
Otherwise, make further queries to get the rest of the data (which may
take some time).
timeout : positive int or None
If an int, block until the work is done and statements are retrieved, or
until the timeout has expired, in which case the results so far will be
returned in the response object, and further results will be added in
a separate thread as they become available. If simple_response is True,
all statements available will be returned. Otherwise (if None), block
indefinitely until all statements are retrieved. Default is None.
simple_response : bool
If True, a simple list of statements is returned (thus block should also
be True). If block is False, only the original sample will be returned
(as though persist was False), until the statements are done loading, in
which case the rest should appear in the list. This behavior is not
encouraged. Default is False (which breaks backwards compatibility with
usage of INDRA versions from before 1/22/2019). WE ENCOURAGE ALL NEW
USE-CASES TO USE THE PROCESSOR, AS THIS FEATURE MAY BE REMOVED AT A
LATER DATE.
ev_limit : int or None
Limit the amount of evidence returned per Statement. Default is 10.
best_first : bool
If True, the preassembled statements will be sorted by the amount of
evidence they have, and those with the most evidence will be
prioritized. When using `max_stmts`, this means you will get the "best"
statements. If False, statements will be queried in arbitrary order.
tries : int > 0
Set the number of times to try the query. The database often caches
results, so if a query times out the first time, trying again after a
timeout will often succeed fast enough to avoid a timeout. This can also
help gracefully handle an unreliable connection, if you're willing to
wait. Default is 2.
max_stmts : int or None
Select the maximum number of statements to return. When set less than
1000 the effect is much the same as setting persist to false, and will
guarantee a faster response. Default is None.
Returns
-------
processor : :py:class:`IndraDBRestProcessor`
An instance of the IndraDBRestProcessor, which has an attribute
`statements` which will be populated when the query/queries are done.
This is the default behavior, and is encouraged in all future cases,
however a simple list of statements may be returned using the
`simple_response` option described above.
"""
processor = IndraDBRestProcessor(subject, object, agents, stmt_type,
use_exact_type, persist, timeout,
ev_limit, best_first, tries, max_stmts)
# Format the result appropriately.
if simple_response:
ret = processor.statements
else:
ret = processor
return ret | python | 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):
processor = IndraDBRestProcessor(subject, object, agents, stmt_type,
use_exact_type, persist, timeout,
ev_limit, best_first, tries, max_stmts)
# Format the result appropriately.
if simple_response:
ret = processor.statements
else:
ret = processor
return ret | [
"def",
"get_statements",
"(",
"subject",
"=",
"None",
",",
"object",
"=",
"None",
",",
"agents",
"=",
"None",
",",
"stmt_type",
"=",
"None",
",",
"use_exact_type",
"=",
"False",
",",
"persist",
"=",
"True",
",",
"timeout",
"=",
"None",
",",
"simple_respo... | Get a processor for the INDRA DB web API matching given agents and type.
There are two types of responses available. You can just get a list of
INDRA Statements, or you can get an IndraDBRestProcessor object, which allow
Statements to be loaded in a background thread, providing a sample of the
best* content available promptly in the sample_statements attribute, and
populates the statements attribute when the paged load is complete.
The latter should be used in all new code, and where convenient the prior
should be converted to use the processor, as this option may be removed in
the future.
* In the sense of having the most supporting evidence.
Parameters
----------
subject/object : str
Optionally specify the subject and/or object of the statements in
you wish to get from the database. By default, the namespace is assumed
to be HGNC gene names, however you may specify another namespace by
including `@<namespace>` at the end of the name string. For example, if
you want to specify an agent by chebi, you could use `CHEBI:6801@CHEBI`,
or if you wanted to use the HGNC id, you could use `6871@HGNC`.
agents : list[str]
A list of agents, specified in the same manner as subject and object,
but without specifying their grammatical position.
stmt_type : str
Specify the types of interactions you are interested in, as indicated
by the sub-classes of INDRA's Statements. This argument is *not* case
sensitive. If the statement class given has sub-classes
(e.g. RegulateAmount has IncreaseAmount and DecreaseAmount), then both
the class itself, and its subclasses, will be queried, by default. If
you do not want this behavior, set use_exact_type=True. Note that if
max_stmts is set, it is possible only the exact statement type will
be returned, as this is the first searched. The processor then cycles
through the types, getting a page of results for each type and adding it
to the quota, until the max number of statements is reached.
use_exact_type : bool
If stmt_type is given, and you only want to search for that specific
statement type, set this to True. Default is False.
persist : bool
Default is True. When False, if a query comes back limited (not all
results returned), just give up and pass along what was returned.
Otherwise, make further queries to get the rest of the data (which may
take some time).
timeout : positive int or None
If an int, block until the work is done and statements are retrieved, or
until the timeout has expired, in which case the results so far will be
returned in the response object, and further results will be added in
a separate thread as they become available. If simple_response is True,
all statements available will be returned. Otherwise (if None), block
indefinitely until all statements are retrieved. Default is None.
simple_response : bool
If True, a simple list of statements is returned (thus block should also
be True). If block is False, only the original sample will be returned
(as though persist was False), until the statements are done loading, in
which case the rest should appear in the list. This behavior is not
encouraged. Default is False (which breaks backwards compatibility with
usage of INDRA versions from before 1/22/2019). WE ENCOURAGE ALL NEW
USE-CASES TO USE THE PROCESSOR, AS THIS FEATURE MAY BE REMOVED AT A
LATER DATE.
ev_limit : int or None
Limit the amount of evidence returned per Statement. Default is 10.
best_first : bool
If True, the preassembled statements will be sorted by the amount of
evidence they have, and those with the most evidence will be
prioritized. When using `max_stmts`, this means you will get the "best"
statements. If False, statements will be queried in arbitrary order.
tries : int > 0
Set the number of times to try the query. The database often caches
results, so if a query times out the first time, trying again after a
timeout will often succeed fast enough to avoid a timeout. This can also
help gracefully handle an unreliable connection, if you're willing to
wait. Default is 2.
max_stmts : int or None
Select the maximum number of statements to return. When set less than
1000 the effect is much the same as setting persist to false, and will
guarantee a faster response. Default is None.
Returns
-------
processor : :py:class:`IndraDBRestProcessor`
An instance of the IndraDBRestProcessor, which has an attribute
`statements` which will be populated when the query/queries are done.
This is the default behavior, and is encouraged in all future cases,
however a simple list of statements may be returned using the
`simple_response` option described above. | [
"Get",
"a",
"processor",
"for",
"the",
"INDRA",
"DB",
"web",
"API",
"matching",
"given",
"agents",
"and",
"type",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/indra_db_rest/api.py#L15-L116 |
18,953 | sorgerlab/indra | indra/sources/indra_db_rest/api.py | get_statements_by_hash | 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 Statement. Default is 100.
best_first : bool
If True, the preassembled statements will be sorted by the amount of
evidence they have, and those with the most evidence will be
prioritized. When using `max_stmts`, this means you will get the "best"
statements. If False, statements will be queried in arbitrary order.
tries : int > 0
Set the number of times to try the query. The database often caches
results, so if a query times out the first time, trying again after a
timeout will often succeed fast enough to avoid a timeout. This can
also help gracefully handle an unreliable connection, if you're
willing to wait. Default is 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 []
if isinstance(hash_list[0], str):
hash_list = [int(h) for h in hash_list]
if not all([isinstance(h, int) for h in hash_list]):
raise ValueError("Hashes must be ints or strings that can be "
"converted into ints.")
resp = submit_statement_request('post', 'from_hashes', ev_limit=ev_limit,
data={'hashes': hash_list},
best_first=best_first, tries=tries)
return stmts_from_json(resp.json()['statements'].values()) | python | 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 []
if isinstance(hash_list[0], str):
hash_list = [int(h) for h in hash_list]
if not all([isinstance(h, int) for h in hash_list]):
raise ValueError("Hashes must be ints or strings that can be "
"converted into ints.")
resp = submit_statement_request('post', 'from_hashes', ev_limit=ev_limit,
data={'hashes': hash_list},
best_first=best_first, tries=tries)
return stmts_from_json(resp.json()['statements'].values()) | [
"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_l... | 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 Statement. Default is 100.
best_first : bool
If True, the preassembled statements will be sorted by the amount of
evidence they have, and those with the most evidence will be
prioritized. When using `max_stmts`, this means you will get the "best"
statements. If False, statements will be queried in arbitrary order.
tries : int > 0
Set the number of times to try the query. The database often caches
results, so if a query times out the first time, trying again after a
timeout will often succeed fast enough to avoid a timeout. This can
also help gracefully handle an unreliable connection, if you're
willing to wait. Default is 2. | [
"Get",
"fully",
"formed",
"statements",
"from",
"a",
"list",
"of",
"hashes",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/indra_db_rest/api.py#L120-L154 |
18,954 | sorgerlab/indra | indra/sources/indra_db_rest/api.py | get_statements_for_paper | 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 type can be any one of
'pmid', 'pmcid', 'doi', 'pii', 'manuscript id', or 'trid', which is the
primary key id of the text references in the database.
ev_limit : int or None
Limit the amount of evidence returned per Statement. Default is 10.
best_first : bool
If True, the preassembled statements will be sorted by the amount of
evidence they have, and those with the most evidence will be
prioritized. When using `max_stmts`, this means you will get the "best"
statements. If False, statements will be queried in arbitrary order.
tries : int > 0
Set the number of times to try the query. The database often caches
results, so if a query times out the first time, trying again after a
timeout will often succeed fast enough to avoid a timeout. This can also
help gracefully handle an unreliable connection, if you're willing to
wait. Default is 2.
max_stmts : int or None
Select a maximum number of statements to be returned. Default is None.
Returns
-------
stmts : list[:py:class:`indra.statements.Statement`]
A list of INDRA Statement instances.
"""
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},
ev_limit=ev_limit, best_first=best_first,
tries=tries, max_stmts=max_stmts)
stmts_json = resp.json()['statements']
return stmts_from_json(stmts_json.values()) | python | 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},
ev_limit=ev_limit, best_first=best_first,
tries=tries, max_stmts=max_stmts)
stmts_json = resp.json()['statements']
return stmts_from_json(stmts_json.values()) | [
"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",
"... | 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 type can be any one of
'pmid', 'pmcid', 'doi', 'pii', 'manuscript id', or 'trid', which is the
primary key id of the text references in the database.
ev_limit : int or None
Limit the amount of evidence returned per Statement. Default is 10.
best_first : bool
If True, the preassembled statements will be sorted by the amount of
evidence they have, and those with the most evidence will be
prioritized. When using `max_stmts`, this means you will get the "best"
statements. If False, statements will be queried in arbitrary order.
tries : int > 0
Set the number of times to try the query. The database often caches
results, so if a query times out the first time, trying again after a
timeout will often succeed fast enough to avoid a timeout. This can also
help gracefully handle an unreliable connection, if you're willing to
wait. Default is 2.
max_stmts : int or None
Select a maximum number of statements to be returned. Default is None.
Returns
-------
stmts : list[:py:class:`indra.statements.Statement`]
A list of INDRA Statement instances. | [
"Get",
"the",
"set",
"of",
"raw",
"Statements",
"extracted",
"from",
"a",
"paper",
"given",
"by",
"the",
"id",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/indra_db_rest/api.py#L158-L194 |
18,955 | sorgerlab/indra | indra/sources/indra_db_rest/api.py | submit_curation | 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
A very short phrase categorizing the error or type of curation,
e.g. "grounding" for a grounding error, or "correct" if you are
marking a statement as correct.
curator : str
The name or identifier for the curator.
text : str
A brief description of the problem.
source : str
The name of the access point through which the curation was performed.
The default is 'direct_client', meaning this function was used
directly. Any higher-level application should identify itself here.
ev_hash : int
A hash of the sentence and other evidence information. Elsewhere
referred to as `source_hash`.
is_test : bool
Used in testing. If True, no curation will actually be added to the
database.
"""
data = {'tag': tag, 'text': text, 'curator': curator, 'source': source,
'ev_hash': ev_hash}
url = 'curation/submit/%s' % hash_val
if is_test:
qstr = '?test'
else:
qstr = ''
return make_db_rest_request('post', url, qstr, data=data) | python | 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' % hash_val
if is_test:
qstr = '?test'
else:
qstr = ''
return make_db_rest_request('post', url, qstr, data=data) | [
"def",
"submit_curation",
"(",
"hash_val",
",",
"tag",
",",
"curator",
",",
"text",
"=",
"None",
",",
"source",
"=",
"'indra_rest_client'",
",",
"ev_hash",
"=",
"None",
",",
"is_test",
"=",
"False",
")",
":",
"data",
"=",
"{",
"'tag'",
":",
"tag",
",",... | Submit a curation for the given statement at the relevant level.
Parameters
----------
hash_val : int
The hash corresponding to the statement.
tag : str
A very short phrase categorizing the error or type of curation,
e.g. "grounding" for a grounding error, or "correct" if you are
marking a statement as correct.
curator : str
The name or identifier for the curator.
text : str
A brief description of the problem.
source : str
The name of the access point through which the curation was performed.
The default is 'direct_client', meaning this function was used
directly. Any higher-level application should identify itself here.
ev_hash : int
A hash of the sentence and other evidence information. Elsewhere
referred to as `source_hash`.
is_test : bool
Used in testing. If True, no curation will actually be added to the
database. | [
"Submit",
"a",
"curation",
"for",
"the",
"given",
"statement",
"at",
"the",
"relevant",
"level",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/indra_db_rest/api.py#L197-L231 |
18,956 | sorgerlab/indra | indra/sources/indra_db_rest/api.py | get_statement_queries | 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]
A list of INDRA statements.
"""
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 = 'TEXT'
dbid = ag.name
return '%s@%s' % (dbid, ns)
queries = []
url_base = get_url_base('statements/from_agents')
non_binary_statements = [Complex, SelfModification, ActiveForm]
for stmt in stmts:
kwargs = {}
if type(stmt) not in non_binary_statements:
for pos, ag in zip(['subject', 'object'], stmt.agent_list()):
if ag is not None:
kwargs[pos] = pick_ns(ag)
else:
for i, ag in enumerate(stmt.agent_list()):
if ag is not None:
kwargs['agent%d' % i] = pick_ns(ag)
kwargs['type'] = stmt.__class__.__name__
kwargs.update(params)
query_str = '?' + '&'.join(['%s=%s' % (k, v) for k, v in kwargs.items()
if v is not None])
queries.append(url_base + query_str)
return queries | python | 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 = 'TEXT'
dbid = ag.name
return '%s@%s' % (dbid, ns)
queries = []
url_base = get_url_base('statements/from_agents')
non_binary_statements = [Complex, SelfModification, ActiveForm]
for stmt in stmts:
kwargs = {}
if type(stmt) not in non_binary_statements:
for pos, ag in zip(['subject', 'object'], stmt.agent_list()):
if ag is not None:
kwargs[pos] = pick_ns(ag)
else:
for i, ag in enumerate(stmt.agent_list()):
if ag is not None:
kwargs['agent%d' % i] = pick_ns(ag)
kwargs['type'] = stmt.__class__.__name__
kwargs.update(params)
query_str = '?' + '&'.join(['%s=%s' % (k, v) for k, v in kwargs.items()
if v is not None])
queries.append(url_base + query_str)
return queries | [
"def",
"get_statement_queries",
"(",
"stmts",
",",
"*",
"*",
"params",
")",
":",
"def",
"pick_ns",
"(",
"ag",
")",
":",
"for",
"ns",
"in",
"[",
"'HGNC'",
",",
"'FPLX'",
",",
"'CHEMBL'",
",",
"'CHEBI'",
",",
"'GO'",
",",
"'MESH'",
"]",
":",
"if",
"n... | 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]
A list of INDRA statements. | [
"Get",
"queries",
"used",
"to",
"search",
"based",
"on",
"a",
"statement",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/indra_db_rest/api.py#L234-L274 |
18,957 | sorgerlab/indra | indra/tools/incremental_model.py | IncrementalModel.save | 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
"""
with open(model_fname, 'wb') as fh:
pickle.dump(self.stmts, fh, protocol=4) | python | def save(self, model_fname='model.pkl'):
with open(model_fname, 'wb') as fh:
pickle.dump(self.stmts, fh, protocol=4) | [
"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.
Parameters
----------
model_fname : Optional[str]
The name of the pickle file to save the state of the
IncrementalModel in. Default: model.pkl | [
"Save",
"the",
"state",
"of",
"the",
"IncrementalModel",
"in",
"a",
"pickle",
"file",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/incremental_model.py#L45-L55 |
18,958 | sorgerlab/indra | indra/tools/incremental_model.py | IncrementalModel.add_statements | 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 Statements to be added to the model.
"""
if pmid not in self.stmts:
self.stmts[pmid] = stmts
else:
self.stmts[pmid] += stmts | python | def add_statements(self, pmid, stmts):
if pmid not in self.stmts:
self.stmts[pmid] = stmts
else:
self.stmts[pmid] += stmts | [
"def",
"add_statements",
"(",
"self",
",",
"pmid",
",",
"stmts",
")",
":",
"if",
"pmid",
"not",
"in",
"self",
".",
"stmts",
":",
"self",
".",
"stmts",
"[",
"pmid",
"]",
"=",
"stmts",
"else",
":",
"self",
".",
"stmts",
"[",
"pmid",
"]",
"+=",
"stm... | 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 Statements to be added to the model. | [
"Add",
"INDRA",
"Statements",
"to",
"the",
"incremental",
"model",
"indexed",
"by",
"PMID",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/incremental_model.py#L57-L70 |
18,959 | sorgerlab/indra | indra/tools/incremental_model.py | IncrementalModel.preassemble | 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.
Currently the following filter options are implemented:
- grounding: require that all Agents in statements are grounded
- human_only: require that all proteins are human proteins
- prior_one: require that at least one Agent is in the prior model
- prior_all: require that all Agents are in the prior model
Parameters
----------
filters : Optional[list[str]]
A list of filter options to apply when choosing the statements.
See description above for more details. Default: None
grounding_map : Optional[dict]
A user supplied grounding map which maps a string to a
dictionary of database IDs (in the format used by Agents'
db_refs).
"""
stmts = self.get_statements()
# Filter out hypotheses
stmts = ac.filter_no_hypothesis(stmts)
# Fix grounding
if grounding_map is not None:
stmts = ac.map_grounding(stmts, grounding_map=grounding_map)
else:
stmts = ac.map_grounding(stmts)
if filters and ('grounding' in filters):
stmts = ac.filter_grounded_only(stmts)
# Fix sites
stmts = ac.map_sequence(stmts)
if filters and 'human_only' in filters:
stmts = ac.filter_human_only(stmts)
# Run preassembly
stmts = ac.run_preassembly(stmts, return_toplevel=False)
# Run relevance filter
stmts = self._relevance_filter(stmts, filters)
# Save Statements
self.assembled_stmts = stmts | python | 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_grounding(stmts, grounding_map=grounding_map)
else:
stmts = ac.map_grounding(stmts)
if filters and ('grounding' in filters):
stmts = ac.filter_grounded_only(stmts)
# Fix sites
stmts = ac.map_sequence(stmts)
if filters and 'human_only' in filters:
stmts = ac.filter_human_only(stmts)
# Run preassembly
stmts = ac.run_preassembly(stmts, return_toplevel=False)
# Run relevance filter
stmts = self._relevance_filter(stmts, filters)
# Save Statements
self.assembled_stmts = stmts | [
"def",
"preassemble",
"(",
"self",
",",
"filters",
"=",
"None",
",",
"grounding_map",
"=",
"None",
")",
":",
"stmts",
"=",
"self",
".",
"get_statements",
"(",
")",
"# Filter out hypotheses",
"stmts",
"=",
"ac",
".",
"filter_no_hypothesis",
"(",
"stmts",
")",... | 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.
Currently the following filter options are implemented:
- grounding: require that all Agents in statements are grounded
- human_only: require that all proteins are human proteins
- prior_one: require that at least one Agent is in the prior model
- prior_all: require that all Agents are in the prior model
Parameters
----------
filters : Optional[list[str]]
A list of filter options to apply when choosing the statements.
See description above for more details. Default: None
grounding_map : Optional[dict]
A user supplied grounding map which maps a string to a
dictionary of database IDs (in the format used by Agents'
db_refs). | [
"Preassemble",
"the",
"Statements",
"collected",
"in",
"the",
"model",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/incremental_model.py#L84-L134 |
18,960 | sorgerlab/indra | indra/tools/incremental_model.py | IncrementalModel.get_model_agents | 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_stmts:
for a in stmt.agent_list():
if a is not None:
agents.append(a)
return agents | python | 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 | [
"def",
"get_model_agents",
"(",
"self",
")",
":",
"model_stmts",
"=",
"self",
".",
"get_statements",
"(",
")",
"agents",
"=",
"[",
"]",
"for",
"stmt",
"in",
"model_stmts",
":",
"for",
"a",
"in",
"stmt",
".",
"agent_list",
"(",
")",
":",
"if",
"a",
"i... | Return a list of all Agents from all Statements.
Returns
-------
agents : list[indra.statements.Agent]
A list of Agents that are in the model. | [
"Return",
"a",
"list",
"of",
"all",
"Agents",
"from",
"all",
"Statements",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/incremental_model.py#L149-L163 |
18,961 | sorgerlab/indra | indra/tools/incremental_model.py | IncrementalModel.get_statements | 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 = []
for s in stmt_lists:
stmts += s
return stmts | python | def get_statements(self):
stmt_lists = [v for k, v in self.stmts.items()]
stmts = []
for s in stmt_lists:
stmts += s
return stmts | [
"def",
"get_statements",
"(",
"self",
")",
":",
"stmt_lists",
"=",
"[",
"v",
"for",
"k",
",",
"v",
"in",
"self",
".",
"stmts",
".",
"items",
"(",
")",
"]",
"stmts",
"=",
"[",
"]",
"for",
"s",
"in",
"stmt_lists",
":",
"stmts",
"+=",
"s",
"return",... | 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. | [
"Return",
"a",
"list",
"of",
"all",
"Statements",
"in",
"a",
"single",
"list",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/incremental_model.py#L165-L177 |
18,962 | sorgerlab/indra | indra/tools/incremental_model.py | IncrementalModel.get_statements_noprior | 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 for k, v in self.stmts.items() if k != 'prior']
stmts = []
for s in stmt_lists:
stmts += s
return stmts | python | 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 | [
"def",
"get_statements_noprior",
"(",
"self",
")",
":",
"stmt_lists",
"=",
"[",
"v",
"for",
"k",
",",
"v",
"in",
"self",
".",
"stmts",
".",
"items",
"(",
")",
"if",
"k",
"!=",
"'prior'",
"]",
"stmts",
"=",
"[",
"]",
"for",
"s",
"in",
"stmt_lists",
... | 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). | [
"Return",
"a",
"list",
"of",
"all",
"non",
"-",
"prior",
"Statements",
"in",
"a",
"single",
"list",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/incremental_model.py#L179-L192 |
18,963 | sorgerlab/indra | indra/sources/bel/api.py | process_ndex_neighborhood | 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.
Example: ['BRAF', 'MAP2K1']
network_id : Optional[str]
The UUID of the network in NDEx. By default, the BEL Large Corpus
network is used.
rdf_out : Optional[str]
Name of the output file to save the RDF returned by the web service.
This is useful for debugging purposes or to repeat the same query
on an offline RDF file later. Default: bel_output.rdf
Returns
-------
bp : BelRdfProcessor
A BelRdfProcessor object which contains INDRA Statements in bp.statements.
Notes
-----
This function calls process_belrdf to the returned RDF string from the
webservice.
"""
logger.warning('This method is deprecated and the results are not '
'guaranteed to be correct. Please use '
'process_pybel_neighborhood instead.')
if network_id is None:
network_id = '9ea3c170-01ad-11e5-ac0f-000c29cb28fb'
url = ndex_bel2rdf + '/network/%s/asBELRDF/query' % network_id
params = {'searchString': ' '.join(gene_names)}
# The ndex_client returns the rdf as the content of a json dict
res_json = ndex_client.send_request(url, params, is_json=True)
if not res_json:
logger.error('No response for NDEx neighborhood query.')
return None
if res_json.get('error'):
error_msg = res_json.get('message')
logger.error('BEL/RDF response contains error: %s' % error_msg)
return None
rdf = res_json.get('content')
if not rdf:
logger.error('BEL/RDF response is empty.')
return None
with open(rdf_out, 'wb') as fh:
fh.write(rdf.encode('utf-8'))
bp = process_belrdf(rdf, print_output=print_output)
return bp | python | 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 '
'process_pybel_neighborhood instead.')
if network_id is None:
network_id = '9ea3c170-01ad-11e5-ac0f-000c29cb28fb'
url = ndex_bel2rdf + '/network/%s/asBELRDF/query' % network_id
params = {'searchString': ' '.join(gene_names)}
# The ndex_client returns the rdf as the content of a json dict
res_json = ndex_client.send_request(url, params, is_json=True)
if not res_json:
logger.error('No response for NDEx neighborhood query.')
return None
if res_json.get('error'):
error_msg = res_json.get('message')
logger.error('BEL/RDF response contains error: %s' % error_msg)
return None
rdf = res_json.get('content')
if not rdf:
logger.error('BEL/RDF response is empty.')
return None
with open(rdf_out, 'wb') as fh:
fh.write(rdf.encode('utf-8'))
bp = process_belrdf(rdf, print_output=print_output)
return bp | [
"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 '",
"'guarantee... | Return a BelRdfProcessor for an NDEx network neighborhood.
Parameters
----------
gene_names : list
A list of HGNC gene symbols to search the neighborhood of.
Example: ['BRAF', 'MAP2K1']
network_id : Optional[str]
The UUID of the network in NDEx. By default, the BEL Large Corpus
network is used.
rdf_out : Optional[str]
Name of the output file to save the RDF returned by the web service.
This is useful for debugging purposes or to repeat the same query
on an offline RDF file later. Default: bel_output.rdf
Returns
-------
bp : BelRdfProcessor
A BelRdfProcessor object which contains INDRA Statements in bp.statements.
Notes
-----
This function calls process_belrdf to the returned RDF string from the
webservice. | [
"Return",
"a",
"BelRdfProcessor",
"for",
"an",
"NDEx",
"network",
"neighborhood",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/bel/api.py#L20-L71 |
18,964 | sorgerlab/indra | indra/sources/bel/api.py | process_pybel_neighborhood | 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 genes in the given list.
Parameters
----------
network_file : Optional[str]
Path to the network file to process. If not given, by default, the
BEL Large Corpus is used.
network_type : Optional[str]
This function allows processing both BEL Script files and JSON files.
This argument controls which type is assumed to be processed, and the
value can be either 'belscript' or 'json'. Default: bel_script
Returns
-------
bp : PybelProcessor
A PybelProcessor object which contains INDRA Statements in
bp.statements.
"""
if network_file is None:
# Use large corpus as base network
network_file = os.path.join(os.path.dirname(os.path.abspath(__file__)),
os.path.pardir, os.path.pardir,
os.path.pardir, 'data', 'large_corpus.bel')
if network_type == 'belscript':
bp = process_belscript(network_file, **kwargs)
elif network_type == 'json':
bp = process_json_file(network_file)
filtered_stmts = []
for stmt in bp.statements:
found = False
for agent in stmt.agent_list():
if agent is not None:
if agent.name in gene_names:
found = True
if found:
filtered_stmts.append(stmt)
bp.statements = filtered_stmts
return bp | python | 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(__file__)),
os.path.pardir, os.path.pardir,
os.path.pardir, 'data', 'large_corpus.bel')
if network_type == 'belscript':
bp = process_belscript(network_file, **kwargs)
elif network_type == 'json':
bp = process_json_file(network_file)
filtered_stmts = []
for stmt in bp.statements:
found = False
for agent in stmt.agent_list():
if agent is not None:
if agent.name in gene_names:
found = True
if found:
filtered_stmts.append(stmt)
bp.statements = filtered_stmts
return bp | [
"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",
"=",
... | 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 genes in the given list.
Parameters
----------
network_file : Optional[str]
Path to the network file to process. If not given, by default, the
BEL Large Corpus is used.
network_type : Optional[str]
This function allows processing both BEL Script files and JSON files.
This argument controls which type is assumed to be processed, and the
value can be either 'belscript' or 'json'. Default: bel_script
Returns
-------
bp : PybelProcessor
A PybelProcessor object which contains INDRA Statements in
bp.statements. | [
"Return",
"PybelProcessor",
"around",
"neighborhood",
"of",
"given",
"genes",
"in",
"a",
"network",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/bel/api.py#L74-L119 |
18,965 | sorgerlab/indra | indra/sources/bel/api.py | process_pybel_graph | 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.statements.
"""
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.values()))
return bp | python | 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.values()))
return bp | [
"def",
"process_pybel_graph",
"(",
"graph",
")",
":",
"bp",
"=",
"PybelProcessor",
"(",
"graph",
")",
"bp",
".",
"get_statements",
"(",
")",
"if",
"bp",
".",
"annot_manager",
".",
"failures",
":",
"logger",
".",
"warning",
"(",
"'missing %d annotation pairs'",... | 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.statements. | [
"Return",
"a",
"PybelProcessor",
"by",
"processing",
"a",
"PyBEL",
"graph",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/bel/api.py#L167-L187 |
18,966 | sorgerlab/indra | indra/sources/bel/api.py | process_belscript | 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 defaults
of PyBEL, namely we set `citation_clearing` to False
and `no_identifier_validation` to True.
Parameters
----------
file_name : str
The path to a BEL script file.
Returns
-------
bp : PybelProcessor
A PybelProcessor object which contains INDRA Statements in
bp.statements.
"""
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_name, **kwargs)
return process_pybel_graph(pybel_graph) | python | 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_name, **kwargs)
return process_pybel_graph(pybel_graph) | [
"def",
"process_belscript",
"(",
"file_name",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'citation_clearing'",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"'citation_clearing'",
"]",
"=",
"False",
"if",
"'no_identifier_validation'",
"not",
"in",
"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 defaults
of PyBEL, namely we set `citation_clearing` to False
and `no_identifier_validation` to True.
Parameters
----------
file_name : str
The path to a BEL script file.
Returns
-------
bp : PybelProcessor
A PybelProcessor object which contains INDRA Statements in
bp.statements. | [
"Return",
"a",
"PybelProcessor",
"by",
"processing",
"a",
"BEL",
"script",
"file",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/bel/api.py#L190-L216 |
18,967 | sorgerlab/indra | indra/sources/bel/api.py | process_json_file | 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
-------
bp : PybelProcessor
A PybelProcessor object which contains INDRA Statements in
bp.statements.
"""
with open(file_name, 'rt') as fh:
pybel_graph = pybel.from_json_file(fh, False)
return process_pybel_graph(pybel_graph) | python | 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) | [
"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.
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
-------
bp : PybelProcessor
A PybelProcessor object which contains INDRA Statements in
bp.statements. | [
"Return",
"a",
"PybelProcessor",
"by",
"processing",
"a",
"Node",
"-",
"Link",
"JSON",
"file",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/bel/api.py#L219-L238 |
18,968 | sorgerlab/indra | indra/sources/bel/api.py | process_cbn_jgif_file | 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
bp.statements.
"""
with open(file_name, 'r') as jgf:
return process_pybel_graph(pybel.from_cbn_jgif(json.load(jgf))) | python | 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))) | [
"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.
Parameters
----------
file_name : str
The path to a CBN JGIF JSON file.
Returns
-------
bp : PybelProcessor
A PybelProcessor object which contains INDRA Statements in
bp.statements. | [
"Return",
"a",
"PybelProcessor",
"by",
"processing",
"a",
"CBN",
"JGIF",
"JSON",
"file",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/bel/api.py#L241-L256 |
18,969 | sorgerlab/indra | indra/resources/update_resources.py | update_famplex | 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 in csv_names:
url = famplex_url_pattern % csv_name
save_from_http(url, os.path.join(path,'famplex/%s.csv' % csv_name)) | python | 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:
url = famplex_url_pattern % csv_name
save_from_http(url, os.path.join(path,'famplex/%s.csv' % csv_name)) | [
"def",
"update_famplex",
"(",
")",
":",
"famplex_url_pattern",
"=",
"'https://raw.githubusercontent.com/sorgerlab/famplex/master/%s.csv'",
"csv_names",
"=",
"[",
"'entities'",
",",
"'equivalences'",
",",
"'gene_prefixes'",
",",
"'grounding_map'",
",",
"'relations'",
"]",
"f... | Update all the CSV files that form the FamPlex resource. | [
"Update",
"all",
"the",
"CSV",
"files",
"that",
"form",
"the",
"FamPlex",
"resource",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/resources/update_resources.py#L421-L429 |
18,970 | sorgerlab/indra | indra/resources/update_resources.py | update_lincs_small_molecules | 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.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, 'lincs_small_molecules.json')
with open(fname, 'w') as fh:
json.dump(sm_dict, fh, indent=1) | python | 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, 'lincs_small_molecules.json')
with open(fname, 'w') as fh:
json.dump(sm_dict, fh, indent=1) | [
"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",
"... | 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. | [
"Load",
"the",
"csv",
"of",
"LINCS",
"small",
"molecule",
"metadata",
"into",
"a",
"dict",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/resources/update_resources.py#L439-L452 |
18,971 | sorgerlab/indra | indra/resources/update_resources.py | update_lincs_proteins | 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/'
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(path, 'lincs_proteins.json')
with open(fname, 'w') as fh:
json.dump(prot_dict, fh, indent=1) | python | 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(path, 'lincs_proteins.json')
with open(fname, 'w') as fh:
json.dump(prot_dict, fh, indent=1) | [
"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",
... | 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. | [
"Load",
"the",
"csv",
"of",
"LINCS",
"protein",
"metadata",
"into",
"a",
"dict",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/resources/update_resources.py#L455-L468 |
18,972 | sorgerlab/indra | indra/assemblers/index_card/assembler.py | _get_is_direct | 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 default to direct.'''
any_indirect = False
for ev in stmt.evidence:
if ev.epistemics.get('direct') is True:
return True
elif ev.epistemics.get('direct') is False:
# This guarantees that we have seen at least
# some evidence that the statement is indirect
any_indirect = True
if any_indirect:
return False
return True | python | 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 default to direct.'''
any_indirect = False
for ev in stmt.evidence:
if ev.epistemics.get('direct') is True:
return True
elif ev.epistemics.get('direct') is False:
# This guarantees that we have seen at least
# some evidence that the statement is indirect
any_indirect = True
if any_indirect:
return False
return True | [
"def",
"_get_is_direct",
"(",
"stmt",
")",
":",
"any_indirect",
"=",
"False",
"for",
"ev",
"in",
"stmt",
".",
"evidence",
":",
"if",
"ev",
".",
"epistemics",
".",
"get",
"(",
"'direct'",
")",
"is",
"True",
":",
"return",
"True",
"elif",
"ev",
".",
"e... | 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 default to direct. | [
"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",
... | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/index_card/assembler.py#L418-L434 |
18,973 | sorgerlab/indra | indra/assemblers/index_card/assembler.py | IndexCardAssembler.make_model | 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)
elif isinstance(stmt, Complex):
card = assemble_complex(stmt)
elif isinstance(stmt, Translocation):
card = assemble_translocation(stmt)
elif isinstance(stmt, RegulateActivity):
card = assemble_regulate_activity(stmt)
elif isinstance(stmt, RegulateAmount):
card = assemble_regulate_amount(stmt)
else:
continue
if card is not None:
card.card['meta'] = {'id': stmt.uuid, 'belief': stmt.belief}
if self.pmc_override is not None:
card.card['pmc_id'] = self.pmc_override
else:
card.card['pmc_id'] = get_pmc_id(stmt)
self.cards.append(card) | python | 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)
elif isinstance(stmt, Complex):
card = assemble_complex(stmt)
elif isinstance(stmt, Translocation):
card = assemble_translocation(stmt)
elif isinstance(stmt, RegulateActivity):
card = assemble_regulate_activity(stmt)
elif isinstance(stmt, RegulateAmount):
card = assemble_regulate_amount(stmt)
else:
continue
if card is not None:
card.card['meta'] = {'id': stmt.uuid, 'belief': stmt.belief}
if self.pmc_override is not None:
card.card['pmc_id'] = self.pmc_override
else:
card.card['pmc_id'] = get_pmc_id(stmt)
self.cards.append(card) | [
"def",
"make_model",
"(",
"self",
")",
":",
"for",
"stmt",
"in",
"self",
".",
"statements",
":",
"if",
"isinstance",
"(",
"stmt",
",",
"Modification",
")",
":",
"card",
"=",
"assemble_modification",
"(",
"stmt",
")",
"elif",
"isinstance",
"(",
"stmt",
",... | Assemble statements into index cards. | [
"Assemble",
"statements",
"into",
"index",
"cards",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/index_card/assembler.py#L48-L71 |
18,974 | sorgerlab/indra | indra/assemblers/index_card/assembler.py | IndexCardAssembler.print_model | 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
# card not as a list
if len(cards) == 1:
cards = cards[0]
cards_json = json.dumps(cards, indent=1)
return cards_json | python | 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 cards_json | [
"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... | Return the assembled cards as a JSON string.
Returns
-------
cards_json : str
The JSON string representing the assembled cards. | [
"Return",
"the",
"assembled",
"cards",
"as",
"a",
"JSON",
"string",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/index_card/assembler.py#L73-L87 |
18,975 | sorgerlab/indra | indra/sources/geneways/processor.py | geneways_action_to_indra_statement_type | 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
this verb as a physical, logical, or other interaction
Returns
-------
statement_generator :
If there is no mapping to INDRA statements from this action type
the return value is None.
If there is such a mapping, statement_generator is an anonymous
function that takes in the subject agent, object agent, and evidence,
in that order, and returns an INDRA statement object.
"""
actiontype = actiontype.lower()
statement_generator = None
is_direct = (plo == 'P')
if actiontype == 'bind':
statement_generator = lambda substance1, substance2, evidence: \
Complex([substance1, substance2], evidence=evidence)
is_direct = True
elif actiontype == 'phosphorylate':
statement_generator = lambda substance1, substance2, evidence: \
Phosphorylation(substance1, substance2, evidence=evidence)
is_direct = True
return (statement_generator, is_direct) | python | 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: \
Complex([substance1, substance2], evidence=evidence)
is_direct = True
elif actiontype == 'phosphorylate':
statement_generator = lambda substance1, substance2, evidence: \
Phosphorylation(substance1, substance2, evidence=evidence)
is_direct = True
return (statement_generator, is_direct) | [
"def",
"geneways_action_to_indra_statement_type",
"(",
"actiontype",
",",
"plo",
")",
":",
"actiontype",
"=",
"actiontype",
".",
"lower",
"(",
")",
"statement_generator",
"=",
"None",
"is_direct",
"=",
"(",
"plo",
"==",
"'P'",
")",
"if",
"actiontype",
"==",
"'... | 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
this verb as a physical, logical, or other interaction
Returns
-------
statement_generator :
If there is no mapping to INDRA statements from this action type
the return value is None.
If there is such a mapping, statement_generator is an anonymous
function that takes in the subject agent, object agent, and evidence,
in that order, and returns an INDRA statement object. | [
"Return",
"INDRA",
"Statement",
"corresponding",
"to",
"Geneways",
"action",
"type",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/geneways/processor.py#L155-L189 |
18,976 | sorgerlab/indra | indra/sources/geneways/processor.py | GenewaysProcessor.make_statement | 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 same action if they are
referring to the same relationship - there may be multiple
Geneways action mentions corresponding to each action.
mention : GenewaysActionMention
The Geneways action mention object corresponding to a single
mention of a mechanism in a specific text. We make a new INDRA
statement corresponding to each action mention.
Returns
-------
statement : indra.statements.Statement
An INDRA statement corresponding to the provided Geneways action
mention, or None if the action mention's type does not map onto
any INDRA statement type in geneways_action_type_mapper.
"""
(statement_generator, is_direct) = \
geneways_action_to_indra_statement_type(mention.actiontype,
action.plo)
if statement_generator is None:
# Geneways statement does not map onto an indra statement
return None
# Try to find the full-text sentence
# Unfortunately, the sentence numbers in the Geneways dataset
# don't correspond to an obvious sentence segmentation.
# This code looks for sentences with the subject, object, and verb
# listed by the Geneways action mention table and only includes
# it in the evidence if there is exactly one such sentence
text = None
if self.get_ft_mention:
try:
content, content_type = get_full_text(mention.pmid, 'pmid')
if content is not None:
ftm = FullTextMention(mention, content)
sentences = ftm.find_matching_sentences()
if len(sentences) == 1:
text = sentences[0]
except Exception:
logger.warning('Could not fetch full text for PMID ' +
mention.pmid)
# Make an evidence object
epistemics = dict()
epistemics['direct'] = is_direct
annotations = mention.make_annotation()
annotations['plo'] = action.plo # plo only in action table
evidence = Evidence(source_api='geneways',
source_id=mention.actionmentionid,
pmid=mention.pmid, text=text,
epistemics=epistemics,
annotations=annotations)
# Construct the grounded and name standardized agents
# Note that this involves grounding the agent by
# converting the Entrez ID listed in the Geneways data with
# HGNC and UniProt
upstream_agent = get_agent(mention.upstream, action.up)
downstream_agent = get_agent(mention.downstream, action.dn)
# Make the statement
return statement_generator(upstream_agent, downstream_agent, evidence) | python | 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:
# Geneways statement does not map onto an indra statement
return None
# Try to find the full-text sentence
# Unfortunately, the sentence numbers in the Geneways dataset
# don't correspond to an obvious sentence segmentation.
# This code looks for sentences with the subject, object, and verb
# listed by the Geneways action mention table and only includes
# it in the evidence if there is exactly one such sentence
text = None
if self.get_ft_mention:
try:
content, content_type = get_full_text(mention.pmid, 'pmid')
if content is not None:
ftm = FullTextMention(mention, content)
sentences = ftm.find_matching_sentences()
if len(sentences) == 1:
text = sentences[0]
except Exception:
logger.warning('Could not fetch full text for PMID ' +
mention.pmid)
# Make an evidence object
epistemics = dict()
epistemics['direct'] = is_direct
annotations = mention.make_annotation()
annotations['plo'] = action.plo # plo only in action table
evidence = Evidence(source_api='geneways',
source_id=mention.actionmentionid,
pmid=mention.pmid, text=text,
epistemics=epistemics,
annotations=annotations)
# Construct the grounded and name standardized agents
# Note that this involves grounding the agent by
# converting the Entrez ID listed in the Geneways data with
# HGNC and UniProt
upstream_agent = get_agent(mention.upstream, action.up)
downstream_agent = get_agent(mention.downstream, action.dn)
# Make the statement
return statement_generator(upstream_agent, downstream_agent, evidence) | [
"def",
"make_statement",
"(",
"self",
",",
"action",
",",
"mention",
")",
":",
"(",
"statement_generator",
",",
"is_direct",
")",
"=",
"geneways_action_to_indra_statement_type",
"(",
"mention",
".",
"actiontype",
",",
"action",
".",
"plo",
")",
"if",
"statement_... | 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 same action if they are
referring to the same relationship - there may be multiple
Geneways action mentions corresponding to each action.
mention : GenewaysActionMention
The Geneways action mention object corresponding to a single
mention of a mechanism in a specific text. We make a new INDRA
statement corresponding to each action mention.
Returns
-------
statement : indra.statements.Statement
An INDRA statement corresponding to the provided Geneways action
mention, or None if the action mention's type does not map onto
any INDRA statement type in geneways_action_type_mapper. | [
"Makes",
"an",
"INDRA",
"statement",
"from",
"a",
"Geneways",
"action",
"and",
"action",
"mention",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/geneways/processor.py#L71-L139 |
18,977 | sorgerlab/indra | indra/preassembler/hierarchy_manager.py | HierarchyManager.load_from_rdf_file | 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')
self.initialize() | python | def load_from_rdf_file(self, rdf_file):
self.graph = rdflib.Graph()
self.graph.parse(os.path.abspath(rdf_file), format='nt')
self.initialize() | [
"def",
"load_from_rdf_file",
"(",
"self",
",",
"rdf_file",
")",
":",
"self",
".",
"graph",
"=",
"rdflib",
".",
"Graph",
"(",
")",
"self",
".",
"graph",
".",
"parse",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"rdf_file",
")",
",",
"format",
"=",
... | Initialize given an RDF input file representing the hierarchy."
Parameters
----------
rdf_file : str
Path to an RDF file. | [
"Initialize",
"given",
"an",
"RDF",
"input",
"file",
"representing",
"the",
"hierarchy",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/preassembler/hierarchy_manager.py#L62-L72 |
18,978 | sorgerlab/indra | indra/preassembler/hierarchy_manager.py | HierarchyManager.load_from_rdf_string | 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.initialize() | python | def load_from_rdf_string(self, rdf_str):
self.graph = rdflib.Graph()
self.graph.parse(data=rdf_str, format='nt')
self.initialize() | [
"def",
"load_from_rdf_string",
"(",
"self",
",",
"rdf_str",
")",
":",
"self",
".",
"graph",
"=",
"rdflib",
".",
"Graph",
"(",
")",
"self",
".",
"graph",
".",
"parse",
"(",
"data",
"=",
"rdf_str",
",",
"format",
"=",
"'nt'",
")",
"self",
".",
"initial... | Initialize given an RDF string representing the hierarchy."
Parameters
----------
rdf_str : str
An RDF string. | [
"Initialize",
"given",
"an",
"RDF",
"string",
"representing",
"the",
"hierarchy",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/preassembler/hierarchy_manager.py#L74-L84 |
18,979 | sorgerlab/indra | indra/preassembler/hierarchy_manager.py | HierarchyManager.extend_with | 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.
"""
self.graph.parse(os.path.abspath(rdf_file), format='nt')
self.initialize() | python | def extend_with(self, rdf_file):
self.graph.parse(os.path.abspath(rdf_file), format='nt')
self.initialize() | [
"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.
Parameters
----------
rdf_file : str
An RDF file which is parsed such that the current graph and the
graph described by the file are merged. | [
"Extend",
"the",
"RDF",
"graph",
"of",
"this",
"HierarchyManager",
"with",
"another",
"RDF",
"file",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/preassembler/hierarchy_manager.py#L116-L126 |
18,980 | sorgerlab/indra | indra/preassembler/hierarchy_manager.py | HierarchyManager.build_transitive_closures | 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
for rel, tc_dict in ((self.isa_objects, self.isa_closure),
(self.partof_objects, self.partof_closure),
(self.isa_or_partof_objects,
self.isa_or_partof_closure)):
self.build_transitive_closure(rel, tc_dict) | python | 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_objects,
self.isa_or_partof_closure)):
self.build_transitive_closure(rel, tc_dict) | [
"def",
"build_transitive_closures",
"(",
"self",
")",
":",
"self",
".",
"component_counter",
"=",
"0",
"for",
"rel",
",",
"tc_dict",
"in",
"(",
"(",
"self",
".",
"isa_objects",
",",
"self",
".",
"isa_closure",
")",
",",
"(",
"self",
".",
"partof_objects",
... | 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. | [
"Build",
"the",
"transitive",
"closures",
"of",
"the",
"hierarchy",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/preassembler/hierarchy_manager.py#L128-L140 |
18,981 | sorgerlab/indra | indra/preassembler/hierarchy_manager.py | HierarchyManager.build_transitive_closure | 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.transitiveClosure(rel_fun, x)
xs = x.toPython()
for y in rel_closure:
ys = y.toPython()
if xs == ys:
continue
try:
tc_dict[xs].append(ys)
except KeyError:
tc_dict[xs] = [ys]
if rel == self.isa_or_partof_objects:
self._add_component(xs, ys) | python | 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)
xs = x.toPython()
for y in rel_closure:
ys = y.toPython()
if xs == ys:
continue
try:
tc_dict[xs].append(ys)
except KeyError:
tc_dict[xs] = [ys]
if rel == self.isa_or_partof_objects:
self._add_component(xs, ys) | [
"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",
".... | Build a transitive closure for a given relation in a given dict. | [
"Build",
"a",
"transitive",
"closure",
"for",
"a",
"given",
"relation",
"in",
"a",
"given",
"dict",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/preassembler/hierarchy_manager.py#L142-L158 |
18,982 | sorgerlab/indra | indra/preassembler/hierarchy_manager.py | HierarchyManager.directly_or_indirectly_related | 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 indirectly.
Parameters
----------
ns1 : str
Namespace code for an entity.
id1 : str
URI for an entity.
ns2 : str
Namespace code for an entity.
id2 : str
URI for an entity.
closure_dict: dict
A dictionary mapping node names to nodes that have the
specified relationship, directly or indirectly. Empty if this
has not been precomputed.
relation_func: function
Function with arguments (node, graph) that generates objects
with some relationship with node on the given graph.
Returns
-------
bool
True if t1 has the specified relationship with t2, either
directly or through a series of intermediates; False otherwise.
"""
# 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 only id1 is None, then it cannot be isa
elif id1 is None:
return False
if closure_dict:
term1 = self.get_uri(ns1, id1)
term2 = self.get_uri(ns2, id2)
ec = closure_dict.get(term1)
if ec is not None and term2 in ec:
return True
else:
return False
else:
if not self.uri_as_name:
e1 = self.find_entity(id1)
e2 = self.find_entity(id2)
if e1 is None or e2 is None:
return False
t1 = rdflib.term.URIRef(e1)
t2 = rdflib.term.URIRef(e2)
else:
u1 = self.get_uri(ns1, id1)
u2 = self.get_uri(ns2, id2)
t1 = rdflib.term.URIRef(u1)
t2 = rdflib.term.URIRef(u2)
to = self.graph.transitiveClosure(relation_func, t1)
if t2 in to:
return True
else:
return False | python | 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 only id1 is None, then it cannot be isa
elif id1 is None:
return False
if closure_dict:
term1 = self.get_uri(ns1, id1)
term2 = self.get_uri(ns2, id2)
ec = closure_dict.get(term1)
if ec is not None and term2 in ec:
return True
else:
return False
else:
if not self.uri_as_name:
e1 = self.find_entity(id1)
e2 = self.find_entity(id2)
if e1 is None or e2 is None:
return False
t1 = rdflib.term.URIRef(e1)
t2 = rdflib.term.URIRef(e2)
else:
u1 = self.get_uri(ns1, id1)
u2 = self.get_uri(ns2, id2)
t1 = rdflib.term.URIRef(u1)
t2 = rdflib.term.URIRef(u2)
to = self.graph.transitiveClosure(relation_func, t1)
if t2 in to:
return True
else:
return False | [
"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"... | Return True if two entities have the speicified relationship.
This relation is constructed possibly through multiple links connecting
the two entities directly or indirectly.
Parameters
----------
ns1 : str
Namespace code for an entity.
id1 : str
URI for an entity.
ns2 : str
Namespace code for an entity.
id2 : str
URI for an entity.
closure_dict: dict
A dictionary mapping node names to nodes that have the
specified relationship, directly or indirectly. Empty if this
has not been precomputed.
relation_func: function
Function with arguments (node, graph) that generates objects
with some relationship with node on the given graph.
Returns
-------
bool
True if t1 has the specified relationship with t2, either
directly or through a series of intermediates; False otherwise. | [
"Return",
"True",
"if",
"two",
"entities",
"have",
"the",
"speicified",
"relationship",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/preassembler/hierarchy_manager.py#L240-L304 |
18,983 | sorgerlab/indra | indra/preassembler/hierarchy_manager.py | HierarchyManager.isa | 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.
id2 : str
URI for an entity.
Returns
-------
bool
True if t1 has an "isa" relationship with t2, either directly or
through a series of intermediates; False otherwise.
"""
rel_fun = lambda node, graph: self.isa_objects(node)
return self.directly_or_indirectly_related(ns1, id1, ns2, id2,
self.isa_closure,
rel_fun) | python | 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,
rel_fun) | [
"def",
"isa",
"(",
"self",
",",
"ns1",
",",
"id1",
",",
"ns2",
",",
"id2",
")",
":",
"rel_fun",
"=",
"lambda",
"node",
",",
"graph",
":",
"self",
".",
"isa_objects",
"(",
"node",
")",
"return",
"self",
".",
"directly_or_indirectly_related",
"(",
"ns1",... | 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.
id2 : str
URI for an entity.
Returns
-------
bool
True if t1 has an "isa" relationship with t2, either directly or
through a series of intermediates; False otherwise. | [
"Return",
"True",
"if",
"one",
"entity",
"has",
"an",
"isa",
"relationship",
"to",
"another",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/preassembler/hierarchy_manager.py#L306-L329 |
18,984 | sorgerlab/indra | indra/preassembler/hierarchy_manager.py | HierarchyManager.partof | 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 : str
URI for an entity.
Returns
-------
bool
True if t1 has a "partof" relationship with t2, either directly or
through a series of intermediates; False otherwise.
"""
rel_fun = lambda node, graph: self.partof_objects(node)
return self.directly_or_indirectly_related(ns1, id1, ns2, id2,
self.partof_closure,
rel_fun) | python | 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,
rel_fun) | [
"def",
"partof",
"(",
"self",
",",
"ns1",
",",
"id1",
",",
"ns2",
",",
"id2",
")",
":",
"rel_fun",
"=",
"lambda",
"node",
",",
"graph",
":",
"self",
".",
"partof_objects",
"(",
"node",
")",
"return",
"self",
".",
"directly_or_indirectly_related",
"(",
... | 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 : str
URI for an entity.
Returns
-------
bool
True if t1 has a "partof" relationship with t2, either directly or
through a series of intermediates; False otherwise. | [
"Return",
"True",
"if",
"one",
"entity",
"is",
"partof",
"another",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/preassembler/hierarchy_manager.py#L331-L354 |
18,985 | sorgerlab/indra | indra/preassembler/hierarchy_manager.py | HierarchyManager.isa_or_partof | 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 for an entity.
id2 : str
URI for an entity.
Returns
-------
bool
True if t1 has a "isa" or "partof" relationship with t2, either
directly or through a series of intermediates; False otherwise.
"""
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,
rel_fun) | python | 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,
rel_fun) | [
"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_relat... | 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 for an entity.
id2 : str
URI for an entity.
Returns
-------
bool
True if t1 has a "isa" or "partof" relationship with t2, either
directly or through a series of intermediates; False otherwise. | [
"Return",
"True",
"if",
"two",
"entities",
"are",
"in",
"an",
"isa",
"or",
"partof",
"relationship"
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/preassembler/hierarchy_manager.py#L356-L379 |
18,986 | sorgerlab/indra | indra/preassembler/hierarchy_manager.py | HierarchyManager.is_opposite | 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 entity.
id2 : str
URI for an entity.
Returns
-------
bool
True if t1 has an "is_opposite" relationship with t2.
"""
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')
to = self.graph.objects(t1, rel)
if t2 in to:
return True
return False | python | 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')
to = self.graph.objects(t1, rel)
if t2 in to:
return True
return False | [
"def",
"is_opposite",
"(",
"self",
",",
"ns1",
",",
"id1",
",",
"ns2",
",",
"id2",
")",
":",
"u1",
"=",
"self",
".",
"get_uri",
"(",
"ns1",
",",
"id1",
")",
"u2",
"=",
"self",
".",
"get_uri",
"(",
"ns2",
",",
"id2",
")",
"t1",
"=",
"rdflib",
... | 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 entity.
id2 : str
URI for an entity.
Returns
-------
bool
True if t1 has an "is_opposite" relationship with t2. | [
"Return",
"True",
"if",
"two",
"entities",
"are",
"in",
"an",
"is_opposite",
"relationship"
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/preassembler/hierarchy_manager.py#L381-L409 |
18,987 | sorgerlab/indra | indra/preassembler/hierarchy_manager.py | HierarchyManager.get_parents | 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
'all': return all parents irrespective of level;
'immediate': return only the immediate parents;
'top': return only the highest level parents
"""
# 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
if not all_parents or type == 'all':
return all_parents
# If we need immediate parents, we search again, this time knowing that
# the uri is definitely in the graph since it has some parents
if type == 'immediate':
node = rdflib.term.URIRef(uri)
immediate_parents = list(set(self.isa_or_partof_objects(node)))
return [p.toPython() for p in immediate_parents]
elif type == 'top':
top_parents = [p for p in all_parents if
not self.isa_or_partof_closure.get(p)]
return top_parents | python | 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
if not all_parents or type == 'all':
return all_parents
# If we need immediate parents, we search again, this time knowing that
# the uri is definitely in the graph since it has some parents
if type == 'immediate':
node = rdflib.term.URIRef(uri)
immediate_parents = list(set(self.isa_or_partof_objects(node)))
return [p.toPython() for p in immediate_parents]
elif type == 'top':
top_parents = [p for p in all_parents if
not self.isa_or_partof_closure.get(p)]
return top_parents | [
"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",
",",
"[",
"]",
")"... | 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
'all': return all parents irrespective of level;
'immediate': return only the immediate parents;
'top': return only the highest level parents | [
"Return",
"parents",
"of",
"a",
"given",
"entry",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/preassembler/hierarchy_manager.py#L411-L439 |
18,988 | sorgerlab/indra | indra/sources/trips/drum_reader.py | _get_perf | 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 | 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 | [
"def",
"_get_perf",
"(",
"text",
",",
"msg_id",
")",
":",
"msg",
"=",
"KQMLPerformative",
"(",
"'REQUEST'",
")",
"msg",
".",
"set",
"(",
"'receiver'",
",",
"'READER'",
")",
"content",
"=",
"KQMLList",
"(",
"'run-text'",
")",
"content",
".",
"sets",
"(",
... | Return a request message for a given text. | [
"Return",
"a",
"request",
"message",
"for",
"a",
"given",
"text",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/trips/drum_reader.py#L156-L164 |
18,989 | sorgerlab/indra | indra/sources/trips/drum_reader.py | DrumReader.read_pmc | 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('receiver', 'READER')
content = KQMLList('run-pmcid')
content.sets('pmcid', pmcid)
content.set('reply-when-done', 'true')
msg.set('content', content)
msg.set('reply-with', 'P-%s' % pmcid)
self.reply_counter += 1
self.send(msg) | python | 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)
msg.set('reply-with', 'P-%s' % pmcid)
self.reply_counter += 1
self.send(msg) | [
"def",
"read_pmc",
"(",
"self",
",",
"pmcid",
")",
":",
"msg",
"=",
"KQMLPerformative",
"(",
"'REQUEST'",
")",
"msg",
".",
"set",
"(",
"'receiver'",
",",
"'READER'",
")",
"content",
"=",
"KQMLList",
"(",
"'run-pmcid'",
")",
"content",
".",
"sets",
"(",
... | 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. | [
"Read",
"a",
"given",
"PMC",
"article",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/trips/drum_reader.py#L87-L104 |
18,990 | sorgerlab/indra | indra/sources/trips/drum_reader.py | DrumReader.read_text | 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(text, msg_id)
self.reply_counter += 1
self.msg_counter += 1
self.send(kqml_perf) | python | 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) | [
"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"... | Read a given text phrase.
Parameters
----------
text : str
The text to read. Typically a sentence or a paragraph. | [
"Read",
"a",
"given",
"text",
"phrase",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/trips/drum_reader.py#L106-L119 |
18,991 | sorgerlab/indra | indra/sources/trips/drum_reader.py | DrumReader.receive_reply | 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('ekb')
self.extractions.append(extractions)
self.reply_counter -= 1
if self.reply_counter == 0:
self.exit(0) | python | 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.gets('ekb')
self.extractions.append(extractions)
self.reply_counter -= 1
if self.reply_counter == 0:
self.exit(0) | [
"def",
"receive_reply",
"(",
"self",
",",
"msg",
",",
"content",
")",
":",
"reply_head",
"=",
"content",
".",
"head",
"(",
")",
"if",
"reply_head",
"==",
"'error'",
":",
"comment",
"=",
"content",
".",
"gets",
"(",
"'comment'",
")",
"logger",
".",
"err... | Handle replies with reading results. | [
"Handle",
"replies",
"with",
"reading",
"results",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/trips/drum_reader.py#L121-L132 |
18,992 | sorgerlab/indra | indra/sources/hume/visualize_causal.py | split_long_sentence | 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_sentence = ''
for i in range(len(words)):
split_sentence = split_sentence + words[i]
if (i+1) % words_per_line == 0:
split_sentence = split_sentence + '\n'
elif i != len(words) - 1:
split_sentence = split_sentence + " "
return split_sentence | python | 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_sentence + '\n'
elif i != len(words) - 1:
split_sentence = split_sentence + " "
return split_sentence | [
"def",
"split_long_sentence",
"(",
"sentence",
",",
"words_per_line",
")",
":",
"words",
"=",
"sentence",
".",
"split",
"(",
"' '",
")",
"split_sentence",
"=",
"''",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"words",
")",
")",
":",
"split_sentence",
"=... | 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 | [
"Takes",
"a",
"sentence",
"and",
"adds",
"a",
"newline",
"every",
"words_per_line",
"words",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/hume/visualize_causal.py#L7-L25 |
18,993 | sorgerlab/indra | indra/sources/hume/visualize_causal.py | shorter_name | 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 ambiguous, identifier
"""
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('.', '_') | python | 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('.', '_') | [
"def",
"shorter_name",
"(",
"key",
")",
":",
"key_short",
"=",
"key",
"for",
"sep",
"in",
"[",
"'#'",
",",
"'/'",
"]",
":",
"ind",
"=",
"key_short",
".",
"rfind",
"(",
"sep",
")",
"if",
"ind",
"is",
"not",
"None",
":",
"key_short",
"=",
"key_short"... | 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 ambiguous, identifier | [
"Return",
"a",
"shorter",
"name",
"for",
"an",
"id",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/hume/visualize_causal.py#L28-L51 |
18,994 | sorgerlab/indra | indra/sources/hume/visualize_causal.py | add_event_property_edges | 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]
value_entry = None
value_str = None
if '@id' in value[0]:
value = value[0]['@id']
if value in entries:
value_str = get_entry_compact_text_repr(entries[value],
entries)
#get_entry_compact_text_repr(entry, entries)
if value_str is not None:
edges.append([shorter_name(event_entity['@id']),
shorter_name(value),
shorter_name(prop)])
node_labels[shorter_name(value)] = value_str | python | 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]
value_entry = None
value_str = None
if '@id' in value[0]:
value = value[0]['@id']
if value in entries:
value_str = get_entry_compact_text_repr(entries[value],
entries)
#get_entry_compact_text_repr(entry, entries)
if value_str is not None:
edges.append([shorter_name(event_entity['@id']),
shorter_name(value),
shorter_name(prop)])
node_labels[shorter_name(value)] = value_str | [
"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"... | Adds edges to the graph for event properties. | [
"Adds",
"edges",
"to",
"the",
"graph",
"for",
"event",
"properties",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/hume/visualize_causal.py#L54-L76 |
18,995 | sorgerlab/indra | indra/sources/hume/visualize_causal.py | get_sourced_from | 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 | 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 | [
"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'",
"]"... | Get a list of values from the source_from attribute | [
"Get",
"a",
"list",
"of",
"values",
"from",
"the",
"source_from",
"attribute"
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/hume/visualize_causal.py#L127-L134 |
18,996 | sorgerlab/indra | indra/sources/hume/visualize_causal.py | get_entry_compact_text_repr | 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:
sources = get_sourced_from(entry)
# There are a lot of references to this entity, each of which refer
# to it by a different text label. For the sake of visualization,
# let's pick one of these labels (in this case, the shortest one)
if sources is not None:
texts = []
for source in sources:
source_entry = entries[source]
texts.append(get_shortest_text_value(source_entry))
return get_shortest_string(texts) | python | 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
# to it by a different text label. For the sake of visualization,
# let's pick one of these labels (in this case, the shortest one)
if sources is not None:
texts = []
for source in sources:
source_entry = entries[source]
texts.append(get_shortest_text_value(source_entry))
return get_shortest_string(texts) | [
"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",
... | 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. | [
"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",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/hume/visualize_causal.py#L137-L154 |
18,997 | sorgerlab/indra | indra/sources/sparser/api.py | process_text | def process_text(text, output_fmt='json', outbuf=None, cleanup=True, key='',
**kwargs):
"""Return processor with Statements extracted by reading text with Sparser.
Parameters
----------
text : str
The text to be processed
output_fmt: Optional[str]
The output format to obtain from Sparser, with the two options being
'json' and 'xml'. Default: 'json'
outbuf : Optional[file]
A file like object that the Sparser output is written to.
cleanup : Optional[bool]
If True, the temporary file created, which is used as an input
file for Sparser, as well as the output file created by Sparser
are removed. Default: True
key : Optional[str]
A key which is embedded into the name of the temporary file
passed to Sparser for reading. Default is empty string.
Returns
-------
SparserXMLProcessor or SparserJSONProcessor depending on what output
format was chosen.
"""
nxml_str = make_nxml_from_text(text)
return process_nxml_str(nxml_str, output_fmt, outbuf, cleanup, key,
**kwargs) | python | 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) | [
"def",
"process_text",
"(",
"text",
",",
"output_fmt",
"=",
"'json'",
",",
"outbuf",
"=",
"None",
",",
"cleanup",
"=",
"True",
",",
"key",
"=",
"''",
",",
"*",
"*",
"kwargs",
")",
":",
"nxml_str",
"=",
"make_nxml_from_text",
"(",
"text",
")",
"return",... | Return processor with Statements extracted by reading text with Sparser.
Parameters
----------
text : str
The text to be processed
output_fmt: Optional[str]
The output format to obtain from Sparser, with the two options being
'json' and 'xml'. Default: 'json'
outbuf : Optional[file]
A file like object that the Sparser output is written to.
cleanup : Optional[bool]
If True, the temporary file created, which is used as an input
file for Sparser, as well as the output file created by Sparser
are removed. Default: True
key : Optional[str]
A key which is embedded into the name of the temporary file
passed to Sparser for reading. Default is empty string.
Returns
-------
SparserXMLProcessor or SparserJSONProcessor depending on what output
format was chosen. | [
"Return",
"processor",
"with",
"Statements",
"extracted",
"by",
"reading",
"text",
"with",
"Sparser",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/sparser/api.py#L31-L59 |
18,998 | sorgerlab/indra | indra/sources/sparser/api.py | process_nxml_str | def process_nxml_str(nxml_str, output_fmt='json', outbuf=None, cleanup=True,
key='', **kwargs):
"""Return processor with Statements extracted by reading an NXML string.
Parameters
----------
nxml_str : str
The string value of the NXML-formatted paper to be read.
output_fmt: Optional[str]
The output format to obtain from Sparser, with the two options being
'json' and 'xml'. Default: 'json'
outbuf : Optional[file]
A file like object that the Sparser output is written to.
cleanup : Optional[bool]
If True, the temporary file created in this function,
which is used as an input file for Sparser, as well as the
output file created by Sparser are removed. Default: True
key : Optional[str]
A key which is embedded into the name of the temporary file
passed to Sparser for reading. Default is empty string.
Returns
-------
SparserXMLProcessor or SparserJSONProcessor depending on what output
format was chosen.
"""
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'))
try:
sp = process_nxml_file(tmp_fname, output_fmt, outbuf, cleanup,
**kwargs)
finally:
if cleanup and os.path.exists(tmp_fname):
os.remove(tmp_fname)
return sp | python | 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'))
try:
sp = process_nxml_file(tmp_fname, output_fmt, outbuf, cleanup,
**kwargs)
finally:
if cleanup and os.path.exists(tmp_fname):
os.remove(tmp_fname)
return sp | [
"def",
"process_nxml_str",
"(",
"nxml_str",
",",
"output_fmt",
"=",
"'json'",
",",
"outbuf",
"=",
"None",
",",
"cleanup",
"=",
"True",
",",
"key",
"=",
"''",
",",
"*",
"*",
"kwargs",
")",
":",
"tmp_fname",
"=",
"'PMC%s_%d.nxml'",
"%",
"(",
"key",
",",
... | Return processor with Statements extracted by reading an NXML string.
Parameters
----------
nxml_str : str
The string value of the NXML-formatted paper to be read.
output_fmt: Optional[str]
The output format to obtain from Sparser, with the two options being
'json' and 'xml'. Default: 'json'
outbuf : Optional[file]
A file like object that the Sparser output is written to.
cleanup : Optional[bool]
If True, the temporary file created in this function,
which is used as an input file for Sparser, as well as the
output file created by Sparser are removed. Default: True
key : Optional[str]
A key which is embedded into the name of the temporary file
passed to Sparser for reading. Default is empty string.
Returns
-------
SparserXMLProcessor or SparserJSONProcessor depending on what output
format was chosen. | [
"Return",
"processor",
"with",
"Statements",
"extracted",
"by",
"reading",
"an",
"NXML",
"string",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/sparser/api.py#L62-L97 |
18,999 | sorgerlab/indra | indra/sources/sparser/api.py | process_nxml_file | def process_nxml_file(fname, output_fmt='json', outbuf=None, cleanup=True,
**kwargs):
"""Return processor with Statements extracted by reading an NXML file.
Parameters
----------
fname : str
The path to the NXML file to be read.
output_fmt: Optional[str]
The output format to obtain from Sparser, with the two options being
'json' and 'xml'. Default: 'json'
outbuf : Optional[file]
A file like object that the Sparser output is written to.
cleanup : Optional[bool]
If True, the output file created by Sparser is removed.
Default: True
Returns
-------
sp : SparserXMLProcessor or SparserJSONProcessor depending on what output
format was chosen.
"""
sp = None
out_fname = None
try:
out_fname = run_sparser(fname, output_fmt, outbuf, **kwargs)
sp = process_sparser_output(out_fname, output_fmt)
except Exception as e:
logger.error("Sparser failed to run on %s." % fname)
logger.exception(e)
finally:
if out_fname is not None and os.path.exists(out_fname) and cleanup:
os.remove(out_fname)
return sp | python | 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, output_fmt)
except Exception as e:
logger.error("Sparser failed to run on %s." % fname)
logger.exception(e)
finally:
if out_fname is not None and os.path.exists(out_fname) and cleanup:
os.remove(out_fname)
return sp | [
"def",
"process_nxml_file",
"(",
"fname",
",",
"output_fmt",
"=",
"'json'",
",",
"outbuf",
"=",
"None",
",",
"cleanup",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"sp",
"=",
"None",
"out_fname",
"=",
"None",
"try",
":",
"out_fname",
"=",
"run_spar... | Return processor with Statements extracted by reading an NXML file.
Parameters
----------
fname : str
The path to the NXML file to be read.
output_fmt: Optional[str]
The output format to obtain from Sparser, with the two options being
'json' and 'xml'. Default: 'json'
outbuf : Optional[file]
A file like object that the Sparser output is written to.
cleanup : Optional[bool]
If True, the output file created by Sparser is removed.
Default: True
Returns
-------
sp : SparserXMLProcessor or SparserJSONProcessor depending on what output
format was chosen. | [
"Return",
"processor",
"with",
"Statements",
"extracted",
"by",
"reading",
"an",
"NXML",
"file",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/sparser/api.py#L100-L134 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.