Code
stringlengths 103
85.9k
| Summary
listlengths 0
94
|
---|---|
Please provide a description of the function:def save_dot(self, file_name='graph.dot'):
s = self.get_string()
with open(file_name, 'wt') as fh:
fh.write(s) | [
"Save the graph in a graphviz dot file.\n\n Parameters\n ----------\n file_name : Optional[str]\n The name of the file to save the graph dot string to.\n "
]
|
Please provide a description of the function:def save_pdf(self, file_name='graph.pdf', prog='dot'):
self.graph.draw(file_name, prog=prog) | [
"Draw the graph and save as an image or pdf file.\n\n Parameters\n ----------\n file_name : Optional[str]\n The name of the file to save the graph as. Default: graph.pdf\n prog : Optional[str]\n The graphviz program to use for graph layout. Default: dot\n "
]
|
Please provide a description of the function:def _add_edge(self, source, target, **kwargs):
# Start with default edge properties
edge_properties = self.edge_properties
# Overwrite ones that are given in function call explicitly
for k, v in kwargs.items():
edge_properties[k] = v
self.graph.add_edge(source, target, **edge_properties) | [
"Add an edge to the graph."
]
|
Please provide a description of the function:def _add_node(self, agent):
if agent is None:
return
node_label = _get_node_label(agent)
if isinstance(agent, Agent) and agent.bound_conditions:
bound_agents = [bc.agent for bc in agent.bound_conditions if
bc.is_bound]
if bound_agents:
bound_names = [_get_node_label(a) for a in bound_agents]
node_label = _get_node_label(agent) + '/' + \
'/'.join(bound_names)
self._complex_nodes.append([agent] + bound_agents)
else:
node_label = _get_node_label(agent)
node_key = _get_node_key(agent)
if node_key in self.existing_nodes:
return
self.existing_nodes.append(node_key)
self.graph.add_node(node_key,
label=node_label,
**self.node_properties) | [
"Add an Agent as a node to the graph."
]
|
Please provide a description of the function:def _add_stmt_edge(self, stmt):
# Skip statements with None in the subject position
source = _get_node_key(stmt.agent_list()[0])
target = _get_node_key(stmt.agent_list()[1])
edge_key = (source, target, stmt.__class__.__name__)
if edge_key in self.existing_edges:
return
self.existing_edges.append(edge_key)
if isinstance(stmt, RemoveModification) or \
isinstance(stmt, Inhibition) or \
isinstance(stmt, DecreaseAmount) or \
isinstance(stmt, Gap) or \
(isinstance(stmt, Influence) and stmt.overall_polarity() == -1):
color = '#ff0000'
else:
color = '#000000'
params = {'color': color,
'arrowhead': 'normal',
'dir': 'forward'}
self._add_edge(source, target, **params) | [
"Assemble a Modification statement."
]
|
Please provide a description of the function:def _add_complex(self, members, is_association=False):
params = {'color': '#0000ff',
'arrowhead': 'dot',
'arrowtail': 'dot',
'dir': 'both'}
for m1, m2 in itertools.combinations(members, 2):
if self._has_complex_node(m1, m2):
continue
if is_association:
m1_key = _get_node_key(m1.concept)
m2_key = _get_node_key(m2.concept)
else:
m1_key = _get_node_key(m1)
m2_key = _get_node_key(m2)
edge_key = (set([m1_key, m2_key]), 'complex')
if edge_key in self.existing_edges:
return
self.existing_edges.append(edge_key)
self._add_edge(m1_key, m2_key, **params) | [
"Assemble a Complex statement."
]
|
Please provide a description of the function:def process_from_file(signor_data_file, signor_complexes_file=None):
# Get generator over the CSV file
data_iter = read_unicode_csv(signor_data_file, delimiter=';', skiprows=1)
complexes_iter = None
if signor_complexes_file:
complexes_iter = read_unicode_csv(signor_complexes_file, delimiter=';',
skiprows=1)
else:
logger.warning('Signor complex mapping file not provided, Statements '
'involving complexes will not be expanded to members.')
return _processor_from_data(data_iter, complexes_iter) | [
"Process Signor interaction data from CSV files.\n\n Parameters\n ----------\n signor_data_file : str\n Path to the Signor interaction data file in CSV format.\n signor_complexes_file : str\n Path to the Signor complexes data in CSV format. If unspecified,\n Signor complexes will not be expanded to their constitutents.\n\n Returns\n -------\n indra.sources.signor.SignorProcessor\n SignorProcessor containing Statements extracted from the Signor data.\n "
]
|
Please provide a description of the function:def _handle_response(res, delimiter):
if res.status_code == 200:
# Python 2 -- csv.reader will need bytes
if sys.version_info[0] < 3:
csv_io = BytesIO(res.content)
# Python 3 -- csv.reader needs str
else:
csv_io = StringIO(res.text)
data_iter = read_unicode_csv_fileobj(csv_io, delimiter=delimiter,
skiprows=1)
else:
raise Exception('Could not download Signor data.')
return data_iter | [
"Get an iterator over the CSV data from the response."
]
|
Please provide a description of the function:def get_protein_expression(gene_names, cell_types):
A = 0.2438361
B = 3.0957627
mrna_amounts = cbio_client.get_ccle_mrna(gene_names, cell_types)
protein_amounts = copy(mrna_amounts)
for cell_type in cell_types:
amounts = mrna_amounts.get(cell_type)
if amounts is None:
continue
for gene_name, amount in amounts.items():
if amount is not None:
protein_amount = 10**(A * amount + B)
protein_amounts[cell_type][gene_name] = protein_amount
return protein_amounts | [
"Return the protein expression levels of genes in cell types.\n\n Parameters\n ----------\n gene_names : list\n HGNC gene symbols for which expression levels are queried.\n cell_types : list\n List of cell type names in which expression levels are queried.\n The cell type names follow the CCLE database conventions.\n\n Example: LOXIMVI_SKIN, BT20_BREAST\n\n Returns\n -------\n res : dict[dict[float]]\n A dictionary keyed by cell line, which contains another dictionary\n that is keyed by gene name, with estimated protein amounts as values.\n "
]
|
Please provide a description of the function:def get_aspect(cx, aspect_name):
if isinstance(cx, dict):
return cx.get(aspect_name)
for entry in cx:
if list(entry.keys())[0] == aspect_name:
return entry[aspect_name] | [
"Return an aspect given the name of the aspect"
]
|
Please provide a description of the function:def classify_nodes(graph, hub):
node_stats = defaultdict(lambda: defaultdict(list))
for u, v, data in graph.edges(data=True):
# This means the node is downstream of the hub
if hub == u:
h, o = u, v
if data['i'] != 'Complex':
node_stats[o]['up'].append(-1)
else:
node_stats[o]['up'].append(0)
# This means the node is upstream of the hub
elif hub == v:
h, o = v, u
if data['i'] != 'Complex':
node_stats[o]['up'].append(1)
else:
node_stats[o]['up'].append(0)
else:
continue
node_stats[o]['interaction'].append(edge_type_to_class(data['i']))
node_classes = {}
for node_id, stats in node_stats.items():
up = max(set(stats['up']), key=stats['up'].count)
# Special case: if up is not 0 then we should exclude complexes
# from the edge_type states so that we don't end up with
# (-1, complex, ...) or (1, complex, ...) as the node class
interactions = [i for i in stats['interaction'] if
not (up != 0 and i == 'complex')]
edge_type = max(set(interactions), key=interactions.count)
node_type = graph.nodes[node_id]['type']
node_classes[node_id] = (up, edge_type, node_type)
return node_classes | [
"Classify each node based on its type and relationship to the hub."
]
|
Please provide a description of the function:def get_attributes(aspect, id):
attributes = {}
for entry in aspect:
if entry['po'] == id:
attributes[entry['n']] = entry['v']
return attributes | [
"Return the attributes pointing to a given ID in a given aspect."
]
|
Please provide a description of the function:def cx_to_networkx(cx):
graph = networkx.MultiDiGraph()
for node_entry in get_aspect(cx, 'nodes'):
id = node_entry['@id']
attrs = get_attributes(get_aspect(cx, 'nodeAttributes'), id)
attrs['n'] = node_entry['n']
graph.add_node(id, **attrs)
for edge_entry in get_aspect(cx, 'edges'):
id = edge_entry['@id']
attrs = get_attributes(get_aspect(cx, 'edgeAttributes'), id)
attrs['i'] = edge_entry['i']
graph.add_edge(edge_entry['s'], edge_entry['t'], key=id, **attrs)
return graph | [
"Return a MultiDiGraph representation of a CX network."
]
|
Please provide a description of the function:def get_quadrant_from_class(node_class):
up, edge_type, _ = node_class
if up == 0:
return 0 if random.random() < 0.5 else 7
mappings = {(-1, 'modification'): 1,
(-1, 'amount'): 2,
(-1, 'activity'): 3,
(1, 'activity'): 4,
(1, 'amount'): 5,
(1, 'modification'): 6}
return mappings[(up, edge_type)] | [
"Return the ID of the segment of the plane corresponding to a class."
]
|
Please provide a description of the function:def get_coordinates(node_class):
quadrant_size = (2 * math.pi / 8.0)
quadrant = get_quadrant_from_class(node_class)
begin_angle = quadrant_size * quadrant
r = 200 + 800*random.random()
alpha = begin_angle + random.random() * quadrant_size
x = r * math.cos(alpha)
y = r * math.sin(alpha)
return x, y | [
"Generate coordinates for a node in a given class."
]
|
Please provide a description of the function:def get_layout_aspect(hub, node_classes):
aspect = [{'node': hub, 'x': 0.0, 'y': 0.0}]
for node, node_class in node_classes.items():
if node == hub:
continue
x, y = get_coordinates(node_class)
aspect.append({'node': node, 'x': x, 'y': y})
return aspect | [
"Get the full layout aspect with coordinates for each node."
]
|
Please provide a description of the function:def get_node_by_name(graph, name):
for id, attrs in graph.nodes(data=True):
if attrs['n'] == name:
return id | [
"Return a node ID given its name."
]
|
Please provide a description of the function:def add_semantic_hub_layout(cx, hub):
graph = cx_to_networkx(cx)
hub_node = get_node_by_name(graph, hub)
node_classes = classify_nodes(graph, hub_node)
layout_aspect = get_layout_aspect(hub_node, node_classes)
cx['cartesianLayout'] = layout_aspect | [
"Attach a layout aspect to a CX network given a hub node."
]
|
Please provide a description of the function:def get_metadata(doi):
url = crossref_url + 'works/' + doi
res = requests.get(url)
if res.status_code != 200:
logger.info('Could not get CrossRef metadata for DOI %s, code %d' %
(doi, res.status_code))
return None
raw_message = res.json()
metadata = raw_message.get('message')
return metadata | [
"Returns the metadata of an article given its DOI from CrossRef\n as a JSON dict"
]
|
Please provide a description of the function:def get_fulltext_links(doi):
metadata = get_metadata(doi)
if metadata is None:
return None
links = metadata.get('link')
return links | [
"Return a list of links to the full text of an article given its DOI.\n Each list entry is a dictionary with keys:\n - URL: the URL to the full text\n - content-type: e.g. text/xml or text/plain\n - content-version\n - intended-application: e.g. text-mining\n "
]
|
Please provide a description of the function:def doi_query(pmid, search_limit=10):
# Get article metadata from PubMed
pubmed_meta_dict = pubmed_client.get_metadata_for_ids([pmid],
get_issns_from_nlm=True)
if pubmed_meta_dict is None or pubmed_meta_dict.get(pmid) is None:
logger.warning('No metadata found in Pubmed for PMID%s' % pmid)
return None
# The test above ensures we've got this now
pubmed_meta = pubmed_meta_dict[pmid]
# Check if we already got a DOI from Pubmed itself!
if pubmed_meta.get('doi'):
return pubmed_meta.get('doi')
# Check for the title, which we'll need for the CrossRef search
pm_article_title = pubmed_meta.get('title')
if pm_article_title is None:
logger.warning('No article title found in Pubmed for PMID%s' % pmid)
return None
# Get the ISSN list
pm_issn_list = pubmed_meta.get('issn_list')
if not pm_issn_list:
logger.warning('No ISSNs found in Pubmed for PMID%s' % pmid)
return None
# Get the page number
pm_page = pubmed_meta.get('page')
if not pm_page:
logger.debug('No page number found in Pubmed for PMID%s' % pmid)
return None
# Now query CrossRef using the title we've got
url = crossref_search_url
params = {'q': pm_article_title, 'sort': 'score'}
try:
res = requests.get(crossref_search_url, params)
except requests.exceptions.ConnectionError as e:
logger.error('CrossRef service could not be reached.')
logger.error(e)
return None
except Exception as e:
logger.error('Error accessing CrossRef service: %s' % str(e))
return None
if res.status_code != 200:
logger.info('PMID%s: no search results from CrossRef, code %d' %
(pmid, res.status_code))
return None
raw_message = res.json()
mapped_doi = None
# Iterate over the search results, looking up XREF metadata
for result_ix, result in enumerate(raw_message):
if result_ix > search_limit:
logger.info('PMID%s: No match found within first %s results, '
'giving up!' % (pmid, search_limit))
break
xref_doi_url = result['doi']
# Strip the URL prefix off of the DOI
m = re.match('^http://dx.doi.org/(.*)$', xref_doi_url)
xref_doi = m.groups()[0]
# Get the XREF metadata using the DOI
xref_meta = get_metadata(xref_doi)
if xref_meta is None:
continue
xref_issn_list = xref_meta.get('ISSN')
xref_page = xref_meta.get('page')
# If there's no ISSN info for this article, skip to the next result
if not xref_issn_list:
logger.debug('No ISSN found for DOI %s, skipping' % xref_doi_url)
continue
# If there's no page info for this article, skip to the next result
if not xref_page:
logger.debug('No page number found for DOI %s, skipping' %
xref_doi_url)
continue
# Now check for an ISSN match by looking for the set intersection
# between the Pubmed ISSN list and the CrossRef ISSN list.
matching_issns = set(pm_issn_list).intersection(set(xref_issn_list))
# Before comparing page numbers, regularize the page numbers a bit.
# Note that we only compare the first page number, since frequently
# the final page number will simply be missing in one of the data
# sources. We also canonicalize page numbers of the form '14E' to
# 'E14' (which is the format used by Pubmed).
pm_start_page = pm_page.split('-')[0].upper()
xr_start_page = xref_page.split('-')[0].upper()
if xr_start_page.endswith('E'):
xr_start_page = 'E' + xr_start_page[:-1]
# Now compare the ISSN list and page numbers
if matching_issns and pm_start_page == xr_start_page:
# We found a match!
mapped_doi = xref_doi
break
# Otherwise, keep looking through the results...
# Return a DOI, or None if we didn't find one that met our matching
# criteria
return mapped_doi | [
"Get the DOI for a PMID by matching CrossRef and Pubmed metadata.\n\n Searches CrossRef using the article title and then accepts search hits only\n if they have a matching journal ISSN and page number with what is obtained\n from the Pubmed database.\n "
]
|
Please provide a description of the function:def get_agent_rule_str(agent):
rule_str_list = [_n(agent.name)]
# If it's a molecular agent
if isinstance(agent, ist.Agent):
for mod in agent.mods:
mstr = abbrevs[mod.mod_type]
if mod.residue is not None:
mstr += mod.residue
if mod.position is not None:
mstr += mod.position
rule_str_list.append('%s' % mstr)
for mut in agent.mutations:
res_from = mut.residue_from if mut.residue_from else 'mut'
res_to = mut.residue_to if mut.residue_to else 'X'
if mut.position is None:
mut_site_name = res_from
else:
mut_site_name = res_from + mut.position
mstr = mut_site_name + res_to
rule_str_list.append(mstr)
if agent.bound_conditions:
for b in agent.bound_conditions:
if b.is_bound:
rule_str_list.append(_n(b.agent.name))
else:
rule_str_list.append('n' + _n(b.agent.name))
if agent.location is not None:
rule_str_list.append(_n(agent.location))
if agent.activity is not None:
if agent.activity.is_active:
rule_str_list.append(agent.activity.activity_type[:3])
else:
rule_str_list.append(agent.activity.activity_type[:3] + '_inact')
rule_str = '_'.join(rule_str_list)
return rule_str | [
"Construct a string from an Agent as part of a PySB rule name."
]
|
Please provide a description of the function:def add_rule_to_model(model, rule, annotations=None):
try:
model.add_component(rule)
# If the rule was actually added, also add the annotations
if annotations:
model.annotations += annotations
# If this rule is already in the model, issue a warning and continue
except ComponentDuplicateNameError:
msg = "Rule %s already in model! Skipping." % rule.name
logger.debug(msg) | [
"Add a Rule to a PySB model and handle duplicate component errors."
]
|
Please provide a description of the function:def get_create_parameter(model, param):
norm_name = _n(param.name)
parameter = model.parameters.get(norm_name)
if not param.unique and parameter is not None:
return parameter
if param.unique:
pnum = 1
while True:
pname = norm_name + '_%d' % pnum
if model.parameters.get(pname) is None:
break
pnum += 1
else:
pname = norm_name
parameter = Parameter(pname, param.value)
model.add_component(parameter)
return parameter | [
"Return parameter with given name, creating it if needed.\n\n If unique is false and the parameter exists, the value is not changed; if\n it does not exist, it will be created. If unique is true then upon conflict\n a number is added to the end of the parameter name.\n\n Parameters\n ----------\n model : pysb.Model\n The model to add the parameter to\n param : Param\n An assembly parameter object\n "
]
|
Please provide a description of the function:def get_uncond_agent(agent):
agent_uncond = ist.Agent(_n(agent.name), mutations=agent.mutations)
return agent_uncond | [
"Construct the unconditional state of an Agent.\n\n The unconditional Agent is a copy of the original agent but\n without any bound conditions and modification conditions.\n Mutation conditions, however, are preserved since they are static.\n "
]
|
Please provide a description of the function:def grounded_monomer_patterns(model, agent, ignore_activities=False):
# If it's not a molecular agent
if not isinstance(agent, ist.Agent):
monomer = model.monomers.get(agent.name)
if not monomer:
return
yield monomer()
# Iterate over all model annotations to identify the monomer associated
# with this agent
monomer = None
for ann in model.annotations:
if monomer:
break
if not ann.predicate == 'is':
continue
if not isinstance(ann.subject, Monomer):
continue
(ns, id) = parse_identifiers_url(ann.object)
if ns is None and id is None:
continue
# We now have an identifiers.org namespace/ID for a given monomer;
# we check to see if there is a matching identifier in the db_refs
# for this agent
for db_ns, db_id in agent.db_refs.items():
# We've found a match! Return first match
# FIXME Could also update this to check for alternative
# FIXME matches, or make sure that all grounding IDs match,
# FIXME etc.
if db_ns == ns and db_id == id:
monomer = ann.subject
break
# We looked at all the annotations in the model and didn't find a
# match
if monomer is None:
logger.info('No monomer found corresponding to agent %s' % agent)
return
# Now that we have a monomer for the agent, look for site/state
# combinations corresponding to the state of the agent. For every one of
# the modifications specified in the agent signature, check to see if it
# can be satisfied based on the agent's annotations. For every one we find
# that is consistent, we yield it--there may be more than one.
# FIXME
# Create a list of tuples, each one representing the site conditions
# that can satisfy a particular agent condition. Each entry in the list
# will contain a list of dicts associated with a particular mod/activity
# condition. Each dict will represent a site/state combination satisfying
# the constraints imposed by that mod/activity condition.
sc_list = []
for mod in agent.mods:
# Find all site/state combinations that have the appropriate
# modification type
# As we iterate, build up a dict identifying the annotations of
# particular sites
mod_sites = {}
res_sites = set([])
pos_sites = set([])
for ann in monomer.site_annotations:
# Don't forget to handle Nones!
if ann.predicate == 'is_modification' and \
ann.object == mod.mod_type:
site_state = ann.subject
assert isinstance(site_state, tuple)
assert len(site_state) == 2
mod_sites[site_state[0]] = site_state[1]
elif ann.predicate == 'is_residue' and \
ann.object == mod.residue:
res_sites.add(ann.subject)
elif ann.predicate == 'is_position' and \
ann.object == mod.position:
pos_sites.add(ann.subject)
# If the residue field of the agent is specified,
viable_sites = set(mod_sites.keys())
if mod.residue is not None:
viable_sites = viable_sites.intersection(res_sites)
if mod.position is not None:
viable_sites = viable_sites.intersection(pos_sites)
# If there are no viable sites annotated in the model matching the
# available info in the mod condition, then we won't be able to
# satisfy the conditions on this agent
if not viable_sites:
return
# Otherwise, update the
# If there are any sites left after we subject them to residue
# and position constraints, then return the relevant monomer patterns!
pattern_list = []
for site_name in viable_sites:
pattern_list.append({site_name: (mod_sites[site_name], WILD)})
sc_list.append(pattern_list)
# Now check for monomer patterns satisfying the agent's activity condition
if agent.activity and not ignore_activities:
# Iterate through annotations with this monomer as the subject
# and a has_active_pattern or has_inactive_pattern relationship
# FIXME: Currently activity type is not annotated/checked
# FIXME act_type = agent.activity.activity_type
rel_type = 'has_active_pattern' if agent.activity.is_active \
else 'has_inactive_pattern'
active_form_list = []
for ann in model.annotations:
if ann.subject == monomer and ann.predicate == rel_type:
# The annotation object contains the active/inactive pattern
active_form_list.append(ann.object)
sc_list.append(active_form_list)
# Now that we've got a list of conditions
for pattern_combo in itertools.product(*sc_list):
mp_sc = {}
for pattern in pattern_combo:
mp_sc.update(pattern)
if mp_sc:
yield monomer(**mp_sc)
if not sc_list:
yield monomer() | [
"Get monomer patterns for the agent accounting for grounding information.\n\n Parameters\n ----------\n model : pysb.core.Model\n The model to search for MonomerPatterns matching the given Agent.\n agent : indra.statements.Agent\n The Agent to find matching MonomerPatterns for.\n ignore_activites : bool\n Whether to ignore any ActivityConditions on the agent when determining\n the required site conditions for the MonomerPattern. For example, if\n set to True, will find a match for the agent `MAPK1(activity=kinase)`\n even if the corresponding MAPK1 Monomer in the model has no site\n named `kinase`. Default is False (more stringent matching).\n\n Returns\n -------\n generator of MonomerPatterns\n "
]
|
Please provide a description of the function:def get_monomer_pattern(model, agent, extra_fields=None):
try:
monomer = model.monomers[_n(agent.name)]
except KeyError as e:
logger.warning('Monomer with name %s not found in model' %
_n(agent.name))
return None
# Get the agent site pattern
pattern = get_site_pattern(agent)
if extra_fields is not None:
for k, v in extra_fields.items():
# This is an important assumption, it only sets the given pattern
# on the monomer if that site/key is not already specified at the
# Agent level. For instance, if the Agent is specified to have
# 'activity', that site will not be updated here.
if k not in pattern:
pattern[k] = v
# If a model is given, return the Monomer with the generated pattern,
# otherwise just return the pattern
try:
monomer_pattern = monomer(**pattern)
except Exception as e:
logger.info("Invalid site pattern %s for monomer %s" %
(pattern, monomer))
return None
return monomer_pattern | [
"Construct a PySB MonomerPattern from an Agent."
]
|
Please provide a description of the function:def get_site_pattern(agent):
if not isinstance(agent, ist.Agent):
return {}
pattern = {}
# 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:
pattern[get_binding_site_name(bc.agent)] = ANY
else:
pattern[get_binding_site_name(bc.agent)] = None
# Handle modifications
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:
pattern[mod_site] = (site_states[1], WILD)
else:
pattern[mod_site] = (site_states[0], WILD)
# Handle mutations
for mc in agent.mutations:
res_from = mc.residue_from if mc.residue_from else 'mut'
res_to = mc.residue_to if mc.residue_to else 'X'
if mc.position is None:
mut_site_name = res_from
else:
mut_site_name = res_from + mc.position
pattern[mut_site_name] = res_to
# Handle location
if agent.location is not None:
pattern['loc'] = _n(agent.location)
# Handle activity
if agent.activity is not None:
active_site_name = agent.activity.activity_type
if agent.activity.is_active:
active_site_state = 'active'
else:
active_site_state = 'inactive'
pattern[active_site_name] = active_site_state
return pattern | [
"Construct a dictionary of Monomer site states from an Agent.\n\n This crates the mapping to the associated PySB monomer from an\n INDRA Agent object."
]
|
Please provide a description of the function:def set_base_initial_condition(model, monomer, value):
# Build up monomer pattern dict
sites_dict = {}
for site in monomer.sites:
if site in monomer.site_states:
if site == 'loc' and 'cytoplasm' in monomer.site_states['loc']:
sites_dict['loc'] = 'cytoplasm'
else:
sites_dict[site] = monomer.site_states[site][0]
else:
sites_dict[site] = None
mp = monomer(**sites_dict)
pname = monomer.name + '_0'
try:
p = model.parameters[pname]
p.value = value
except KeyError:
p = Parameter(pname, value)
model.add_component(p)
model.initial(mp, p) | [
"Set an initial condition for a monomer in its 'default' state."
]
|
Please provide a description of the function:def get_annotation(component, db_name, db_ref):
url = get_identifiers_url(db_name, db_ref)
if not url:
return None
subj = component
ann = Annotation(subj, url, 'is')
return ann | [
"Construct model Annotations for each component.\n\n Annotation formats follow guidelines at http://identifiers.org/.\n "
]
|
Please provide a description of the function:def parse_identifiers_url(url):
url_pattern = 'http://identifiers.org/([A-Za-z]+)/([A-Za-z0-9:]+)'
match = re.match(url_pattern, url)
if match is not None:
g = match.groups()
if not len(g) == 2:
return (None, None)
ns_map = {'hgnc': 'HGNC', 'uniprot': 'UP', 'chebi':'CHEBI',
'interpro':'IP', 'pfam':'XFAM', 'fplx': 'FPLX',
'go': 'GO', 'mesh': 'MESH', 'pubchem.compound': 'PUBCHEM'}
ns = g[0]
id = g[1]
if not ns in ns_map.keys():
return (None, None)
if ns == 'hgnc':
if id.startswith('HGNC:'):
id = id[5:]
else:
logger.warning('HGNC URL missing "HGNC:" prefix: %s' % url)
return (None, None)
indra_ns = ns_map[ns]
return (indra_ns, id)
return (None, None) | [
"Parse an identifiers.org URL into (namespace, ID) tuple."
]
|
Please provide a description of the function:def complex_monomers_one_step(stmt, agent_set):
for i, member in enumerate(stmt.members):
gene_mono = agent_set.get_create_base_agent(member)
# Specify a binding site for each of the other complex members
# bp = abbreviation for "binding partner"
for j, bp in enumerate(stmt.members):
# The protein doesn't bind to itstmt!
if i == j:
continue
gene_mono.create_site(get_binding_site_name(bp)) | [
"In this (very simple) implementation, proteins in a complex are\n each given site names corresponding to each of the other members\n of the complex (lower case). So the resulting complex can be\n \"fully connected\" in that each member can be bound to\n all the others."
]
|
Please provide a description of the function:def make_model(self, policies=None, initial_conditions=True,
reverse_effects=False, model_name='indra_model'):
ppa = PysbPreassembler(self.statements)
self.processed_policies = self.process_policies(policies)
ppa.replace_activities()
if reverse_effects:
ppa.add_reverse_effects()
self.statements = ppa.statements
self.model = Model()
self.model.name = model_name
self.agent_set = BaseAgentSet()
# Collect information about the monomers/self.agent_set from the
# statements
self._monomers()
# Add the monomers to the model based on our BaseAgentSet
for agent_name, agent in self.agent_set.items():
m = Monomer(_n(agent_name), agent.sites, agent.site_states)
m.site_annotations = agent.site_annotations
self.model.add_component(m)
for db_name, db_ref in agent.db_refs.items():
a = get_annotation(m, db_name, db_ref)
if a is not None:
self.model.add_annotation(a)
# Iterate over the active_forms
for af in agent.active_forms:
self.model.add_annotation(Annotation(m, af,
'has_active_pattern'))
for iaf in agent.inactive_forms:
self.model.add_annotation(Annotation(m, iaf,
'has_inactive_pattern'))
for at in agent.activity_types:
act_site_cond = {at: 'active'}
self.model.add_annotation(Annotation(m, act_site_cond,
'has_active_pattern'))
inact_site_cond = {at: 'inactive'}
self.model.add_annotation(Annotation(m, inact_site_cond,
'has_inactive_pattern'))
# Iterate over the statements to generate rules
self._assemble()
# Add initial conditions
if initial_conditions:
self.add_default_initial_conditions()
return self.model | [
"Assemble the PySB model from the collected INDRA Statements.\n\n This method assembles a PySB model from the set of INDRA Statements.\n The assembled model is both returned and set as the assembler's\n model argument.\n\n Parameters\n ----------\n policies : Optional[Union[str, dict]]\n A string or dictionary that defines one or more assembly policies.\n\n If policies is a string, it defines a global assembly policy\n that applies to all Statement types.\n Example: one_step, interactions_only\n\n A dictionary of policies has keys corresponding to Statement types\n and values to the policy to be applied to that type of Statement.\n For Statement types whose policy is undefined, the 'default'\n policy is applied.\n Example: {'Phosphorylation': 'two_step'}\n initial_conditions : Optional[bool]\n If True, default initial conditions are generated for the\n Monomers in the model. Default: True\n reverse_effects : Optional[bool]\n If True, reverse rules are added to the model for activity,\n modification and amount regulations that have no corresponding\n reverse effects. Default: False\n model_name : Optional[str]\n The name attribute assigned to the PySB Model object.\n Default: \"indra_model\"\n\n Returns\n -------\n model : pysb.Model\n The assembled PySB model object.\n "
]
|
Please provide a description of the function:def add_default_initial_conditions(self, value=None):
if value is not None:
try:
value_num = float(value)
except ValueError:
logger.error('Invalid initial condition value.')
return
else:
value_num = self.default_initial_amount
if self.model is None:
return
for m in self.model.monomers:
set_base_initial_condition(self.model, m, value_num) | [
"Set default initial conditions in the PySB model.\n\n Parameters\n ----------\n value : Optional[float]\n Optionally a value can be supplied which will be the initial\n amount applied. Otherwise a built-in default is used.\n "
]
|
Please provide a description of the function:def set_expression(self, expression_dict):
if self.model is None:
return
monomers_found = []
monomers_notfound = []
# Iterate over all the monomers
for m in self.model.monomers:
if (m.name in expression_dict and
expression_dict[m.name] is not None):
# Try to get the expression amount from the dict
init = expression_dict[m.name]
# We interpret nan and None as not expressed
if math.isnan(init):
init = 0
init_round = round(init)
set_base_initial_condition(self.model, m, init_round)
monomers_found.append(m.name)
else:
set_base_initial_condition(self.model, m,
self.default_initial_amount)
monomers_notfound.append(m.name)
logger.info('Monomers set to given context')
logger.info('-----------------------------')
for m in monomers_found:
logger.info('%s' % m)
if monomers_notfound:
logger.info('')
logger.info('Monomers not found in given context')
logger.info('-----------------------------------')
for m in monomers_notfound:
logger.info('%s' % m) | [
"Set protein expression amounts as initial conditions\n\n Parameters\n ----------\n expression_dict : dict\n A dictionary in which the keys are gene names and the\n values are numbers representing the absolute amount\n (count per cell) of proteins expressed. Proteins that\n are not expressed can be represented as nan. Entries\n that are not in the dict or are in there but resolve\n to None, are set to the default initial amount.\n Example: {'EGFR': 12345, 'BRAF': 4567, 'ESR1': nan}\n "
]
|
Please provide a description of the function:def set_context(self, cell_type):
if self.model is None:
return
monomer_names = [m.name for m in self.model.monomers]
res = context_client.get_protein_expression(monomer_names, [cell_type])
amounts = res.get(cell_type)
if not amounts:
logger.warning('Could not get context for %s cell type.' %
cell_type)
self.add_default_initial_conditions()
return
self.set_expression(amounts) | [
"Set protein expression amounts from CCLE as initial conditions.\n\n This method uses :py:mod:`indra.databases.context_client` to get\n protein expression levels for a given cell type and set initial\n conditions for Monomers in the model accordingly.\n\n Parameters\n ----------\n cell_type : str\n Cell type name for which expression levels are queried.\n The cell type name follows the CCLE database conventions.\n\n Example: LOXIMVI_SKIN, BT20_BREAST\n "
]
|
Please provide a description of the function:def export_model(self, format, file_name=None):
# Handle SBGN as special case
if format == 'sbgn':
exp_str = export_sbgn(self.model)
elif format == 'kappa_im':
# NOTE: this export is not a str, rather a graph object
return export_kappa_im(self.model, file_name)
elif format == 'kappa_cm':
# NOTE: this export is not a str, rather a graph object
return export_kappa_cm(self.model, file_name)
else:
try:
exp_str = pysb.export.export(self.model, format)
except KeyError:
logging.error('Unknown export format: %s' % format)
return None
if file_name:
with open(file_name, 'wb') as fh:
fh.write(exp_str.encode('utf-8'))
return exp_str | [
"Save the assembled model in a modeling formalism other than PySB.\n\n For more details on exporting PySB models, see\n http://pysb.readthedocs.io/en/latest/modules/export/index.html\n\n Parameters\n ----------\n format : str\n The format to export into, for instance \"kappa\", \"bngl\",\n \"sbml\", \"matlab\", \"mathematica\", \"potterswheel\". See\n http://pysb.readthedocs.io/en/latest/modules/export/index.html\n for a list of supported formats. In addition to the formats\n supported by PySB itself, this method also provides \"sbgn\"\n output.\n\n file_name : Optional[str]\n An optional file name to save the exported model into.\n\n Returns\n -------\n exp_str : str or object\n The exported model string or object\n "
]
|
Please provide a description of the function:def save_rst(self, file_name='pysb_model.rst', module_name='pysb_module'):
if self.model is not None:
with open(file_name, 'wt') as fh:
fh.write('.. _%s:\n\n' % module_name)
fh.write('Module\n======\n\n')
fh.write('INDRA-assembled model\n---------------------\n\n')
fh.write('::\n\n')
model_str = pysb.export.export(self.model, 'pysb_flat')
model_str = '\t' + model_str.replace('\n', '\n\t')
fh.write(model_str) | [
"Save the assembled model as an RST file for literate modeling.\n\n Parameters\n ----------\n file_name : Optional[str]\n The name of the file to save the RST in.\n Default: pysb_model.rst\n module_name : Optional[str]\n The name of the python function defining the module.\n Default: pysb_module\n "
]
|
Please provide a description of the function:def _dispatch(self, stmt, stage, *args):
policy = self.processed_policies[stmt.uuid]
class_name = stmt.__class__.__name__.lower()
# We map remove modifications to their positive counterparts
if isinstance(stmt, ist.RemoveModification):
class_name = ist.modclass_to_modtype[stmt.__class__]
# We handle any kind of activity regulation in regulateactivity
if isinstance(stmt, ist.RegulateActivity):
class_name = 'regulateactivity'
func_name = '%s_%s_%s' % (class_name, stage, policy.name)
func = globals().get(func_name)
if func is None:
# The specific policy is not implemented for the
# given statement type.
# We try to apply a default policy next.
func_name = '%s_%s_default' % (class_name, stage)
func = globals().get(func_name)
if func is None:
# The given statement type doesn't have a default
# policy.
raise UnknownPolicyError('%s function %s not defined' %
(stage, func_name))
return func(stmt, *args) | [
"Construct and call an assembly function.\n\n This function constructs the name of the assembly function based on\n the type of statement, the corresponding policy and the stage\n of assembly. It then calls that function to perform the assembly\n task."
]
|
Please provide a description of the function:def _monomers(self):
for stmt in self.statements:
if _is_whitelisted(stmt):
self._dispatch(stmt, 'monomers', self.agent_set) | [
"Calls the appropriate monomers method based on policies."
]
|
Please provide a description of the function:def _assemble(self):
for stmt in self.statements:
pol = self.processed_policies[stmt.uuid]
if _is_whitelisted(stmt):
self._dispatch(stmt, 'assemble', self.model, self.agent_set,
pol.parameters) | [
"Calls the appropriate assemble method based on policies."
]
|
Please provide a description of the function:def send_query(text, service_endpoint='drum', query_args=None):
if service_endpoint in ['drum', 'drum-dev', 'cwms', 'cwmsreader']:
url = base_url + service_endpoint
else:
logger.error('Invalid service endpoint: %s' % service_endpoint)
return ''
if query_args is None:
query_args = {}
query_args.update({'input': text})
res = requests.get(url, query_args, timeout=3600)
if not res.status_code == 200:
logger.error('Problem with TRIPS query: status code %s' %
res.status_code)
return ''
# Gets unicode content
return res.text | [
"Send a query to the TRIPS web service.\n\n Parameters\n ----------\n text : str\n The text to be processed.\n service_endpoint : Optional[str]\n Selects the TRIPS/DRUM web service endpoint to use. Is a choice between\n \"drum\" (default), \"drum-dev\", a nightly build, and \"cwms\" for use with\n more general knowledge extraction.\n query_args : Optional[dict]\n A dictionary of arguments to be passed with the query.\n\n Returns\n -------\n html : str\n The HTML result returned by the web service.\n "
]
|
Please provide a description of the function:def get_xml(html, content_tag='ekb', fail_if_empty=False):
cont = re.findall(r'<%(tag)s(.*?)>(.*?)</%(tag)s>' % {'tag': content_tag},
html, re.MULTILINE | re.DOTALL)
if cont:
events_terms = ''.join([l.strip() for l in cont[0][1].splitlines()])
if 'xmlns' in cont[0][0]:
meta = ' '.join([l.strip() for l in cont[0][0].splitlines()])
else:
meta = ''
else:
events_terms = ''
meta = ''
if fail_if_empty:
assert events_terms != '',\
"Got empty string for events content from html:\n%s" % html
header = ('<?xml version="1.0" encoding="utf-8" standalone="yes"?><%s%s>'
% (content_tag, meta))
footer = '</%s>' % content_tag
return header + events_terms.replace('\n', '') + footer | [
"Extract the content XML from the HTML output of the TRIPS web service.\n\n Parameters\n ----------\n html : str\n The HTML output from the TRIPS web service.\n content_tag : str\n The xml tag used to label the content. Default is 'ekb'.\n fail_if_empty : bool\n If True, and if the xml content found is an empty string, raise an\n exception. Default is False.\n\n Returns\n -------\n The extraction knowledge base (e.g. EKB) XML that contains the event and\n term extractions.\n "
]
|
Please provide a description of the function:def save_xml(xml_str, file_name, pretty=True):
try:
fh = open(file_name, 'wt')
except IOError:
logger.error('Could not open %s for writing.' % file_name)
return
if pretty:
xmld = xml.dom.minidom.parseString(xml_str)
xml_str_pretty = xmld.toprettyxml()
fh.write(xml_str_pretty)
else:
fh.write(xml_str)
fh.close() | [
"Save the TRIPS EKB XML in a file.\n\n Parameters\n ----------\n xml_str : str\n The TRIPS EKB XML string to be saved.\n file_name : str\n The name of the file to save the result in.\n pretty : Optional[bool]\n If True, the XML is pretty printed.\n "
]
|
Please provide a description of the function:def process_table(fname):
book = openpyxl.load_workbook(fname, read_only=True)
try:
rel_sheet = book['Relations']
except Exception as e:
rel_sheet = book['Causal']
event_sheet = book['Events']
entities_sheet = book['Entities']
sp = SofiaExcelProcessor(rel_sheet.rows, event_sheet.rows,
entities_sheet.rows)
return sp | [
"Return processor by processing a given sheet of a spreadsheet file.\n\n Parameters\n ----------\n fname : str\n The name of the Excel file (typically .xlsx extension) to process\n\n Returns\n -------\n sp : indra.sources.sofia.processor.SofiaProcessor\n A SofiaProcessor object which has a list of extracted INDRA\n Statements as its statements attribute.\n "
]
|
Please provide a description of the function:def process_text(text, out_file='sofia_output.json', auth=None):
text_json = {'text': text}
if not auth:
user, password = _get_sofia_auth()
else:
user, password = auth
if not user or not password:
raise ValueError('Could not use SOFIA web service since'
' authentication information is missing. Please'
' set SOFIA_USERNAME and SOFIA_PASSWORD in the'
' INDRA configuration file or as environmental'
' variables.')
json_response, status_code, process_status = \
_text_processing(text_json=text_json, user=user, password=password)
# Check response status
if process_status != 'Done' or status_code != 200:
return None
# Cache reading output
if out_file:
with open(out_file, 'w') as fh:
json.dump(json_response, fh, indent=1)
return process_json(json_response) | [
"Return processor by processing text given as a string.\n\n Parameters\n ----------\n text : str\n A string containing the text to be processed with Sofia.\n out_file : Optional[str]\n The path to a file to save the reader's output into.\n Default: sofia_output.json\n auth : Optional[list]\n A username/password pair for the Sofia web service. If not given,\n the SOFIA_USERNAME and SOFIA_PASSWORD values are loaded from either\n the INDRA config or the environment.\n\n Returns\n -------\n sp : indra.sources.sofia.processor.SofiaProcessor\n A SofiaProcessor object which has a list of extracted INDRA\n Statements as its statements attribute. If the API did not process\n the text, None is returned.\n "
]
|
Please provide a description of the function:def _get_dict_from_list(dict_key, list_of_dicts):
the_dict = [cur_dict for cur_dict in list_of_dicts
if cur_dict.get(dict_key)]
if not the_dict:
raise ValueError('Could not find a dict with key %s' % dict_key)
return the_dict[0][dict_key] | [
"Retrieve a specific dict from a list of dicts.\n\n Parameters\n ----------\n dict_key : str\n The (single) key of the dict to be retrieved from the list.\n list_of_dicts : list\n The list of dicts to search for the specific dict.\n\n Returns\n -------\n dict value\n The value associated with the dict_key (e.g., a list of nodes or\n edges).\n "
]
|
Please provide a description of the function:def _initialize_node_agents(self):
nodes = _get_dict_from_list('nodes', self.cx)
invalid_genes = []
for node in nodes:
id = node['@id']
cx_db_refs = self.get_aliases(node)
up_id = cx_db_refs.get('UP')
if up_id:
gene_name = uniprot_client.get_gene_name(up_id)
hgnc_id = hgnc_client.get_hgnc_id(gene_name)
db_refs = {'UP': up_id, 'HGNC': hgnc_id, 'TEXT': gene_name}
agent = Agent(gene_name, db_refs=db_refs)
self._node_names[id] = gene_name
self._node_agents[id] = agent
continue
else:
node_name = node['n']
self._node_names[id] = node_name
hgnc_id = hgnc_client.get_hgnc_id(node_name)
db_refs = {'TEXT': node_name}
if not hgnc_id:
if not self.require_grounding:
self._node_agents[id] = \
Agent(node_name, db_refs=db_refs)
invalid_genes.append(node_name)
else:
db_refs.update({'HGNC': hgnc_id})
up_id = hgnc_client.get_uniprot_id(hgnc_id)
# It's possible that a valid HGNC ID will not have a
# Uniprot ID, as in the case of HOTAIR (HOX transcript
# antisense RNA, HGNC:33510)
if up_id:
db_refs.update({'UP': up_id})
self._node_agents[id] = Agent(node_name, db_refs=db_refs)
if invalid_genes:
verb = 'Skipped' if self.require_grounding else 'Included'
logger.info('%s invalid gene symbols: %s' %
(verb, ', '.join(invalid_genes))) | [
"Initialize internal dicts containing node information."
]
|
Please provide a description of the function:def get_pmids(self):
pmids = []
for ea in self._edge_attributes.values():
edge_pmids = ea.get('pmids')
if edge_pmids:
pmids += edge_pmids
return list(set(pmids)) | [
"Get list of all PMIDs associated with edges in the network."
]
|
Please provide a description of the function:def get_statements(self):
edges = _get_dict_from_list('edges', self.cx)
for edge in edges:
edge_type = edge.get('i')
if not edge_type:
continue
stmt_type = _stmt_map.get(edge_type)
if stmt_type:
id = edge['@id']
source_agent = self._node_agents.get(edge['s'])
target_agent = self._node_agents.get(edge['t'])
if not source_agent or not target_agent:
logger.info("Skipping edge %s->%s: %s" %
(self._node_names[edge['s']],
self._node_names[edge['t']], edge))
continue
ev = self._create_evidence(id)
if stmt_type == Complex:
stmt = stmt_type([source_agent, target_agent], evidence=ev)
else:
stmt = stmt_type(source_agent, target_agent, evidence=ev)
self.statements.append(stmt)
return self.statements | [
"Convert network edges into Statements.\n\n Returns\n -------\n list of Statements\n Converted INDRA Statements.\n "
]
|
Please provide a description of the function:def _create_evidence(self, edge_id):
pmids = None
edge_attr = self._edge_attributes.get(edge_id)
if edge_attr:
pmids = edge_attr.get('pmids')
if not pmids:
return [Evidence(source_api='ndex',
source_id=self._network_info['externalId'],
annotations={'edge_id': edge_id})]
else:
evidence = []
for pmid in pmids:
evidence.append(
Evidence(source_api='ndex',
source_id=self._network_info['externalId'],
pmid=pmid,
annotations={'edge_id': edge_id}))
return evidence | [
"Create Evidence object for a specific edge/Statement in the network.\n\n Parameters\n ----------\n edge_id : int\n ID of the edge in the underlying NDEx network.\n "
]
|
Please provide a description of the function:def node_has_edge_with_label(self, node_name, edge_label):
G = self.G
for edge in G.edges(node_name):
to = edge[1]
relation_name = G.edges[node_name, to]['relation']
if relation_name == edge_label:
return to
return None | [
"Looks for an edge from node_name to some other node with the specified\n label. Returns the node to which this edge points if it exists, or None\n if it doesn't.\n\n Parameters\n ----------\n G :\n The graph object\n node_name :\n Node that the edge starts at\n edge_label :\n The text in the relation property of the edge\n "
]
|
Please provide a description of the function:def general_node_label(self, node):
G = self.G
if G.node[node]['is_event']:
return 'event type=' + G.node[node]['type']
else:
return 'entity text=' + G.node[node]['text'] | [
"Used for debugging - gives a short text description of a\n graph node."
]
|
Please provide a description of the function:def print_parent_and_children_info(self, node):
G = self.G
parents = G.predecessors(node)
children = G.successors(node)
print(general_node_label(G, node))
tabs = '\t'
for parent in parents:
relation = G.edges[parent, node]['relation']
print(tabs + 'Parent (%s): %s' % (relation,
general_node_label(G, parent)))
for cop in G.successors(parent):
if cop != node:
relation = G.edges[parent, cop]['relation']
print(tabs + 'Child of parent (%s): %s' % (relation,
general_node_label(G, cop)))
for child in children:
relation = G.edges[node, child]['relation']
print(tabs + 'Child (%s): (%s)' % (relation,
general_node_label(G, child))) | [
"Used for debugging - prints a short description of a a node, its\n children, its parents, and its parents' children."
]
|
Please provide a description of the function:def find_event_parent_with_event_child(self, parent_name, child_name):
G = self.G
matches = []
for n in G.node.keys():
if G.node[n]['is_event'] and G.node[n]['type'] == parent_name:
children = G.successors(n)
for child in children:
if G.node[child]['is_event'] and \
G.node[child]['type'] == child_name:
matches.append((n, child))
break
return list(set(matches)) | [
"Finds all event nodes (is_event node attribute is True) that are\n of the type parent_name, that have a child event node with the type\n child_name."
]
|
Please provide a description of the function:def find_event_with_outgoing_edges(self, event_name, desired_relations):
G = self.G
desired_relations = set(desired_relations)
desired_event_nodes = []
for node in G.node.keys():
if G.node[node]['is_event'] and G.node[node]['type'] == event_name:
has_relations = [G.edges[node, edge[1]]['relation'] for
edge in G.edges(node)]
has_relations = set(has_relations)
# Did the outgoing edges from this node have all of the
# desired relations?
if desired_relations.issubset(has_relations):
desired_event_nodes.append(node)
return desired_event_nodes | [
"Gets a list of event nodes with the specified event_name and\n outgoing edges annotated with each of the specified relations.\n\n Parameters\n ----------\n event_name : str\n Look for event nodes with this name\n desired_relations : list[str]\n Look for event nodes with outgoing edges annotated with each of\n these relations\n\n Returns\n -------\n event_nodes : list[str]\n Event nodes that fit the desired criteria\n "
]
|
Please provide a description of the function:def get_related_node(self, node, relation):
G = self.G
for edge in G.edges(node):
to = edge[1]
to_relation = G.edges[node, to]['relation']
if to_relation == relation:
return to
return None | [
"Looks for an edge from node to some other node, such that the edge\n is annotated with the given relation. If there exists such an edge,\n returns the name of the node it points to. Otherwise, returns None."
]
|
Please provide a description of the function:def get_entity_text_for_relation(self, node, relation):
G = self.G
related_node = self.get_related_node(node, relation)
if related_node is not None:
if not G.node[related_node]['is_event']:
return G.node[related_node]['text']
else:
return None
else:
return None | [
"Looks for an edge from node to some other node, such that the edge is\n annotated with the given relation. If there exists such an edge, and\n the node at the other edge is an entity, return that entity's text.\n Otherwise, returns None."
]
|
Please provide a description of the function:def process_increase_expression_amount(self):
statements = []
pwcs = self.find_event_parent_with_event_child(
'Positive_regulation', 'Gene_expression')
for pair in pwcs:
pos_reg = pair[0]
expression = pair[1]
cause = self.get_entity_text_for_relation(pos_reg, 'Cause')
target = self.get_entity_text_for_relation(expression, 'Theme')
if cause is not None and target is not None:
theme_node = self.get_related_node(expression, 'Theme')
assert(theme_node is not None)
evidence = self.node_to_evidence(theme_node, is_direct=False)
statements.append(IncreaseAmount(s2a(cause), s2a(target),
evidence=evidence))
return statements | [
"Looks for Positive_Regulation events with a specified Cause\n and a Gene_Expression theme, and processes them into INDRA statements.\n "
]
|
Please provide a description of the function:def process_phosphorylation_statements(self):
G = self.G
statements = []
pwcs = self.find_event_parent_with_event_child('Positive_regulation',
'Phosphorylation')
for pair in pwcs:
(pos_reg, phos) = pair
cause = self.get_entity_text_for_relation(pos_reg, 'Cause')
theme = self.get_entity_text_for_relation(phos, 'Theme')
print('Cause:', cause, 'Theme:', theme)
# If the trigger word is dephosphorylate or similar, then we
# extract a dephosphorylation statement
trigger_word = self.get_entity_text_for_relation(phos,
'Phosphorylation')
if 'dephos' in trigger_word:
deph = True
else:
deph = False
site = self.get_entity_text_for_relation(phos, 'Site')
theme_node = self.get_related_node(phos, 'Theme')
assert(theme_node is not None)
evidence = self.node_to_evidence(theme_node, is_direct=False)
if theme is not None:
if deph:
statements.append(Dephosphorylation(s2a(cause),
s2a(theme), site, evidence=evidence))
else:
statements.append(Phosphorylation(s2a(cause),
s2a(theme), site, evidence=evidence))
return statements | [
"Looks for Phosphorylation events in the graph and extracts them into\n INDRA statements.\n\n In particular, looks for a Positive_regulation event node with a child\n Phosphorylation event node.\n\n If Positive_regulation has an outgoing Cause edge, that's the subject\n If Phosphorylation has an outgoing Theme edge, that's the object\n If Phosphorylation has an outgoing Site edge, that's the site\n "
]
|
Please provide a description of the function:def process_binding_statements(self):
G = self.G
statements = []
binding_nodes = self.find_event_with_outgoing_edges('Binding',
['Theme',
'Theme2'])
for node in binding_nodes:
theme1 = self.get_entity_text_for_relation(node, 'Theme')
theme1_node = self.get_related_node(node, 'Theme')
theme2 = self.get_entity_text_for_relation(node, 'Theme2')
assert(theme1 is not None)
assert(theme2 is not None)
evidence = self.node_to_evidence(theme1_node, is_direct=True)
statements.append(Complex([s2a(theme1), s2a(theme2)],
evidence=evidence))
return statements | [
"Looks for Binding events in the graph and extracts them into INDRA\n statements.\n\n In particular, looks for a Binding event node with outgoing edges\n with relations Theme and Theme2 - the entities these edges point to\n are the two constituents of the Complex INDRA statement.\n "
]
|
Please provide a description of the function:def node_to_evidence(self, entity_node, is_direct):
# We assume that the entire event is within a single sentence, and
# get this sentence by getting the sentence containing one of the
# entities
sentence_text = self.G.node[entity_node]['sentence_text']
# Make annotations object containing the fully connected subgraph
# containing these nodes
subgraph = self.connected_subgraph(entity_node)
edge_properties = {}
for edge in subgraph.edges():
edge_properties[edge] = subgraph.edges[edge]
annotations = {'node_properties': subgraph.node,
'edge_properties': edge_properties}
# Make evidence object
epistemics = dict()
evidence = Evidence(source_api='tees',
pmid=self.pmid,
text=sentence_text,
epistemics={'direct': is_direct},
annotations=annotations)
return evidence | [
"Computes an evidence object for a statement.\n\n We assume that the entire event happens within a single statement, and\n get the text of the sentence by getting the text of the sentence\n containing the provided node that corresponds to one of the entities\n participanting in the event.\n\n The Evidence's pmid is whatever was provided to the constructor\n (perhaps None), and the annotations are the subgraph containing the\n provided node, its ancestors, and its descendants.\n "
]
|
Please provide a description of the function:def connected_subgraph(self, node):
G = self.G
subgraph_nodes = set()
subgraph_nodes.add(node)
subgraph_nodes.update(dag.ancestors(G, node))
subgraph_nodes.update(dag.descendants(G, node))
# Keep adding the ancesotrs and descendants on nodes of the graph
# until we can't do so any longer
graph_changed = True
while graph_changed:
initial_count = len(subgraph_nodes)
old_nodes = set(subgraph_nodes)
for n in old_nodes:
subgraph_nodes.update(dag.ancestors(G, n))
subgraph_nodes.update(dag.descendants(G, n))
current_count = len(subgraph_nodes)
graph_changed = current_count > initial_count
return G.subgraph(subgraph_nodes) | [
"Returns the subgraph containing the given node, its ancestors, and\n its descendants.\n\n Parameters\n ----------\n node : str\n We want to create the subgraph containing this node.\n\n Returns\n -------\n subgraph : networkx.DiGraph\n The subgraph containing the specified node.\n "
]
|
Please provide a description of the function:def process_text(text, save_xml_name='trips_output.xml', save_xml_pretty=True,
offline=False, service_endpoint='drum'):
if not offline:
html = client.send_query(text, service_endpoint)
xml = client.get_xml(html)
else:
if offline_reading:
try:
dr = DrumReader()
if dr is None:
raise Exception('DrumReader could not be instantiated.')
except BaseException as e:
logger.error(e)
logger.error('Make sure drum/bin/trips-drum is running in'
' a separate process')
return None
try:
dr.read_text(text)
dr.start()
except SystemExit:
pass
xml = dr.extractions[0]
else:
logger.error('Offline reading with TRIPS/DRUM not available.')
logger.error('Error message was: %s' % offline_err)
msg =
logger.error(msg)
return None
if save_xml_name:
client.save_xml(xml, save_xml_name, save_xml_pretty)
return process_xml(xml) | [
"Return a TripsProcessor by processing text.\n\n Parameters\n ----------\n text : str\n The text to be processed.\n save_xml_name : Optional[str]\n The name of the file to save the returned TRIPS extraction knowledge\n base XML. Default: trips_output.xml\n save_xml_pretty : Optional[bool]\n If True, the saved XML is pretty-printed. Some third-party tools\n require non-pretty-printed XMLs which can be obtained by setting this\n to False. Default: True\n offline : Optional[bool]\n If True, offline reading is used with a local instance of DRUM, if\n available. Default: False\n service_endpoint : Optional[str]\n Selects the TRIPS/DRUM web service endpoint to use. Is a choice between\n \"drum\" (default) and \"drum-dev\", a nightly build.\n\n Returns\n -------\n tp : TripsProcessor\n A TripsProcessor containing the extracted INDRA Statements\n in tp.statements.\n ",
"\n To install DRUM locally, follow instructions at\n https://github.com/wdebeaum/drum.\n Next, install the pykqml package either from pip or from\n https://github.com/bgyori/pykqml.\n Once installed, run drum/bin/trips-drum in a separate process.\n "
]
|
Please provide a description of the function:def process_xml_file(file_name):
with open(file_name, 'rb') as fh:
ekb = fh.read().decode('utf-8')
return process_xml(ekb) | [
"Return a TripsProcessor by processing a TRIPS EKB XML file.\n\n Parameters\n ----------\n file_name : str\n Path to a TRIPS extraction knowledge base (EKB) file to be processed.\n\n Returns\n -------\n tp : TripsProcessor\n A TripsProcessor containing the extracted INDRA Statements\n in tp.statements.\n "
]
|
Please provide a description of the function:def process_xml(xml_string):
tp = TripsProcessor(xml_string)
if tp.tree is None:
return None
tp.get_modifications_indirect()
tp.get_activations_causal()
tp.get_activations_stimulate()
tp.get_complexes()
tp.get_modifications()
tp.get_active_forms()
tp.get_active_forms_state()
tp.get_activations()
tp.get_translocation()
tp.get_regulate_amounts()
tp.get_degradations()
tp.get_syntheses()
tp.get_conversions()
tp.get_simple_increase_decrease()
return tp | [
"Return a TripsProcessor by processing a TRIPS EKB XML string.\n\n Parameters\n ----------\n xml_string : str\n A TRIPS extraction knowledge base (EKB) string to be processed.\n http://trips.ihmc.us/parser/api.html\n\n Returns\n -------\n tp : TripsProcessor\n A TripsProcessor containing the extracted INDRA Statements\n in tp.statements.\n "
]
|
Please provide a description of the function:def load_eidos_curation_table():
url = 'https://raw.githubusercontent.com/clulab/eidos/master/' + \
'src/main/resources/org/clulab/wm/eidos/english/confidence/' + \
'rule_summary.tsv'
# Load the table of scores from the URL above into a data frame
res = StringIO(requests.get(url).text)
table = pandas.read_table(res, sep='\t')
# Drop the last "Grant total" row
table = table.drop(table.index[len(table)-1])
return table | [
"Return a pandas table of Eidos curation data."
]
|
Please provide a description of the function:def get_eidos_bayesian_scorer(prior_counts=None):
table = load_eidos_curation_table()
subtype_counts = {'eidos': {r: [c, i] for r, c, i in
zip(table['RULE'], table['Num correct'],
table['Num incorrect'])}}
prior_counts = prior_counts if prior_counts else copy.deepcopy(
default_priors)
scorer = BayesianScorer(prior_counts=prior_counts,
subtype_counts=subtype_counts)
return scorer | [
"Return a BayesianScorer based on Eidos curation counts."
]
|
Please provide a description of the function:def get_eidos_scorer():
table = load_eidos_curation_table()
# Get the overall precision
total_num = table['COUNT of RULE'].sum()
weighted_sum = table['COUNT of RULE'].dot(table['% correct'])
precision = weighted_sum / total_num
# We have to divide this into a random and systematic component, for now
# in an ad-hoc manner
syst_error = 0.05
rand_error = 1 - precision - syst_error
prior_probs = {'rand': {'eidos': rand_error}, 'syst': {'eidos': syst_error}}
# Get a dict of rule-specific errors.
subtype_probs = {'eidos':
{k: 1.0-min(v, 0.95)-syst_error for k, v
in zip(table['RULE'], table['% correct'])}}
scorer = SimpleScorer(prior_probs, subtype_probs)
return scorer | [
"Return a SimpleScorer based on Eidos curated precision estimates."
]
|
Please provide a description of the function:def process_from_web():
logger.info('Downloading table from %s' % trrust_human_url)
res = requests.get(trrust_human_url)
res.raise_for_status()
df = pandas.read_table(io.StringIO(res.text))
tp = TrrustProcessor(df)
tp.extract_statements()
return tp | [
"Return a TrrustProcessor based on the online interaction table.\n\n Returns\n -------\n TrrustProcessor\n A TrrustProcessor object that has a list of INDRA Statements in its\n statements attribute.\n "
]
|
Please provide a description of the function:def process_from_webservice(id_val, id_type='pmcid', source='pmc',
with_grounding=True):
if with_grounding:
fmt = '%s.normed/%s/%s'
else:
fmt = '%s/%s/%s'
resp = requests.get(RLIMSP_URL + fmt % (source, id_type, id_val))
if resp.status_code != 200:
raise RLIMSP_Error("Bad status code: %d - %s"
% (resp.status_code, resp.reason))
rp = RlimspProcessor(resp.json())
rp.extract_statements()
return rp | [
"Return an output from RLIMS-p for the given PubMed ID or PMC ID.\n\n Parameters\n ----------\n id_val : str\n A PMCID, with the prefix PMC, or pmid, with no prefix, of the paper to\n be \"read\".\n id_type : str\n Either 'pmid' or 'pmcid'. The default is 'pmcid'.\n source : str\n Either 'pmc' or 'medline', whether you want pmc fulltext or medline\n abstracts.\n with_grounding : bool\n The RLIMS-P web service provides two endpoints, one pre-grounded, the\n other not so much. The grounded endpoint returns far less content, and\n may perform some grounding that can be handled by the grounding mapper.\n\n Returns\n -------\n :py:class:`indra.sources.rlimsp.processor.RlimspProcessor`\n An RlimspProcessor which contains a list of extracted INDRA Statements\n in its statements attribute.\n "
]
|
Please provide a description of the function:def process_from_json_file(filename, doc_id_type=None):
with open(filename, 'rt') as f:
lines = f.readlines()
json_list = []
for line in lines:
json_list.append(json.loads(line))
rp = RlimspProcessor(json_list, doc_id_type=doc_id_type)
rp.extract_statements()
return rp | [
"Process RLIMSP extractions from a bulk-download JSON file.\n\n Parameters\n ----------\n filename : str\n Path to the JSON file.\n doc_id_type : Optional[str]\n In some cases the RLIMS-P paragraph info doesn't contain 'pmid' or\n 'pmcid' explicitly, instead if contains a 'docId' key. This parameter\n allows defining what ID type 'docId' sould be interpreted as. Its\n values should be 'pmid' or 'pmcid' or None if not used.\n\n Returns\n -------\n :py:class:`indra.sources.rlimsp.processor.RlimspProcessor`\n An RlimspProcessor which contains a list of extracted INDRA Statements\n in its statements attribute.\n "
]
|
Please provide a description of the function:def export_dict(self):
"Convert this into an ordinary dict (of dicts)."
return {k: v.export_dict() if isinstance(v, self.__class__) else v
for k, v in self.items()} | []
|
Please provide a description of the function:def get(self, key):
"Find the first value within the tree which has the key."
if key in self.keys():
return self[key]
else:
res = None
for v in self.values():
# This could get weird if the actual expected returned value
# is None, especially in teh case of overlap. Any ambiguity
# would be resolved by get_path(s).
if hasattr(v, 'get'):
res = v.get(key)
if res is not None:
break
return res | []
|
Please provide a description of the function:def get_path(self, key):
"Like `get`, but also return the path taken to the value."
if key in self.keys():
return (key,), self[key]
else:
key_path, res = (None, None)
for sub_key, v in self.items():
if isinstance(v, self.__class__):
key_path, res = v.get_path(key)
elif hasattr(v, 'get'):
res = v.get(key)
key_path = (key,) if res is not None else None
if res is not None and key_path is not None:
key_path = (sub_key,) + key_path
break
return key_path, res | []
|
Please provide a description of the function: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 | []
|
Please provide a description of the function: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 | []
|
Please provide a description of the function: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 | [
"Get the deepest entries as a flat set."
]
|
Please provide a description of the function:def _read_reach_rule_regexps():
reach_rule_filename = \
os.path.join(os.path.dirname(os.path.abspath(__file__)),
'reach_rule_regexps.txt')
with open(reach_rule_filename, 'r') as f:
reach_rule_regexp = []
for line in f:
reach_rule_regexp.append(line.rstrip())
return reach_rule_regexp | [
"Load in a file with the regular expressions corresponding to each\n reach rule. Why regular expression matching?\n The rule name in found_by has instances of some reach rules for each\n possible event type\n (activation, binding, etc). This makes for too many different types of\n rules for practical curation of examples.\n We use regular expressions to only match the rule used for extraction,\n independently of what the event is.\n "
]
|
Please provide a description of the function: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 | [
"Returns the category of reach rule from the reach rule instance.\n\n Looks at a list of regular\n expressions corresponding to reach rule types, and returns the longest\n regexp that matches, or None if none of them match.\n\n Parameters\n ----------\n evidence : indra.statements.Evidence\n A reach evidence object to subtype\n\n Returns\n -------\n best_match : str\n A regular expression corresponding to the reach rule that was used to\n extract this evidence\n "
]
|
Please provide a description of the function: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('-------------------') | [
"Print the number of events in the REACH output by type."
]
|
Please provide a description of the function: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] | [
"Gather all event IDs in the REACH output by type.\n\n These IDs are stored in the self.all_events dict.\n "
]
|
Please provide a description of the function: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)) | [
"Extract Modification INDRA Statements."
]
|
Please provide a description of the function: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) | [
"Extract RegulateAmount INDRA Statements."
]
|
Please provide a description of the function: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) | [
"Extract INDRA Complex Statements."
]
|
Please provide a description of the function: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) | [
"Extract INDRA Activation Statements."
]
|
Please provide a description of the function: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) | [
"Extract INDRA Translocation Statements."
]
|
Please provide a description of the function: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 | [
"Return a list of ModConditions given a mod term dict."
]
|
Please provide a description of the function: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) | [
"Return sentence coordinates for a given entity.\n\n Given an entity term return the associated sentence coordinates as\n a tuple of the form (int, int). Returns None if for any reason the\n sentence coordinates cannot be found.\n "
]
|
Please provide a description of the function: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 | [
"Get the section of the paper that the event is from."
]
|
Please provide a description of the function: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 | [
"Return a single or a complex controller agent."
]
|
Please provide a description of the function:def _sanitize(text):
d = {'-LRB-': '(', '-RRB-': ')'}
return re.sub('|'.join(d.keys()), lambda m: d[m.group(0)], text) | [
"Return sanitized Eidos text field for human readability."
]
|
Please provide a description of the function:def _get_time_stamp(entry):
if not entry or entry == 'Undef':
return None
try:
dt = datetime.datetime.strptime(entry, '%Y-%m-%dT%H:%M')
except Exception as e:
logger.debug('Could not parse %s format' % entry)
return None
return dt | [
"Return datetime object from a timex constraint start/end entry.\n\n Example string format to convert: 2018-01-01T00:00\n "
]
|
Please provide a description of the function:def ref_context_from_geoloc(geoloc):
text = geoloc.get('text')
geoid = geoloc.get('geoID')
rc = RefContext(name=text, db_refs={'GEOID': geoid})
return rc | [
"Return a RefContext object given a geoloc entry."
]
|
Please provide a description of the function: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 | [
"Return a TimeContext object given a timex entry."
]
|
Please provide a description of the function: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 [] | [
"Return IDs of all arguments of a given type"
]
|
Please provide a description of the function: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) | [
"Extract causal relations as Statements."
]
|
Please provide a description of the function: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 | [
"Return the Evidence object for the INDRA Statment."
]
|
Please provide a description of the function: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 | [
"Return negation attached to an event.\n\n Example: \"states\": [{\"@type\": \"State\", \"type\": \"NEGATION\",\n \"text\": \"n't\"}]\n "
]
|
Please provide a description of the function: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 | [
"Return hedging markers attached to an event.\n\n Example: \"states\": [{\"@type\": \"State\", \"type\": \"HEDGE\",\n \"text\": \"could\"}\n "
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.