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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
19,100 | sorgerlab/indra | indra/util/nested_dict.py | NestedDict.gets | def gets(self, key):
"Like `get`, but return all matches, not just the first."
result_list = []
if key in self.keys():
result_list.append(self[key])
for v in self.values():
if isinstance(v, self.__class__):
sub_res_list = v.gets(key)
for res in sub_res_list:
result_list.append(res)
elif isinstance(v, dict):
if key in v.keys():
result_list.append(v[key])
return result_list | python | def gets(self, key):
"Like `get`, but return all matches, not just the first."
result_list = []
if key in self.keys():
result_list.append(self[key])
for v in self.values():
if isinstance(v, self.__class__):
sub_res_list = v.gets(key)
for res in sub_res_list:
result_list.append(res)
elif isinstance(v, dict):
if key in v.keys():
result_list.append(v[key])
return result_list | [
"def",
"gets",
"(",
"self",
",",
"key",
")",
":",
"result_list",
"=",
"[",
"]",
"if",
"key",
"in",
"self",
".",
"keys",
"(",
")",
":",
"result_list",
".",
"append",
"(",
"self",
"[",
"key",
"]",
")",
"for",
"v",
"in",
"self",
".",
"values",
"("... | Like `get`, but return all matches, not just the first. | [
"Like",
"get",
"but",
"return",
"all",
"matches",
"not",
"just",
"the",
"first",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/util/nested_dict.py#L91-L104 |
19,101 | sorgerlab/indra | indra/util/nested_dict.py | NestedDict.get_paths | def get_paths(self, key):
"Like `gets`, but include the paths, like `get_path` for all matches."
result_list = []
if key in self.keys():
result_list.append(((key,), self[key]))
for sub_key, v in self.items():
if isinstance(v, self.__class__):
sub_res_list = v.get_paths(key)
for key_path, res in sub_res_list:
result_list.append(((sub_key,) + key_path, res))
elif isinstance(v, dict):
if key in v.keys():
result_list.append(((sub_key, key), v[key]))
return result_list | python | def get_paths(self, key):
"Like `gets`, but include the paths, like `get_path` for all matches."
result_list = []
if key in self.keys():
result_list.append(((key,), self[key]))
for sub_key, v in self.items():
if isinstance(v, self.__class__):
sub_res_list = v.get_paths(key)
for key_path, res in sub_res_list:
result_list.append(((sub_key,) + key_path, res))
elif isinstance(v, dict):
if key in v.keys():
result_list.append(((sub_key, key), v[key]))
return result_list | [
"def",
"get_paths",
"(",
"self",
",",
"key",
")",
":",
"result_list",
"=",
"[",
"]",
"if",
"key",
"in",
"self",
".",
"keys",
"(",
")",
":",
"result_list",
".",
"append",
"(",
"(",
"(",
"key",
",",
")",
",",
"self",
"[",
"key",
"]",
")",
")",
... | Like `gets`, but include the paths, like `get_path` for all matches. | [
"Like",
"gets",
"but",
"include",
"the",
"paths",
"like",
"get_path",
"for",
"all",
"matches",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/util/nested_dict.py#L106-L119 |
19,102 | sorgerlab/indra | indra/util/nested_dict.py | NestedDict.get_leaves | def get_leaves(self):
"""Get the deepest entries as a flat set."""
ret_set = set()
for val in self.values():
if isinstance(val, self.__class__):
ret_set |= val.get_leaves()
elif isinstance(val, dict):
ret_set |= set(val.values())
elif isinstance(val, list):
ret_set |= set(val)
elif isinstance(val, set):
ret_set |= val
else:
ret_set.add(val)
return ret_set | python | def get_leaves(self):
ret_set = set()
for val in self.values():
if isinstance(val, self.__class__):
ret_set |= val.get_leaves()
elif isinstance(val, dict):
ret_set |= set(val.values())
elif isinstance(val, list):
ret_set |= set(val)
elif isinstance(val, set):
ret_set |= val
else:
ret_set.add(val)
return ret_set | [
"def",
"get_leaves",
"(",
"self",
")",
":",
"ret_set",
"=",
"set",
"(",
")",
"for",
"val",
"in",
"self",
".",
"values",
"(",
")",
":",
"if",
"isinstance",
"(",
"val",
",",
"self",
".",
"__class__",
")",
":",
"ret_set",
"|=",
"val",
".",
"get_leaves... | Get the deepest entries as a flat set. | [
"Get",
"the",
"deepest",
"entries",
"as",
"a",
"flat",
"set",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/util/nested_dict.py#L121-L135 |
19,103 | sorgerlab/indra | indra/sources/reach/processor.py | determine_reach_subtype | def determine_reach_subtype(event_name):
"""Returns the category of reach rule from the reach rule instance.
Looks at a list of regular
expressions corresponding to reach rule types, and returns the longest
regexp that matches, or None if none of them match.
Parameters
----------
evidence : indra.statements.Evidence
A reach evidence object to subtype
Returns
-------
best_match : str
A regular expression corresponding to the reach rule that was used to
extract this evidence
"""
best_match_length = None
best_match = None
for ss in reach_rule_regexps:
if re.search(ss, event_name):
if best_match is None or len(ss) > best_match_length:
best_match = ss
best_match_length = len(ss)
return best_match | python | def determine_reach_subtype(event_name):
best_match_length = None
best_match = None
for ss in reach_rule_regexps:
if re.search(ss, event_name):
if best_match is None or len(ss) > best_match_length:
best_match = ss
best_match_length = len(ss)
return best_match | [
"def",
"determine_reach_subtype",
"(",
"event_name",
")",
":",
"best_match_length",
"=",
"None",
"best_match",
"=",
"None",
"for",
"ss",
"in",
"reach_rule_regexps",
":",
"if",
"re",
".",
"search",
"(",
"ss",
",",
"event_name",
")",
":",
"if",
"best_match",
"... | Returns the category of reach rule from the reach rule instance.
Looks at a list of regular
expressions corresponding to reach rule types, and returns the longest
regexp that matches, or None if none of them match.
Parameters
----------
evidence : indra.statements.Evidence
A reach evidence object to subtype
Returns
-------
best_match : str
A regular expression corresponding to the reach rule that was used to
extract this evidence | [
"Returns",
"the",
"category",
"of",
"reach",
"rule",
"from",
"the",
"reach",
"rule",
"instance",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/reach/processor.py#L835-L862 |
19,104 | sorgerlab/indra | indra/sources/reach/processor.py | ReachProcessor.print_event_statistics | def print_event_statistics(self):
"""Print the number of events in the REACH output by type."""
logger.info('All events by type')
logger.info('-------------------')
for k, v in self.all_events.items():
logger.info('%s, %s' % (k, len(v)))
logger.info('-------------------') | python | def print_event_statistics(self):
logger.info('All events by type')
logger.info('-------------------')
for k, v in self.all_events.items():
logger.info('%s, %s' % (k, len(v)))
logger.info('-------------------') | [
"def",
"print_event_statistics",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"'All events by type'",
")",
"logger",
".",
"info",
"(",
"'-------------------'",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"all_events",
".",
"items",
"(",
")",
":",
... | Print the number of events in the REACH output by type. | [
"Print",
"the",
"number",
"of",
"events",
"in",
"the",
"REACH",
"output",
"by",
"type",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/reach/processor.py#L52-L58 |
19,105 | sorgerlab/indra | indra/sources/reach/processor.py | ReachProcessor.get_all_events | def get_all_events(self):
"""Gather all event IDs in the REACH output by type.
These IDs are stored in the self.all_events dict.
"""
self.all_events = {}
events = self.tree.execute("$.events.frames")
if events is None:
return
for e in events:
event_type = e.get('type')
frame_id = e.get('frame_id')
try:
self.all_events[event_type].append(frame_id)
except KeyError:
self.all_events[event_type] = [frame_id] | python | def get_all_events(self):
self.all_events = {}
events = self.tree.execute("$.events.frames")
if events is None:
return
for e in events:
event_type = e.get('type')
frame_id = e.get('frame_id')
try:
self.all_events[event_type].append(frame_id)
except KeyError:
self.all_events[event_type] = [frame_id] | [
"def",
"get_all_events",
"(",
"self",
")",
":",
"self",
".",
"all_events",
"=",
"{",
"}",
"events",
"=",
"self",
".",
"tree",
".",
"execute",
"(",
"\"$.events.frames\"",
")",
"if",
"events",
"is",
"None",
":",
"return",
"for",
"e",
"in",
"events",
":",... | Gather all event IDs in the REACH output by type.
These IDs are stored in the self.all_events dict. | [
"Gather",
"all",
"event",
"IDs",
"in",
"the",
"REACH",
"output",
"by",
"type",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/reach/processor.py#L60-L75 |
19,106 | sorgerlab/indra | indra/sources/reach/processor.py | ReachProcessor.get_modifications | def get_modifications(self):
"""Extract Modification INDRA Statements."""
# Find all event frames that are a type of protein modification
qstr = "$.events.frames[(@.type is 'protein-modification')]"
res = self.tree.execute(qstr)
if res is None:
return
# Extract each of the results when possible
for r in res:
# The subtype of the modification
modification_type = r.get('subtype')
# Skip negated events (i.e. something doesn't happen)
epistemics = self._get_epistemics(r)
if epistemics.get('negated'):
continue
annotations, context = self._get_annot_context(r)
frame_id = r['frame_id']
args = r['arguments']
site = None
theme = None
# Find the substrate (the "theme" agent here) and the
# site and position it is modified on
for a in args:
if self._get_arg_type(a) == 'theme':
theme = a['arg']
elif self._get_arg_type(a) == 'site':
site = a['text']
theme_agent, theme_coords = self._get_agent_from_entity(theme)
if site is not None:
mods = self._parse_site_text(site)
else:
mods = [(None, None)]
for mod in mods:
# Add up to one statement for each site
residue, pos = mod
# Now we need to look for all regulation event to get to the
# enzymes (the "controller" here)
qstr = "$.events.frames[(@.type is 'regulation') and " + \
"(@.arguments[0].arg is '%s')]" % frame_id
reg_res = self.tree.execute(qstr)
reg_res = list(reg_res)
for reg in reg_res:
controller_agent, controller_coords = None, None
for a in reg['arguments']:
if self._get_arg_type(a) == 'controller':
controller = a.get('arg')
if controller is not None:
controller_agent, controller_coords = \
self._get_agent_from_entity(controller)
break
# Check the polarity of the regulation and if negative,
# flip the modification type.
# For instance, negative-regulation of a phosphorylation
# will become an (indirect) dephosphorylation
reg_subtype = reg.get('subtype')
if reg_subtype == 'negative-regulation':
modification_type = \
modtype_to_inverse.get(modification_type)
if not modification_type:
logger.warning('Unhandled modification type: %s' %
modification_type)
continue
sentence = reg['verbose-text']
annotations['agents']['coords'] = [controller_coords,
theme_coords]
ev = Evidence(source_api='reach', text=sentence,
annotations=annotations, pmid=self.citation,
context=context, epistemics=epistemics)
args = [controller_agent, theme_agent, residue, pos, ev]
# Here ModStmt is a sub-class of Modification
ModStmt = modtype_to_modclass.get(modification_type)
if ModStmt is None:
logger.warning('Unhandled modification type: %s' %
modification_type)
else:
# Handle this special case here because only
# enzyme argument is needed
if modification_type == 'autophosphorylation':
args = [theme_agent, residue, pos, ev]
self.statements.append(ModStmt(*args)) | python | def get_modifications(self):
# Find all event frames that are a type of protein modification
qstr = "$.events.frames[(@.type is 'protein-modification')]"
res = self.tree.execute(qstr)
if res is None:
return
# Extract each of the results when possible
for r in res:
# The subtype of the modification
modification_type = r.get('subtype')
# Skip negated events (i.e. something doesn't happen)
epistemics = self._get_epistemics(r)
if epistemics.get('negated'):
continue
annotations, context = self._get_annot_context(r)
frame_id = r['frame_id']
args = r['arguments']
site = None
theme = None
# Find the substrate (the "theme" agent here) and the
# site and position it is modified on
for a in args:
if self._get_arg_type(a) == 'theme':
theme = a['arg']
elif self._get_arg_type(a) == 'site':
site = a['text']
theme_agent, theme_coords = self._get_agent_from_entity(theme)
if site is not None:
mods = self._parse_site_text(site)
else:
mods = [(None, None)]
for mod in mods:
# Add up to one statement for each site
residue, pos = mod
# Now we need to look for all regulation event to get to the
# enzymes (the "controller" here)
qstr = "$.events.frames[(@.type is 'regulation') and " + \
"(@.arguments[0].arg is '%s')]" % frame_id
reg_res = self.tree.execute(qstr)
reg_res = list(reg_res)
for reg in reg_res:
controller_agent, controller_coords = None, None
for a in reg['arguments']:
if self._get_arg_type(a) == 'controller':
controller = a.get('arg')
if controller is not None:
controller_agent, controller_coords = \
self._get_agent_from_entity(controller)
break
# Check the polarity of the regulation and if negative,
# flip the modification type.
# For instance, negative-regulation of a phosphorylation
# will become an (indirect) dephosphorylation
reg_subtype = reg.get('subtype')
if reg_subtype == 'negative-regulation':
modification_type = \
modtype_to_inverse.get(modification_type)
if not modification_type:
logger.warning('Unhandled modification type: %s' %
modification_type)
continue
sentence = reg['verbose-text']
annotations['agents']['coords'] = [controller_coords,
theme_coords]
ev = Evidence(source_api='reach', text=sentence,
annotations=annotations, pmid=self.citation,
context=context, epistemics=epistemics)
args = [controller_agent, theme_agent, residue, pos, ev]
# Here ModStmt is a sub-class of Modification
ModStmt = modtype_to_modclass.get(modification_type)
if ModStmt is None:
logger.warning('Unhandled modification type: %s' %
modification_type)
else:
# Handle this special case here because only
# enzyme argument is needed
if modification_type == 'autophosphorylation':
args = [theme_agent, residue, pos, ev]
self.statements.append(ModStmt(*args)) | [
"def",
"get_modifications",
"(",
"self",
")",
":",
"# Find all event frames that are a type of protein modification",
"qstr",
"=",
"\"$.events.frames[(@.type is 'protein-modification')]\"",
"res",
"=",
"self",
".",
"tree",
".",
"execute",
"(",
"qstr",
")",
"if",
"res",
"i... | Extract Modification INDRA Statements. | [
"Extract",
"Modification",
"INDRA",
"Statements",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/reach/processor.py#L87-L173 |
19,107 | sorgerlab/indra | indra/sources/reach/processor.py | ReachProcessor.get_regulate_amounts | def get_regulate_amounts(self):
"""Extract RegulateAmount INDRA Statements."""
qstr = "$.events.frames[(@.type is 'transcription')]"
res = self.tree.execute(qstr)
all_res = []
if res is not None:
all_res += list(res)
qstr = "$.events.frames[(@.type is 'amount')]"
res = self.tree.execute(qstr)
if res is not None:
all_res += list(res)
for r in all_res:
subtype = r.get('subtype')
epistemics = self._get_epistemics(r)
if epistemics.get('negated'):
continue
annotations, context = self._get_annot_context(r)
frame_id = r['frame_id']
args = r['arguments']
theme = None
for a in args:
if self._get_arg_type(a) == 'theme':
theme = a['arg']
break
if theme is None:
continue
theme_agent, theme_coords = self._get_agent_from_entity(theme)
qstr = "$.events.frames[(@.type is 'regulation') and " + \
"(@.arguments[0].arg is '%s')]" % frame_id
reg_res = self.tree.execute(qstr)
for reg in reg_res:
controller_agent, controller_coords = None, None
for a in reg['arguments']:
if self._get_arg_type(a) == 'controller':
controller_agent, controller_coords = \
self._get_controller_agent(a)
sentence = reg['verbose-text']
annotations['agents']['coords'] = [controller_coords,
theme_coords]
ev = Evidence(source_api='reach', text=sentence,
annotations=annotations, pmid=self.citation,
context=context, epistemics=epistemics)
args = [controller_agent, theme_agent, ev]
subtype = reg.get('subtype')
if subtype == 'positive-regulation':
st = IncreaseAmount(*args)
else:
st = DecreaseAmount(*args)
self.statements.append(st) | python | def get_regulate_amounts(self):
qstr = "$.events.frames[(@.type is 'transcription')]"
res = self.tree.execute(qstr)
all_res = []
if res is not None:
all_res += list(res)
qstr = "$.events.frames[(@.type is 'amount')]"
res = self.tree.execute(qstr)
if res is not None:
all_res += list(res)
for r in all_res:
subtype = r.get('subtype')
epistemics = self._get_epistemics(r)
if epistemics.get('negated'):
continue
annotations, context = self._get_annot_context(r)
frame_id = r['frame_id']
args = r['arguments']
theme = None
for a in args:
if self._get_arg_type(a) == 'theme':
theme = a['arg']
break
if theme is None:
continue
theme_agent, theme_coords = self._get_agent_from_entity(theme)
qstr = "$.events.frames[(@.type is 'regulation') and " + \
"(@.arguments[0].arg is '%s')]" % frame_id
reg_res = self.tree.execute(qstr)
for reg in reg_res:
controller_agent, controller_coords = None, None
for a in reg['arguments']:
if self._get_arg_type(a) == 'controller':
controller_agent, controller_coords = \
self._get_controller_agent(a)
sentence = reg['verbose-text']
annotations['agents']['coords'] = [controller_coords,
theme_coords]
ev = Evidence(source_api='reach', text=sentence,
annotations=annotations, pmid=self.citation,
context=context, epistemics=epistemics)
args = [controller_agent, theme_agent, ev]
subtype = reg.get('subtype')
if subtype == 'positive-regulation':
st = IncreaseAmount(*args)
else:
st = DecreaseAmount(*args)
self.statements.append(st) | [
"def",
"get_regulate_amounts",
"(",
"self",
")",
":",
"qstr",
"=",
"\"$.events.frames[(@.type is 'transcription')]\"",
"res",
"=",
"self",
".",
"tree",
".",
"execute",
"(",
"qstr",
")",
"all_res",
"=",
"[",
"]",
"if",
"res",
"is",
"not",
"None",
":",
"all_re... | Extract RegulateAmount INDRA Statements. | [
"Extract",
"RegulateAmount",
"INDRA",
"Statements",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/reach/processor.py#L175-L224 |
19,108 | sorgerlab/indra | indra/sources/reach/processor.py | ReachProcessor.get_complexes | def get_complexes(self):
"""Extract INDRA Complex Statements."""
qstr = "$.events.frames[@.type is 'complex-assembly']"
res = self.tree.execute(qstr)
if res is None:
return
for r in res:
epistemics = self._get_epistemics(r)
if epistemics.get('negated'):
continue
# Due to an issue with the REACH output serialization
# (though seemingly not with the raw mentions), sometimes
# a redundant complex-assembly event is reported which can
# be recognized by the missing direct flag, which we can filter
# for here
if epistemics.get('direct') is None:
continue
annotations, context = self._get_annot_context(r)
args = r['arguments']
sentence = r['verbose-text']
members = []
agent_coordinates = []
for a in args:
agent, coords = self._get_agent_from_entity(a['arg'])
members.append(agent)
agent_coordinates.append(coords)
annotations['agents']['coords'] = agent_coordinates
ev = Evidence(source_api='reach', text=sentence,
annotations=annotations, pmid=self.citation,
context=context, epistemics=epistemics)
stmt = Complex(members, ev)
self.statements.append(stmt) | python | def get_complexes(self):
qstr = "$.events.frames[@.type is 'complex-assembly']"
res = self.tree.execute(qstr)
if res is None:
return
for r in res:
epistemics = self._get_epistemics(r)
if epistemics.get('negated'):
continue
# Due to an issue with the REACH output serialization
# (though seemingly not with the raw mentions), sometimes
# a redundant complex-assembly event is reported which can
# be recognized by the missing direct flag, which we can filter
# for here
if epistemics.get('direct') is None:
continue
annotations, context = self._get_annot_context(r)
args = r['arguments']
sentence = r['verbose-text']
members = []
agent_coordinates = []
for a in args:
agent, coords = self._get_agent_from_entity(a['arg'])
members.append(agent)
agent_coordinates.append(coords)
annotations['agents']['coords'] = agent_coordinates
ev = Evidence(source_api='reach', text=sentence,
annotations=annotations, pmid=self.citation,
context=context, epistemics=epistemics)
stmt = Complex(members, ev)
self.statements.append(stmt) | [
"def",
"get_complexes",
"(",
"self",
")",
":",
"qstr",
"=",
"\"$.events.frames[@.type is 'complex-assembly']\"",
"res",
"=",
"self",
".",
"tree",
".",
"execute",
"(",
"qstr",
")",
"if",
"res",
"is",
"None",
":",
"return",
"for",
"r",
"in",
"res",
":",
"epi... | Extract INDRA Complex Statements. | [
"Extract",
"INDRA",
"Complex",
"Statements",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/reach/processor.py#L226-L258 |
19,109 | sorgerlab/indra | indra/sources/reach/processor.py | ReachProcessor.get_activation | def get_activation(self):
"""Extract INDRA Activation Statements."""
qstr = "$.events.frames[@.type is 'activation']"
res = self.tree.execute(qstr)
if res is None:
return
for r in res:
epistemics = self._get_epistemics(r)
if epistemics.get('negated'):
continue
sentence = r['verbose-text']
annotations, context = self._get_annot_context(r)
ev = Evidence(source_api='reach', text=sentence,
pmid=self.citation, annotations=annotations,
context=context, epistemics=epistemics)
args = r['arguments']
for a in args:
if self._get_arg_type(a) == 'controller':
controller_agent, controller_coords = \
self._get_controller_agent(a)
if self._get_arg_type(a) == 'controlled':
controlled = a['arg']
controlled_agent, controlled_coords = \
self._get_agent_from_entity(controlled)
annotations['agents']['coords'] = [controller_coords,
controlled_coords]
if r['subtype'] == 'positive-activation':
st = Activation(controller_agent, controlled_agent,
evidence=ev)
else:
st = Inhibition(controller_agent, controlled_agent,
evidence=ev)
self.statements.append(st) | python | def get_activation(self):
qstr = "$.events.frames[@.type is 'activation']"
res = self.tree.execute(qstr)
if res is None:
return
for r in res:
epistemics = self._get_epistemics(r)
if epistemics.get('negated'):
continue
sentence = r['verbose-text']
annotations, context = self._get_annot_context(r)
ev = Evidence(source_api='reach', text=sentence,
pmid=self.citation, annotations=annotations,
context=context, epistemics=epistemics)
args = r['arguments']
for a in args:
if self._get_arg_type(a) == 'controller':
controller_agent, controller_coords = \
self._get_controller_agent(a)
if self._get_arg_type(a) == 'controlled':
controlled = a['arg']
controlled_agent, controlled_coords = \
self._get_agent_from_entity(controlled)
annotations['agents']['coords'] = [controller_coords,
controlled_coords]
if r['subtype'] == 'positive-activation':
st = Activation(controller_agent, controlled_agent,
evidence=ev)
else:
st = Inhibition(controller_agent, controlled_agent,
evidence=ev)
self.statements.append(st) | [
"def",
"get_activation",
"(",
"self",
")",
":",
"qstr",
"=",
"\"$.events.frames[@.type is 'activation']\"",
"res",
"=",
"self",
".",
"tree",
".",
"execute",
"(",
"qstr",
")",
"if",
"res",
"is",
"None",
":",
"return",
"for",
"r",
"in",
"res",
":",
"epistemi... | Extract INDRA Activation Statements. | [
"Extract",
"INDRA",
"Activation",
"Statements",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/reach/processor.py#L260-L292 |
19,110 | sorgerlab/indra | indra/sources/reach/processor.py | ReachProcessor.get_translocation | def get_translocation(self):
"""Extract INDRA Translocation Statements."""
qstr = "$.events.frames[@.type is 'translocation']"
res = self.tree.execute(qstr)
if res is None:
return
for r in res:
epistemics = self._get_epistemics(r)
if epistemics.get('negated'):
continue
sentence = r['verbose-text']
annotations, context = self._get_annot_context(r)
args = r['arguments']
from_location = None
to_location = None
for a in args:
if self._get_arg_type(a) == 'theme':
agent, theme_coords = self._get_agent_from_entity(a['arg'])
if agent is None:
continue
elif self._get_arg_type(a) == 'source':
from_location = self._get_location_by_id(a['arg'])
elif self._get_arg_type(a) == 'destination':
to_location = self._get_location_by_id(a['arg'])
annotations['agents']['coords'] = [theme_coords]
ev = Evidence(source_api='reach', text=sentence,
pmid=self.citation, annotations=annotations,
context=context, epistemics=epistemics)
st = Translocation(agent, from_location, to_location,
evidence=ev)
self.statements.append(st) | python | def get_translocation(self):
qstr = "$.events.frames[@.type is 'translocation']"
res = self.tree.execute(qstr)
if res is None:
return
for r in res:
epistemics = self._get_epistemics(r)
if epistemics.get('negated'):
continue
sentence = r['verbose-text']
annotations, context = self._get_annot_context(r)
args = r['arguments']
from_location = None
to_location = None
for a in args:
if self._get_arg_type(a) == 'theme':
agent, theme_coords = self._get_agent_from_entity(a['arg'])
if agent is None:
continue
elif self._get_arg_type(a) == 'source':
from_location = self._get_location_by_id(a['arg'])
elif self._get_arg_type(a) == 'destination':
to_location = self._get_location_by_id(a['arg'])
annotations['agents']['coords'] = [theme_coords]
ev = Evidence(source_api='reach', text=sentence,
pmid=self.citation, annotations=annotations,
context=context, epistemics=epistemics)
st = Translocation(agent, from_location, to_location,
evidence=ev)
self.statements.append(st) | [
"def",
"get_translocation",
"(",
"self",
")",
":",
"qstr",
"=",
"\"$.events.frames[@.type is 'translocation']\"",
"res",
"=",
"self",
".",
"tree",
".",
"execute",
"(",
"qstr",
")",
"if",
"res",
"is",
"None",
":",
"return",
"for",
"r",
"in",
"res",
":",
"ep... | Extract INDRA Translocation Statements. | [
"Extract",
"INDRA",
"Translocation",
"Statements",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/reach/processor.py#L294-L324 |
19,111 | sorgerlab/indra | indra/sources/reach/processor.py | ReachProcessor._get_mod_conditions | def _get_mod_conditions(self, mod_term):
"""Return a list of ModConditions given a mod term dict."""
site = mod_term.get('site')
if site is not None:
mods = self._parse_site_text(site)
else:
mods = [Site(None, None)]
mcs = []
for mod in mods:
mod_res, mod_pos = mod
mod_type_str = mod_term['type'].lower()
mod_state = agent_mod_map.get(mod_type_str)
if mod_state is not None:
mc = ModCondition(mod_state[0], residue=mod_res,
position=mod_pos, is_modified=mod_state[1])
mcs.append(mc)
else:
logger.warning('Unhandled entity modification type: %s'
% mod_type_str)
return mcs | python | def _get_mod_conditions(self, mod_term):
site = mod_term.get('site')
if site is not None:
mods = self._parse_site_text(site)
else:
mods = [Site(None, None)]
mcs = []
for mod in mods:
mod_res, mod_pos = mod
mod_type_str = mod_term['type'].lower()
mod_state = agent_mod_map.get(mod_type_str)
if mod_state is not None:
mc = ModCondition(mod_state[0], residue=mod_res,
position=mod_pos, is_modified=mod_state[1])
mcs.append(mc)
else:
logger.warning('Unhandled entity modification type: %s'
% mod_type_str)
return mcs | [
"def",
"_get_mod_conditions",
"(",
"self",
",",
"mod_term",
")",
":",
"site",
"=",
"mod_term",
".",
"get",
"(",
"'site'",
")",
"if",
"site",
"is",
"not",
"None",
":",
"mods",
"=",
"self",
".",
"_parse_site_text",
"(",
"site",
")",
"else",
":",
"mods",
... | Return a list of ModConditions given a mod term dict. | [
"Return",
"a",
"list",
"of",
"ModConditions",
"given",
"a",
"mod",
"term",
"dict",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/reach/processor.py#L469-L489 |
19,112 | sorgerlab/indra | indra/sources/reach/processor.py | ReachProcessor._get_entity_coordinates | def _get_entity_coordinates(self, entity_term):
"""Return sentence coordinates for a given entity.
Given an entity term return the associated sentence coordinates as
a tuple of the form (int, int). Returns None if for any reason the
sentence coordinates cannot be found.
"""
# The following lines get the starting coordinate of the sentence
# containing the entity.
sent_id = entity_term.get('sentence')
if sent_id is None:
return None
qstr = "$.sentences.frames[(@.frame_id is \'%s')]" % sent_id
res = self.tree.execute(qstr)
if res is None:
return None
try:
sentence = next(res)
except StopIteration:
return None
sent_start = sentence.get('start-pos')
if sent_start is None:
return None
sent_start = sent_start.get('offset')
if sent_start is None:
return None
# Get the entity coordinate in the entire text and subtract the
# coordinate of the first character in the associated sentence to
# get the sentence coordinate of the entity. Return None if entity
# coordinates are missing
entity_start = entity_term.get('start-pos')
entity_stop = entity_term.get('end-pos')
if entity_start is None or entity_stop is None:
return None
entity_start = entity_start.get('offset')
entity_stop = entity_stop.get('offset')
if entity_start is None or entity_stop is None:
return None
return (entity_start - sent_start, entity_stop - sent_start) | python | def _get_entity_coordinates(self, entity_term):
# The following lines get the starting coordinate of the sentence
# containing the entity.
sent_id = entity_term.get('sentence')
if sent_id is None:
return None
qstr = "$.sentences.frames[(@.frame_id is \'%s')]" % sent_id
res = self.tree.execute(qstr)
if res is None:
return None
try:
sentence = next(res)
except StopIteration:
return None
sent_start = sentence.get('start-pos')
if sent_start is None:
return None
sent_start = sent_start.get('offset')
if sent_start is None:
return None
# Get the entity coordinate in the entire text and subtract the
# coordinate of the first character in the associated sentence to
# get the sentence coordinate of the entity. Return None if entity
# coordinates are missing
entity_start = entity_term.get('start-pos')
entity_stop = entity_term.get('end-pos')
if entity_start is None or entity_stop is None:
return None
entity_start = entity_start.get('offset')
entity_stop = entity_stop.get('offset')
if entity_start is None or entity_stop is None:
return None
return (entity_start - sent_start, entity_stop - sent_start) | [
"def",
"_get_entity_coordinates",
"(",
"self",
",",
"entity_term",
")",
":",
"# The following lines get the starting coordinate of the sentence",
"# containing the entity.",
"sent_id",
"=",
"entity_term",
".",
"get",
"(",
"'sentence'",
")",
"if",
"sent_id",
"is",
"None",
... | Return sentence coordinates for a given entity.
Given an entity term return the associated sentence coordinates as
a tuple of the form (int, int). Returns None if for any reason the
sentence coordinates cannot be found. | [
"Return",
"sentence",
"coordinates",
"for",
"a",
"given",
"entity",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/reach/processor.py#L491-L529 |
19,113 | sorgerlab/indra | indra/sources/reach/processor.py | ReachProcessor._get_section | def _get_section(self, event):
"""Get the section of the paper that the event is from."""
sentence_id = event.get('sentence')
section = None
if sentence_id:
qstr = "$.sentences.frames[(@.frame_id is \'%s\')]" % sentence_id
res = self.tree.execute(qstr)
if res:
sentence_frame = list(res)[0]
passage_id = sentence_frame.get('passage')
if passage_id:
qstr = "$.sentences.frames[(@.frame_id is \'%s\')]" % \
passage_id
res = self.tree.execute(qstr)
if res:
passage_frame = list(res)[0]
section = passage_frame.get('section-id')
# If the section is in the standard list, return as is
if section in self._section_list:
return section
# Next, handle a few special cases that come up in practice
elif section.startswith('fig'):
return 'figure'
elif section.startswith('supm'):
return 'supplementary'
elif section == 'article-title':
return 'title'
elif section in ['subjects|methods', 'methods|subjects']:
return 'methods'
elif section == 'conclusions':
return 'conclusion'
elif section == 'intro':
return 'introduction'
else:
return None | python | def _get_section(self, event):
sentence_id = event.get('sentence')
section = None
if sentence_id:
qstr = "$.sentences.frames[(@.frame_id is \'%s\')]" % sentence_id
res = self.tree.execute(qstr)
if res:
sentence_frame = list(res)[0]
passage_id = sentence_frame.get('passage')
if passage_id:
qstr = "$.sentences.frames[(@.frame_id is \'%s\')]" % \
passage_id
res = self.tree.execute(qstr)
if res:
passage_frame = list(res)[0]
section = passage_frame.get('section-id')
# If the section is in the standard list, return as is
if section in self._section_list:
return section
# Next, handle a few special cases that come up in practice
elif section.startswith('fig'):
return 'figure'
elif section.startswith('supm'):
return 'supplementary'
elif section == 'article-title':
return 'title'
elif section in ['subjects|methods', 'methods|subjects']:
return 'methods'
elif section == 'conclusions':
return 'conclusion'
elif section == 'intro':
return 'introduction'
else:
return None | [
"def",
"_get_section",
"(",
"self",
",",
"event",
")",
":",
"sentence_id",
"=",
"event",
".",
"get",
"(",
"'sentence'",
")",
"section",
"=",
"None",
"if",
"sentence_id",
":",
"qstr",
"=",
"\"$.sentences.frames[(@.frame_id is \\'%s\\')]\"",
"%",
"sentence_id",
"r... | Get the section of the paper that the event is from. | [
"Get",
"the",
"section",
"of",
"the",
"paper",
"that",
"the",
"event",
"is",
"from",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/reach/processor.py#L610-L644 |
19,114 | sorgerlab/indra | indra/sources/reach/processor.py | ReachProcessor._get_controller_agent | def _get_controller_agent(self, arg):
"""Return a single or a complex controller agent."""
controller_agent = None
controller = arg.get('arg')
# There is either a single controller here
if controller is not None:
controller_agent, coords = self._get_agent_from_entity(controller)
# Or the controller is a complex
elif arg['argument-type'] == 'complex':
controllers = list(arg.get('args').values())
controller_agent, coords = \
self._get_agent_from_entity(controllers[0])
bound_agents = [self._get_agent_from_entity(c)[0]
for c in controllers[1:]]
bound_conditions = [BoundCondition(ba, True) for
ba in bound_agents]
controller_agent.bound_conditions = bound_conditions
return controller_agent, coords | python | def _get_controller_agent(self, arg):
controller_agent = None
controller = arg.get('arg')
# There is either a single controller here
if controller is not None:
controller_agent, coords = self._get_agent_from_entity(controller)
# Or the controller is a complex
elif arg['argument-type'] == 'complex':
controllers = list(arg.get('args').values())
controller_agent, coords = \
self._get_agent_from_entity(controllers[0])
bound_agents = [self._get_agent_from_entity(c)[0]
for c in controllers[1:]]
bound_conditions = [BoundCondition(ba, True) for
ba in bound_agents]
controller_agent.bound_conditions = bound_conditions
return controller_agent, coords | [
"def",
"_get_controller_agent",
"(",
"self",
",",
"arg",
")",
":",
"controller_agent",
"=",
"None",
"controller",
"=",
"arg",
".",
"get",
"(",
"'arg'",
")",
"# There is either a single controller here",
"if",
"controller",
"is",
"not",
"None",
":",
"controller_age... | Return a single or a complex controller agent. | [
"Return",
"a",
"single",
"or",
"a",
"complex",
"controller",
"agent",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/reach/processor.py#L646-L663 |
19,115 | sorgerlab/indra | indra/sources/eidos/processor.py | _sanitize | def _sanitize(text):
"""Return sanitized Eidos text field for human readability."""
d = {'-LRB-': '(', '-RRB-': ')'}
return re.sub('|'.join(d.keys()), lambda m: d[m.group(0)], text) | python | def _sanitize(text):
d = {'-LRB-': '(', '-RRB-': ')'}
return re.sub('|'.join(d.keys()), lambda m: d[m.group(0)], text) | [
"def",
"_sanitize",
"(",
"text",
")",
":",
"d",
"=",
"{",
"'-LRB-'",
":",
"'('",
",",
"'-RRB-'",
":",
"')'",
"}",
"return",
"re",
".",
"sub",
"(",
"'|'",
".",
"join",
"(",
"d",
".",
"keys",
"(",
")",
")",
",",
"lambda",
"m",
":",
"d",
"[",
... | Return sanitized Eidos text field for human readability. | [
"Return",
"sanitized",
"Eidos",
"text",
"field",
"for",
"human",
"readability",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/eidos/processor.py#L380-L383 |
19,116 | sorgerlab/indra | indra/sources/eidos/processor.py | ref_context_from_geoloc | def ref_context_from_geoloc(geoloc):
"""Return a RefContext object given a geoloc entry."""
text = geoloc.get('text')
geoid = geoloc.get('geoID')
rc = RefContext(name=text, db_refs={'GEOID': geoid})
return rc | python | def ref_context_from_geoloc(geoloc):
text = geoloc.get('text')
geoid = geoloc.get('geoID')
rc = RefContext(name=text, db_refs={'GEOID': geoid})
return rc | [
"def",
"ref_context_from_geoloc",
"(",
"geoloc",
")",
":",
"text",
"=",
"geoloc",
".",
"get",
"(",
"'text'",
")",
"geoid",
"=",
"geoloc",
".",
"get",
"(",
"'geoID'",
")",
"rc",
"=",
"RefContext",
"(",
"name",
"=",
"text",
",",
"db_refs",
"=",
"{",
"'... | Return a RefContext object given a geoloc entry. | [
"Return",
"a",
"RefContext",
"object",
"given",
"a",
"geoloc",
"entry",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/eidos/processor.py#L401-L406 |
19,117 | sorgerlab/indra | indra/sources/eidos/processor.py | time_context_from_timex | def time_context_from_timex(timex):
"""Return a TimeContext object given a timex entry."""
time_text = timex.get('text')
constraint = timex['intervals'][0]
start = _get_time_stamp(constraint.get('start'))
end = _get_time_stamp(constraint.get('end'))
duration = constraint['duration']
tc = TimeContext(text=time_text, start=start, end=end,
duration=duration)
return tc | python | def time_context_from_timex(timex):
time_text = timex.get('text')
constraint = timex['intervals'][0]
start = _get_time_stamp(constraint.get('start'))
end = _get_time_stamp(constraint.get('end'))
duration = constraint['duration']
tc = TimeContext(text=time_text, start=start, end=end,
duration=duration)
return tc | [
"def",
"time_context_from_timex",
"(",
"timex",
")",
":",
"time_text",
"=",
"timex",
".",
"get",
"(",
"'text'",
")",
"constraint",
"=",
"timex",
"[",
"'intervals'",
"]",
"[",
"0",
"]",
"start",
"=",
"_get_time_stamp",
"(",
"constraint",
".",
"get",
"(",
... | Return a TimeContext object given a timex entry. | [
"Return",
"a",
"TimeContext",
"object",
"given",
"a",
"timex",
"entry",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/eidos/processor.py#L409-L418 |
19,118 | sorgerlab/indra | indra/sources/eidos/processor.py | find_args | def find_args(event, arg_type):
"""Return IDs of all arguments of a given type"""
args = event.get('arguments', {})
obj_tags = [arg for arg in args if arg['type'] == arg_type]
if obj_tags:
return [o['value']['@id'] for o in obj_tags]
else:
return [] | python | def find_args(event, arg_type):
args = event.get('arguments', {})
obj_tags = [arg for arg in args if arg['type'] == arg_type]
if obj_tags:
return [o['value']['@id'] for o in obj_tags]
else:
return [] | [
"def",
"find_args",
"(",
"event",
",",
"arg_type",
")",
":",
"args",
"=",
"event",
".",
"get",
"(",
"'arguments'",
",",
"{",
"}",
")",
"obj_tags",
"=",
"[",
"arg",
"for",
"arg",
"in",
"args",
"if",
"arg",
"[",
"'type'",
"]",
"==",
"arg_type",
"]",
... | Return IDs of all arguments of a given type | [
"Return",
"IDs",
"of",
"all",
"arguments",
"of",
"a",
"given",
"type"
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/eidos/processor.py#L430-L437 |
19,119 | sorgerlab/indra | indra/sources/eidos/processor.py | EidosProcessor.extract_causal_relations | def extract_causal_relations(self):
"""Extract causal relations as Statements."""
# Get the extractions that are labeled as directed and causal
relations = [e for e in self.doc.extractions if
'DirectedRelation' in e['labels'] and
'Causal' in e['labels']]
# For each relation, we try to extract an INDRA Statement and
# save it if its valid
for relation in relations:
stmt = self.get_causal_relation(relation)
if stmt is not None:
self.statements.append(stmt) | python | def extract_causal_relations(self):
# Get the extractions that are labeled as directed and causal
relations = [e for e in self.doc.extractions if
'DirectedRelation' in e['labels'] and
'Causal' in e['labels']]
# For each relation, we try to extract an INDRA Statement and
# save it if its valid
for relation in relations:
stmt = self.get_causal_relation(relation)
if stmt is not None:
self.statements.append(stmt) | [
"def",
"extract_causal_relations",
"(",
"self",
")",
":",
"# Get the extractions that are labeled as directed and causal",
"relations",
"=",
"[",
"e",
"for",
"e",
"in",
"self",
".",
"doc",
".",
"extractions",
"if",
"'DirectedRelation'",
"in",
"e",
"[",
"'labels'",
"... | Extract causal relations as Statements. | [
"Extract",
"causal",
"relations",
"as",
"Statements",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/eidos/processor.py#L27-L38 |
19,120 | sorgerlab/indra | indra/sources/eidos/processor.py | EidosProcessor.get_evidence | def get_evidence(self, relation):
"""Return the Evidence object for the INDRA Statment."""
provenance = relation.get('provenance')
# First try looking up the full sentence through provenance
text = None
context = None
if provenance:
sentence_tag = provenance[0].get('sentence')
if sentence_tag and '@id' in sentence_tag:
sentence_id = sentence_tag['@id']
sentence = self.doc.sentences.get(sentence_id)
if sentence is not None:
text = _sanitize(sentence['text'])
# Get temporal constraints if available
timexes = sentence.get('timexes', [])
if timexes:
# We currently handle just one timex per statement
timex = timexes[0]
tc = time_context_from_timex(timex)
context = WorldContext(time=tc)
# Get geolocation if available
geolocs = sentence.get('geolocs', [])
if geolocs:
geoloc = geolocs[0]
rc = ref_context_from_geoloc(geoloc)
if context:
context.geo_location = rc
else:
context = WorldContext(geo_location=rc)
# Here we try to get the title of the document and set it
# in the provenance
doc_id = provenance[0].get('document', {}).get('@id')
if doc_id:
title = self.doc.documents.get(doc_id, {}).get('title')
if title:
provenance[0]['document']['title'] = title
annotations = {'found_by': relation.get('rule'),
'provenance': provenance}
if self.doc.dct is not None:
annotations['document_creation_time'] = self.doc.dct.to_json()
epistemics = {}
negations = self.get_negation(relation)
hedgings = self.get_hedging(relation)
if hedgings:
epistemics['hedgings'] = hedgings
if negations:
# This is the INDRA standard to show negation
epistemics['negated'] = True
# But we can also save the texts associated with the negation
# under annotations, just in case it's needed
annotations['negated_texts'] = negations
# If that fails, we can still get the text of the relation
if text is None:
text = _sanitize(event.get('text'))
ev = Evidence(source_api='eidos', text=text, annotations=annotations,
context=context, epistemics=epistemics)
return ev | python | def get_evidence(self, relation):
provenance = relation.get('provenance')
# First try looking up the full sentence through provenance
text = None
context = None
if provenance:
sentence_tag = provenance[0].get('sentence')
if sentence_tag and '@id' in sentence_tag:
sentence_id = sentence_tag['@id']
sentence = self.doc.sentences.get(sentence_id)
if sentence is not None:
text = _sanitize(sentence['text'])
# Get temporal constraints if available
timexes = sentence.get('timexes', [])
if timexes:
# We currently handle just one timex per statement
timex = timexes[0]
tc = time_context_from_timex(timex)
context = WorldContext(time=tc)
# Get geolocation if available
geolocs = sentence.get('geolocs', [])
if geolocs:
geoloc = geolocs[0]
rc = ref_context_from_geoloc(geoloc)
if context:
context.geo_location = rc
else:
context = WorldContext(geo_location=rc)
# Here we try to get the title of the document and set it
# in the provenance
doc_id = provenance[0].get('document', {}).get('@id')
if doc_id:
title = self.doc.documents.get(doc_id, {}).get('title')
if title:
provenance[0]['document']['title'] = title
annotations = {'found_by': relation.get('rule'),
'provenance': provenance}
if self.doc.dct is not None:
annotations['document_creation_time'] = self.doc.dct.to_json()
epistemics = {}
negations = self.get_negation(relation)
hedgings = self.get_hedging(relation)
if hedgings:
epistemics['hedgings'] = hedgings
if negations:
# This is the INDRA standard to show negation
epistemics['negated'] = True
# But we can also save the texts associated with the negation
# under annotations, just in case it's needed
annotations['negated_texts'] = negations
# If that fails, we can still get the text of the relation
if text is None:
text = _sanitize(event.get('text'))
ev = Evidence(source_api='eidos', text=text, annotations=annotations,
context=context, epistemics=epistemics)
return ev | [
"def",
"get_evidence",
"(",
"self",
",",
"relation",
")",
":",
"provenance",
"=",
"relation",
".",
"get",
"(",
"'provenance'",
")",
"# First try looking up the full sentence through provenance",
"text",
"=",
"None",
"context",
"=",
"None",
"if",
"provenance",
":",
... | Return the Evidence object for the INDRA Statment. | [
"Return",
"the",
"Evidence",
"object",
"for",
"the",
"INDRA",
"Statment",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/eidos/processor.py#L119-L181 |
19,121 | sorgerlab/indra | indra/sources/eidos/processor.py | EidosProcessor.get_negation | def get_negation(event):
"""Return negation attached to an event.
Example: "states": [{"@type": "State", "type": "NEGATION",
"text": "n't"}]
"""
states = event.get('states', [])
if not states:
return []
negs = [state for state in states
if state.get('type') == 'NEGATION']
neg_texts = [neg['text'] for neg in negs]
return neg_texts | python | def get_negation(event):
states = event.get('states', [])
if not states:
return []
negs = [state for state in states
if state.get('type') == 'NEGATION']
neg_texts = [neg['text'] for neg in negs]
return neg_texts | [
"def",
"get_negation",
"(",
"event",
")",
":",
"states",
"=",
"event",
".",
"get",
"(",
"'states'",
",",
"[",
"]",
")",
"if",
"not",
"states",
":",
"return",
"[",
"]",
"negs",
"=",
"[",
"state",
"for",
"state",
"in",
"states",
"if",
"state",
".",
... | Return negation attached to an event.
Example: "states": [{"@type": "State", "type": "NEGATION",
"text": "n't"}] | [
"Return",
"negation",
"attached",
"to",
"an",
"event",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/eidos/processor.py#L184-L196 |
19,122 | sorgerlab/indra | indra/sources/eidos/processor.py | EidosProcessor.get_hedging | def get_hedging(event):
"""Return hedging markers attached to an event.
Example: "states": [{"@type": "State", "type": "HEDGE",
"text": "could"}
"""
states = event.get('states', [])
if not states:
return []
hedgings = [state for state in states
if state.get('type') == 'HEDGE']
hedging_texts = [hedging['text'] for hedging in hedgings]
return hedging_texts | python | def get_hedging(event):
states = event.get('states', [])
if not states:
return []
hedgings = [state for state in states
if state.get('type') == 'HEDGE']
hedging_texts = [hedging['text'] for hedging in hedgings]
return hedging_texts | [
"def",
"get_hedging",
"(",
"event",
")",
":",
"states",
"=",
"event",
".",
"get",
"(",
"'states'",
",",
"[",
"]",
")",
"if",
"not",
"states",
":",
"return",
"[",
"]",
"hedgings",
"=",
"[",
"state",
"for",
"state",
"in",
"states",
"if",
"state",
"."... | Return hedging markers attached to an event.
Example: "states": [{"@type": "State", "type": "HEDGE",
"text": "could"} | [
"Return",
"hedging",
"markers",
"attached",
"to",
"an",
"event",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/eidos/processor.py#L199-L211 |
19,123 | sorgerlab/indra | indra/sources/eidos/processor.py | EidosProcessor.get_groundings | def get_groundings(entity):
"""Return groundings as db_refs for an entity."""
def get_grounding_entries(grounding):
if not grounding:
return None
entries = []
values = grounding.get('values', [])
# Values could still have been a None entry here
if values:
for entry in values:
ont_concept = entry.get('ontologyConcept')
value = entry.get('value')
if ont_concept is None or value is None:
continue
entries.append((ont_concept, value))
return entries
# Save raw text and Eidos scored groundings as db_refs
db_refs = {'TEXT': entity['text']}
groundings = entity.get('groundings')
if not groundings:
return db_refs
for g in groundings:
entries = get_grounding_entries(g)
# Only add these groundings if there are actual values listed
if entries:
key = g['name'].upper()
if key == 'UN':
db_refs[key] = [(s[0].replace(' ', '_'), s[1])
for s in entries]
else:
db_refs[key] = entries
return db_refs | python | def get_groundings(entity):
def get_grounding_entries(grounding):
if not grounding:
return None
entries = []
values = grounding.get('values', [])
# Values could still have been a None entry here
if values:
for entry in values:
ont_concept = entry.get('ontologyConcept')
value = entry.get('value')
if ont_concept is None or value is None:
continue
entries.append((ont_concept, value))
return entries
# Save raw text and Eidos scored groundings as db_refs
db_refs = {'TEXT': entity['text']}
groundings = entity.get('groundings')
if not groundings:
return db_refs
for g in groundings:
entries = get_grounding_entries(g)
# Only add these groundings if there are actual values listed
if entries:
key = g['name'].upper()
if key == 'UN':
db_refs[key] = [(s[0].replace(' ', '_'), s[1])
for s in entries]
else:
db_refs[key] = entries
return db_refs | [
"def",
"get_groundings",
"(",
"entity",
")",
":",
"def",
"get_grounding_entries",
"(",
"grounding",
")",
":",
"if",
"not",
"grounding",
":",
"return",
"None",
"entries",
"=",
"[",
"]",
"values",
"=",
"grounding",
".",
"get",
"(",
"'values'",
",",
"[",
"]... | Return groundings as db_refs for an entity. | [
"Return",
"groundings",
"as",
"db_refs",
"for",
"an",
"entity",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/eidos/processor.py#L243-L276 |
19,124 | sorgerlab/indra | indra/sources/eidos/processor.py | EidosProcessor.get_concept | def get_concept(entity):
"""Return Concept from an Eidos entity."""
# Use the canonical name as the name of the Concept
name = entity['canonicalName']
db_refs = EidosProcessor.get_groundings(entity)
concept = Concept(name, db_refs=db_refs)
return concept | python | def get_concept(entity):
# Use the canonical name as the name of the Concept
name = entity['canonicalName']
db_refs = EidosProcessor.get_groundings(entity)
concept = Concept(name, db_refs=db_refs)
return concept | [
"def",
"get_concept",
"(",
"entity",
")",
":",
"# Use the canonical name as the name of the Concept",
"name",
"=",
"entity",
"[",
"'canonicalName'",
"]",
"db_refs",
"=",
"EidosProcessor",
".",
"get_groundings",
"(",
"entity",
")",
"concept",
"=",
"Concept",
"(",
"na... | Return Concept from an Eidos entity. | [
"Return",
"Concept",
"from",
"an",
"Eidos",
"entity",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/eidos/processor.py#L279-L285 |
19,125 | sorgerlab/indra | indra/sources/eidos/processor.py | EidosProcessor.time_context_from_ref | def time_context_from_ref(self, timex):
"""Return a time context object given a timex reference entry."""
# If the timex has a value set, it means that it refers to a DCT or
# a TimeExpression e.g. "value": {"@id": "_:DCT_1"} and the parameters
# need to be taken from there
value = timex.get('value')
if value:
# Here we get the TimeContext directly from the stashed DCT
# dictionary
tc = self.doc.timexes.get(value['@id'])
return tc
return None | python | def time_context_from_ref(self, timex):
# If the timex has a value set, it means that it refers to a DCT or
# a TimeExpression e.g. "value": {"@id": "_:DCT_1"} and the parameters
# need to be taken from there
value = timex.get('value')
if value:
# Here we get the TimeContext directly from the stashed DCT
# dictionary
tc = self.doc.timexes.get(value['@id'])
return tc
return None | [
"def",
"time_context_from_ref",
"(",
"self",
",",
"timex",
")",
":",
"# If the timex has a value set, it means that it refers to a DCT or",
"# a TimeExpression e.g. \"value\": {\"@id\": \"_:DCT_1\"} and the parameters",
"# need to be taken from there",
"value",
"=",
"timex",
".",
"get"... | Return a time context object given a timex reference entry. | [
"Return",
"a",
"time",
"context",
"object",
"given",
"a",
"timex",
"reference",
"entry",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/eidos/processor.py#L287-L298 |
19,126 | sorgerlab/indra | indra/sources/eidos/processor.py | EidosProcessor.geo_context_from_ref | def geo_context_from_ref(self, ref):
"""Return a ref context object given a location reference entry."""
value = ref.get('value')
if value:
# Here we get the RefContext from the stashed geoloc dictionary
rc = self.doc.geolocs.get(value['@id'])
return rc
return None | python | def geo_context_from_ref(self, ref):
value = ref.get('value')
if value:
# Here we get the RefContext from the stashed geoloc dictionary
rc = self.doc.geolocs.get(value['@id'])
return rc
return None | [
"def",
"geo_context_from_ref",
"(",
"self",
",",
"ref",
")",
":",
"value",
"=",
"ref",
".",
"get",
"(",
"'value'",
")",
"if",
"value",
":",
"# Here we get the RefContext from the stashed geoloc dictionary",
"rc",
"=",
"self",
".",
"doc",
".",
"geolocs",
".",
"... | Return a ref context object given a location reference entry. | [
"Return",
"a",
"ref",
"context",
"object",
"given",
"a",
"location",
"reference",
"entry",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/eidos/processor.py#L300-L307 |
19,127 | sorgerlab/indra | indra/sources/eidos/processor.py | EidosDocument.time_context_from_dct | def time_context_from_dct(dct):
"""Return a time context object given a DCT entry."""
time_text = dct.get('text')
start = _get_time_stamp(dct.get('start'))
end = _get_time_stamp(dct.get('end'))
duration = dct.get('duration')
tc = TimeContext(text=time_text, start=start, end=end,
duration=duration)
return tc | python | def time_context_from_dct(dct):
time_text = dct.get('text')
start = _get_time_stamp(dct.get('start'))
end = _get_time_stamp(dct.get('end'))
duration = dct.get('duration')
tc = TimeContext(text=time_text, start=start, end=end,
duration=duration)
return tc | [
"def",
"time_context_from_dct",
"(",
"dct",
")",
":",
"time_text",
"=",
"dct",
".",
"get",
"(",
"'text'",
")",
"start",
"=",
"_get_time_stamp",
"(",
"dct",
".",
"get",
"(",
"'start'",
")",
")",
"end",
"=",
"_get_time_stamp",
"(",
"dct",
".",
"get",
"("... | Return a time context object given a DCT entry. | [
"Return",
"a",
"time",
"context",
"object",
"given",
"a",
"DCT",
"entry",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/eidos/processor.py#L369-L377 |
19,128 | sorgerlab/indra | indra/statements/util.py | make_hash | def make_hash(s, n_bytes):
"""Make the hash from a matches key."""
raw_h = int(md5(s.encode('utf-8')).hexdigest()[:n_bytes], 16)
# Make it a signed int.
return 16**n_bytes//2 - raw_h | python | def make_hash(s, n_bytes):
raw_h = int(md5(s.encode('utf-8')).hexdigest()[:n_bytes], 16)
# Make it a signed int.
return 16**n_bytes//2 - raw_h | [
"def",
"make_hash",
"(",
"s",
",",
"n_bytes",
")",
":",
"raw_h",
"=",
"int",
"(",
"md5",
"(",
"s",
".",
"encode",
"(",
"'utf-8'",
")",
")",
".",
"hexdigest",
"(",
")",
"[",
":",
"n_bytes",
"]",
",",
"16",
")",
"# Make it a signed int.",
"return",
"... | Make the hash from a matches key. | [
"Make",
"the",
"hash",
"from",
"a",
"matches",
"key",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/statements/util.py#L12-L16 |
19,129 | sorgerlab/indra | indra/sources/tees/parse_tees.py | parse_a1 | def parse_a1(a1_text):
"""Parses an a1 file, the file TEES outputs that lists the entities in
the extracted events.
Parameters
----------
a1_text : str
Text of the TEES a1 output file, specifying the entities
Returns
-------
entities : Dictionary mapping TEES identifiers to TEESEntity objects
describing each entity. Each row of the .a1 file corresponds to one
TEESEntity object.
"""
entities = {}
for line in a1_text.split('\n'):
if len(line) == 0:
continue
tokens = line.rstrip().split('\t')
if len(tokens) != 3:
raise Exception('Expected three tab-seperated tokens per line ' +
'in the a1 file output from TEES.')
identifier = tokens[0]
entity_info = tokens[1]
entity_name = tokens[2]
info_tokens = entity_info.split()
if len(info_tokens) != 3:
raise Exception('Expected three space-seperated tokens in the ' +
'second column of the a2 file output from TEES.')
entity_type = info_tokens[0]
first_offset = int(info_tokens[1])
second_offset = int(info_tokens[2])
offsets = (first_offset, second_offset)
entities[identifier] = TEESEntity(
identifier,
entity_type,
entity_name,
offsets)
return entities | python | def parse_a1(a1_text):
entities = {}
for line in a1_text.split('\n'):
if len(line) == 0:
continue
tokens = line.rstrip().split('\t')
if len(tokens) != 3:
raise Exception('Expected three tab-seperated tokens per line ' +
'in the a1 file output from TEES.')
identifier = tokens[0]
entity_info = tokens[1]
entity_name = tokens[2]
info_tokens = entity_info.split()
if len(info_tokens) != 3:
raise Exception('Expected three space-seperated tokens in the ' +
'second column of the a2 file output from TEES.')
entity_type = info_tokens[0]
first_offset = int(info_tokens[1])
second_offset = int(info_tokens[2])
offsets = (first_offset, second_offset)
entities[identifier] = TEESEntity(
identifier,
entity_type,
entity_name,
offsets)
return entities | [
"def",
"parse_a1",
"(",
"a1_text",
")",
":",
"entities",
"=",
"{",
"}",
"for",
"line",
"in",
"a1_text",
".",
"split",
"(",
"'\\n'",
")",
":",
"if",
"len",
"(",
"line",
")",
"==",
"0",
":",
"continue",
"tokens",
"=",
"line",
".",
"rstrip",
"(",
")... | Parses an a1 file, the file TEES outputs that lists the entities in
the extracted events.
Parameters
----------
a1_text : str
Text of the TEES a1 output file, specifying the entities
Returns
-------
entities : Dictionary mapping TEES identifiers to TEESEntity objects
describing each entity. Each row of the .a1 file corresponds to one
TEESEntity object. | [
"Parses",
"an",
"a1",
"file",
"the",
"file",
"TEES",
"outputs",
"that",
"lists",
"the",
"entities",
"in",
"the",
"extracted",
"events",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/tees/parse_tees.py#L71-L115 |
19,130 | sorgerlab/indra | indra/sources/tees/parse_tees.py | parse_output | def parse_output(a1_text, a2_text, sentence_segmentations):
"""Parses the output of the TEES reader and returns a networkx graph
with the event information.
Parameters
----------
a1_text : str
Contents of the TEES a1 output, specifying the entities
a1_text : str
Contents of the TEES a2 output, specifying the event graph
sentence_segmentations : str
Concents of the TEES sentence segmentation output XML
Returns
-------
events : networkx.DiGraph
networkx graph with the entities, events, and relationship between
extracted by TEES
"""
# Parse the sentence segmentation document
tees_sentences = TEESSentences(sentence_segmentations)
# Parse the a1 (entities) file
entities = parse_a1(a1_text)
# Parse the a2 (events) file
events = parse_a2(a2_text, entities, tees_sentences)
return events | python | def parse_output(a1_text, a2_text, sentence_segmentations):
# Parse the sentence segmentation document
tees_sentences = TEESSentences(sentence_segmentations)
# Parse the a1 (entities) file
entities = parse_a1(a1_text)
# Parse the a2 (events) file
events = parse_a2(a2_text, entities, tees_sentences)
return events | [
"def",
"parse_output",
"(",
"a1_text",
",",
"a2_text",
",",
"sentence_segmentations",
")",
":",
"# Parse the sentence segmentation document",
"tees_sentences",
"=",
"TEESSentences",
"(",
"sentence_segmentations",
")",
"# Parse the a1 (entities) file",
"entities",
"=",
"parse_... | Parses the output of the TEES reader and returns a networkx graph
with the event information.
Parameters
----------
a1_text : str
Contents of the TEES a1 output, specifying the entities
a1_text : str
Contents of the TEES a2 output, specifying the event graph
sentence_segmentations : str
Concents of the TEES sentence segmentation output XML
Returns
-------
events : networkx.DiGraph
networkx graph with the entities, events, and relationship between
extracted by TEES | [
"Parses",
"the",
"output",
"of",
"the",
"TEES",
"reader",
"and",
"returns",
"a",
"networkx",
"graph",
"with",
"the",
"event",
"information",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/tees/parse_tees.py#L272-L301 |
19,131 | sorgerlab/indra | indra/sources/tees/parse_tees.py | tees_parse_networkx_to_dot | def tees_parse_networkx_to_dot(G, output_file, subgraph_nodes):
"""Converts TEES extractions stored in a networkx graph into a graphviz
.dot file.
Parameters
----------
G : networkx.DiGraph
Graph with TEES extractions returned by run_and_parse_tees
output_file : str
Output file to which to write .dot file
subgraph_nodes : list[str]
Only convert the connected graph that includes these ndoes
"""
with codecs.open(output_file, 'w', encoding='utf-8') as f:
f.write('digraph teesParse {\n')
mentioned_nodes = set()
for from_node in subgraph_nodes:
for edge in G.edges(from_node):
to_node = edge[1]
mentioned_nodes.add(from_node)
mentioned_nodes.add(to_node)
relation = G.edges[from_node, to_node]['relation']
f.write('%s -> %s [ label = "%s" ];\n' % (from_node, to_node,
relation))
for node in mentioned_nodes:
is_event = G.node[node]['is_event']
if is_event:
node_type = G.node[node]['type']
negated = G.node[node]['negated']
speculation = G.node[node]['speculation']
# Add a tag to the label if the event is negated or speculation
if negated and speculation:
tag = ' {NS}'
elif negated:
tag = ' {N}'
elif speculation:
tag = ' {S}'
else:
tag = ''
node_label = node_type + tag
else:
node_label = G.node[node]['text']
f.write('%s [label="%s"];\n' % (node, node_label))
f.write('}\n') | python | def tees_parse_networkx_to_dot(G, output_file, subgraph_nodes):
with codecs.open(output_file, 'w', encoding='utf-8') as f:
f.write('digraph teesParse {\n')
mentioned_nodes = set()
for from_node in subgraph_nodes:
for edge in G.edges(from_node):
to_node = edge[1]
mentioned_nodes.add(from_node)
mentioned_nodes.add(to_node)
relation = G.edges[from_node, to_node]['relation']
f.write('%s -> %s [ label = "%s" ];\n' % (from_node, to_node,
relation))
for node in mentioned_nodes:
is_event = G.node[node]['is_event']
if is_event:
node_type = G.node[node]['type']
negated = G.node[node]['negated']
speculation = G.node[node]['speculation']
# Add a tag to the label if the event is negated or speculation
if negated and speculation:
tag = ' {NS}'
elif negated:
tag = ' {N}'
elif speculation:
tag = ' {S}'
else:
tag = ''
node_label = node_type + tag
else:
node_label = G.node[node]['text']
f.write('%s [label="%s"];\n' % (node, node_label))
f.write('}\n') | [
"def",
"tees_parse_networkx_to_dot",
"(",
"G",
",",
"output_file",
",",
"subgraph_nodes",
")",
":",
"with",
"codecs",
".",
"open",
"(",
"output_file",
",",
"'w'",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"'digraph teesP... | Converts TEES extractions stored in a networkx graph into a graphviz
.dot file.
Parameters
----------
G : networkx.DiGraph
Graph with TEES extractions returned by run_and_parse_tees
output_file : str
Output file to which to write .dot file
subgraph_nodes : list[str]
Only convert the connected graph that includes these ndoes | [
"Converts",
"TEES",
"extractions",
"stored",
"in",
"a",
"networkx",
"graph",
"into",
"a",
"graphviz",
".",
"dot",
"file",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/tees/parse_tees.py#L303-L354 |
19,132 | sorgerlab/indra | indra/sources/cwms/processor.py | CWMSProcessor._get_event | def _get_event(self, event, find_str):
"""Get a concept referred from the event by the given string."""
# Get the term with the given element id
element = event.find(find_str)
if element is None:
return None
element_id = element.attrib.get('id')
element_term = self.tree.find("*[@id='%s']" % element_id)
if element_term is None:
return None
time, location = self._extract_time_loc(element_term)
# Now see if there is a modifier like assoc-with connected
# to the main concept
assoc_with = self._get_assoc_with(element_term)
# Get the element's text and use it to construct a Concept
element_text_element = element_term.find('text')
if element_text_element is None:
return None
element_text = element_text_element.text
element_db_refs = {'TEXT': element_text}
element_name = sanitize_name(element_text)
element_type_element = element_term.find('type')
if element_type_element is not None:
element_db_refs['CWMS'] = element_type_element.text
# If there's an assoc-with, we tack it on as extra grounding
if assoc_with is not None:
element_db_refs['CWMS'] += ('|%s' % assoc_with)
concept = Concept(element_name, db_refs=element_db_refs)
if time or location:
context = WorldContext(time=time, geo_location=location)
else:
context = None
event_obj = Event(concept, context=context)
return event_obj | python | def _get_event(self, event, find_str):
# Get the term with the given element id
element = event.find(find_str)
if element is None:
return None
element_id = element.attrib.get('id')
element_term = self.tree.find("*[@id='%s']" % element_id)
if element_term is None:
return None
time, location = self._extract_time_loc(element_term)
# Now see if there is a modifier like assoc-with connected
# to the main concept
assoc_with = self._get_assoc_with(element_term)
# Get the element's text and use it to construct a Concept
element_text_element = element_term.find('text')
if element_text_element is None:
return None
element_text = element_text_element.text
element_db_refs = {'TEXT': element_text}
element_name = sanitize_name(element_text)
element_type_element = element_term.find('type')
if element_type_element is not None:
element_db_refs['CWMS'] = element_type_element.text
# If there's an assoc-with, we tack it on as extra grounding
if assoc_with is not None:
element_db_refs['CWMS'] += ('|%s' % assoc_with)
concept = Concept(element_name, db_refs=element_db_refs)
if time or location:
context = WorldContext(time=time, geo_location=location)
else:
context = None
event_obj = Event(concept, context=context)
return event_obj | [
"def",
"_get_event",
"(",
"self",
",",
"event",
",",
"find_str",
")",
":",
"# Get the term with the given element id",
"element",
"=",
"event",
".",
"find",
"(",
"find_str",
")",
"if",
"element",
"is",
"None",
":",
"return",
"None",
"element_id",
"=",
"element... | Get a concept referred from the event by the given string. | [
"Get",
"a",
"concept",
"referred",
"from",
"the",
"event",
"by",
"the",
"given",
"string",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/cwms/processor.py#L115-L152 |
19,133 | sorgerlab/indra | indra/assemblers/cag/assembler.py | CAGAssembler.make_model | def make_model(self, grounding_ontology='UN', grounding_threshold=None):
"""Return a networkx MultiDiGraph representing a causal analysis graph.
Parameters
----------
grounding_ontology : Optional[str]
The ontology from which the grounding should be taken
(e.g. UN, FAO)
grounding_threshold : Optional[float]
Minimum threshold score for Eidos grounding.
Returns
-------
nx.MultiDiGraph
The assembled CAG.
"""
if grounding_threshold is not None:
self.grounding_threshold = grounding_threshold
self.grounding_ontology = grounding_ontology
# Filter to Influence Statements which are currently supported
statements = [stmt for stmt in self.statements if
isinstance(stmt, Influence)]
# Initialize graph
self.CAG = nx.MultiDiGraph()
# Add nodes and edges to the graph
for s in statements:
# Get standardized name of subject and object
# subj, obj = (self._node_name(s.subj), self._node_name(s.obj))
# See if both subject and object have polarities given
has_both_polarity = (s.subj.delta['polarity'] is not None and
s.obj.delta['polarity'] is not None)
# Add the nodes to the graph
for node, delta in zip((s.subj.concept, s.obj.concept),
(s.subj.delta, s.obj.delta)):
self.CAG.add_node(self._node_name(node),
simulable=has_both_polarity,
mods=delta['adjectives'])
# Edge is solid if both nodes have polarity given
linestyle = 'solid' if has_both_polarity else 'dotted'
if has_both_polarity:
same_polarity = (s.subj.delta['polarity'] ==
s.obj.delta['polarity'])
if same_polarity:
target_arrow_shape, linecolor = ('circle', 'green')
else:
target_arrow_shape, linecolor = ('tee', 'maroon')
else:
target_arrow_shape, linecolor = ('triangle', 'maroon')
# Add edge to the graph with metadata from statement
provenance = []
if s.evidence:
provenance = s.evidence[0].annotations.get('provenance', [])
if provenance:
provenance[0]['text'] = s.evidence[0].text
self.CAG.add_edge(
self._node_name(s.subj.concept),
self._node_name(s.obj.concept),
subj_polarity=s.subj.delta['polarity'],
subj_adjectives=s.subj.delta['adjectives'],
obj_polarity=s.obj.delta['polarity'],
obj_adjectives=s.obj.delta['adjectives'],
linestyle=linestyle,
linecolor=linecolor,
targetArrowShape=target_arrow_shape,
provenance=provenance,
)
return self.CAG | python | def make_model(self, grounding_ontology='UN', grounding_threshold=None):
if grounding_threshold is not None:
self.grounding_threshold = grounding_threshold
self.grounding_ontology = grounding_ontology
# Filter to Influence Statements which are currently supported
statements = [stmt for stmt in self.statements if
isinstance(stmt, Influence)]
# Initialize graph
self.CAG = nx.MultiDiGraph()
# Add nodes and edges to the graph
for s in statements:
# Get standardized name of subject and object
# subj, obj = (self._node_name(s.subj), self._node_name(s.obj))
# See if both subject and object have polarities given
has_both_polarity = (s.subj.delta['polarity'] is not None and
s.obj.delta['polarity'] is not None)
# Add the nodes to the graph
for node, delta in zip((s.subj.concept, s.obj.concept),
(s.subj.delta, s.obj.delta)):
self.CAG.add_node(self._node_name(node),
simulable=has_both_polarity,
mods=delta['adjectives'])
# Edge is solid if both nodes have polarity given
linestyle = 'solid' if has_both_polarity else 'dotted'
if has_both_polarity:
same_polarity = (s.subj.delta['polarity'] ==
s.obj.delta['polarity'])
if same_polarity:
target_arrow_shape, linecolor = ('circle', 'green')
else:
target_arrow_shape, linecolor = ('tee', 'maroon')
else:
target_arrow_shape, linecolor = ('triangle', 'maroon')
# Add edge to the graph with metadata from statement
provenance = []
if s.evidence:
provenance = s.evidence[0].annotations.get('provenance', [])
if provenance:
provenance[0]['text'] = s.evidence[0].text
self.CAG.add_edge(
self._node_name(s.subj.concept),
self._node_name(s.obj.concept),
subj_polarity=s.subj.delta['polarity'],
subj_adjectives=s.subj.delta['adjectives'],
obj_polarity=s.obj.delta['polarity'],
obj_adjectives=s.obj.delta['adjectives'],
linestyle=linestyle,
linecolor=linecolor,
targetArrowShape=target_arrow_shape,
provenance=provenance,
)
return self.CAG | [
"def",
"make_model",
"(",
"self",
",",
"grounding_ontology",
"=",
"'UN'",
",",
"grounding_threshold",
"=",
"None",
")",
":",
"if",
"grounding_threshold",
"is",
"not",
"None",
":",
"self",
".",
"grounding_threshold",
"=",
"grounding_threshold",
"self",
".",
"grou... | Return a networkx MultiDiGraph representing a causal analysis graph.
Parameters
----------
grounding_ontology : Optional[str]
The ontology from which the grounding should be taken
(e.g. UN, FAO)
grounding_threshold : Optional[float]
Minimum threshold score for Eidos grounding.
Returns
-------
nx.MultiDiGraph
The assembled CAG. | [
"Return",
"a",
"networkx",
"MultiDiGraph",
"representing",
"a",
"causal",
"analysis",
"graph",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/cag/assembler.py#L49-L124 |
19,134 | sorgerlab/indra | indra/assemblers/cag/assembler.py | CAGAssembler.export_to_cytoscapejs | def export_to_cytoscapejs(self):
"""Return CAG in format readable by CytoscapeJS.
Return
------
dict
A JSON-like dict representing the graph for use with
CytoscapeJS.
"""
def _create_edge_data_dict(e):
"""Return a dict from a MultiDiGraph edge for CytoscapeJS export."""
# A hack to get rid of the redundant 'Provenance' label.
if e[3].get('provenance'):
tooltip = e[3]['provenance'][0]
if tooltip.get('@type'):
del tooltip['@type']
else:
tooltip = None
edge_data_dict = {
'id' : e[0]+'_'+e[1],
'source' : e[0],
'target' : e[1],
'linestyle' : e[3]["linestyle"],
'linecolor' : e[3]["linecolor"],
'targetArrowShape' : e[3]["targetArrowShape"],
'subj_adjectives' : e[3]["subj_adjectives"],
'subj_polarity' : e[3]["subj_polarity"],
'obj_adjectives' : e[3]["obj_adjectives"],
'obj_polarity' : e[3]["obj_polarity"],
'tooltip' : tooltip,
'simulable' : False if (
e[3]['obj_polarity'] is None or
e[3]['subj_polarity'] is None) else True,
}
return edge_data_dict
return {
'nodes': [{'data': {
'id': n[0],
'simulable': n[1]['simulable'],
'tooltip': 'Modifiers: '+json.dumps(n[1]['mods'])}
} for n in self.CAG.nodes(data=True)],
'edges': [{'data': _create_edge_data_dict(e)}
for e in self.CAG.edges(data=True, keys=True)]
} | python | def export_to_cytoscapejs(self):
def _create_edge_data_dict(e):
"""Return a dict from a MultiDiGraph edge for CytoscapeJS export."""
# A hack to get rid of the redundant 'Provenance' label.
if e[3].get('provenance'):
tooltip = e[3]['provenance'][0]
if tooltip.get('@type'):
del tooltip['@type']
else:
tooltip = None
edge_data_dict = {
'id' : e[0]+'_'+e[1],
'source' : e[0],
'target' : e[1],
'linestyle' : e[3]["linestyle"],
'linecolor' : e[3]["linecolor"],
'targetArrowShape' : e[3]["targetArrowShape"],
'subj_adjectives' : e[3]["subj_adjectives"],
'subj_polarity' : e[3]["subj_polarity"],
'obj_adjectives' : e[3]["obj_adjectives"],
'obj_polarity' : e[3]["obj_polarity"],
'tooltip' : tooltip,
'simulable' : False if (
e[3]['obj_polarity'] is None or
e[3]['subj_polarity'] is None) else True,
}
return edge_data_dict
return {
'nodes': [{'data': {
'id': n[0],
'simulable': n[1]['simulable'],
'tooltip': 'Modifiers: '+json.dumps(n[1]['mods'])}
} for n in self.CAG.nodes(data=True)],
'edges': [{'data': _create_edge_data_dict(e)}
for e in self.CAG.edges(data=True, keys=True)]
} | [
"def",
"export_to_cytoscapejs",
"(",
"self",
")",
":",
"def",
"_create_edge_data_dict",
"(",
"e",
")",
":",
"\"\"\"Return a dict from a MultiDiGraph edge for CytoscapeJS export.\"\"\"",
"# A hack to get rid of the redundant 'Provenance' label.",
"if",
"e",
"[",
"3",
"]",
".",
... | Return CAG in format readable by CytoscapeJS.
Return
------
dict
A JSON-like dict representing the graph for use with
CytoscapeJS. | [
"Return",
"CAG",
"in",
"format",
"readable",
"by",
"CytoscapeJS",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/cag/assembler.py#L203-L248 |
19,135 | sorgerlab/indra | indra/assemblers/cag/assembler.py | CAGAssembler.generate_jupyter_js | def generate_jupyter_js(self, cyjs_style=None, cyjs_layout=None):
"""Generate Javascript from a template to run in Jupyter notebooks.
Parameters
----------
cyjs_style : Optional[dict]
A dict that sets CytoscapeJS style as specified in
https://github.com/cytoscape/cytoscape.js/blob/master/documentation/md/style.md.
cyjs_layout : Optional[dict]
A dict that sets CytoscapeJS
`layout parameters <http://js.cytoscape.org/#core/layout>`_.
Returns
-------
str
A Javascript string to be rendered in a Jupyter notebook cell.
"""
# First, export the CAG to CyJS
cyjs_elements = self.export_to_cytoscapejs()
# Load the Javascript template
tempf = os.path.join(os.path.dirname(os.path.abspath(__file__)),
'cag_template.js')
with open(tempf, 'r') as fh:
template = fh.read()
# Load the default style and layout
stylef = os.path.join(os.path.dirname(os.path.abspath(__file__)),
'cag_style.json')
with open(stylef, 'r') as fh:
style = json.load(fh)
# Apply style and layout only if arg wasn't passed in
if cyjs_style is None:
cyjs_style = style['style']
if cyjs_layout is None:
cyjs_layout = style['layout']
# Now fill in the template
formatted_args = tuple(json.dumps(x, indent=2) for x in
(cyjs_elements, cyjs_style, cyjs_layout))
js_str = template % formatted_args
return js_str | python | def generate_jupyter_js(self, cyjs_style=None, cyjs_layout=None):
# First, export the CAG to CyJS
cyjs_elements = self.export_to_cytoscapejs()
# Load the Javascript template
tempf = os.path.join(os.path.dirname(os.path.abspath(__file__)),
'cag_template.js')
with open(tempf, 'r') as fh:
template = fh.read()
# Load the default style and layout
stylef = os.path.join(os.path.dirname(os.path.abspath(__file__)),
'cag_style.json')
with open(stylef, 'r') as fh:
style = json.load(fh)
# Apply style and layout only if arg wasn't passed in
if cyjs_style is None:
cyjs_style = style['style']
if cyjs_layout is None:
cyjs_layout = style['layout']
# Now fill in the template
formatted_args = tuple(json.dumps(x, indent=2) for x in
(cyjs_elements, cyjs_style, cyjs_layout))
js_str = template % formatted_args
return js_str | [
"def",
"generate_jupyter_js",
"(",
"self",
",",
"cyjs_style",
"=",
"None",
",",
"cyjs_layout",
"=",
"None",
")",
":",
"# First, export the CAG to CyJS",
"cyjs_elements",
"=",
"self",
".",
"export_to_cytoscapejs",
"(",
")",
"# Load the Javascript template",
"tempf",
"=... | Generate Javascript from a template to run in Jupyter notebooks.
Parameters
----------
cyjs_style : Optional[dict]
A dict that sets CytoscapeJS style as specified in
https://github.com/cytoscape/cytoscape.js/blob/master/documentation/md/style.md.
cyjs_layout : Optional[dict]
A dict that sets CytoscapeJS
`layout parameters <http://js.cytoscape.org/#core/layout>`_.
Returns
-------
str
A Javascript string to be rendered in a Jupyter notebook cell. | [
"Generate",
"Javascript",
"from",
"a",
"template",
"to",
"run",
"in",
"Jupyter",
"notebooks",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/cag/assembler.py#L250-L289 |
19,136 | sorgerlab/indra | indra/assemblers/cag/assembler.py | CAGAssembler._node_name | def _node_name(self, concept):
"""Return a standardized name for a node given a Concept."""
if (# grounding threshold is specified
self.grounding_threshold is not None
# The particular eidos ontology grounding (un/wdi/fao) is present
and concept.db_refs[self.grounding_ontology]
# The grounding score is above the grounding threshold
and (concept.db_refs[self.grounding_ontology][0][1] >
self.grounding_threshold)):
entry = concept.db_refs[self.grounding_ontology][0][0]
return entry.split('/')[-1].replace('_', ' ').capitalize()
else:
return concept.name.capitalize() | python | def _node_name(self, concept):
if (# grounding threshold is specified
self.grounding_threshold is not None
# The particular eidos ontology grounding (un/wdi/fao) is present
and concept.db_refs[self.grounding_ontology]
# The grounding score is above the grounding threshold
and (concept.db_refs[self.grounding_ontology][0][1] >
self.grounding_threshold)):
entry = concept.db_refs[self.grounding_ontology][0][0]
return entry.split('/')[-1].replace('_', ' ').capitalize()
else:
return concept.name.capitalize() | [
"def",
"_node_name",
"(",
"self",
",",
"concept",
")",
":",
"if",
"(",
"# grounding threshold is specified",
"self",
".",
"grounding_threshold",
"is",
"not",
"None",
"# The particular eidos ontology grounding (un/wdi/fao) is present",
"and",
"concept",
".",
"db_refs",
"["... | Return a standardized name for a node given a Concept. | [
"Return",
"a",
"standardized",
"name",
"for",
"a",
"node",
"given",
"a",
"Concept",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/cag/assembler.py#L291-L303 |
19,137 | sorgerlab/indra | indra/sources/bel/rdf_processor.py | term_from_uri | def term_from_uri(uri):
"""Removes prepended URI information from terms."""
if uri is None:
return None
# This insures that if we get a Literal with an integer value (as we
# do for modification positions), it will get converted to a string,
# not an integer.
if isinstance(uri, rdflib.Literal):
uri = str(uri.toPython())
# This is to handle URIs like
# http://www.openbel.org/bel/namespace//MAPK%20Erk1/3%20Family
# or
# http://www.openbel.org/bel/namespace/MAPK%20Erk1/3%20Family
# In the current implementation, the order of the patterns
# matters.
patterns = ['http://www.openbel.org/bel/namespace//(.*)',
'http://www.openbel.org/vocabulary//(.*)',
'http://www.openbel.org/bel//(.*)',
'http://www.openbel.org/bel/namespace/(.*)',
'http://www.openbel.org/vocabulary/(.*)',
'http://www.openbel.org/bel/(.*)']
for pr in patterns:
match = re.match(pr, uri)
if match is not None:
term = match.groups()[0]
term = unquote(term)
return term
# If none of the patterns match then the URI is actually a simple term
# for instance a site: "341" or a substitution: "sub(V,600,E)"
return uri | python | def term_from_uri(uri):
if uri is None:
return None
# This insures that if we get a Literal with an integer value (as we
# do for modification positions), it will get converted to a string,
# not an integer.
if isinstance(uri, rdflib.Literal):
uri = str(uri.toPython())
# This is to handle URIs like
# http://www.openbel.org/bel/namespace//MAPK%20Erk1/3%20Family
# or
# http://www.openbel.org/bel/namespace/MAPK%20Erk1/3%20Family
# In the current implementation, the order of the patterns
# matters.
patterns = ['http://www.openbel.org/bel/namespace//(.*)',
'http://www.openbel.org/vocabulary//(.*)',
'http://www.openbel.org/bel//(.*)',
'http://www.openbel.org/bel/namespace/(.*)',
'http://www.openbel.org/vocabulary/(.*)',
'http://www.openbel.org/bel/(.*)']
for pr in patterns:
match = re.match(pr, uri)
if match is not None:
term = match.groups()[0]
term = unquote(term)
return term
# If none of the patterns match then the URI is actually a simple term
# for instance a site: "341" or a substitution: "sub(V,600,E)"
return uri | [
"def",
"term_from_uri",
"(",
"uri",
")",
":",
"if",
"uri",
"is",
"None",
":",
"return",
"None",
"# This insures that if we get a Literal with an integer value (as we",
"# do for modification positions), it will get converted to a string,",
"# not an integer.",
"if",
"isinstance",
... | Removes prepended URI information from terms. | [
"Removes",
"prepended",
"URI",
"information",
"from",
"terms",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/bel/rdf_processor.py#L37-L66 |
19,138 | sorgerlab/indra | indra/sources/bel/rdf_processor.py | BelRdfProcessor.get_activating_mods | def get_activating_mods(self):
"""Extract INDRA ActiveForm Statements with a single mod from BEL.
The SPARQL pattern used for extraction from BEL looks for a
ModifiedProteinAbundance as subject and an Activiy of a
ProteinAbundance as object.
Examples:
proteinAbundance(HGNC:INSR,proteinModification(P,Y))
directlyIncreases
kinaseActivity(proteinAbundance(HGNC:INSR))
"""
q_mods = prefixes + """
SELECT ?speciesName ?actType ?mod ?pos ?rel ?stmt ?species
WHERE {
?stmt a belvoc:Statement .
?stmt belvoc:hasRelationship ?rel .
?stmt belvoc:hasSubject ?subject .
?stmt belvoc:hasObject ?object .
?object belvoc:hasActivityType ?actType .
?object belvoc:hasChild ?species .
?species a belvoc:ProteinAbundance .
?species belvoc:hasConcept ?speciesName .
?subject a belvoc:ModifiedProteinAbundance .
?subject belvoc:hasModificationType ?mod .
?subject belvoc:hasChild ?species .
OPTIONAL { ?subject belvoc:hasModificationPosition ?pos . }
FILTER (?rel = belvoc:DirectlyIncreases ||
?rel = belvoc:DirectlyDecreases)
}
"""
# Now make the PySB for the phosphorylation
res_mods = self.g.query(q_mods)
for stmt in res_mods:
evidence = self._get_evidence(stmt[5])
# Parse out the elements of the query
species = self._get_agent(stmt[0], stmt[6])
act_type = term_from_uri(stmt[1]).lower()
mod = term_from_uri(stmt[2])
mod_pos = term_from_uri(stmt[3])
mc = self._get_mod_condition(mod, mod_pos)
species.mods = [mc]
rel = term_from_uri(stmt[4])
if rel == 'DirectlyDecreases':
is_active = False
else:
is_active = True
stmt_str = strip_statement(stmt[5])
# Mark this as a converted statement
self.converted_direct_stmts.append(stmt_str)
st = ActiveForm(species, act_type, is_active, evidence)
self.statements.append(st) | python | def get_activating_mods(self):
q_mods = prefixes + """
SELECT ?speciesName ?actType ?mod ?pos ?rel ?stmt ?species
WHERE {
?stmt a belvoc:Statement .
?stmt belvoc:hasRelationship ?rel .
?stmt belvoc:hasSubject ?subject .
?stmt belvoc:hasObject ?object .
?object belvoc:hasActivityType ?actType .
?object belvoc:hasChild ?species .
?species a belvoc:ProteinAbundance .
?species belvoc:hasConcept ?speciesName .
?subject a belvoc:ModifiedProteinAbundance .
?subject belvoc:hasModificationType ?mod .
?subject belvoc:hasChild ?species .
OPTIONAL { ?subject belvoc:hasModificationPosition ?pos . }
FILTER (?rel = belvoc:DirectlyIncreases ||
?rel = belvoc:DirectlyDecreases)
}
"""
# Now make the PySB for the phosphorylation
res_mods = self.g.query(q_mods)
for stmt in res_mods:
evidence = self._get_evidence(stmt[5])
# Parse out the elements of the query
species = self._get_agent(stmt[0], stmt[6])
act_type = term_from_uri(stmt[1]).lower()
mod = term_from_uri(stmt[2])
mod_pos = term_from_uri(stmt[3])
mc = self._get_mod_condition(mod, mod_pos)
species.mods = [mc]
rel = term_from_uri(stmt[4])
if rel == 'DirectlyDecreases':
is_active = False
else:
is_active = True
stmt_str = strip_statement(stmt[5])
# Mark this as a converted statement
self.converted_direct_stmts.append(stmt_str)
st = ActiveForm(species, act_type, is_active, evidence)
self.statements.append(st) | [
"def",
"get_activating_mods",
"(",
"self",
")",
":",
"q_mods",
"=",
"prefixes",
"+",
"\"\"\"\n SELECT ?speciesName ?actType ?mod ?pos ?rel ?stmt ?species\n WHERE {\n ?stmt a belvoc:Statement .\n ?stmt belvoc:hasRelationship ?rel .\n ... | Extract INDRA ActiveForm Statements with a single mod from BEL.
The SPARQL pattern used for extraction from BEL looks for a
ModifiedProteinAbundance as subject and an Activiy of a
ProteinAbundance as object.
Examples:
proteinAbundance(HGNC:INSR,proteinModification(P,Y))
directlyIncreases
kinaseActivity(proteinAbundance(HGNC:INSR)) | [
"Extract",
"INDRA",
"ActiveForm",
"Statements",
"with",
"a",
"single",
"mod",
"from",
"BEL",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/bel/rdf_processor.py#L225-L279 |
19,139 | sorgerlab/indra | indra/sources/bel/rdf_processor.py | BelRdfProcessor.get_complexes | def get_complexes(self):
"""Extract INDRA Complex Statements from BEL.
The SPARQL query used to extract Complexes looks for ComplexAbundance
terms and their constituents. This pattern is distinct from other
patterns in this processor in that it queries for terms, not
full statements.
Examples:
complexAbundance(proteinAbundance(HGNC:PPARG),
proteinAbundance(HGNC:RXRA))
decreases
biologicalProcess(MESHPP:"Insulin Resistance")
"""
q_cmplx = prefixes + """
SELECT ?complexTerm ?childName ?child ?stmt
WHERE {
{
{?stmt belvoc:hasSubject ?complexTerm}
UNION
{?stmt belvoc:hasObject ?complexTerm .}
UNION
{?stmt belvoc:hasSubject ?term .
?term belvoc:hasChild ?complexTerm .}
UNION
{?stmt belvoc:hasObject ?term .
?term belvoc:hasChild ?complexTerm .}
}
?complexTerm a belvoc:Term .
?complexTerm a belvoc:ComplexAbundance .
?complexTerm belvoc:hasChild ?child .
?child belvoc:hasConcept ?childName .
}
"""
# Run the query
res_cmplx = self.g.query(q_cmplx)
# Store the members of each complex in a dict of lists, keyed by the
# term for the complex
cmplx_dict = collections.defaultdict(list)
cmplx_ev = {}
for stmt in res_cmplx:
stmt_uri = stmt[3]
ev = self._get_evidence(stmt_uri)
for e in ev:
e.epistemics['direct'] = True
cmplx_name = term_from_uri(stmt[0])
cmplx_id = stmt_uri + '#' + cmplx_name
child = self._get_agent(stmt[1], stmt[2])
cmplx_dict[cmplx_id].append(child)
# This might be written multiple times but with the same
# evidence
cmplx_ev[cmplx_id] = ev
# Now iterate over the stored complex information and create binding
# statements
for cmplx_id, cmplx_list in cmplx_dict.items():
if len(cmplx_list) < 2:
msg = 'Complex %s has less than 2 members! Skipping.' % \
cmplx_name
logger.warning(msg)
else:
self.statements.append(Complex(cmplx_list,
evidence=cmplx_ev[cmplx_id])) | python | def get_complexes(self):
q_cmplx = prefixes + """
SELECT ?complexTerm ?childName ?child ?stmt
WHERE {
{
{?stmt belvoc:hasSubject ?complexTerm}
UNION
{?stmt belvoc:hasObject ?complexTerm .}
UNION
{?stmt belvoc:hasSubject ?term .
?term belvoc:hasChild ?complexTerm .}
UNION
{?stmt belvoc:hasObject ?term .
?term belvoc:hasChild ?complexTerm .}
}
?complexTerm a belvoc:Term .
?complexTerm a belvoc:ComplexAbundance .
?complexTerm belvoc:hasChild ?child .
?child belvoc:hasConcept ?childName .
}
"""
# Run the query
res_cmplx = self.g.query(q_cmplx)
# Store the members of each complex in a dict of lists, keyed by the
# term for the complex
cmplx_dict = collections.defaultdict(list)
cmplx_ev = {}
for stmt in res_cmplx:
stmt_uri = stmt[3]
ev = self._get_evidence(stmt_uri)
for e in ev:
e.epistemics['direct'] = True
cmplx_name = term_from_uri(stmt[0])
cmplx_id = stmt_uri + '#' + cmplx_name
child = self._get_agent(stmt[1], stmt[2])
cmplx_dict[cmplx_id].append(child)
# This might be written multiple times but with the same
# evidence
cmplx_ev[cmplx_id] = ev
# Now iterate over the stored complex information and create binding
# statements
for cmplx_id, cmplx_list in cmplx_dict.items():
if len(cmplx_list) < 2:
msg = 'Complex %s has less than 2 members! Skipping.' % \
cmplx_name
logger.warning(msg)
else:
self.statements.append(Complex(cmplx_list,
evidence=cmplx_ev[cmplx_id])) | [
"def",
"get_complexes",
"(",
"self",
")",
":",
"q_cmplx",
"=",
"prefixes",
"+",
"\"\"\"\n SELECT ?complexTerm ?childName ?child ?stmt\n WHERE {\n {\n {?stmt belvoc:hasSubject ?complexTerm}\n UNION\n {?stmt belvoc:h... | Extract INDRA Complex Statements from BEL.
The SPARQL query used to extract Complexes looks for ComplexAbundance
terms and their constituents. This pattern is distinct from other
patterns in this processor in that it queries for terms, not
full statements.
Examples:
complexAbundance(proteinAbundance(HGNC:PPARG),
proteinAbundance(HGNC:RXRA))
decreases
biologicalProcess(MESHPP:"Insulin Resistance") | [
"Extract",
"INDRA",
"Complex",
"Statements",
"from",
"BEL",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/bel/rdf_processor.py#L281-L344 |
19,140 | sorgerlab/indra | indra/sources/bel/rdf_processor.py | BelRdfProcessor.get_activating_subs | def get_activating_subs(self):
"""Extract INDRA ActiveForm Statements based on a mutation from BEL.
The SPARQL pattern used to extract ActiveForms due to mutations look
for a ProteinAbundance as a subject which has a child encoding the
amino acid substitution. The object of the statement is an
ActivityType of the same ProteinAbundance, which is either increased
or decreased.
Examples:
proteinAbundance(HGNC:NRAS,substitution(Q,61,K))
directlyIncreases
gtpBoundActivity(proteinAbundance(HGNC:NRAS))
proteinAbundance(HGNC:TP53,substitution(F,134,I))
directlyDecreases
transcriptionalActivity(proteinAbundance(HGNC:TP53))
"""
q_mods = prefixes + """
SELECT ?enzyme_name ?sub_label ?act_type ?rel ?stmt ?subject
WHERE {
?stmt a belvoc:Statement .
?stmt belvoc:hasRelationship ?rel .
?stmt belvoc:hasSubject ?subject .
?stmt belvoc:hasObject ?object .
?subject a belvoc:ProteinAbundance .
?subject belvoc:hasConcept ?enzyme_name .
?subject belvoc:hasChild ?sub_expr .
?sub_expr rdfs:label ?sub_label .
?object a belvoc:AbundanceActivity .
?object belvoc:hasActivityType ?act_type .
?object belvoc:hasChild ?enzyme .
?enzyme a belvoc:ProteinAbundance .
?enzyme belvoc:hasConcept ?enzyme_name .
}
"""
# Now make the PySB for the phosphorylation
res_mods = self.g.query(q_mods)
for stmt in res_mods:
evidence = self._get_evidence(stmt[4])
# Parse out the elements of the query
enz = self._get_agent(stmt[0], stmt[5])
sub_expr = term_from_uri(stmt[1])
act_type = term_from_uri(stmt[2]).lower()
# Parse the WT and substituted residues from the node label.
# Strangely, the RDF for substituted residue doesn't break the
# terms of the BEL expression down into their meaning, as happens
# for modified protein abundances. Instead, the substitution
# just comes back as a string, e.g., "sub(V,600,E)". This code
# parses the arguments back out using a regular expression.
match = re.match('sub\(([A-Z]),([0-9]*),([A-Z])\)', sub_expr)
if match:
matches = match.groups()
wt_residue = matches[0]
position = matches[1]
sub_residue = matches[2]
else:
logger.warning("Could not parse substitution expression %s" %
sub_expr)
continue
mc = MutCondition(position, wt_residue, sub_residue)
enz.mutations = [mc]
rel = strip_statement(stmt[3])
if rel == 'DirectlyDecreases':
is_active = False
else:
is_active = True
stmt_str = strip_statement(stmt[4])
# Mark this as a converted statement
self.converted_direct_stmts.append(stmt_str)
st = ActiveForm(enz, act_type, is_active, evidence)
self.statements.append(st) | python | def get_activating_subs(self):
q_mods = prefixes + """
SELECT ?enzyme_name ?sub_label ?act_type ?rel ?stmt ?subject
WHERE {
?stmt a belvoc:Statement .
?stmt belvoc:hasRelationship ?rel .
?stmt belvoc:hasSubject ?subject .
?stmt belvoc:hasObject ?object .
?subject a belvoc:ProteinAbundance .
?subject belvoc:hasConcept ?enzyme_name .
?subject belvoc:hasChild ?sub_expr .
?sub_expr rdfs:label ?sub_label .
?object a belvoc:AbundanceActivity .
?object belvoc:hasActivityType ?act_type .
?object belvoc:hasChild ?enzyme .
?enzyme a belvoc:ProteinAbundance .
?enzyme belvoc:hasConcept ?enzyme_name .
}
"""
# Now make the PySB for the phosphorylation
res_mods = self.g.query(q_mods)
for stmt in res_mods:
evidence = self._get_evidence(stmt[4])
# Parse out the elements of the query
enz = self._get_agent(stmt[0], stmt[5])
sub_expr = term_from_uri(stmt[1])
act_type = term_from_uri(stmt[2]).lower()
# Parse the WT and substituted residues from the node label.
# Strangely, the RDF for substituted residue doesn't break the
# terms of the BEL expression down into their meaning, as happens
# for modified protein abundances. Instead, the substitution
# just comes back as a string, e.g., "sub(V,600,E)". This code
# parses the arguments back out using a regular expression.
match = re.match('sub\(([A-Z]),([0-9]*),([A-Z])\)', sub_expr)
if match:
matches = match.groups()
wt_residue = matches[0]
position = matches[1]
sub_residue = matches[2]
else:
logger.warning("Could not parse substitution expression %s" %
sub_expr)
continue
mc = MutCondition(position, wt_residue, sub_residue)
enz.mutations = [mc]
rel = strip_statement(stmt[3])
if rel == 'DirectlyDecreases':
is_active = False
else:
is_active = True
stmt_str = strip_statement(stmt[4])
# Mark this as a converted statement
self.converted_direct_stmts.append(stmt_str)
st = ActiveForm(enz, act_type, is_active, evidence)
self.statements.append(st) | [
"def",
"get_activating_subs",
"(",
"self",
")",
":",
"q_mods",
"=",
"prefixes",
"+",
"\"\"\"\n SELECT ?enzyme_name ?sub_label ?act_type ?rel ?stmt ?subject\n WHERE {\n ?stmt a belvoc:Statement .\n ?stmt belvoc:hasRelationship ?rel .\n ... | Extract INDRA ActiveForm Statements based on a mutation from BEL.
The SPARQL pattern used to extract ActiveForms due to mutations look
for a ProteinAbundance as a subject which has a child encoding the
amino acid substitution. The object of the statement is an
ActivityType of the same ProteinAbundance, which is either increased
or decreased.
Examples:
proteinAbundance(HGNC:NRAS,substitution(Q,61,K))
directlyIncreases
gtpBoundActivity(proteinAbundance(HGNC:NRAS))
proteinAbundance(HGNC:TP53,substitution(F,134,I))
directlyDecreases
transcriptionalActivity(proteinAbundance(HGNC:TP53)) | [
"Extract",
"INDRA",
"ActiveForm",
"Statements",
"based",
"on",
"a",
"mutation",
"from",
"BEL",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/bel/rdf_processor.py#L346-L421 |
19,141 | sorgerlab/indra | indra/sources/bel/rdf_processor.py | BelRdfProcessor.get_conversions | def get_conversions(self):
"""Extract Conversion INDRA Statements from BEL.
The SPARQL query used to extract Conversions searches for
a subject (controller) which is an AbundanceActivity
which directlyIncreases a Reaction with a given list of
Reactants and Products.
Examples:
catalyticActivity(proteinAbundance(HGNC:HMOX1))
directlyIncreases
reaction(reactants(abundance(CHEBI:heme)),
products(abundance(SCHEM:Biliverdine),
abundance(CHEBI:"carbon monoxide")))
"""
query = prefixes + """
SELECT DISTINCT ?controller ?controllerName ?controllerActivity
?product ?productName ?reactant ?reactantName ?stmt
WHERE {
?stmt a belvoc:Statement .
?stmt belvoc:hasRelationship ?rel .
?stmt belvoc:hasSubject ?subject .
?stmt belvoc:hasObject ?rxn .
?subject a belvoc:AbundanceActivity .
?subject belvoc:hasActivityType ?controllerActivity .
?subject belvoc:hasChild ?controller .
?controller belvoc:hasConcept ?controllerName .
?rxn a belvoc:Reaction .
?rxn belvoc:hasChild ?reactants .
?reactants rdfs:label ?reactLabel .
FILTER (regex(?reactLabel, "^reactants.*"))
?rxn belvoc:hasChild ?products .
?products rdfs:label ?prodLabel .
FILTER (regex(?prodLabel, "^products.*"))
?reactants belvoc:hasChild ?reactant .
?products belvoc:hasChild ?product .
?reactant belvoc:hasConcept ?reactantName .
?product belvoc:hasConcept ?productName .
}
"""
res = self.g.query(query)
# We need to collect all pieces of the same statement so that we can
# collect multiple reactants and products
stmt_map = collections.defaultdict(list)
for stmt in res:
stmt_map[stmt[-1]].append(stmt)
for stmts in stmt_map.values():
# First we get the shared part of the Statement
stmt = stmts[0]
subj = self._get_agent(stmt[1], stmt[0])
evidence = self._get_evidence(stmt[-1])
stmt_str = strip_statement(stmt[-1])
# Now we collect the participants
obj_from_map = {}
obj_to_map = {}
for stmt in stmts:
reactant_name = stmt[6]
product_name = stmt[4]
if reactant_name not in obj_from_map:
obj_from_map[reactant_name] = \
self._get_agent(stmt[6], stmt[5])
if product_name not in obj_to_map:
obj_to_map[product_name] = \
self._get_agent(stmt[4], stmt[3])
obj_from = list(obj_from_map.values())
obj_to = list(obj_to_map.values())
st = Conversion(subj, obj_from, obj_to, evidence=evidence)
# If we've matched a pattern, mark this as a converted statement
self.statements.append(st)
self.converted_direct_stmts.append(stmt_str) | python | def get_conversions(self):
query = prefixes + """
SELECT DISTINCT ?controller ?controllerName ?controllerActivity
?product ?productName ?reactant ?reactantName ?stmt
WHERE {
?stmt a belvoc:Statement .
?stmt belvoc:hasRelationship ?rel .
?stmt belvoc:hasSubject ?subject .
?stmt belvoc:hasObject ?rxn .
?subject a belvoc:AbundanceActivity .
?subject belvoc:hasActivityType ?controllerActivity .
?subject belvoc:hasChild ?controller .
?controller belvoc:hasConcept ?controllerName .
?rxn a belvoc:Reaction .
?rxn belvoc:hasChild ?reactants .
?reactants rdfs:label ?reactLabel .
FILTER (regex(?reactLabel, "^reactants.*"))
?rxn belvoc:hasChild ?products .
?products rdfs:label ?prodLabel .
FILTER (regex(?prodLabel, "^products.*"))
?reactants belvoc:hasChild ?reactant .
?products belvoc:hasChild ?product .
?reactant belvoc:hasConcept ?reactantName .
?product belvoc:hasConcept ?productName .
}
"""
res = self.g.query(query)
# We need to collect all pieces of the same statement so that we can
# collect multiple reactants and products
stmt_map = collections.defaultdict(list)
for stmt in res:
stmt_map[stmt[-1]].append(stmt)
for stmts in stmt_map.values():
# First we get the shared part of the Statement
stmt = stmts[0]
subj = self._get_agent(stmt[1], stmt[0])
evidence = self._get_evidence(stmt[-1])
stmt_str = strip_statement(stmt[-1])
# Now we collect the participants
obj_from_map = {}
obj_to_map = {}
for stmt in stmts:
reactant_name = stmt[6]
product_name = stmt[4]
if reactant_name not in obj_from_map:
obj_from_map[reactant_name] = \
self._get_agent(stmt[6], stmt[5])
if product_name not in obj_to_map:
obj_to_map[product_name] = \
self._get_agent(stmt[4], stmt[3])
obj_from = list(obj_from_map.values())
obj_to = list(obj_to_map.values())
st = Conversion(subj, obj_from, obj_to, evidence=evidence)
# If we've matched a pattern, mark this as a converted statement
self.statements.append(st)
self.converted_direct_stmts.append(stmt_str) | [
"def",
"get_conversions",
"(",
"self",
")",
":",
"query",
"=",
"prefixes",
"+",
"\"\"\"\n SELECT DISTINCT ?controller ?controllerName ?controllerActivity\n ?product ?productName ?reactant ?reactantName ?stmt\n WHERE {\n ?stmt a belvoc:Statement... | Extract Conversion INDRA Statements from BEL.
The SPARQL query used to extract Conversions searches for
a subject (controller) which is an AbundanceActivity
which directlyIncreases a Reaction with a given list of
Reactants and Products.
Examples:
catalyticActivity(proteinAbundance(HGNC:HMOX1))
directlyIncreases
reaction(reactants(abundance(CHEBI:heme)),
products(abundance(SCHEM:Biliverdine),
abundance(CHEBI:"carbon monoxide"))) | [
"Extract",
"Conversion",
"INDRA",
"Statements",
"from",
"BEL",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/bel/rdf_processor.py#L654-L725 |
19,142 | sorgerlab/indra | indra/sources/bel/rdf_processor.py | BelRdfProcessor.get_degenerate_statements | def get_degenerate_statements(self):
"""Get all degenerate BEL statements.
Stores the results of the query in self.degenerate_stmts.
"""
logger.info("Checking for 'degenerate' statements...\n")
# Get rules of type protein X -> activity Y
q_stmts = prefixes + """
SELECT ?stmt
WHERE {
?stmt a belvoc:Statement .
?stmt belvoc:hasSubject ?subj .
?stmt belvoc:hasObject ?obj .
{
{ ?stmt belvoc:hasRelationship belvoc:DirectlyIncreases . }
UNION
{ ?stmt belvoc:hasRelationship belvoc:DirectlyDecreases . }
}
{
{ ?subj a belvoc:ProteinAbundance . }
UNION
{ ?subj a belvoc:ModifiedProteinAbundance . }
}
?subj belvoc:hasConcept ?xName .
{
{
?obj a belvoc:ProteinAbundance .
?obj belvoc:hasConcept ?yName .
}
UNION
{
?obj a belvoc:ModifiedProteinAbundance .
?obj belvoc:hasChild ?proteinY .
?proteinY belvoc:hasConcept ?yName .
}
UNION
{
?obj a belvoc:AbundanceActivity .
?obj belvoc:hasChild ?objChild .
?objChild a belvoc:ProteinAbundance .
?objChild belvoc:hasConcept ?yName .
}
}
FILTER (?xName != ?yName)
}
"""
res_stmts = self.g.query(q_stmts)
logger.info("Protein -> Protein/Activity statements:")
logger.info("---------------------------------------")
for stmt in res_stmts:
stmt_str = strip_statement(stmt[0])
logger.info(stmt_str)
self.degenerate_stmts.append(stmt_str) | python | def get_degenerate_statements(self):
logger.info("Checking for 'degenerate' statements...\n")
# Get rules of type protein X -> activity Y
q_stmts = prefixes + """
SELECT ?stmt
WHERE {
?stmt a belvoc:Statement .
?stmt belvoc:hasSubject ?subj .
?stmt belvoc:hasObject ?obj .
{
{ ?stmt belvoc:hasRelationship belvoc:DirectlyIncreases . }
UNION
{ ?stmt belvoc:hasRelationship belvoc:DirectlyDecreases . }
}
{
{ ?subj a belvoc:ProteinAbundance . }
UNION
{ ?subj a belvoc:ModifiedProteinAbundance . }
}
?subj belvoc:hasConcept ?xName .
{
{
?obj a belvoc:ProteinAbundance .
?obj belvoc:hasConcept ?yName .
}
UNION
{
?obj a belvoc:ModifiedProteinAbundance .
?obj belvoc:hasChild ?proteinY .
?proteinY belvoc:hasConcept ?yName .
}
UNION
{
?obj a belvoc:AbundanceActivity .
?obj belvoc:hasChild ?objChild .
?objChild a belvoc:ProteinAbundance .
?objChild belvoc:hasConcept ?yName .
}
}
FILTER (?xName != ?yName)
}
"""
res_stmts = self.g.query(q_stmts)
logger.info("Protein -> Protein/Activity statements:")
logger.info("---------------------------------------")
for stmt in res_stmts:
stmt_str = strip_statement(stmt[0])
logger.info(stmt_str)
self.degenerate_stmts.append(stmt_str) | [
"def",
"get_degenerate_statements",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"\"Checking for 'degenerate' statements...\\n\"",
")",
"# Get rules of type protein X -> activity Y",
"q_stmts",
"=",
"prefixes",
"+",
"\"\"\"\n SELECT ?stmt\n WHERE {\n ... | Get all degenerate BEL statements.
Stores the results of the query in self.degenerate_stmts. | [
"Get",
"all",
"degenerate",
"BEL",
"statements",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/bel/rdf_processor.py#L774-L827 |
19,143 | sorgerlab/indra | indra/sources/bel/rdf_processor.py | BelRdfProcessor.print_statement_coverage | def print_statement_coverage(self):
"""Display how many of the direct statements have been converted.
Also prints how many are considered 'degenerate' and not converted."""
if not self.all_direct_stmts:
self.get_all_direct_statements()
if not self.degenerate_stmts:
self.get_degenerate_statements()
if not self.all_indirect_stmts:
self.get_all_indirect_statements()
logger.info('')
logger.info("Total indirect statements: %d" %
len(self.all_indirect_stmts))
logger.info("Converted indirect statements: %d" %
len(self.converted_indirect_stmts))
logger.info(">> Unhandled indirect statements: %d" %
(len(self.all_indirect_stmts) -
len(self.converted_indirect_stmts)))
logger.info('')
logger.info("Total direct statements: %d" % len(self.all_direct_stmts))
logger.info("Converted direct statements: %d" %
len(self.converted_direct_stmts))
logger.info("Degenerate direct statements: %d" %
len(self.degenerate_stmts))
logger.info(">> Unhandled direct statements: %d" %
(len(self.all_direct_stmts) -
len(self.converted_direct_stmts) -
len(self.degenerate_stmts)))
logger.info('')
logger.info("--- Unhandled direct statements ---------")
for stmt in self.all_direct_stmts:
if not (stmt in self.converted_direct_stmts or
stmt in self.degenerate_stmts):
logger.info(stmt)
logger.info('')
logger.info("--- Unhandled indirect statements ---------")
for stmt in self.all_indirect_stmts:
if not (stmt in self.converted_indirect_stmts or
stmt in self.degenerate_stmts):
logger.info(stmt) | python | def print_statement_coverage(self):
if not self.all_direct_stmts:
self.get_all_direct_statements()
if not self.degenerate_stmts:
self.get_degenerate_statements()
if not self.all_indirect_stmts:
self.get_all_indirect_statements()
logger.info('')
logger.info("Total indirect statements: %d" %
len(self.all_indirect_stmts))
logger.info("Converted indirect statements: %d" %
len(self.converted_indirect_stmts))
logger.info(">> Unhandled indirect statements: %d" %
(len(self.all_indirect_stmts) -
len(self.converted_indirect_stmts)))
logger.info('')
logger.info("Total direct statements: %d" % len(self.all_direct_stmts))
logger.info("Converted direct statements: %d" %
len(self.converted_direct_stmts))
logger.info("Degenerate direct statements: %d" %
len(self.degenerate_stmts))
logger.info(">> Unhandled direct statements: %d" %
(len(self.all_direct_stmts) -
len(self.converted_direct_stmts) -
len(self.degenerate_stmts)))
logger.info('')
logger.info("--- Unhandled direct statements ---------")
for stmt in self.all_direct_stmts:
if not (stmt in self.converted_direct_stmts or
stmt in self.degenerate_stmts):
logger.info(stmt)
logger.info('')
logger.info("--- Unhandled indirect statements ---------")
for stmt in self.all_indirect_stmts:
if not (stmt in self.converted_indirect_stmts or
stmt in self.degenerate_stmts):
logger.info(stmt) | [
"def",
"print_statement_coverage",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"all_direct_stmts",
":",
"self",
".",
"get_all_direct_statements",
"(",
")",
"if",
"not",
"self",
".",
"degenerate_stmts",
":",
"self",
".",
"get_degenerate_statements",
"(",
")"... | Display how many of the direct statements have been converted.
Also prints how many are considered 'degenerate' and not converted. | [
"Display",
"how",
"many",
"of",
"the",
"direct",
"statements",
"have",
"been",
"converted",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/bel/rdf_processor.py#L829-L871 |
19,144 | sorgerlab/indra | indra/sources/bel/rdf_processor.py | BelRdfProcessor.print_statements | def print_statements(self):
"""Print all extracted INDRA Statements."""
logger.info('--- Direct INDRA statements ----------')
for i, stmt in enumerate(self.statements):
logger.info("%s: %s" % (i, stmt))
logger.info('--- Indirect INDRA statements ----------')
for i, stmt in enumerate(self.indirect_stmts):
logger.info("%s: %s" % (i, stmt)) | python | def print_statements(self):
logger.info('--- Direct INDRA statements ----------')
for i, stmt in enumerate(self.statements):
logger.info("%s: %s" % (i, stmt))
logger.info('--- Indirect INDRA statements ----------')
for i, stmt in enumerate(self.indirect_stmts):
logger.info("%s: %s" % (i, stmt)) | [
"def",
"print_statements",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"'--- Direct INDRA statements ----------'",
")",
"for",
"i",
",",
"stmt",
"in",
"enumerate",
"(",
"self",
".",
"statements",
")",
":",
"logger",
".",
"info",
"(",
"\"%s: %s\"",
"%"... | Print all extracted INDRA Statements. | [
"Print",
"all",
"extracted",
"INDRA",
"Statements",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/bel/rdf_processor.py#L873-L880 |
19,145 | sorgerlab/indra | indra/sources/medscan/api.py | process_directory_statements_sorted_by_pmid | def process_directory_statements_sorted_by_pmid(directory_name):
"""Processes a directory filled with CSXML files, first normalizing the
character encoding to utf-8, and then processing into INDRA statements
sorted by pmid.
Parameters
----------
directory_name : str
The name of a directory filled with csxml files to process
Returns
-------
pmid_dict : dict
A dictionary mapping pmids to a list of statements corresponding to
that pmid
"""
s_dict = defaultdict(list)
mp = process_directory(directory_name, lazy=True)
for statement in mp.iter_statements():
s_dict[statement.evidence[0].pmid].append(statement)
return s_dict | python | def process_directory_statements_sorted_by_pmid(directory_name):
s_dict = defaultdict(list)
mp = process_directory(directory_name, lazy=True)
for statement in mp.iter_statements():
s_dict[statement.evidence[0].pmid].append(statement)
return s_dict | [
"def",
"process_directory_statements_sorted_by_pmid",
"(",
"directory_name",
")",
":",
"s_dict",
"=",
"defaultdict",
"(",
"list",
")",
"mp",
"=",
"process_directory",
"(",
"directory_name",
",",
"lazy",
"=",
"True",
")",
"for",
"statement",
"in",
"mp",
".",
"ite... | Processes a directory filled with CSXML files, first normalizing the
character encoding to utf-8, and then processing into INDRA statements
sorted by pmid.
Parameters
----------
directory_name : str
The name of a directory filled with csxml files to process
Returns
-------
pmid_dict : dict
A dictionary mapping pmids to a list of statements corresponding to
that pmid | [
"Processes",
"a",
"directory",
"filled",
"with",
"CSXML",
"files",
"first",
"normalizing",
"the",
"character",
"encoding",
"to",
"utf",
"-",
"8",
"and",
"then",
"processing",
"into",
"INDRA",
"statements",
"sorted",
"by",
"pmid",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/medscan/api.py#L9-L30 |
19,146 | sorgerlab/indra | indra/sources/medscan/api.py | process_directory | def process_directory(directory_name, lazy=False):
"""Processes a directory filled with CSXML files, first normalizing the
character encodings to utf-8, and then processing into a list of INDRA
statements.
Parameters
----------
directory_name : str
The name of a directory filled with csxml files to process
lazy : bool
If True, the statements will not be generated immediately, but rather
a generator will be formulated, and statements can be retrieved by
using `iter_statements`. If False, the `statements` attribute will be
populated immediately. Default is False.
Returns
-------
mp : indra.sources.medscan.processor.MedscanProcessor
A MedscanProcessor populated with INDRA statements extracted from the
csxml files
"""
# Parent Medscan processor containing extractions from all files
mp = MedscanProcessor()
mp.process_directory(directory_name, lazy)
return mp | python | def process_directory(directory_name, lazy=False):
# Parent Medscan processor containing extractions from all files
mp = MedscanProcessor()
mp.process_directory(directory_name, lazy)
return mp | [
"def",
"process_directory",
"(",
"directory_name",
",",
"lazy",
"=",
"False",
")",
":",
"# Parent Medscan processor containing extractions from all files",
"mp",
"=",
"MedscanProcessor",
"(",
")",
"mp",
".",
"process_directory",
"(",
"directory_name",
",",
"lazy",
")",
... | Processes a directory filled with CSXML files, first normalizing the
character encodings to utf-8, and then processing into a list of INDRA
statements.
Parameters
----------
directory_name : str
The name of a directory filled with csxml files to process
lazy : bool
If True, the statements will not be generated immediately, but rather
a generator will be formulated, and statements can be retrieved by
using `iter_statements`. If False, the `statements` attribute will be
populated immediately. Default is False.
Returns
-------
mp : indra.sources.medscan.processor.MedscanProcessor
A MedscanProcessor populated with INDRA statements extracted from the
csxml files | [
"Processes",
"a",
"directory",
"filled",
"with",
"CSXML",
"files",
"first",
"normalizing",
"the",
"character",
"encodings",
"to",
"utf",
"-",
"8",
"and",
"then",
"processing",
"into",
"a",
"list",
"of",
"INDRA",
"statements",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/medscan/api.py#L33-L58 |
19,147 | sorgerlab/indra | indra/sources/medscan/api.py | process_file_sorted_by_pmid | def process_file_sorted_by_pmid(file_name):
"""Processes a file and returns a dictionary mapping pmids to a list of
statements corresponding to that pmid.
Parameters
----------
file_name : str
A csxml file to process
Returns
-------
s_dict : dict
Dictionary mapping pmids to a list of statements corresponding to
that pmid
"""
s_dict = defaultdict(list)
mp = process_file(file_name, lazy=True)
for statement in mp.iter_statements():
s_dict[statement.evidence[0].pmid].append(statement)
return s_dict | python | def process_file_sorted_by_pmid(file_name):
s_dict = defaultdict(list)
mp = process_file(file_name, lazy=True)
for statement in mp.iter_statements():
s_dict[statement.evidence[0].pmid].append(statement)
return s_dict | [
"def",
"process_file_sorted_by_pmid",
"(",
"file_name",
")",
":",
"s_dict",
"=",
"defaultdict",
"(",
"list",
")",
"mp",
"=",
"process_file",
"(",
"file_name",
",",
"lazy",
"=",
"True",
")",
"for",
"statement",
"in",
"mp",
".",
"iter_statements",
"(",
")",
... | Processes a file and returns a dictionary mapping pmids to a list of
statements corresponding to that pmid.
Parameters
----------
file_name : str
A csxml file to process
Returns
-------
s_dict : dict
Dictionary mapping pmids to a list of statements corresponding to
that pmid | [
"Processes",
"a",
"file",
"and",
"returns",
"a",
"dictionary",
"mapping",
"pmids",
"to",
"a",
"list",
"of",
"statements",
"corresponding",
"to",
"that",
"pmid",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/medscan/api.py#L61-L81 |
19,148 | sorgerlab/indra | indra/sources/medscan/api.py | process_file | def process_file(filename, interval=None, lazy=False):
"""Process a CSXML file for its relevant information.
Consider running the fix_csxml_character_encoding.py script in
indra/sources/medscan to fix any encoding issues in the input file before
processing.
Attributes
----------
filename : str
The csxml file, containing Medscan XML, to process
interval : (start, end) or None
Select the interval of documents to read, starting with the
`start`th document and ending before the `end`th document. If
either is None, the value is considered undefined. If the value
exceeds the bounds of available documents, it will simply be
ignored.
lazy : bool
If True, the statements will not be generated immediately, but rather
a generator will be formulated, and statements can be retrieved by
using `iter_statements`. If False, the `statements` attribute will be
populated immediately. Default is False.
Returns
-------
mp : MedscanProcessor
A MedscanProcessor object containing extracted statements
"""
mp = MedscanProcessor()
mp.process_csxml_file(filename, interval, lazy)
return mp | python | def process_file(filename, interval=None, lazy=False):
mp = MedscanProcessor()
mp.process_csxml_file(filename, interval, lazy)
return mp | [
"def",
"process_file",
"(",
"filename",
",",
"interval",
"=",
"None",
",",
"lazy",
"=",
"False",
")",
":",
"mp",
"=",
"MedscanProcessor",
"(",
")",
"mp",
".",
"process_csxml_file",
"(",
"filename",
",",
"interval",
",",
"lazy",
")",
"return",
"mp"
] | Process a CSXML file for its relevant information.
Consider running the fix_csxml_character_encoding.py script in
indra/sources/medscan to fix any encoding issues in the input file before
processing.
Attributes
----------
filename : str
The csxml file, containing Medscan XML, to process
interval : (start, end) or None
Select the interval of documents to read, starting with the
`start`th document and ending before the `end`th document. If
either is None, the value is considered undefined. If the value
exceeds the bounds of available documents, it will simply be
ignored.
lazy : bool
If True, the statements will not be generated immediately, but rather
a generator will be formulated, and statements can be retrieved by
using `iter_statements`. If False, the `statements` attribute will be
populated immediately. Default is False.
Returns
-------
mp : MedscanProcessor
A MedscanProcessor object containing extracted statements | [
"Process",
"a",
"CSXML",
"file",
"for",
"its",
"relevant",
"information",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/medscan/api.py#L84-L114 |
19,149 | sorgerlab/indra | indra/explanation/reporting.py | stmts_from_path | def stmts_from_path(path, model, stmts):
"""Return source Statements corresponding to a path in a model.
Parameters
----------
path : list[tuple[str, int]]
A list of tuples where the first element of the tuple is the
name of a rule, and the second is the associated polarity along
a path.
model : pysb.core.Model
A PySB model which contains the rules along the path.
stmts : list[indra.statements.Statement]
A list of INDRA Statements from which the model was assembled.
Returns
-------
path_stmts : list[indra.statements.Statement]
The Statements from which the rules along the path were obtained.
"""
path_stmts = []
for path_rule, sign in path:
for rule in model.rules:
if rule.name == path_rule:
stmt = stmt_from_rule(path_rule, model, stmts)
assert stmt is not None
path_stmts.append(stmt)
return path_stmts | python | def stmts_from_path(path, model, stmts):
path_stmts = []
for path_rule, sign in path:
for rule in model.rules:
if rule.name == path_rule:
stmt = stmt_from_rule(path_rule, model, stmts)
assert stmt is not None
path_stmts.append(stmt)
return path_stmts | [
"def",
"stmts_from_path",
"(",
"path",
",",
"model",
",",
"stmts",
")",
":",
"path_stmts",
"=",
"[",
"]",
"for",
"path_rule",
",",
"sign",
"in",
"path",
":",
"for",
"rule",
"in",
"model",
".",
"rules",
":",
"if",
"rule",
".",
"name",
"==",
"path_rule... | Return source Statements corresponding to a path in a model.
Parameters
----------
path : list[tuple[str, int]]
A list of tuples where the first element of the tuple is the
name of a rule, and the second is the associated polarity along
a path.
model : pysb.core.Model
A PySB model which contains the rules along the path.
stmts : list[indra.statements.Statement]
A list of INDRA Statements from which the model was assembled.
Returns
-------
path_stmts : list[indra.statements.Statement]
The Statements from which the rules along the path were obtained. | [
"Return",
"source",
"Statements",
"corresponding",
"to",
"a",
"path",
"in",
"a",
"model",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/explanation/reporting.py#L3-L29 |
19,150 | sorgerlab/indra | indra/sources/bel/processor.py | extract_context | def extract_context(annotations, annot_manager):
"""Return a BioContext object extracted from the annotations.
The entries that are extracted into the BioContext are popped from the
annotations.
Parameters
----------
annotations : dict
PyBEL annotations dict
annot_manager : AnnotationManager
An annotation manager to get name/db reference mappings for each ot the
annotation types.
Returns
-------
bc : BioContext
An INDRA BioContext object
"""
def get_annot(annotations, key):
"""Return a specific annotation given a key."""
val = annotations.pop(key, None)
if val:
val_list = [v for v, tf in val.items() if tf]
if len(val_list) > 1:
logger.warning('More than one "%s" in annotations' % key)
elif not val_list:
return None
return val_list[0]
return None
bc = BioContext()
species = get_annot(annotations, 'Species')
if species:
name = annot_manager.get_mapping('Species', species)
bc.species = RefContext(name=name, db_refs={'TAXONOMY': species})
mappings = (('CellLine', 'cell_line', None),
('Disease', 'disease', None),
('Anatomy', 'organ', None),
('Cell', 'cell_type', None),
('CellStructure', 'location', 'MESH'))
for bel_name, indra_name, ns in mappings:
ann = get_annot(annotations, bel_name)
if ann:
ref = annot_manager.get_mapping(bel_name, ann)
if ref is None:
continue
if not ns:
db_ns, db_id = ref.split('_', 1)
else:
db_ns, db_id = ns, ref
setattr(bc, indra_name,
RefContext(name=ann, db_refs={db_ns: db_id}))
# Overwrite blank BioContext
if not bc:
bc = None
return bc | python | def extract_context(annotations, annot_manager):
def get_annot(annotations, key):
"""Return a specific annotation given a key."""
val = annotations.pop(key, None)
if val:
val_list = [v for v, tf in val.items() if tf]
if len(val_list) > 1:
logger.warning('More than one "%s" in annotations' % key)
elif not val_list:
return None
return val_list[0]
return None
bc = BioContext()
species = get_annot(annotations, 'Species')
if species:
name = annot_manager.get_mapping('Species', species)
bc.species = RefContext(name=name, db_refs={'TAXONOMY': species})
mappings = (('CellLine', 'cell_line', None),
('Disease', 'disease', None),
('Anatomy', 'organ', None),
('Cell', 'cell_type', None),
('CellStructure', 'location', 'MESH'))
for bel_name, indra_name, ns in mappings:
ann = get_annot(annotations, bel_name)
if ann:
ref = annot_manager.get_mapping(bel_name, ann)
if ref is None:
continue
if not ns:
db_ns, db_id = ref.split('_', 1)
else:
db_ns, db_id = ns, ref
setattr(bc, indra_name,
RefContext(name=ann, db_refs={db_ns: db_id}))
# Overwrite blank BioContext
if not bc:
bc = None
return bc | [
"def",
"extract_context",
"(",
"annotations",
",",
"annot_manager",
")",
":",
"def",
"get_annot",
"(",
"annotations",
",",
"key",
")",
":",
"\"\"\"Return a specific annotation given a key.\"\"\"",
"val",
"=",
"annotations",
".",
"pop",
"(",
"key",
",",
"None",
")"... | Return a BioContext object extracted from the annotations.
The entries that are extracted into the BioContext are popped from the
annotations.
Parameters
----------
annotations : dict
PyBEL annotations dict
annot_manager : AnnotationManager
An annotation manager to get name/db reference mappings for each ot the
annotation types.
Returns
-------
bc : BioContext
An INDRA BioContext object | [
"Return",
"a",
"BioContext",
"object",
"extracted",
"from",
"the",
"annotations",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/bel/processor.py#L492-L549 |
19,151 | sorgerlab/indra | indra/util/plot_formatting.py | format_axis | def format_axis(ax, label_padding=2, tick_padding=0, yticks_position='left'):
"""Set standardized axis formatting for figure."""
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position(yticks_position)
ax.yaxis.set_tick_params(which='both', direction='out', labelsize=fontsize,
pad=tick_padding, length=2, width=0.5)
ax.xaxis.set_tick_params(which='both', direction='out', labelsize=fontsize,
pad=tick_padding, length=2, width=0.5)
ax.xaxis.labelpad = label_padding
ax.yaxis.labelpad = label_padding
ax.xaxis.label.set_size(fontsize)
ax.yaxis.label.set_size(fontsize) | python | def format_axis(ax, label_padding=2, tick_padding=0, yticks_position='left'):
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position(yticks_position)
ax.yaxis.set_tick_params(which='both', direction='out', labelsize=fontsize,
pad=tick_padding, length=2, width=0.5)
ax.xaxis.set_tick_params(which='both', direction='out', labelsize=fontsize,
pad=tick_padding, length=2, width=0.5)
ax.xaxis.labelpad = label_padding
ax.yaxis.labelpad = label_padding
ax.xaxis.label.set_size(fontsize)
ax.yaxis.label.set_size(fontsize) | [
"def",
"format_axis",
"(",
"ax",
",",
"label_padding",
"=",
"2",
",",
"tick_padding",
"=",
"0",
",",
"yticks_position",
"=",
"'left'",
")",
":",
"ax",
".",
"xaxis",
".",
"set_ticks_position",
"(",
"'bottom'",
")",
"ax",
".",
"yaxis",
".",
"set_ticks_positi... | Set standardized axis formatting for figure. | [
"Set",
"standardized",
"axis",
"formatting",
"for",
"figure",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/util/plot_formatting.py#L17-L28 |
19,152 | sorgerlab/indra | indra/assemblers/html/assembler.py | HtmlAssembler.make_model | def make_model(self):
"""Return the assembled HTML content as a string.
Returns
-------
str
The assembled HTML as a string.
"""
stmts_formatted = []
stmt_rows = group_and_sort_statements(self.statements,
self.ev_totals if self.ev_totals else None)
for key, verb, stmts in stmt_rows:
# This will now be ordered by prevalence and entity pairs.
stmt_info_list = []
for stmt in stmts:
stmt_hash = stmt.get_hash(shallow=True)
ev_list = self._format_evidence_text(stmt)
english = self._format_stmt_text(stmt)
if self.ev_totals:
total_evidence = self.ev_totals.get(int(stmt_hash), '?')
if total_evidence == '?':
logger.warning('The hash %s was not found in the '
'evidence totals dict.' % stmt_hash)
evidence_count_str = '%s / %s' % (len(ev_list), total_evidence)
else:
evidence_count_str = str(len(ev_list))
stmt_info_list.append({
'hash': stmt_hash,
'english': english,
'evidence': ev_list,
'evidence_count': evidence_count_str})
short_name = make_string_from_sort_key(key, verb)
short_name_key = str(uuid.uuid4())
stmts_formatted.append((short_name, short_name_key, stmt_info_list))
metadata = {k.replace('_', ' ').title(): v
for k, v in self.metadata.items()}
if self.db_rest_url and not self.db_rest_url.endswith('statements'):
db_rest_url = self.db_rest_url + '/statements'
else:
db_rest_url = '.'
self.model = template.render(stmt_data=stmts_formatted,
metadata=metadata, title=self.title,
db_rest_url=db_rest_url)
return self.model | python | def make_model(self):
stmts_formatted = []
stmt_rows = group_and_sort_statements(self.statements,
self.ev_totals if self.ev_totals else None)
for key, verb, stmts in stmt_rows:
# This will now be ordered by prevalence and entity pairs.
stmt_info_list = []
for stmt in stmts:
stmt_hash = stmt.get_hash(shallow=True)
ev_list = self._format_evidence_text(stmt)
english = self._format_stmt_text(stmt)
if self.ev_totals:
total_evidence = self.ev_totals.get(int(stmt_hash), '?')
if total_evidence == '?':
logger.warning('The hash %s was not found in the '
'evidence totals dict.' % stmt_hash)
evidence_count_str = '%s / %s' % (len(ev_list), total_evidence)
else:
evidence_count_str = str(len(ev_list))
stmt_info_list.append({
'hash': stmt_hash,
'english': english,
'evidence': ev_list,
'evidence_count': evidence_count_str})
short_name = make_string_from_sort_key(key, verb)
short_name_key = str(uuid.uuid4())
stmts_formatted.append((short_name, short_name_key, stmt_info_list))
metadata = {k.replace('_', ' ').title(): v
for k, v in self.metadata.items()}
if self.db_rest_url and not self.db_rest_url.endswith('statements'):
db_rest_url = self.db_rest_url + '/statements'
else:
db_rest_url = '.'
self.model = template.render(stmt_data=stmts_formatted,
metadata=metadata, title=self.title,
db_rest_url=db_rest_url)
return self.model | [
"def",
"make_model",
"(",
"self",
")",
":",
"stmts_formatted",
"=",
"[",
"]",
"stmt_rows",
"=",
"group_and_sort_statements",
"(",
"self",
".",
"statements",
",",
"self",
".",
"ev_totals",
"if",
"self",
".",
"ev_totals",
"else",
"None",
")",
"for",
"key",
"... | Return the assembled HTML content as a string.
Returns
-------
str
The assembled HTML as a string. | [
"Return",
"the",
"assembled",
"HTML",
"content",
"as",
"a",
"string",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/html/assembler.py#L99-L142 |
19,153 | sorgerlab/indra | indra/assemblers/html/assembler.py | HtmlAssembler.append_warning | def append_warning(self, msg):
"""Append a warning message to the model to expose issues."""
assert self.model is not None, "You must already have run make_model!"
addendum = ('\t<span style="color:red;">(CAUTION: %s occurred when '
'creating this page.)</span>' % msg)
self.model = self.model.replace(self.title, self.title + addendum)
return self.model | python | def append_warning(self, msg):
assert self.model is not None, "You must already have run make_model!"
addendum = ('\t<span style="color:red;">(CAUTION: %s occurred when '
'creating this page.)</span>' % msg)
self.model = self.model.replace(self.title, self.title + addendum)
return self.model | [
"def",
"append_warning",
"(",
"self",
",",
"msg",
")",
":",
"assert",
"self",
".",
"model",
"is",
"not",
"None",
",",
"\"You must already have run make_model!\"",
"addendum",
"=",
"(",
"'\\t<span style=\"color:red;\">(CAUTION: %s occurred when '",
"'creating this page.)</sp... | Append a warning message to the model to expose issues. | [
"Append",
"a",
"warning",
"message",
"to",
"the",
"model",
"to",
"expose",
"issues",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/html/assembler.py#L144-L150 |
19,154 | sorgerlab/indra | indra/assemblers/html/assembler.py | HtmlAssembler.save_model | def save_model(self, fname):
"""Save the assembled HTML into a file.
Parameters
----------
fname : str
The path to the file to save the HTML into.
"""
if self.model is None:
self.make_model()
with open(fname, 'wb') as fh:
fh.write(self.model.encode('utf-8')) | python | def save_model(self, fname):
if self.model is None:
self.make_model()
with open(fname, 'wb') as fh:
fh.write(self.model.encode('utf-8')) | [
"def",
"save_model",
"(",
"self",
",",
"fname",
")",
":",
"if",
"self",
".",
"model",
"is",
"None",
":",
"self",
".",
"make_model",
"(",
")",
"with",
"open",
"(",
"fname",
",",
"'wb'",
")",
"as",
"fh",
":",
"fh",
".",
"write",
"(",
"self",
".",
... | Save the assembled HTML into a file.
Parameters
----------
fname : str
The path to the file to save the HTML into. | [
"Save",
"the",
"assembled",
"HTML",
"into",
"a",
"file",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/html/assembler.py#L152-L164 |
19,155 | sorgerlab/indra | indra/assemblers/html/assembler.py | HtmlAssembler._format_evidence_text | def _format_evidence_text(stmt):
"""Returns evidence metadata with highlighted evidence text.
Parameters
----------
stmt : indra.Statement
The Statement with Evidence to be formatted.
Returns
-------
list of dicts
List of dictionaries corresponding to each Evidence object in the
Statement's evidence list. Each dictionary has keys 'source_api',
'pmid' and 'text', drawn from the corresponding fields in the
Evidence objects. The text entry of the dict includes
`<span>` tags identifying the agents referenced by the Statement.
"""
def get_role(ag_ix):
if isinstance(stmt, Complex) or \
isinstance(stmt, SelfModification) or \
isinstance(stmt, ActiveForm) or isinstance(stmt, Conversion) or\
isinstance(stmt, Translocation):
return 'other'
else:
assert len(stmt.agent_list()) == 2, (len(stmt.agent_list()),
type(stmt))
return 'subject' if ag_ix == 0 else 'object'
ev_list = []
for ix, ev in enumerate(stmt.evidence):
# Expand the source api to include the sub-database
if ev.source_api == 'biopax' and \
'source_sub_id' in ev.annotations and \
ev.annotations['source_sub_id']:
source_api = '%s:%s' % (ev.source_api,
ev.annotations['source_sub_id'])
else:
source_api = ev.source_api
# Prepare the evidence text
if ev.text is None:
format_text = None
else:
indices = []
for ix, ag in enumerate(stmt.agent_list()):
if ag is None:
continue
# If the statement has been preassembled, it will have
# this entry in annotations
try:
ag_text = ev.annotations['agents']['raw_text'][ix]
if ag_text is None:
raise KeyError
# Otherwise we try to get the agent text from db_refs
except KeyError:
ag_text = ag.db_refs.get('TEXT')
if ag_text is None:
continue
role = get_role(ix)
# Get the tag with the correct badge
tag_start = '<span class="badge badge-%s">' % role
tag_close = '</span>'
# Build up a set of indices
indices += [(m.start(), m.start() + len(ag_text),
ag_text, tag_start, tag_close)
for m in re.finditer(re.escape(ag_text),
ev.text)]
format_text = tag_text(ev.text, indices)
ev_list.append({'source_api': source_api,
'pmid': ev.pmid,
'text_refs': ev.text_refs,
'text': format_text,
'source_hash': ev.source_hash })
return ev_list | python | def _format_evidence_text(stmt):
def get_role(ag_ix):
if isinstance(stmt, Complex) or \
isinstance(stmt, SelfModification) or \
isinstance(stmt, ActiveForm) or isinstance(stmt, Conversion) or\
isinstance(stmt, Translocation):
return 'other'
else:
assert len(stmt.agent_list()) == 2, (len(stmt.agent_list()),
type(stmt))
return 'subject' if ag_ix == 0 else 'object'
ev_list = []
for ix, ev in enumerate(stmt.evidence):
# Expand the source api to include the sub-database
if ev.source_api == 'biopax' and \
'source_sub_id' in ev.annotations and \
ev.annotations['source_sub_id']:
source_api = '%s:%s' % (ev.source_api,
ev.annotations['source_sub_id'])
else:
source_api = ev.source_api
# Prepare the evidence text
if ev.text is None:
format_text = None
else:
indices = []
for ix, ag in enumerate(stmt.agent_list()):
if ag is None:
continue
# If the statement has been preassembled, it will have
# this entry in annotations
try:
ag_text = ev.annotations['agents']['raw_text'][ix]
if ag_text is None:
raise KeyError
# Otherwise we try to get the agent text from db_refs
except KeyError:
ag_text = ag.db_refs.get('TEXT')
if ag_text is None:
continue
role = get_role(ix)
# Get the tag with the correct badge
tag_start = '<span class="badge badge-%s">' % role
tag_close = '</span>'
# Build up a set of indices
indices += [(m.start(), m.start() + len(ag_text),
ag_text, tag_start, tag_close)
for m in re.finditer(re.escape(ag_text),
ev.text)]
format_text = tag_text(ev.text, indices)
ev_list.append({'source_api': source_api,
'pmid': ev.pmid,
'text_refs': ev.text_refs,
'text': format_text,
'source_hash': ev.source_hash })
return ev_list | [
"def",
"_format_evidence_text",
"(",
"stmt",
")",
":",
"def",
"get_role",
"(",
"ag_ix",
")",
":",
"if",
"isinstance",
"(",
"stmt",
",",
"Complex",
")",
"or",
"isinstance",
"(",
"stmt",
",",
"SelfModification",
")",
"or",
"isinstance",
"(",
"stmt",
",",
"... | Returns evidence metadata with highlighted evidence text.
Parameters
----------
stmt : indra.Statement
The Statement with Evidence to be formatted.
Returns
-------
list of dicts
List of dictionaries corresponding to each Evidence object in the
Statement's evidence list. Each dictionary has keys 'source_api',
'pmid' and 'text', drawn from the corresponding fields in the
Evidence objects. The text entry of the dict includes
`<span>` tags identifying the agents referenced by the Statement. | [
"Returns",
"evidence",
"metadata",
"with",
"highlighted",
"evidence",
"text",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/html/assembler.py#L167-L241 |
19,156 | sorgerlab/indra | indra/sources/reach/api.py | process_pmc | def process_pmc(pmc_id, offline=False, output_fname=default_output_fname):
"""Return a ReachProcessor by processing a paper with a given PMC id.
Uses the PMC client to obtain the full text. If it's not available,
None is returned.
Parameters
----------
pmc_id : str
The ID of a PubmedCentral article. The string may start with PMC but
passing just the ID also works.
Examples: 3717945, PMC3717945
https://www.ncbi.nlm.nih.gov/pmc/
offline : Optional[bool]
If set to True, the REACH system is ran offline. Otherwise (by default)
the web service is called. Default: False
Returns
-------
rp : ReachProcessor
A ReachProcessor containing the extracted INDRA Statements
in rp.statements.
"""
xml_str = pmc_client.get_xml(pmc_id)
if xml_str is None:
return None
fname = pmc_id + '.nxml'
with open(fname, 'wb') as fh:
fh.write(xml_str.encode('utf-8'))
ids = id_lookup(pmc_id, 'pmcid')
pmid = ids.get('pmid')
rp = process_nxml_file(fname, citation=pmid, offline=offline,
output_fname=output_fname)
return rp | python | def process_pmc(pmc_id, offline=False, output_fname=default_output_fname):
xml_str = pmc_client.get_xml(pmc_id)
if xml_str is None:
return None
fname = pmc_id + '.nxml'
with open(fname, 'wb') as fh:
fh.write(xml_str.encode('utf-8'))
ids = id_lookup(pmc_id, 'pmcid')
pmid = ids.get('pmid')
rp = process_nxml_file(fname, citation=pmid, offline=offline,
output_fname=output_fname)
return rp | [
"def",
"process_pmc",
"(",
"pmc_id",
",",
"offline",
"=",
"False",
",",
"output_fname",
"=",
"default_output_fname",
")",
":",
"xml_str",
"=",
"pmc_client",
".",
"get_xml",
"(",
"pmc_id",
")",
"if",
"xml_str",
"is",
"None",
":",
"return",
"None",
"fname",
... | Return a ReachProcessor by processing a paper with a given PMC id.
Uses the PMC client to obtain the full text. If it's not available,
None is returned.
Parameters
----------
pmc_id : str
The ID of a PubmedCentral article. The string may start with PMC but
passing just the ID also works.
Examples: 3717945, PMC3717945
https://www.ncbi.nlm.nih.gov/pmc/
offline : Optional[bool]
If set to True, the REACH system is ran offline. Otherwise (by default)
the web service is called. Default: False
Returns
-------
rp : ReachProcessor
A ReachProcessor containing the extracted INDRA Statements
in rp.statements. | [
"Return",
"a",
"ReachProcessor",
"by",
"processing",
"a",
"paper",
"with",
"a",
"given",
"PMC",
"id",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/reach/api.py#L41-L74 |
19,157 | sorgerlab/indra | indra/sources/reach/api.py | process_pubmed_abstract | def process_pubmed_abstract(pubmed_id, offline=False,
output_fname=default_output_fname, **kwargs):
"""Return a ReachProcessor by processing an abstract with a given Pubmed id.
Uses the Pubmed client to get the abstract. If that fails, None is
returned.
Parameters
----------
pubmed_id : str
The ID of a Pubmed article. The string may start with PMID but
passing just the ID also works.
Examples: 27168024, PMID27168024
https://www.ncbi.nlm.nih.gov/pubmed/
offline : Optional[bool]
If set to True, the REACH system is ran offline. Otherwise (by default)
the web service is called. Default: False
output_fname : Optional[str]
The file to output the REACH JSON output to.
Defaults to reach_output.json in current working directory.
**kwargs : keyword arguments
All other keyword arguments are passed directly to `process_text`.
Returns
-------
rp : ReachProcessor
A ReachProcessor containing the extracted INDRA Statements
in rp.statements.
"""
abs_txt = pubmed_client.get_abstract(pubmed_id)
if abs_txt is None:
return None
rp = process_text(abs_txt, citation=pubmed_id, offline=offline,
output_fname=output_fname, **kwargs)
if rp and rp.statements:
for st in rp.statements:
for ev in st.evidence:
ev.epistemics['section_type'] = 'abstract'
return rp | python | def process_pubmed_abstract(pubmed_id, offline=False,
output_fname=default_output_fname, **kwargs):
abs_txt = pubmed_client.get_abstract(pubmed_id)
if abs_txt is None:
return None
rp = process_text(abs_txt, citation=pubmed_id, offline=offline,
output_fname=output_fname, **kwargs)
if rp and rp.statements:
for st in rp.statements:
for ev in st.evidence:
ev.epistemics['section_type'] = 'abstract'
return rp | [
"def",
"process_pubmed_abstract",
"(",
"pubmed_id",
",",
"offline",
"=",
"False",
",",
"output_fname",
"=",
"default_output_fname",
",",
"*",
"*",
"kwargs",
")",
":",
"abs_txt",
"=",
"pubmed_client",
".",
"get_abstract",
"(",
"pubmed_id",
")",
"if",
"abs_txt",
... | Return a ReachProcessor by processing an abstract with a given Pubmed id.
Uses the Pubmed client to get the abstract. If that fails, None is
returned.
Parameters
----------
pubmed_id : str
The ID of a Pubmed article. The string may start with PMID but
passing just the ID also works.
Examples: 27168024, PMID27168024
https://www.ncbi.nlm.nih.gov/pubmed/
offline : Optional[bool]
If set to True, the REACH system is ran offline. Otherwise (by default)
the web service is called. Default: False
output_fname : Optional[str]
The file to output the REACH JSON output to.
Defaults to reach_output.json in current working directory.
**kwargs : keyword arguments
All other keyword arguments are passed directly to `process_text`.
Returns
-------
rp : ReachProcessor
A ReachProcessor containing the extracted INDRA Statements
in rp.statements. | [
"Return",
"a",
"ReachProcessor",
"by",
"processing",
"an",
"abstract",
"with",
"a",
"given",
"Pubmed",
"id",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/reach/api.py#L77-L115 |
19,158 | sorgerlab/indra | indra/sources/reach/api.py | process_text | def process_text(text, citation=None, offline=False,
output_fname=default_output_fname, timeout=None):
"""Return a ReachProcessor by processing the given text.
Parameters
----------
text : str
The text to be processed.
citation : Optional[str]
A PubMed ID passed to be used in the evidence for the extracted INDRA
Statements. This is used when the text to be processed comes from
a publication that is not otherwise identified. Default: None
offline : Optional[bool]
If set to True, the REACH system is ran offline. Otherwise (by default)
the web service is called. Default: False
output_fname : Optional[str]
The file to output the REACH JSON output to.
Defaults to reach_output.json in current working directory.
timeout : Optional[float]
This only applies when reading online (`offline=False`). Only wait for
`timeout` seconds for the api to respond.
Returns
-------
rp : ReachProcessor
A ReachProcessor containing the extracted INDRA Statements
in rp.statements.
"""
if offline:
if not try_offline:
logger.error('Offline reading is not available.')
return None
try:
api_ruler = reach_reader.get_api_ruler()
except ReachOfflineReadingError as e:
logger.error(e)
logger.error('Cannot read offline because the REACH ApiRuler '
'could not be instantiated.')
return None
try:
result_map = api_ruler.annotateText(text, 'fries')
except JavaException as e:
logger.error('Could not process text.')
logger.error(e)
return None
# REACH version < 1.3.3
json_str = result_map.get('resultJson')
if not json_str:
# REACH version >= 1.3.3
json_str = result_map.get('result')
if not isinstance(json_str, bytes):
json_str = json_str.encode('utf-8')
else:
data = {'text': text.encode('utf-8')}
try:
res = requests.post(reach_text_url, data, timeout=timeout)
except requests.exceptions.RequestException as e:
logger.error('Could not connect to REACH service:')
logger.error(e)
return None
# TODO: we could use res.json() here to get a dict
# directly
# This is a byte string
json_str = res.content
if not isinstance(json_str, bytes):
raise TypeError('{} is {} instead of {}'.format(json_str, json_str.__class__, bytes))
with open(output_fname, 'wb') as fh:
fh.write(json_str)
return process_json_str(json_str.decode('utf-8'), citation) | python | def process_text(text, citation=None, offline=False,
output_fname=default_output_fname, timeout=None):
if offline:
if not try_offline:
logger.error('Offline reading is not available.')
return None
try:
api_ruler = reach_reader.get_api_ruler()
except ReachOfflineReadingError as e:
logger.error(e)
logger.error('Cannot read offline because the REACH ApiRuler '
'could not be instantiated.')
return None
try:
result_map = api_ruler.annotateText(text, 'fries')
except JavaException as e:
logger.error('Could not process text.')
logger.error(e)
return None
# REACH version < 1.3.3
json_str = result_map.get('resultJson')
if not json_str:
# REACH version >= 1.3.3
json_str = result_map.get('result')
if not isinstance(json_str, bytes):
json_str = json_str.encode('utf-8')
else:
data = {'text': text.encode('utf-8')}
try:
res = requests.post(reach_text_url, data, timeout=timeout)
except requests.exceptions.RequestException as e:
logger.error('Could not connect to REACH service:')
logger.error(e)
return None
# TODO: we could use res.json() here to get a dict
# directly
# This is a byte string
json_str = res.content
if not isinstance(json_str, bytes):
raise TypeError('{} is {} instead of {}'.format(json_str, json_str.__class__, bytes))
with open(output_fname, 'wb') as fh:
fh.write(json_str)
return process_json_str(json_str.decode('utf-8'), citation) | [
"def",
"process_text",
"(",
"text",
",",
"citation",
"=",
"None",
",",
"offline",
"=",
"False",
",",
"output_fname",
"=",
"default_output_fname",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"offline",
":",
"if",
"not",
"try_offline",
":",
"logger",
".",
... | Return a ReachProcessor by processing the given text.
Parameters
----------
text : str
The text to be processed.
citation : Optional[str]
A PubMed ID passed to be used in the evidence for the extracted INDRA
Statements. This is used when the text to be processed comes from
a publication that is not otherwise identified. Default: None
offline : Optional[bool]
If set to True, the REACH system is ran offline. Otherwise (by default)
the web service is called. Default: False
output_fname : Optional[str]
The file to output the REACH JSON output to.
Defaults to reach_output.json in current working directory.
timeout : Optional[float]
This only applies when reading online (`offline=False`). Only wait for
`timeout` seconds for the api to respond.
Returns
-------
rp : ReachProcessor
A ReachProcessor containing the extracted INDRA Statements
in rp.statements. | [
"Return",
"a",
"ReachProcessor",
"by",
"processing",
"the",
"given",
"text",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/reach/api.py#L118-L187 |
19,159 | sorgerlab/indra | indra/sources/reach/api.py | process_nxml_str | def process_nxml_str(nxml_str, citation=None, offline=False,
output_fname=default_output_fname):
"""Return a ReachProcessor by processing the given NXML string.
NXML is the format used by PubmedCentral for papers in the open
access subset.
Parameters
----------
nxml_str : str
The NXML string to be processed.
citation : Optional[str]
A PubMed ID passed to be used in the evidence for the extracted INDRA
Statements. Default: None
offline : Optional[bool]
If set to True, the REACH system is ran offline. Otherwise (by default)
the web service is called. Default: False
output_fname : Optional[str]
The file to output the REACH JSON output to.
Defaults to reach_output.json in current working directory.
Returns
-------
rp : ReachProcessor
A ReachProcessor containing the extracted INDRA Statements
in rp.statements.
"""
if offline:
if not try_offline:
logger.error('Offline reading is not available.')
return None
try:
api_ruler = reach_reader.get_api_ruler()
except ReachOfflineReadingError as e:
logger.error(e)
logger.error('Cannot read offline because the REACH ApiRuler '
'could not be instantiated.')
return None
try:
result_map = api_ruler.annotateNxml(nxml_str, 'fries')
except JavaException as e:
logger.error('Could not process NXML.')
logger.error(e)
return None
# REACH version < 1.3.3
json_str = result_map.get('resultJson')
if not json_str:
# REACH version >= 1.3.3
json_str = result_map.get('result')
if json_str is None:
logger.warning('No results retrieved')
return None
if isinstance(json_str, bytes):
json_str = json_str.decode('utf-8')
return process_json_str(json_str, citation)
else:
data = {'nxml': nxml_str}
try:
res = requests.post(reach_nxml_url, data)
except requests.exceptions.RequestException as e:
logger.error('Could not connect to REACH service:')
logger.error(e)
return None
if res.status_code != 200:
logger.error('Could not process NXML via REACH service.'
+ 'Status code: %d' % res.status_code)
return None
json_str = res.text
with open(output_fname, 'wb') as fh:
fh.write(json_str.encode('utf-8'))
return process_json_str(json_str, citation) | python | def process_nxml_str(nxml_str, citation=None, offline=False,
output_fname=default_output_fname):
if offline:
if not try_offline:
logger.error('Offline reading is not available.')
return None
try:
api_ruler = reach_reader.get_api_ruler()
except ReachOfflineReadingError as e:
logger.error(e)
logger.error('Cannot read offline because the REACH ApiRuler '
'could not be instantiated.')
return None
try:
result_map = api_ruler.annotateNxml(nxml_str, 'fries')
except JavaException as e:
logger.error('Could not process NXML.')
logger.error(e)
return None
# REACH version < 1.3.3
json_str = result_map.get('resultJson')
if not json_str:
# REACH version >= 1.3.3
json_str = result_map.get('result')
if json_str is None:
logger.warning('No results retrieved')
return None
if isinstance(json_str, bytes):
json_str = json_str.decode('utf-8')
return process_json_str(json_str, citation)
else:
data = {'nxml': nxml_str}
try:
res = requests.post(reach_nxml_url, data)
except requests.exceptions.RequestException as e:
logger.error('Could not connect to REACH service:')
logger.error(e)
return None
if res.status_code != 200:
logger.error('Could not process NXML via REACH service.'
+ 'Status code: %d' % res.status_code)
return None
json_str = res.text
with open(output_fname, 'wb') as fh:
fh.write(json_str.encode('utf-8'))
return process_json_str(json_str, citation) | [
"def",
"process_nxml_str",
"(",
"nxml_str",
",",
"citation",
"=",
"None",
",",
"offline",
"=",
"False",
",",
"output_fname",
"=",
"default_output_fname",
")",
":",
"if",
"offline",
":",
"if",
"not",
"try_offline",
":",
"logger",
".",
"error",
"(",
"'Offline ... | Return a ReachProcessor by processing the given NXML string.
NXML is the format used by PubmedCentral for papers in the open
access subset.
Parameters
----------
nxml_str : str
The NXML string to be processed.
citation : Optional[str]
A PubMed ID passed to be used in the evidence for the extracted INDRA
Statements. Default: None
offline : Optional[bool]
If set to True, the REACH system is ran offline. Otherwise (by default)
the web service is called. Default: False
output_fname : Optional[str]
The file to output the REACH JSON output to.
Defaults to reach_output.json in current working directory.
Returns
-------
rp : ReachProcessor
A ReachProcessor containing the extracted INDRA Statements
in rp.statements. | [
"Return",
"a",
"ReachProcessor",
"by",
"processing",
"the",
"given",
"NXML",
"string",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/reach/api.py#L190-L261 |
19,160 | sorgerlab/indra | indra/sources/reach/api.py | process_nxml_file | def process_nxml_file(file_name, citation=None, offline=False,
output_fname=default_output_fname):
"""Return a ReachProcessor by processing the given NXML file.
NXML is the format used by PubmedCentral for papers in the open
access subset.
Parameters
----------
file_name : str
The name of the NXML file to be processed.
citation : Optional[str]
A PubMed ID passed to be used in the evidence for the extracted INDRA
Statements. Default: None
offline : Optional[bool]
If set to True, the REACH system is ran offline. Otherwise (by default)
the web service is called. Default: False
output_fname : Optional[str]
The file to output the REACH JSON output to.
Defaults to reach_output.json in current working directory.
Returns
-------
rp : ReachProcessor
A ReachProcessor containing the extracted INDRA Statements
in rp.statements.
"""
with open(file_name, 'rb') as f:
nxml_str = f.read().decode('utf-8')
return process_nxml_str(nxml_str, citation, False, output_fname) | python | def process_nxml_file(file_name, citation=None, offline=False,
output_fname=default_output_fname):
with open(file_name, 'rb') as f:
nxml_str = f.read().decode('utf-8')
return process_nxml_str(nxml_str, citation, False, output_fname) | [
"def",
"process_nxml_file",
"(",
"file_name",
",",
"citation",
"=",
"None",
",",
"offline",
"=",
"False",
",",
"output_fname",
"=",
"default_output_fname",
")",
":",
"with",
"open",
"(",
"file_name",
",",
"'rb'",
")",
"as",
"f",
":",
"nxml_str",
"=",
"f",
... | Return a ReachProcessor by processing the given NXML file.
NXML is the format used by PubmedCentral for papers in the open
access subset.
Parameters
----------
file_name : str
The name of the NXML file to be processed.
citation : Optional[str]
A PubMed ID passed to be used in the evidence for the extracted INDRA
Statements. Default: None
offline : Optional[bool]
If set to True, the REACH system is ran offline. Otherwise (by default)
the web service is called. Default: False
output_fname : Optional[str]
The file to output the REACH JSON output to.
Defaults to reach_output.json in current working directory.
Returns
-------
rp : ReachProcessor
A ReachProcessor containing the extracted INDRA Statements
in rp.statements. | [
"Return",
"a",
"ReachProcessor",
"by",
"processing",
"the",
"given",
"NXML",
"file",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/reach/api.py#L264-L293 |
19,161 | sorgerlab/indra | indra/sources/reach/api.py | process_json_file | def process_json_file(file_name, citation=None):
"""Return a ReachProcessor by processing the given REACH json file.
The output from the REACH parser is in this json format. This function is
useful if the output is saved as a file and needs to be processed.
For more information on the format, see: https://github.com/clulab/reach
Parameters
----------
file_name : str
The name of the json file to be processed.
citation : Optional[str]
A PubMed ID passed to be used in the evidence for the extracted INDRA
Statements. Default: None
Returns
-------
rp : ReachProcessor
A ReachProcessor containing the extracted INDRA Statements
in rp.statements.
"""
try:
with open(file_name, 'rb') as fh:
json_str = fh.read().decode('utf-8')
return process_json_str(json_str, citation)
except IOError:
logger.error('Could not read file %s.' % file_name) | python | def process_json_file(file_name, citation=None):
try:
with open(file_name, 'rb') as fh:
json_str = fh.read().decode('utf-8')
return process_json_str(json_str, citation)
except IOError:
logger.error('Could not read file %s.' % file_name) | [
"def",
"process_json_file",
"(",
"file_name",
",",
"citation",
"=",
"None",
")",
":",
"try",
":",
"with",
"open",
"(",
"file_name",
",",
"'rb'",
")",
"as",
"fh",
":",
"json_str",
"=",
"fh",
".",
"read",
"(",
")",
".",
"decode",
"(",
"'utf-8'",
")",
... | Return a ReachProcessor by processing the given REACH json file.
The output from the REACH parser is in this json format. This function is
useful if the output is saved as a file and needs to be processed.
For more information on the format, see: https://github.com/clulab/reach
Parameters
----------
file_name : str
The name of the json file to be processed.
citation : Optional[str]
A PubMed ID passed to be used in the evidence for the extracted INDRA
Statements. Default: None
Returns
-------
rp : ReachProcessor
A ReachProcessor containing the extracted INDRA Statements
in rp.statements. | [
"Return",
"a",
"ReachProcessor",
"by",
"processing",
"the",
"given",
"REACH",
"json",
"file",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/reach/api.py#L296-L322 |
19,162 | sorgerlab/indra | indra/sources/reach/api.py | process_json_str | def process_json_str(json_str, citation=None):
"""Return a ReachProcessor by processing the given REACH json string.
The output from the REACH parser is in this json format.
For more information on the format, see: https://github.com/clulab/reach
Parameters
----------
json_str : str
The json string to be processed.
citation : Optional[str]
A PubMed ID passed to be used in the evidence for the extracted INDRA
Statements. Default: None
Returns
-------
rp : ReachProcessor
A ReachProcessor containing the extracted INDRA Statements
in rp.statements.
"""
if not isinstance(json_str, basestring):
raise TypeError('{} is {} instead of {}'.format(json_str,
json_str.__class__,
basestring))
json_str = json_str.replace('frame-id', 'frame_id')
json_str = json_str.replace('argument-label', 'argument_label')
json_str = json_str.replace('object-meta', 'object_meta')
json_str = json_str.replace('doc-id', 'doc_id')
json_str = json_str.replace('is-hypothesis', 'is_hypothesis')
json_str = json_str.replace('is-negated', 'is_negated')
json_str = json_str.replace('is-direct', 'is_direct')
json_str = json_str.replace('found-by', 'found_by')
try:
json_dict = json.loads(json_str)
except ValueError:
logger.error('Could not decode JSON string.')
return None
rp = ReachProcessor(json_dict, citation)
rp.get_modifications()
rp.get_complexes()
rp.get_activation()
rp.get_translocation()
rp.get_regulate_amounts()
return rp | python | def process_json_str(json_str, citation=None):
if not isinstance(json_str, basestring):
raise TypeError('{} is {} instead of {}'.format(json_str,
json_str.__class__,
basestring))
json_str = json_str.replace('frame-id', 'frame_id')
json_str = json_str.replace('argument-label', 'argument_label')
json_str = json_str.replace('object-meta', 'object_meta')
json_str = json_str.replace('doc-id', 'doc_id')
json_str = json_str.replace('is-hypothesis', 'is_hypothesis')
json_str = json_str.replace('is-negated', 'is_negated')
json_str = json_str.replace('is-direct', 'is_direct')
json_str = json_str.replace('found-by', 'found_by')
try:
json_dict = json.loads(json_str)
except ValueError:
logger.error('Could not decode JSON string.')
return None
rp = ReachProcessor(json_dict, citation)
rp.get_modifications()
rp.get_complexes()
rp.get_activation()
rp.get_translocation()
rp.get_regulate_amounts()
return rp | [
"def",
"process_json_str",
"(",
"json_str",
",",
"citation",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"json_str",
",",
"basestring",
")",
":",
"raise",
"TypeError",
"(",
"'{} is {} instead of {}'",
".",
"format",
"(",
"json_str",
",",
"json_str",... | Return a ReachProcessor by processing the given REACH json string.
The output from the REACH parser is in this json format.
For more information on the format, see: https://github.com/clulab/reach
Parameters
----------
json_str : str
The json string to be processed.
citation : Optional[str]
A PubMed ID passed to be used in the evidence for the extracted INDRA
Statements. Default: None
Returns
-------
rp : ReachProcessor
A ReachProcessor containing the extracted INDRA Statements
in rp.statements. | [
"Return",
"a",
"ReachProcessor",
"by",
"processing",
"the",
"given",
"REACH",
"json",
"string",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/reach/api.py#L325-L369 |
19,163 | sorgerlab/indra | indra/tools/reading/wait_for_complete.py | make_parser | def make_parser():
"""Generate the parser for this script."""
parser = ArgumentParser(
'wait_for_complete.py',
usage='%(prog)s [-h] queue_name [options]',
description=('Wait for a set of batch jobs to complete, and monitor '
'them as they run.'),
epilog=('Jobs can also be monitored, terminated, and otherwise '
'managed on the AWS website. However this tool will also tag '
'the instances, and should be run whenever a job is submitted '
'to AWS.')
)
parser.add_argument(
dest='queue_name',
help=('The name of the queue to watch and wait for completion. If no '
'jobs are specified, this will wait until all jobs in the queue '
'are completed (either SUCCEEDED or FAILED).')
)
parser.add_argument(
'--watch', '-w',
dest='job_list',
metavar='JOB_ID',
nargs='+',
help=('Specify particular jobs using their job ids, as reported by '
'the submit command. Many ids may be specified.')
)
parser.add_argument(
'--prefix', '-p',
dest='job_name_prefix',
help='Specify a prefix for the name of the jobs to watch and wait for.'
)
parser.add_argument(
'--interval', '-i',
dest='poll_interval',
default=10,
type=int,
help=('The time interval to wait between job status checks, in '
'seconds (default: %(default)d seconds).')
)
parser.add_argument(
'--timeout', '-T',
metavar='TIMEOUT',
type=int,
help=('If the logs are not updated for %(metavar)s seconds, '
'print a warning. If `--kill_on_log_timeout` flag is set, then '
'the offending jobs will be automatically terminated.')
)
parser.add_argument(
'--kill_on_timeout', '-K',
action='store_true',
help='If a log times out, terminate the offending job.'
)
parser.add_argument(
'--stash_log_method', '-l',
choices=['s3', 'local'],
metavar='METHOD',
help=('Select a method from: [%(choices)s] to store the job logs. '
'If no method is specified, the logs will not be '
'loaded off of AWS. If \'s3\' is specified, then '
'`job_name_prefix` must also be given, as this will indicate '
'where on s3 to store the logs.')
)
return parser | python | def make_parser():
parser = ArgumentParser(
'wait_for_complete.py',
usage='%(prog)s [-h] queue_name [options]',
description=('Wait for a set of batch jobs to complete, and monitor '
'them as they run.'),
epilog=('Jobs can also be monitored, terminated, and otherwise '
'managed on the AWS website. However this tool will also tag '
'the instances, and should be run whenever a job is submitted '
'to AWS.')
)
parser.add_argument(
dest='queue_name',
help=('The name of the queue to watch and wait for completion. If no '
'jobs are specified, this will wait until all jobs in the queue '
'are completed (either SUCCEEDED or FAILED).')
)
parser.add_argument(
'--watch', '-w',
dest='job_list',
metavar='JOB_ID',
nargs='+',
help=('Specify particular jobs using their job ids, as reported by '
'the submit command. Many ids may be specified.')
)
parser.add_argument(
'--prefix', '-p',
dest='job_name_prefix',
help='Specify a prefix for the name of the jobs to watch and wait for.'
)
parser.add_argument(
'--interval', '-i',
dest='poll_interval',
default=10,
type=int,
help=('The time interval to wait between job status checks, in '
'seconds (default: %(default)d seconds).')
)
parser.add_argument(
'--timeout', '-T',
metavar='TIMEOUT',
type=int,
help=('If the logs are not updated for %(metavar)s seconds, '
'print a warning. If `--kill_on_log_timeout` flag is set, then '
'the offending jobs will be automatically terminated.')
)
parser.add_argument(
'--kill_on_timeout', '-K',
action='store_true',
help='If a log times out, terminate the offending job.'
)
parser.add_argument(
'--stash_log_method', '-l',
choices=['s3', 'local'],
metavar='METHOD',
help=('Select a method from: [%(choices)s] to store the job logs. '
'If no method is specified, the logs will not be '
'loaded off of AWS. If \'s3\' is specified, then '
'`job_name_prefix` must also be given, as this will indicate '
'where on s3 to store the logs.')
)
return parser | [
"def",
"make_parser",
"(",
")",
":",
"parser",
"=",
"ArgumentParser",
"(",
"'wait_for_complete.py'",
",",
"usage",
"=",
"'%(prog)s [-h] queue_name [options]'",
",",
"description",
"=",
"(",
"'Wait for a set of batch jobs to complete, and monitor '",
"'them as they run.'",
")"... | Generate the parser for this script. | [
"Generate",
"the",
"parser",
"for",
"this",
"script",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/reading/wait_for_complete.py#L4-L66 |
19,164 | sorgerlab/indra | indra/literature/__init__.py | id_lookup | def id_lookup(paper_id, idtype):
"""Take an ID of type PMID, PMCID, or DOI and lookup the other IDs.
If the DOI is not found in Pubmed, try to obtain the DOI by doing a
reverse-lookup of the DOI in CrossRef using article metadata.
Parameters
----------
paper_id : str
ID of the article.
idtype : str
Type of the ID: 'pmid', 'pmcid', or 'doi
Returns
-------
ids : dict
A dictionary with the following keys: pmid, pmcid and doi.
"""
if idtype not in ('pmid', 'pmcid', 'doi'):
raise ValueError("Invalid idtype %s; must be 'pmid', 'pmcid', "
"or 'doi'." % idtype)
ids = {'doi': None, 'pmid': None, 'pmcid': None}
pmc_id_results = pmc_client.id_lookup(paper_id, idtype)
# Start with the results of the PMC lookup and then override with the
# provided ID
ids['pmid'] = pmc_id_results.get('pmid')
ids['pmcid'] = pmc_id_results.get('pmcid')
ids['doi'] = pmc_id_results.get('doi')
ids[idtype] = paper_id
# If we gave a DOI, then our work is done after looking for PMID and PMCID
if idtype == 'doi':
return ids
# If we gave a PMID or PMCID, we need to check to see if we got a DOI.
# If we got a DOI back, we're done.
elif ids.get('doi'):
return ids
# If we get here, then we've given PMID or PMCID and don't have a DOI yet.
# If we gave a PMCID and have neither a PMID nor a DOI, then we'll run
# into problems later on when we try to the reverse lookup using CrossRef.
# So we bail here and return what we have (PMCID only) with a warning.
if ids.get('pmcid') and ids.get('doi') is None and ids.get('pmid') is None:
logger.warning('%s: PMCID without PMID or DOI' % ids.get('pmcid'))
return ids
# To clarify the state of things at this point:
assert ids.get('pmid') is not None
assert ids.get('doi') is None
# As a last result, we try to get the DOI from CrossRef (which internally
# tries to get the DOI from Pubmed in the process of collecting the
# necessary metadata for the lookup):
ids['doi'] = crossref_client.doi_query(ids['pmid'])
# It may still be None, but at this point there's nothing we can do...
return ids | python | def id_lookup(paper_id, idtype):
if idtype not in ('pmid', 'pmcid', 'doi'):
raise ValueError("Invalid idtype %s; must be 'pmid', 'pmcid', "
"or 'doi'." % idtype)
ids = {'doi': None, 'pmid': None, 'pmcid': None}
pmc_id_results = pmc_client.id_lookup(paper_id, idtype)
# Start with the results of the PMC lookup and then override with the
# provided ID
ids['pmid'] = pmc_id_results.get('pmid')
ids['pmcid'] = pmc_id_results.get('pmcid')
ids['doi'] = pmc_id_results.get('doi')
ids[idtype] = paper_id
# If we gave a DOI, then our work is done after looking for PMID and PMCID
if idtype == 'doi':
return ids
# If we gave a PMID or PMCID, we need to check to see if we got a DOI.
# If we got a DOI back, we're done.
elif ids.get('doi'):
return ids
# If we get here, then we've given PMID or PMCID and don't have a DOI yet.
# If we gave a PMCID and have neither a PMID nor a DOI, then we'll run
# into problems later on when we try to the reverse lookup using CrossRef.
# So we bail here and return what we have (PMCID only) with a warning.
if ids.get('pmcid') and ids.get('doi') is None and ids.get('pmid') is None:
logger.warning('%s: PMCID without PMID or DOI' % ids.get('pmcid'))
return ids
# To clarify the state of things at this point:
assert ids.get('pmid') is not None
assert ids.get('doi') is None
# As a last result, we try to get the DOI from CrossRef (which internally
# tries to get the DOI from Pubmed in the process of collecting the
# necessary metadata for the lookup):
ids['doi'] = crossref_client.doi_query(ids['pmid'])
# It may still be None, but at this point there's nothing we can do...
return ids | [
"def",
"id_lookup",
"(",
"paper_id",
",",
"idtype",
")",
":",
"if",
"idtype",
"not",
"in",
"(",
"'pmid'",
",",
"'pmcid'",
",",
"'doi'",
")",
":",
"raise",
"ValueError",
"(",
"\"Invalid idtype %s; must be 'pmid', 'pmcid', \"",
"\"or 'doi'.\"",
"%",
"idtype",
")",... | Take an ID of type PMID, PMCID, or DOI and lookup the other IDs.
If the DOI is not found in Pubmed, try to obtain the DOI by doing a
reverse-lookup of the DOI in CrossRef using article metadata.
Parameters
----------
paper_id : str
ID of the article.
idtype : str
Type of the ID: 'pmid', 'pmcid', or 'doi
Returns
-------
ids : dict
A dictionary with the following keys: pmid, pmcid and doi. | [
"Take",
"an",
"ID",
"of",
"type",
"PMID",
"PMCID",
"or",
"DOI",
"and",
"lookup",
"the",
"other",
"IDs",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/literature/__init__.py#L19-L71 |
19,165 | sorgerlab/indra | indra/literature/__init__.py | get_full_text | def get_full_text(paper_id, idtype, preferred_content_type='text/xml'):
"""Return the content and the content type of an article.
This function retreives the content of an article by its PubMed ID,
PubMed Central ID, or DOI. It prioritizes full text content when available
and returns an abstract from PubMed as a fallback.
Parameters
----------
paper_id : string
ID of the article.
idtype : 'pmid', 'pmcid', or 'doi
Type of the ID.
preferred_content_type : Optional[st]r
Preference for full-text format, if available. Can be one of
'text/xml', 'text/plain', 'application/pdf'. Default: 'text/xml'
Returns
-------
content : str
The content of the article.
content_type : str
The content type of the article
"""
if preferred_content_type not in \
('text/xml', 'text/plain', 'application/pdf'):
raise ValueError("preferred_content_type must be one of 'text/xml', "
"'text/plain', or 'application/pdf'.")
ids = id_lookup(paper_id, idtype)
pmcid = ids.get('pmcid')
pmid = ids.get('pmid')
doi = ids.get('doi')
# First try to find paper via PMC
if pmcid:
nxml = pmc_client.get_xml(pmcid)
if nxml:
return nxml, 'pmc_oa_xml'
# If we got here, it means we didn't find the full text in PMC, so we'll
# need either the DOI (for lookup in CrossRef) and/or the PMID (so we
# can fall back on the abstract. If by some strange turn we have neither,
# give up now.
if not doi and not pmid:
return (None, None)
# If it does not have PMC NXML then we attempt to obtain the full-text
# through the CrossRef Click-through API
if doi:
# Get publisher
publisher = crossref_client.get_publisher(doi)
# First check for whether this is Elsevier--if so, use the Elsevier
# client directly, because the Clickthrough API key seems unreliable.
# Return full XML.
if publisher == 'Elsevier BV':
logger.info('Elsevier: %s' % pmid)
#article = elsevier_client.get_article(doi, output='txt')
try:
article_xml = elsevier_client.download_article(doi)
except Exception as e:
logger.error("Error downloading Elsevier article: %s" % e)
article_xml = None
if article_xml is not None:
return (article_xml, 'elsevier_xml')
# FIXME FIXME FIXME
# Because we don't yet have a way to process non-Elsevier content
# obtained from CrossRef, which includes both XML of unknown format
# and PDFs, we just comment this section out for now
"""
# Check if there are any full text links
links = crossref_client.get_fulltext_links(doi)
if links:
headers = {}
# Set the Cross Ref Clickthrough API key in the header, if we've
# got one
cr_api_key = crossref_client.get_api_key()
if cr_api_key is not None:
headers['CR-Clickthrough-Client-Token'] = cr_api_key
# Utility function to get particular links by content-type
def lookup_content_type(link_list, content_type):
content_list = [l.get('URL') for l in link_list
if l.get('content-type') == content_type]
return None if not content_list else content_list[0]
# First check for what the user asked for
if lookup_content_type(links, preferred_content_type):
req = requests.get(lookup_content_type(links,
preferred_content_type),
headers=headers)
if req.status_code == 200:
req_content_type = req.headers['Content-Type']
return req.text, req_content_type
elif req.status_code == 400:
logger.warning('Full text query returned 400 (Bad Request): '
'Perhaps missing CrossRef Clickthrough API '
'key?')
return (None, None)
# Check for XML first
if lookup_content_type(links, 'text/xml'):
req = requests.get(lookup_content_type(links, 'text/xml'),
headers=headers)
if req.status_code == 200:
req_content_type = req.headers['Content-Type']
return req.text, req_content_type
elif req.status_code == 400:
logger.warning('Full text query returned 400 (Bad Request):'
'Perhaps missing CrossRef Clickthrough API '
'key?')
return (None, None)
# Next, plain text
elif lookup_content_type(links, 'text/plain'):
req = requests.get(lookup_content_type(links, 'text/plain'),
headers=headers)
if req.status_code == 200:
req_content_type = req.headers['Content-Type']
return req.text, req_content_type
elif req.status_code == 400:
logger.warning('Full text query returned 400 (Bad Request):'
'Perhaps missing CrossRef Clickthrough API '
'key?')
return (None, None)
elif lookup_content_type(links, 'application/pdf'):
pass
# Wiley's links are often of content-type 'unspecified'.
elif lookup_content_type(links, 'unspecified'):
req = requests.get(lookup_content_type(links, 'unspecified'),
headers=headers)
if req.status_code == 200:
req_content_type = req.headers['Content-Type']
return 'foo', req_content_type
elif req.status_code == 400:
logger.warning('Full text query returned 400 (Bad Request):'
'Perhaps missing CrossRef Clickthrough API '
'key?')
return (None, None)
elif req.status_code == 401:
logger.warning('Full text query returned 401 (Unauthorized)')
return (None, None)
elif req.status_code == 403:
logger.warning('Full text query returned 403 (Forbidden)')
return (None, None)
else:
raise Exception("Unknown content type(s): %s" % links)
elif publisher == 'American Society for Biochemistry & Molecular ' \
'Biology (ASBMB)':
url = crossref_client.get_url(doi)
return get_asbmb_full_text(url)
"""
# end FIXME FIXME FIXME
# No full text links and not a publisher we support. We'll have to
# fall back to the abstract.
#elif pmid:
if pmid:
abstract = pubmed_client.get_abstract(pmid)
if abstract is None:
return (None, None)
else:
return abstract, 'abstract'
# We have a useless DOI and no PMID. Give up.
else:
return (None, None)
# We don't have a DOI but we're guaranteed to have a PMID at this point,
# so we fall back to the abstract:
else:
abstract = pubmed_client.get_abstract(pmid)
if abstract is None:
return (None, None)
else:
return abstract, 'abstract'
# We'll only get here if we've missed a combination of conditions
assert False | python | def get_full_text(paper_id, idtype, preferred_content_type='text/xml'):
if preferred_content_type not in \
('text/xml', 'text/plain', 'application/pdf'):
raise ValueError("preferred_content_type must be one of 'text/xml', "
"'text/plain', or 'application/pdf'.")
ids = id_lookup(paper_id, idtype)
pmcid = ids.get('pmcid')
pmid = ids.get('pmid')
doi = ids.get('doi')
# First try to find paper via PMC
if pmcid:
nxml = pmc_client.get_xml(pmcid)
if nxml:
return nxml, 'pmc_oa_xml'
# If we got here, it means we didn't find the full text in PMC, so we'll
# need either the DOI (for lookup in CrossRef) and/or the PMID (so we
# can fall back on the abstract. If by some strange turn we have neither,
# give up now.
if not doi and not pmid:
return (None, None)
# If it does not have PMC NXML then we attempt to obtain the full-text
# through the CrossRef Click-through API
if doi:
# Get publisher
publisher = crossref_client.get_publisher(doi)
# First check for whether this is Elsevier--if so, use the Elsevier
# client directly, because the Clickthrough API key seems unreliable.
# Return full XML.
if publisher == 'Elsevier BV':
logger.info('Elsevier: %s' % pmid)
#article = elsevier_client.get_article(doi, output='txt')
try:
article_xml = elsevier_client.download_article(doi)
except Exception as e:
logger.error("Error downloading Elsevier article: %s" % e)
article_xml = None
if article_xml is not None:
return (article_xml, 'elsevier_xml')
# FIXME FIXME FIXME
# Because we don't yet have a way to process non-Elsevier content
# obtained from CrossRef, which includes both XML of unknown format
# and PDFs, we just comment this section out for now
"""
# Check if there are any full text links
links = crossref_client.get_fulltext_links(doi)
if links:
headers = {}
# Set the Cross Ref Clickthrough API key in the header, if we've
# got one
cr_api_key = crossref_client.get_api_key()
if cr_api_key is not None:
headers['CR-Clickthrough-Client-Token'] = cr_api_key
# Utility function to get particular links by content-type
def lookup_content_type(link_list, content_type):
content_list = [l.get('URL') for l in link_list
if l.get('content-type') == content_type]
return None if not content_list else content_list[0]
# First check for what the user asked for
if lookup_content_type(links, preferred_content_type):
req = requests.get(lookup_content_type(links,
preferred_content_type),
headers=headers)
if req.status_code == 200:
req_content_type = req.headers['Content-Type']
return req.text, req_content_type
elif req.status_code == 400:
logger.warning('Full text query returned 400 (Bad Request): '
'Perhaps missing CrossRef Clickthrough API '
'key?')
return (None, None)
# Check for XML first
if lookup_content_type(links, 'text/xml'):
req = requests.get(lookup_content_type(links, 'text/xml'),
headers=headers)
if req.status_code == 200:
req_content_type = req.headers['Content-Type']
return req.text, req_content_type
elif req.status_code == 400:
logger.warning('Full text query returned 400 (Bad Request):'
'Perhaps missing CrossRef Clickthrough API '
'key?')
return (None, None)
# Next, plain text
elif lookup_content_type(links, 'text/plain'):
req = requests.get(lookup_content_type(links, 'text/plain'),
headers=headers)
if req.status_code == 200:
req_content_type = req.headers['Content-Type']
return req.text, req_content_type
elif req.status_code == 400:
logger.warning('Full text query returned 400 (Bad Request):'
'Perhaps missing CrossRef Clickthrough API '
'key?')
return (None, None)
elif lookup_content_type(links, 'application/pdf'):
pass
# Wiley's links are often of content-type 'unspecified'.
elif lookup_content_type(links, 'unspecified'):
req = requests.get(lookup_content_type(links, 'unspecified'),
headers=headers)
if req.status_code == 200:
req_content_type = req.headers['Content-Type']
return 'foo', req_content_type
elif req.status_code == 400:
logger.warning('Full text query returned 400 (Bad Request):'
'Perhaps missing CrossRef Clickthrough API '
'key?')
return (None, None)
elif req.status_code == 401:
logger.warning('Full text query returned 401 (Unauthorized)')
return (None, None)
elif req.status_code == 403:
logger.warning('Full text query returned 403 (Forbidden)')
return (None, None)
else:
raise Exception("Unknown content type(s): %s" % links)
elif publisher == 'American Society for Biochemistry & Molecular ' \
'Biology (ASBMB)':
url = crossref_client.get_url(doi)
return get_asbmb_full_text(url)
"""
# end FIXME FIXME FIXME
# No full text links and not a publisher we support. We'll have to
# fall back to the abstract.
#elif pmid:
if pmid:
abstract = pubmed_client.get_abstract(pmid)
if abstract is None:
return (None, None)
else:
return abstract, 'abstract'
# We have a useless DOI and no PMID. Give up.
else:
return (None, None)
# We don't have a DOI but we're guaranteed to have a PMID at this point,
# so we fall back to the abstract:
else:
abstract = pubmed_client.get_abstract(pmid)
if abstract is None:
return (None, None)
else:
return abstract, 'abstract'
# We'll only get here if we've missed a combination of conditions
assert False | [
"def",
"get_full_text",
"(",
"paper_id",
",",
"idtype",
",",
"preferred_content_type",
"=",
"'text/xml'",
")",
":",
"if",
"preferred_content_type",
"not",
"in",
"(",
"'text/xml'",
",",
"'text/plain'",
",",
"'application/pdf'",
")",
":",
"raise",
"ValueError",
"(",... | Return the content and the content type of an article.
This function retreives the content of an article by its PubMed ID,
PubMed Central ID, or DOI. It prioritizes full text content when available
and returns an abstract from PubMed as a fallback.
Parameters
----------
paper_id : string
ID of the article.
idtype : 'pmid', 'pmcid', or 'doi
Type of the ID.
preferred_content_type : Optional[st]r
Preference for full-text format, if available. Can be one of
'text/xml', 'text/plain', 'application/pdf'. Default: 'text/xml'
Returns
-------
content : str
The content of the article.
content_type : str
The content type of the article | [
"Return",
"the",
"content",
"and",
"the",
"content",
"type",
"of",
"an",
"article",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/literature/__init__.py#L74-L244 |
19,166 | sorgerlab/indra | indra/sources/reach/reader.py | ReachReader.get_api_ruler | def get_api_ruler(self):
"""Return the existing reader if it exists or launch a new one.
Returns
-------
api_ruler : org.clulab.reach.apis.ApiRuler
An instance of the REACH ApiRuler class (java object).
"""
if self.api_ruler is None:
try:
self.api_ruler = \
autoclass('org.clulab.reach.export.apis.ApiRuler')
except JavaException as e:
raise ReachOfflineReadingError(e)
return self.api_ruler | python | def get_api_ruler(self):
if self.api_ruler is None:
try:
self.api_ruler = \
autoclass('org.clulab.reach.export.apis.ApiRuler')
except JavaException as e:
raise ReachOfflineReadingError(e)
return self.api_ruler | [
"def",
"get_api_ruler",
"(",
"self",
")",
":",
"if",
"self",
".",
"api_ruler",
"is",
"None",
":",
"try",
":",
"self",
".",
"api_ruler",
"=",
"autoclass",
"(",
"'org.clulab.reach.export.apis.ApiRuler'",
")",
"except",
"JavaException",
"as",
"e",
":",
"raise",
... | Return the existing reader if it exists or launch a new one.
Returns
-------
api_ruler : org.clulab.reach.apis.ApiRuler
An instance of the REACH ApiRuler class (java object). | [
"Return",
"the",
"existing",
"reader",
"if",
"it",
"exists",
"or",
"launch",
"a",
"new",
"one",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/reach/reader.py#L55-L69 |
19,167 | sorgerlab/indra | indra/sources/biogrid.py | _download_biogrid_data | def _download_biogrid_data(url):
"""Downloads zipped, tab-separated Biogrid data in .tab2 format.
Parameters:
-----------
url : str
URL of the BioGrid zip file.
Returns
-------
csv.reader
A csv.reader object for iterating over the rows (header has already
been skipped).
"""
res = requests.get(biogrid_file_url)
if res.status_code != 200:
raise Exception('Unable to download Biogrid data: status code %s'
% res.status_code)
zip_bytes = BytesIO(res.content)
zip_file = ZipFile(zip_bytes)
zip_info_list = zip_file.infolist()
# There should be only one file in this zip archive
if len(zip_info_list) != 1:
raise Exception('There should be exactly zipfile in BioGrid zip '
'archive: %s' % str(zip_info_list))
unzipped_bytes = zip_file.read(zip_info_list[0]) # Unzip the file
biogrid_str = StringIO(unzipped_bytes.decode('utf8')) # Make file-like obj
csv_reader = csv.reader(biogrid_str, delimiter='\t') # Get csv reader
next(csv_reader) # Skip the header
return csv_reader | python | def _download_biogrid_data(url):
res = requests.get(biogrid_file_url)
if res.status_code != 200:
raise Exception('Unable to download Biogrid data: status code %s'
% res.status_code)
zip_bytes = BytesIO(res.content)
zip_file = ZipFile(zip_bytes)
zip_info_list = zip_file.infolist()
# There should be only one file in this zip archive
if len(zip_info_list) != 1:
raise Exception('There should be exactly zipfile in BioGrid zip '
'archive: %s' % str(zip_info_list))
unzipped_bytes = zip_file.read(zip_info_list[0]) # Unzip the file
biogrid_str = StringIO(unzipped_bytes.decode('utf8')) # Make file-like obj
csv_reader = csv.reader(biogrid_str, delimiter='\t') # Get csv reader
next(csv_reader) # Skip the header
return csv_reader | [
"def",
"_download_biogrid_data",
"(",
"url",
")",
":",
"res",
"=",
"requests",
".",
"get",
"(",
"biogrid_file_url",
")",
"if",
"res",
".",
"status_code",
"!=",
"200",
":",
"raise",
"Exception",
"(",
"'Unable to download Biogrid data: status code %s'",
"%",
"res",
... | Downloads zipped, tab-separated Biogrid data in .tab2 format.
Parameters:
-----------
url : str
URL of the BioGrid zip file.
Returns
-------
csv.reader
A csv.reader object for iterating over the rows (header has already
been skipped). | [
"Downloads",
"zipped",
"tab",
"-",
"separated",
"Biogrid",
"data",
"in",
".",
"tab2",
"format",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/biogrid.py#L156-L185 |
19,168 | sorgerlab/indra | indra/sources/biogrid.py | BiogridProcessor._make_agent | def _make_agent(self, entrez_id, text_id):
"""Make an Agent object, appropriately grounded.
Parameters
----------
entrez_id : str
Entrez id number
text_id : str
A plain text systematic name, or None if not listed.
Returns
-------
agent : indra.statements.Agent
A grounded agent object.
"""
hgnc_name, db_refs = self._make_db_refs(entrez_id, text_id)
if hgnc_name is not None:
name = hgnc_name
elif text_id is not None:
name = text_id
# Handle case where the name is None
else:
return None
return Agent(name, db_refs=db_refs) | python | def _make_agent(self, entrez_id, text_id):
hgnc_name, db_refs = self._make_db_refs(entrez_id, text_id)
if hgnc_name is not None:
name = hgnc_name
elif text_id is not None:
name = text_id
# Handle case where the name is None
else:
return None
return Agent(name, db_refs=db_refs) | [
"def",
"_make_agent",
"(",
"self",
",",
"entrez_id",
",",
"text_id",
")",
":",
"hgnc_name",
",",
"db_refs",
"=",
"self",
".",
"_make_db_refs",
"(",
"entrez_id",
",",
"text_id",
")",
"if",
"hgnc_name",
"is",
"not",
"None",
":",
"name",
"=",
"hgnc_name",
"... | Make an Agent object, appropriately grounded.
Parameters
----------
entrez_id : str
Entrez id number
text_id : str
A plain text systematic name, or None if not listed.
Returns
-------
agent : indra.statements.Agent
A grounded agent object. | [
"Make",
"an",
"Agent",
"object",
"appropriately",
"grounded",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/biogrid.py#L97-L121 |
19,169 | sorgerlab/indra | indra/sources/biogrid.py | BiogridProcessor._make_db_refs | def _make_db_refs(self, entrez_id, text_id):
"""Looks up the HGNC ID and name, as well as the Uniprot ID.
Parameters
----------
entrez_id : str
Entrez gene ID.
text_id : str or None
A plain text systematic name, or None if not listed in the
Biogrid data.
Returns
-------
hgnc_name : str
Official HGNC symbol for the gene.
db_refs : dict
db_refs grounding dictionary, used when constructing the Agent
object.
"""
db_refs = {}
if text_id != '-' and text_id is not None:
db_refs['TEXT'] = text_id
hgnc_id = hgnc_client.get_hgnc_from_entrez(entrez_id)
hgnc_name = hgnc_client.get_hgnc_name(hgnc_id)
if hgnc_id is not None:
db_refs['HGNC'] = hgnc_id
up_id = hgnc_client.get_uniprot_id(hgnc_id)
if up_id is not None:
db_refs['UP'] = up_id
return (hgnc_name, db_refs) | python | def _make_db_refs(self, entrez_id, text_id):
db_refs = {}
if text_id != '-' and text_id is not None:
db_refs['TEXT'] = text_id
hgnc_id = hgnc_client.get_hgnc_from_entrez(entrez_id)
hgnc_name = hgnc_client.get_hgnc_name(hgnc_id)
if hgnc_id is not None:
db_refs['HGNC'] = hgnc_id
up_id = hgnc_client.get_uniprot_id(hgnc_id)
if up_id is not None:
db_refs['UP'] = up_id
return (hgnc_name, db_refs) | [
"def",
"_make_db_refs",
"(",
"self",
",",
"entrez_id",
",",
"text_id",
")",
":",
"db_refs",
"=",
"{",
"}",
"if",
"text_id",
"!=",
"'-'",
"and",
"text_id",
"is",
"not",
"None",
":",
"db_refs",
"[",
"'TEXT'",
"]",
"=",
"text_id",
"hgnc_id",
"=",
"hgnc_cl... | Looks up the HGNC ID and name, as well as the Uniprot ID.
Parameters
----------
entrez_id : str
Entrez gene ID.
text_id : str or None
A plain text systematic name, or None if not listed in the
Biogrid data.
Returns
-------
hgnc_name : str
Official HGNC symbol for the gene.
db_refs : dict
db_refs grounding dictionary, used when constructing the Agent
object. | [
"Looks",
"up",
"the",
"HGNC",
"ID",
"and",
"name",
"as",
"well",
"as",
"the",
"Uniprot",
"ID",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/biogrid.py#L123-L153 |
19,170 | sorgerlab/indra | indra/assemblers/kami/assembler.py | KamiAssembler.make_model | def make_model(self, policies=None, initial_conditions=True,
reverse_effects=False):
"""Assemble the Kami model from the collected INDRA Statements.
This method assembles a Kami model from the set of INDRA Statements.
The assembled model is both returned and set as the assembler's
model argument.
Parameters
----------
policies : Optional[Union[str, dict]]
A string or dictionary of policies, as defined in
:py:class:`indra.assemblers.KamiAssembler`. This set of policies
locally supersedes the default setting in the assembler. This
is useful when this function is called multiple times with
different policies.
initial_conditions : Optional[bool]
If True, default initial conditions are generated for the
agents in the model.
Returns
-------
model : dict
The assembled Kami model.
"""
self.processed_policies = self.process_policies(policies)
ppa = PysbPreassembler(self.statements)
ppa.replace_activities()
if reverse_effects:
ppa.add_reverse_effects()
self.statements = ppa.statements
# Set local policies for this make_model call that overwrite
# the global policies of the Kami assembler
if policies is not None:
global_policies = self.policies
if isinstance(policies, basestring):
local_policies = {'other': policies}
else:
local_policies = {'other': 'default'}
local_policies.update(policies)
self.policies = local_policies
self.model = {}
graphs = []
self.model['graphs'] = graphs
self.model['typing'] = []
# Action graph generated here
action_graph = {'id': 'action_graph',
'attrs': {'name': 'action_graph'}}
action_graph['graph'] = {'nodes': [], 'edges': []}
graphs.append(action_graph)
# Iterate over the statements to generate rules
self._assemble()
# Add initial conditions
#if initial_conditions:
# self.add_default_initial_conditions()
# If local policies were applied, revert to the global one
if policies is not None:
self.policies = global_policies
return self.model | python | def make_model(self, policies=None, initial_conditions=True,
reverse_effects=False):
self.processed_policies = self.process_policies(policies)
ppa = PysbPreassembler(self.statements)
ppa.replace_activities()
if reverse_effects:
ppa.add_reverse_effects()
self.statements = ppa.statements
# Set local policies for this make_model call that overwrite
# the global policies of the Kami assembler
if policies is not None:
global_policies = self.policies
if isinstance(policies, basestring):
local_policies = {'other': policies}
else:
local_policies = {'other': 'default'}
local_policies.update(policies)
self.policies = local_policies
self.model = {}
graphs = []
self.model['graphs'] = graphs
self.model['typing'] = []
# Action graph generated here
action_graph = {'id': 'action_graph',
'attrs': {'name': 'action_graph'}}
action_graph['graph'] = {'nodes': [], 'edges': []}
graphs.append(action_graph)
# Iterate over the statements to generate rules
self._assemble()
# Add initial conditions
#if initial_conditions:
# self.add_default_initial_conditions()
# If local policies were applied, revert to the global one
if policies is not None:
self.policies = global_policies
return self.model | [
"def",
"make_model",
"(",
"self",
",",
"policies",
"=",
"None",
",",
"initial_conditions",
"=",
"True",
",",
"reverse_effects",
"=",
"False",
")",
":",
"self",
".",
"processed_policies",
"=",
"self",
".",
"process_policies",
"(",
"policies",
")",
"ppa",
"=",... | Assemble the Kami model from the collected INDRA Statements.
This method assembles a Kami model from the set of INDRA Statements.
The assembled model is both returned and set as the assembler's
model argument.
Parameters
----------
policies : Optional[Union[str, dict]]
A string or dictionary of policies, as defined in
:py:class:`indra.assemblers.KamiAssembler`. This set of policies
locally supersedes the default setting in the assembler. This
is useful when this function is called multiple times with
different policies.
initial_conditions : Optional[bool]
If True, default initial conditions are generated for the
agents in the model.
Returns
-------
model : dict
The assembled Kami model. | [
"Assemble",
"the",
"Kami",
"model",
"from",
"the",
"collected",
"INDRA",
"Statements",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/kami/assembler.py#L24-L87 |
19,171 | sorgerlab/indra | indra/assemblers/kami/assembler.py | Nugget.add_agent | def add_agent(self, agent):
"""Add an INDRA Agent and its conditions to the Nugget."""
agent_id = self.add_node(agent.name)
self.add_typing(agent_id, 'agent')
# Handle bound conditions
for bc in agent.bound_conditions:
# Here we make the assumption that the binding site
# is simply named after the binding partner
if bc.is_bound:
test_type = 'is_bnd'
else:
test_type = 'is_free'
bound_name = bc.agent.name
agent_bs = get_binding_site_name(bc.agent)
test_name = '%s_bound_to_%s_test' % (agent_id, bound_name)
agent_bs_id = self.add_node(agent_bs)
test_id = self.add_node(test_name)
self.add_edge(agent_bs_id, agent_id)
self.add_edge(agent_bs_id, test_id)
self.add_typing(agent_bs_id, 'locus')
self.add_typing(test_id, test_type)
for mod in agent.mods:
mod_site_str = abbrevs[mod.mod_type]
if mod.residue is not None:
mod_site_str = mod.residue
mod_pos_str = mod.position if mod.position is not None else ''
mod_site = ('%s%s' % (mod_site_str, mod_pos_str))
site_states = states[mod.mod_type]
if mod.is_modified:
val = site_states[1]
else:
val = site_states[0]
mod_site_id = self.add_node(mod_site, {'val': val})
self.add_edge(mod_site_id, agent_id)
self.add_typing(mod_site_id, 'state')
return agent_id | python | def add_agent(self, agent):
agent_id = self.add_node(agent.name)
self.add_typing(agent_id, 'agent')
# Handle bound conditions
for bc in agent.bound_conditions:
# Here we make the assumption that the binding site
# is simply named after the binding partner
if bc.is_bound:
test_type = 'is_bnd'
else:
test_type = 'is_free'
bound_name = bc.agent.name
agent_bs = get_binding_site_name(bc.agent)
test_name = '%s_bound_to_%s_test' % (agent_id, bound_name)
agent_bs_id = self.add_node(agent_bs)
test_id = self.add_node(test_name)
self.add_edge(agent_bs_id, agent_id)
self.add_edge(agent_bs_id, test_id)
self.add_typing(agent_bs_id, 'locus')
self.add_typing(test_id, test_type)
for mod in agent.mods:
mod_site_str = abbrevs[mod.mod_type]
if mod.residue is not None:
mod_site_str = mod.residue
mod_pos_str = mod.position if mod.position is not None else ''
mod_site = ('%s%s' % (mod_site_str, mod_pos_str))
site_states = states[mod.mod_type]
if mod.is_modified:
val = site_states[1]
else:
val = site_states[0]
mod_site_id = self.add_node(mod_site, {'val': val})
self.add_edge(mod_site_id, agent_id)
self.add_typing(mod_site_id, 'state')
return agent_id | [
"def",
"add_agent",
"(",
"self",
",",
"agent",
")",
":",
"agent_id",
"=",
"self",
".",
"add_node",
"(",
"agent",
".",
"name",
")",
"self",
".",
"add_typing",
"(",
"agent_id",
",",
"'agent'",
")",
"# Handle bound conditions",
"for",
"bc",
"in",
"agent",
"... | Add an INDRA Agent and its conditions to the Nugget. | [
"Add",
"an",
"INDRA",
"Agent",
"and",
"its",
"conditions",
"to",
"the",
"Nugget",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/kami/assembler.py#L134-L170 |
19,172 | sorgerlab/indra | indra/assemblers/kami/assembler.py | Nugget.add_node | def add_node(self, name_base, attrs=None):
"""Add a node with a given base name to the Nugget and return ID."""
if name_base not in self.counters:
node_id = name_base
else:
node_id = '%s_%d' % (name_base, self.counters[name_base])
node = {'id': node_id}
if attrs:
node['attrs'] = attrs
self.nodes.append(node)
self.counters[node_id] += 1
return node_id | python | def add_node(self, name_base, attrs=None):
if name_base not in self.counters:
node_id = name_base
else:
node_id = '%s_%d' % (name_base, self.counters[name_base])
node = {'id': node_id}
if attrs:
node['attrs'] = attrs
self.nodes.append(node)
self.counters[node_id] += 1
return node_id | [
"def",
"add_node",
"(",
"self",
",",
"name_base",
",",
"attrs",
"=",
"None",
")",
":",
"if",
"name_base",
"not",
"in",
"self",
".",
"counters",
":",
"node_id",
"=",
"name_base",
"else",
":",
"node_id",
"=",
"'%s_%d'",
"%",
"(",
"name_base",
",",
"self"... | Add a node with a given base name to the Nugget and return ID. | [
"Add",
"a",
"node",
"with",
"a",
"given",
"base",
"name",
"to",
"the",
"Nugget",
"and",
"return",
"ID",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/kami/assembler.py#L172-L183 |
19,173 | sorgerlab/indra | indra/assemblers/kami/assembler.py | Nugget.get_nugget_dict | def get_nugget_dict(self):
"""Return the Nugget as a dictionary."""
nugget_dict = \
{'id': self.id,
'graph': {
'nodes': self.nodes,
'edges': self.edges
},
'attrs': {
'name': self.name,
'rate': self.rate
}
}
return nugget_dict | python | def get_nugget_dict(self):
nugget_dict = \
{'id': self.id,
'graph': {
'nodes': self.nodes,
'edges': self.edges
},
'attrs': {
'name': self.name,
'rate': self.rate
}
}
return nugget_dict | [
"def",
"get_nugget_dict",
"(",
"self",
")",
":",
"nugget_dict",
"=",
"{",
"'id'",
":",
"self",
".",
"id",
",",
"'graph'",
":",
"{",
"'nodes'",
":",
"self",
".",
"nodes",
",",
"'edges'",
":",
"self",
".",
"edges",
"}",
",",
"'attrs'",
":",
"{",
"'na... | Return the Nugget as a dictionary. | [
"Return",
"the",
"Nugget",
"as",
"a",
"dictionary",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/kami/assembler.py#L193-L206 |
19,174 | sorgerlab/indra | indra/sources/tees/api.py | process_text | def process_text(text, pmid=None, python2_path=None):
"""Processes the specified plain text with TEES and converts output to
supported INDRA statements. Check for the TEES installation is the
TEES_PATH environment variable, and configuration file; if not found,
checks candidate paths in tees_candidate_paths. Raises an exception if
TEES cannot be found in any of these places.
Parameters
----------
text : str
Plain text to process with TEES
pmid : str
The PMID from which the paper comes from, to be stored in the Evidence
object of statements. Set to None if this is unspecified.
python2_path : str
TEES is only compatible with python 2. This processor invokes this
external python 2 interpreter so that the processor can be run in
either python 2 or python 3. If None, searches for an executible named
python2 in the PATH environment variable.
Returns
-------
tp : TEESProcessor
A TEESProcessor object which contains a list of INDRA statements
extracted from TEES extractions
"""
# Try to locate python2 in one of the directories of the PATH environment
# variable if it is not provided
if python2_path is None:
for path in os.environ["PATH"].split(os.pathsep):
proposed_python2_path = os.path.join(path, 'python2.7')
if os.path.isfile(proposed_python2_path):
python2_path = proposed_python2_path
print('Found python 2 interpreter at', python2_path)
break
if python2_path is None:
raise Exception('Could not find python2 in the directories ' +
'listed in the PATH environment variable. ' +
'Need python2 to run TEES.')
# Run TEES
a1_text, a2_text, sentence_segmentations = run_on_text(text,
python2_path)
# Run the TEES processor
tp = TEESProcessor(a1_text, a2_text, sentence_segmentations, pmid)
return tp | python | def process_text(text, pmid=None, python2_path=None):
# Try to locate python2 in one of the directories of the PATH environment
# variable if it is not provided
if python2_path is None:
for path in os.environ["PATH"].split(os.pathsep):
proposed_python2_path = os.path.join(path, 'python2.7')
if os.path.isfile(proposed_python2_path):
python2_path = proposed_python2_path
print('Found python 2 interpreter at', python2_path)
break
if python2_path is None:
raise Exception('Could not find python2 in the directories ' +
'listed in the PATH environment variable. ' +
'Need python2 to run TEES.')
# Run TEES
a1_text, a2_text, sentence_segmentations = run_on_text(text,
python2_path)
# Run the TEES processor
tp = TEESProcessor(a1_text, a2_text, sentence_segmentations, pmid)
return tp | [
"def",
"process_text",
"(",
"text",
",",
"pmid",
"=",
"None",
",",
"python2_path",
"=",
"None",
")",
":",
"# Try to locate python2 in one of the directories of the PATH environment",
"# variable if it is not provided",
"if",
"python2_path",
"is",
"None",
":",
"for",
"path... | Processes the specified plain text with TEES and converts output to
supported INDRA statements. Check for the TEES installation is the
TEES_PATH environment variable, and configuration file; if not found,
checks candidate paths in tees_candidate_paths. Raises an exception if
TEES cannot be found in any of these places.
Parameters
----------
text : str
Plain text to process with TEES
pmid : str
The PMID from which the paper comes from, to be stored in the Evidence
object of statements. Set to None if this is unspecified.
python2_path : str
TEES is only compatible with python 2. This processor invokes this
external python 2 interpreter so that the processor can be run in
either python 2 or python 3. If None, searches for an executible named
python2 in the PATH environment variable.
Returns
-------
tp : TEESProcessor
A TEESProcessor object which contains a list of INDRA statements
extracted from TEES extractions | [
"Processes",
"the",
"specified",
"plain",
"text",
"with",
"TEES",
"and",
"converts",
"output",
"to",
"supported",
"INDRA",
"statements",
".",
"Check",
"for",
"the",
"TEES",
"installation",
"is",
"the",
"TEES_PATH",
"environment",
"variable",
"and",
"configuration"... | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/tees/api.py#L46-L93 |
19,175 | sorgerlab/indra | indra/sources/tees/api.py | run_on_text | def run_on_text(text, python2_path):
"""Runs TEES on the given text in a temporary directory and returns a
temporary directory with TEES output.
The caller should delete this directory when done with it. This function
runs TEES and produces TEES output files but does not process TEES output
into INDRA statements.
Parameters
----------
text : str
Text from which to extract relationships
python2_path : str
The path to the python 2 interpreter
Returns
-------
output_dir : str
Temporary directory with TEES output. The caller should delete this
directgory when done with it.
"""
tees_path = get_config('TEES_PATH')
if tees_path is None:
# If TEES directory is not specifies, see if any of the candidate paths
# exist and contain all of the files expected for a TEES installation.
for cpath in tees_candidate_paths:
cpath = os.path.expanduser(cpath)
if os.path.isdir(cpath):
# Check to see if it has all of the expected files and
# directories
has_expected_files = True
for f in tees_installation_files:
fpath = os.path.join(cpath, f)
present = os.path.isfile(fpath)
has_expected_files = has_expected_files and present
has_expected_dirs = True
for d in tees_installation_dirs:
dpath = os.path.join(cpath, d)
present = os.path.isdir(dpath)
has_expected_dirs = has_expected_dirs and present
if has_expected_files and has_expected_dirs:
# We found a directory with all of the files and
# directories we expected in a TEES installation - let's
# assume it's a TEES installation
tees_path = cpath
print('Found TEES installation at ' + cpath)
break
# Make sure the provided TEES directory exists
if not os.path.isdir(tees_path):
raise Exception('Provided TEES directory does not exist.')
# Make sure the classify.py script exists within this directory
classify_path = 'classify.py'
# if not os.path.isfile(classify_path):
# raise Exception('classify.py does not exist in provided TEES path.')
# Create a temporary directory to tag the shared-task files
tmp_dir = tempfile.mkdtemp(suffix='indra_tees_processor')
pwd = os.path.abspath(os.getcwd())
try:
# Write text to a file in the temporary directory
text_path = os.path.join(tmp_dir, 'text.txt')
# Had some trouble with non-ascii characters. A possible TODO item in
# the future is to look into resolving this, for now just ignoring
# non-latin-1 characters
with codecs.open(text_path, 'w', encoding='latin-1', errors='ignore') \
as f:
f.write(text)
# Run TEES
output_path = os.path.join(tmp_dir, 'output')
model_path = os.path.join(tees_path, 'tees_data/models/GE11-test/')
command = [python2_path, classify_path, '-m', model_path,
'-i', text_path,
'-o', output_path]
try:
pwd = os.path.abspath(os.getcwd())
os.chdir(tees_path) # Change to TEES directory
# print('cwd is:', os.getcwd())
# out = subprocess.check_output(command, stderr=subprocess.STDOUT)
p = subprocess.Popen(command, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, cwd=tees_path)
p.wait()
(so, se) = p.communicate()
print(so)
print(se)
os.chdir(pwd) # Change back to previous directory
# print('cwd is:', os.getcwd())
# print(out.decode('utf-8'))
except BaseException as e:
# If there's an error, print it out and then propagate the
# exception
os.chdir(pwd) # Change back to previous directory
# print (e.output.decode('utf-8'))
raise e
except BaseException as e:
# If there was an exception, delete the temporary directory and
# pass on the exception
shutil.rmtree(tmp_dir)
raise e
# Return the temporary directory with the TEES output
output_tuple = extract_output(tmp_dir)
shutil.rmtree(tmp_dir)
return output_tuple | python | def run_on_text(text, python2_path):
tees_path = get_config('TEES_PATH')
if tees_path is None:
# If TEES directory is not specifies, see if any of the candidate paths
# exist and contain all of the files expected for a TEES installation.
for cpath in tees_candidate_paths:
cpath = os.path.expanduser(cpath)
if os.path.isdir(cpath):
# Check to see if it has all of the expected files and
# directories
has_expected_files = True
for f in tees_installation_files:
fpath = os.path.join(cpath, f)
present = os.path.isfile(fpath)
has_expected_files = has_expected_files and present
has_expected_dirs = True
for d in tees_installation_dirs:
dpath = os.path.join(cpath, d)
present = os.path.isdir(dpath)
has_expected_dirs = has_expected_dirs and present
if has_expected_files and has_expected_dirs:
# We found a directory with all of the files and
# directories we expected in a TEES installation - let's
# assume it's a TEES installation
tees_path = cpath
print('Found TEES installation at ' + cpath)
break
# Make sure the provided TEES directory exists
if not os.path.isdir(tees_path):
raise Exception('Provided TEES directory does not exist.')
# Make sure the classify.py script exists within this directory
classify_path = 'classify.py'
# if not os.path.isfile(classify_path):
# raise Exception('classify.py does not exist in provided TEES path.')
# Create a temporary directory to tag the shared-task files
tmp_dir = tempfile.mkdtemp(suffix='indra_tees_processor')
pwd = os.path.abspath(os.getcwd())
try:
# Write text to a file in the temporary directory
text_path = os.path.join(tmp_dir, 'text.txt')
# Had some trouble with non-ascii characters. A possible TODO item in
# the future is to look into resolving this, for now just ignoring
# non-latin-1 characters
with codecs.open(text_path, 'w', encoding='latin-1', errors='ignore') \
as f:
f.write(text)
# Run TEES
output_path = os.path.join(tmp_dir, 'output')
model_path = os.path.join(tees_path, 'tees_data/models/GE11-test/')
command = [python2_path, classify_path, '-m', model_path,
'-i', text_path,
'-o', output_path]
try:
pwd = os.path.abspath(os.getcwd())
os.chdir(tees_path) # Change to TEES directory
# print('cwd is:', os.getcwd())
# out = subprocess.check_output(command, stderr=subprocess.STDOUT)
p = subprocess.Popen(command, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, cwd=tees_path)
p.wait()
(so, se) = p.communicate()
print(so)
print(se)
os.chdir(pwd) # Change back to previous directory
# print('cwd is:', os.getcwd())
# print(out.decode('utf-8'))
except BaseException as e:
# If there's an error, print it out and then propagate the
# exception
os.chdir(pwd) # Change back to previous directory
# print (e.output.decode('utf-8'))
raise e
except BaseException as e:
# If there was an exception, delete the temporary directory and
# pass on the exception
shutil.rmtree(tmp_dir)
raise e
# Return the temporary directory with the TEES output
output_tuple = extract_output(tmp_dir)
shutil.rmtree(tmp_dir)
return output_tuple | [
"def",
"run_on_text",
"(",
"text",
",",
"python2_path",
")",
":",
"tees_path",
"=",
"get_config",
"(",
"'TEES_PATH'",
")",
"if",
"tees_path",
"is",
"None",
":",
"# If TEES directory is not specifies, see if any of the candidate paths",
"# exist and contain all of the files ex... | Runs TEES on the given text in a temporary directory and returns a
temporary directory with TEES output.
The caller should delete this directory when done with it. This function
runs TEES and produces TEES output files but does not process TEES output
into INDRA statements.
Parameters
----------
text : str
Text from which to extract relationships
python2_path : str
The path to the python 2 interpreter
Returns
-------
output_dir : str
Temporary directory with TEES output. The caller should delete this
directgory when done with it. | [
"Runs",
"TEES",
"on",
"the",
"given",
"text",
"in",
"a",
"temporary",
"directory",
"and",
"returns",
"a",
"temporary",
"directory",
"with",
"TEES",
"output",
".",
"The",
"caller",
"should",
"delete",
"this",
"directory",
"when",
"done",
"with",
"it",
".",
... | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/tees/api.py#L95-L206 |
19,176 | sorgerlab/indra | indra/sources/tees/api.py | extract_output | def extract_output(output_dir):
"""Extract the text of the a1, a2, and sentence segmentation files from the
TEES output directory. These files are located within a compressed archive.
Parameters
----------
output_dir : str
Directory containing the output of the TEES system
Returns
-------
a1_text : str
The text of the TEES a1 file (specifying the entities)
a2_text : str
The text of the TEES a2 file (specifying the event graph)
sentence_segmentations : str
The text of the XML file specifying the sentence segmentation
"""
# Locate the file of sentences segmented by the TEES system, described
# in a compressed xml document
sentences_glob = os.path.join(output_dir, '*-preprocessed.xml.gz')
sentences_filename_candidates = glob.glob(sentences_glob)
# Make sure there is exactly one such file
if len(sentences_filename_candidates) != 1:
m = 'Looking for exactly one file matching %s but found %d matches'
raise Exception(m % (
sentences_glob, len(sentences_filename_candidates)))
return None, None, None
# Read in the sentence segmentation XML
sentence_segmentation_filename = sentences_filename_candidates[0]
with gzip.GzipFile(sentences_filename_candidates[0], 'r') as f:
sentence_segmentations = f.read().decode('utf-8')
# Create a temporary directory to which to extract the a1 and a2 files from
# the tarball
tmp_dir = tempfile.mkdtemp(suffix='indra_tees_processor')
try:
# Make sure the tarfile with the extracted events is in shared task
# format is in the output directory
tarfile_glob = os.path.join(output_dir, '*-events.tar.gz')
candidate_tarfiles = glob.glob(tarfile_glob)
if len(candidate_tarfiles) != 1:
raise Exception('Expected exactly one match for glob %s' %
tarfile_glob)
return None, None, None
# Decide what tar files to extract
# (We're not blindly extracting all files because of the security
# warning in the documentation for TarFile.extractall
# In particular, we want to make sure that the filename doesn't
# try to specify a relative or absolute path other than the current
# directory by making sure the filename starts with an alphanumeric
# character.
# We're also only interested in files with the .a1 or .a2 extension
tar_file = tarfile.open(candidate_tarfiles[0])
a1_file = None
a2_file = None
extract_these = []
for m in tar_file.getmembers():
if re.match('[a-zA-Z0-9].*.a[12]', m.name):
extract_these.append(m)
if m.name.endswith('.a1'):
a1_file = m.name
elif m.name.endswith('.a2'):
a2_file = m.name
else:
assert(False)
# There should be exactly two files that match these criteria
if len(extract_these) != 2 or a1_file is None or a2_file is None:
raise Exception('We thought there would be one .a1 and one .a2' +
' file in the tarball, but we got %d files total' %
len(extract_these))
return None, None, None
# Extract the files that we decided to extract
tar_file.extractall(path=tmp_dir, members=extract_these)
# Read the text of the a1 (entities) file
with codecs.open(os.path.join(tmp_dir, a1_file), 'r',
encoding='utf-8') as f:
a1_text = f.read()
# Read the text of the a2 (events) file
with codecs.open(os.path.join(tmp_dir, a2_file), 'r',
encoding='utf-8') as f:
a2_text = f.read()
# Now that we're done, remove the temporary directory
shutil.rmtree(tmp_dir)
# Return the extracted text
return a1_text, a2_text, sentence_segmentations
except BaseException as e:
# If there was an exception, delete the temporary directory and
# pass on the exception
print('Not removing temporary directory: ' + tmp_dir)
shutil.rmtree(tmp_dir)
raise e
return None, None, None | python | def extract_output(output_dir):
# Locate the file of sentences segmented by the TEES system, described
# in a compressed xml document
sentences_glob = os.path.join(output_dir, '*-preprocessed.xml.gz')
sentences_filename_candidates = glob.glob(sentences_glob)
# Make sure there is exactly one such file
if len(sentences_filename_candidates) != 1:
m = 'Looking for exactly one file matching %s but found %d matches'
raise Exception(m % (
sentences_glob, len(sentences_filename_candidates)))
return None, None, None
# Read in the sentence segmentation XML
sentence_segmentation_filename = sentences_filename_candidates[0]
with gzip.GzipFile(sentences_filename_candidates[0], 'r') as f:
sentence_segmentations = f.read().decode('utf-8')
# Create a temporary directory to which to extract the a1 and a2 files from
# the tarball
tmp_dir = tempfile.mkdtemp(suffix='indra_tees_processor')
try:
# Make sure the tarfile with the extracted events is in shared task
# format is in the output directory
tarfile_glob = os.path.join(output_dir, '*-events.tar.gz')
candidate_tarfiles = glob.glob(tarfile_glob)
if len(candidate_tarfiles) != 1:
raise Exception('Expected exactly one match for glob %s' %
tarfile_glob)
return None, None, None
# Decide what tar files to extract
# (We're not blindly extracting all files because of the security
# warning in the documentation for TarFile.extractall
# In particular, we want to make sure that the filename doesn't
# try to specify a relative or absolute path other than the current
# directory by making sure the filename starts with an alphanumeric
# character.
# We're also only interested in files with the .a1 or .a2 extension
tar_file = tarfile.open(candidate_tarfiles[0])
a1_file = None
a2_file = None
extract_these = []
for m in tar_file.getmembers():
if re.match('[a-zA-Z0-9].*.a[12]', m.name):
extract_these.append(m)
if m.name.endswith('.a1'):
a1_file = m.name
elif m.name.endswith('.a2'):
a2_file = m.name
else:
assert(False)
# There should be exactly two files that match these criteria
if len(extract_these) != 2 or a1_file is None or a2_file is None:
raise Exception('We thought there would be one .a1 and one .a2' +
' file in the tarball, but we got %d files total' %
len(extract_these))
return None, None, None
# Extract the files that we decided to extract
tar_file.extractall(path=tmp_dir, members=extract_these)
# Read the text of the a1 (entities) file
with codecs.open(os.path.join(tmp_dir, a1_file), 'r',
encoding='utf-8') as f:
a1_text = f.read()
# Read the text of the a2 (events) file
with codecs.open(os.path.join(tmp_dir, a2_file), 'r',
encoding='utf-8') as f:
a2_text = f.read()
# Now that we're done, remove the temporary directory
shutil.rmtree(tmp_dir)
# Return the extracted text
return a1_text, a2_text, sentence_segmentations
except BaseException as e:
# If there was an exception, delete the temporary directory and
# pass on the exception
print('Not removing temporary directory: ' + tmp_dir)
shutil.rmtree(tmp_dir)
raise e
return None, None, None | [
"def",
"extract_output",
"(",
"output_dir",
")",
":",
"# Locate the file of sentences segmented by the TEES system, described",
"# in a compressed xml document",
"sentences_glob",
"=",
"os",
".",
"path",
".",
"join",
"(",
"output_dir",
",",
"'*-preprocessed.xml.gz'",
")",
"se... | Extract the text of the a1, a2, and sentence segmentation files from the
TEES output directory. These files are located within a compressed archive.
Parameters
----------
output_dir : str
Directory containing the output of the TEES system
Returns
-------
a1_text : str
The text of the TEES a1 file (specifying the entities)
a2_text : str
The text of the TEES a2 file (specifying the event graph)
sentence_segmentations : str
The text of the XML file specifying the sentence segmentation | [
"Extract",
"the",
"text",
"of",
"the",
"a1",
"a2",
"and",
"sentence",
"segmentation",
"files",
"from",
"the",
"TEES",
"output",
"directory",
".",
"These",
"files",
"are",
"located",
"within",
"a",
"compressed",
"archive",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/tees/api.py#L208-L312 |
19,177 | sorgerlab/indra | indra/sources/eidos/reader.py | _list_to_seq | def _list_to_seq(lst):
"""Return a scala.collection.Seq from a Python list."""
ml = autoclass('scala.collection.mutable.MutableList')()
for element in lst:
ml.appendElem(element)
return ml | python | def _list_to_seq(lst):
ml = autoclass('scala.collection.mutable.MutableList')()
for element in lst:
ml.appendElem(element)
return ml | [
"def",
"_list_to_seq",
"(",
"lst",
")",
":",
"ml",
"=",
"autoclass",
"(",
"'scala.collection.mutable.MutableList'",
")",
"(",
")",
"for",
"element",
"in",
"lst",
":",
"ml",
".",
"appendElem",
"(",
"element",
")",
"return",
"ml"
] | Return a scala.collection.Seq from a Python list. | [
"Return",
"a",
"scala",
".",
"collection",
".",
"Seq",
"from",
"a",
"Python",
"list",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/eidos/reader.py#L130-L135 |
19,178 | sorgerlab/indra | indra/sources/eidos/reader.py | EidosReader.process_text | def process_text(self, text, format='json'):
"""Return a mentions JSON object given text.
Parameters
----------
text : str
Text to be processed.
format : str
The format of the output to produce, one of "json" or "json_ld".
Default: "json"
Returns
-------
json_dict : dict
A JSON object of mentions extracted from text.
"""
if self.eidos_reader is None:
self.initialize_reader()
default_arg = lambda x: autoclass('scala.Some')(x)
today = datetime.date.today().strftime("%Y-%m-%d")
fname = 'default_file_name'
annot_doc = self.eidos_reader.extractFromText(
text,
True, # keep text
False, # CAG-relevant only
default_arg(today), # doc creation time
default_arg(fname) # file name
)
if format == 'json':
mentions = annot_doc.odinMentions()
ser = autoclass(eidos_package +
'.serialization.json.WMJSONSerializer')
mentions_json = ser.toJsonStr(mentions)
elif format == 'json_ld':
# We need to get a Scala Seq of annot docs here
ml = _list_to_seq([annot_doc])
# We currently do not need toinstantiate the adjective grounder
# if we want to reinstate it, we would need to do the following
# ag = EidosAdjectiveGrounder.fromConfig(
# EidosSystem.defaultConfig.getConfig("adjectiveGrounder"))
# We now create a JSON-LD corpus
jc = autoclass(eidos_package + '.serialization.json.JLDCorpus')
corpus = jc(ml)
# Finally, serialize the corpus into JSON string
mentions_json = corpus.toJsonStr()
json_dict = json.loads(mentions_json)
return json_dict | python | def process_text(self, text, format='json'):
if self.eidos_reader is None:
self.initialize_reader()
default_arg = lambda x: autoclass('scala.Some')(x)
today = datetime.date.today().strftime("%Y-%m-%d")
fname = 'default_file_name'
annot_doc = self.eidos_reader.extractFromText(
text,
True, # keep text
False, # CAG-relevant only
default_arg(today), # doc creation time
default_arg(fname) # file name
)
if format == 'json':
mentions = annot_doc.odinMentions()
ser = autoclass(eidos_package +
'.serialization.json.WMJSONSerializer')
mentions_json = ser.toJsonStr(mentions)
elif format == 'json_ld':
# We need to get a Scala Seq of annot docs here
ml = _list_to_seq([annot_doc])
# We currently do not need toinstantiate the adjective grounder
# if we want to reinstate it, we would need to do the following
# ag = EidosAdjectiveGrounder.fromConfig(
# EidosSystem.defaultConfig.getConfig("adjectiveGrounder"))
# We now create a JSON-LD corpus
jc = autoclass(eidos_package + '.serialization.json.JLDCorpus')
corpus = jc(ml)
# Finally, serialize the corpus into JSON string
mentions_json = corpus.toJsonStr()
json_dict = json.loads(mentions_json)
return json_dict | [
"def",
"process_text",
"(",
"self",
",",
"text",
",",
"format",
"=",
"'json'",
")",
":",
"if",
"self",
".",
"eidos_reader",
"is",
"None",
":",
"self",
".",
"initialize_reader",
"(",
")",
"default_arg",
"=",
"lambda",
"x",
":",
"autoclass",
"(",
"'scala.S... | Return a mentions JSON object given text.
Parameters
----------
text : str
Text to be processed.
format : str
The format of the output to produce, one of "json" or "json_ld".
Default: "json"
Returns
-------
json_dict : dict
A JSON object of mentions extracted from text. | [
"Return",
"a",
"mentions",
"JSON",
"object",
"given",
"text",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/eidos/reader.py#L80-L127 |
19,179 | sorgerlab/indra | indra/sources/eidos/api.py | process_text | def process_text(text, out_format='json_ld', save_json='eidos_output.json',
webservice=None):
"""Return an EidosProcessor by processing the given text.
This constructs a reader object via Java and extracts mentions
from the text. It then serializes the mentions into JSON and
processes the result with process_json.
Parameters
----------
text : str
The text to be processed.
out_format : Optional[str]
The type of Eidos output to read into and process. Currently only
'json-ld' is supported which is also the default value used.
save_json : Optional[str]
The name of a file in which to dump the JSON output of Eidos.
webservice : Optional[str]
An Eidos reader web service URL to send the request to.
If None, the reading is assumed to be done with the Eidos JAR rather
than via a web service. Default: None
Returns
-------
ep : EidosProcessor
An EidosProcessor containing the extracted INDRA Statements in its
statements attribute.
"""
if not webservice:
if eidos_reader is None:
logger.error('Eidos reader is not available.')
return None
json_dict = eidos_reader.process_text(text, out_format)
else:
res = requests.post('%s/process_text' % webservice,
json={'text': text})
json_dict = res.json()
if save_json:
with open(save_json, 'wt') as fh:
json.dump(json_dict, fh, indent=2)
return process_json(json_dict) | python | def process_text(text, out_format='json_ld', save_json='eidos_output.json',
webservice=None):
if not webservice:
if eidos_reader is None:
logger.error('Eidos reader is not available.')
return None
json_dict = eidos_reader.process_text(text, out_format)
else:
res = requests.post('%s/process_text' % webservice,
json={'text': text})
json_dict = res.json()
if save_json:
with open(save_json, 'wt') as fh:
json.dump(json_dict, fh, indent=2)
return process_json(json_dict) | [
"def",
"process_text",
"(",
"text",
",",
"out_format",
"=",
"'json_ld'",
",",
"save_json",
"=",
"'eidos_output.json'",
",",
"webservice",
"=",
"None",
")",
":",
"if",
"not",
"webservice",
":",
"if",
"eidos_reader",
"is",
"None",
":",
"logger",
".",
"error",
... | Return an EidosProcessor by processing the given text.
This constructs a reader object via Java and extracts mentions
from the text. It then serializes the mentions into JSON and
processes the result with process_json.
Parameters
----------
text : str
The text to be processed.
out_format : Optional[str]
The type of Eidos output to read into and process. Currently only
'json-ld' is supported which is also the default value used.
save_json : Optional[str]
The name of a file in which to dump the JSON output of Eidos.
webservice : Optional[str]
An Eidos reader web service URL to send the request to.
If None, the reading is assumed to be done with the Eidos JAR rather
than via a web service. Default: None
Returns
-------
ep : EidosProcessor
An EidosProcessor containing the extracted INDRA Statements in its
statements attribute. | [
"Return",
"an",
"EidosProcessor",
"by",
"processing",
"the",
"given",
"text",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/eidos/api.py#L22-L62 |
19,180 | sorgerlab/indra | indra/sources/eidos/api.py | process_json_file | def process_json_file(file_name):
"""Return an EidosProcessor by processing the given Eidos JSON-LD file.
This function is useful if the output from Eidos is saved as a file and
needs to be processed.
Parameters
----------
file_name : str
The name of the JSON-LD file to be processed.
Returns
-------
ep : EidosProcessor
A EidosProcessor containing the extracted INDRA Statements
in its statements attribute.
"""
try:
with open(file_name, 'rb') as fh:
json_str = fh.read().decode('utf-8')
return process_json_str(json_str)
except IOError:
logger.exception('Could not read file %s.' % file_name) | python | def process_json_file(file_name):
try:
with open(file_name, 'rb') as fh:
json_str = fh.read().decode('utf-8')
return process_json_str(json_str)
except IOError:
logger.exception('Could not read file %s.' % file_name) | [
"def",
"process_json_file",
"(",
"file_name",
")",
":",
"try",
":",
"with",
"open",
"(",
"file_name",
",",
"'rb'",
")",
"as",
"fh",
":",
"json_str",
"=",
"fh",
".",
"read",
"(",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"return",
"process_json_str",
"("... | Return an EidosProcessor by processing the given Eidos JSON-LD file.
This function is useful if the output from Eidos is saved as a file and
needs to be processed.
Parameters
----------
file_name : str
The name of the JSON-LD file to be processed.
Returns
-------
ep : EidosProcessor
A EidosProcessor containing the extracted INDRA Statements
in its statements attribute. | [
"Return",
"an",
"EidosProcessor",
"by",
"processing",
"the",
"given",
"Eidos",
"JSON",
"-",
"LD",
"file",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/eidos/api.py#L65-L87 |
19,181 | sorgerlab/indra | indra/sources/eidos/api.py | process_json | def process_json(json_dict):
"""Return an EidosProcessor by processing a Eidos JSON-LD dict.
Parameters
----------
json_dict : dict
The JSON-LD dict to be processed.
Returns
-------
ep : EidosProcessor
A EidosProcessor containing the extracted INDRA Statements
in its statements attribute.
"""
ep = EidosProcessor(json_dict)
ep.extract_causal_relations()
ep.extract_correlations()
ep.extract_events()
return ep | python | def process_json(json_dict):
ep = EidosProcessor(json_dict)
ep.extract_causal_relations()
ep.extract_correlations()
ep.extract_events()
return ep | [
"def",
"process_json",
"(",
"json_dict",
")",
":",
"ep",
"=",
"EidosProcessor",
"(",
"json_dict",
")",
"ep",
".",
"extract_causal_relations",
"(",
")",
"ep",
".",
"extract_correlations",
"(",
")",
"ep",
".",
"extract_events",
"(",
")",
"return",
"ep"
] | Return an EidosProcessor by processing a Eidos JSON-LD dict.
Parameters
----------
json_dict : dict
The JSON-LD dict to be processed.
Returns
-------
ep : EidosProcessor
A EidosProcessor containing the extracted INDRA Statements
in its statements attribute. | [
"Return",
"an",
"EidosProcessor",
"by",
"processing",
"a",
"Eidos",
"JSON",
"-",
"LD",
"dict",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/eidos/api.py#L108-L126 |
19,182 | sorgerlab/indra | indra/databases/chembl_client.py | get_drug_inhibition_stmts | def get_drug_inhibition_stmts(drug):
"""Query ChEMBL for kinetics data given drug as Agent get back statements
Parameters
----------
drug : Agent
Agent representing drug with MESH or CHEBI grounding
Returns
-------
stmts : list of INDRA statements
INDRA statements generated by querying ChEMBL for all kinetics data of
a drug interacting with protein targets
"""
chebi_id = drug.db_refs.get('CHEBI')
mesh_id = drug.db_refs.get('MESH')
if chebi_id:
drug_chembl_id = chebi_client.get_chembl_id(chebi_id)
elif mesh_id:
drug_chembl_id = get_chembl_id(mesh_id)
else:
logger.error('Drug missing ChEBI or MESH grounding.')
return None
logger.info('Drug: %s' % (drug_chembl_id))
query_dict = {'query': 'activity',
'params': {'molecule_chembl_id': drug_chembl_id,
'limit': 10000}
}
res = send_query(query_dict)
activities = res['activities']
targ_act_dict = activities_by_target(activities)
target_chembl_ids = [x for x in targ_act_dict]
protein_targets = get_protein_targets_only(target_chembl_ids)
filtered_targ_act_dict = {t: targ_act_dict[t]
for t in [x for x in protein_targets]}
stmts = []
for target_chembl_id in filtered_targ_act_dict:
target_activity_ids = filtered_targ_act_dict[target_chembl_id]
target_activites = [x for x in activities
if x['activity_id'] in target_activity_ids]
target_upids = []
targ_comp = protein_targets[target_chembl_id]['target_components']
for t_c in targ_comp:
target_upids.append(t_c['accession'])
evidence = []
for assay in target_activites:
ev = get_evidence(assay)
if not ev:
continue
evidence.append(ev)
if len(evidence) > 0:
for target_upid in target_upids:
agent_name = uniprot_client.get_gene_name(target_upid)
target_agent = Agent(agent_name, db_refs={'UP': target_upid})
st = Inhibition(drug, target_agent, evidence=evidence)
stmts.append(st)
return stmts | python | def get_drug_inhibition_stmts(drug):
chebi_id = drug.db_refs.get('CHEBI')
mesh_id = drug.db_refs.get('MESH')
if chebi_id:
drug_chembl_id = chebi_client.get_chembl_id(chebi_id)
elif mesh_id:
drug_chembl_id = get_chembl_id(mesh_id)
else:
logger.error('Drug missing ChEBI or MESH grounding.')
return None
logger.info('Drug: %s' % (drug_chembl_id))
query_dict = {'query': 'activity',
'params': {'molecule_chembl_id': drug_chembl_id,
'limit': 10000}
}
res = send_query(query_dict)
activities = res['activities']
targ_act_dict = activities_by_target(activities)
target_chembl_ids = [x for x in targ_act_dict]
protein_targets = get_protein_targets_only(target_chembl_ids)
filtered_targ_act_dict = {t: targ_act_dict[t]
for t in [x for x in protein_targets]}
stmts = []
for target_chembl_id in filtered_targ_act_dict:
target_activity_ids = filtered_targ_act_dict[target_chembl_id]
target_activites = [x for x in activities
if x['activity_id'] in target_activity_ids]
target_upids = []
targ_comp = protein_targets[target_chembl_id]['target_components']
for t_c in targ_comp:
target_upids.append(t_c['accession'])
evidence = []
for assay in target_activites:
ev = get_evidence(assay)
if not ev:
continue
evidence.append(ev)
if len(evidence) > 0:
for target_upid in target_upids:
agent_name = uniprot_client.get_gene_name(target_upid)
target_agent = Agent(agent_name, db_refs={'UP': target_upid})
st = Inhibition(drug, target_agent, evidence=evidence)
stmts.append(st)
return stmts | [
"def",
"get_drug_inhibition_stmts",
"(",
"drug",
")",
":",
"chebi_id",
"=",
"drug",
".",
"db_refs",
".",
"get",
"(",
"'CHEBI'",
")",
"mesh_id",
"=",
"drug",
".",
"db_refs",
".",
"get",
"(",
"'MESH'",
")",
"if",
"chebi_id",
":",
"drug_chembl_id",
"=",
"ch... | Query ChEMBL for kinetics data given drug as Agent get back statements
Parameters
----------
drug : Agent
Agent representing drug with MESH or CHEBI grounding
Returns
-------
stmts : list of INDRA statements
INDRA statements generated by querying ChEMBL for all kinetics data of
a drug interacting with protein targets | [
"Query",
"ChEMBL",
"for",
"kinetics",
"data",
"given",
"drug",
"as",
"Agent",
"get",
"back",
"statements"
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/databases/chembl_client.py#L46-L102 |
19,183 | sorgerlab/indra | indra/databases/chembl_client.py | send_query | def send_query(query_dict):
"""Query ChEMBL API
Parameters
----------
query_dict : dict
'query' : string of the endpoint to query
'params' : dict of params for the query
Returns
-------
js : dict
dict parsed from json that is unique to the submitted query
"""
query = query_dict['query']
params = query_dict['params']
url = 'https://www.ebi.ac.uk/chembl/api/data/' + query + '.json'
r = requests.get(url, params=params)
r.raise_for_status()
js = r.json()
return js | python | def send_query(query_dict):
query = query_dict['query']
params = query_dict['params']
url = 'https://www.ebi.ac.uk/chembl/api/data/' + query + '.json'
r = requests.get(url, params=params)
r.raise_for_status()
js = r.json()
return js | [
"def",
"send_query",
"(",
"query_dict",
")",
":",
"query",
"=",
"query_dict",
"[",
"'query'",
"]",
"params",
"=",
"query_dict",
"[",
"'params'",
"]",
"url",
"=",
"'https://www.ebi.ac.uk/chembl/api/data/'",
"+",
"query",
"+",
"'.json'",
"r",
"=",
"requests",
".... | Query ChEMBL API
Parameters
----------
query_dict : dict
'query' : string of the endpoint to query
'params' : dict of params for the query
Returns
-------
js : dict
dict parsed from json that is unique to the submitted query | [
"Query",
"ChEMBL",
"API"
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/databases/chembl_client.py#L105-L125 |
19,184 | sorgerlab/indra | indra/databases/chembl_client.py | query_target | def query_target(target_chembl_id):
"""Query ChEMBL API target by id
Parameters
----------
target_chembl_id : str
Returns
-------
target : dict
dict parsed from json that is unique for the target
"""
query_dict = {'query': 'target',
'params': {'target_chembl_id': target_chembl_id,
'limit': 1}}
res = send_query(query_dict)
target = res['targets'][0]
return target | python | def query_target(target_chembl_id):
query_dict = {'query': 'target',
'params': {'target_chembl_id': target_chembl_id,
'limit': 1}}
res = send_query(query_dict)
target = res['targets'][0]
return target | [
"def",
"query_target",
"(",
"target_chembl_id",
")",
":",
"query_dict",
"=",
"{",
"'query'",
":",
"'target'",
",",
"'params'",
":",
"{",
"'target_chembl_id'",
":",
"target_chembl_id",
",",
"'limit'",
":",
"1",
"}",
"}",
"res",
"=",
"send_query",
"(",
"query_... | Query ChEMBL API target by id
Parameters
----------
target_chembl_id : str
Returns
-------
target : dict
dict parsed from json that is unique for the target | [
"Query",
"ChEMBL",
"API",
"target",
"by",
"id"
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/databases/chembl_client.py#L128-L145 |
19,185 | sorgerlab/indra | indra/databases/chembl_client.py | activities_by_target | def activities_by_target(activities):
"""Get back lists of activities in a dict keyed by ChEMBL target id
Parameters
----------
activities : list
response from a query returning activities for a drug
Returns
-------
targ_act_dict : dict
dictionary keyed to ChEMBL target ids with lists of activity ids
"""
targ_act_dict = defaultdict(lambda: [])
for activity in activities:
target_chembl_id = activity['target_chembl_id']
activity_id = activity['activity_id']
targ_act_dict[target_chembl_id].append(activity_id)
for target_chembl_id in targ_act_dict:
targ_act_dict[target_chembl_id] = \
list(set(targ_act_dict[target_chembl_id]))
return targ_act_dict | python | def activities_by_target(activities):
targ_act_dict = defaultdict(lambda: [])
for activity in activities:
target_chembl_id = activity['target_chembl_id']
activity_id = activity['activity_id']
targ_act_dict[target_chembl_id].append(activity_id)
for target_chembl_id in targ_act_dict:
targ_act_dict[target_chembl_id] = \
list(set(targ_act_dict[target_chembl_id]))
return targ_act_dict | [
"def",
"activities_by_target",
"(",
"activities",
")",
":",
"targ_act_dict",
"=",
"defaultdict",
"(",
"lambda",
":",
"[",
"]",
")",
"for",
"activity",
"in",
"activities",
":",
"target_chembl_id",
"=",
"activity",
"[",
"'target_chembl_id'",
"]",
"activity_id",
"=... | Get back lists of activities in a dict keyed by ChEMBL target id
Parameters
----------
activities : list
response from a query returning activities for a drug
Returns
-------
targ_act_dict : dict
dictionary keyed to ChEMBL target ids with lists of activity ids | [
"Get",
"back",
"lists",
"of",
"activities",
"in",
"a",
"dict",
"keyed",
"by",
"ChEMBL",
"target",
"id"
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/databases/chembl_client.py#L148-L169 |
19,186 | sorgerlab/indra | indra/databases/chembl_client.py | get_protein_targets_only | def get_protein_targets_only(target_chembl_ids):
"""Given list of ChEMBL target ids, return dict of SINGLE PROTEIN targets
Parameters
----------
target_chembl_ids : list
list of chembl_ids as strings
Returns
-------
protein_targets : dict
dictionary keyed to ChEMBL target ids with lists of activity ids
"""
protein_targets = {}
for target_chembl_id in target_chembl_ids:
target = query_target(target_chembl_id)
if 'SINGLE PROTEIN' in target['target_type']:
protein_targets[target_chembl_id] = target
return protein_targets | python | def get_protein_targets_only(target_chembl_ids):
protein_targets = {}
for target_chembl_id in target_chembl_ids:
target = query_target(target_chembl_id)
if 'SINGLE PROTEIN' in target['target_type']:
protein_targets[target_chembl_id] = target
return protein_targets | [
"def",
"get_protein_targets_only",
"(",
"target_chembl_ids",
")",
":",
"protein_targets",
"=",
"{",
"}",
"for",
"target_chembl_id",
"in",
"target_chembl_ids",
":",
"target",
"=",
"query_target",
"(",
"target_chembl_id",
")",
"if",
"'SINGLE PROTEIN'",
"in",
"target",
... | Given list of ChEMBL target ids, return dict of SINGLE PROTEIN targets
Parameters
----------
target_chembl_ids : list
list of chembl_ids as strings
Returns
-------
protein_targets : dict
dictionary keyed to ChEMBL target ids with lists of activity ids | [
"Given",
"list",
"of",
"ChEMBL",
"target",
"ids",
"return",
"dict",
"of",
"SINGLE",
"PROTEIN",
"targets"
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/databases/chembl_client.py#L172-L190 |
19,187 | sorgerlab/indra | indra/databases/chembl_client.py | get_evidence | def get_evidence(assay):
"""Given an activity, return an INDRA Evidence object.
Parameters
----------
assay : dict
an activity from the activities list returned by a query to the API
Returns
-------
ev : :py:class:`Evidence`
an :py:class:`Evidence` object containing the kinetics of the
"""
kin = get_kinetics(assay)
source_id = assay.get('assay_chembl_id')
if not kin:
return None
annotations = {'kinetics': kin}
chembl_doc_id = str(assay.get('document_chembl_id'))
pmid = get_pmid(chembl_doc_id)
ev = Evidence(source_api='chembl', pmid=pmid, source_id=source_id,
annotations=annotations)
return ev | python | def get_evidence(assay):
kin = get_kinetics(assay)
source_id = assay.get('assay_chembl_id')
if not kin:
return None
annotations = {'kinetics': kin}
chembl_doc_id = str(assay.get('document_chembl_id'))
pmid = get_pmid(chembl_doc_id)
ev = Evidence(source_api='chembl', pmid=pmid, source_id=source_id,
annotations=annotations)
return ev | [
"def",
"get_evidence",
"(",
"assay",
")",
":",
"kin",
"=",
"get_kinetics",
"(",
"assay",
")",
"source_id",
"=",
"assay",
".",
"get",
"(",
"'assay_chembl_id'",
")",
"if",
"not",
"kin",
":",
"return",
"None",
"annotations",
"=",
"{",
"'kinetics'",
":",
"ki... | Given an activity, return an INDRA Evidence object.
Parameters
----------
assay : dict
an activity from the activities list returned by a query to the API
Returns
-------
ev : :py:class:`Evidence`
an :py:class:`Evidence` object containing the kinetics of the | [
"Given",
"an",
"activity",
"return",
"an",
"INDRA",
"Evidence",
"object",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/databases/chembl_client.py#L193-L215 |
19,188 | sorgerlab/indra | indra/databases/chembl_client.py | get_kinetics | def get_kinetics(assay):
"""Given an activity, return its kinetics values.
Parameters
----------
assay : dict
an activity from the activities list returned by a query to the API
Returns
-------
kin : dict
dictionary of values with units keyed to value types 'IC50', 'EC50',
'INH', 'Potency', 'Kd'
"""
try:
val = float(assay.get('standard_value'))
except TypeError:
logger.warning('Invalid assay value: %s' % assay.get('standard_value'))
return None
unit = assay.get('standard_units')
if unit == 'nM':
unit_sym = 1e-9 * units.mol / units.liter
elif unit == 'uM':
unit_sym = 1e-6 * units.mol / units.liter
else:
logger.warning('Unhandled unit: %s' % unit)
return None
param_type = assay.get('standard_type')
if param_type not in ['IC50', 'EC50', 'INH', 'Potency', 'Kd']:
logger.warning('Unhandled parameter type: %s' % param_type)
logger.info(str(assay))
return None
kin = {param_type: val * unit_sym}
return kin | python | def get_kinetics(assay):
try:
val = float(assay.get('standard_value'))
except TypeError:
logger.warning('Invalid assay value: %s' % assay.get('standard_value'))
return None
unit = assay.get('standard_units')
if unit == 'nM':
unit_sym = 1e-9 * units.mol / units.liter
elif unit == 'uM':
unit_sym = 1e-6 * units.mol / units.liter
else:
logger.warning('Unhandled unit: %s' % unit)
return None
param_type = assay.get('standard_type')
if param_type not in ['IC50', 'EC50', 'INH', 'Potency', 'Kd']:
logger.warning('Unhandled parameter type: %s' % param_type)
logger.info(str(assay))
return None
kin = {param_type: val * unit_sym}
return kin | [
"def",
"get_kinetics",
"(",
"assay",
")",
":",
"try",
":",
"val",
"=",
"float",
"(",
"assay",
".",
"get",
"(",
"'standard_value'",
")",
")",
"except",
"TypeError",
":",
"logger",
".",
"warning",
"(",
"'Invalid assay value: %s'",
"%",
"assay",
".",
"get",
... | Given an activity, return its kinetics values.
Parameters
----------
assay : dict
an activity from the activities list returned by a query to the API
Returns
-------
kin : dict
dictionary of values with units keyed to value types 'IC50', 'EC50',
'INH', 'Potency', 'Kd' | [
"Given",
"an",
"activity",
"return",
"its",
"kinetics",
"values",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/databases/chembl_client.py#L218-L251 |
19,189 | sorgerlab/indra | indra/databases/chembl_client.py | get_pmid | def get_pmid(doc_id):
"""Get PMID from document_chembl_id
Parameters
----------
doc_id : str
Returns
-------
pmid : str
"""
url_pmid = 'https://www.ebi.ac.uk/chembl/api/data/document.json'
params = {'document_chembl_id': doc_id}
res = requests.get(url_pmid, params=params)
js = res.json()
pmid = str(js['documents'][0]['pubmed_id'])
return pmid | python | def get_pmid(doc_id):
url_pmid = 'https://www.ebi.ac.uk/chembl/api/data/document.json'
params = {'document_chembl_id': doc_id}
res = requests.get(url_pmid, params=params)
js = res.json()
pmid = str(js['documents'][0]['pubmed_id'])
return pmid | [
"def",
"get_pmid",
"(",
"doc_id",
")",
":",
"url_pmid",
"=",
"'https://www.ebi.ac.uk/chembl/api/data/document.json'",
"params",
"=",
"{",
"'document_chembl_id'",
":",
"doc_id",
"}",
"res",
"=",
"requests",
".",
"get",
"(",
"url_pmid",
",",
"params",
"=",
"params",... | Get PMID from document_chembl_id
Parameters
----------
doc_id : str
Returns
-------
pmid : str | [
"Get",
"PMID",
"from",
"document_chembl_id"
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/databases/chembl_client.py#L254-L270 |
19,190 | sorgerlab/indra | indra/databases/chembl_client.py | get_target_chemblid | def get_target_chemblid(target_upid):
"""Get ChEMBL ID from UniProt upid
Parameters
----------
target_upid : str
Returns
-------
target_chembl_id : str
"""
url = 'https://www.ebi.ac.uk/chembl/api/data/target.json'
params = {'target_components__accession': target_upid}
r = requests.get(url, params=params)
r.raise_for_status()
js = r.json()
target_chemblid = js['targets'][0]['target_chembl_id']
return target_chemblid | python | def get_target_chemblid(target_upid):
url = 'https://www.ebi.ac.uk/chembl/api/data/target.json'
params = {'target_components__accession': target_upid}
r = requests.get(url, params=params)
r.raise_for_status()
js = r.json()
target_chemblid = js['targets'][0]['target_chembl_id']
return target_chemblid | [
"def",
"get_target_chemblid",
"(",
"target_upid",
")",
":",
"url",
"=",
"'https://www.ebi.ac.uk/chembl/api/data/target.json'",
"params",
"=",
"{",
"'target_components__accession'",
":",
"target_upid",
"}",
"r",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"params",
... | Get ChEMBL ID from UniProt upid
Parameters
----------
target_upid : str
Returns
-------
target_chembl_id : str | [
"Get",
"ChEMBL",
"ID",
"from",
"UniProt",
"upid"
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/databases/chembl_client.py#L273-L290 |
19,191 | sorgerlab/indra | indra/databases/chembl_client.py | get_mesh_id | def get_mesh_id(nlm_mesh):
"""Get MESH ID from NLM MESH
Parameters
----------
nlm_mesh : str
Returns
-------
mesh_id : str
"""
url_nlm2mesh = 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi'
params = {'db': 'mesh', 'term': nlm_mesh, 'retmode': 'JSON'}
r = requests.get(url_nlm2mesh, params=params)
res = r.json()
mesh_id = res['esearchresult']['idlist'][0]
return mesh_id | python | def get_mesh_id(nlm_mesh):
url_nlm2mesh = 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi'
params = {'db': 'mesh', 'term': nlm_mesh, 'retmode': 'JSON'}
r = requests.get(url_nlm2mesh, params=params)
res = r.json()
mesh_id = res['esearchresult']['idlist'][0]
return mesh_id | [
"def",
"get_mesh_id",
"(",
"nlm_mesh",
")",
":",
"url_nlm2mesh",
"=",
"'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi'",
"params",
"=",
"{",
"'db'",
":",
"'mesh'",
",",
"'term'",
":",
"nlm_mesh",
",",
"'retmode'",
":",
"'JSON'",
"}",
"r",
"=",
"request... | Get MESH ID from NLM MESH
Parameters
----------
nlm_mesh : str
Returns
-------
mesh_id : str | [
"Get",
"MESH",
"ID",
"from",
"NLM",
"MESH"
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/databases/chembl_client.py#L293-L309 |
19,192 | sorgerlab/indra | indra/databases/chembl_client.py | get_pcid | def get_pcid(mesh_id):
"""Get PC ID from MESH ID
Parameters
----------
mesh : str
Returns
-------
pcid : str
"""
url_mesh2pcid = 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/elink.fcgi'
params = {'dbfrom': 'mesh', 'id': mesh_id,
'db': 'pccompound', 'retmode': 'JSON'}
r = requests.get(url_mesh2pcid, params=params)
res = r.json()
pcid = res['linksets'][0]['linksetdbs'][0]['links'][0]
return pcid | python | def get_pcid(mesh_id):
url_mesh2pcid = 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/elink.fcgi'
params = {'dbfrom': 'mesh', 'id': mesh_id,
'db': 'pccompound', 'retmode': 'JSON'}
r = requests.get(url_mesh2pcid, params=params)
res = r.json()
pcid = res['linksets'][0]['linksetdbs'][0]['links'][0]
return pcid | [
"def",
"get_pcid",
"(",
"mesh_id",
")",
":",
"url_mesh2pcid",
"=",
"'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/elink.fcgi'",
"params",
"=",
"{",
"'dbfrom'",
":",
"'mesh'",
",",
"'id'",
":",
"mesh_id",
",",
"'db'",
":",
"'pccompound'",
",",
"'retmode'",
":",
"'J... | Get PC ID from MESH ID
Parameters
----------
mesh : str
Returns
-------
pcid : str | [
"Get",
"PC",
"ID",
"from",
"MESH",
"ID"
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/databases/chembl_client.py#L312-L329 |
19,193 | sorgerlab/indra | indra/databases/chembl_client.py | get_chembl_id | def get_chembl_id(nlm_mesh):
"""Get ChEMBL ID from NLM MESH
Parameters
----------
nlm_mesh : str
Returns
-------
chembl_id : str
"""
mesh_id = get_mesh_id(nlm_mesh)
pcid = get_pcid(mesh_id)
url_mesh2pcid = 'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/' + \
'cid/%s/synonyms/JSON' % pcid
r = requests.get(url_mesh2pcid)
res = r.json()
synonyms = res['InformationList']['Information'][0]['Synonym']
chembl_id = [syn for syn in synonyms
if 'CHEMBL' in syn and 'SCHEMBL' not in syn][0]
return chembl_id | python | def get_chembl_id(nlm_mesh):
mesh_id = get_mesh_id(nlm_mesh)
pcid = get_pcid(mesh_id)
url_mesh2pcid = 'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/' + \
'cid/%s/synonyms/JSON' % pcid
r = requests.get(url_mesh2pcid)
res = r.json()
synonyms = res['InformationList']['Information'][0]['Synonym']
chembl_id = [syn for syn in synonyms
if 'CHEMBL' in syn and 'SCHEMBL' not in syn][0]
return chembl_id | [
"def",
"get_chembl_id",
"(",
"nlm_mesh",
")",
":",
"mesh_id",
"=",
"get_mesh_id",
"(",
"nlm_mesh",
")",
"pcid",
"=",
"get_pcid",
"(",
"mesh_id",
")",
"url_mesh2pcid",
"=",
"'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/'",
"+",
"'cid/%s/synonyms/JSON'",
"%",
"pc... | Get ChEMBL ID from NLM MESH
Parameters
----------
nlm_mesh : str
Returns
-------
chembl_id : str | [
"Get",
"ChEMBL",
"ID",
"from",
"NLM",
"MESH"
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/databases/chembl_client.py#L332-L352 |
19,194 | sorgerlab/indra | indra/sources/geneways/find_full_text_sentence.py | FullTextMention.get_sentences | def get_sentences(self, root_element, block_tags):
"""Returns a list of plain-text sentences by iterating through
XML tags except for those listed in block_tags."""
sentences = []
for element in root_element:
if not self.any_ends_with(block_tags, element.tag):
# tag not in block_tags
if element.text is not None and not re.match('^\s*$',
element.text):
sentences.extend(self.sentence_tokenize(element.text))
sentences.extend(self.get_sentences(element, block_tags))
f = open('sentence_debug.txt', 'w')
for s in sentences:
f.write(s.lower() + '\n')
f.close()
return sentences | python | def get_sentences(self, root_element, block_tags):
sentences = []
for element in root_element:
if not self.any_ends_with(block_tags, element.tag):
# tag not in block_tags
if element.text is not None and not re.match('^\s*$',
element.text):
sentences.extend(self.sentence_tokenize(element.text))
sentences.extend(self.get_sentences(element, block_tags))
f = open('sentence_debug.txt', 'w')
for s in sentences:
f.write(s.lower() + '\n')
f.close()
return sentences | [
"def",
"get_sentences",
"(",
"self",
",",
"root_element",
",",
"block_tags",
")",
":",
"sentences",
"=",
"[",
"]",
"for",
"element",
"in",
"root_element",
":",
"if",
"not",
"self",
".",
"any_ends_with",
"(",
"block_tags",
",",
"element",
".",
"tag",
")",
... | Returns a list of plain-text sentences by iterating through
XML tags except for those listed in block_tags. | [
"Returns",
"a",
"list",
"of",
"plain",
"-",
"text",
"sentences",
"by",
"iterating",
"through",
"XML",
"tags",
"except",
"for",
"those",
"listed",
"in",
"block_tags",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/geneways/find_full_text_sentence.py#L33-L49 |
19,195 | sorgerlab/indra | indra/sources/geneways/find_full_text_sentence.py | FullTextMention.any_ends_with | def any_ends_with(self, string_list, pattern):
"""Returns true iff one of the strings in string_list ends in
pattern."""
try:
s_base = basestring
except:
s_base = str
is_string = isinstance(pattern, s_base)
if not is_string:
return False
for s in string_list:
if pattern.endswith(s):
return True
return False | python | def any_ends_with(self, string_list, pattern):
try:
s_base = basestring
except:
s_base = str
is_string = isinstance(pattern, s_base)
if not is_string:
return False
for s in string_list:
if pattern.endswith(s):
return True
return False | [
"def",
"any_ends_with",
"(",
"self",
",",
"string_list",
",",
"pattern",
")",
":",
"try",
":",
"s_base",
"=",
"basestring",
"except",
":",
"s_base",
"=",
"str",
"is_string",
"=",
"isinstance",
"(",
"pattern",
",",
"s_base",
")",
"if",
"not",
"is_string",
... | Returns true iff one of the strings in string_list ends in
pattern. | [
"Returns",
"true",
"iff",
"one",
"of",
"the",
"strings",
"in",
"string_list",
"ends",
"in",
"pattern",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/geneways/find_full_text_sentence.py#L51-L66 |
19,196 | sorgerlab/indra | indra/sources/geneways/find_full_text_sentence.py | FullTextMention.get_tag_names | def get_tag_names(self):
"""Returns the set of tag names present in the XML."""
root = etree.fromstring(self.xml_full_text.encode('utf-8'))
return self.get_children_tag_names(root) | python | def get_tag_names(self):
root = etree.fromstring(self.xml_full_text.encode('utf-8'))
return self.get_children_tag_names(root) | [
"def",
"get_tag_names",
"(",
"self",
")",
":",
"root",
"=",
"etree",
".",
"fromstring",
"(",
"self",
".",
"xml_full_text",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"return",
"self",
".",
"get_children_tag_names",
"(",
"root",
")"
] | Returns the set of tag names present in the XML. | [
"Returns",
"the",
"set",
"of",
"tag",
"names",
"present",
"in",
"the",
"XML",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/geneways/find_full_text_sentence.py#L120-L123 |
19,197 | sorgerlab/indra | indra/sources/geneways/find_full_text_sentence.py | FullTextMention.get_children_tag_names | def get_children_tag_names(self, xml_element):
"""Returns all tag names of xml element and its children."""
tags = set()
tags.add(self.remove_namespace_from_tag(xml_element.tag))
for element in xml_element.iter(tag=etree.Element):
if element != xml_element:
new_tags = self.get_children_tag_names(element)
if new_tags is not None:
tags.update(new_tags)
return tags | python | def get_children_tag_names(self, xml_element):
tags = set()
tags.add(self.remove_namespace_from_tag(xml_element.tag))
for element in xml_element.iter(tag=etree.Element):
if element != xml_element:
new_tags = self.get_children_tag_names(element)
if new_tags is not None:
tags.update(new_tags)
return tags | [
"def",
"get_children_tag_names",
"(",
"self",
",",
"xml_element",
")",
":",
"tags",
"=",
"set",
"(",
")",
"tags",
".",
"add",
"(",
"self",
".",
"remove_namespace_from_tag",
"(",
"xml_element",
".",
"tag",
")",
")",
"for",
"element",
"in",
"xml_element",
".... | Returns all tag names of xml element and its children. | [
"Returns",
"all",
"tag",
"names",
"of",
"xml",
"element",
"and",
"its",
"children",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/geneways/find_full_text_sentence.py#L125-L135 |
19,198 | sorgerlab/indra | indra/sources/geneways/find_full_text_sentence.py | FullTextMention.string_matches_sans_whitespace | def string_matches_sans_whitespace(self, str1, str2_fuzzy_whitespace):
"""Check if two strings match, modulo their whitespace."""
str2_fuzzy_whitespace = re.sub('\s+', '\s*', str2_fuzzy_whitespace)
return re.search(str2_fuzzy_whitespace, str1) is not None | python | def string_matches_sans_whitespace(self, str1, str2_fuzzy_whitespace):
str2_fuzzy_whitespace = re.sub('\s+', '\s*', str2_fuzzy_whitespace)
return re.search(str2_fuzzy_whitespace, str1) is not None | [
"def",
"string_matches_sans_whitespace",
"(",
"self",
",",
"str1",
",",
"str2_fuzzy_whitespace",
")",
":",
"str2_fuzzy_whitespace",
"=",
"re",
".",
"sub",
"(",
"'\\s+'",
",",
"'\\s*'",
",",
"str2_fuzzy_whitespace",
")",
"return",
"re",
".",
"search",
"(",
"str2_... | Check if two strings match, modulo their whitespace. | [
"Check",
"if",
"two",
"strings",
"match",
"modulo",
"their",
"whitespace",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/geneways/find_full_text_sentence.py#L137-L140 |
19,199 | sorgerlab/indra | indra/sources/geneways/find_full_text_sentence.py | FullTextMention.sentence_matches | def sentence_matches(self, sentence_text):
"""Returns true iff the sentence contains this mention's upstream
and downstream participants, and if one of the stemmed verbs in
the sentence is the same as the stemmed action type."""
has_upstream = False
has_downstream = False
has_verb = False
# Get the first word of the action type and assume this is the verb
# (Ex. get depends for depends on)
actiontype_words = word_tokenize(self.mention.actiontype)
actiontype_verb_stemmed = stem(actiontype_words[0])
words = word_tokenize(sentence_text)
if self.string_matches_sans_whitespace(sentence_text.lower(),
self.mention.upstream.lower()):
has_upstream = True
if self.string_matches_sans_whitespace(sentence_text.lower(),
self.mention.downstream.lower()):
has_downstream = True
for word in words:
if actiontype_verb_stemmed == stem(word):
has_verb = True
return has_upstream and has_downstream and has_verb | python | def sentence_matches(self, sentence_text):
has_upstream = False
has_downstream = False
has_verb = False
# Get the first word of the action type and assume this is the verb
# (Ex. get depends for depends on)
actiontype_words = word_tokenize(self.mention.actiontype)
actiontype_verb_stemmed = stem(actiontype_words[0])
words = word_tokenize(sentence_text)
if self.string_matches_sans_whitespace(sentence_text.lower(),
self.mention.upstream.lower()):
has_upstream = True
if self.string_matches_sans_whitespace(sentence_text.lower(),
self.mention.downstream.lower()):
has_downstream = True
for word in words:
if actiontype_verb_stemmed == stem(word):
has_verb = True
return has_upstream and has_downstream and has_verb | [
"def",
"sentence_matches",
"(",
"self",
",",
"sentence_text",
")",
":",
"has_upstream",
"=",
"False",
"has_downstream",
"=",
"False",
"has_verb",
"=",
"False",
"# Get the first word of the action type and assume this is the verb",
"# (Ex. get depends for depends on)",
"actionty... | Returns true iff the sentence contains this mention's upstream
and downstream participants, and if one of the stemmed verbs in
the sentence is the same as the stemmed action type. | [
"Returns",
"true",
"iff",
"the",
"sentence",
"contains",
"this",
"mention",
"s",
"upstream",
"and",
"downstream",
"participants",
"and",
"if",
"one",
"of",
"the",
"stemmed",
"verbs",
"in",
"the",
"sentence",
"is",
"the",
"same",
"as",
"the",
"stemmed",
"acti... | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/geneways/find_full_text_sentence.py#L142-L169 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.