Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def stmts_to_json(stmts_in, use_sbo=False):
if not isinstance(stmts_in, list):
json_dict = stmts_in.to_json(use_sbo=use_sbo)
return json_dict
else:
json_dict = [st.to_json(use_sbo=use_sbo) for st in stmts_in]
return json_dict | [
"Return the JSON-serialized form of one or more INDRA Statements.\n\n Parameters\n ----------\n stmts_in : Statement or list[Statement]\n A Statement or list of Statement objects to serialize into JSON.\n use_sbo : Optional[bool]\n If True, SBO annotations are added to each applicable elem... |
Please provide a description of the function:def _promote_support(sup_list, uuid_dict, on_missing='handle'):
valid_handling_choices = ['handle', 'error', 'ignore']
if on_missing not in valid_handling_choices:
raise InputError('Invalid option for `on_missing_support`: \'%s\'\n'
... | [
"Promote the list of support-related uuids to Statements, if possible."
] |
Please provide a description of the function:def draw_stmt_graph(stmts):
import networkx
try:
import matplotlib.pyplot as plt
except Exception:
logger.error('Could not import matplotlib, not drawing graph.')
return
try: # This checks whether networkx has this package to wor... | [
"Render the attributes of a list of Statements as directed graphs.\n\n The layout works well for a single Statement or a few Statements at a time.\n This function displays the plot of the graph using plt.show().\n\n Parameters\n ----------\n stmts : list[indra.statements.Statement]\n A list of... |
Please provide a description of the function:def _fix_json_agents(ag_obj):
if isinstance(ag_obj, str):
logger.info("Fixing string agent: %s." % ag_obj)
ret = {'name': ag_obj, 'db_refs': {'TEXT': ag_obj}}
elif isinstance(ag_obj, list):
# Recursive for complexes and similar.
r... | [
"Fix the json representation of an agent."
] |
Please provide a description of the function:def set_statements_pmid(self, pmid):
# Replace PMID value in JSON dict first
for stmt in self.json_stmts:
evs = stmt.get('evidence', [])
for ev in evs:
ev['pmid'] = pmid
# Replace PMID value in extracte... | [
"Set the evidence PMID of Statements that have been extracted.\n\n Parameters\n ----------\n pmid : str or None\n The PMID to be used in the Evidence objects of the Statements\n that were extracted by the processor.\n "
] |
Please provide a description of the function:def get_args(node):
arg_roles = {}
args = node.findall('arg') + \
[node.find('arg1'), node.find('arg2'), node.find('arg3')]
for arg in args:
if arg is not None:
id = arg.attrib.get('id')
if id is not None:
... | [
"Return the arguments of a node in the event graph."
] |
Please provide a description of the function:def type_match(a, b):
# If the types are the same, return True
if a['type'] == b['type']:
return True
# Otherwise, look at some special cases
eq_groups = [
{'ONT::GENE-PROTEIN', 'ONT::GENE', 'ONT::PROTEIN'},
{'ONT::PHARMACOLOGIC-S... | [
"Return True of the types of a and b are compatible, False otherwise."
] |
Please provide a description of the function:def add_graph(patterns, G):
if not patterns:
patterns.append([G])
return
for i, graphs in enumerate(patterns):
if networkx.is_isomorphic(graphs[0], G, node_match=type_match,
edge_match=type_match):
... | [
"Add a graph to a set of unique patterns."
] |
Please provide a description of the function:def draw(graph, fname):
ag = networkx.nx_agraph.to_agraph(graph)
ag.draw(fname, prog='dot') | [
"Draw a graph and save it into a file"
] |
Please provide a description of the function:def build_patterns(fnames):
patterns = []
for fn in fnames:
et = ET.parse(fn)
res = et.findall('CC') + et.findall('EVENT')
for event in res:
G = networkx.DiGraph()
build_event_graph(G, et, event)
add_gr... | [
"Return a list of CC/EVENT graph patterns from a list of EKB files"
] |
Please provide a description of the function:def build_event_graph(graph, tree, node):
# If we have already added this node then let's return
if node_key(node) in graph:
return
type = get_type(node)
text = get_text(node)
label = '%s (%s)' % (type, text)
graph.add_node(node_key(node)... | [
"Return a DiGraph of a specific event structure, built recursively"
] |
Please provide a description of the function:def get_extracted_events(fnames):
event_list = []
for fn in fnames:
tp = trips.process_xml_file(fn)
ed = tp.extracted_events
for k, v in ed.items():
event_list += v
return event_list | [
"Get a full list of all extracted event IDs from a list of EKB files"
] |
Please provide a description of the function:def check_event_coverage(patterns, event_list):
proportions = []
for pattern_list in patterns:
proportion = 0
for pattern in pattern_list:
for node in pattern.nodes():
if node in event_list:
proport... | [
"Calculate the ratio of patterns that were extracted."
] |
Please provide a description of the function:def _load_wm_map(exclude_auto=None):
exclude_auto = [] if not exclude_auto else exclude_auto
path_here = os.path.dirname(os.path.abspath(__file__))
ontomap_file = os.path.join(path_here, '../resources/wm_ontomap.tsv')
mappings = {}
def make_hume_pre... | [
"Load an ontology map for world models.\n\n exclude_auto : None or list[tuple]\n A list of ontology mappings for which automated mappings should be\n excluded, e.g. [(HUME, UN)] would result in not using mappings\n from HUME to UN.\n ",
"We need to do this because the HUME prefixes are ... |
Please provide a description of the function:def map_statements(self):
for stmt in self.statements:
for agent in stmt.agent_list():
if agent is None:
continue
all_mappings = []
for db_name, db_id in agent.db_refs.items():
... | [
"Run the ontology mapping on the statements."
] |
Please provide a description of the function:def load_grounding_map(grounding_map_path, ignore_path=None,
lineterminator='\r\n'):
g_map = {}
map_rows = read_unicode_csv(grounding_map_path, delimiter=',',
quotechar='"',
q... | [
"Return a grounding map dictionary loaded from a csv file.\n\n In the file pointed to by grounding_map_path, the number of name_space ID\n pairs can vary per row and commas are\n used to pad out entries containing fewer than the maximum amount of\n name spaces appearing in the file. Lines should be term... |
Please provide a description of the function:def all_agents(stmts):
agents = []
for stmt in stmts:
for agent in stmt.agent_list():
# Agents don't always have a TEXT db_refs entry (for instance
# in the case of Statements from databases) so we check for this.
if a... | [
"Return a list of all of the agents from a list of statements.\n\n Only agents that are not None and have a TEXT entry are returned.\n\n Parameters\n ----------\n stmts : list of :py:class:`indra.statements.Statement`\n\n Returns\n -------\n agents : list of :py:class:`indra.statements.Agent`\n... |
Please provide a description of the function:def get_sentences_for_agent(text, stmts, max_sentences=None):
sentences = []
for stmt in stmts:
for agent in stmt.agent_list():
if agent is not None and agent.db_refs.get('TEXT') == text:
sentences.append((stmt.evidence[0].pmi... | [
"Returns evidence sentences with a given agent text from a list of statements\n\n Parameters\n ----------\n text : str\n An agent text\n\n stmts : list of :py:class:`indra.statements.Statement`\n INDRA Statements to search in for evidence statements.\n\n max_sentences : Optional[int/Non... |
Please provide a description of the function:def agent_texts_with_grounding(stmts):
allag = all_agents(stmts)
# Convert PFAM-DEF lists into tuples so that they are hashable and can
# be tabulated with a Counter
for ag in allag:
pfam_def = ag.db_refs.get('PFAM-DEF')
if pfam_def is no... | [
"Return agent text groundings in a list of statements with their counts\n\n Parameters\n ----------\n stmts: list of :py:class:`indra.statements.Statement`\n\n Returns\n -------\n list of tuple\n List of tuples of the form\n (text: str, ((name_space: str, ID: str, count: int)...),\n ... |
Please provide a description of the function:def ungrounded_texts(stmts):
ungrounded = [ag.db_refs['TEXT']
for s in stmts
for ag in s.agent_list()
if ag is not None and list(ag.db_refs.keys()) == ['TEXT']]
ungroundc = Counter(ungrounded)
ungroundc =... | [
"Return a list of all ungrounded entities ordered by number of mentions\n\n Parameters\n ----------\n stmts : list of :py:class:`indra.statements.Statement`\n\n Returns\n -------\n ungroundc : list of tuple\n list of tuples of the form (text: str, count: int) sorted in descending\n ord... |
Please provide a description of the function:def get_agents_with_name(name, stmts):
return [ag for stmt in stmts for ag in stmt.agent_list()
if ag is not None and ag.name == name] | [
"Return all agents within a list of statements with a particular name."
] |
Please provide a description of the function:def save_base_map(filename, grouped_by_text):
rows = []
for group in grouped_by_text:
text_string = group[0]
for db, db_id, count in group[1]:
if db == 'UP':
name = uniprot_client.get_mnemonic(db_id)
else:
... | [
"Dump a list of agents along with groundings and counts into a csv file\n\n Parameters\n ----------\n filename : str\n Filepath for output file\n grouped_by_text : list of tuple\n List of tuples of the form output by agent_texts_with_grounding\n "
] |
Please provide a description of the function:def protein_map_from_twg(twg):
protein_map = {}
unmatched = 0
matched = 0
logger.info('Building grounding map for human proteins')
for agent_text, grounding_list, _ in twg:
# If 'UP' (Uniprot) not one of the grounding entries for this text,
... | [
"Build map of entity texts to validate protein grounding.\n\n Looks at the grounding of the entity texts extracted from the statements\n and finds proteins where there is grounding to a human protein that maps to\n an HGNC name that is an exact match to the entity text. Returns a dict that\n can be use... |
Please provide a description of the function:def save_sentences(twg, stmts, filename, agent_limit=300):
sentences = []
unmapped_texts = [t[0] for t in twg]
counter = 0
logger.info('Getting sentences for top %d unmapped agent texts.' %
agent_limit)
for text in unmapped_texts:
... | [
"Write evidence sentences for stmts with ungrounded agents to csv file.\n\n Parameters\n ----------\n twg: list of tuple\n list of tuples of ungrounded agent_texts with counts of the\n number of times they are mentioned in the list of statements.\n Should be sorted in descending order ... |
Please provide a description of the function:def _get_text_for_grounding(stmt, agent_text):
text = None
# First we will try to get content from the DB
try:
from indra_db.util.content_scripts \
import get_text_content_from_text_refs
from indra.literature.deft_tools import uni... | [
"Get text context for Deft disambiguation\n\n If the INDRA database is available, attempts to get the fulltext from\n which the statement was extracted. If the fulltext is not available, the\n abstract is returned. If the indra database is not available, uses the\n pubmed client to get the abstract. If ... |
Please provide a description of the function:def update_agent_db_refs(self, agent, agent_text, do_rename=True):
map_db_refs = deepcopy(self.gm.get(agent_text))
self.standardize_agent_db_refs(agent, map_db_refs, do_rename) | [
"Update db_refs of agent using the grounding map\n\n If the grounding map is missing one of the HGNC symbol or Uniprot ID,\n attempts to reconstruct one from the other.\n\n Parameters\n ----------\n agent : :py:class:`indra.statements.Agent`\n The agent whose db_refs wi... |
Please provide a description of the function:def map_agents_for_stmt(self, stmt, do_rename=True):
mapped_stmt = deepcopy(stmt)
# Iterate over the agents
# Update agents directly participating in the statement
agent_list = mapped_stmt.agent_list()
for idx, agent in enume... | [
"Return a new Statement whose agents have been grounding mapped.\n\n Parameters\n ----------\n stmt : :py:class:`indra.statements.Statement`\n The Statement whose agents need mapping.\n do_rename: Optional[bool]\n If True, the Agent name is updated based on the mapp... |
Please provide a description of the function:def map_agent(self, agent, do_rename):
agent_text = agent.db_refs.get('TEXT')
mapped_to_agent_json = self.agent_map.get(agent_text)
if mapped_to_agent_json:
mapped_to_agent = \
Agent._from_json(mapped_to_agent_jso... | [
"Return the given Agent with its grounding mapped.\n\n This function grounds a single agent. It returns the new Agent object\n (which might be a different object if we load a new agent state\n from json) or the same object otherwise.\n\n Parameters\n ----------\n agent : :p... |
Please provide a description of the function:def map_agents(self, stmts, do_rename=True):
# Make a copy of the stmts
mapped_stmts = []
num_skipped = 0
# Iterate over the statements
for stmt in stmts:
mapped_stmt = self.map_agents_for_stmt(stmt, do_rename)
... | [
"Return a new list of statements whose agents have been mapped\n\n Parameters\n ----------\n stmts : list of :py:class:`indra.statements.Statement`\n The statements whose agents need mapping\n do_rename: Optional[bool]\n If True, the Agent name is updated based on t... |
Please provide a description of the function:def rename_agents(self, stmts):
# Make a copy of the stmts
mapped_stmts = deepcopy(stmts)
# Iterate over the statements
for _, stmt in enumerate(mapped_stmts):
# Iterate over the agents
for agent in stmt.agent_... | [
"Return a list of mapped statements with updated agent names.\n\n Creates a new list of statements without modifying the original list.\n\n The agents in a statement should be renamed if the grounding map has\n updated their db_refs. If an agent contains a FamPlex grounding, the\n FamPle... |
Please provide a description of the function:def get_complexes(self, cplx_df):
# Group the agents for the complex
logger.info('Processing complexes...')
for cplx_id, this_cplx in cplx_df.groupby('CPLX_ID'):
agents = []
for hprd_id in this_cplx.HPRD_ID:
... | [
"Generate Complex Statements from the HPRD protein complexes data.\n\n Parameters\n ----------\n cplx_df : pandas.DataFrame\n DataFrame loaded from the PROTEIN_COMPLEXES.txt file.\n "
] |
Please provide a description of the function:def get_ptms(self, ptm_df):
logger.info('Processing PTMs...')
# Iterate over the rows of the dataframe
for ix, row in ptm_df.iterrows():
# Check the modification type; if we can't make an INDRA statement
# for it, then... | [
"Generate Modification statements from the HPRD PTM data.\n\n Parameters\n ----------\n ptm_df : pandas.DataFrame\n DataFrame loaded from the POST_TRANSLATIONAL_MODIFICATIONS.txt file.\n "
] |
Please provide a description of the function:def get_ppis(self, ppi_df):
logger.info('Processing PPIs...')
for ix, row in ppi_df.iterrows():
agA = self._make_agent(row['HPRD_ID_A'])
agB = self._make_agent(row['HPRD_ID_B'])
# If don't get valid agents for both... | [
"Generate Complex Statements from the HPRD PPI data.\n\n Parameters\n ----------\n ppi_df : pandas.DataFrame\n DataFrame loaded from the BINARY_PROTEIN_PROTEIN_INTERACTIONS.txt\n file.\n "
] |
Please provide a description of the function:def _build_verb_statement_mapping():
path_this = os.path.dirname(os.path.abspath(__file__))
map_path = os.path.join(path_this, 'isi_verb_to_indra_statement_type.tsv')
with open(map_path, 'r') as f:
first_line = True
verb_to_statement_type = {... | [
"Build the mapping between ISI verb strings and INDRA statement classes.\n\n Looks up the INDRA statement class name, if any, in a resource file,\n and resolves this class name to a class.\n\n Returns\n -------\n verb_to_statement_type : dict\n Dictionary mapping verb name to an INDRA statment... |
Please provide a description of the function:def get_statements(self):
for k, v in self.reader_output.items():
for interaction in v['interactions']:
self._process_interaction(k, interaction, v['text'], self.pmid,
self.extra_annotatio... | [
"Process reader output to produce INDRA Statements."
] |
Please provide a description of the function:def _process_interaction(self, source_id, interaction, text, pmid,
extra_annotations):
verb = interaction[0].lower()
subj = interaction[-2]
obj = interaction[-1]
# Make ungrounded agent objects for the su... | [
"Process an interaction JSON tuple from the ISI output, and adds up\n to one statement to the list of extracted statements.\n\n Parameters\n ----------\n source_id : str\n the JSON key corresponding to the sentence in the ISI output\n interaction: the JSON list with... |
Please provide a description of the function:def make_annotation(self):
annotation = dict()
# Put all properties of the action object into the annotation
for item in dir(self):
if len(item) > 0 and item[0] != '_' and \
not inspect.ismethod(getattr(self, ... | [
"Returns a dictionary with all properties of the action mention."
] |
Please provide a description of the function:def _match_to_array(m):
return [_cast_biopax_element(m.get(i)) for i in range(m.varSize())] | [
" Returns an array consisting of the elements obtained from a pattern\n search cast into their appropriate classes. "
] |
Please provide a description of the function:def _is_complex(pe):
val = isinstance(pe, _bp('Complex')) or \
isinstance(pe, _bpimpl('Complex'))
return val | [
"Return True if the physical entity is a complex"
] |
Please provide a description of the function:def _is_protein(pe):
val = isinstance(pe, _bp('Protein')) or \
isinstance(pe, _bpimpl('Protein')) or \
isinstance(pe, _bp('ProteinReference')) or \
isinstance(pe, _bpimpl('ProteinReference'))
return val | [
"Return True if the element is a protein"
] |
Please provide a description of the function:def _is_rna(pe):
val = isinstance(pe, _bp('Rna')) or isinstance(pe, _bpimpl('Rna'))
return val | [
"Return True if the element is an RNA"
] |
Please provide a description of the function:def _is_small_molecule(pe):
val = isinstance(pe, _bp('SmallMolecule')) or \
isinstance(pe, _bpimpl('SmallMolecule')) or \
isinstance(pe, _bp('SmallMoleculeReference')) or \
isinstance(pe, _bpimpl('SmallMoleculeReference'))
ret... | [
"Return True if the element is a small molecule"
] |
Please provide a description of the function:def _is_physical_entity(pe):
val = isinstance(pe, _bp('PhysicalEntity')) or \
isinstance(pe, _bpimpl('PhysicalEntity'))
return val | [
"Return True if the element is a physical entity"
] |
Please provide a description of the function:def _is_modification_or_activity(feature):
if not (isinstance(feature, _bp('ModificationFeature')) or \
isinstance(feature, _bpimpl('ModificationFeature'))):
return None
mf_type = feature.getModificationType()
if mf_type is None:
... | [
"Return True if the feature is a modification"
] |
Please provide a description of the function:def _is_reference(bpe):
if isinstance(bpe, _bp('ProteinReference')) or \
isinstance(bpe, _bpimpl('ProteinReference')) or \
isinstance(bpe, _bp('SmallMoleculeReference')) or \
isinstance(bpe, _bpimpl('SmallMoleculeReference')) or \
isi... | [
"Return True if the element is an entity reference."
] |
Please provide a description of the function:def _is_entity(bpe):
if isinstance(bpe, _bp('Protein')) or \
isinstance(bpe, _bpimpl('Protein')) or \
isinstance(bpe, _bp('SmallMolecule')) or \
isinstance(bpe, _bpimpl('SmallMolecule')) or \
isinstance(bpe, _bp('Complex')) or \
... | [
"Return True if the element is a physical entity."
] |
Please provide a description of the function:def _is_catalysis(bpe):
if isinstance(bpe, _bp('Catalysis')) or \
isinstance(bpe, _bpimpl('Catalysis')):
return True
else:
return False | [
"Return True if the element is Catalysis."
] |
Please provide a description of the function:def print_statements(self):
for i, stmt in enumerate(self.statements):
print("%s: %s" % (i, stmt)) | [
"Print all INDRA Statements collected by the processors."
] |
Please provide a description of the function:def save_model(self, file_name=None):
if file_name is None:
logger.error('Missing file name')
return
pcc.model_to_owl(self.model, file_name) | [
"Save the BioPAX model object in an OWL file.\n\n Parameters\n ----------\n file_name : Optional[str]\n The name of the OWL file to save the model in.\n "
] |
Please provide a description of the function:def eliminate_exact_duplicates(self):
# Here we use the deep hash of each Statement, and by making a dict,
# we effectively keep only one Statement with a given deep hash
self.statements = list({stmt.get_hash(shallow=False, refresh=True): stm... | [
"Eliminate Statements that were extracted multiple times.\n\n Due to the way the patterns are implemented, they can sometimes yield\n the same Statement information multiple times, in which case,\n we end up with redundant Statements that aren't from independent\n underlying entries. To ... |
Please provide a description of the function:def get_complexes(self):
for obj in self.model.getObjects().toArray():
bpe = _cast_biopax_element(obj)
if not _is_complex(bpe):
continue
ev = self._get_evidence(bpe)
members = self._get_complex... | [
"Extract INDRA Complex Statements from the BioPAX model.\n\n This method searches for org.biopax.paxtools.model.level3.Complex\n objects which represent molecular complexes. It doesn't reuse\n BioPAX Pattern's org.biopax.paxtools.pattern.PatternBox.inComplexWith\n query since that retrie... |
Please provide a description of the function:def get_modifications(self):
for modtype, modclass in modtype_to_modclass.items():
# TODO: we could possibly try to also extract generic
# modifications here
if modtype == 'modification':
continue
... | [
"Extract INDRA Modification Statements from the BioPAX model.\n\n To extract Modifications, this method reuses the structure of\n BioPAX Pattern's\n org.biopax.paxtools.pattern.PatternBox.constrolsStateChange pattern\n with additional constraints to specify the type of state change\n ... |
Please provide a description of the function:def get_activity_modification(self):
mod_filter = 'residue modification, active'
for is_active in [True, False]:
p = self._construct_modification_pattern()
rel = mcct.GAIN if is_active else mcct.LOSS
p.add(mcc(rel,... | [
"Extract INDRA ActiveForm statements from the BioPAX model.\n\n This method extracts ActiveForm Statements that are due to\n protein modifications. This method reuses the structure of\n BioPAX Pattern's\n org.biopax.paxtools.pattern.PatternBox.constrolsStateChange pattern\n with a... |
Please provide a description of the function:def get_regulate_activities(self):
mcc = _bpp('constraint.ModificationChangeConstraint')
mcct = _bpp('constraint.ModificationChangeConstraint$Type')
mod_filter = 'residue modification, active'
# Start with a generic modification patte... | [
"Get Activation/Inhibition INDRA Statements from the BioPAX model.\n\n This method extracts Activation/Inhibition Statements and reuses the\n structure of BioPAX Pattern's\n org.biopax.paxtools.pattern.PatternBox.constrolsStateChange pattern\n with additional constraints to specify the g... |
Please provide a description of the function:def get_regulate_amounts(self):
p = pb.controlsExpressionWithTemplateReac()
s = _bpp('Searcher')
res = s.searchPlain(self.model, p)
res_array = [_match_to_array(m) for m in res.toArray()]
stmts = []
for res in res_arra... | [
"Extract INDRA RegulateAmount Statements from the BioPAX model.\n\n This method extracts IncreaseAmount/DecreaseAmount Statements from\n the BioPAX model. It fully reuses BioPAX Pattern's\n org.biopax.paxtools.pattern.PatternBox.controlsExpressionWithTemplateReac\n pattern to find Templa... |
Please provide a description of the function:def get_conversions(self):
# NOTE: This pattern gets all reactions in which a protein is the
# controller and chemicals are converted. But with this pattern only
# a single chemical is extracted from each side. This can be misleading
... | [
"Extract Conversion INDRA Statements from the BioPAX model.\n\n This method uses a custom BioPAX Pattern\n (one that is not implemented PatternBox) to query for\n BiochemicalReactions whose left and right hand sides are collections\n of SmallMolecules. This pattern thereby extracts metab... |
Please provide a description of the function:def get_gef(self):
p = self._gef_gap_base()
s = _bpp('Searcher')
res = s.searchPlain(self.model, p)
res_array = [_match_to_array(m) for m in res.toArray()]
for r in res_array:
controller_pe = r[p.indexOf('controlle... | [
"Extract Gef INDRA Statements from the BioPAX model.\n\n This method uses a custom BioPAX Pattern\n (one that is not implemented PatternBox) to query for controlled\n BiochemicalReactions in which the same protein is in complex with\n GDP on the left hand side and in complex with GTP on ... |
Please provide a description of the function:def get_gap(self):
p = self._gef_gap_base()
s = _bpp('Searcher')
res = s.searchPlain(self.model, p)
res_array = [_match_to_array(m) for m in res.toArray()]
for r in res_array:
controller_pe = r[p.indexOf('controlle... | [
"Extract Gap INDRA Statements from the BioPAX model.\n\n This method uses a custom BioPAX Pattern\n (one that is not implemented PatternBox) to query for controlled\n BiochemicalReactions in which the same protein is in complex with\n GTP on the left hand side and in complex with GDP on ... |
Please provide a description of the function:def _get_entity_mods(bpe):
if _is_entity(bpe):
features = bpe.getFeature().toArray()
else:
features = bpe.getEntityFeature().toArray()
mods = []
for feature in features:
if not _is_modification(feat... | [
"Get all the modifications of an entity in INDRA format"
] |
Please provide a description of the function:def _get_generic_modification(self, mod_class):
mod_type = modclass_to_modtype[mod_class]
if issubclass(mod_class, RemoveModification):
mod_gain_const = mcct.LOSS
mod_type = modtype_to_inverse[mod_type]
else:
... | [
"Get all modification reactions given a Modification class."
] |
Please provide a description of the function:def _construct_modification_pattern():
# The following constraints were pieced together based on the
# following two higher level constrains: pb.controlsStateChange(),
# pb.controlsPhosphorylation().
p = _bpp('Pattern')(_bpimpl('Physi... | [
"Construct the BioPAX pattern to extract modification reactions."
] |
Please provide a description of the function:def _extract_mod_from_feature(mf):
# ModificationFeature / SequenceModificationVocabulary
mf_type = mf.getModificationType()
if mf_type is None:
return None
mf_type_terms = mf_type.getTerm().toArray()
known_mf_type... | [
"Extract the type of modification and the position from\n a ModificationFeature object in the INDRA format."
] |
Please provide a description of the function:def _get_entref(bpe):
if not _is_reference(bpe):
try:
er = bpe.getEntityReference()
except AttributeError:
return None
return er
else:
return bpe | [
"Returns the entity reference of an entity if it exists or\n return the entity reference that was passed in as argument."
] |
Please provide a description of the function:def _stmt_location_to_agents(stmt, location):
if location is None:
return
agents = stmt.agent_list()
for a in agents:
if a is not None:
a.location = location | [
"Apply an event location to the Agents in the corresponding Statement.\n\n If a Statement is in a given location we represent that by requiring all\n Agents in the Statement to be in that location.\n "
] |
Please provide a description of the function:def _get_db_refs(term):
db_refs = {}
# Here we extract the text name of the Agent
# There are two relevant tags to consider here.
# The <text> tag typically contains a larger phrase surrounding the
# term but it contains the term in a raw, non-canoni... | [
"Extract database references for a TERM."
] |
Please provide a description of the function:def get_all_events(self):
self.all_events = {}
events = self.tree.findall('EVENT')
events += self.tree.findall('CC')
for e in events:
event_id = e.attrib['id']
if event_id in self._static_events:
... | [
"Make a list of all events in the TRIPS EKB.\n\n The events are stored in self.all_events.\n "
] |
Please provide a description of the function:def get_activations(self):
act_events = self.tree.findall("EVENT/[type='ONT::ACTIVATE']")
inact_events = self.tree.findall("EVENT/[type='ONT::DEACTIVATE']")
inact_events += self.tree.findall("EVENT/[type='ONT::INHIBIT']")
for event in... | [
"Extract direct Activation INDRA Statements."
] |
Please provide a description of the function:def get_activations_causal(self):
# Search for causal connectives of type ONT::CAUSE
ccs = self.tree.findall("CC/[type='ONT::CAUSE']")
for cc in ccs:
factor = cc.find("arg/[@role=':FACTOR']")
outcome = cc.find("arg/[@r... | [
"Extract causal Activation INDRA Statements."
] |
Please provide a description of the function:def get_activations_stimulate(self):
# TODO: extract to other patterns:
# - Stimulation by EGF activates ERK
# - Stimulation by EGF leads to ERK activation
# Search for stimulation event
stim_events = self.tree.findall("EVENT/... | [
"Extract Activation INDRA Statements via stimulation."
] |
Please provide a description of the function:def get_degradations(self):
deg_events = self.tree.findall("EVENT/[type='ONT::CONSUME']")
for event in deg_events:
if event.attrib['id'] in self._static_events:
continue
affected = event.find(".//*[@role=':AFFE... | [
"Extract Degradation INDRA Statements."
] |
Please provide a description of the function:def get_regulate_amounts(self):
pos_events = []
neg_events = []
pattern = "EVENT/[type='ONT::STIMULATE']/arg2/[type='ONT::TRANSCRIBE']/.."
pos_events += self.tree.findall(pattern)
pattern = "EVENT/[type='ONT::INCREASE']/arg2/[... | [
"Extract Increase/DecreaseAmount Statements."
] |
Please provide a description of the function:def get_active_forms(self):
act_events = self.tree.findall("EVENT/[type='ONT::ACTIVATE']")
def _agent_is_basic(agent):
if not agent.mods and not agent.mutations \
and not agent.bound_conditions and not agent.location:
... | [
"Extract ActiveForm INDRA Statements."
] |
Please provide a description of the function:def get_active_forms_state(self):
for term in self._isolated_terms:
act = term.find('features/active')
if act is None:
continue
if act.text == 'TRUE':
is_active = True
elif act.t... | [
"Extract ActiveForm INDRA Statements."
] |
Please provide a description of the function:def get_complexes(self):
bind_events = self.tree.findall("EVENT/[type='ONT::BIND']")
bind_events += self.tree.findall("EVENT/[type='ONT::INTERACT']")
for event in bind_events:
if event.attrib['id'] in self._static_events:
... | [
"Extract Complex INDRA Statements."
] |
Please provide a description of the function:def get_modifications(self):
# Get all the specific mod types
mod_event_types = list(ont_to_mod_type.keys())
# Add ONT::PTMs as a special case
mod_event_types += ['ONT::PTM']
mod_events = []
for mod_event_type in mod_e... | [
"Extract all types of Modification INDRA Statements."
] |
Please provide a description of the function:def get_modifications_indirect(self):
# Get all the specific mod types
mod_event_types = list(ont_to_mod_type.keys())
# Add ONT::PTMs as a special case
mod_event_types += ['ONT::PTM']
def get_increase_events(mod_event_types):... | [
"Extract indirect Modification INDRA Statements."
] |
Please provide a description of the function:def get_agents(self):
agents_dict = self.get_term_agents()
agents = [a for a in agents_dict.values() if a is not None]
return agents | [
"Return list of INDRA Agents corresponding to TERMs in the EKB.\n\n This is meant to be used when entities e.g. \"phosphorylated ERK\",\n rather than events need to be extracted from processed natural\n language. These entities with their respective states are represented\n as INDRA Agen... |
Please provide a description of the function:def get_term_agents(self):
terms = self.tree.findall('TERM')
agents = {}
assoc_links = []
for term in terms:
term_id = term.attrib.get('id')
if term_id:
agent = self._get_agent_by_id(term_id, No... | [
"Return dict of INDRA Agents keyed by corresponding TERMs in the EKB.\n\n This is meant to be used when entities e.g. \"phosphorylated ERK\",\n rather than events need to be extracted from processed natural\n language. These entities with their respective states are represented\n as INDR... |
Please provide a description of the function:def _get_evidence_text(self, event_tag):
par_id = event_tag.attrib.get('paragraph')
uttnum = event_tag.attrib.get('uttnum')
event_text = event_tag.find('text')
if self.sentences is not None and uttnum is not None:
sentence... | [
"Extract the evidence for an event.\n\n Pieces of text linked to an EVENT are fragments of a sentence. The\n EVENT refers to the paragraph ID and the \"uttnum\", which corresponds\n to a sentence ID. Here we find and return the full sentence from which\n the event was taken.\n "
] |
Please provide a description of the function:def _get_agent_grounding(agent):
def _get_id(_agent, key):
_id = _agent.db_refs.get(key)
if isinstance(_id, list):
_id = _id[0]
return _id
hgnc_id = _get_id(agent, 'HGNC')
if hgnc_id:
hgnc_name = hgnc_client.get_h... | [
"Convert an agent to the corresponding PyBEL DSL object (to be filled with variants later)."
] |
Please provide a description of the function:def get_causal_edge(stmt, activates):
any_contact = any(
evidence.epistemics.get('direct', False)
for evidence in stmt.evidence
)
if any_contact:
return pc.DIRECTLY_INCREASES if activates else pc.DIRECTLY_DECREASES
return pc.INCR... | [
"Returns the causal, polar edge with the correct \"contact\"."
] |
Please provide a description of the function:def to_database(self, manager=None):
network = pybel.to_database(self.model, manager=manager)
return network | [
"Send the model to the PyBEL database\n\n This function wraps :py:func:`pybel.to_database`.\n\n Parameters\n ----------\n manager : Optional[pybel.manager.Manager]\n A PyBEL database manager. If none, first checks the PyBEL\n configuration for ``PYBEL_CONNECTION`` t... |
Please provide a description of the function:def to_web(self, host=None, user=None, password=None):
response = pybel.to_web(self.model, host=host, user=user,
password=password)
return response | [
"Send the model to BEL Commons by wrapping :py:func:`pybel.to_web`\n\n The parameters ``host``, ``user``, and ``password`` all check the\n PyBEL configuration, which is located at\n ``~/.config/pybel/config.json`` by default\n\n Parameters\n ----------\n host : Optional[str... |
Please provide a description of the function:def save_model(self, path, output_format=None):
if output_format == 'pickle':
pybel.to_pickle(self.model, path)
else:
with open(path, 'w') as fh:
if output_format == 'json':
pybel.to_json_fi... | [
"Save the :class:`pybel.BELGraph` using one of the outputs from\n :py:mod:`pybel`\n\n Parameters\n ----------\n path : str\n The path to output to\n output_format : Optional[str]\n Output format as ``cx``, ``pickle``, ``json`` or defaults to ``bel``\n ... |
Please provide a description of the function:def _add_nodes_edges(self, subj_agent, obj_agent, relation, evidences):
subj_data, subj_edge = _get_agent_node(subj_agent)
obj_data, obj_edge = _get_agent_node(obj_agent)
# If we failed to create nodes for subject or object, skip it
i... | [
"Given subj/obj agents, relation, and evidence, add nodes/edges."
] |
Please provide a description of the function:def _assemble_regulate_activity(self, stmt):
act_obj = deepcopy(stmt.obj)
act_obj.activity = stmt._get_activity_condition()
# We set is_active to True here since the polarity is encoded
# in the edge (decreases/increases)
act_... | [
"Example: p(HGNC:MAP2K1) => act(p(HGNC:MAPK1))"
] |
Please provide a description of the function:def _assemble_modification(self, stmt):
sub_agent = deepcopy(stmt.sub)
sub_agent.mods.append(stmt._get_mod_condition())
activates = isinstance(stmt, AddModification)
relation = get_causal_edge(stmt, activates)
self._add_nodes_... | [
"Example: p(HGNC:MAP2K1) => p(HGNC:MAPK1, pmod(Ph, Thr, 185))"
] |
Please provide a description of the function:def _assemble_regulate_amount(self, stmt):
activates = isinstance(stmt, IncreaseAmount)
relation = get_causal_edge(stmt, activates)
self._add_nodes_edges(stmt.subj, stmt.obj, relation, stmt.evidence) | [
"Example: p(HGNC:ELK1) => p(HGNC:FOS)"
] |
Please provide a description of the function:def _assemble_gef(self, stmt):
gef = deepcopy(stmt.gef)
gef.activity = ActivityCondition('gef', True)
ras = deepcopy(stmt.ras)
ras.activity = ActivityCondition('gtpbound', True)
self._add_nodes_edges(gef, ras, pc.DIRECTLY_INCR... | [
"Example: act(p(HGNC:SOS1), ma(gef)) => act(p(HGNC:KRAS), ma(gtp))"
] |
Please provide a description of the function:def _assemble_gap(self, stmt):
gap = deepcopy(stmt.gap)
gap.activity = ActivityCondition('gap', True)
ras = deepcopy(stmt.ras)
ras.activity = ActivityCondition('gtpbound', True)
self._add_nodes_edges(gap, ras, pc.DIRECTLY_DECR... | [
"Example: act(p(HGNC:RASA1), ma(gap)) =| act(p(HGNC:KRAS), ma(gtp))"
] |
Please provide a description of the function:def _assemble_active_form(self, stmt):
act_agent = Agent(stmt.agent.name, db_refs=stmt.agent.db_refs)
act_agent.activity = ActivityCondition(stmt.activity, True)
activates = stmt.is_active
relation = get_causal_edge(stmt, activates)
... | [
"Example: p(HGNC:ELK1, pmod(Ph)) => act(p(HGNC:ELK1), ma(tscript))"
] |
Please provide a description of the function:def _assemble_complex(self, stmt):
complex_data, _ = _get_complex_node(stmt.members)
if complex_data is None:
logger.info('skip adding complex with no members: %s', stmt.members)
return
self.model.add_node_from_data(co... | [
"Example: complex(p(HGNC:MAPK14), p(HGNC:TAB1))"
] |
Please provide a description of the function:def _assemble_conversion(self, stmt):
pybel_lists = ([], [])
for pybel_list, agent_list in \
zip(pybel_lists, (stmt.obj_from, stmt.obj_to)):
for agent in agent_list:
node = _get_agent_grounding(... | [
"Example: p(HGNC:HK1) => rxn(reactants(a(CHEBI:\"CHEBI:17634\")),\n products(a(CHEBI:\"CHEBI:4170\")))"
] |
Please provide a description of the function:def _assemble_autophosphorylation(self, stmt):
sub_agent = deepcopy(stmt.enz)
mc = stmt._get_mod_condition()
sub_agent.mods.append(mc)
# FIXME Ignore any bound conditions on the substrate!!!
# This is because if they are inclu... | [
"Example: complex(p(HGNC:MAPK14), p(HGNC:TAB1)) =>\n p(HGNC:MAPK14, pmod(Ph, Tyr, 100))"
] |
Please provide a description of the function:def _assemble_transphosphorylation(self, stmt):
# Check our assumptions about the bound condition of the enzyme
assert len(stmt.enz.bound_conditions) == 1
assert stmt.enz.bound_conditions[0].is_bound
# Create a modified protein node f... | [
"Example: complex(p(HGNC:EGFR)) =>\n p(HGNC:EGFR, pmod(Ph, Tyr, 1173))"
] |
Please provide a description of the function:def get_binding_site_name(agent):
# Try to construct a binding site name based on parent
grounding = agent.get_grounding()
if grounding != (None, None):
uri = hierarchies['entity'].get_uri(grounding[0], grounding[1])
# Get highest level paren... | [
"Return a binding site name from a given agent."
] |
Please provide a description of the function:def get_mod_site_name(mod_condition):
if mod_condition.residue is None:
mod_str = abbrevs[mod_condition.mod_type]
else:
mod_str = mod_condition.residue
mod_pos = mod_condition.position if \
mod_condition.position is not None else ''
... | [
"Return site names for a modification."
] |
Please provide a description of the function:def process_flat_files(id_mappings_file, complexes_file=None, ptm_file=None,
ppi_file=None, seq_file=None, motif_window=7):
id_df = pd.read_csv(id_mappings_file, delimiter='\t', names=_hprd_id_cols,
dtype='str')
id_... | [
"Get INDRA Statements from HPRD data.\n\n Of the arguments, `id_mappings_file` is required, and at least one of\n `complexes_file`, `ptm_file`, and `ppi_file` must also be given. If\n `ptm_file` is given, `seq_file` must also be given.\n\n Note that many proteins (> 1,600) in the HPRD content are assoc... |
Please provide a description of the function:def _gather_active_forms(self):
for stmt in self.statements:
if isinstance(stmt, ActiveForm):
base_agent = self.agent_set.get_create_base_agent(stmt.agent)
# Handle the case where an activity flag is set
... | [
"Collect all the active forms of each Agent in the Statements."
] |
Please provide a description of the function:def replace_activities(self):
logger.debug('Running PySB Preassembler replace activities')
# TODO: handle activity hierarchies
new_stmts = []
def has_agent_activity(stmt):
for agent in stmt.agent_list():
... | [
"Replace ative flags with Agent states when possible.",
"Return True if any agents in the Statement have activity."
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.