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_proper... | [
"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
... | [
"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__)
... | [
"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):
... | [
"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... | [
"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 no... |
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_i... | [
"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... | [
"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 foll... |
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... | [
"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,... | [
"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,
(... | [
"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 *... | [
"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':... | [
"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_... | [
"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... | [
"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 ... | [
"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 ... | [
"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:
pna... | [
"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 ... |
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()
# I... | [
"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... |
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
... | [
"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 b... | [
"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']:
... | [
"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 ... | [
"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 par... | [
"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_ac... | [
"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... |
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
... | [
"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 expressio... | [
"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. Pro... |
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)
... | [
"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... |
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
... | [
"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 \"... |
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')
... | [
"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 de... |
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)... | [
"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.param... | [
"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)
ret... | [
"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\"... |
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].spl... | [
"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 t... |
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)
xm... | [
"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 ... | [
"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... |
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 S... | [
"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 : Opti... |
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_... | [
"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 va... |
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')
... | [
"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 st... | [
"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',
... | [
"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:
... | [
"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 s... |
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.ed... | [
"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)
... | [
"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[n... | [
"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 even... |
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_n... | [
"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 = ... | [
"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... | [
"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 Phospho... |
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',
... | [
"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_no... | [
"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... |
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... | [
"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 subg... |
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 ... | [
"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 : Optio... |
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\... |
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.g... | [
"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... |
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 fram... | [
"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 incorre... | [
"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 divi... | [
"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()
ret... | [
"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, i... | [
"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\... |
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... | [
"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' ke... |
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 exp... | [] |
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():
... | [] |
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__):
... | [] |
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 isinsta... | [] |
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())
... | [
"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... | [
"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... |
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
... | [
"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 ... |
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')
... | [
"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
# Extra... | [
"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')... | [
"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... | [
"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('... | [
"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... | [
"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_re... | [
"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 ... | [
"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:
... | [
"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(control... | [
"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
r... | [
"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(... | [
"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']]... | [
"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('sen... | [
"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]
ret... | [
"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 h... | [
"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.