id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
18,800
sorgerlab/indra
indra/sources/hprd/processor.py
HprdProcessor.get_complexes
def get_complexes(self, cplx_df): """Generate Complex Statements from the HPRD protein complexes data. Parameters ---------- cplx_df : pandas.DataFrame DataFrame loaded from the PROTEIN_COMPLEXES.txt file. """ # 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: ag = self._make_agent(hprd_id) if ag is not None: agents.append(ag) # Make sure we got some agents! if not agents: continue # Get evidence info from first member of complex row0 = this_cplx.iloc[0] isoform_id = '%s_1' % row0.HPRD_ID ev_list = self._get_evidence(row0.HPRD_ID, isoform_id, row0.PMIDS, row0.EVIDENCE, 'interactions') stmt = Complex(agents, evidence=ev_list) self.statements.append(stmt)
python
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: ag = self._make_agent(hprd_id) if ag is not None: agents.append(ag) # Make sure we got some agents! if not agents: continue # Get evidence info from first member of complex row0 = this_cplx.iloc[0] isoform_id = '%s_1' % row0.HPRD_ID ev_list = self._get_evidence(row0.HPRD_ID, isoform_id, row0.PMIDS, row0.EVIDENCE, 'interactions') stmt = Complex(agents, evidence=ev_list) self.statements.append(stmt)
[ "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'", ")", ":", "a...
Generate Complex Statements from the HPRD protein complexes data. Parameters ---------- cplx_df : pandas.DataFrame DataFrame loaded from the PROTEIN_COMPLEXES.txt file.
[ "Generate", "Complex", "Statements", "from", "the", "HPRD", "protein", "complexes", "data", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/hprd/processor.py#L151-L176
18,801
sorgerlab/indra
indra/sources/hprd/processor.py
HprdProcessor.get_ptms
def get_ptms(self, ptm_df): """Generate Modification statements from the HPRD PTM data. Parameters ---------- ptm_df : pandas.DataFrame DataFrame loaded from the POST_TRANSLATIONAL_MODIFICATIONS.txt file. """ 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 skip it ptm_class = _ptm_map[row['MOD_TYPE']] if ptm_class is None: continue # Use the Refseq protein ID for the substrate to make sure that # we get the right Uniprot ID for the isoform sub_ag = self._make_agent(row['HPRD_ID'], refseq_id=row['REFSEQ_PROTEIN']) # If we couldn't get the substrate, skip the statement if sub_ag is None: continue enz_id = _nan_to_none(row['ENZ_HPRD_ID']) enz_ag = self._make_agent(enz_id) res = _nan_to_none(row['RESIDUE']) pos = _nan_to_none(row['POSITION']) if pos is not None and ';' in pos: pos, dash = pos.split(';') assert dash == '-' # As a fallback for later site mapping, we also get the protein # sequence information in case there was a problem with the # RefSeq->Uniprot mapping assert res assert pos motif_dict = self._get_seq_motif(row['REFSEQ_PROTEIN'], res, pos) # Get evidence ev_list = self._get_evidence( row['HPRD_ID'], row['HPRD_ISOFORM'], row['PMIDS'], row['EVIDENCE'], 'ptms', motif_dict) stmt = ptm_class(enz_ag, sub_ag, res, pos, evidence=ev_list) self.statements.append(stmt)
python
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 skip it ptm_class = _ptm_map[row['MOD_TYPE']] if ptm_class is None: continue # Use the Refseq protein ID for the substrate to make sure that # we get the right Uniprot ID for the isoform sub_ag = self._make_agent(row['HPRD_ID'], refseq_id=row['REFSEQ_PROTEIN']) # If we couldn't get the substrate, skip the statement if sub_ag is None: continue enz_id = _nan_to_none(row['ENZ_HPRD_ID']) enz_ag = self._make_agent(enz_id) res = _nan_to_none(row['RESIDUE']) pos = _nan_to_none(row['POSITION']) if pos is not None and ';' in pos: pos, dash = pos.split(';') assert dash == '-' # As a fallback for later site mapping, we also get the protein # sequence information in case there was a problem with the # RefSeq->Uniprot mapping assert res assert pos motif_dict = self._get_seq_motif(row['REFSEQ_PROTEIN'], res, pos) # Get evidence ev_list = self._get_evidence( row['HPRD_ID'], row['HPRD_ISOFORM'], row['PMIDS'], row['EVIDENCE'], 'ptms', motif_dict) stmt = ptm_class(enz_ag, sub_ag, res, pos, evidence=ev_list) self.statements.append(stmt)
[ "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; i...
Generate Modification statements from the HPRD PTM data. Parameters ---------- ptm_df : pandas.DataFrame DataFrame loaded from the POST_TRANSLATIONAL_MODIFICATIONS.txt file.
[ "Generate", "Modification", "statements", "from", "the", "HPRD", "PTM", "data", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/hprd/processor.py#L178-L220
18,802
sorgerlab/indra
indra/sources/hprd/processor.py
HprdProcessor.get_ppis
def get_ppis(self, ppi_df): """Generate Complex Statements from the HPRD PPI data. Parameters ---------- ppi_df : pandas.DataFrame DataFrame loaded from the BINARY_PROTEIN_PROTEIN_INTERACTIONS.txt file. """ 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, skip this PPI if agA is None or agB is None: continue isoform_id = '%s_1' % row['HPRD_ID_A'] ev_list = self._get_evidence( row['HPRD_ID_A'], isoform_id, row['PMIDS'], row['EVIDENCE'], 'interactions') stmt = Complex([agA, agB], evidence=ev_list) self.statements.append(stmt)
python
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, skip this PPI if agA is None or agB is None: continue isoform_id = '%s_1' % row['HPRD_ID_A'] ev_list = self._get_evidence( row['HPRD_ID_A'], isoform_id, row['PMIDS'], row['EVIDENCE'], 'interactions') stmt = Complex([agA, agB], evidence=ev_list) self.statements.append(stmt)
[ "def", "get_ppis", "(", "self", ",", "ppi_df", ")", ":", "logger", ".", "info", "(", "'Processing PPIs...'", ")", "for", "ix", ",", "row", "in", "ppi_df", ".", "iterrows", "(", ")", ":", "agA", "=", "self", ".", "_make_agent", "(", "row", "[", "'HPRD...
Generate Complex Statements from the HPRD PPI data. Parameters ---------- ppi_df : pandas.DataFrame DataFrame loaded from the BINARY_PROTEIN_PROTEIN_INTERACTIONS.txt file.
[ "Generate", "Complex", "Statements", "from", "the", "HPRD", "PPI", "data", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/hprd/processor.py#L222-L243
18,803
sorgerlab/indra
indra/sources/isi/processor.py
_build_verb_statement_mapping
def _build_verb_statement_mapping(): """Build the mapping between ISI verb strings and INDRA statement classes. Looks up the INDRA statement class name, if any, in a resource file, and resolves this class name to a class. Returns ------- verb_to_statement_type : dict Dictionary mapping verb name to an INDRA statment class """ 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 = {} for line in f: if not first_line: line = line[:-1] tokens = line.split('\t') if len(tokens) == 2 and len(tokens[1]) > 0: verb = tokens[0] s_type = tokens[1] try: statement_class = getattr(ist, s_type) verb_to_statement_type[verb] = statement_class except Exception: pass else: first_line = False return verb_to_statement_type
python
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 = {} for line in f: if not first_line: line = line[:-1] tokens = line.split('\t') if len(tokens) == 2 and len(tokens[1]) > 0: verb = tokens[0] s_type = tokens[1] try: statement_class = getattr(ist, s_type) verb_to_statement_type[verb] = statement_class except Exception: pass else: first_line = False return verb_to_statement_type
[ "def", "_build_verb_statement_mapping", "(", ")", ":", "path_this", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "__file__", ")", ")", "map_path", "=", "os", ".", "path", ".", "join", "(", "path_this", ",", "'isi...
Build the mapping between ISI verb strings and INDRA statement classes. Looks up the INDRA statement class name, if any, in a resource file, and resolves this class name to a class. Returns ------- verb_to_statement_type : dict Dictionary mapping verb name to an INDRA statment class
[ "Build", "the", "mapping", "between", "ISI", "verb", "strings", "and", "INDRA", "statement", "classes", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/isi/processor.py#L167-L198
18,804
sorgerlab/indra
indra/sources/isi/processor.py
IsiProcessor.get_statements
def get_statements(self): """Process reader output to produce INDRA Statements.""" for k, v in self.reader_output.items(): for interaction in v['interactions']: self._process_interaction(k, interaction, v['text'], self.pmid, self.extra_annotations)
python
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_annotations)
[ "def", "get_statements", "(", "self", ")", ":", "for", "k", ",", "v", "in", "self", ".", "reader_output", ".", "items", "(", ")", ":", "for", "interaction", "in", "v", "[", "'interactions'", "]", ":", "self", ".", "_process_interaction", "(", "k", ",",...
Process reader output to produce INDRA Statements.
[ "Process", "reader", "output", "to", "produce", "INDRA", "Statements", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/isi/processor.py#L38-L43
18,805
sorgerlab/indra
indra/sources/isi/processor.py
IsiProcessor._process_interaction
def _process_interaction(self, source_id, interaction, text, pmid, extra_annotations): """Process an interaction JSON tuple from the ISI output, and adds up to one statement to the list of extracted statements. Parameters ---------- source_id : str the JSON key corresponding to the sentence in the ISI output interaction: the JSON list with subject/verb/object information about the event in the ISI output text : str the text of the sentence pmid : str the PMID of the article from which the information was extracted extra_annotations : dict Additional annotations to add to the statement's evidence, potentially containing metadata about the source. Annotations with the key "interaction" will be overridden by the JSON interaction tuple from the ISI output """ verb = interaction[0].lower() subj = interaction[-2] obj = interaction[-1] # Make ungrounded agent objects for the subject and object # Grounding will happen after all statements are extracted in __init__ subj = self._make_agent(subj) obj = self._make_agent(obj) # Make an evidence object annotations = deepcopy(extra_annotations) if 'interaction' in extra_annotations: logger.warning("'interaction' key of extra_annotations ignored" + " since this is reserved for storing the raw ISI " + "input.") annotations['source_id'] = source_id annotations['interaction'] = interaction ev = ist.Evidence(source_api='isi', pmid=pmid, text=text.rstrip(), annotations=annotations) # For binding time interactions, it is said that a catayst might be # specified. We don't use this for now, but extract in case we want # to in the future cataylst_specified = False if len(interaction) == 4: catalyst = interaction[1] if catalyst is not None: cataylst_specified = True self.verbs.add(verb) statement = None if verb in verb_to_statement_type: statement_class = verb_to_statement_type[verb] if statement_class == ist.Complex: statement = ist.Complex([subj, obj], evidence=ev) else: statement = statement_class(subj, obj, evidence=ev) if statement is not None: # For Complex statements, the ISI reader produces two events: # binds(A, B) and binds(B, A) # We want only one Complex statement for each sentence, so check # to see if we already have a Complex for this source_id with the # same members already_have = False if type(statement) == ist.Complex: for old_s in self.statements: old_id = statement.evidence[0].source_id new_id = old_s.evidence[0].source_id if type(old_s) == ist.Complex and old_id == new_id: old_statement_members = \ [m.db_refs['TEXT'] for m in old_s.members] old_statement_members = sorted(old_statement_members) new_statement_members = [m.db_refs['TEXT'] for m in statement.members] new_statement_members = sorted(new_statement_members) if old_statement_members == new_statement_members: already_have = True break if not already_have: self.statements.append(statement)
python
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 subject and object # Grounding will happen after all statements are extracted in __init__ subj = self._make_agent(subj) obj = self._make_agent(obj) # Make an evidence object annotations = deepcopy(extra_annotations) if 'interaction' in extra_annotations: logger.warning("'interaction' key of extra_annotations ignored" + " since this is reserved for storing the raw ISI " + "input.") annotations['source_id'] = source_id annotations['interaction'] = interaction ev = ist.Evidence(source_api='isi', pmid=pmid, text=text.rstrip(), annotations=annotations) # For binding time interactions, it is said that a catayst might be # specified. We don't use this for now, but extract in case we want # to in the future cataylst_specified = False if len(interaction) == 4: catalyst = interaction[1] if catalyst is not None: cataylst_specified = True self.verbs.add(verb) statement = None if verb in verb_to_statement_type: statement_class = verb_to_statement_type[verb] if statement_class == ist.Complex: statement = ist.Complex([subj, obj], evidence=ev) else: statement = statement_class(subj, obj, evidence=ev) if statement is not None: # For Complex statements, the ISI reader produces two events: # binds(A, B) and binds(B, A) # We want only one Complex statement for each sentence, so check # to see if we already have a Complex for this source_id with the # same members already_have = False if type(statement) == ist.Complex: for old_s in self.statements: old_id = statement.evidence[0].source_id new_id = old_s.evidence[0].source_id if type(old_s) == ist.Complex and old_id == new_id: old_statement_members = \ [m.db_refs['TEXT'] for m in old_s.members] old_statement_members = sorted(old_statement_members) new_statement_members = [m.db_refs['TEXT'] for m in statement.members] new_statement_members = sorted(new_statement_members) if old_statement_members == new_statement_members: already_have = True break if not already_have: self.statements.append(statement)
[ "def", "_process_interaction", "(", "self", ",", "source_id", ",", "interaction", ",", "text", ",", "pmid", ",", "extra_annotations", ")", ":", "verb", "=", "interaction", "[", "0", "]", ".", "lower", "(", ")", "subj", "=", "interaction", "[", "-", "2", ...
Process an interaction JSON tuple from the ISI output, and adds up to one statement to the list of extracted statements. Parameters ---------- source_id : str the JSON key corresponding to the sentence in the ISI output interaction: the JSON list with subject/verb/object information about the event in the ISI output text : str the text of the sentence pmid : str the PMID of the article from which the information was extracted extra_annotations : dict Additional annotations to add to the statement's evidence, potentially containing metadata about the source. Annotations with the key "interaction" will be overridden by the JSON interaction tuple from the ISI output
[ "Process", "an", "interaction", "JSON", "tuple", "from", "the", "ISI", "output", "and", "adds", "up", "to", "one", "statement", "to", "the", "list", "of", "extracted", "statements", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/isi/processor.py#L59-L146
18,806
sorgerlab/indra
indra/sources/geneways/actionmention_parser.py
GenewaysActionMention.make_annotation
def make_annotation(self): """Returns a dictionary with all properties of the action mention.""" 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, item)): annotation[item] = getattr(self, item) return annotation
python
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, item)): annotation[item] = getattr(self, item) return annotation
[ "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", ...
Returns a dictionary with all properties of the action mention.
[ "Returns", "a", "dictionary", "with", "all", "properties", "of", "the", "action", "mention", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/geneways/actionmention_parser.py#L31-L41
18,807
sorgerlab/indra
indra/sources/biopax/processor.py
_match_to_array
def _match_to_array(m): """ Returns an array consisting of the elements obtained from a pattern search cast into their appropriate classes. """ return [_cast_biopax_element(m.get(i)) for i in range(m.varSize())]
python
def _match_to_array(m): return [_cast_biopax_element(m.get(i)) for i in range(m.varSize())]
[ "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 search cast into their appropriate classes.
[ "Returns", "an", "array", "consisting", "of", "the", "elements", "obtained", "from", "a", "pattern", "search", "cast", "into", "their", "appropriate", "classes", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/biopax/processor.py#L1374-L1377
18,808
sorgerlab/indra
indra/sources/biopax/processor.py
_is_complex
def _is_complex(pe): """Return True if the physical entity is a complex""" val = isinstance(pe, _bp('Complex')) or \ isinstance(pe, _bpimpl('Complex')) return val
python
def _is_complex(pe): val = isinstance(pe, _bp('Complex')) or \ isinstance(pe, _bpimpl('Complex')) return val
[ "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
[ "Return", "True", "if", "the", "physical", "entity", "is", "a", "complex" ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/biopax/processor.py#L1379-L1383
18,809
sorgerlab/indra
indra/sources/biopax/processor.py
_is_protein
def _is_protein(pe): """Return True if the element is a protein""" val = isinstance(pe, _bp('Protein')) or \ isinstance(pe, _bpimpl('Protein')) or \ isinstance(pe, _bp('ProteinReference')) or \ isinstance(pe, _bpimpl('ProteinReference')) return val
python
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
[ "def", "_is_protein", "(", "pe", ")", ":", "val", "=", "isinstance", "(", "pe", ",", "_bp", "(", "'Protein'", ")", ")", "or", "isinstance", "(", "pe", ",", "_bpimpl", "(", "'Protein'", ")", ")", "or", "isinstance", "(", "pe", ",", "_bp", "(", "'Pro...
Return True if the element is a protein
[ "Return", "True", "if", "the", "element", "is", "a", "protein" ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/biopax/processor.py#L1385-L1391
18,810
sorgerlab/indra
indra/sources/biopax/processor.py
_is_rna
def _is_rna(pe): """Return True if the element is an RNA""" val = isinstance(pe, _bp('Rna')) or isinstance(pe, _bpimpl('Rna')) return val
python
def _is_rna(pe): val = isinstance(pe, _bp('Rna')) or isinstance(pe, _bpimpl('Rna')) return val
[ "def", "_is_rna", "(", "pe", ")", ":", "val", "=", "isinstance", "(", "pe", ",", "_bp", "(", "'Rna'", ")", ")", "or", "isinstance", "(", "pe", ",", "_bpimpl", "(", "'Rna'", ")", ")", "return", "val" ]
Return True if the element is an RNA
[ "Return", "True", "if", "the", "element", "is", "an", "RNA" ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/biopax/processor.py#L1393-L1396
18,811
sorgerlab/indra
indra/sources/biopax/processor.py
_is_small_molecule
def _is_small_molecule(pe): """Return True if the element is a small molecule""" val = isinstance(pe, _bp('SmallMolecule')) or \ isinstance(pe, _bpimpl('SmallMolecule')) or \ isinstance(pe, _bp('SmallMoleculeReference')) or \ isinstance(pe, _bpimpl('SmallMoleculeReference')) return val
python
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')) return val
[ "def", "_is_small_molecule", "(", "pe", ")", ":", "val", "=", "isinstance", "(", "pe", ",", "_bp", "(", "'SmallMolecule'", ")", ")", "or", "isinstance", "(", "pe", ",", "_bpimpl", "(", "'SmallMolecule'", ")", ")", "or", "isinstance", "(", "pe", ",", "_...
Return True if the element is a small molecule
[ "Return", "True", "if", "the", "element", "is", "a", "small", "molecule" ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/biopax/processor.py#L1398-L1404
18,812
sorgerlab/indra
indra/sources/biopax/processor.py
_is_physical_entity
def _is_physical_entity(pe): """Return True if the element is a physical entity""" val = isinstance(pe, _bp('PhysicalEntity')) or \ isinstance(pe, _bpimpl('PhysicalEntity')) return val
python
def _is_physical_entity(pe): val = isinstance(pe, _bp('PhysicalEntity')) or \ isinstance(pe, _bpimpl('PhysicalEntity')) return val
[ "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
[ "Return", "True", "if", "the", "element", "is", "a", "physical", "entity" ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/biopax/processor.py#L1406-L1410
18,813
sorgerlab/indra
indra/sources/biopax/processor.py
_is_modification_or_activity
def _is_modification_or_activity(feature): """Return True if the feature is a modification""" if not (isinstance(feature, _bp('ModificationFeature')) or \ isinstance(feature, _bpimpl('ModificationFeature'))): return None mf_type = feature.getModificationType() if mf_type is None: return None mf_type_terms = mf_type.getTerm().toArray() for term in mf_type_terms: if term in ('residue modification, active', 'residue modification, inactive', 'active', 'inactive'): return 'activity' return 'modification'
python
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 None mf_type_terms = mf_type.getTerm().toArray() for term in mf_type_terms: if term in ('residue modification, active', 'residue modification, inactive', 'active', 'inactive'): return 'activity' return 'modification'
[ "def", "_is_modification_or_activity", "(", "feature", ")", ":", "if", "not", "(", "isinstance", "(", "feature", ",", "_bp", "(", "'ModificationFeature'", ")", ")", "or", "isinstance", "(", "feature", ",", "_bpimpl", "(", "'ModificationFeature'", ")", ")", ")"...
Return True if the feature is a modification
[ "Return", "True", "if", "the", "feature", "is", "a", "modification" ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/biopax/processor.py#L1418-L1432
18,814
sorgerlab/indra
indra/sources/biopax/processor.py
_is_reference
def _is_reference(bpe): """Return True if the element is an entity reference.""" if isinstance(bpe, _bp('ProteinReference')) or \ isinstance(bpe, _bpimpl('ProteinReference')) or \ isinstance(bpe, _bp('SmallMoleculeReference')) or \ isinstance(bpe, _bpimpl('SmallMoleculeReference')) or \ isinstance(bpe, _bp('RnaReference')) or \ isinstance(bpe, _bpimpl('RnaReference')) or \ isinstance(bpe, _bp('EntityReference')) or \ isinstance(bpe, _bpimpl('EntityReference')): return True else: return False
python
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 \ isinstance(bpe, _bp('RnaReference')) or \ isinstance(bpe, _bpimpl('RnaReference')) or \ isinstance(bpe, _bp('EntityReference')) or \ isinstance(bpe, _bpimpl('EntityReference')): return True else: return False
[ "def", "_is_reference", "(", "bpe", ")", ":", "if", "isinstance", "(", "bpe", ",", "_bp", "(", "'ProteinReference'", ")", ")", "or", "isinstance", "(", "bpe", ",", "_bpimpl", "(", "'ProteinReference'", ")", ")", "or", "isinstance", "(", "bpe", ",", "_bp"...
Return True if the element is an entity reference.
[ "Return", "True", "if", "the", "element", "is", "an", "entity", "reference", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/biopax/processor.py#L1434-L1446
18,815
sorgerlab/indra
indra/sources/biopax/processor.py
_is_entity
def _is_entity(bpe): """Return True if the element is a physical entity.""" 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 \ isinstance(bpe, _bpimpl('Complex')) or \ isinstance(bpe, _bp('Rna')) or \ isinstance(bpe, _bpimpl('Rna')) or \ isinstance(bpe, _bp('RnaRegion')) or \ isinstance(bpe, _bpimpl('RnaRegion')) or \ isinstance(bpe, _bp('DnaRegion')) or \ isinstance(bpe, _bpimpl('DnaRegion')) or \ isinstance(bpe, _bp('PhysicalEntity')) or \ isinstance(bpe, _bpimpl('PhysicalEntity')): return True else: return False
python
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 \ isinstance(bpe, _bpimpl('Complex')) or \ isinstance(bpe, _bp('Rna')) or \ isinstance(bpe, _bpimpl('Rna')) or \ isinstance(bpe, _bp('RnaRegion')) or \ isinstance(bpe, _bpimpl('RnaRegion')) or \ isinstance(bpe, _bp('DnaRegion')) or \ isinstance(bpe, _bpimpl('DnaRegion')) or \ isinstance(bpe, _bp('PhysicalEntity')) or \ isinstance(bpe, _bpimpl('PhysicalEntity')): return True else: return False
[ "def", "_is_entity", "(", "bpe", ")", ":", "if", "isinstance", "(", "bpe", ",", "_bp", "(", "'Protein'", ")", ")", "or", "isinstance", "(", "bpe", ",", "_bpimpl", "(", "'Protein'", ")", ")", "or", "isinstance", "(", "bpe", ",", "_bp", "(", "'SmallMol...
Return True if the element is a physical entity.
[ "Return", "True", "if", "the", "element", "is", "a", "physical", "entity", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/biopax/processor.py#L1448-L1466
18,816
sorgerlab/indra
indra/sources/biopax/processor.py
_is_catalysis
def _is_catalysis(bpe): """Return True if the element is Catalysis.""" if isinstance(bpe, _bp('Catalysis')) or \ isinstance(bpe, _bpimpl('Catalysis')): return True else: return False
python
def _is_catalysis(bpe): if isinstance(bpe, _bp('Catalysis')) or \ isinstance(bpe, _bpimpl('Catalysis')): return True else: return False
[ "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.
[ "Return", "True", "if", "the", "element", "is", "Catalysis", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/biopax/processor.py#L1468-L1474
18,817
sorgerlab/indra
indra/sources/biopax/processor.py
BiopaxProcessor.print_statements
def print_statements(self): """Print all INDRA Statements collected by the processors.""" for i, stmt in enumerate(self.statements): print("%s: %s" % (i, stmt))
python
def print_statements(self): for i, stmt in enumerate(self.statements): print("%s: %s" % (i, stmt))
[ "def", "print_statements", "(", "self", ")", ":", "for", "i", ",", "stmt", "in", "enumerate", "(", "self", ".", "statements", ")", ":", "print", "(", "\"%s: %s\"", "%", "(", "i", ",", "stmt", ")", ")" ]
Print all INDRA Statements collected by the processors.
[ "Print", "all", "INDRA", "Statements", "collected", "by", "the", "processors", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/biopax/processor.py#L53-L56
18,818
sorgerlab/indra
indra/sources/biopax/processor.py
BiopaxProcessor.save_model
def save_model(self, file_name=None): """Save the BioPAX model object in an OWL file. Parameters ---------- file_name : Optional[str] The name of the OWL file to save the model in. """ if file_name is None: logger.error('Missing file name') return pcc.model_to_owl(self.model, file_name)
python
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)
[ "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. Parameters ---------- file_name : Optional[str] The name of the OWL file to save the model in.
[ "Save", "the", "BioPAX", "model", "object", "in", "an", "OWL", "file", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/biopax/processor.py#L58-L69
18,819
sorgerlab/indra
indra/sources/biopax/processor.py
BiopaxProcessor.eliminate_exact_duplicates
def eliminate_exact_duplicates(self): """Eliminate Statements that were extracted multiple times. Due to the way the patterns are implemented, they can sometimes yield the same Statement information multiple times, in which case, we end up with redundant Statements that aren't from independent underlying entries. To avoid this, here, we filter out such duplicates. """ # 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): stmt for stmt in self.statements}.values())
python
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): stmt for stmt in self.statements}.values())
[ "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", "(", ...
Eliminate Statements that were extracted multiple times. Due to the way the patterns are implemented, they can sometimes yield the same Statement information multiple times, in which case, we end up with redundant Statements that aren't from independent underlying entries. To avoid this, here, we filter out such duplicates.
[ "Eliminate", "Statements", "that", "were", "extracted", "multiple", "times", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/biopax/processor.py#L71-L83
18,820
sorgerlab/indra
indra/sources/biopax/processor.py
BiopaxProcessor.get_complexes
def get_complexes(self): """Extract INDRA Complex Statements from the BioPAX model. This method searches for org.biopax.paxtools.model.level3.Complex objects which represent molecular complexes. It doesn't reuse BioPAX Pattern's org.biopax.paxtools.pattern.PatternBox.inComplexWith query since that retrieves pairs of complex members rather than the full complex. """ 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_members(bpe) if members is not None: if len(members) > 10: logger.debug('Skipping complex with more than 10 members.') continue complexes = _get_combinations(members) for c in complexes: self.statements.append(decode_obj(Complex(c, ev), encoding='utf-8'))
python
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_members(bpe) if members is not None: if len(members) > 10: logger.debug('Skipping complex with more than 10 members.') continue complexes = _get_combinations(members) for c in complexes: self.statements.append(decode_obj(Complex(c, ev), encoding='utf-8'))
[ "def", "get_complexes", "(", "self", ")", ":", "for", "obj", "in", "self", ".", "model", ".", "getObjects", "(", ")", ".", "toArray", "(", ")", ":", "bpe", "=", "_cast_biopax_element", "(", "obj", ")", "if", "not", "_is_complex", "(", "bpe", ")", ":"...
Extract INDRA Complex Statements from the BioPAX model. This method searches for org.biopax.paxtools.model.level3.Complex objects which represent molecular complexes. It doesn't reuse BioPAX Pattern's org.biopax.paxtools.pattern.PatternBox.inComplexWith query since that retrieves pairs of complex members rather than the full complex.
[ "Extract", "INDRA", "Complex", "Statements", "from", "the", "BioPAX", "model", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/biopax/processor.py#L86-L109
18,821
sorgerlab/indra
indra/sources/biopax/processor.py
BiopaxProcessor.get_modifications
def get_modifications(self): """Extract INDRA Modification Statements from the BioPAX model. To extract Modifications, this method reuses the structure of BioPAX Pattern's org.biopax.paxtools.pattern.PatternBox.constrolsStateChange pattern with additional constraints to specify the type of state change occurring (phosphorylation, deubiquitination, etc.). """ for modtype, modclass in modtype_to_modclass.items(): # TODO: we could possibly try to also extract generic # modifications here if modtype == 'modification': continue stmts = self._get_generic_modification(modclass) self.statements += stmts
python
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 stmts = self._get_generic_modification(modclass) self.statements += stmts
[ "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'", ":",...
Extract INDRA Modification Statements from the BioPAX model. To extract Modifications, this method reuses the structure of BioPAX Pattern's org.biopax.paxtools.pattern.PatternBox.constrolsStateChange pattern with additional constraints to specify the type of state change occurring (phosphorylation, deubiquitination, etc.).
[ "Extract", "INDRA", "Modification", "Statements", "from", "the", "BioPAX", "model", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/biopax/processor.py#L111-L126
18,822
sorgerlab/indra
indra/sources/biopax/processor.py
BiopaxProcessor.get_activity_modification
def get_activity_modification(self): """Extract INDRA ActiveForm statements from the BioPAX model. This method extracts ActiveForm Statements that are due to protein modifications. This method reuses the structure of BioPAX Pattern's org.biopax.paxtools.pattern.PatternBox.constrolsStateChange pattern with additional constraints to specify the gain or loss of a modification occurring (phosphorylation, deubiquitination, etc.) and the gain or loss of activity due to the modification state change. """ 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, mod_filter), "input simple PE", "output simple PE") 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: reaction = r[p.indexOf('Conversion')] activity = 'activity' input_spe = r[p.indexOf('input simple PE')] output_spe = r[p.indexOf('output simple PE')] # Get the modifications mod_in = \ BiopaxProcessor._get_entity_mods(input_spe) mod_out = \ BiopaxProcessor._get_entity_mods(output_spe) mod_shared = _get_mod_intersection(mod_in, mod_out) gained_mods = _get_mod_difference(mod_out, mod_in) # Here we get the evidence for the BiochemicalReaction ev = self._get_evidence(reaction) agents = self._get_agents_from_entity(output_spe) for agent in _listify(agents): static_mods = _get_mod_difference(agent.mods, gained_mods) # NOTE: with the ActiveForm representation we cannot # separate static_mods and gained_mods. We assume here # that the static_mods are inconsequential and therefore # are not mentioned as an Agent condition, following # don't care don't write semantics. Therefore only the # gained_mods are listed in the ActiveForm as Agent # conditions. if gained_mods: agent.mods = gained_mods stmt = ActiveForm(agent, activity, is_active, evidence=ev) self.statements.append(decode_obj(stmt, encoding='utf-8'))
python
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, mod_filter), "input simple PE", "output simple PE") 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: reaction = r[p.indexOf('Conversion')] activity = 'activity' input_spe = r[p.indexOf('input simple PE')] output_spe = r[p.indexOf('output simple PE')] # Get the modifications mod_in = \ BiopaxProcessor._get_entity_mods(input_spe) mod_out = \ BiopaxProcessor._get_entity_mods(output_spe) mod_shared = _get_mod_intersection(mod_in, mod_out) gained_mods = _get_mod_difference(mod_out, mod_in) # Here we get the evidence for the BiochemicalReaction ev = self._get_evidence(reaction) agents = self._get_agents_from_entity(output_spe) for agent in _listify(agents): static_mods = _get_mod_difference(agent.mods, gained_mods) # NOTE: with the ActiveForm representation we cannot # separate static_mods and gained_mods. We assume here # that the static_mods are inconsequential and therefore # are not mentioned as an Agent condition, following # don't care don't write semantics. Therefore only the # gained_mods are listed in the ActiveForm as Agent # conditions. if gained_mods: agent.mods = gained_mods stmt = ActiveForm(agent, activity, is_active, evidence=ev) self.statements.append(decode_obj(stmt, encoding='utf-8'))
[ "def", "get_activity_modification", "(", "self", ")", ":", "mod_filter", "=", "'residue modification, active'", "for", "is_active", "in", "[", "True", ",", "False", "]", ":", "p", "=", "self", ".", "_construct_modification_pattern", "(", ")", "rel", "=", "mcct",...
Extract INDRA ActiveForm statements from the BioPAX model. This method extracts ActiveForm Statements that are due to protein modifications. This method reuses the structure of BioPAX Pattern's org.biopax.paxtools.pattern.PatternBox.constrolsStateChange pattern with additional constraints to specify the gain or loss of a modification occurring (phosphorylation, deubiquitination, etc.) and the gain or loss of activity due to the modification state change.
[ "Extract", "INDRA", "ActiveForm", "statements", "from", "the", "BioPAX", "model", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/biopax/processor.py#L128-L185
18,823
sorgerlab/indra
indra/sources/biopax/processor.py
BiopaxProcessor.get_regulate_amounts
def get_regulate_amounts(self): """Extract INDRA RegulateAmount Statements from the BioPAX model. This method extracts IncreaseAmount/DecreaseAmount Statements from the BioPAX model. It fully reuses BioPAX Pattern's org.biopax.paxtools.pattern.PatternBox.controlsExpressionWithTemplateReac pattern to find TemplateReactions which control the expression of a protein. """ 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_array: # FIXME: for some reason labels are not accessible # for these queries. It would be more reliable # to get results by label instead of index. ''' controller_er = res[p.indexOf('controller ER')] generic_controller_er = res[p.indexOf('generic controller ER')] controller_simple_pe = res[p.indexOf('controller simple PE')] controller_pe = res[p.indexOf('controller PE')] control = res[p.indexOf('Control')] conversion = res[p.indexOf('Conversion')] input_pe = res[p.indexOf('input PE')] input_simple_pe = res[p.indexOf('input simple PE')] changed_generic_er = res[p.indexOf('changed generic ER')] output_pe = res[p.indexOf('output PE')] output_simple_pe = res[p.indexOf('output simple PE')] changed_er = res[p.indexOf('changed ER')] ''' # TODO: here, res[3] is the complex physical entity # for instance http://pathwaycommons.org/pc2/ # Complex_43c6b8330562c1b411d21e9d1185bae9 # consists of 3 components: JUN, FOS and NFAT # where NFAT further contains 3 member physical entities. # # However, res[2] iterates over all 5 member physical entities # of the complex which doesn't represent the underlying # structure faithfully. It would be better to use res[3] # (the complex itself) and look at components and then # members. However, then, it would not be clear how to # construct an INDRA Agent for the controller. controller = self._get_agents_from_entity(res[2]) controlled_pe = res[6] controlled = self._get_agents_from_entity(controlled_pe) conversion = res[5] direction = conversion.getTemplateDirection() if direction is not None: direction = direction.name() if direction != 'FORWARD': logger.warning('Unhandled conversion direction %s' % direction) continue # Sometimes interaction type is annotated as # term=='TRANSCRIPTION'. Other times this is not # annotated. int_type = conversion.getInteractionType().toArray() if int_type: for it in int_type: for term in it.getTerm().toArray(): pass control = res[4] control_type = control.getControlType() if control_type: control_type = control_type.name() ev = self._get_evidence(control) for subj, obj in itertools.product(_listify(controller), _listify(controlled)): subj_act = ActivityCondition('transcription', True) subj.activity = subj_act if control_type == 'ACTIVATION': st = IncreaseAmount(subj, obj, evidence=ev) elif control_type == 'INHIBITION': st = DecreaseAmount(subj, obj, evidence=ev) else: logger.warning('Unhandled control type %s' % control_type) continue st_dec = decode_obj(st, encoding='utf-8') self.statements.append(st_dec)
python
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_array: # FIXME: for some reason labels are not accessible # for these queries. It would be more reliable # to get results by label instead of index. ''' controller_er = res[p.indexOf('controller ER')] generic_controller_er = res[p.indexOf('generic controller ER')] controller_simple_pe = res[p.indexOf('controller simple PE')] controller_pe = res[p.indexOf('controller PE')] control = res[p.indexOf('Control')] conversion = res[p.indexOf('Conversion')] input_pe = res[p.indexOf('input PE')] input_simple_pe = res[p.indexOf('input simple PE')] changed_generic_er = res[p.indexOf('changed generic ER')] output_pe = res[p.indexOf('output PE')] output_simple_pe = res[p.indexOf('output simple PE')] changed_er = res[p.indexOf('changed ER')] ''' # TODO: here, res[3] is the complex physical entity # for instance http://pathwaycommons.org/pc2/ # Complex_43c6b8330562c1b411d21e9d1185bae9 # consists of 3 components: JUN, FOS and NFAT # where NFAT further contains 3 member physical entities. # # However, res[2] iterates over all 5 member physical entities # of the complex which doesn't represent the underlying # structure faithfully. It would be better to use res[3] # (the complex itself) and look at components and then # members. However, then, it would not be clear how to # construct an INDRA Agent for the controller. controller = self._get_agents_from_entity(res[2]) controlled_pe = res[6] controlled = self._get_agents_from_entity(controlled_pe) conversion = res[5] direction = conversion.getTemplateDirection() if direction is not None: direction = direction.name() if direction != 'FORWARD': logger.warning('Unhandled conversion direction %s' % direction) continue # Sometimes interaction type is annotated as # term=='TRANSCRIPTION'. Other times this is not # annotated. int_type = conversion.getInteractionType().toArray() if int_type: for it in int_type: for term in it.getTerm().toArray(): pass control = res[4] control_type = control.getControlType() if control_type: control_type = control_type.name() ev = self._get_evidence(control) for subj, obj in itertools.product(_listify(controller), _listify(controlled)): subj_act = ActivityCondition('transcription', True) subj.activity = subj_act if control_type == 'ACTIVATION': st = IncreaseAmount(subj, obj, evidence=ev) elif control_type == 'INHIBITION': st = DecreaseAmount(subj, obj, evidence=ev) else: logger.warning('Unhandled control type %s' % control_type) continue st_dec = decode_obj(st, encoding='utf-8') self.statements.append(st_dec)
[ "def", "get_regulate_amounts", "(", "self", ")", ":", "p", "=", "pb", ".", "controlsExpressionWithTemplateReac", "(", ")", "s", "=", "_bpp", "(", "'Searcher'", ")", "res", "=", "s", ".", "searchPlain", "(", "self", ".", "model", ",", "p", ")", "res_array...
Extract INDRA RegulateAmount Statements from the BioPAX model. This method extracts IncreaseAmount/DecreaseAmount Statements from the BioPAX model. It fully reuses BioPAX Pattern's org.biopax.paxtools.pattern.PatternBox.controlsExpressionWithTemplateReac pattern to find TemplateReactions which control the expression of a protein.
[ "Extract", "INDRA", "RegulateAmount", "Statements", "from", "the", "BioPAX", "model", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/biopax/processor.py#L261-L342
18,824
sorgerlab/indra
indra/sources/biopax/processor.py
BiopaxProcessor.get_gef
def get_gef(self): """Extract Gef INDRA Statements from the BioPAX model. This method uses a custom BioPAX Pattern (one that is not implemented PatternBox) to query for controlled BiochemicalReactions in which the same protein is in complex with GDP on the left hand side and in complex with GTP on the right hand side. This implies that the controller is a GEF for the GDP/GTP-bound protein. """ 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('controller PE')] input_pe = r[p.indexOf('input PE')] input_spe = r[p.indexOf('input simple PE')] output_pe = r[p.indexOf('output PE')] output_spe = r[p.indexOf('output simple PE')] reaction = r[p.indexOf('Conversion')] control = r[p.indexOf('Control')] # Make sure the GEF is not a complex # TODO: it could be possible to extract certain complexes here, for # instance ones that only have a single protein if _is_complex(controller_pe): continue members_in = self._get_complex_members(input_pe) members_out = self._get_complex_members(output_pe) if not (members_in and members_out): continue # Make sure the outgoing complex has exactly 2 members # TODO: by finding matching proteins on either side, in principle # it would be possible to find Gef relationships in complexes # with more members if len(members_out) != 2: continue # Make sure complex starts with GDP that becomes GTP gdp_in = False for member in members_in: if isinstance(member, Agent) and member.name == 'GDP': gdp_in = True gtp_out = False for member in members_out: if isinstance(member, Agent) and member.name == 'GTP': gtp_out = True if not (gdp_in and gtp_out): continue ras_list = self._get_agents_from_entity(input_spe) gef_list = self._get_agents_from_entity(controller_pe) ev = self._get_evidence(control) for gef, ras in itertools.product(_listify(gef_list), _listify(ras_list)): st = Gef(gef, ras, evidence=ev) st_dec = decode_obj(st, encoding='utf-8') self.statements.append(st_dec)
python
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('controller PE')] input_pe = r[p.indexOf('input PE')] input_spe = r[p.indexOf('input simple PE')] output_pe = r[p.indexOf('output PE')] output_spe = r[p.indexOf('output simple PE')] reaction = r[p.indexOf('Conversion')] control = r[p.indexOf('Control')] # Make sure the GEF is not a complex # TODO: it could be possible to extract certain complexes here, for # instance ones that only have a single protein if _is_complex(controller_pe): continue members_in = self._get_complex_members(input_pe) members_out = self._get_complex_members(output_pe) if not (members_in and members_out): continue # Make sure the outgoing complex has exactly 2 members # TODO: by finding matching proteins on either side, in principle # it would be possible to find Gef relationships in complexes # with more members if len(members_out) != 2: continue # Make sure complex starts with GDP that becomes GTP gdp_in = False for member in members_in: if isinstance(member, Agent) and member.name == 'GDP': gdp_in = True gtp_out = False for member in members_out: if isinstance(member, Agent) and member.name == 'GTP': gtp_out = True if not (gdp_in and gtp_out): continue ras_list = self._get_agents_from_entity(input_spe) gef_list = self._get_agents_from_entity(controller_pe) ev = self._get_evidence(control) for gef, ras in itertools.product(_listify(gef_list), _listify(ras_list)): st = Gef(gef, ras, evidence=ev) st_dec = decode_obj(st, encoding='utf-8') self.statements.append(st_dec)
[ "def", "get_gef", "(", "self", ")", ":", "p", "=", "self", ".", "_gef_gap_base", "(", ")", "s", "=", "_bpp", "(", "'Searcher'", ")", "res", "=", "s", ".", "searchPlain", "(", "self", ".", "model", ",", "p", ")", "res_array", "=", "[", "_match_to_ar...
Extract Gef INDRA Statements from the BioPAX model. This method uses a custom BioPAX Pattern (one that is not implemented PatternBox) to query for controlled BiochemicalReactions in which the same protein is in complex with GDP on the left hand side and in complex with GTP on the right hand side. This implies that the controller is a GEF for the GDP/GTP-bound protein.
[ "Extract", "Gef", "INDRA", "Statements", "from", "the", "BioPAX", "model", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/biopax/processor.py#L474-L531
18,825
sorgerlab/indra
indra/sources/biopax/processor.py
BiopaxProcessor.get_gap
def get_gap(self): """Extract Gap INDRA Statements from the BioPAX model. This method uses a custom BioPAX Pattern (one that is not implemented PatternBox) to query for controlled BiochemicalReactions in which the same protein is in complex with GTP on the left hand side and in complex with GDP on the right hand side. This implies that the controller is a GAP for the GDP/GTP-bound protein. """ 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('controller PE')] input_pe = r[p.indexOf('input PE')] input_spe = r[p.indexOf('input simple PE')] output_pe = r[p.indexOf('output PE')] output_spe = r[p.indexOf('output simple PE')] reaction = r[p.indexOf('Conversion')] control = r[p.indexOf('Control')] # Make sure the GAP is not a complex # TODO: it could be possible to extract certain complexes here, for # instance ones that only have a single protein if _is_complex(controller_pe): continue members_in = self._get_complex_members(input_pe) members_out = self._get_complex_members(output_pe) if not (members_in and members_out): continue # Make sure the outgoing complex has exactly 2 members # TODO: by finding matching proteins on either side, in principle # it would be possible to find Gap relationships in complexes # with more members if len(members_out) != 2: continue # Make sure complex starts with GDP that becomes GTP gtp_in = False for member in members_in: if isinstance(member, Agent) and member.name == 'GTP': gtp_in = True gdp_out = False for member in members_out: if isinstance(member, Agent) and member.name == 'GDP': gdp_out = True if not (gtp_in and gdp_out): continue ras_list = self._get_agents_from_entity(input_spe) gap_list = self._get_agents_from_entity(controller_pe) ev = self._get_evidence(control) for gap, ras in itertools.product(_listify(gap_list), _listify(ras_list)): st = Gap(gap, ras, evidence=ev) st_dec = decode_obj(st, encoding='utf-8') self.statements.append(st_dec)
python
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('controller PE')] input_pe = r[p.indexOf('input PE')] input_spe = r[p.indexOf('input simple PE')] output_pe = r[p.indexOf('output PE')] output_spe = r[p.indexOf('output simple PE')] reaction = r[p.indexOf('Conversion')] control = r[p.indexOf('Control')] # Make sure the GAP is not a complex # TODO: it could be possible to extract certain complexes here, for # instance ones that only have a single protein if _is_complex(controller_pe): continue members_in = self._get_complex_members(input_pe) members_out = self._get_complex_members(output_pe) if not (members_in and members_out): continue # Make sure the outgoing complex has exactly 2 members # TODO: by finding matching proteins on either side, in principle # it would be possible to find Gap relationships in complexes # with more members if len(members_out) != 2: continue # Make sure complex starts with GDP that becomes GTP gtp_in = False for member in members_in: if isinstance(member, Agent) and member.name == 'GTP': gtp_in = True gdp_out = False for member in members_out: if isinstance(member, Agent) and member.name == 'GDP': gdp_out = True if not (gtp_in and gdp_out): continue ras_list = self._get_agents_from_entity(input_spe) gap_list = self._get_agents_from_entity(controller_pe) ev = self._get_evidence(control) for gap, ras in itertools.product(_listify(gap_list), _listify(ras_list)): st = Gap(gap, ras, evidence=ev) st_dec = decode_obj(st, encoding='utf-8') self.statements.append(st_dec)
[ "def", "get_gap", "(", "self", ")", ":", "p", "=", "self", ".", "_gef_gap_base", "(", ")", "s", "=", "_bpp", "(", "'Searcher'", ")", "res", "=", "s", ".", "searchPlain", "(", "self", ".", "model", ",", "p", ")", "res_array", "=", "[", "_match_to_ar...
Extract Gap INDRA Statements from the BioPAX model. This method uses a custom BioPAX Pattern (one that is not implemented PatternBox) to query for controlled BiochemicalReactions in which the same protein is in complex with GTP on the left hand side and in complex with GDP on the right hand side. This implies that the controller is a GAP for the GDP/GTP-bound protein.
[ "Extract", "Gap", "INDRA", "Statements", "from", "the", "BioPAX", "model", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/biopax/processor.py#L533-L590
18,826
sorgerlab/indra
indra/sources/biopax/processor.py
BiopaxProcessor._get_entity_mods
def _get_entity_mods(bpe): """Get all the modifications of an entity in INDRA format""" if _is_entity(bpe): features = bpe.getFeature().toArray() else: features = bpe.getEntityFeature().toArray() mods = [] for feature in features: if not _is_modification(feature): continue mc = BiopaxProcessor._extract_mod_from_feature(feature) if mc is not None: mods.append(mc) return mods
python
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(feature): continue mc = BiopaxProcessor._extract_mod_from_feature(feature) if mc is not None: mods.append(mc) return mods
[ "def", "_get_entity_mods", "(", "bpe", ")", ":", "if", "_is_entity", "(", "bpe", ")", ":", "features", "=", "bpe", ".", "getFeature", "(", ")", ".", "toArray", "(", ")", "else", ":", "features", "=", "bpe", ".", "getEntityFeature", "(", ")", ".", "to...
Get all the modifications of an entity in INDRA format
[ "Get", "all", "the", "modifications", "of", "an", "entity", "in", "INDRA", "format" ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/biopax/processor.py#L633-L646
18,827
sorgerlab/indra
indra/sources/biopax/processor.py
BiopaxProcessor._get_generic_modification
def _get_generic_modification(self, mod_class): """Get all modification reactions given a Modification 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: mod_gain_const = mcct.GAIN mod_filter = mod_type[:5] # Start with a generic modification pattern p = BiopaxProcessor._construct_modification_pattern() p.add(mcc(mod_gain_const, mod_filter), "input simple PE", "output simple PE") s = _bpp('Searcher') res = s.searchPlain(self.model, p) res_array = [_match_to_array(m) for m in res.toArray()] stmts = [] for r in res_array: controller_pe = r[p.indexOf('controller PE')] input_pe = r[p.indexOf('input PE')] input_spe = r[p.indexOf('input simple PE')] output_spe = r[p.indexOf('output simple PE')] reaction = r[p.indexOf('Conversion')] control = r[p.indexOf('Control')] if not _is_catalysis(control): continue cat_dir = control.getCatalysisDirection() if cat_dir is not None and cat_dir.name() != 'LEFT_TO_RIGHT': logger.debug('Unexpected catalysis direction: %s.' % \ control.getCatalysisDirection()) continue enzs = BiopaxProcessor._get_primary_controller(controller_pe) if not enzs: continue ''' if _is_complex(input_pe): sub_members_in = self._get_complex_members(input_pe) sub_members_out = self._get_complex_members(output_pe) # TODO: It is possible to find which member of the complex is # actually modified. That member will be the substrate and # all other members of the complex will be bound to it. logger.info('Cannot handle complex substrates.') continue ''' subs = BiopaxProcessor._get_agents_from_entity(input_spe, expand_pe=False) ev = self._get_evidence(control) for enz, sub in itertools.product(_listify(enzs), _listify(subs)): # Get the modifications mod_in = \ BiopaxProcessor._get_entity_mods(input_spe) mod_out = \ BiopaxProcessor._get_entity_mods(output_spe) sub.mods = _get_mod_intersection(mod_in, mod_out) if issubclass(mod_class, AddModification): gained_mods = _get_mod_difference(mod_out, mod_in) else: gained_mods = _get_mod_difference(mod_in, mod_out) for mod in gained_mods: # Is it guaranteed that these are all modifications # of the type we are extracting? if mod.mod_type not in (mod_type, modtype_to_inverse[mod_type]): continue stmt = mod_class(enz, sub, mod.residue, mod.position, evidence=ev) stmts.append(decode_obj(stmt, encoding='utf-8')) return stmts
python
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: mod_gain_const = mcct.GAIN mod_filter = mod_type[:5] # Start with a generic modification pattern p = BiopaxProcessor._construct_modification_pattern() p.add(mcc(mod_gain_const, mod_filter), "input simple PE", "output simple PE") s = _bpp('Searcher') res = s.searchPlain(self.model, p) res_array = [_match_to_array(m) for m in res.toArray()] stmts = [] for r in res_array: controller_pe = r[p.indexOf('controller PE')] input_pe = r[p.indexOf('input PE')] input_spe = r[p.indexOf('input simple PE')] output_spe = r[p.indexOf('output simple PE')] reaction = r[p.indexOf('Conversion')] control = r[p.indexOf('Control')] if not _is_catalysis(control): continue cat_dir = control.getCatalysisDirection() if cat_dir is not None and cat_dir.name() != 'LEFT_TO_RIGHT': logger.debug('Unexpected catalysis direction: %s.' % \ control.getCatalysisDirection()) continue enzs = BiopaxProcessor._get_primary_controller(controller_pe) if not enzs: continue ''' if _is_complex(input_pe): sub_members_in = self._get_complex_members(input_pe) sub_members_out = self._get_complex_members(output_pe) # TODO: It is possible to find which member of the complex is # actually modified. That member will be the substrate and # all other members of the complex will be bound to it. logger.info('Cannot handle complex substrates.') continue ''' subs = BiopaxProcessor._get_agents_from_entity(input_spe, expand_pe=False) ev = self._get_evidence(control) for enz, sub in itertools.product(_listify(enzs), _listify(subs)): # Get the modifications mod_in = \ BiopaxProcessor._get_entity_mods(input_spe) mod_out = \ BiopaxProcessor._get_entity_mods(output_spe) sub.mods = _get_mod_intersection(mod_in, mod_out) if issubclass(mod_class, AddModification): gained_mods = _get_mod_difference(mod_out, mod_in) else: gained_mods = _get_mod_difference(mod_in, mod_out) for mod in gained_mods: # Is it guaranteed that these are all modifications # of the type we are extracting? if mod.mod_type not in (mod_type, modtype_to_inverse[mod_type]): continue stmt = mod_class(enz, sub, mod.residue, mod.position, evidence=ev) stmts.append(decode_obj(stmt, encoding='utf-8')) return stmts
[ "def", "_get_generic_modification", "(", "self", ",", "mod_class", ")", ":", "mod_type", "=", "modclass_to_modtype", "[", "mod_class", "]", "if", "issubclass", "(", "mod_class", ",", "RemoveModification", ")", ":", "mod_gain_const", "=", "mcct", ".", "LOSS", "mo...
Get all modification reactions given a Modification class.
[ "Get", "all", "modification", "reactions", "given", "a", "Modification", "class", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/biopax/processor.py#L648-L721
18,828
sorgerlab/indra
indra/sources/biopax/processor.py
BiopaxProcessor._construct_modification_pattern
def _construct_modification_pattern(): """Construct the BioPAX pattern to extract modification reactions.""" # The following constraints were pieced together based on the # following two higher level constrains: pb.controlsStateChange(), # pb.controlsPhosphorylation(). p = _bpp('Pattern')(_bpimpl('PhysicalEntity')().getModelInterface(), 'controller PE') # Getting the control itself p.add(cb.peToControl(), "controller PE", "Control") # Link the control to the conversion that it controls p.add(cb.controlToConv(), "Control", "Conversion") # The controller shouldn't be a participant of the conversion p.add(_bpp('constraint.NOT')(cb.participant()), "Conversion", "controller PE") # Get the input participant of the conversion p.add(pt(rt.INPUT, True), "Control", "Conversion", "input PE") # Get the specific PhysicalEntity p.add(cb.linkToSpecific(), "input PE", "input simple PE") # Link to ER p.add(cb.peToER(), "input simple PE", "input simple ER") # Make sure the participant is a protein p.add(tp(_bpimpl('Protein')().getModelInterface()), "input simple PE") # Link to the other side of the conversion p.add(cs(cst.OTHER_SIDE), "input PE", "Conversion", "output PE") # Make sure the two sides are not the same p.add(_bpp('constraint.Equality')(False), "input PE", "output PE") # Get the specific PhysicalEntity p.add(cb.linkToSpecific(), "output PE", "output simple PE") # Link to ER p.add(cb.peToER(), "output simple PE", "output simple ER") p.add(_bpp('constraint.Equality')(True), "input simple ER", "output simple ER") # Make sure the output is a Protein p.add(tp(_bpimpl('Protein')().getModelInterface()), "output simple PE") p.add(_bpp('constraint.NOT')(cb.linkToSpecific()), "input PE", "output simple PE") p.add(_bpp('constraint.NOT')(cb.linkToSpecific()), "output PE", "input simple PE") return p
python
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('PhysicalEntity')().getModelInterface(), 'controller PE') # Getting the control itself p.add(cb.peToControl(), "controller PE", "Control") # Link the control to the conversion that it controls p.add(cb.controlToConv(), "Control", "Conversion") # The controller shouldn't be a participant of the conversion p.add(_bpp('constraint.NOT')(cb.participant()), "Conversion", "controller PE") # Get the input participant of the conversion p.add(pt(rt.INPUT, True), "Control", "Conversion", "input PE") # Get the specific PhysicalEntity p.add(cb.linkToSpecific(), "input PE", "input simple PE") # Link to ER p.add(cb.peToER(), "input simple PE", "input simple ER") # Make sure the participant is a protein p.add(tp(_bpimpl('Protein')().getModelInterface()), "input simple PE") # Link to the other side of the conversion p.add(cs(cst.OTHER_SIDE), "input PE", "Conversion", "output PE") # Make sure the two sides are not the same p.add(_bpp('constraint.Equality')(False), "input PE", "output PE") # Get the specific PhysicalEntity p.add(cb.linkToSpecific(), "output PE", "output simple PE") # Link to ER p.add(cb.peToER(), "output simple PE", "output simple ER") p.add(_bpp('constraint.Equality')(True), "input simple ER", "output simple ER") # Make sure the output is a Protein p.add(tp(_bpimpl('Protein')().getModelInterface()), "output simple PE") p.add(_bpp('constraint.NOT')(cb.linkToSpecific()), "input PE", "output simple PE") p.add(_bpp('constraint.NOT')(cb.linkToSpecific()), "output PE", "input simple PE") return p
[ "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", ...
Construct the BioPAX pattern to extract modification reactions.
[ "Construct", "the", "BioPAX", "pattern", "to", "extract", "modification", "reactions", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/biopax/processor.py#L788-L826
18,829
sorgerlab/indra
indra/sources/biopax/processor.py
BiopaxProcessor._extract_mod_from_feature
def _extract_mod_from_feature(mf): """Extract the type of modification and the position from a ModificationFeature object in the INDRA format.""" # ModificationFeature / SequenceModificationVocabulary mf_type = mf.getModificationType() if mf_type is None: return None mf_type_terms = mf_type.getTerm().toArray() known_mf_type = None for t in mf_type_terms: if t.startswith('MOD_RES '): t = t[8:] mf_type_indra = _mftype_dict.get(t) if mf_type_indra is not None: known_mf_type = mf_type_indra break if not known_mf_type: logger.debug('Skipping modification with unknown terms: %s' % ', '.join(mf_type_terms)) return None mod_type, residue = known_mf_type # getFeatureLocation returns SequenceLocation, which is the # generic parent class of SequenceSite and SequenceInterval. # Here we need to cast to SequenceSite in order to get to # the sequence position. mf_pos = mf.getFeatureLocation() if mf_pos is not None: # If it is not a SequenceSite we can't handle it if not mf_pos.modelInterface.getName() == \ 'org.biopax.paxtools.model.level3.SequenceSite': mod_pos = None else: mf_site = cast(_bp('SequenceSite'), mf_pos) mf_pos_status = mf_site.getPositionStatus() if mf_pos_status is None: mod_pos = None elif mf_pos_status and mf_pos_status.toString() != 'EQUAL': logger.debug('Modification site position is %s' % mf_pos_status.toString()) else: mod_pos = mf_site.getSequencePosition() mod_pos = '%s' % mod_pos else: mod_pos = None mc = ModCondition(mod_type, residue, mod_pos, True) return mc
python
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 = None for t in mf_type_terms: if t.startswith('MOD_RES '): t = t[8:] mf_type_indra = _mftype_dict.get(t) if mf_type_indra is not None: known_mf_type = mf_type_indra break if not known_mf_type: logger.debug('Skipping modification with unknown terms: %s' % ', '.join(mf_type_terms)) return None mod_type, residue = known_mf_type # getFeatureLocation returns SequenceLocation, which is the # generic parent class of SequenceSite and SequenceInterval. # Here we need to cast to SequenceSite in order to get to # the sequence position. mf_pos = mf.getFeatureLocation() if mf_pos is not None: # If it is not a SequenceSite we can't handle it if not mf_pos.modelInterface.getName() == \ 'org.biopax.paxtools.model.level3.SequenceSite': mod_pos = None else: mf_site = cast(_bp('SequenceSite'), mf_pos) mf_pos_status = mf_site.getPositionStatus() if mf_pos_status is None: mod_pos = None elif mf_pos_status and mf_pos_status.toString() != 'EQUAL': logger.debug('Modification site position is %s' % mf_pos_status.toString()) else: mod_pos = mf_site.getSequencePosition() mod_pos = '%s' % mod_pos else: mod_pos = None mc = ModCondition(mod_type, residue, mod_pos, True) return mc
[ "def", "_extract_mod_from_feature", "(", "mf", ")", ":", "# ModificationFeature / SequenceModificationVocabulary", "mf_type", "=", "mf", ".", "getModificationType", "(", ")", "if", "mf_type", "is", "None", ":", "return", "None", "mf_type_terms", "=", "mf_type", ".", ...
Extract the type of modification and the position from a ModificationFeature object in the INDRA format.
[ "Extract", "the", "type", "of", "modification", "and", "the", "position", "from", "a", "ModificationFeature", "object", "in", "the", "INDRA", "format", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/biopax/processor.py#L875-L922
18,830
sorgerlab/indra
indra/sources/biopax/processor.py
BiopaxProcessor._get_entref
def _get_entref(bpe): """Returns the entity reference of an entity if it exists or return the entity reference that was passed in as argument.""" if not _is_reference(bpe): try: er = bpe.getEntityReference() except AttributeError: return None return er else: return bpe
python
def _get_entref(bpe): if not _is_reference(bpe): try: er = bpe.getEntityReference() except AttributeError: return None return er else: return bpe
[ "def", "_get_entref", "(", "bpe", ")", ":", "if", "not", "_is_reference", "(", "bpe", ")", ":", "try", ":", "er", "=", "bpe", ".", "getEntityReference", "(", ")", "except", "AttributeError", ":", "return", "None", "return", "er", "else", ":", "return", ...
Returns the entity reference of an entity if it exists or return the entity reference that was passed in as argument.
[ "Returns", "the", "entity", "reference", "of", "an", "entity", "if", "it", "exists", "or", "return", "the", "entity", "reference", "that", "was", "passed", "in", "as", "argument", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/biopax/processor.py#L1224-L1234
18,831
sorgerlab/indra
indra/sources/trips/processor.py
_stmt_location_to_agents
def _stmt_location_to_agents(stmt, location): """Apply an event location to the Agents in the corresponding Statement. If a Statement is in a given location we represent that by requiring all Agents in the Statement to be in that location. """ if location is None: return agents = stmt.agent_list() for a in agents: if a is not None: a.location = location
python
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
[ "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", "...
Apply an event location to the Agents in the corresponding Statement. If a Statement is in a given location we represent that by requiring all Agents in the Statement to be in that location.
[ "Apply", "an", "event", "location", "to", "the", "Agents", "in", "the", "corresponding", "Statement", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/trips/processor.py#L1710-L1721
18,832
sorgerlab/indra
indra/sources/trips/processor.py
TripsProcessor.get_all_events
def get_all_events(self): """Make a list of all events in the TRIPS EKB. The events are stored in self.all_events. """ 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: continue event_type = e.find('type').text try: self.all_events[event_type].append(event_id) except KeyError: self.all_events[event_type] = [event_id]
python
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: continue event_type = e.find('type').text try: self.all_events[event_type].append(event_id) except KeyError: self.all_events[event_type] = [event_id]
[ "def", "get_all_events", "(", "self", ")", ":", "self", ".", "all_events", "=", "{", "}", "events", "=", "self", ".", "tree", ".", "findall", "(", "'EVENT'", ")", "events", "+=", "self", ".", "tree", ".", "findall", "(", "'CC'", ")", "for", "e", "i...
Make a list of all events in the TRIPS EKB. The events are stored in self.all_events.
[ "Make", "a", "list", "of", "all", "events", "in", "the", "TRIPS", "EKB", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/trips/processor.py#L98-L114
18,833
sorgerlab/indra
indra/sources/trips/processor.py
TripsProcessor.get_activations
def get_activations(self): """Extract direct Activation INDRA Statements.""" 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 (act_events + inact_events): event_id = event.attrib['id'] if event_id in self._static_events: continue # Get the activating agent in the event agent = event.find(".//*[@role=':AGENT']") if agent is None: continue agent_id = agent.attrib.get('id') if agent_id is None: logger.debug( 'Skipping activation with missing activator agent') continue activator_agent = self._get_agent_by_id(agent_id, event_id) if activator_agent is None: continue # Get the activated agent in the event affected = event.find(".//*[@role=':AFFECTED']") if affected is None: logger.debug( 'Skipping activation with missing affected agent') continue affected_id = affected.attrib.get('id') if affected_id is None: logger.debug( 'Skipping activation with missing affected agent') continue affected_agent = self._get_agent_by_id(affected_id, event_id) if affected_agent is None: logger.debug( 'Skipping activation with missing affected agent') continue is_activation = True if _is_type(event, 'ONT::ACTIVATE'): self._add_extracted('ONT::ACTIVATE', event.attrib['id']) elif _is_type(event, 'ONT::INHIBIT'): is_activation = False self._add_extracted('ONT::INHIBIT', event.attrib['id']) elif _is_type(event, 'ONT::DEACTIVATE'): is_activation = False self._add_extracted('ONT::DEACTIVATE', event.attrib['id']) ev = self._get_evidence(event) location = self._get_event_location(event) for a1, a2 in _agent_list_product((activator_agent, affected_agent)): if is_activation: st = Activation(a1, a2, evidence=[deepcopy(ev)]) else: st = Inhibition(a1, a2, evidence=[deepcopy(ev)]) _stmt_location_to_agents(st, location) self.statements.append(st)
python
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 (act_events + inact_events): event_id = event.attrib['id'] if event_id in self._static_events: continue # Get the activating agent in the event agent = event.find(".//*[@role=':AGENT']") if agent is None: continue agent_id = agent.attrib.get('id') if agent_id is None: logger.debug( 'Skipping activation with missing activator agent') continue activator_agent = self._get_agent_by_id(agent_id, event_id) if activator_agent is None: continue # Get the activated agent in the event affected = event.find(".//*[@role=':AFFECTED']") if affected is None: logger.debug( 'Skipping activation with missing affected agent') continue affected_id = affected.attrib.get('id') if affected_id is None: logger.debug( 'Skipping activation with missing affected agent') continue affected_agent = self._get_agent_by_id(affected_id, event_id) if affected_agent is None: logger.debug( 'Skipping activation with missing affected agent') continue is_activation = True if _is_type(event, 'ONT::ACTIVATE'): self._add_extracted('ONT::ACTIVATE', event.attrib['id']) elif _is_type(event, 'ONT::INHIBIT'): is_activation = False self._add_extracted('ONT::INHIBIT', event.attrib['id']) elif _is_type(event, 'ONT::DEACTIVATE'): is_activation = False self._add_extracted('ONT::DEACTIVATE', event.attrib['id']) ev = self._get_evidence(event) location = self._get_event_location(event) for a1, a2 in _agent_list_product((activator_agent, affected_agent)): if is_activation: st = Activation(a1, a2, evidence=[deepcopy(ev)]) else: st = Inhibition(a1, a2, evidence=[deepcopy(ev)]) _stmt_location_to_agents(st, location) self.statements.append(st)
[ "def", "get_activations", "(", "self", ")", ":", "act_events", "=", "self", ".", "tree", ".", "findall", "(", "\"EVENT/[type='ONT::ACTIVATE']\"", ")", "inact_events", "=", "self", ".", "tree", ".", "findall", "(", "\"EVENT/[type='ONT::DEACTIVATE']\"", ")", "inact_...
Extract direct Activation INDRA Statements.
[ "Extract", "direct", "Activation", "INDRA", "Statements", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/trips/processor.py#L116-L174
18,834
sorgerlab/indra
indra/sources/trips/processor.py
TripsProcessor.get_activations_causal
def get_activations_causal(self): """Extract causal Activation INDRA Statements.""" # 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/[@role=':OUTCOME']") # If either the factor or the outcome is missing, skip if factor is None or outcome is None: continue factor_id = factor.attrib.get('id') # Here, implicitly, we require that the factor is a TERM # and not an EVENT factor_term = self.tree.find("TERM/[@id='%s']" % factor_id) outcome_id = outcome.attrib.get('id') # Here it is implicit that the outcome is an event not # a TERM outcome_event = self.tree.find("EVENT/[@id='%s']" % outcome_id) if factor_term is None or outcome_event is None: continue factor_term_type = factor_term.find('type') # The factor term must be a molecular entity if factor_term_type is None or \ factor_term_type.text not in molecule_types: continue factor_agent = self._get_agent_by_id(factor_id, None) if factor_agent is None: continue outcome_event_type = outcome_event.find('type') if outcome_event_type is None: continue # Construct evidence ev = self._get_evidence(cc) ev.epistemics['direct'] = False location = self._get_event_location(outcome_event) if outcome_event_type.text in ['ONT::ACTIVATE', 'ONT::ACTIVITY', 'ONT::DEACTIVATE']: if outcome_event_type.text in ['ONT::ACTIVATE', 'ONT::DEACTIVATE']: agent_tag = outcome_event.find(".//*[@role=':AFFECTED']") elif outcome_event_type.text == 'ONT::ACTIVITY': agent_tag = outcome_event.find(".//*[@role=':AGENT']") if agent_tag is None or agent_tag.attrib.get('id') is None: continue outcome_agent = self._get_agent_by_id(agent_tag.attrib['id'], outcome_id) if outcome_agent is None: continue if outcome_event_type.text == 'ONT::DEACTIVATE': is_activation = False else: is_activation = True for a1, a2 in _agent_list_product((factor_agent, outcome_agent)): if is_activation: st = Activation(a1, a2, evidence=[deepcopy(ev)]) else: st = Inhibition(a1, a2, evidence=[deepcopy(ev)]) _stmt_location_to_agents(st, location) self.statements.append(st)
python
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/[@role=':OUTCOME']") # If either the factor or the outcome is missing, skip if factor is None or outcome is None: continue factor_id = factor.attrib.get('id') # Here, implicitly, we require that the factor is a TERM # and not an EVENT factor_term = self.tree.find("TERM/[@id='%s']" % factor_id) outcome_id = outcome.attrib.get('id') # Here it is implicit that the outcome is an event not # a TERM outcome_event = self.tree.find("EVENT/[@id='%s']" % outcome_id) if factor_term is None or outcome_event is None: continue factor_term_type = factor_term.find('type') # The factor term must be a molecular entity if factor_term_type is None or \ factor_term_type.text not in molecule_types: continue factor_agent = self._get_agent_by_id(factor_id, None) if factor_agent is None: continue outcome_event_type = outcome_event.find('type') if outcome_event_type is None: continue # Construct evidence ev = self._get_evidence(cc) ev.epistemics['direct'] = False location = self._get_event_location(outcome_event) if outcome_event_type.text in ['ONT::ACTIVATE', 'ONT::ACTIVITY', 'ONT::DEACTIVATE']: if outcome_event_type.text in ['ONT::ACTIVATE', 'ONT::DEACTIVATE']: agent_tag = outcome_event.find(".//*[@role=':AFFECTED']") elif outcome_event_type.text == 'ONT::ACTIVITY': agent_tag = outcome_event.find(".//*[@role=':AGENT']") if agent_tag is None or agent_tag.attrib.get('id') is None: continue outcome_agent = self._get_agent_by_id(agent_tag.attrib['id'], outcome_id) if outcome_agent is None: continue if outcome_event_type.text == 'ONT::DEACTIVATE': is_activation = False else: is_activation = True for a1, a2 in _agent_list_product((factor_agent, outcome_agent)): if is_activation: st = Activation(a1, a2, evidence=[deepcopy(ev)]) else: st = Inhibition(a1, a2, evidence=[deepcopy(ev)]) _stmt_location_to_agents(st, location) self.statements.append(st)
[ "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", ...
Extract causal Activation INDRA Statements.
[ "Extract", "causal", "Activation", "INDRA", "Statements", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/trips/processor.py#L176-L235
18,835
sorgerlab/indra
indra/sources/trips/processor.py
TripsProcessor.get_activations_stimulate
def get_activations_stimulate(self): """Extract Activation INDRA Statements via stimulation.""" # 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/[type='ONT::STIMULATE']") for event in stim_events: event_id = event.attrib.get('id') if event_id in self._static_events: continue controller = event.find("arg1/[@role=':AGENT']") affected = event.find("arg2/[@role=':AFFECTED']") # If either the controller or the affected is missing, skip if controller is None or affected is None: continue controller_id = controller.attrib.get('id') # Here, implicitly, we require that the controller is a TERM # and not an EVENT controller_term = self.tree.find("TERM/[@id='%s']" % controller_id) affected_id = affected.attrib.get('id') # Here it is implicit that the affected is an event not # a TERM affected_event = self.tree.find("EVENT/[@id='%s']" % affected_id) if controller_term is None or affected_event is None: continue controller_term_type = controller_term.find('type') # The controller term must be a molecular entity if controller_term_type is None or \ controller_term_type.text not in molecule_types: continue controller_agent = self._get_agent_by_id(controller_id, None) if controller_agent is None: continue affected_event_type = affected_event.find('type') if affected_event_type is None: continue # Construct evidence ev = self._get_evidence(event) ev.epistemics['direct'] = False location = self._get_event_location(affected_event) if affected_event_type.text == 'ONT::ACTIVATE': affected = affected_event.find(".//*[@role=':AFFECTED']") if affected is None: continue affected_agent = self._get_agent_by_id(affected.attrib['id'], affected_id) if affected_agent is None: continue for a1, a2 in _agent_list_product((controller_agent, affected_agent)): st = Activation(a1, a2, evidence=[deepcopy(ev)]) _stmt_location_to_agents(st, location) self.statements.append(st) elif affected_event_type.text == 'ONT::ACTIVITY': agent_tag = affected_event.find(".//*[@role=':AGENT']") if agent_tag is None: continue affected_agent = self._get_agent_by_id(agent_tag.attrib['id'], affected_id) if affected_agent is None: continue for a1, a2 in _agent_list_product((controller_agent, affected_agent)): st = Activation(a1, a2, evidence=[deepcopy(ev)]) _stmt_location_to_agents(st, location) self.statements.append(st)
python
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/[type='ONT::STIMULATE']") for event in stim_events: event_id = event.attrib.get('id') if event_id in self._static_events: continue controller = event.find("arg1/[@role=':AGENT']") affected = event.find("arg2/[@role=':AFFECTED']") # If either the controller or the affected is missing, skip if controller is None or affected is None: continue controller_id = controller.attrib.get('id') # Here, implicitly, we require that the controller is a TERM # and not an EVENT controller_term = self.tree.find("TERM/[@id='%s']" % controller_id) affected_id = affected.attrib.get('id') # Here it is implicit that the affected is an event not # a TERM affected_event = self.tree.find("EVENT/[@id='%s']" % affected_id) if controller_term is None or affected_event is None: continue controller_term_type = controller_term.find('type') # The controller term must be a molecular entity if controller_term_type is None or \ controller_term_type.text not in molecule_types: continue controller_agent = self._get_agent_by_id(controller_id, None) if controller_agent is None: continue affected_event_type = affected_event.find('type') if affected_event_type is None: continue # Construct evidence ev = self._get_evidence(event) ev.epistemics['direct'] = False location = self._get_event_location(affected_event) if affected_event_type.text == 'ONT::ACTIVATE': affected = affected_event.find(".//*[@role=':AFFECTED']") if affected is None: continue affected_agent = self._get_agent_by_id(affected.attrib['id'], affected_id) if affected_agent is None: continue for a1, a2 in _agent_list_product((controller_agent, affected_agent)): st = Activation(a1, a2, evidence=[deepcopy(ev)]) _stmt_location_to_agents(st, location) self.statements.append(st) elif affected_event_type.text == 'ONT::ACTIVITY': agent_tag = affected_event.find(".//*[@role=':AGENT']") if agent_tag is None: continue affected_agent = self._get_agent_by_id(agent_tag.attrib['id'], affected_id) if affected_agent is None: continue for a1, a2 in _agent_list_product((controller_agent, affected_agent)): st = Activation(a1, a2, evidence=[deepcopy(ev)]) _stmt_location_to_agents(st, location) self.statements.append(st)
[ "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", "(",...
Extract Activation INDRA Statements via stimulation.
[ "Extract", "Activation", "INDRA", "Statements", "via", "stimulation", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/trips/processor.py#L237-L303
18,836
sorgerlab/indra
indra/sources/trips/processor.py
TripsProcessor.get_degradations
def get_degradations(self): """Extract Degradation INDRA Statements.""" 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=':AFFECTED']") if affected is None: msg = 'Skipping degradation event with no affected term.' logger.debug(msg) continue # Make sure the degradation is affecting a molecule type # Temporarily removed for CwC compatibility with no type tag #affected_type = affected.find('type') #if affected_type is None or \ # affected_type.text not in molecule_types: # continue affected_id = affected.attrib.get('id') if affected_id is None: logger.debug( 'Skipping degradation event with missing affected agent') continue affected_agent = self._get_agent_by_id(affected_id, event.attrib['id']) if affected_agent is None: logger.debug( 'Skipping degradation event with missing affected agent') continue agent = event.find(".//*[@role=':AGENT']") if agent is None: agent_agent = None else: agent_id = agent.attrib.get('id') if agent_id is None: agent_agent = None else: agent_agent = self._get_agent_by_id(agent_id, event.attrib['id']) ev = self._get_evidence(event) location = self._get_event_location(event) for subj, obj in \ _agent_list_product((agent_agent, affected_agent)): st = DecreaseAmount(subj, obj, evidence=deepcopy(ev)) _stmt_location_to_agents(st, location) self.statements.append(st) self._add_extracted(_get_type(event), event.attrib['id'])
python
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=':AFFECTED']") if affected is None: msg = 'Skipping degradation event with no affected term.' logger.debug(msg) continue # Make sure the degradation is affecting a molecule type # Temporarily removed for CwC compatibility with no type tag #affected_type = affected.find('type') #if affected_type is None or \ # affected_type.text not in molecule_types: # continue affected_id = affected.attrib.get('id') if affected_id is None: logger.debug( 'Skipping degradation event with missing affected agent') continue affected_agent = self._get_agent_by_id(affected_id, event.attrib['id']) if affected_agent is None: logger.debug( 'Skipping degradation event with missing affected agent') continue agent = event.find(".//*[@role=':AGENT']") if agent is None: agent_agent = None else: agent_id = agent.attrib.get('id') if agent_id is None: agent_agent = None else: agent_agent = self._get_agent_by_id(agent_id, event.attrib['id']) ev = self._get_evidence(event) location = self._get_event_location(event) for subj, obj in \ _agent_list_product((agent_agent, affected_agent)): st = DecreaseAmount(subj, obj, evidence=deepcopy(ev)) _stmt_location_to_agents(st, location) self.statements.append(st) self._add_extracted(_get_type(event), event.attrib['id'])
[ "def", "get_degradations", "(", "self", ")", ":", "deg_events", "=", "self", ".", "tree", ".", "findall", "(", "\"EVENT/[type='ONT::CONSUME']\"", ")", "for", "event", "in", "deg_events", ":", "if", "event", ".", "attrib", "[", "'id'", "]", "in", "self", "....
Extract Degradation INDRA Statements.
[ "Extract", "Degradation", "INDRA", "Statements", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/trips/processor.py#L305-L354
18,837
sorgerlab/indra
indra/sources/trips/processor.py
TripsProcessor.get_complexes
def get_complexes(self): """Extract Complex INDRA Statements.""" 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: continue arg1 = event.find("arg1") arg2 = event.find("arg2") # EKB-AGENT if arg1 is None and arg2 is None: args = list(event.findall('arg')) if len(args) < 2: continue arg1 = args[0] arg2 = args[1] if (arg1 is None or arg1.attrib.get('id') is None) or \ (arg2 is None or arg2.attrib.get('id') is None): logger.debug('Skipping complex with less than 2 members') continue agent1 = self._get_agent_by_id(arg1.attrib['id'], event.attrib['id']) agent2 = self._get_agent_by_id(arg2.attrib['id'], event.attrib['id']) if agent1 is None or agent2 is None: logger.debug('Skipping complex with less than 2 members') continue # Information on binding site is either attached to the agent term # in a features/site tag or attached to the event itself in # a site tag ''' site_feature = self._find_in_term(arg1.attrib['id'], 'features/site') if site_feature is not None: sites, positions = self._get_site_by_id(site_id) print sites, positions site_feature = self._find_in_term(arg2.attrib['id'], 'features/site') if site_feature is not None: sites, positions = self._get_site_by_id(site_id) print sites, positions site = event.find("site") if site is not None: sites, positions = self._get_site_by_id(site.attrib['id']) print sites, positions ''' ev = self._get_evidence(event) location = self._get_event_location(event) for a1, a2 in _agent_list_product((agent1, agent2)): st = Complex([a1, a2], evidence=deepcopy(ev)) _stmt_location_to_agents(st, location) self.statements.append(st) self._add_extracted(_get_type(event), event.attrib['id'])
python
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: continue arg1 = event.find("arg1") arg2 = event.find("arg2") # EKB-AGENT if arg1 is None and arg2 is None: args = list(event.findall('arg')) if len(args) < 2: continue arg1 = args[0] arg2 = args[1] if (arg1 is None or arg1.attrib.get('id') is None) or \ (arg2 is None or arg2.attrib.get('id') is None): logger.debug('Skipping complex with less than 2 members') continue agent1 = self._get_agent_by_id(arg1.attrib['id'], event.attrib['id']) agent2 = self._get_agent_by_id(arg2.attrib['id'], event.attrib['id']) if agent1 is None or agent2 is None: logger.debug('Skipping complex with less than 2 members') continue # Information on binding site is either attached to the agent term # in a features/site tag or attached to the event itself in # a site tag ''' site_feature = self._find_in_term(arg1.attrib['id'], 'features/site') if site_feature is not None: sites, positions = self._get_site_by_id(site_id) print sites, positions site_feature = self._find_in_term(arg2.attrib['id'], 'features/site') if site_feature is not None: sites, positions = self._get_site_by_id(site_id) print sites, positions site = event.find("site") if site is not None: sites, positions = self._get_site_by_id(site.attrib['id']) print sites, positions ''' ev = self._get_evidence(event) location = self._get_event_location(event) for a1, a2 in _agent_list_product((agent1, agent2)): st = Complex([a1, a2], evidence=deepcopy(ev)) _stmt_location_to_agents(st, location) self.statements.append(st) self._add_extracted(_get_type(event), event.attrib['id'])
[ "def", "get_complexes", "(", "self", ")", ":", "bind_events", "=", "self", ".", "tree", ".", "findall", "(", "\"EVENT/[type='ONT::BIND']\"", ")", "bind_events", "+=", "self", ".", "tree", ".", "findall", "(", "\"EVENT/[type='ONT::INTERACT']\"", ")", "for", "even...
Extract Complex INDRA Statements.
[ "Extract", "Complex", "INDRA", "Statements", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/trips/processor.py#L637-L693
18,838
sorgerlab/indra
indra/sources/trips/processor.py
TripsProcessor.get_modifications
def get_modifications(self): """Extract all types of Modification INDRA Statements.""" # 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_event_types: events = self.tree.findall("EVENT/[type='%s']" % mod_event_type) mod_extracted = self.extracted_events.get(mod_event_type, []) for event in events: event_id = event.attrib.get('id') if event_id not in mod_extracted: mod_events.append(event) # Iterate over all modification events for event in mod_events: stmts = self._get_modification_event(event) if stmts: for stmt in stmts: self.statements.append(stmt)
python
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_event_types: events = self.tree.findall("EVENT/[type='%s']" % mod_event_type) mod_extracted = self.extracted_events.get(mod_event_type, []) for event in events: event_id = event.attrib.get('id') if event_id not in mod_extracted: mod_events.append(event) # Iterate over all modification events for event in mod_events: stmts = self._get_modification_event(event) if stmts: for stmt in stmts: self.statements.append(stmt)
[ "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",...
Extract all types of Modification INDRA Statements.
[ "Extract", "all", "types", "of", "Modification", "INDRA", "Statements", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/trips/processor.py#L695-L715
18,839
sorgerlab/indra
indra/sources/trips/processor.py
TripsProcessor.get_modifications_indirect
def get_modifications_indirect(self): """Extract indirect Modification INDRA Statements.""" # 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): mod_events = [] events = self.tree.findall("EVENT/[type='ONT::INCREASE']") for event in events: affected = event.find(".//*[@role=':AFFECTED']") if affected is None: continue affected_id = affected.attrib.get('id') if not affected_id: continue pattern = "EVENT/[@id='%s']" % affected_id affected_event = self.tree.find(pattern) if affected_event is not None: affected_type = affected_event.find('type') if affected_type is not None and \ affected_type.text in mod_event_types: mod_events.append(event) return mod_events def get_cause_events(mod_event_types): mod_events = [] ccs = self.tree.findall("CC/[type='ONT::CAUSE']") for cc in ccs: outcome = cc.find(".//*[@role=':OUTCOME']") if outcome is None: continue outcome_id = outcome.attrib.get('id') if not outcome_id: continue pattern = "EVENT/[@id='%s']" % outcome_id outcome_event = self.tree.find(pattern) if outcome_event is not None: outcome_type = outcome_event.find('type') if outcome_type is not None and \ outcome_type.text in mod_event_types: mod_events.append(cc) return mod_events mod_events = get_increase_events(mod_event_types) mod_events += get_cause_events(mod_event_types) # Iterate over all modification events for event in mod_events: event_id = event.attrib['id'] if event_id in self._static_events: continue event_type = _get_type(event) # Get enzyme Agent enzyme = event.find(".//*[@role=':AGENT']") if enzyme is None: enzyme = event.find(".//*[@role=':FACTOR']") if enzyme is None: return enzyme_id = enzyme.attrib.get('id') if enzyme_id is None: continue enzyme_agent = self._get_agent_by_id(enzyme_id, event_id) affected_event_tag = event.find(".//*[@role=':AFFECTED']") if affected_event_tag is None: affected_event_tag = event.find(".//*[@role=':OUTCOME']") if affected_event_tag is None: return affected_id = affected_event_tag.attrib.get('id') if not affected_id: return affected_event = self.tree.find("EVENT/[@id='%s']" % affected_id) if affected_event is None: return # Iterate over all enzyme agents if there are multiple ones for enz_t in _agent_list_product((enzyme_agent, )): # enz_t comes out as a tuple so we need to take the first # element here enz = enz_t[0] # Note that we re-run the extraction code here potentially # multiple times. This is mainly to make sure each Statement # object created here is independent (i.e. has different UUIDs) # without having to manipulate it after creation. stmts = self._get_modification_event(affected_event) stmts_to_make = [] if stmts: for stmt in stmts: # The affected event should have no enzyme but should # have a substrate if stmt.enz is None and stmt.sub is not None: stmts_to_make.append(stmt) for stmt in stmts_to_make: stmt.enz = enz for ev in stmt.evidence: ev.epistemics['direct'] = False self.statements.append(stmt) self._add_extracted(event_type, event.attrib['id']) self._add_extracted(affected_event.find('type').text, affected_id)
python
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): mod_events = [] events = self.tree.findall("EVENT/[type='ONT::INCREASE']") for event in events: affected = event.find(".//*[@role=':AFFECTED']") if affected is None: continue affected_id = affected.attrib.get('id') if not affected_id: continue pattern = "EVENT/[@id='%s']" % affected_id affected_event = self.tree.find(pattern) if affected_event is not None: affected_type = affected_event.find('type') if affected_type is not None and \ affected_type.text in mod_event_types: mod_events.append(event) return mod_events def get_cause_events(mod_event_types): mod_events = [] ccs = self.tree.findall("CC/[type='ONT::CAUSE']") for cc in ccs: outcome = cc.find(".//*[@role=':OUTCOME']") if outcome is None: continue outcome_id = outcome.attrib.get('id') if not outcome_id: continue pattern = "EVENT/[@id='%s']" % outcome_id outcome_event = self.tree.find(pattern) if outcome_event is not None: outcome_type = outcome_event.find('type') if outcome_type is not None and \ outcome_type.text in mod_event_types: mod_events.append(cc) return mod_events mod_events = get_increase_events(mod_event_types) mod_events += get_cause_events(mod_event_types) # Iterate over all modification events for event in mod_events: event_id = event.attrib['id'] if event_id in self._static_events: continue event_type = _get_type(event) # Get enzyme Agent enzyme = event.find(".//*[@role=':AGENT']") if enzyme is None: enzyme = event.find(".//*[@role=':FACTOR']") if enzyme is None: return enzyme_id = enzyme.attrib.get('id') if enzyme_id is None: continue enzyme_agent = self._get_agent_by_id(enzyme_id, event_id) affected_event_tag = event.find(".//*[@role=':AFFECTED']") if affected_event_tag is None: affected_event_tag = event.find(".//*[@role=':OUTCOME']") if affected_event_tag is None: return affected_id = affected_event_tag.attrib.get('id') if not affected_id: return affected_event = self.tree.find("EVENT/[@id='%s']" % affected_id) if affected_event is None: return # Iterate over all enzyme agents if there are multiple ones for enz_t in _agent_list_product((enzyme_agent, )): # enz_t comes out as a tuple so we need to take the first # element here enz = enz_t[0] # Note that we re-run the extraction code here potentially # multiple times. This is mainly to make sure each Statement # object created here is independent (i.e. has different UUIDs) # without having to manipulate it after creation. stmts = self._get_modification_event(affected_event) stmts_to_make = [] if stmts: for stmt in stmts: # The affected event should have no enzyme but should # have a substrate if stmt.enz is None and stmt.sub is not None: stmts_to_make.append(stmt) for stmt in stmts_to_make: stmt.enz = enz for ev in stmt.evidence: ev.epistemics['direct'] = False self.statements.append(stmt) self._add_extracted(event_type, event.attrib['id']) self._add_extracted(affected_event.find('type').text, affected_id)
[ "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...
Extract indirect Modification INDRA Statements.
[ "Extract", "indirect", "Modification", "INDRA", "Statements", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/trips/processor.py#L717-L821
18,840
sorgerlab/indra
indra/sources/trips/processor.py
TripsProcessor.get_agents
def get_agents(self): """Return list of INDRA Agents corresponding to TERMs in the EKB. This is meant to be used when entities e.g. "phosphorylated ERK", rather than events need to be extracted from processed natural language. These entities with their respective states are represented as INDRA Agents. Returns ------- agents : list[indra.statements.Agent] List of INDRA Agents extracted from EKB. """ agents_dict = self.get_term_agents() agents = [a for a in agents_dict.values() if a is not None] return agents
python
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
[ "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. This is meant to be used when entities e.g. "phosphorylated ERK", rather than events need to be extracted from processed natural language. These entities with their respective states are represented as INDRA Agents. Returns ------- agents : list[indra.statements.Agent] List of INDRA Agents extracted from EKB.
[ "Return", "list", "of", "INDRA", "Agents", "corresponding", "to", "TERMs", "in", "the", "EKB", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/trips/processor.py#L1059-L1074
18,841
sorgerlab/indra
indra/sources/trips/processor.py
TripsProcessor.get_term_agents
def get_term_agents(self): """Return dict of INDRA Agents keyed by corresponding TERMs in the EKB. This is meant to be used when entities e.g. "phosphorylated ERK", rather than events need to be extracted from processed natural language. These entities with their respective states are represented as INDRA Agents. Further, each key of the dictionary corresponds to the ID assigned by TRIPS to the given TERM that the Agent was extracted from. Returns ------- agents : dict[str, indra.statements.Agent] Dict of INDRA Agents extracted from EKB. """ 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, None) agents[term_id] = agent # Handle assoc-with links aw = term.find('assoc-with') if aw is not None: aw_id = aw.attrib.get('id') if aw_id: assoc_links.append((term_id, aw_id)) # We only keep the target end of assoc with links if both # source and target are in the list for source, target in assoc_links: if target in agents and source in agents: agents.pop(source) return agents
python
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, None) agents[term_id] = agent # Handle assoc-with links aw = term.find('assoc-with') if aw is not None: aw_id = aw.attrib.get('id') if aw_id: assoc_links.append((term_id, aw_id)) # We only keep the target end of assoc with links if both # source and target are in the list for source, target in assoc_links: if target in agents and source in agents: agents.pop(source) return agents
[ "def", "get_term_agents", "(", "self", ")", ":", "terms", "=", "self", ".", "tree", ".", "findall", "(", "'TERM'", ")", "agents", "=", "{", "}", "assoc_links", "=", "[", "]", "for", "term", "in", "terms", ":", "term_id", "=", "term", ".", "attrib", ...
Return dict of INDRA Agents keyed by corresponding TERMs in the EKB. This is meant to be used when entities e.g. "phosphorylated ERK", rather than events need to be extracted from processed natural language. These entities with their respective states are represented as INDRA Agents. Further, each key of the dictionary corresponds to the ID assigned by TRIPS to the given TERM that the Agent was extracted from. Returns ------- agents : dict[str, indra.statements.Agent] Dict of INDRA Agents extracted from EKB.
[ "Return", "dict", "of", "INDRA", "Agents", "keyed", "by", "corresponding", "TERMs", "in", "the", "EKB", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/trips/processor.py#L1076-L1110
18,842
sorgerlab/indra
indra/sources/trips/processor.py
TripsProcessor._get_evidence_text
def _get_evidence_text(self, event_tag): """Extract the evidence for an event. Pieces of text linked to an EVENT are fragments of a sentence. The EVENT refers to the paragraph ID and the "uttnum", which corresponds to a sentence ID. Here we find and return the full sentence from which the event was taken. """ 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 = self.sentences[uttnum] elif event_text is not None: sentence = event_text.text else: sentence = None return sentence
python
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 = self.sentences[uttnum] elif event_text is not None: sentence = event_text.text else: sentence = None return sentence
[ "def", "_get_evidence_text", "(", "self", ",", "event_tag", ")", ":", "par_id", "=", "event_tag", ".", "attrib", ".", "get", "(", "'paragraph'", ")", "uttnum", "=", "event_tag", ".", "attrib", ".", "get", "(", "'uttnum'", ")", "event_text", "=", "event_tag...
Extract the evidence for an event. Pieces of text linked to an EVENT are fragments of a sentence. The EVENT refers to the paragraph ID and the "uttnum", which corresponds to a sentence ID. Here we find and return the full sentence from which the event was taken.
[ "Extract", "the", "evidence", "for", "an", "event", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/trips/processor.py#L1596-L1613
18,843
sorgerlab/indra
indra/assemblers/pybel/assembler.py
get_causal_edge
def get_causal_edge(stmt, activates): """Returns the causal, polar edge with the correct "contact".""" 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.INCREASES if activates else pc.DECREASES
python
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.INCREASES if activates else pc.DECREASES
[ "def", "get_causal_edge", "(", "stmt", ",", "activates", ")", ":", "any_contact", "=", "any", "(", "evidence", ".", "epistemics", ".", "get", "(", "'direct'", ",", "False", ")", "for", "evidence", "in", "stmt", ".", "evidence", ")", "if", "any_contact", ...
Returns the causal, polar edge with the correct "contact".
[ "Returns", "the", "causal", "polar", "edge", "with", "the", "correct", "contact", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/pybel/assembler.py#L568-L577
18,844
sorgerlab/indra
indra/assemblers/pybel/assembler.py
PybelAssembler.to_database
def to_database(self, manager=None): """Send the model to the PyBEL database This function wraps :py:func:`pybel.to_database`. Parameters ---------- manager : Optional[pybel.manager.Manager] A PyBEL database manager. If none, first checks the PyBEL configuration for ``PYBEL_CONNECTION`` then checks the environment variable ``PYBEL_REMOTE_HOST``. Finally, defaults to using SQLite database in PyBEL data directory (automatically configured by PyBEL) Returns ------- network : Optional[pybel.manager.models.Network] The SQLAlchemy model representing the network that was uploaded. Returns None if upload fails. """ network = pybel.to_database(self.model, manager=manager) return network
python
def to_database(self, manager=None): network = pybel.to_database(self.model, manager=manager) return network
[ "def", "to_database", "(", "self", ",", "manager", "=", "None", ")", ":", "network", "=", "pybel", ".", "to_database", "(", "self", ".", "model", ",", "manager", "=", "manager", ")", "return", "network" ]
Send the model to the PyBEL database This function wraps :py:func:`pybel.to_database`. Parameters ---------- manager : Optional[pybel.manager.Manager] A PyBEL database manager. If none, first checks the PyBEL configuration for ``PYBEL_CONNECTION`` then checks the environment variable ``PYBEL_REMOTE_HOST``. Finally, defaults to using SQLite database in PyBEL data directory (automatically configured by PyBEL) Returns ------- network : Optional[pybel.manager.models.Network] The SQLAlchemy model representing the network that was uploaded. Returns None if upload fails.
[ "Send", "the", "model", "to", "the", "PyBEL", "database" ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/pybel/assembler.py#L149-L170
18,845
sorgerlab/indra
indra/assemblers/pysb/sites.py
get_binding_site_name
def get_binding_site_name(agent): """Return a binding site name from a given 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 parents in hierarchy parents = hierarchies['entity'].get_parents(uri, 'top') if parents: # Choose the first parent if there are more than one parent_uri = sorted(parents)[0] parent_agent = _agent_from_uri(parent_uri) binding_site = _n(parent_agent.name).lower() return binding_site # Fall back to Agent's own name if one from parent can't be constructed binding_site = _n(agent.name).lower() return binding_site
python
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 parents in hierarchy parents = hierarchies['entity'].get_parents(uri, 'top') if parents: # Choose the first parent if there are more than one parent_uri = sorted(parents)[0] parent_agent = _agent_from_uri(parent_uri) binding_site = _n(parent_agent.name).lower() return binding_site # Fall back to Agent's own name if one from parent can't be constructed binding_site = _n(agent.name).lower() return binding_site
[ "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", "["...
Return a binding site name from a given agent.
[ "Return", "a", "binding", "site", "name", "from", "a", "given", "agent", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/pysb/sites.py#L68-L84
18,846
sorgerlab/indra
indra/assemblers/pysb/sites.py
get_mod_site_name
def get_mod_site_name(mod_condition): """Return site names for a modification.""" 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 '' name = ('%s%s' % (mod_str, mod_pos)) return name
python
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 '' name = ('%s%s' % (mod_str, mod_pos)) return name
[ "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"...
Return site names for a modification.
[ "Return", "site", "names", "for", "a", "modification", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/pysb/sites.py#L87-L96
18,847
sorgerlab/indra
indra/sources/hprd/api.py
process_flat_files
def process_flat_files(id_mappings_file, complexes_file=None, ptm_file=None, ppi_file=None, seq_file=None, motif_window=7): """Get INDRA Statements from HPRD data. Of the arguments, `id_mappings_file` is required, and at least one of `complexes_file`, `ptm_file`, and `ppi_file` must also be given. If `ptm_file` is given, `seq_file` must also be given. Note that many proteins (> 1,600) in the HPRD content are associated with outdated RefSeq IDs that cannot be mapped to Uniprot IDs. For these, the Uniprot ID obtained from the HGNC ID (itself obtained from the Entrez ID) is used. Because the sequence referenced by the Uniprot ID obtained this way may be different from the (outdated) RefSeq sequence included with the HPRD content, it is possible that this will lead to invalid site positions with respect to the Uniprot IDs. To allow these site positions to be mapped during assembly, the Modification statements produced by the HprdProcessor include an additional key in the `annotations` field of their Evidence object. The annotations field is called 'site_motif' and it maps to a dictionary with three elements: 'motif', 'respos', and 'off_by_one'. 'motif' gives the peptide sequence obtained from the RefSeq sequence included with HPRD. 'respos' indicates the position in the peptide sequence containing the residue. Note that these positions are ONE-INDEXED (not zero-indexed). Finally, the 'off-by-one' field contains a boolean value indicating whether the correct position was inferred as being an off-by-one (methionine cleavage) error. If True, it means that the given residue could not be found in the HPRD RefSeq sequence at the given position, but a matching residue was found at position+1, suggesting a sequence numbering based on the methionine-cleaved sequence. The peptide included in the 'site_motif' dictionary is based on this updated position. Parameters ---------- id_mappings_file : str Path to HPRD_ID_MAPPINGS.txt file. complexes_file : Optional[str] Path to PROTEIN_COMPLEXES.txt file. ptm_file : Optional[str] Path to POST_TRANSLATIONAL_MODIFICATIONS.txt file. ppi_file : Optional[str] Path to BINARY_PROTEIN_PROTEIN_INTERACTIONS.txt file. seq_file : Optional[str] Path to PROTEIN_SEQUENCES.txt file. motif_window : int Number of flanking amino acids to include on each side of the PTM target residue in the 'site_motif' annotations field of the Evidence for Modification Statements. Default is 7. Returns ------- HprdProcessor An HprdProcessor object which contains a list of extracted INDRA Statements in its statements attribute. """ id_df = pd.read_csv(id_mappings_file, delimiter='\t', names=_hprd_id_cols, dtype='str') id_df = id_df.set_index('HPRD_ID') if complexes_file is None and ptm_file is None and ppi_file is None: raise ValueError('At least one of complexes_file, ptm_file, or ' 'ppi_file must be given.') if ptm_file and not seq_file: raise ValueError('If ptm_file is given, seq_file must also be given.') # Load complexes into dataframe cplx_df = None if complexes_file: cplx_df = pd.read_csv(complexes_file, delimiter='\t', names=_cplx_cols, dtype='str', na_values=['-', 'None']) # Load ptm data into dataframe ptm_df = None seq_dict = None if ptm_file: ptm_df = pd.read_csv(ptm_file, delimiter='\t', names=_ptm_cols, dtype='str', na_values='-') # Load protein sequences as a dict keyed by RefSeq ID seq_dict = load_fasta_sequences(seq_file, id_index=2) # Load the PPI data into dataframe ppi_df = None if ppi_file: ppi_df = pd.read_csv(ppi_file, delimiter='\t', names=_ppi_cols, dtype='str') # Create the processor return HprdProcessor(id_df, cplx_df, ptm_df, ppi_df, seq_dict, motif_window)
python
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_df = id_df.set_index('HPRD_ID') if complexes_file is None and ptm_file is None and ppi_file is None: raise ValueError('At least one of complexes_file, ptm_file, or ' 'ppi_file must be given.') if ptm_file and not seq_file: raise ValueError('If ptm_file is given, seq_file must also be given.') # Load complexes into dataframe cplx_df = None if complexes_file: cplx_df = pd.read_csv(complexes_file, delimiter='\t', names=_cplx_cols, dtype='str', na_values=['-', 'None']) # Load ptm data into dataframe ptm_df = None seq_dict = None if ptm_file: ptm_df = pd.read_csv(ptm_file, delimiter='\t', names=_ptm_cols, dtype='str', na_values='-') # Load protein sequences as a dict keyed by RefSeq ID seq_dict = load_fasta_sequences(seq_file, id_index=2) # Load the PPI data into dataframe ppi_df = None if ppi_file: ppi_df = pd.read_csv(ppi_file, delimiter='\t', names=_ppi_cols, dtype='str') # Create the processor return HprdProcessor(id_df, cplx_df, ptm_df, ppi_df, seq_dict, motif_window)
[ "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"...
Get INDRA Statements from HPRD data. Of the arguments, `id_mappings_file` is required, and at least one of `complexes_file`, `ptm_file`, and `ppi_file` must also be given. If `ptm_file` is given, `seq_file` must also be given. Note that many proteins (> 1,600) in the HPRD content are associated with outdated RefSeq IDs that cannot be mapped to Uniprot IDs. For these, the Uniprot ID obtained from the HGNC ID (itself obtained from the Entrez ID) is used. Because the sequence referenced by the Uniprot ID obtained this way may be different from the (outdated) RefSeq sequence included with the HPRD content, it is possible that this will lead to invalid site positions with respect to the Uniprot IDs. To allow these site positions to be mapped during assembly, the Modification statements produced by the HprdProcessor include an additional key in the `annotations` field of their Evidence object. The annotations field is called 'site_motif' and it maps to a dictionary with three elements: 'motif', 'respos', and 'off_by_one'. 'motif' gives the peptide sequence obtained from the RefSeq sequence included with HPRD. 'respos' indicates the position in the peptide sequence containing the residue. Note that these positions are ONE-INDEXED (not zero-indexed). Finally, the 'off-by-one' field contains a boolean value indicating whether the correct position was inferred as being an off-by-one (methionine cleavage) error. If True, it means that the given residue could not be found in the HPRD RefSeq sequence at the given position, but a matching residue was found at position+1, suggesting a sequence numbering based on the methionine-cleaved sequence. The peptide included in the 'site_motif' dictionary is based on this updated position. Parameters ---------- id_mappings_file : str Path to HPRD_ID_MAPPINGS.txt file. complexes_file : Optional[str] Path to PROTEIN_COMPLEXES.txt file. ptm_file : Optional[str] Path to POST_TRANSLATIONAL_MODIFICATIONS.txt file. ppi_file : Optional[str] Path to BINARY_PROTEIN_PROTEIN_INTERACTIONS.txt file. seq_file : Optional[str] Path to PROTEIN_SEQUENCES.txt file. motif_window : int Number of flanking amino acids to include on each side of the PTM target residue in the 'site_motif' annotations field of the Evidence for Modification Statements. Default is 7. Returns ------- HprdProcessor An HprdProcessor object which contains a list of extracted INDRA Statements in its statements attribute.
[ "Get", "INDRA", "Statements", "from", "HPRD", "data", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/hprd/api.py#L22-L104
18,848
sorgerlab/indra
indra/assemblers/pysb/preassembler.py
PysbPreassembler._gather_active_forms
def _gather_active_forms(self): """Collect all the active forms of each Agent in the Statements.""" 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 agent_to_add = stmt.agent if stmt.agent.activity: new_agent = fast_deepcopy(stmt.agent) new_agent.activity = None agent_to_add = new_agent base_agent.add_activity_form(agent_to_add, stmt.is_active)
python
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 agent_to_add = stmt.agent if stmt.agent.activity: new_agent = fast_deepcopy(stmt.agent) new_agent.activity = None agent_to_add = new_agent base_agent.add_activity_form(agent_to_add, stmt.is_active)
[ "def", "_gather_active_forms", "(", "self", ")", ":", "for", "stmt", "in", "self", ".", "statements", ":", "if", "isinstance", "(", "stmt", ",", "ActiveForm", ")", ":", "base_agent", "=", "self", ".", "agent_set", ".", "get_create_base_agent", "(", "stmt", ...
Collect all the active forms of each Agent in the Statements.
[ "Collect", "all", "the", "active", "forms", "of", "each", "Agent", "in", "the", "Statements", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/pysb/preassembler.py#L28-L39
18,849
sorgerlab/indra
indra/assemblers/pysb/preassembler.py
PysbPreassembler.replace_activities
def replace_activities(self): """Replace ative flags with Agent states when possible.""" logger.debug('Running PySB Preassembler replace activities') # TODO: handle activity hierarchies new_stmts = [] def has_agent_activity(stmt): """Return True if any agents in the Statement have activity.""" for agent in stmt.agent_list(): if isinstance(agent, Agent) and agent.activity is not None: return True return False # First collect all explicit active forms self._gather_active_forms() # Iterate over all statements for j, stmt in enumerate(self.statements): logger.debug('%d/%d %s' % (j + 1, len(self.statements), stmt)) # If the Statement doesn't have any activities, we can just # keep it and move on if not has_agent_activity(stmt): new_stmts.append(stmt) continue stmt_agents = stmt.agent_list() num_agents = len(stmt_agents) # Make a list with an empty list for each Agent so that later # we can build combinations of Agent forms agent_forms = [[] for a in stmt_agents] for i, agent in enumerate(stmt_agents): # This is the case where there is an activity flag on an # Agent which we will attempt to replace with an explicit # active form if agent is not None and isinstance(agent, Agent) and \ agent.activity is not None: base_agent = self.agent_set.get_create_base_agent(agent) # If it is an "active" state if agent.activity.is_active: active_forms = base_agent.active_forms # If no explicit active forms are known then we use # the generic one if not active_forms: active_forms = [agent] # If it is an "inactive" state else: active_forms = base_agent.inactive_forms # If no explicit inactive forms are known then we use # the generic one if not active_forms: active_forms = [agent] # We now iterate over the active agent forms and create # new agents for af in active_forms: new_agent = fast_deepcopy(agent) self._set_agent_context(af, new_agent) agent_forms[i].append(new_agent) # Otherwise we just copy over the agent as is else: agent_forms[i].append(agent) # Now create all possible combinations of the agents and create new # statements as needed agent_combs = itertools.product(*agent_forms) for agent_comb in agent_combs: new_stmt = fast_deepcopy(stmt) new_stmt.set_agent_list(agent_comb) new_stmts.append(new_stmt) self.statements = new_stmts
python
def replace_activities(self): logger.debug('Running PySB Preassembler replace activities') # TODO: handle activity hierarchies new_stmts = [] def has_agent_activity(stmt): """Return True if any agents in the Statement have activity.""" for agent in stmt.agent_list(): if isinstance(agent, Agent) and agent.activity is not None: return True return False # First collect all explicit active forms self._gather_active_forms() # Iterate over all statements for j, stmt in enumerate(self.statements): logger.debug('%d/%d %s' % (j + 1, len(self.statements), stmt)) # If the Statement doesn't have any activities, we can just # keep it and move on if not has_agent_activity(stmt): new_stmts.append(stmt) continue stmt_agents = stmt.agent_list() num_agents = len(stmt_agents) # Make a list with an empty list for each Agent so that later # we can build combinations of Agent forms agent_forms = [[] for a in stmt_agents] for i, agent in enumerate(stmt_agents): # This is the case where there is an activity flag on an # Agent which we will attempt to replace with an explicit # active form if agent is not None and isinstance(agent, Agent) and \ agent.activity is not None: base_agent = self.agent_set.get_create_base_agent(agent) # If it is an "active" state if agent.activity.is_active: active_forms = base_agent.active_forms # If no explicit active forms are known then we use # the generic one if not active_forms: active_forms = [agent] # If it is an "inactive" state else: active_forms = base_agent.inactive_forms # If no explicit inactive forms are known then we use # the generic one if not active_forms: active_forms = [agent] # We now iterate over the active agent forms and create # new agents for af in active_forms: new_agent = fast_deepcopy(agent) self._set_agent_context(af, new_agent) agent_forms[i].append(new_agent) # Otherwise we just copy over the agent as is else: agent_forms[i].append(agent) # Now create all possible combinations of the agents and create new # statements as needed agent_combs = itertools.product(*agent_forms) for agent_comb in agent_combs: new_stmt = fast_deepcopy(stmt) new_stmt.set_agent_list(agent_comb) new_stmts.append(new_stmt) self.statements = new_stmts
[ "def", "replace_activities", "(", "self", ")", ":", "logger", ".", "debug", "(", "'Running PySB Preassembler replace activities'", ")", "# TODO: handle activity hierarchies", "new_stmts", "=", "[", "]", "def", "has_agent_activity", "(", "stmt", ")", ":", "\"\"\"Return T...
Replace ative flags with Agent states when possible.
[ "Replace", "ative", "flags", "with", "Agent", "states", "when", "possible", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/pysb/preassembler.py#L41-L105
18,850
sorgerlab/indra
indra/assemblers/pysb/preassembler.py
PysbPreassembler.add_reverse_effects
def add_reverse_effects(self): """Add Statements for the reverse effects of some Statements. For instance, if a protein is phosphorylated but never dephosphorylated in the model, we add a generic dephosphorylation here. This step is usually optional in the assembly process. """ # TODO: generalize to other modification sites pos_mod_sites = {} neg_mod_sites = {} syntheses = [] degradations = [] for stmt in self.statements: if isinstance(stmt, Phosphorylation): agent = stmt.sub.name try: pos_mod_sites[agent].append((stmt.residue, stmt.position)) except KeyError: pos_mod_sites[agent] = [(stmt.residue, stmt.position)] elif isinstance(stmt, Dephosphorylation): agent = stmt.sub.name try: neg_mod_sites[agent].append((stmt.residue, stmt.position)) except KeyError: neg_mod_sites[agent] = [(stmt.residue, stmt.position)] elif isinstance(stmt, Influence): if stmt.overall_polarity() == 1: syntheses.append(stmt.obj.name) elif stmt.overall_polarity() == -1: degradations.append(stmt.obj.name) elif isinstance(stmt, IncreaseAmount): syntheses.append(stmt.obj.name) elif isinstance(stmt, DecreaseAmount): degradations.append(stmt.obj.name) new_stmts = [] for agent_name, pos_sites in pos_mod_sites.items(): neg_sites = neg_mod_sites.get(agent_name, []) no_neg_site = set(pos_sites).difference(set(neg_sites)) for residue, position in no_neg_site: st = Dephosphorylation(Agent('phosphatase'), Agent(agent_name), residue, position) new_stmts.append(st) for agent_name in syntheses: if agent_name not in degradations: st = DecreaseAmount(None, Agent(agent_name)) new_stmts.append(st) self.statements += new_stmts
python
def add_reverse_effects(self): # TODO: generalize to other modification sites pos_mod_sites = {} neg_mod_sites = {} syntheses = [] degradations = [] for stmt in self.statements: if isinstance(stmt, Phosphorylation): agent = stmt.sub.name try: pos_mod_sites[agent].append((stmt.residue, stmt.position)) except KeyError: pos_mod_sites[agent] = [(stmt.residue, stmt.position)] elif isinstance(stmt, Dephosphorylation): agent = stmt.sub.name try: neg_mod_sites[agent].append((stmt.residue, stmt.position)) except KeyError: neg_mod_sites[agent] = [(stmt.residue, stmt.position)] elif isinstance(stmt, Influence): if stmt.overall_polarity() == 1: syntheses.append(stmt.obj.name) elif stmt.overall_polarity() == -1: degradations.append(stmt.obj.name) elif isinstance(stmt, IncreaseAmount): syntheses.append(stmt.obj.name) elif isinstance(stmt, DecreaseAmount): degradations.append(stmt.obj.name) new_stmts = [] for agent_name, pos_sites in pos_mod_sites.items(): neg_sites = neg_mod_sites.get(agent_name, []) no_neg_site = set(pos_sites).difference(set(neg_sites)) for residue, position in no_neg_site: st = Dephosphorylation(Agent('phosphatase'), Agent(agent_name), residue, position) new_stmts.append(st) for agent_name in syntheses: if agent_name not in degradations: st = DecreaseAmount(None, Agent(agent_name)) new_stmts.append(st) self.statements += new_stmts
[ "def", "add_reverse_effects", "(", "self", ")", ":", "# TODO: generalize to other modification sites", "pos_mod_sites", "=", "{", "}", "neg_mod_sites", "=", "{", "}", "syntheses", "=", "[", "]", "degradations", "=", "[", "]", "for", "stmt", "in", "self", ".", ...
Add Statements for the reverse effects of some Statements. For instance, if a protein is phosphorylated but never dephosphorylated in the model, we add a generic dephosphorylation here. This step is usually optional in the assembly process.
[ "Add", "Statements", "for", "the", "reverse", "effects", "of", "some", "Statements", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/pysb/preassembler.py#L107-L156
18,851
sorgerlab/indra
indra/preassembler/sitemapper.py
_get_uniprot_id
def _get_uniprot_id(agent): """Return the UniProt ID for an agent, looking up in HGNC if necessary. If the UniProt ID is a list then return the first ID by default. """ up_id = agent.db_refs.get('UP') hgnc_id = agent.db_refs.get('HGNC') if up_id is None: if hgnc_id is None: # If both UniProt and HGNC refs are missing we can't # sequence check and so don't report a failure. return None # Try to get UniProt ID from HGNC up_id = hgnc_client.get_uniprot_id(hgnc_id) # If this fails, again, we can't sequence check if up_id is None: return None # If the UniProt ID is a list then choose the first one. if not isinstance(up_id, basestring) and \ isinstance(up_id[0], basestring): up_id = up_id[0] return up_id
python
def _get_uniprot_id(agent): up_id = agent.db_refs.get('UP') hgnc_id = agent.db_refs.get('HGNC') if up_id is None: if hgnc_id is None: # If both UniProt and HGNC refs are missing we can't # sequence check and so don't report a failure. return None # Try to get UniProt ID from HGNC up_id = hgnc_client.get_uniprot_id(hgnc_id) # If this fails, again, we can't sequence check if up_id is None: return None # If the UniProt ID is a list then choose the first one. if not isinstance(up_id, basestring) and \ isinstance(up_id[0], basestring): up_id = up_id[0] return up_id
[ "def", "_get_uniprot_id", "(", "agent", ")", ":", "up_id", "=", "agent", ".", "db_refs", ".", "get", "(", "'UP'", ")", "hgnc_id", "=", "agent", ".", "db_refs", ".", "get", "(", "'HGNC'", ")", "if", "up_id", "is", "None", ":", "if", "hgnc_id", "is", ...
Return the UniProt ID for an agent, looking up in HGNC if necessary. If the UniProt ID is a list then return the first ID by default.
[ "Return", "the", "UniProt", "ID", "for", "an", "agent", "looking", "up", "in", "HGNC", "if", "necessary", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/preassembler/sitemapper.py#L333-L354
18,852
sorgerlab/indra
indra/preassembler/sitemapper.py
SiteMapper.map_sites
def map_sites(self, stmts): """Check a set of statements for invalid modification sites. Statements are checked against Uniprot reference sequences to determine if residues referred to by post-translational modifications exist at the given positions. If there is nothing amiss with a statement (modifications on any of the agents, modifications made in the statement, etc.), then the statement goes into the list of valid statements. If there is a problem with the statement, the offending modifications are looked up in the site map (:py:attr:`site_map`), and an instance of :py:class:`MappedStatement` is added to the list of mapped statements. Parameters ---------- stmts : list of :py:class:`indra.statement.Statement` The statements to check for site errors. Returns ------- tuple 2-tuple containing (valid_statements, mapped_statements). The first element of the tuple is a list of valid statements (:py:class:`indra.statement.Statement`) that were not found to contain any site errors. The second element of the tuple is a list of mapped statements (:py:class:`MappedStatement`) with information on the incorrect sites and corresponding statements with correctly mapped sites. """ valid_statements = [] mapped_statements = [] for stmt in stmts: mapped_stmt = self.map_stmt_sites(stmt) # If we got a MappedStatement as a return value, we add that to the # list of mapped statements, otherwise, the original Statement is # not invalid so we add it to the other list directly. if mapped_stmt is not None: mapped_statements.append(mapped_stmt) else: valid_statements.append(stmt) return valid_statements, mapped_statements
python
def map_sites(self, stmts): valid_statements = [] mapped_statements = [] for stmt in stmts: mapped_stmt = self.map_stmt_sites(stmt) # If we got a MappedStatement as a return value, we add that to the # list of mapped statements, otherwise, the original Statement is # not invalid so we add it to the other list directly. if mapped_stmt is not None: mapped_statements.append(mapped_stmt) else: valid_statements.append(stmt) return valid_statements, mapped_statements
[ "def", "map_sites", "(", "self", ",", "stmts", ")", ":", "valid_statements", "=", "[", "]", "mapped_statements", "=", "[", "]", "for", "stmt", "in", "stmts", ":", "mapped_stmt", "=", "self", ".", "map_stmt_sites", "(", "stmt", ")", "# If we got a MappedState...
Check a set of statements for invalid modification sites. Statements are checked against Uniprot reference sequences to determine if residues referred to by post-translational modifications exist at the given positions. If there is nothing amiss with a statement (modifications on any of the agents, modifications made in the statement, etc.), then the statement goes into the list of valid statements. If there is a problem with the statement, the offending modifications are looked up in the site map (:py:attr:`site_map`), and an instance of :py:class:`MappedStatement` is added to the list of mapped statements. Parameters ---------- stmts : list of :py:class:`indra.statement.Statement` The statements to check for site errors. Returns ------- tuple 2-tuple containing (valid_statements, mapped_statements). The first element of the tuple is a list of valid statements (:py:class:`indra.statement.Statement`) that were not found to contain any site errors. The second element of the tuple is a list of mapped statements (:py:class:`MappedStatement`) with information on the incorrect sites and corresponding statements with correctly mapped sites.
[ "Check", "a", "set", "of", "statements", "for", "invalid", "modification", "sites", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/preassembler/sitemapper.py#L203-L246
18,853
sorgerlab/indra
indra/preassembler/sitemapper.py
SiteMapper._map_agent_sites
def _map_agent_sites(self, agent): """Check an agent for invalid sites and update if necessary. Parameters ---------- agent : :py:class:`indra.statements.Agent` Agent to check for invalid modification sites. Returns ------- tuple The first element is a list of MappedSite objects, the second element is either the original Agent, if unchanged, or a copy of it. """ # If there are no modifications on this agent, then we can return the # copy of the agent if agent is None or not agent.mods: return [], agent new_agent = deepcopy(agent) mapped_sites = [] # Now iterate over all the modifications and map each one for idx, mod_condition in enumerate(agent.mods): mapped_site = \ self._map_agent_mod(agent, mod_condition) # If we couldn't do the mapping or the mapped site isn't invalid # then we don't need to change the existing ModCondition if not mapped_site or mapped_site.not_invalid(): continue # Otherwise, if there is a mapping, we replace the old ModCondition # with the new one where only the residue and position are updated, # the mod type and the is modified flag are kept. if mapped_site.has_mapping(): mc = ModCondition(mod_condition.mod_type, mapped_site.mapped_res, mapped_site.mapped_pos, mod_condition.is_modified) new_agent.mods[idx] = mc # Finally, whether or not we have a mapping, we keep track of mapped # sites and make them available to the caller mapped_sites.append(mapped_site) return mapped_sites, new_agent
python
def _map_agent_sites(self, agent): # If there are no modifications on this agent, then we can return the # copy of the agent if agent is None or not agent.mods: return [], agent new_agent = deepcopy(agent) mapped_sites = [] # Now iterate over all the modifications and map each one for idx, mod_condition in enumerate(agent.mods): mapped_site = \ self._map_agent_mod(agent, mod_condition) # If we couldn't do the mapping or the mapped site isn't invalid # then we don't need to change the existing ModCondition if not mapped_site or mapped_site.not_invalid(): continue # Otherwise, if there is a mapping, we replace the old ModCondition # with the new one where only the residue and position are updated, # the mod type and the is modified flag are kept. if mapped_site.has_mapping(): mc = ModCondition(mod_condition.mod_type, mapped_site.mapped_res, mapped_site.mapped_pos, mod_condition.is_modified) new_agent.mods[idx] = mc # Finally, whether or not we have a mapping, we keep track of mapped # sites and make them available to the caller mapped_sites.append(mapped_site) return mapped_sites, new_agent
[ "def", "_map_agent_sites", "(", "self", ",", "agent", ")", ":", "# If there are no modifications on this agent, then we can return the", "# copy of the agent", "if", "agent", "is", "None", "or", "not", "agent", ".", "mods", ":", "return", "[", "]", ",", "agent", "ne...
Check an agent for invalid sites and update if necessary. Parameters ---------- agent : :py:class:`indra.statements.Agent` Agent to check for invalid modification sites. Returns ------- tuple The first element is a list of MappedSite objects, the second element is either the original Agent, if unchanged, or a copy of it.
[ "Check", "an", "agent", "for", "invalid", "sites", "and", "update", "if", "necessary", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/preassembler/sitemapper.py#L248-L289
18,854
sorgerlab/indra
indra/preassembler/sitemapper.py
SiteMapper._map_agent_mod
def _map_agent_mod(self, agent, mod_condition): """Map a single modification condition on an agent. Parameters ---------- agent : :py:class:`indra.statements.Agent` Agent to check for invalid modification sites. mod_condition : :py:class:`indra.statements.ModCondition` Modification to check for validity and map. Returns ------- protmapper.MappedSite or None A MappedSite object is returned if a UniProt ID was found for the agent, and if both the position and residue for the modification condition were available. Otherwise None is returned. """ # Get the UniProt ID of the agent, if not found, return up_id = _get_uniprot_id(agent) if not up_id: logger.debug("No uniprot ID for %s" % agent.name) return None # If no site information for this residue, skip if mod_condition.position is None or mod_condition.residue is None: return None # Otherwise, try to map it and return the mapped site mapped_site = \ self.map_to_human_ref(up_id, 'uniprot', mod_condition.residue, mod_condition.position, do_methionine_offset=self.do_methionine_offset, do_orthology_mapping=self.do_orthology_mapping, do_isoform_mapping=self.do_isoform_mapping) return mapped_site
python
def _map_agent_mod(self, agent, mod_condition): # Get the UniProt ID of the agent, if not found, return up_id = _get_uniprot_id(agent) if not up_id: logger.debug("No uniprot ID for %s" % agent.name) return None # If no site information for this residue, skip if mod_condition.position is None or mod_condition.residue is None: return None # Otherwise, try to map it and return the mapped site mapped_site = \ self.map_to_human_ref(up_id, 'uniprot', mod_condition.residue, mod_condition.position, do_methionine_offset=self.do_methionine_offset, do_orthology_mapping=self.do_orthology_mapping, do_isoform_mapping=self.do_isoform_mapping) return mapped_site
[ "def", "_map_agent_mod", "(", "self", ",", "agent", ",", "mod_condition", ")", ":", "# Get the UniProt ID of the agent, if not found, return", "up_id", "=", "_get_uniprot_id", "(", "agent", ")", "if", "not", "up_id", ":", "logger", ".", "debug", "(", "\"No uniprot I...
Map a single modification condition on an agent. Parameters ---------- agent : :py:class:`indra.statements.Agent` Agent to check for invalid modification sites. mod_condition : :py:class:`indra.statements.ModCondition` Modification to check for validity and map. Returns ------- protmapper.MappedSite or None A MappedSite object is returned if a UniProt ID was found for the agent, and if both the position and residue for the modification condition were available. Otherwise None is returned.
[ "Map", "a", "single", "modification", "condition", "on", "an", "agent", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/preassembler/sitemapper.py#L291-L324
18,855
sorgerlab/indra
indra/mechlinker/__init__.py
_get_graph_reductions
def _get_graph_reductions(graph): """Return transitive reductions on a DAG. This is used to reduce the set of activities of a BaseAgent to the most specific one(s) possible. For instance, if a BaseAgent is know to have 'activity', 'catalytic' and 'kinase' activity, then this function will return {'activity': 'kinase', 'catalytic': 'kinase', 'kinase': 'kinase'} as the set of reductions. """ def frontier(g, nd): """Return the nodes after nd in the topological sort that are at the lowest possible level of the topological sort.""" if g.out_degree(nd) == 0: return set([nd]) else: frontiers = set() for n in g.successors(nd): frontiers = frontiers.union(frontier(graph, n)) return frontiers reductions = {} nodes_sort = list(networkx.algorithms.dag.topological_sort(graph)) frontiers = [frontier(graph, n) for n in nodes_sort] # This loop ensures that if a node n2 comes after node n1 in the topological # sort, and their frontiers are identical then n1 can be reduced to n2. # If their frontiers aren't identical, the reduction cannot be done. for i, n1 in enumerate(nodes_sort): for j, n2 in enumerate(nodes_sort): if i > j: continue if frontiers[i] == frontiers[j]: reductions[n1] = n2 return reductions
python
def _get_graph_reductions(graph): def frontier(g, nd): """Return the nodes after nd in the topological sort that are at the lowest possible level of the topological sort.""" if g.out_degree(nd) == 0: return set([nd]) else: frontiers = set() for n in g.successors(nd): frontiers = frontiers.union(frontier(graph, n)) return frontiers reductions = {} nodes_sort = list(networkx.algorithms.dag.topological_sort(graph)) frontiers = [frontier(graph, n) for n in nodes_sort] # This loop ensures that if a node n2 comes after node n1 in the topological # sort, and their frontiers are identical then n1 can be reduced to n2. # If their frontiers aren't identical, the reduction cannot be done. for i, n1 in enumerate(nodes_sort): for j, n2 in enumerate(nodes_sort): if i > j: continue if frontiers[i] == frontiers[j]: reductions[n1] = n2 return reductions
[ "def", "_get_graph_reductions", "(", "graph", ")", ":", "def", "frontier", "(", "g", ",", "nd", ")", ":", "\"\"\"Return the nodes after nd in the topological sort that are at the\n lowest possible level of the topological sort.\"\"\"", "if", "g", ".", "out_degree", "(", ...
Return transitive reductions on a DAG. This is used to reduce the set of activities of a BaseAgent to the most specific one(s) possible. For instance, if a BaseAgent is know to have 'activity', 'catalytic' and 'kinase' activity, then this function will return {'activity': 'kinase', 'catalytic': 'kinase', 'kinase': 'kinase'} as the set of reductions.
[ "Return", "transitive", "reductions", "on", "a", "DAG", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/mechlinker/__init__.py#L764-L795
18,856
sorgerlab/indra
indra/mechlinker/__init__.py
MechLinker.gather_explicit_activities
def gather_explicit_activities(self): """Aggregate all explicit activities and active forms of Agents. This function iterates over self.statements and extracts explicitly stated activity types and active forms for Agents. """ for stmt in self.statements: agents = stmt.agent_list() # Activity types given as ActivityConditions for agent in agents: if agent is not None and agent.activity is not None: agent_base = self._get_base(agent) agent_base.add_activity(agent.activity.activity_type) # Object activities given in RegulateActivity statements if isinstance(stmt, RegulateActivity): if stmt.obj is not None: obj_base = self._get_base(stmt.obj) obj_base.add_activity(stmt.obj_activity) # Activity types given in ActiveForms elif isinstance(stmt, ActiveForm): agent_base = self._get_base(stmt.agent) agent_base.add_activity(stmt.activity) if stmt.is_active: agent_base.add_active_state(stmt.activity, stmt.agent, stmt.evidence) else: agent_base.add_inactive_state(stmt.activity, stmt.agent, stmt.evidence)
python
def gather_explicit_activities(self): for stmt in self.statements: agents = stmt.agent_list() # Activity types given as ActivityConditions for agent in agents: if agent is not None and agent.activity is not None: agent_base = self._get_base(agent) agent_base.add_activity(agent.activity.activity_type) # Object activities given in RegulateActivity statements if isinstance(stmt, RegulateActivity): if stmt.obj is not None: obj_base = self._get_base(stmt.obj) obj_base.add_activity(stmt.obj_activity) # Activity types given in ActiveForms elif isinstance(stmt, ActiveForm): agent_base = self._get_base(stmt.agent) agent_base.add_activity(stmt.activity) if stmt.is_active: agent_base.add_active_state(stmt.activity, stmt.agent, stmt.evidence) else: agent_base.add_inactive_state(stmt.activity, stmt.agent, stmt.evidence)
[ "def", "gather_explicit_activities", "(", "self", ")", ":", "for", "stmt", "in", "self", ".", "statements", ":", "agents", "=", "stmt", ".", "agent_list", "(", ")", "# Activity types given as ActivityConditions", "for", "agent", "in", "agents", ":", "if", "agent...
Aggregate all explicit activities and active forms of Agents. This function iterates over self.statements and extracts explicitly stated activity types and active forms for Agents.
[ "Aggregate", "all", "explicit", "activities", "and", "active", "forms", "of", "Agents", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/mechlinker/__init__.py#L39-L66
18,857
sorgerlab/indra
indra/mechlinker/__init__.py
MechLinker.gather_implicit_activities
def gather_implicit_activities(self): """Aggregate all implicit activities and active forms of Agents. Iterate over self.statements and collect the implied activities and active forms of Agents that appear in the Statements. Note that using this function to collect implied Agent activities can be risky. Assume, for instance, that a Statement from a reading system states that EGF bound to EGFR phosphorylates ERK. This would be interpreted as implicit evidence for the EGFR-bound form of EGF to have 'kinase' activity, which is clearly incorrect. In contrast the alternative pair of this function: gather_explicit_activities collects only explicitly stated activities. """ for stmt in self.statements: if isinstance(stmt, Phosphorylation) or \ isinstance(stmt, Transphosphorylation) or \ isinstance(stmt, Autophosphorylation): if stmt.enz is not None: enz_base = self._get_base(stmt.enz) enz_base.add_activity('kinase') enz_base.add_active_state('kinase', stmt.enz.mods) elif isinstance(stmt, Dephosphorylation): if stmt.enz is not None: enz_base = self._get_base(stmt.enz) enz_base.add_activity('phosphatase') enz_base.add_active_state('phosphatase', stmt.enz.mods) elif isinstance(stmt, Modification): if stmt.enz is not None: enz_base = self._get_base(stmt.enz) enz_base.add_activity('catalytic') enz_base.add_active_state('catalytic', stmt.enz.mods) elif isinstance(stmt, SelfModification): if stmt.enz is not None: enz_base = self._get_base(stmt.enz) enz_base.add_activity('catalytic') enz_base.add_active_state('catalytic', stmt.enz.mods) elif isinstance(stmt, Gef): if stmt.gef is not None: gef_base = self._get_base(stmt.gef) gef_base.add_activity('gef') if stmt.gef.activity is not None: act = stmt.gef.activity.activity_type else: act = 'activity' gef_base.add_active_state(act, stmt.gef.mods) elif isinstance(stmt, Gap): if stmt.gap is not None: gap_base = self._get_base(stmt.gap) gap_base.add_activity('gap') if stmt.gap.activity is not None: act = stmt.gap.activity.activity_type else: act = 'activity' gap_base.add_active_state('act', stmt.gap.mods) elif isinstance(stmt, RegulateActivity): if stmt.subj is not None: subj_base = self._get_base(stmt.subj) subj_base.add_activity(stmt.j)
python
def gather_implicit_activities(self): for stmt in self.statements: if isinstance(stmt, Phosphorylation) or \ isinstance(stmt, Transphosphorylation) or \ isinstance(stmt, Autophosphorylation): if stmt.enz is not None: enz_base = self._get_base(stmt.enz) enz_base.add_activity('kinase') enz_base.add_active_state('kinase', stmt.enz.mods) elif isinstance(stmt, Dephosphorylation): if stmt.enz is not None: enz_base = self._get_base(stmt.enz) enz_base.add_activity('phosphatase') enz_base.add_active_state('phosphatase', stmt.enz.mods) elif isinstance(stmt, Modification): if stmt.enz is not None: enz_base = self._get_base(stmt.enz) enz_base.add_activity('catalytic') enz_base.add_active_state('catalytic', stmt.enz.mods) elif isinstance(stmt, SelfModification): if stmt.enz is not None: enz_base = self._get_base(stmt.enz) enz_base.add_activity('catalytic') enz_base.add_active_state('catalytic', stmt.enz.mods) elif isinstance(stmt, Gef): if stmt.gef is not None: gef_base = self._get_base(stmt.gef) gef_base.add_activity('gef') if stmt.gef.activity is not None: act = stmt.gef.activity.activity_type else: act = 'activity' gef_base.add_active_state(act, stmt.gef.mods) elif isinstance(stmt, Gap): if stmt.gap is not None: gap_base = self._get_base(stmt.gap) gap_base.add_activity('gap') if stmt.gap.activity is not None: act = stmt.gap.activity.activity_type else: act = 'activity' gap_base.add_active_state('act', stmt.gap.mods) elif isinstance(stmt, RegulateActivity): if stmt.subj is not None: subj_base = self._get_base(stmt.subj) subj_base.add_activity(stmt.j)
[ "def", "gather_implicit_activities", "(", "self", ")", ":", "for", "stmt", "in", "self", ".", "statements", ":", "if", "isinstance", "(", "stmt", ",", "Phosphorylation", ")", "or", "isinstance", "(", "stmt", ",", "Transphosphorylation", ")", "or", "isinstance"...
Aggregate all implicit activities and active forms of Agents. Iterate over self.statements and collect the implied activities and active forms of Agents that appear in the Statements. Note that using this function to collect implied Agent activities can be risky. Assume, for instance, that a Statement from a reading system states that EGF bound to EGFR phosphorylates ERK. This would be interpreted as implicit evidence for the EGFR-bound form of EGF to have 'kinase' activity, which is clearly incorrect. In contrast the alternative pair of this function: gather_explicit_activities collects only explicitly stated activities.
[ "Aggregate", "all", "implicit", "activities", "and", "active", "forms", "of", "Agents", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/mechlinker/__init__.py#L68-L127
18,858
sorgerlab/indra
indra/mechlinker/__init__.py
MechLinker.require_active_forms
def require_active_forms(self): """Rewrites Statements with Agents' active forms in active positions. As an example, the enzyme in a Modification Statement can be expected to be in an active state. Similarly, subjects of RegulateAmount and RegulateActivity Statements can be expected to be in an active form. This function takes the collected active states of Agents in their corresponding BaseAgents and then rewrites other Statements to apply the active Agent states to them. Returns ------- new_stmts : list[indra.statements.Statement] A list of Statements which includes the newly rewritten Statements. This list is also set as the internal Statement list of the MechLinker. """ logger.info('Setting required active forms on %d statements...' % len(self.statements)) new_stmts = [] for stmt in self.statements: if isinstance(stmt, Modification): if stmt.enz is None: new_stmts.append(stmt) continue enz_base = self._get_base(stmt.enz) active_forms = enz_base.get_active_forms() if not active_forms: new_stmts.append(stmt) else: for af in active_forms: new_stmt = fast_deepcopy(stmt) new_stmt.uuid = str(uuid.uuid4()) evs = af.apply_to(new_stmt.enz) new_stmt.partial_evidence = evs new_stmts.append(new_stmt) elif isinstance(stmt, RegulateAmount) or \ isinstance(stmt, RegulateActivity): if stmt.subj is None: new_stmts.append(stmt) continue subj_base = self._get_base(stmt.subj) active_forms = subj_base.get_active_forms() if not active_forms: new_stmts.append(stmt) else: for af in active_forms: new_stmt = fast_deepcopy(stmt) new_stmt.uuid = str(uuid.uuid4()) evs = af.apply_to(new_stmt.subj) new_stmt.partial_evidence = evs new_stmts.append(new_stmt) else: new_stmts.append(stmt) self.statements = new_stmts return new_stmts
python
def require_active_forms(self): logger.info('Setting required active forms on %d statements...' % len(self.statements)) new_stmts = [] for stmt in self.statements: if isinstance(stmt, Modification): if stmt.enz is None: new_stmts.append(stmt) continue enz_base = self._get_base(stmt.enz) active_forms = enz_base.get_active_forms() if not active_forms: new_stmts.append(stmt) else: for af in active_forms: new_stmt = fast_deepcopy(stmt) new_stmt.uuid = str(uuid.uuid4()) evs = af.apply_to(new_stmt.enz) new_stmt.partial_evidence = evs new_stmts.append(new_stmt) elif isinstance(stmt, RegulateAmount) or \ isinstance(stmt, RegulateActivity): if stmt.subj is None: new_stmts.append(stmt) continue subj_base = self._get_base(stmt.subj) active_forms = subj_base.get_active_forms() if not active_forms: new_stmts.append(stmt) else: for af in active_forms: new_stmt = fast_deepcopy(stmt) new_stmt.uuid = str(uuid.uuid4()) evs = af.apply_to(new_stmt.subj) new_stmt.partial_evidence = evs new_stmts.append(new_stmt) else: new_stmts.append(stmt) self.statements = new_stmts return new_stmts
[ "def", "require_active_forms", "(", "self", ")", ":", "logger", ".", "info", "(", "'Setting required active forms on %d statements...'", "%", "len", "(", "self", ".", "statements", ")", ")", "new_stmts", "=", "[", "]", "for", "stmt", "in", "self", ".", "statem...
Rewrites Statements with Agents' active forms in active positions. As an example, the enzyme in a Modification Statement can be expected to be in an active state. Similarly, subjects of RegulateAmount and RegulateActivity Statements can be expected to be in an active form. This function takes the collected active states of Agents in their corresponding BaseAgents and then rewrites other Statements to apply the active Agent states to them. Returns ------- new_stmts : list[indra.statements.Statement] A list of Statements which includes the newly rewritten Statements. This list is also set as the internal Statement list of the MechLinker.
[ "Rewrites", "Statements", "with", "Agents", "active", "forms", "in", "active", "positions", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/mechlinker/__init__.py#L166-L221
18,859
sorgerlab/indra
indra/mechlinker/__init__.py
MechLinker.reduce_activities
def reduce_activities(self): """Rewrite the activity types referenced in Statements for consistency. Activity types are reduced to the most specific form whenever possible. For instance, if 'kinase' is the only specific activity type known for the BaseAgent of BRAF, its generic 'activity' forms are rewritten to 'kinase'. """ for stmt in self.statements: agents = stmt.agent_list() for agent in agents: if agent is not None and agent.activity is not None: agent_base = self._get_base(agent) act_red = agent_base.get_activity_reduction( agent.activity.activity_type) if act_red is not None: agent.activity.activity_type = act_red if isinstance(stmt, RegulateActivity): if stmt.obj is not None: obj_base = self._get_base(stmt.obj) act_red = \ obj_base.get_activity_reduction(stmt.obj_activity) if act_red is not None: stmt.obj_activity = act_red elif isinstance(stmt, ActiveForm): agent_base = self._get_base(stmt.agent) act_red = agent_base.get_activity_reduction(stmt.activity) if act_red is not None: stmt.activity = act_red
python
def reduce_activities(self): for stmt in self.statements: agents = stmt.agent_list() for agent in agents: if agent is not None and agent.activity is not None: agent_base = self._get_base(agent) act_red = agent_base.get_activity_reduction( agent.activity.activity_type) if act_red is not None: agent.activity.activity_type = act_red if isinstance(stmt, RegulateActivity): if stmt.obj is not None: obj_base = self._get_base(stmt.obj) act_red = \ obj_base.get_activity_reduction(stmt.obj_activity) if act_red is not None: stmt.obj_activity = act_red elif isinstance(stmt, ActiveForm): agent_base = self._get_base(stmt.agent) act_red = agent_base.get_activity_reduction(stmt.activity) if act_red is not None: stmt.activity = act_red
[ "def", "reduce_activities", "(", "self", ")", ":", "for", "stmt", "in", "self", ".", "statements", ":", "agents", "=", "stmt", ".", "agent_list", "(", ")", "for", "agent", "in", "agents", ":", "if", "agent", "is", "not", "None", "and", "agent", ".", ...
Rewrite the activity types referenced in Statements for consistency. Activity types are reduced to the most specific form whenever possible. For instance, if 'kinase' is the only specific activity type known for the BaseAgent of BRAF, its generic 'activity' forms are rewritten to 'kinase'.
[ "Rewrite", "the", "activity", "types", "referenced", "in", "Statements", "for", "consistency", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/mechlinker/__init__.py#L223-L251
18,860
sorgerlab/indra
indra/mechlinker/__init__.py
MechLinker.infer_complexes
def infer_complexes(stmts): """Return inferred Complex from Statements implying physical interaction. Parameters ---------- stmts : list[indra.statements.Statement] A list of Statements to infer Complexes from. Returns ------- linked_stmts : list[indra.mechlinker.LinkedStatement] A list of LinkedStatements representing the inferred Statements. """ interact_stmts = _get_statements_by_type(stmts, Modification) linked_stmts = [] for mstmt in interact_stmts: if mstmt.enz is None: continue st = Complex([mstmt.enz, mstmt.sub], evidence=mstmt.evidence) linked_stmts.append(st) return linked_stmts
python
def infer_complexes(stmts): interact_stmts = _get_statements_by_type(stmts, Modification) linked_stmts = [] for mstmt in interact_stmts: if mstmt.enz is None: continue st = Complex([mstmt.enz, mstmt.sub], evidence=mstmt.evidence) linked_stmts.append(st) return linked_stmts
[ "def", "infer_complexes", "(", "stmts", ")", ":", "interact_stmts", "=", "_get_statements_by_type", "(", "stmts", ",", "Modification", ")", "linked_stmts", "=", "[", "]", "for", "mstmt", "in", "interact_stmts", ":", "if", "mstmt", ".", "enz", "is", "None", "...
Return inferred Complex from Statements implying physical interaction. Parameters ---------- stmts : list[indra.statements.Statement] A list of Statements to infer Complexes from. Returns ------- linked_stmts : list[indra.mechlinker.LinkedStatement] A list of LinkedStatements representing the inferred Statements.
[ "Return", "inferred", "Complex", "from", "Statements", "implying", "physical", "interaction", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/mechlinker/__init__.py#L254-L274
18,861
sorgerlab/indra
indra/mechlinker/__init__.py
MechLinker.infer_activations
def infer_activations(stmts): """Return inferred RegulateActivity from Modification + ActiveForm. This function looks for combinations of Modification and ActiveForm Statements and infers Activation/Inhibition Statements from them. For example, if we know that A phosphorylates B, and the phosphorylated form of B is active, then we can infer that A activates B. This can also be viewed as having "explained" a given Activation/Inhibition Statement with a combination of more mechanistic Modification + ActiveForm Statements. Parameters ---------- stmts : list[indra.statements.Statement] A list of Statements to infer RegulateActivity from. Returns ------- linked_stmts : list[indra.mechlinker.LinkedStatement] A list of LinkedStatements representing the inferred Statements. """ linked_stmts = [] af_stmts = _get_statements_by_type(stmts, ActiveForm) mod_stmts = _get_statements_by_type(stmts, Modification) for af_stmt, mod_stmt in itertools.product(*(af_stmts, mod_stmts)): # There has to be an enzyme and the substrate and the # agent of the active form have to match if mod_stmt.enz is None or \ (not af_stmt.agent.entity_matches(mod_stmt.sub)): continue # We now check the modifications to make sure they are consistent if not af_stmt.agent.mods: continue found = False for mc in af_stmt.agent.mods: if mc.mod_type == modclass_to_modtype[mod_stmt.__class__] and \ mc.residue == mod_stmt.residue and \ mc.position == mod_stmt.position: found = True if not found: continue # Collect evidence ev = mod_stmt.evidence # Finally, check the polarity of the ActiveForm if af_stmt.is_active: st = Activation(mod_stmt.enz, mod_stmt.sub, af_stmt.activity, evidence=ev) else: st = Inhibition(mod_stmt.enz, mod_stmt.sub, af_stmt.activity, evidence=ev) linked_stmts.append(LinkedStatement([af_stmt, mod_stmt], st)) return linked_stmts
python
def infer_activations(stmts): linked_stmts = [] af_stmts = _get_statements_by_type(stmts, ActiveForm) mod_stmts = _get_statements_by_type(stmts, Modification) for af_stmt, mod_stmt in itertools.product(*(af_stmts, mod_stmts)): # There has to be an enzyme and the substrate and the # agent of the active form have to match if mod_stmt.enz is None or \ (not af_stmt.agent.entity_matches(mod_stmt.sub)): continue # We now check the modifications to make sure they are consistent if not af_stmt.agent.mods: continue found = False for mc in af_stmt.agent.mods: if mc.mod_type == modclass_to_modtype[mod_stmt.__class__] and \ mc.residue == mod_stmt.residue and \ mc.position == mod_stmt.position: found = True if not found: continue # Collect evidence ev = mod_stmt.evidence # Finally, check the polarity of the ActiveForm if af_stmt.is_active: st = Activation(mod_stmt.enz, mod_stmt.sub, af_stmt.activity, evidence=ev) else: st = Inhibition(mod_stmt.enz, mod_stmt.sub, af_stmt.activity, evidence=ev) linked_stmts.append(LinkedStatement([af_stmt, mod_stmt], st)) return linked_stmts
[ "def", "infer_activations", "(", "stmts", ")", ":", "linked_stmts", "=", "[", "]", "af_stmts", "=", "_get_statements_by_type", "(", "stmts", ",", "ActiveForm", ")", "mod_stmts", "=", "_get_statements_by_type", "(", "stmts", ",", "Modification", ")", "for", "af_s...
Return inferred RegulateActivity from Modification + ActiveForm. This function looks for combinations of Modification and ActiveForm Statements and infers Activation/Inhibition Statements from them. For example, if we know that A phosphorylates B, and the phosphorylated form of B is active, then we can infer that A activates B. This can also be viewed as having "explained" a given Activation/Inhibition Statement with a combination of more mechanistic Modification + ActiveForm Statements. Parameters ---------- stmts : list[indra.statements.Statement] A list of Statements to infer RegulateActivity from. Returns ------- linked_stmts : list[indra.mechlinker.LinkedStatement] A list of LinkedStatements representing the inferred Statements.
[ "Return", "inferred", "RegulateActivity", "from", "Modification", "+", "ActiveForm", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/mechlinker/__init__.py#L277-L328
18,862
sorgerlab/indra
indra/mechlinker/__init__.py
MechLinker.infer_active_forms
def infer_active_forms(stmts): """Return inferred ActiveForm from RegulateActivity + Modification. This function looks for combinations of Activation/Inhibition Statements and Modification Statements, and infers an ActiveForm from them. For example, if we know that A activates B and A phosphorylates B, then we can infer that the phosphorylated form of B is active. Parameters ---------- stmts : list[indra.statements.Statement] A list of Statements to infer ActiveForms from. Returns ------- linked_stmts : list[indra.mechlinker.LinkedStatement] A list of LinkedStatements representing the inferred Statements. """ linked_stmts = [] for act_stmt in _get_statements_by_type(stmts, RegulateActivity): # TODO: revise the conditions here if not (act_stmt.subj.activity is not None and act_stmt.subj.activity.activity_type == 'kinase' and act_stmt.subj.activity.is_active): continue matching = [] ev = act_stmt.evidence for mod_stmt in _get_statements_by_type(stmts, Modification): if mod_stmt.enz is not None: if mod_stmt.enz.entity_matches(act_stmt.subj) and \ mod_stmt.sub.entity_matches(act_stmt.obj): matching.append(mod_stmt) ev.extend(mod_stmt.evidence) if not matching: continue mods = [] for mod_stmt in matching: mod_type_name = mod_stmt.__class__.__name__.lower() if isinstance(mod_stmt, AddModification): is_modified = True else: is_modified = False mod_type_name = mod_type_name[2:] mc = ModCondition(mod_type_name, mod_stmt.residue, mod_stmt.position, is_modified) mods.append(mc) source_stmts = [act_stmt] + [m for m in matching] st = ActiveForm(Agent(act_stmt.obj.name, mods=mods, db_refs=act_stmt.obj.db_refs), act_stmt.obj_activity, act_stmt.is_activation, evidence=ev) linked_stmts.append(LinkedStatement(source_stmts, st)) logger.info('inferred: %s' % st) return linked_stmts
python
def infer_active_forms(stmts): linked_stmts = [] for act_stmt in _get_statements_by_type(stmts, RegulateActivity): # TODO: revise the conditions here if not (act_stmt.subj.activity is not None and act_stmt.subj.activity.activity_type == 'kinase' and act_stmt.subj.activity.is_active): continue matching = [] ev = act_stmt.evidence for mod_stmt in _get_statements_by_type(stmts, Modification): if mod_stmt.enz is not None: if mod_stmt.enz.entity_matches(act_stmt.subj) and \ mod_stmt.sub.entity_matches(act_stmt.obj): matching.append(mod_stmt) ev.extend(mod_stmt.evidence) if not matching: continue mods = [] for mod_stmt in matching: mod_type_name = mod_stmt.__class__.__name__.lower() if isinstance(mod_stmt, AddModification): is_modified = True else: is_modified = False mod_type_name = mod_type_name[2:] mc = ModCondition(mod_type_name, mod_stmt.residue, mod_stmt.position, is_modified) mods.append(mc) source_stmts = [act_stmt] + [m for m in matching] st = ActiveForm(Agent(act_stmt.obj.name, mods=mods, db_refs=act_stmt.obj.db_refs), act_stmt.obj_activity, act_stmt.is_activation, evidence=ev) linked_stmts.append(LinkedStatement(source_stmts, st)) logger.info('inferred: %s' % st) return linked_stmts
[ "def", "infer_active_forms", "(", "stmts", ")", ":", "linked_stmts", "=", "[", "]", "for", "act_stmt", "in", "_get_statements_by_type", "(", "stmts", ",", "RegulateActivity", ")", ":", "# TODO: revise the conditions here", "if", "not", "(", "act_stmt", ".", "subj"...
Return inferred ActiveForm from RegulateActivity + Modification. This function looks for combinations of Activation/Inhibition Statements and Modification Statements, and infers an ActiveForm from them. For example, if we know that A activates B and A phosphorylates B, then we can infer that the phosphorylated form of B is active. Parameters ---------- stmts : list[indra.statements.Statement] A list of Statements to infer ActiveForms from. Returns ------- linked_stmts : list[indra.mechlinker.LinkedStatement] A list of LinkedStatements representing the inferred Statements.
[ "Return", "inferred", "ActiveForm", "from", "RegulateActivity", "+", "Modification", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/mechlinker/__init__.py#L331-L385
18,863
sorgerlab/indra
indra/mechlinker/__init__.py
MechLinker.infer_modifications
def infer_modifications(stmts): """Return inferred Modification from RegulateActivity + ActiveForm. This function looks for combinations of Activation/Inhibition Statements and ActiveForm Statements that imply a Modification Statement. For example, if we know that A activates B, and phosphorylated B is active, then we can infer that A leads to the phosphorylation of B. An additional requirement when making this assumption is that the activity of B should only be dependent on the modified state and not other context - otherwise the inferred Modification is not necessarily warranted. Parameters ---------- stmts : list[indra.statements.Statement] A list of Statements to infer Modifications from. Returns ------- linked_stmts : list[indra.mechlinker.LinkedStatement] A list of LinkedStatements representing the inferred Statements. """ linked_stmts = [] for act_stmt in _get_statements_by_type(stmts, RegulateActivity): for af_stmt in _get_statements_by_type(stmts, ActiveForm): if not af_stmt.agent.entity_matches(act_stmt.obj): continue mods = af_stmt.agent.mods # Make sure the ActiveForm only involves modified sites if af_stmt.agent.mutations or \ af_stmt.agent.bound_conditions or \ af_stmt.agent.location: continue if not af_stmt.agent.mods: continue for mod in af_stmt.agent.mods: evs = act_stmt.evidence + af_stmt.evidence for ev in evs: ev.epistemics['direct'] = False if mod.is_modified: mod_type_name = mod.mod_type else: mod_type_name = modtype_to_inverse[mod.mod_type] mod_class = modtype_to_modclass[mod_type_name] if not mod_class: continue st = mod_class(act_stmt.subj, act_stmt.obj, mod.residue, mod.position, evidence=evs) ls = LinkedStatement([act_stmt, af_stmt], st) linked_stmts.append(ls) logger.info('inferred: %s' % st) return linked_stmts
python
def infer_modifications(stmts): linked_stmts = [] for act_stmt in _get_statements_by_type(stmts, RegulateActivity): for af_stmt in _get_statements_by_type(stmts, ActiveForm): if not af_stmt.agent.entity_matches(act_stmt.obj): continue mods = af_stmt.agent.mods # Make sure the ActiveForm only involves modified sites if af_stmt.agent.mutations or \ af_stmt.agent.bound_conditions or \ af_stmt.agent.location: continue if not af_stmt.agent.mods: continue for mod in af_stmt.agent.mods: evs = act_stmt.evidence + af_stmt.evidence for ev in evs: ev.epistemics['direct'] = False if mod.is_modified: mod_type_name = mod.mod_type else: mod_type_name = modtype_to_inverse[mod.mod_type] mod_class = modtype_to_modclass[mod_type_name] if not mod_class: continue st = mod_class(act_stmt.subj, act_stmt.obj, mod.residue, mod.position, evidence=evs) ls = LinkedStatement([act_stmt, af_stmt], st) linked_stmts.append(ls) logger.info('inferred: %s' % st) return linked_stmts
[ "def", "infer_modifications", "(", "stmts", ")", ":", "linked_stmts", "=", "[", "]", "for", "act_stmt", "in", "_get_statements_by_type", "(", "stmts", ",", "RegulateActivity", ")", ":", "for", "af_stmt", "in", "_get_statements_by_type", "(", "stmts", ",", "Activ...
Return inferred Modification from RegulateActivity + ActiveForm. This function looks for combinations of Activation/Inhibition Statements and ActiveForm Statements that imply a Modification Statement. For example, if we know that A activates B, and phosphorylated B is active, then we can infer that A leads to the phosphorylation of B. An additional requirement when making this assumption is that the activity of B should only be dependent on the modified state and not other context - otherwise the inferred Modification is not necessarily warranted. Parameters ---------- stmts : list[indra.statements.Statement] A list of Statements to infer Modifications from. Returns ------- linked_stmts : list[indra.mechlinker.LinkedStatement] A list of LinkedStatements representing the inferred Statements.
[ "Return", "inferred", "Modification", "from", "RegulateActivity", "+", "ActiveForm", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/mechlinker/__init__.py#L388-L441
18,864
sorgerlab/indra
indra/mechlinker/__init__.py
MechLinker.replace_complexes
def replace_complexes(self, linked_stmts=None): """Remove Complex Statements that can be inferred out. This function iterates over self.statements and looks for Complex Statements that either match or are refined by inferred Complex Statements that were linked (provided as the linked_stmts argument). It removes Complex Statements from self.statements that can be explained by the linked statements. Parameters ---------- linked_stmts : Optional[list[indra.mechlinker.LinkedStatement]] A list of linked statements, optionally passed from outside. If None is passed, the MechLinker runs self.infer_complexes to infer Complexes and obtain a list of LinkedStatements that are then used for removing existing Complexes in self.statements. """ if linked_stmts is None: linked_stmts = self.infer_complexes(self.statements) new_stmts = [] for stmt in self.statements: if not isinstance(stmt, Complex): new_stmts.append(stmt) continue found = False for linked_stmt in linked_stmts: if linked_stmt.refinement_of(stmt, hierarchies): found = True if not found: new_stmts.append(stmt) else: logger.info('Removing complex: %s' % stmt) self.statements = new_stmts
python
def replace_complexes(self, linked_stmts=None): if linked_stmts is None: linked_stmts = self.infer_complexes(self.statements) new_stmts = [] for stmt in self.statements: if not isinstance(stmt, Complex): new_stmts.append(stmt) continue found = False for linked_stmt in linked_stmts: if linked_stmt.refinement_of(stmt, hierarchies): found = True if not found: new_stmts.append(stmt) else: logger.info('Removing complex: %s' % stmt) self.statements = new_stmts
[ "def", "replace_complexes", "(", "self", ",", "linked_stmts", "=", "None", ")", ":", "if", "linked_stmts", "is", "None", ":", "linked_stmts", "=", "self", ".", "infer_complexes", "(", "self", ".", "statements", ")", "new_stmts", "=", "[", "]", "for", "stmt...
Remove Complex Statements that can be inferred out. This function iterates over self.statements and looks for Complex Statements that either match or are refined by inferred Complex Statements that were linked (provided as the linked_stmts argument). It removes Complex Statements from self.statements that can be explained by the linked statements. Parameters ---------- linked_stmts : Optional[list[indra.mechlinker.LinkedStatement]] A list of linked statements, optionally passed from outside. If None is passed, the MechLinker runs self.infer_complexes to infer Complexes and obtain a list of LinkedStatements that are then used for removing existing Complexes in self.statements.
[ "Remove", "Complex", "Statements", "that", "can", "be", "inferred", "out", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/mechlinker/__init__.py#L443-L475
18,865
sorgerlab/indra
indra/mechlinker/__init__.py
MechLinker.replace_activations
def replace_activations(self, linked_stmts=None): """Remove RegulateActivity Statements that can be inferred out. This function iterates over self.statements and looks for RegulateActivity Statements that either match or are refined by inferred RegulateActivity Statements that were linked (provided as the linked_stmts argument). It removes RegulateActivity Statements from self.statements that can be explained by the linked statements. Parameters ---------- linked_stmts : Optional[list[indra.mechlinker.LinkedStatement]] A list of linked statements, optionally passed from outside. If None is passed, the MechLinker runs self.infer_activations to infer RegulateActivities and obtain a list of LinkedStatements that are then used for removing existing Complexes in self.statements. """ if linked_stmts is None: linked_stmts = self.infer_activations(self.statements) new_stmts = [] for stmt in self.statements: if not isinstance(stmt, RegulateActivity): new_stmts.append(stmt) continue found = False for linked_stmt in linked_stmts: inferred_stmt = linked_stmt.inferred_stmt if stmt.is_activation == inferred_stmt.is_activation and \ stmt.subj.entity_matches(inferred_stmt.subj) and \ stmt.obj.entity_matches(inferred_stmt.obj): found = True if not found: new_stmts.append(stmt) else: logger.info('Removing regulate activity: %s' % stmt) self.statements = new_stmts
python
def replace_activations(self, linked_stmts=None): if linked_stmts is None: linked_stmts = self.infer_activations(self.statements) new_stmts = [] for stmt in self.statements: if not isinstance(stmt, RegulateActivity): new_stmts.append(stmt) continue found = False for linked_stmt in linked_stmts: inferred_stmt = linked_stmt.inferred_stmt if stmt.is_activation == inferred_stmt.is_activation and \ stmt.subj.entity_matches(inferred_stmt.subj) and \ stmt.obj.entity_matches(inferred_stmt.obj): found = True if not found: new_stmts.append(stmt) else: logger.info('Removing regulate activity: %s' % stmt) self.statements = new_stmts
[ "def", "replace_activations", "(", "self", ",", "linked_stmts", "=", "None", ")", ":", "if", "linked_stmts", "is", "None", ":", "linked_stmts", "=", "self", ".", "infer_activations", "(", "self", ".", "statements", ")", "new_stmts", "=", "[", "]", "for", "...
Remove RegulateActivity Statements that can be inferred out. This function iterates over self.statements and looks for RegulateActivity Statements that either match or are refined by inferred RegulateActivity Statements that were linked (provided as the linked_stmts argument). It removes RegulateActivity Statements from self.statements that can be explained by the linked statements. Parameters ---------- linked_stmts : Optional[list[indra.mechlinker.LinkedStatement]] A list of linked statements, optionally passed from outside. If None is passed, the MechLinker runs self.infer_activations to infer RegulateActivities and obtain a list of LinkedStatements that are then used for removing existing Complexes in self.statements.
[ "Remove", "RegulateActivity", "Statements", "that", "can", "be", "inferred", "out", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/mechlinker/__init__.py#L477-L514
18,866
sorgerlab/indra
indra/mechlinker/__init__.py
BaseAgentSet.get_create_base_agent
def get_create_base_agent(self, agent): """Return BaseAgent from an Agent, creating it if needed. Parameters ---------- agent : indra.statements.Agent Returns ------- base_agent : indra.mechlinker.BaseAgent """ try: base_agent = self.agents[agent.name] except KeyError: base_agent = BaseAgent(agent.name) self.agents[agent.name] = base_agent return base_agent
python
def get_create_base_agent(self, agent): try: base_agent = self.agents[agent.name] except KeyError: base_agent = BaseAgent(agent.name) self.agents[agent.name] = base_agent return base_agent
[ "def", "get_create_base_agent", "(", "self", ",", "agent", ")", ":", "try", ":", "base_agent", "=", "self", ".", "agents", "[", "agent", ".", "name", "]", "except", "KeyError", ":", "base_agent", "=", "BaseAgent", "(", "agent", ".", "name", ")", "self", ...
Return BaseAgent from an Agent, creating it if needed. Parameters ---------- agent : indra.statements.Agent Returns ------- base_agent : indra.mechlinker.BaseAgent
[ "Return", "BaseAgent", "from", "an", "Agent", "creating", "it", "if", "needed", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/mechlinker/__init__.py#L540-L557
18,867
sorgerlab/indra
indra/mechlinker/__init__.py
AgentState.apply_to
def apply_to(self, agent): """Apply this object's state to an Agent. Parameters ---------- agent : indra.statements.Agent The agent to which the state should be applied """ agent.bound_conditions = self.bound_conditions agent.mods = self.mods agent.mutations = self.mutations agent.location = self.location return self.evidence
python
def apply_to(self, agent): agent.bound_conditions = self.bound_conditions agent.mods = self.mods agent.mutations = self.mutations agent.location = self.location return self.evidence
[ "def", "apply_to", "(", "self", ",", "agent", ")", ":", "agent", ".", "bound_conditions", "=", "self", ".", "bound_conditions", "agent", ".", "mods", "=", "self", ".", "mods", "agent", ".", "mutations", "=", "self", ".", "mutations", "agent", ".", "locat...
Apply this object's state to an Agent. Parameters ---------- agent : indra.statements.Agent The agent to which the state should be applied
[ "Apply", "this", "object", "s", "state", "to", "an", "Agent", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/mechlinker/__init__.py#L713-L725
18,868
sorgerlab/indra
indra/tools/live_curation.py
submit_curation
def submit_curation(): """Submit curations for a given corpus. The submitted curations are handled to update the probability model but there is no return value here. The update_belief function can be called separately to calculate update belief scores. Parameters ---------- corpus_id : str The ID of the corpus for which the curation is submitted. curations : dict A set of curations where each key is a Statement UUID in the given corpus and each key is 0 or 1 with 0 corresponding to incorrect and 1 corresponding to correct. """ if request.json is None: abort(Response('Missing application/json header.', 415)) # Get input parameters corpus_id = request.json.get('corpus_id') curations = request.json.get('curations', {}) try: curator.submit_curation(corpus_id, curations) except InvalidCorpusError: abort(Response('The corpus_id "%s" is unknown.' % corpus_id, 400)) return return jsonify({})
python
def submit_curation(): if request.json is None: abort(Response('Missing application/json header.', 415)) # Get input parameters corpus_id = request.json.get('corpus_id') curations = request.json.get('curations', {}) try: curator.submit_curation(corpus_id, curations) except InvalidCorpusError: abort(Response('The corpus_id "%s" is unknown.' % corpus_id, 400)) return return jsonify({})
[ "def", "submit_curation", "(", ")", ":", "if", "request", ".", "json", "is", "None", ":", "abort", "(", "Response", "(", "'Missing application/json header.'", ",", "415", ")", ")", "# Get input parameters", "corpus_id", "=", "request", ".", "json", ".", "get",...
Submit curations for a given corpus. The submitted curations are handled to update the probability model but there is no return value here. The update_belief function can be called separately to calculate update belief scores. Parameters ---------- corpus_id : str The ID of the corpus for which the curation is submitted. curations : dict A set of curations where each key is a Statement UUID in the given corpus and each key is 0 or 1 with 0 corresponding to incorrect and 1 corresponding to correct.
[ "Submit", "curations", "for", "a", "given", "corpus", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/live_curation.py#L239-L265
18,869
sorgerlab/indra
indra/tools/live_curation.py
update_beliefs
def update_beliefs(): """Return updated beliefs based on current probability model.""" if request.json is None: abort(Response('Missing application/json header.', 415)) # Get input parameters corpus_id = request.json.get('corpus_id') try: belief_dict = curator.update_beliefs(corpus_id) except InvalidCorpusError: abort(Response('The corpus_id "%s" is unknown.' % corpus_id, 400)) return return jsonify(belief_dict)
python
def update_beliefs(): if request.json is None: abort(Response('Missing application/json header.', 415)) # Get input parameters corpus_id = request.json.get('corpus_id') try: belief_dict = curator.update_beliefs(corpus_id) except InvalidCorpusError: abort(Response('The corpus_id "%s" is unknown.' % corpus_id, 400)) return return jsonify(belief_dict)
[ "def", "update_beliefs", "(", ")", ":", "if", "request", ".", "json", "is", "None", ":", "abort", "(", "Response", "(", "'Missing application/json header.'", ",", "415", ")", ")", "# Get input parameters", "corpus_id", "=", "request", ".", "json", ".", "get", ...
Return updated beliefs based on current probability model.
[ "Return", "updated", "beliefs", "based", "on", "current", "probability", "model", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/live_curation.py#L269-L280
18,870
sorgerlab/indra
indra/tools/live_curation.py
LiveCurator.reset_scorer
def reset_scorer(self): """Reset the scorer used for couration.""" self.scorer = get_eidos_bayesian_scorer() for corpus_id, corpus in self.corpora.items(): corpus.curations = {}
python
def reset_scorer(self): self.scorer = get_eidos_bayesian_scorer() for corpus_id, corpus in self.corpora.items(): corpus.curations = {}
[ "def", "reset_scorer", "(", "self", ")", ":", "self", ".", "scorer", "=", "get_eidos_bayesian_scorer", "(", ")", "for", "corpus_id", ",", "corpus", "in", "self", ".", "corpora", ".", "items", "(", ")", ":", "corpus", ".", "curations", "=", "{", "}" ]
Reset the scorer used for couration.
[ "Reset", "the", "scorer", "used", "for", "couration", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/live_curation.py#L95-L99
18,871
sorgerlab/indra
indra/tools/live_curation.py
LiveCurator.get_corpus
def get_corpus(self, corpus_id): """Return a corpus given an ID. If the corpus ID cannot be found, an InvalidCorpusError is raised. Parameters ---------- corpus_id : str The ID of the corpus to return. Returns ------- Corpus The corpus with the given ID. """ try: corpus = self.corpora[corpus_id] return corpus except KeyError: raise InvalidCorpusError
python
def get_corpus(self, corpus_id): try: corpus = self.corpora[corpus_id] return corpus except KeyError: raise InvalidCorpusError
[ "def", "get_corpus", "(", "self", ",", "corpus_id", ")", ":", "try", ":", "corpus", "=", "self", ".", "corpora", "[", "corpus_id", "]", "return", "corpus", "except", "KeyError", ":", "raise", "InvalidCorpusError" ]
Return a corpus given an ID. If the corpus ID cannot be found, an InvalidCorpusError is raised. Parameters ---------- corpus_id : str The ID of the corpus to return. Returns ------- Corpus The corpus with the given ID.
[ "Return", "a", "corpus", "given", "an", "ID", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/live_curation.py#L101-L120
18,872
sorgerlab/indra
indra/tools/live_curation.py
LiveCurator.update_beliefs
def update_beliefs(self, corpus_id): """Return updated belief scores for a given corpus. Parameters ---------- corpus_id : str The ID of the corpus for which beliefs are to be updated. Returns ------- dict A dictionary of belief scores with keys corresponding to Statement UUIDs and values to new belief scores. """ corpus = self.get_corpus(corpus_id) be = BeliefEngine(self.scorer) stmts = list(corpus.statements.values()) be.set_prior_probs(stmts) # Here we set beliefs based on actual curation for uuid, correct in corpus.curations.items(): stmt = corpus.statements.get(uuid) if stmt is None: logger.warning('%s is not in the corpus.' % uuid) continue stmt.belief = correct belief_dict = {st.uuid: st.belief for st in stmts} return belief_dict
python
def update_beliefs(self, corpus_id): corpus = self.get_corpus(corpus_id) be = BeliefEngine(self.scorer) stmts = list(corpus.statements.values()) be.set_prior_probs(stmts) # Here we set beliefs based on actual curation for uuid, correct in corpus.curations.items(): stmt = corpus.statements.get(uuid) if stmt is None: logger.warning('%s is not in the corpus.' % uuid) continue stmt.belief = correct belief_dict = {st.uuid: st.belief for st in stmts} return belief_dict
[ "def", "update_beliefs", "(", "self", ",", "corpus_id", ")", ":", "corpus", "=", "self", ".", "get_corpus", "(", "corpus_id", ")", "be", "=", "BeliefEngine", "(", "self", ".", "scorer", ")", "stmts", "=", "list", "(", "corpus", ".", "statements", ".", ...
Return updated belief scores for a given corpus. Parameters ---------- corpus_id : str The ID of the corpus for which beliefs are to be updated. Returns ------- dict A dictionary of belief scores with keys corresponding to Statement UUIDs and values to new belief scores.
[ "Return", "updated", "belief", "scores", "for", "a", "given", "corpus", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/live_curation.py#L174-L200
18,873
sorgerlab/indra
indra/sources/eidos/scala_utils.py
get_python_list
def get_python_list(scala_list): """Return list from elements of scala.collection.immutable.List""" python_list = [] for i in range(scala_list.length()): python_list.append(scala_list.apply(i)) return python_list
python
def get_python_list(scala_list): python_list = [] for i in range(scala_list.length()): python_list.append(scala_list.apply(i)) return python_list
[ "def", "get_python_list", "(", "scala_list", ")", ":", "python_list", "=", "[", "]", "for", "i", "in", "range", "(", "scala_list", ".", "length", "(", ")", ")", ":", "python_list", ".", "append", "(", "scala_list", ".", "apply", "(", "i", ")", ")", "...
Return list from elements of scala.collection.immutable.List
[ "Return", "list", "from", "elements", "of", "scala", ".", "collection", ".", "immutable", ".", "List" ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/eidos/scala_utils.py#L7-L12
18,874
sorgerlab/indra
indra/sources/eidos/scala_utils.py
get_python_dict
def get_python_dict(scala_map): """Return a dict from entries in a scala.collection.immutable.Map""" python_dict = {} keys = get_python_list(scala_map.keys().toList()) for key in keys: python_dict[key] = scala_map.apply(key) return python_dict
python
def get_python_dict(scala_map): python_dict = {} keys = get_python_list(scala_map.keys().toList()) for key in keys: python_dict[key] = scala_map.apply(key) return python_dict
[ "def", "get_python_dict", "(", "scala_map", ")", ":", "python_dict", "=", "{", "}", "keys", "=", "get_python_list", "(", "scala_map", ".", "keys", "(", ")", ".", "toList", "(", ")", ")", "for", "key", "in", "keys", ":", "python_dict", "[", "key", "]", ...
Return a dict from entries in a scala.collection.immutable.Map
[ "Return", "a", "dict", "from", "entries", "in", "a", "scala", ".", "collection", ".", "immutable", ".", "Map" ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/eidos/scala_utils.py#L15-L21
18,875
sorgerlab/indra
indra/sources/eidos/scala_utils.py
get_python_json
def get_python_json(scala_json): """Return a JSON dict from a org.json4s.JsonAST""" def convert_node(node): if node.__class__.__name__ in ('org.json4s.JsonAST$JValue', 'org.json4s.JsonAST$JObject'): # Make a dictionary and then convert each value values_raw = get_python_dict(node.values()) values = {} for k, v in values_raw.items(): values[k] = convert_node(v) return values elif node.__class__.__name__.startswith('scala.collection.immutable.Map') or \ node.__class__.__name__ == \ 'scala.collection.immutable.HashMap$HashTrieMap': values_raw = get_python_dict(node) values = {} for k, v in values_raw.items(): values[k] = convert_node(v) return values elif node.__class__.__name__ == 'org.json4s.JsonAST$JArray': entries_raw = get_python_list(node.values()) entries = [] for entry in entries_raw: entries.append(convert_node(entry)) return entries elif node.__class__.__name__ == 'scala.collection.immutable.$colon$colon': entries_raw = get_python_list(node) entries = [] for entry in entries_raw: entries.append(convert_node(entry)) return entries elif node.__class__.__name__ == 'scala.math.BigInt': return node.intValue() elif node.__class__.__name__ == 'scala.None$': return None elif node.__class__.__name__ == 'scala.collection.immutable.Nil$': return [] elif isinstance(node, (str, int, float)): return node else: logger.error('Cannot convert %s into Python' % node.__class__.__name__) return node.__class__.__name__ python_json = convert_node(scala_json) return python_json
python
def get_python_json(scala_json): def convert_node(node): if node.__class__.__name__ in ('org.json4s.JsonAST$JValue', 'org.json4s.JsonAST$JObject'): # Make a dictionary and then convert each value values_raw = get_python_dict(node.values()) values = {} for k, v in values_raw.items(): values[k] = convert_node(v) return values elif node.__class__.__name__.startswith('scala.collection.immutable.Map') or \ node.__class__.__name__ == \ 'scala.collection.immutable.HashMap$HashTrieMap': values_raw = get_python_dict(node) values = {} for k, v in values_raw.items(): values[k] = convert_node(v) return values elif node.__class__.__name__ == 'org.json4s.JsonAST$JArray': entries_raw = get_python_list(node.values()) entries = [] for entry in entries_raw: entries.append(convert_node(entry)) return entries elif node.__class__.__name__ == 'scala.collection.immutable.$colon$colon': entries_raw = get_python_list(node) entries = [] for entry in entries_raw: entries.append(convert_node(entry)) return entries elif node.__class__.__name__ == 'scala.math.BigInt': return node.intValue() elif node.__class__.__name__ == 'scala.None$': return None elif node.__class__.__name__ == 'scala.collection.immutable.Nil$': return [] elif isinstance(node, (str, int, float)): return node else: logger.error('Cannot convert %s into Python' % node.__class__.__name__) return node.__class__.__name__ python_json = convert_node(scala_json) return python_json
[ "def", "get_python_json", "(", "scala_json", ")", ":", "def", "convert_node", "(", "node", ")", ":", "if", "node", ".", "__class__", ".", "__name__", "in", "(", "'org.json4s.JsonAST$JValue'", ",", "'org.json4s.JsonAST$JObject'", ")", ":", "# Make a dictionary and th...
Return a JSON dict from a org.json4s.JsonAST
[ "Return", "a", "JSON", "dict", "from", "a", "org", ".", "json4s", ".", "JsonAST" ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/eidos/scala_utils.py#L24-L69
18,876
sorgerlab/indra
indra/databases/relevance_client.py
get_heat_kernel
def get_heat_kernel(network_id): """Return the identifier of a heat kernel calculated for a given network. Parameters ---------- network_id : str The UUID of the network in NDEx. Returns ------- kernel_id : str The identifier of the heat kernel calculated for the given network. """ url = ndex_relevance + '/%s/generate_ndex_heat_kernel' % network_id res = ndex_client.send_request(url, {}, is_json=True, use_get=True) if res is None: logger.error('Could not get heat kernel for network %s.' % network_id) return None kernel_id = res.get('kernel_id') if kernel_id is None: logger.error('Could not get heat kernel for network %s.' % network_id) return None return kernel_id
python
def get_heat_kernel(network_id): url = ndex_relevance + '/%s/generate_ndex_heat_kernel' % network_id res = ndex_client.send_request(url, {}, is_json=True, use_get=True) if res is None: logger.error('Could not get heat kernel for network %s.' % network_id) return None kernel_id = res.get('kernel_id') if kernel_id is None: logger.error('Could not get heat kernel for network %s.' % network_id) return None return kernel_id
[ "def", "get_heat_kernel", "(", "network_id", ")", ":", "url", "=", "ndex_relevance", "+", "'/%s/generate_ndex_heat_kernel'", "%", "network_id", "res", "=", "ndex_client", ".", "send_request", "(", "url", ",", "{", "}", ",", "is_json", "=", "True", ",", "use_ge...
Return the identifier of a heat kernel calculated for a given network. Parameters ---------- network_id : str The UUID of the network in NDEx. Returns ------- kernel_id : str The identifier of the heat kernel calculated for the given network.
[ "Return", "the", "identifier", "of", "a", "heat", "kernel", "calculated", "for", "a", "given", "network", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/databases/relevance_client.py#L17-L40
18,877
sorgerlab/indra
indra/databases/relevance_client.py
get_relevant_nodes
def get_relevant_nodes(network_id, query_nodes): """Return a set of network nodes relevant to a given query set. A heat diffusion algorithm is used on a pre-computed heat kernel for the given network which starts from the given query nodes. The nodes in the network are ranked according to heat score which is a measure of relevance with respect to the query nodes. Parameters ---------- network_id : str The UUID of the network in NDEx. query_nodes : list[str] A list of node names with respect to which relevance is queried. Returns ------- ranked_entities : list[(str, float)] A list containing pairs of node names and their relevance scores. """ url = ndex_relevance + '/rank_entities' kernel_id = get_heat_kernel(network_id) if kernel_id is None: return None if isinstance(query_nodes, basestring): query_nodes = [query_nodes] params = {'identifier_set': query_nodes, 'kernel_id': kernel_id} res = ndex_client.send_request(url, params, is_json=True) if res is None: logger.error("ndex_client.send_request returned None.") return None ranked_entities = res.get('ranked_entities') if ranked_entities is None: logger.error('Could not get ranked entities.') return None return ranked_entities
python
def get_relevant_nodes(network_id, query_nodes): url = ndex_relevance + '/rank_entities' kernel_id = get_heat_kernel(network_id) if kernel_id is None: return None if isinstance(query_nodes, basestring): query_nodes = [query_nodes] params = {'identifier_set': query_nodes, 'kernel_id': kernel_id} res = ndex_client.send_request(url, params, is_json=True) if res is None: logger.error("ndex_client.send_request returned None.") return None ranked_entities = res.get('ranked_entities') if ranked_entities is None: logger.error('Could not get ranked entities.') return None return ranked_entities
[ "def", "get_relevant_nodes", "(", "network_id", ",", "query_nodes", ")", ":", "url", "=", "ndex_relevance", "+", "'/rank_entities'", "kernel_id", "=", "get_heat_kernel", "(", "network_id", ")", "if", "kernel_id", "is", "None", ":", "return", "None", "if", "isins...
Return a set of network nodes relevant to a given query set. A heat diffusion algorithm is used on a pre-computed heat kernel for the given network which starts from the given query nodes. The nodes in the network are ranked according to heat score which is a measure of relevance with respect to the query nodes. Parameters ---------- network_id : str The UUID of the network in NDEx. query_nodes : list[str] A list of node names with respect to which relevance is queried. Returns ------- ranked_entities : list[(str, float)] A list containing pairs of node names and their relevance scores.
[ "Return", "a", "set", "of", "network", "nodes", "relevant", "to", "a", "given", "query", "set", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/databases/relevance_client.py#L43-L79
18,878
sorgerlab/indra
indra/belief/__init__.py
_get_belief_package
def _get_belief_package(stmt): """Return the belief packages of a given statement recursively.""" # This list will contain the belief packages for the given statement belief_packages = [] # Iterate over all the support parents for st in stmt.supports: # Recursively get all the belief packages of the parent parent_packages = _get_belief_package(st) package_stmt_keys = [pkg.statement_key for pkg in belief_packages] for package in parent_packages: # Only add this belief package if it hasn't already been added if package.statement_key not in package_stmt_keys: belief_packages.append(package) # Now make the Statement's own belief package and append it to the list belief_package = BeliefPackage(stmt.matches_key(), stmt.evidence) belief_packages.append(belief_package) return belief_packages
python
def _get_belief_package(stmt): # This list will contain the belief packages for the given statement belief_packages = [] # Iterate over all the support parents for st in stmt.supports: # Recursively get all the belief packages of the parent parent_packages = _get_belief_package(st) package_stmt_keys = [pkg.statement_key for pkg in belief_packages] for package in parent_packages: # Only add this belief package if it hasn't already been added if package.statement_key not in package_stmt_keys: belief_packages.append(package) # Now make the Statement's own belief package and append it to the list belief_package = BeliefPackage(stmt.matches_key(), stmt.evidence) belief_packages.append(belief_package) return belief_packages
[ "def", "_get_belief_package", "(", "stmt", ")", ":", "# This list will contain the belief packages for the given statement", "belief_packages", "=", "[", "]", "# Iterate over all the support parents", "for", "st", "in", "stmt", ".", "supports", ":", "# Recursively get all the b...
Return the belief packages of a given statement recursively.
[ "Return", "the", "belief", "packages", "of", "a", "given", "statement", "recursively", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/belief/__init__.py#L415-L431
18,879
sorgerlab/indra
indra/belief/__init__.py
sample_statements
def sample_statements(stmts, seed=None): """Return statements sampled according to belief. Statements are sampled independently according to their belief scores. For instance, a Staement with a belief score of 0.7 will end up in the returned Statement list with probability 0.7. Parameters ---------- stmts : list[indra.statements.Statement] A list of INDRA Statements to sample. seed : Optional[int] A seed for the random number generator used for sampling. Returns ------- new_stmts : list[indra.statements.Statement] A list of INDRA Statements that were chosen by random sampling according to their respective belief scores. """ if seed: numpy.random.seed(seed) new_stmts = [] r = numpy.random.rand(len(stmts)) for i, stmt in enumerate(stmts): if r[i] < stmt.belief: new_stmts.append(stmt) return new_stmts
python
def sample_statements(stmts, seed=None): if seed: numpy.random.seed(seed) new_stmts = [] r = numpy.random.rand(len(stmts)) for i, stmt in enumerate(stmts): if r[i] < stmt.belief: new_stmts.append(stmt) return new_stmts
[ "def", "sample_statements", "(", "stmts", ",", "seed", "=", "None", ")", ":", "if", "seed", ":", "numpy", ".", "random", ".", "seed", "(", "seed", ")", "new_stmts", "=", "[", "]", "r", "=", "numpy", ".", "random", ".", "rand", "(", "len", "(", "s...
Return statements sampled according to belief. Statements are sampled independently according to their belief scores. For instance, a Staement with a belief score of 0.7 will end up in the returned Statement list with probability 0.7. Parameters ---------- stmts : list[indra.statements.Statement] A list of INDRA Statements to sample. seed : Optional[int] A seed for the random number generator used for sampling. Returns ------- new_stmts : list[indra.statements.Statement] A list of INDRA Statements that were chosen by random sampling according to their respective belief scores.
[ "Return", "statements", "sampled", "according", "to", "belief", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/belief/__init__.py#L434-L462
18,880
sorgerlab/indra
indra/belief/__init__.py
evidence_random_noise_prior
def evidence_random_noise_prior(evidence, type_probs, subtype_probs): """Determines the random-noise prior probability for this evidence. If the evidence corresponds to a subtype, and that subtype has a curated prior noise probability, use that. Otherwise, gives the random-noise prior for the overall rule type. """ (stype, subtype) = tag_evidence_subtype(evidence) # Get the subtype, if available # Return the subtype random noise prior, if available if subtype_probs is not None: if stype in subtype_probs: if subtype in subtype_probs[stype]: return subtype_probs[stype][subtype] # Fallback to just returning the overall evidence type random noise prior return type_probs[stype]
python
def evidence_random_noise_prior(evidence, type_probs, subtype_probs): (stype, subtype) = tag_evidence_subtype(evidence) # Get the subtype, if available # Return the subtype random noise prior, if available if subtype_probs is not None: if stype in subtype_probs: if subtype in subtype_probs[stype]: return subtype_probs[stype][subtype] # Fallback to just returning the overall evidence type random noise prior return type_probs[stype]
[ "def", "evidence_random_noise_prior", "(", "evidence", ",", "type_probs", ",", "subtype_probs", ")", ":", "(", "stype", ",", "subtype", ")", "=", "tag_evidence_subtype", "(", "evidence", ")", "# Get the subtype, if available", "# Return the subtype random noise prior, if av...
Determines the random-noise prior probability for this evidence. If the evidence corresponds to a subtype, and that subtype has a curated prior noise probability, use that. Otherwise, gives the random-noise prior for the overall rule type.
[ "Determines", "the", "random", "-", "noise", "prior", "probability", "for", "this", "evidence", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/belief/__init__.py#L465-L483
18,881
sorgerlab/indra
indra/belief/__init__.py
tag_evidence_subtype
def tag_evidence_subtype(evidence): """Returns the type and subtype of an evidence object as a string, typically the extraction rule or database from which the statement was generated. For biopax, this is just the database name. Parameters ---------- statement: indra.statements.Evidence The statement which we wish to subtype Returns ------- types: tuple A tuple with (type, subtype), both strings Returns (type, None) if the type of statement is not yet handled in this function. """ source_api = evidence.source_api annotations = evidence.annotations if source_api == 'biopax': subtype = annotations.get('source_sub_id') elif source_api in ('reach', 'eidos'): if 'found_by' in annotations: from indra.sources.reach.processor import determine_reach_subtype if source_api == 'reach': subtype = determine_reach_subtype(annotations['found_by']) elif source_api == 'eidos': subtype = annotations['found_by'] else: subtype = None else: logger.debug('Could not find found_by attribute in reach ' 'statement annoations') subtype = None elif source_api == 'geneways': subtype = annotations['actiontype'] else: subtype = None return (source_api, subtype)
python
def tag_evidence_subtype(evidence): source_api = evidence.source_api annotations = evidence.annotations if source_api == 'biopax': subtype = annotations.get('source_sub_id') elif source_api in ('reach', 'eidos'): if 'found_by' in annotations: from indra.sources.reach.processor import determine_reach_subtype if source_api == 'reach': subtype = determine_reach_subtype(annotations['found_by']) elif source_api == 'eidos': subtype = annotations['found_by'] else: subtype = None else: logger.debug('Could not find found_by attribute in reach ' 'statement annoations') subtype = None elif source_api == 'geneways': subtype = annotations['actiontype'] else: subtype = None return (source_api, subtype)
[ "def", "tag_evidence_subtype", "(", "evidence", ")", ":", "source_api", "=", "evidence", ".", "source_api", "annotations", "=", "evidence", ".", "annotations", "if", "source_api", "==", "'biopax'", ":", "subtype", "=", "annotations", ".", "get", "(", "'source_su...
Returns the type and subtype of an evidence object as a string, typically the extraction rule or database from which the statement was generated. For biopax, this is just the database name. Parameters ---------- statement: indra.statements.Evidence The statement which we wish to subtype Returns ------- types: tuple A tuple with (type, subtype), both strings Returns (type, None) if the type of statement is not yet handled in this function.
[ "Returns", "the", "type", "and", "subtype", "of", "an", "evidence", "object", "as", "a", "string", "typically", "the", "extraction", "rule", "or", "database", "from", "which", "the", "statement", "was", "generated", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/belief/__init__.py#L486-L528
18,882
sorgerlab/indra
indra/belief/__init__.py
SimpleScorer.score_evidence_list
def score_evidence_list(self, evidences): """Return belief score given a list of supporting evidences.""" def _score(evidences): if not evidences: return 0 # Collect all unique sources sources = [ev.source_api for ev in evidences] uniq_sources = numpy.unique(sources) # Calculate the systematic error factors given unique sources syst_factors = {s: self.prior_probs['syst'][s] for s in uniq_sources} # Calculate the radom error factors for each source rand_factors = {k: [] for k in uniq_sources} for ev in evidences: rand_factors[ev.source_api].append( evidence_random_noise_prior( ev, self.prior_probs['rand'], self.subtype_probs)) # The probability of incorrectness is the product of the # source-specific probabilities neg_prob_prior = 1 for s in uniq_sources: neg_prob_prior *= (syst_factors[s] + numpy.prod(rand_factors[s])) # Finally, the probability of correctness is one minus incorrect prob_prior = 1 - neg_prob_prior return prob_prior pos_evidence = [ev for ev in evidences if not ev.epistemics.get('negated')] neg_evidence = [ev for ev in evidences if ev.epistemics.get('negated')] pp = _score(pos_evidence) np = _score(neg_evidence) # The basic assumption is that the positive and negative evidence # can't simultaneously be correct. # There are two cases to consider. (1) If the positive evidence is # incorrect then there is no Statement and the belief should be 0, # irrespective of the negative evidence. # (2) If the positive evidence is correct and the negative evidence # is incorrect. # This amounts to the following formula: # 0 * (1-pp) + 1 * (pp * (1-np)) which we simplify below score = pp * (1 - np) return score
python
def score_evidence_list(self, evidences): def _score(evidences): if not evidences: return 0 # Collect all unique sources sources = [ev.source_api for ev in evidences] uniq_sources = numpy.unique(sources) # Calculate the systematic error factors given unique sources syst_factors = {s: self.prior_probs['syst'][s] for s in uniq_sources} # Calculate the radom error factors for each source rand_factors = {k: [] for k in uniq_sources} for ev in evidences: rand_factors[ev.source_api].append( evidence_random_noise_prior( ev, self.prior_probs['rand'], self.subtype_probs)) # The probability of incorrectness is the product of the # source-specific probabilities neg_prob_prior = 1 for s in uniq_sources: neg_prob_prior *= (syst_factors[s] + numpy.prod(rand_factors[s])) # Finally, the probability of correctness is one minus incorrect prob_prior = 1 - neg_prob_prior return prob_prior pos_evidence = [ev for ev in evidences if not ev.epistemics.get('negated')] neg_evidence = [ev for ev in evidences if ev.epistemics.get('negated')] pp = _score(pos_evidence) np = _score(neg_evidence) # The basic assumption is that the positive and negative evidence # can't simultaneously be correct. # There are two cases to consider. (1) If the positive evidence is # incorrect then there is no Statement and the belief should be 0, # irrespective of the negative evidence. # (2) If the positive evidence is correct and the negative evidence # is incorrect. # This amounts to the following formula: # 0 * (1-pp) + 1 * (pp * (1-np)) which we simplify below score = pp * (1 - np) return score
[ "def", "score_evidence_list", "(", "self", ",", "evidences", ")", ":", "def", "_score", "(", "evidences", ")", ":", "if", "not", "evidences", ":", "return", "0", "# Collect all unique sources", "sources", "=", "[", "ev", ".", "source_api", "for", "ev", "in",...
Return belief score given a list of supporting evidences.
[ "Return", "belief", "score", "given", "a", "list", "of", "supporting", "evidences", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/belief/__init__.py#L110-L154
18,883
sorgerlab/indra
indra/belief/__init__.py
SimpleScorer.score_statement
def score_statement(self, st, extra_evidence=None): """Computes the prior belief probability for an INDRA Statement. The Statement is assumed to be de-duplicated. In other words, the Statement is assumed to have a list of Evidence objects that supports it. The prior probability of the Statement is calculated based on the number of Evidences it has and their sources. Parameters ---------- st : indra.statements.Statement An INDRA Statements whose belief scores are to be calculated. extra_evidence : list[indra.statements.Evidence] A list of Evidences that are supporting the Statement (that aren't already included in the Statement's own evidence list. Returns ------- belief_score : float The computed prior probability for the statement """ if extra_evidence is None: extra_evidence = [] all_evidence = st.evidence + extra_evidence return self.score_evidence_list(all_evidence)
python
def score_statement(self, st, extra_evidence=None): if extra_evidence is None: extra_evidence = [] all_evidence = st.evidence + extra_evidence return self.score_evidence_list(all_evidence)
[ "def", "score_statement", "(", "self", ",", "st", ",", "extra_evidence", "=", "None", ")", ":", "if", "extra_evidence", "is", "None", ":", "extra_evidence", "=", "[", "]", "all_evidence", "=", "st", ".", "evidence", "+", "extra_evidence", "return", "self", ...
Computes the prior belief probability for an INDRA Statement. The Statement is assumed to be de-duplicated. In other words, the Statement is assumed to have a list of Evidence objects that supports it. The prior probability of the Statement is calculated based on the number of Evidences it has and their sources. Parameters ---------- st : indra.statements.Statement An INDRA Statements whose belief scores are to be calculated. extra_evidence : list[indra.statements.Evidence] A list of Evidences that are supporting the Statement (that aren't already included in the Statement's own evidence list. Returns ------- belief_score : float The computed prior probability for the statement
[ "Computes", "the", "prior", "belief", "probability", "for", "an", "INDRA", "Statement", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/belief/__init__.py#L156-L182
18,884
sorgerlab/indra
indra/belief/__init__.py
SimpleScorer.check_prior_probs
def check_prior_probs(self, statements): """Throw Exception if BeliefEngine parameter is missing. Make sure the scorer has all the information needed to compute belief scores of each statement in the provided list, and raises an exception otherwise. Parameters ---------- statements : list[indra.statements.Statement] List of statements to check """ sources = set() for stmt in statements: sources |= set([ev.source_api for ev in stmt.evidence]) for err_type in ('rand', 'syst'): for source in sources: if source not in self.prior_probs[err_type]: msg = 'BeliefEngine missing probability parameter' + \ ' for source: %s' % source raise Exception(msg)
python
def check_prior_probs(self, statements): sources = set() for stmt in statements: sources |= set([ev.source_api for ev in stmt.evidence]) for err_type in ('rand', 'syst'): for source in sources: if source not in self.prior_probs[err_type]: msg = 'BeliefEngine missing probability parameter' + \ ' for source: %s' % source raise Exception(msg)
[ "def", "check_prior_probs", "(", "self", ",", "statements", ")", ":", "sources", "=", "set", "(", ")", "for", "stmt", "in", "statements", ":", "sources", "|=", "set", "(", "[", "ev", ".", "source_api", "for", "ev", "in", "stmt", ".", "evidence", "]", ...
Throw Exception if BeliefEngine parameter is missing. Make sure the scorer has all the information needed to compute belief scores of each statement in the provided list, and raises an exception otherwise. Parameters ---------- statements : list[indra.statements.Statement] List of statements to check
[ "Throw", "Exception", "if", "BeliefEngine", "parameter", "is", "missing", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/belief/__init__.py#L184-L204
18,885
sorgerlab/indra
indra/belief/__init__.py
BayesianScorer.update_probs
def update_probs(self): """Update the internal probability values given the counts.""" # We deal with the prior probsfirst # This is a fixed assumed value for systematic error syst_error = 0.05 prior_probs = {'syst': {}, 'rand': {}} for source, (p, n) in self.prior_counts.items(): # Skip if there are no actual counts if n + p == 0: continue prior_probs['syst'][source] = syst_error prior_probs['rand'][source] = \ 1 - min((float(p) / (n + p), 1-syst_error)) - syst_error # Next we deal with subtype probs based on counts subtype_probs = {} for source, entry in self.subtype_counts.items(): for rule, (p, n) in entry.items(): # Skip if there are no actual counts if n + p == 0: continue if source not in subtype_probs: subtype_probs[source] = {} subtype_probs[source][rule] = \ 1 - min((float(p) / (n + p), 1-syst_error)) - syst_error # Finally we propagate this into the full probability # data structures of the parent class super(BayesianScorer, self).update_probs(prior_probs, subtype_probs)
python
def update_probs(self): # We deal with the prior probsfirst # This is a fixed assumed value for systematic error syst_error = 0.05 prior_probs = {'syst': {}, 'rand': {}} for source, (p, n) in self.prior_counts.items(): # Skip if there are no actual counts if n + p == 0: continue prior_probs['syst'][source] = syst_error prior_probs['rand'][source] = \ 1 - min((float(p) / (n + p), 1-syst_error)) - syst_error # Next we deal with subtype probs based on counts subtype_probs = {} for source, entry in self.subtype_counts.items(): for rule, (p, n) in entry.items(): # Skip if there are no actual counts if n + p == 0: continue if source not in subtype_probs: subtype_probs[source] = {} subtype_probs[source][rule] = \ 1 - min((float(p) / (n + p), 1-syst_error)) - syst_error # Finally we propagate this into the full probability # data structures of the parent class super(BayesianScorer, self).update_probs(prior_probs, subtype_probs)
[ "def", "update_probs", "(", "self", ")", ":", "# We deal with the prior probsfirst", "# This is a fixed assumed value for systematic error", "syst_error", "=", "0.05", "prior_probs", "=", "{", "'syst'", ":", "{", "}", ",", "'rand'", ":", "{", "}", "}", "for", "sourc...
Update the internal probability values given the counts.
[ "Update", "the", "internal", "probability", "values", "given", "the", "counts", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/belief/__init__.py#L232-L258
18,886
sorgerlab/indra
indra/belief/__init__.py
BayesianScorer.update_counts
def update_counts(self, prior_counts, subtype_counts): """Update the internal counts based on given new counts. Parameters ---------- prior_counts : dict A dictionary of counts of the form [pos, neg] for each source. subtype_counts : dict A dictionary of counts of the form [pos, neg] for each subtype within a source. """ for source, (pos, neg) in prior_counts.items(): if source not in self.prior_counts: self.prior_counts[source] = [0, 0] self.prior_counts[source][0] += pos self.prior_counts[source][1] += neg for source, subtype_dict in subtype_counts.items(): if source not in self.subtype_counts: self.subtype_counts[source] = {} for subtype, (pos, neg) in subtype_dict.items(): if subtype not in self.subtype_counts[source]: self.subtype_counts[source][subtype] = [0, 0] self.subtype_counts[source][subtype][0] += pos self.subtype_counts[source][subtype][1] += neg self.update_probs()
python
def update_counts(self, prior_counts, subtype_counts): for source, (pos, neg) in prior_counts.items(): if source not in self.prior_counts: self.prior_counts[source] = [0, 0] self.prior_counts[source][0] += pos self.prior_counts[source][1] += neg for source, subtype_dict in subtype_counts.items(): if source not in self.subtype_counts: self.subtype_counts[source] = {} for subtype, (pos, neg) in subtype_dict.items(): if subtype not in self.subtype_counts[source]: self.subtype_counts[source][subtype] = [0, 0] self.subtype_counts[source][subtype][0] += pos self.subtype_counts[source][subtype][1] += neg self.update_probs()
[ "def", "update_counts", "(", "self", ",", "prior_counts", ",", "subtype_counts", ")", ":", "for", "source", ",", "(", "pos", ",", "neg", ")", "in", "prior_counts", ".", "items", "(", ")", ":", "if", "source", "not", "in", "self", ".", "prior_counts", "...
Update the internal counts based on given new counts. Parameters ---------- prior_counts : dict A dictionary of counts of the form [pos, neg] for each source. subtype_counts : dict A dictionary of counts of the form [pos, neg] for each subtype within a source.
[ "Update", "the", "internal", "counts", "based", "on", "given", "new", "counts", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/belief/__init__.py#L260-L285
18,887
sorgerlab/indra
indra/belief/__init__.py
BeliefEngine.set_prior_probs
def set_prior_probs(self, statements): """Sets the prior belief probabilities for a list of INDRA Statements. The Statements are assumed to be de-duplicated. In other words, each Statement in the list passed to this function is assumed to have a list of Evidence objects that support it. The prior probability of each Statement is calculated based on the number of Evidences it has and their sources. Parameters ---------- statements : list[indra.statements.Statement] A list of INDRA Statements whose belief scores are to be calculated. Each Statement object's belief attribute is updated by this function. """ self.scorer.check_prior_probs(statements) for st in statements: st.belief = self.scorer.score_statement(st)
python
def set_prior_probs(self, statements): self.scorer.check_prior_probs(statements) for st in statements: st.belief = self.scorer.score_statement(st)
[ "def", "set_prior_probs", "(", "self", ",", "statements", ")", ":", "self", ".", "scorer", ".", "check_prior_probs", "(", "statements", ")", "for", "st", "in", "statements", ":", "st", ".", "belief", "=", "self", ".", "scorer", ".", "score_statement", "(",...
Sets the prior belief probabilities for a list of INDRA Statements. The Statements are assumed to be de-duplicated. In other words, each Statement in the list passed to this function is assumed to have a list of Evidence objects that support it. The prior probability of each Statement is calculated based on the number of Evidences it has and their sources. Parameters ---------- statements : list[indra.statements.Statement] A list of INDRA Statements whose belief scores are to be calculated. Each Statement object's belief attribute is updated by this function.
[ "Sets", "the", "prior", "belief", "probabilities", "for", "a", "list", "of", "INDRA", "Statements", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/belief/__init__.py#L311-L329
18,888
sorgerlab/indra
indra/belief/__init__.py
BeliefEngine.set_hierarchy_probs
def set_hierarchy_probs(self, statements): """Sets hierarchical belief probabilities for INDRA Statements. The Statements are assumed to be in a hierarchical relation graph with the supports and supported_by attribute of each Statement object having been set. The hierarchical belief probability of each Statement is calculated based on its prior probability and the probabilities propagated from Statements supporting it in the hierarchy graph. Parameters ---------- statements : list[indra.statements.Statement] A list of INDRA Statements whose belief scores are to be calculated. Each Statement object's belief attribute is updated by this function. """ def build_hierarchy_graph(stmts): """Return a DiGraph based on matches keys and Statement supports""" g = networkx.DiGraph() for st1 in stmts: g.add_node(st1.matches_key(), stmt=st1) for st2 in st1.supported_by: g.add_node(st2.matches_key(), stmt=st2) g.add_edge(st2.matches_key(), st1.matches_key()) return g def get_ranked_stmts(g): """Return a topological sort of statement matches keys from a graph. """ node_ranks = networkx.algorithms.dag.topological_sort(g) node_ranks = reversed(list(node_ranks)) stmts = [g.node[n]['stmt'] for n in node_ranks] return stmts def assert_no_cycle(g): """If the graph has cycles, throws AssertionError.""" try: cyc = networkx.algorithms.cycles.find_cycle(g) except networkx.exception.NetworkXNoCycle: return msg = 'Cycle found in hierarchy graph: %s' % cyc assert False, msg g = build_hierarchy_graph(statements) assert_no_cycle(g) ranked_stmts = get_ranked_stmts(g) for st in ranked_stmts: bps = _get_belief_package(st) supporting_evidences = [] # NOTE: the last belief package in the list is this statement's own for bp in bps[:-1]: # Iterate over all the parent evidences and add only # non-negated ones for ev in bp.evidences: if not ev.epistemics.get('negated'): supporting_evidences.append(ev) # Now add the Statement's own evidence # Now score all the evidences belief = self.scorer.score_statement(st, supporting_evidences) st.belief = belief
python
def set_hierarchy_probs(self, statements): def build_hierarchy_graph(stmts): """Return a DiGraph based on matches keys and Statement supports""" g = networkx.DiGraph() for st1 in stmts: g.add_node(st1.matches_key(), stmt=st1) for st2 in st1.supported_by: g.add_node(st2.matches_key(), stmt=st2) g.add_edge(st2.matches_key(), st1.matches_key()) return g def get_ranked_stmts(g): """Return a topological sort of statement matches keys from a graph. """ node_ranks = networkx.algorithms.dag.topological_sort(g) node_ranks = reversed(list(node_ranks)) stmts = [g.node[n]['stmt'] for n in node_ranks] return stmts def assert_no_cycle(g): """If the graph has cycles, throws AssertionError.""" try: cyc = networkx.algorithms.cycles.find_cycle(g) except networkx.exception.NetworkXNoCycle: return msg = 'Cycle found in hierarchy graph: %s' % cyc assert False, msg g = build_hierarchy_graph(statements) assert_no_cycle(g) ranked_stmts = get_ranked_stmts(g) for st in ranked_stmts: bps = _get_belief_package(st) supporting_evidences = [] # NOTE: the last belief package in the list is this statement's own for bp in bps[:-1]: # Iterate over all the parent evidences and add only # non-negated ones for ev in bp.evidences: if not ev.epistemics.get('negated'): supporting_evidences.append(ev) # Now add the Statement's own evidence # Now score all the evidences belief = self.scorer.score_statement(st, supporting_evidences) st.belief = belief
[ "def", "set_hierarchy_probs", "(", "self", ",", "statements", ")", ":", "def", "build_hierarchy_graph", "(", "stmts", ")", ":", "\"\"\"Return a DiGraph based on matches keys and Statement supports\"\"\"", "g", "=", "networkx", ".", "DiGraph", "(", ")", "for", "st1", "...
Sets hierarchical belief probabilities for INDRA Statements. The Statements are assumed to be in a hierarchical relation graph with the supports and supported_by attribute of each Statement object having been set. The hierarchical belief probability of each Statement is calculated based on its prior probability and the probabilities propagated from Statements supporting it in the hierarchy graph. Parameters ---------- statements : list[indra.statements.Statement] A list of INDRA Statements whose belief scores are to be calculated. Each Statement object's belief attribute is updated by this function.
[ "Sets", "hierarchical", "belief", "probabilities", "for", "INDRA", "Statements", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/belief/__init__.py#L331-L391
18,889
sorgerlab/indra
indra/belief/__init__.py
BeliefEngine.set_linked_probs
def set_linked_probs(self, linked_statements): """Sets the belief probabilities for a list of linked INDRA Statements. The list of LinkedStatement objects is assumed to come from the MechanismLinker. The belief probability of the inferred Statement is assigned the joint probability of its source Statements. Parameters ---------- linked_statements : list[indra.mechlinker.LinkedStatement] A list of INDRA LinkedStatements whose belief scores are to be calculated. The belief attribute of the inferred Statement in the LinkedStatement object is updated by this function. """ for st in linked_statements: source_probs = [s.belief for s in st.source_stmts] st.inferred_stmt.belief = numpy.prod(source_probs)
python
def set_linked_probs(self, linked_statements): for st in linked_statements: source_probs = [s.belief for s in st.source_stmts] st.inferred_stmt.belief = numpy.prod(source_probs)
[ "def", "set_linked_probs", "(", "self", ",", "linked_statements", ")", ":", "for", "st", "in", "linked_statements", ":", "source_probs", "=", "[", "s", ".", "belief", "for", "s", "in", "st", ".", "source_stmts", "]", "st", ".", "inferred_stmt", ".", "belie...
Sets the belief probabilities for a list of linked INDRA Statements. The list of LinkedStatement objects is assumed to come from the MechanismLinker. The belief probability of the inferred Statement is assigned the joint probability of its source Statements. Parameters ---------- linked_statements : list[indra.mechlinker.LinkedStatement] A list of INDRA LinkedStatements whose belief scores are to be calculated. The belief attribute of the inferred Statement in the LinkedStatement object is updated by this function.
[ "Sets", "the", "belief", "probabilities", "for", "a", "list", "of", "linked", "INDRA", "Statements", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/belief/__init__.py#L393-L409
18,890
sorgerlab/indra
indra/sources/rlimsp/processor.py
RlimspProcessor.extract_statements
def extract_statements(self): """Extract the statements from the json.""" for p_info in self._json: para = RlimspParagraph(p_info, self.doc_id_type) self.statements.extend(para.get_statements()) return
python
def extract_statements(self): for p_info in self._json: para = RlimspParagraph(p_info, self.doc_id_type) self.statements.extend(para.get_statements()) return
[ "def", "extract_statements", "(", "self", ")", ":", "for", "p_info", "in", "self", ".", "_json", ":", "para", "=", "RlimspParagraph", "(", "p_info", ",", "self", ".", "doc_id_type", ")", "self", ".", "statements", ".", "extend", "(", "para", ".", "get_st...
Extract the statements from the json.
[ "Extract", "the", "statements", "from", "the", "json", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/rlimsp/processor.py#L19-L24
18,891
sorgerlab/indra
indra/sources/rlimsp/processor.py
RlimspParagraph._get_agent
def _get_agent(self, entity_id): """Convert the entity dictionary into an INDRA Agent.""" if entity_id is None: return None entity_info = self._entity_dict.get(entity_id) if entity_info is None: logger.warning("Entity key did not resolve to entity.") return None return get_agent_from_entity_info(entity_info)
python
def _get_agent(self, entity_id): if entity_id is None: return None entity_info = self._entity_dict.get(entity_id) if entity_info is None: logger.warning("Entity key did not resolve to entity.") return None return get_agent_from_entity_info(entity_info)
[ "def", "_get_agent", "(", "self", ",", "entity_id", ")", ":", "if", "entity_id", "is", "None", ":", "return", "None", "entity_info", "=", "self", ".", "_entity_dict", ".", "get", "(", "entity_id", ")", "if", "entity_info", "is", "None", ":", "logger", "....
Convert the entity dictionary into an INDRA Agent.
[ "Convert", "the", "entity", "dictionary", "into", "an", "INDRA", "Agent", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/rlimsp/processor.py#L49-L58
18,892
sorgerlab/indra
indra/sources/rlimsp/processor.py
RlimspParagraph._get_evidence
def _get_evidence(self, trigger_id, args, agent_coords, site_coords): """Get the evidence using the info in the trigger entity.""" trigger_info = self._entity_dict[trigger_id] # Get the sentence index from the trigger word. s_idx_set = {self._entity_dict[eid]['sentenceIndex'] for eid in args.values() if 'sentenceIndex' in self._entity_dict[eid]} if s_idx_set: i_min = min(s_idx_set) i_max = max(s_idx_set) text = '. '.join(self._sentences[i_min:(i_max+1)]) + '.' s_start = self._sentence_starts[i_min] annotations = { 'agents': {'coords': [_fix_coords(coords, s_start) for coords in agent_coords]}, 'trigger': {'coords': _fix_coords([trigger_info['charStart'], trigger_info['charEnd']], s_start)} } else: logger.info('Unable to get sentence index') annotations = {} text = None if site_coords: annotations['site'] = {'coords': _fix_coords(site_coords, s_start)} return Evidence(text_refs=self._text_refs.copy(), text=text, source_api='rlimsp', pmid=self._text_refs.get('PMID'), annotations=annotations)
python
def _get_evidence(self, trigger_id, args, agent_coords, site_coords): trigger_info = self._entity_dict[trigger_id] # Get the sentence index from the trigger word. s_idx_set = {self._entity_dict[eid]['sentenceIndex'] for eid in args.values() if 'sentenceIndex' in self._entity_dict[eid]} if s_idx_set: i_min = min(s_idx_set) i_max = max(s_idx_set) text = '. '.join(self._sentences[i_min:(i_max+1)]) + '.' s_start = self._sentence_starts[i_min] annotations = { 'agents': {'coords': [_fix_coords(coords, s_start) for coords in agent_coords]}, 'trigger': {'coords': _fix_coords([trigger_info['charStart'], trigger_info['charEnd']], s_start)} } else: logger.info('Unable to get sentence index') annotations = {} text = None if site_coords: annotations['site'] = {'coords': _fix_coords(site_coords, s_start)} return Evidence(text_refs=self._text_refs.copy(), text=text, source_api='rlimsp', pmid=self._text_refs.get('PMID'), annotations=annotations)
[ "def", "_get_evidence", "(", "self", ",", "trigger_id", ",", "args", ",", "agent_coords", ",", "site_coords", ")", ":", "trigger_info", "=", "self", ".", "_entity_dict", "[", "trigger_id", "]", "# Get the sentence index from the trigger word.", "s_idx_set", "=", "{"...
Get the evidence using the info in the trigger entity.
[ "Get", "the", "evidence", "using", "the", "info", "in", "the", "trigger", "entity", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/rlimsp/processor.py#L84-L115
18,893
sorgerlab/indra
indra/tools/reading/readers.py
get_reader_classes
def get_reader_classes(parent=Reader): """Get all childless the descendants of a parent class, recursively.""" children = parent.__subclasses__() descendants = children[:] for child in children: grandchildren = get_reader_classes(child) if grandchildren: descendants.remove(child) descendants.extend(grandchildren) return descendants
python
def get_reader_classes(parent=Reader): children = parent.__subclasses__() descendants = children[:] for child in children: grandchildren = get_reader_classes(child) if grandchildren: descendants.remove(child) descendants.extend(grandchildren) return descendants
[ "def", "get_reader_classes", "(", "parent", "=", "Reader", ")", ":", "children", "=", "parent", ".", "__subclasses__", "(", ")", "descendants", "=", "children", "[", ":", "]", "for", "child", "in", "children", ":", "grandchildren", "=", "get_reader_classes", ...
Get all childless the descendants of a parent class, recursively.
[ "Get", "all", "childless", "the", "descendants", "of", "a", "parent", "class", "recursively", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/reading/readers.py#L761-L770
18,894
sorgerlab/indra
indra/tools/reading/readers.py
get_reader_class
def get_reader_class(reader_name): """Get a particular reader class by name.""" for reader_class in get_reader_classes(): if reader_class.name.lower() == reader_name.lower(): return reader_class else: logger.error("No such reader: %s" % reader_name) return None
python
def get_reader_class(reader_name): for reader_class in get_reader_classes(): if reader_class.name.lower() == reader_name.lower(): return reader_class else: logger.error("No such reader: %s" % reader_name) return None
[ "def", "get_reader_class", "(", "reader_name", ")", ":", "for", "reader_class", "in", "get_reader_classes", "(", ")", ":", "if", "reader_class", ".", "name", ".", "lower", "(", ")", "==", "reader_name", ".", "lower", "(", ")", ":", "return", "reader_class", ...
Get a particular reader class by name.
[ "Get", "a", "particular", "reader", "class", "by", "name", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/reading/readers.py#L773-L780
18,895
sorgerlab/indra
indra/tools/reading/readers.py
Content.from_file
def from_file(cls, file_path, compressed=False, encoded=False): """Create a content object from a file path.""" file_id = '.'.join(path.basename(file_path).split('.')[:-1]) file_format = file_path.split('.')[-1] content = cls(file_id, file_format, compressed, encoded) content.file_exists = True content._location = path.dirname(file_path) return content
python
def from_file(cls, file_path, compressed=False, encoded=False): file_id = '.'.join(path.basename(file_path).split('.')[:-1]) file_format = file_path.split('.')[-1] content = cls(file_id, file_format, compressed, encoded) content.file_exists = True content._location = path.dirname(file_path) return content
[ "def", "from_file", "(", "cls", ",", "file_path", ",", "compressed", "=", "False", ",", "encoded", "=", "False", ")", ":", "file_id", "=", "'.'", ".", "join", "(", "path", ".", "basename", "(", "file_path", ")", ".", "split", "(", "'.'", ")", "[", ...
Create a content object from a file path.
[ "Create", "a", "content", "object", "from", "a", "file", "path", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/reading/readers.py#L100-L107
18,896
sorgerlab/indra
indra/tools/reading/readers.py
Content.change_id
def change_id(self, new_id): """Change the id of this content.""" self._load_raw_content() self._id = new_id self.get_filename(renew=True) self.get_filepath(renew=True) return
python
def change_id(self, new_id): self._load_raw_content() self._id = new_id self.get_filename(renew=True) self.get_filepath(renew=True) return
[ "def", "change_id", "(", "self", ",", "new_id", ")", ":", "self", ".", "_load_raw_content", "(", ")", "self", ".", "_id", "=", "new_id", "self", ".", "get_filename", "(", "renew", "=", "True", ")", "self", ".", "get_filepath", "(", "renew", "=", "True"...
Change the id of this content.
[ "Change", "the", "id", "of", "this", "content", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/reading/readers.py#L123-L129
18,897
sorgerlab/indra
indra/tools/reading/readers.py
Content.change_format
def change_format(self, new_format): """Change the format label of this content. Note that this does NOT actually alter the format of the content, only the label. """ self._load_raw_content() self._format = new_format self.get_filename(renew=True) self.get_filepath(renew=True) return
python
def change_format(self, new_format): self._load_raw_content() self._format = new_format self.get_filename(renew=True) self.get_filepath(renew=True) return
[ "def", "change_format", "(", "self", ",", "new_format", ")", ":", "self", ".", "_load_raw_content", "(", ")", "self", ".", "_format", "=", "new_format", "self", ".", "get_filename", "(", "renew", "=", "True", ")", "self", ".", "get_filepath", "(", "renew",...
Change the format label of this content. Note that this does NOT actually alter the format of the content, only the label.
[ "Change", "the", "format", "label", "of", "this", "content", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/reading/readers.py#L131-L141
18,898
sorgerlab/indra
indra/tools/reading/readers.py
Content.get_text
def get_text(self): """Get the loaded, decompressed, and decoded text of this content.""" self._load_raw_content() if self._text is None: assert self._raw_content is not None ret_cont = self._raw_content if self.compressed: ret_cont = zlib.decompress(ret_cont, zlib.MAX_WBITS+16) if self.encoded: ret_cont = ret_cont.decode('utf-8') self._text = ret_cont assert self._text is not None return self._text
python
def get_text(self): self._load_raw_content() if self._text is None: assert self._raw_content is not None ret_cont = self._raw_content if self.compressed: ret_cont = zlib.decompress(ret_cont, zlib.MAX_WBITS+16) if self.encoded: ret_cont = ret_cont.decode('utf-8') self._text = ret_cont assert self._text is not None return self._text
[ "def", "get_text", "(", "self", ")", ":", "self", ".", "_load_raw_content", "(", ")", "if", "self", ".", "_text", "is", "None", ":", "assert", "self", ".", "_raw_content", "is", "not", "None", "ret_cont", "=", "self", ".", "_raw_content", "if", "self", ...
Get the loaded, decompressed, and decoded text of this content.
[ "Get", "the", "loaded", "decompressed", "and", "decoded", "text", "of", "this", "content", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/reading/readers.py#L164-L176
18,899
sorgerlab/indra
indra/tools/reading/readers.py
Content.get_filename
def get_filename(self, renew=False): """Get the filename of this content. If the file name doesn't already exist, we created it as {id}.{format}. """ if self._fname is None or renew: self._fname = '%s.%s' % (self._id, self._format) return self._fname
python
def get_filename(self, renew=False): if self._fname is None or renew: self._fname = '%s.%s' % (self._id, self._format) return self._fname
[ "def", "get_filename", "(", "self", ",", "renew", "=", "False", ")", ":", "if", "self", ".", "_fname", "is", "None", "or", "renew", ":", "self", ".", "_fname", "=", "'%s.%s'", "%", "(", "self", ".", "_id", ",", "self", ".", "_format", ")", "return"...
Get the filename of this content. If the file name doesn't already exist, we created it as {id}.{format}.
[ "Get", "the", "filename", "of", "this", "content", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/reading/readers.py#L178-L185