id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
19,200
sorgerlab/indra
indra/databases/__init__.py
get_identifiers_url
def get_identifiers_url(db_name, db_id): """Return an identifiers.org URL for a given database name and ID. Parameters ---------- db_name : str An internal database name: HGNC, UP, CHEBI, etc. db_id : str An identifier in the given database. Returns ------- url : str An identifiers.org URL corresponding to the given database name and ID. """ identifiers_url = 'http://identifiers.org/' bel_scai_url = 'https://arty.scai.fraunhofer.de/artifactory/bel/namespace/' if db_name == 'UP': url = identifiers_url + 'uniprot/%s' % db_id elif db_name == 'HGNC': url = identifiers_url + 'hgnc/HGNC:%s' % db_id elif db_name == 'IP': url = identifiers_url + 'interpro/%s' % db_id elif db_name == 'IPR': url = identifiers_url + 'interpro/%s' % db_id elif db_name == 'CHEBI': url = identifiers_url + 'chebi/%s' % db_id elif db_name == 'NCIT': url = identifiers_url + 'ncit/%s' % db_id elif db_name == 'GO': if db_id.startswith('GO:'): url = identifiers_url + 'go/%s' % db_id else: url = identifiers_url + 'go/GO:%s' % db_id elif db_name in ('PUBCHEM', 'PCID'): # Assuming PCID = PubChem compound ID if db_id.startswith('PUBCHEM:'): db_id = db_id[8:] elif db_id.startswith('PCID:'): db_id = db_id[5:] url = identifiers_url + 'pubchem.compound/%s' % db_id elif db_name == 'PF': url = identifiers_url + 'pfam/%s' % db_id elif db_name == 'MIRBASEM': url = identifiers_url + 'mirbase.mature/%s' % db_id elif db_name == 'MIRBASE': url = identifiers_url + 'mirbase/%s' % db_id elif db_name == 'MESH': url = identifiers_url + 'mesh/%s' % db_id elif db_name == 'EGID': url = identifiers_url + 'ncbigene/%s' % db_id elif db_name == 'HMDB': url = identifiers_url + 'hmdb/%s' % db_id elif db_name == 'LINCS': if db_id.startswith('LSM-'): # Lincs Small Molecule ID url = identifiers_url + 'lincs.smallmolecule/%s' % db_id elif db_id.startswith('LCL-'): # Lincs Cell Line ID url = identifiers_url + 'lincs.cell/%s' % db_id else: # Assume LINCS Protein url = identifiers_url + 'lincs.protein/%s' % db_id elif db_name == 'HMS-LINCS': url = 'http://lincs.hms.harvard.edu/db/sm/%s-101' % db_id # Special cases with no identifiers entry elif db_name == 'SCHEM': url = bel_scai_url + 'selventa-legacy-chemicals/' + \ 'selventa-legacy-chemicals-20150601.belns' elif db_name == 'SCOMP': url = bel_scai_url + 'selventa-named-complexes/' + \ 'selventa-named-complexes-20150601.belns' elif db_name == 'SFAM': url = bel_scai_url + 'selventa-protein-families/' + \ 'selventa-protein-families-20150601.belns' elif db_name == 'FPLX': url = 'http://identifiers.org/fplx/%s' % db_id elif db_name == 'LNCRNADB': if db_id.startswith('ENSG'): url = 'http://www.lncrnadb.org/search/?q=%s' % db_id else: # Assmuing HGNC symbol url = 'http://www.lncrnadb.org/%s/' % db_id elif db_name == 'NXPFA': url = 'https://www.nextprot.org/term/FA-%s' % db_id elif db_name in ('UN', 'WDI', 'FAO'): url = 'https://github.com/clulab/eidos/wiki/JSON-LD#Grounding/%s' % \ db_id elif db_name == 'HUME': url = ('https://github.com/BBN-E/Hume/blob/master/resource/ontologies/' 'hume_ontology/%s' % db_id) elif db_name == 'CWMS': url = 'http://trips.ihmc.us/%s' % db_id elif db_name == 'SIGNOR': # Assuming db_id == Primary ID url = 'https://signor.uniroma2.it/relation_result.php?id=%s' % db_id elif db_name == 'SOFIA': url = 'http://cs.cmu.edu/sofia/%s' % db_id elif db_name == 'CHEMBL': if not db_id.startswith('CHEMBL'): db_id = 'CHEMBL%s' % db_id url = identifiers_url + 'chembl.compound/%s' % db_id elif db_name == 'NONCODE': url = 'http://www.noncode.org/show_gene.php?id=NONHSAG%s' % db_id elif db_name == 'TEXT': return None else: logger.warning('Unhandled name space %s' % db_name) url = None return url
python
def get_identifiers_url(db_name, db_id): identifiers_url = 'http://identifiers.org/' bel_scai_url = 'https://arty.scai.fraunhofer.de/artifactory/bel/namespace/' if db_name == 'UP': url = identifiers_url + 'uniprot/%s' % db_id elif db_name == 'HGNC': url = identifiers_url + 'hgnc/HGNC:%s' % db_id elif db_name == 'IP': url = identifiers_url + 'interpro/%s' % db_id elif db_name == 'IPR': url = identifiers_url + 'interpro/%s' % db_id elif db_name == 'CHEBI': url = identifiers_url + 'chebi/%s' % db_id elif db_name == 'NCIT': url = identifiers_url + 'ncit/%s' % db_id elif db_name == 'GO': if db_id.startswith('GO:'): url = identifiers_url + 'go/%s' % db_id else: url = identifiers_url + 'go/GO:%s' % db_id elif db_name in ('PUBCHEM', 'PCID'): # Assuming PCID = PubChem compound ID if db_id.startswith('PUBCHEM:'): db_id = db_id[8:] elif db_id.startswith('PCID:'): db_id = db_id[5:] url = identifiers_url + 'pubchem.compound/%s' % db_id elif db_name == 'PF': url = identifiers_url + 'pfam/%s' % db_id elif db_name == 'MIRBASEM': url = identifiers_url + 'mirbase.mature/%s' % db_id elif db_name == 'MIRBASE': url = identifiers_url + 'mirbase/%s' % db_id elif db_name == 'MESH': url = identifiers_url + 'mesh/%s' % db_id elif db_name == 'EGID': url = identifiers_url + 'ncbigene/%s' % db_id elif db_name == 'HMDB': url = identifiers_url + 'hmdb/%s' % db_id elif db_name == 'LINCS': if db_id.startswith('LSM-'): # Lincs Small Molecule ID url = identifiers_url + 'lincs.smallmolecule/%s' % db_id elif db_id.startswith('LCL-'): # Lincs Cell Line ID url = identifiers_url + 'lincs.cell/%s' % db_id else: # Assume LINCS Protein url = identifiers_url + 'lincs.protein/%s' % db_id elif db_name == 'HMS-LINCS': url = 'http://lincs.hms.harvard.edu/db/sm/%s-101' % db_id # Special cases with no identifiers entry elif db_name == 'SCHEM': url = bel_scai_url + 'selventa-legacy-chemicals/' + \ 'selventa-legacy-chemicals-20150601.belns' elif db_name == 'SCOMP': url = bel_scai_url + 'selventa-named-complexes/' + \ 'selventa-named-complexes-20150601.belns' elif db_name == 'SFAM': url = bel_scai_url + 'selventa-protein-families/' + \ 'selventa-protein-families-20150601.belns' elif db_name == 'FPLX': url = 'http://identifiers.org/fplx/%s' % db_id elif db_name == 'LNCRNADB': if db_id.startswith('ENSG'): url = 'http://www.lncrnadb.org/search/?q=%s' % db_id else: # Assmuing HGNC symbol url = 'http://www.lncrnadb.org/%s/' % db_id elif db_name == 'NXPFA': url = 'https://www.nextprot.org/term/FA-%s' % db_id elif db_name in ('UN', 'WDI', 'FAO'): url = 'https://github.com/clulab/eidos/wiki/JSON-LD#Grounding/%s' % \ db_id elif db_name == 'HUME': url = ('https://github.com/BBN-E/Hume/blob/master/resource/ontologies/' 'hume_ontology/%s' % db_id) elif db_name == 'CWMS': url = 'http://trips.ihmc.us/%s' % db_id elif db_name == 'SIGNOR': # Assuming db_id == Primary ID url = 'https://signor.uniroma2.it/relation_result.php?id=%s' % db_id elif db_name == 'SOFIA': url = 'http://cs.cmu.edu/sofia/%s' % db_id elif db_name == 'CHEMBL': if not db_id.startswith('CHEMBL'): db_id = 'CHEMBL%s' % db_id url = identifiers_url + 'chembl.compound/%s' % db_id elif db_name == 'NONCODE': url = 'http://www.noncode.org/show_gene.php?id=NONHSAG%s' % db_id elif db_name == 'TEXT': return None else: logger.warning('Unhandled name space %s' % db_name) url = None return url
[ "def", "get_identifiers_url", "(", "db_name", ",", "db_id", ")", ":", "identifiers_url", "=", "'http://identifiers.org/'", "bel_scai_url", "=", "'https://arty.scai.fraunhofer.de/artifactory/bel/namespace/'", "if", "db_name", "==", "'UP'", ":", "url", "=", "identifiers_url",...
Return an identifiers.org URL for a given database name and ID. Parameters ---------- db_name : str An internal database name: HGNC, UP, CHEBI, etc. db_id : str An identifier in the given database. Returns ------- url : str An identifiers.org URL corresponding to the given database name and ID.
[ "Return", "an", "identifiers", ".", "org", "URL", "for", "a", "given", "database", "name", "and", "ID", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/databases/__init__.py#L6-L110
19,201
sorgerlab/indra
indra/tools/assemble_corpus.py
dump_statements
def dump_statements(stmts, fname, protocol=4): """Dump a list of statements into a pickle file. Parameters ---------- fname : str The name of the pickle file to dump statements into. protocol : Optional[int] The pickle protocol to use (use 2 for Python 2 compatibility). Default: 4 """ logger.info('Dumping %d statements into %s...' % (len(stmts), fname)) with open(fname, 'wb') as fh: pickle.dump(stmts, fh, protocol=protocol)
python
def dump_statements(stmts, fname, protocol=4): logger.info('Dumping %d statements into %s...' % (len(stmts), fname)) with open(fname, 'wb') as fh: pickle.dump(stmts, fh, protocol=protocol)
[ "def", "dump_statements", "(", "stmts", ",", "fname", ",", "protocol", "=", "4", ")", ":", "logger", ".", "info", "(", "'Dumping %d statements into %s...'", "%", "(", "len", "(", "stmts", ")", ",", "fname", ")", ")", "with", "open", "(", "fname", ",", ...
Dump a list of statements into a pickle file. Parameters ---------- fname : str The name of the pickle file to dump statements into. protocol : Optional[int] The pickle protocol to use (use 2 for Python 2 compatibility). Default: 4
[ "Dump", "a", "list", "of", "statements", "into", "a", "pickle", "file", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/assemble_corpus.py#L27-L40
19,202
sorgerlab/indra
indra/tools/assemble_corpus.py
load_statements
def load_statements(fname, as_dict=False): """Load statements from a pickle file. Parameters ---------- fname : str The name of the pickle file to load statements from. as_dict : Optional[bool] If True and the pickle file contains a dictionary of statements, it is returned as a dictionary. If False, the statements are always returned in a list. Default: False Returns ------- stmts : list A list or dict of statements that were loaded. """ logger.info('Loading %s...' % fname) with open(fname, 'rb') as fh: # Encoding argument not available in pickle for Python 2 if sys.version_info[0] < 3: stmts = pickle.load(fh) # Encoding argument specified here to enable compatibility with # pickle files created with Python 2 else: stmts = pickle.load(fh, encoding='latin1') if isinstance(stmts, dict): if as_dict: return stmts st = [] for pmid, st_list in stmts.items(): st += st_list stmts = st logger.info('Loaded %d statements' % len(stmts)) return stmts
python
def load_statements(fname, as_dict=False): logger.info('Loading %s...' % fname) with open(fname, 'rb') as fh: # Encoding argument not available in pickle for Python 2 if sys.version_info[0] < 3: stmts = pickle.load(fh) # Encoding argument specified here to enable compatibility with # pickle files created with Python 2 else: stmts = pickle.load(fh, encoding='latin1') if isinstance(stmts, dict): if as_dict: return stmts st = [] for pmid, st_list in stmts.items(): st += st_list stmts = st logger.info('Loaded %d statements' % len(stmts)) return stmts
[ "def", "load_statements", "(", "fname", ",", "as_dict", "=", "False", ")", ":", "logger", ".", "info", "(", "'Loading %s...'", "%", "fname", ")", "with", "open", "(", "fname", ",", "'rb'", ")", "as", "fh", ":", "# Encoding argument not available in pickle for ...
Load statements from a pickle file. Parameters ---------- fname : str The name of the pickle file to load statements from. as_dict : Optional[bool] If True and the pickle file contains a dictionary of statements, it is returned as a dictionary. If False, the statements are always returned in a list. Default: False Returns ------- stmts : list A list or dict of statements that were loaded.
[ "Load", "statements", "from", "a", "pickle", "file", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/assemble_corpus.py#L43-L78
19,203
sorgerlab/indra
indra/tools/assemble_corpus.py
map_grounding
def map_grounding(stmts_in, **kwargs): """Map grounding using the GroundingMapper. Parameters ---------- stmts_in : list[indra.statements.Statement] A list of statements to map. do_rename : Optional[bool] If True, Agents are renamed based on their mapped grounding. grounding_map : Optional[dict] A user supplied grounding map which maps a string to a dictionary of database IDs (in the format used by Agents' db_refs). use_deft : Optional[bool] If True, Deft will be attempted to be used for acronym disambiguation. Default: True save : Optional[str] The name of a pickle file to save the results (stmts_out) into. Returns ------- stmts_out : list[indra.statements.Statement] A list of mapped statements. """ from indra.preassembler.grounding_mapper import GroundingMapper from indra.preassembler.grounding_mapper import gm as grounding_map from indra.preassembler.grounding_mapper import \ default_agent_map as agent_map logger.info('Mapping grounding on %d statements...' % len(stmts_in)) do_rename = kwargs.get('do_rename') gm = kwargs.get('grounding_map', grounding_map) if do_rename is None: do_rename = True gm = GroundingMapper(gm, agent_map, use_deft=kwargs.get('use_deft', True)) stmts_out = gm.map_agents(stmts_in, do_rename=do_rename) dump_pkl = kwargs.get('save') if dump_pkl: dump_statements(stmts_out, dump_pkl) return stmts_out
python
def map_grounding(stmts_in, **kwargs): from indra.preassembler.grounding_mapper import GroundingMapper from indra.preassembler.grounding_mapper import gm as grounding_map from indra.preassembler.grounding_mapper import \ default_agent_map as agent_map logger.info('Mapping grounding on %d statements...' % len(stmts_in)) do_rename = kwargs.get('do_rename') gm = kwargs.get('grounding_map', grounding_map) if do_rename is None: do_rename = True gm = GroundingMapper(gm, agent_map, use_deft=kwargs.get('use_deft', True)) stmts_out = gm.map_agents(stmts_in, do_rename=do_rename) dump_pkl = kwargs.get('save') if dump_pkl: dump_statements(stmts_out, dump_pkl) return stmts_out
[ "def", "map_grounding", "(", "stmts_in", ",", "*", "*", "kwargs", ")", ":", "from", "indra", ".", "preassembler", ".", "grounding_mapper", "import", "GroundingMapper", "from", "indra", ".", "preassembler", ".", "grounding_mapper", "import", "gm", "as", "groundin...
Map grounding using the GroundingMapper. Parameters ---------- stmts_in : list[indra.statements.Statement] A list of statements to map. do_rename : Optional[bool] If True, Agents are renamed based on their mapped grounding. grounding_map : Optional[dict] A user supplied grounding map which maps a string to a dictionary of database IDs (in the format used by Agents' db_refs). use_deft : Optional[bool] If True, Deft will be attempted to be used for acronym disambiguation. Default: True save : Optional[str] The name of a pickle file to save the results (stmts_out) into. Returns ------- stmts_out : list[indra.statements.Statement] A list of mapped statements.
[ "Map", "grounding", "using", "the", "GroundingMapper", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/assemble_corpus.py#L81-L119
19,204
sorgerlab/indra
indra/tools/assemble_corpus.py
merge_groundings
def merge_groundings(stmts_in): """Gather and merge original grounding information from evidences. Each Statement's evidences are traversed to find original grounding information. These groundings are then merged into an overall consensus grounding dict with as much detail as possible. The current implementation is only applicable to Statements whose concept/agent roles are fixed. Complexes, Associations and Conversions cannot be handled correctly. Parameters ---------- stmts_in : list[indra.statements.Statement] A list of INDRA Statements whose groundings should be merged. These Statements are meant to have been preassembled and potentially have multiple pieces of evidence. Returns ------- stmts_out : list[indra.statements.Statement] The list of Statements now with groundings merged at the Statement level. """ def surface_grounding(stmt): # Find the "best" grounding for a given concept and its evidences # and surface that for idx, concept in enumerate(stmt.agent_list()): if concept is None: continue aggregate_groundings = {} for ev in stmt.evidence: if 'agents' in ev.annotations: groundings = ev.annotations['agents']['raw_grounding'][idx] for ns, value in groundings.items(): if ns not in aggregate_groundings: aggregate_groundings[ns] = [] if isinstance(value, list): aggregate_groundings[ns] += value else: aggregate_groundings[ns].append(value) best_groundings = get_best_groundings(aggregate_groundings) concept.db_refs = best_groundings def get_best_groundings(aggregate_groundings): best_groundings = {} for ns, values in aggregate_groundings.items(): # There are 3 possibilities here # 1. All the entries in the list are scored in which case we # get unique entries and sort them by score if all([isinstance(v, (tuple, list)) for v in values]): best_groundings[ns] = [] for unique_value in {v[0] for v in values}: scores = [v[1] for v in values if v[0] == unique_value] best_groundings[ns].append((unique_value, max(scores))) best_groundings[ns] = \ sorted(best_groundings[ns], key=lambda x: x[1], reverse=True) # 2. All the entries in the list are unscored in which case we # get the highest frequency entry elif all([not isinstance(v, (tuple, list)) for v in values]): best_groundings[ns] = max(set(values), key=values.count) # 3. There is a mixture, which can happen when some entries were # mapped with scores and others had no scores to begin with. # In this case, we again pick the highest frequency non-scored # entry assuming that the unmapped version is more reliable. else: unscored_vals = [v for v in values if not isinstance(v, (tuple, list))] best_groundings[ns] = max(set(unscored_vals), key=unscored_vals.count) return best_groundings stmts_out = [] for stmt in stmts_in: if not isinstance(stmt, (Complex, Conversion)): surface_grounding(stmt) stmts_out.append(stmt) return stmts_out
python
def merge_groundings(stmts_in): def surface_grounding(stmt): # Find the "best" grounding for a given concept and its evidences # and surface that for idx, concept in enumerate(stmt.agent_list()): if concept is None: continue aggregate_groundings = {} for ev in stmt.evidence: if 'agents' in ev.annotations: groundings = ev.annotations['agents']['raw_grounding'][idx] for ns, value in groundings.items(): if ns not in aggregate_groundings: aggregate_groundings[ns] = [] if isinstance(value, list): aggregate_groundings[ns] += value else: aggregate_groundings[ns].append(value) best_groundings = get_best_groundings(aggregate_groundings) concept.db_refs = best_groundings def get_best_groundings(aggregate_groundings): best_groundings = {} for ns, values in aggregate_groundings.items(): # There are 3 possibilities here # 1. All the entries in the list are scored in which case we # get unique entries and sort them by score if all([isinstance(v, (tuple, list)) for v in values]): best_groundings[ns] = [] for unique_value in {v[0] for v in values}: scores = [v[1] for v in values if v[0] == unique_value] best_groundings[ns].append((unique_value, max(scores))) best_groundings[ns] = \ sorted(best_groundings[ns], key=lambda x: x[1], reverse=True) # 2. All the entries in the list are unscored in which case we # get the highest frequency entry elif all([not isinstance(v, (tuple, list)) for v in values]): best_groundings[ns] = max(set(values), key=values.count) # 3. There is a mixture, which can happen when some entries were # mapped with scores and others had no scores to begin with. # In this case, we again pick the highest frequency non-scored # entry assuming that the unmapped version is more reliable. else: unscored_vals = [v for v in values if not isinstance(v, (tuple, list))] best_groundings[ns] = max(set(unscored_vals), key=unscored_vals.count) return best_groundings stmts_out = [] for stmt in stmts_in: if not isinstance(stmt, (Complex, Conversion)): surface_grounding(stmt) stmts_out.append(stmt) return stmts_out
[ "def", "merge_groundings", "(", "stmts_in", ")", ":", "def", "surface_grounding", "(", "stmt", ")", ":", "# Find the \"best\" grounding for a given concept and its evidences", "# and surface that", "for", "idx", ",", "concept", "in", "enumerate", "(", "stmt", ".", "agen...
Gather and merge original grounding information from evidences. Each Statement's evidences are traversed to find original grounding information. These groundings are then merged into an overall consensus grounding dict with as much detail as possible. The current implementation is only applicable to Statements whose concept/agent roles are fixed. Complexes, Associations and Conversions cannot be handled correctly. Parameters ---------- stmts_in : list[indra.statements.Statement] A list of INDRA Statements whose groundings should be merged. These Statements are meant to have been preassembled and potentially have multiple pieces of evidence. Returns ------- stmts_out : list[indra.statements.Statement] The list of Statements now with groundings merged at the Statement level.
[ "Gather", "and", "merge", "original", "grounding", "information", "from", "evidences", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/assemble_corpus.py#L122-L201
19,205
sorgerlab/indra
indra/tools/assemble_corpus.py
merge_deltas
def merge_deltas(stmts_in): """Gather and merge original Influence delta information from evidence. This function is only applicable to Influence Statements that have subj and obj deltas. All other statement types are passed through unchanged. Polarities and adjectives for subjects and objects respectivey are collected and merged by travesrsing all evidences of a Statement. Parameters ---------- stmts_in : list[indra.statements.Statement] A list of INDRA Statements whose influence deltas should be merged. These Statements are meant to have been preassembled and potentially have multiple pieces of evidence. Returns ------- stmts_out : list[indra.statements.Statement] The list of Statements now with deltas merged at the Statement level. """ stmts_out = [] for stmt in stmts_in: # This operation is only applicable to Influences if not isinstance(stmt, Influence): stmts_out.append(stmt) continue # At this point this is guaranteed to be an Influence deltas = {} for role in ('subj', 'obj'): for info in ('polarity', 'adjectives'): key = (role, info) deltas[key] = [] for ev in stmt.evidence: entry = ev.annotations.get('%s_%s' % key) deltas[key].append(entry if entry else None) # POLARITY # For polarity we need to work in pairs polarity_pairs = list(zip(deltas[('subj', 'polarity')], deltas[('obj', 'polarity')])) # If we have some fully defined pairs, we take the most common one both_pols = [pair for pair in polarity_pairs if pair[0] is not None and pair[1] is not None] if both_pols: subj_pol, obj_pol = max(set(both_pols), key=both_pols.count) stmt.subj.delta['polarity'] = subj_pol stmt.obj.delta['polarity'] = obj_pol # Otherwise we prefer the case when at least one entry of the # pair is given else: one_pol = [pair for pair in polarity_pairs if pair[0] is not None or pair[1] is not None] if one_pol: subj_pol, obj_pol = max(set(one_pol), key=one_pol.count) stmt.subj.delta['polarity'] = subj_pol stmt.obj.delta['polarity'] = obj_pol # ADJECTIVES for attr, role in ((stmt.subj.delta, 'subj'), (stmt.obj.delta, 'obj')): all_adjectives = [] for adj in deltas[(role, 'adjectives')]: if isinstance(adj, list): all_adjectives += adj elif adj is not None: all_adjectives.append(adj) attr['adjectives'] = all_adjectives stmts_out.append(stmt) return stmts_out
python
def merge_deltas(stmts_in): stmts_out = [] for stmt in stmts_in: # This operation is only applicable to Influences if not isinstance(stmt, Influence): stmts_out.append(stmt) continue # At this point this is guaranteed to be an Influence deltas = {} for role in ('subj', 'obj'): for info in ('polarity', 'adjectives'): key = (role, info) deltas[key] = [] for ev in stmt.evidence: entry = ev.annotations.get('%s_%s' % key) deltas[key].append(entry if entry else None) # POLARITY # For polarity we need to work in pairs polarity_pairs = list(zip(deltas[('subj', 'polarity')], deltas[('obj', 'polarity')])) # If we have some fully defined pairs, we take the most common one both_pols = [pair for pair in polarity_pairs if pair[0] is not None and pair[1] is not None] if both_pols: subj_pol, obj_pol = max(set(both_pols), key=both_pols.count) stmt.subj.delta['polarity'] = subj_pol stmt.obj.delta['polarity'] = obj_pol # Otherwise we prefer the case when at least one entry of the # pair is given else: one_pol = [pair for pair in polarity_pairs if pair[0] is not None or pair[1] is not None] if one_pol: subj_pol, obj_pol = max(set(one_pol), key=one_pol.count) stmt.subj.delta['polarity'] = subj_pol stmt.obj.delta['polarity'] = obj_pol # ADJECTIVES for attr, role in ((stmt.subj.delta, 'subj'), (stmt.obj.delta, 'obj')): all_adjectives = [] for adj in deltas[(role, 'adjectives')]: if isinstance(adj, list): all_adjectives += adj elif adj is not None: all_adjectives.append(adj) attr['adjectives'] = all_adjectives stmts_out.append(stmt) return stmts_out
[ "def", "merge_deltas", "(", "stmts_in", ")", ":", "stmts_out", "=", "[", "]", "for", "stmt", "in", "stmts_in", ":", "# This operation is only applicable to Influences", "if", "not", "isinstance", "(", "stmt", ",", "Influence", ")", ":", "stmts_out", ".", "append...
Gather and merge original Influence delta information from evidence. This function is only applicable to Influence Statements that have subj and obj deltas. All other statement types are passed through unchanged. Polarities and adjectives for subjects and objects respectivey are collected and merged by travesrsing all evidences of a Statement. Parameters ---------- stmts_in : list[indra.statements.Statement] A list of INDRA Statements whose influence deltas should be merged. These Statements are meant to have been preassembled and potentially have multiple pieces of evidence. Returns ------- stmts_out : list[indra.statements.Statement] The list of Statements now with deltas merged at the Statement level.
[ "Gather", "and", "merge", "original", "Influence", "delta", "information", "from", "evidence", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/assemble_corpus.py#L204-L272
19,206
sorgerlab/indra
indra/tools/assemble_corpus.py
map_sequence
def map_sequence(stmts_in, **kwargs): """Map sequences using the SiteMapper. Parameters ---------- stmts_in : list[indra.statements.Statement] A list of statements to map. do_methionine_offset : boolean Whether to check for off-by-one errors in site position (possibly) attributable to site numbering from mature proteins after cleavage of the initial methionine. If True, checks the reference sequence for a known modification at 1 site position greater than the given one; if there exists such a site, creates the mapping. Default is True. do_orthology_mapping : boolean Whether to check sequence positions for known modification sites in mouse or rat sequences (based on PhosphoSitePlus data). If a mouse/rat site is found that is linked to a site in the human reference sequence, a mapping is created. Default is True. do_isoform_mapping : boolean Whether to check sequence positions for known modifications in other human isoforms of the protein (based on PhosphoSitePlus data). If a site is found that is linked to a site in the human reference sequence, a mapping is created. Default is True. use_cache : boolean If True, a cache will be created/used from the laction specified by SITEMAPPER_CACHE_PATH, defined in your INDRA config or the environment. If False, no cache is used. For more details on the cache, see the SiteMapper class definition. save : Optional[str] The name of a pickle file to save the results (stmts_out) into. Returns ------- stmts_out : list[indra.statements.Statement] A list of mapped statements. """ from indra.preassembler.sitemapper import SiteMapper, default_site_map logger.info('Mapping sites on %d statements...' % len(stmts_in)) kwarg_list = ['do_methionine_offset', 'do_orthology_mapping', 'do_isoform_mapping'] sm = SiteMapper(default_site_map, use_cache=kwargs.pop('use_cache', False), **_filter(kwargs, kwarg_list)) valid, mapped = sm.map_sites(stmts_in) correctly_mapped_stmts = [] for ms in mapped: correctly_mapped = all([mm.has_mapping() for mm in ms.mapped_mods]) if correctly_mapped: correctly_mapped_stmts.append(ms.mapped_stmt) stmts_out = valid + correctly_mapped_stmts logger.info('%d statements with valid sites' % len(stmts_out)) dump_pkl = kwargs.get('save') if dump_pkl: dump_statements(stmts_out, dump_pkl) del sm return stmts_out
python
def map_sequence(stmts_in, **kwargs): from indra.preassembler.sitemapper import SiteMapper, default_site_map logger.info('Mapping sites on %d statements...' % len(stmts_in)) kwarg_list = ['do_methionine_offset', 'do_orthology_mapping', 'do_isoform_mapping'] sm = SiteMapper(default_site_map, use_cache=kwargs.pop('use_cache', False), **_filter(kwargs, kwarg_list)) valid, mapped = sm.map_sites(stmts_in) correctly_mapped_stmts = [] for ms in mapped: correctly_mapped = all([mm.has_mapping() for mm in ms.mapped_mods]) if correctly_mapped: correctly_mapped_stmts.append(ms.mapped_stmt) stmts_out = valid + correctly_mapped_stmts logger.info('%d statements with valid sites' % len(stmts_out)) dump_pkl = kwargs.get('save') if dump_pkl: dump_statements(stmts_out, dump_pkl) del sm return stmts_out
[ "def", "map_sequence", "(", "stmts_in", ",", "*", "*", "kwargs", ")", ":", "from", "indra", ".", "preassembler", ".", "sitemapper", "import", "SiteMapper", ",", "default_site_map", "logger", ".", "info", "(", "'Mapping sites on %d statements...'", "%", "len", "(...
Map sequences using the SiteMapper. Parameters ---------- stmts_in : list[indra.statements.Statement] A list of statements to map. do_methionine_offset : boolean Whether to check for off-by-one errors in site position (possibly) attributable to site numbering from mature proteins after cleavage of the initial methionine. If True, checks the reference sequence for a known modification at 1 site position greater than the given one; if there exists such a site, creates the mapping. Default is True. do_orthology_mapping : boolean Whether to check sequence positions for known modification sites in mouse or rat sequences (based on PhosphoSitePlus data). If a mouse/rat site is found that is linked to a site in the human reference sequence, a mapping is created. Default is True. do_isoform_mapping : boolean Whether to check sequence positions for known modifications in other human isoforms of the protein (based on PhosphoSitePlus data). If a site is found that is linked to a site in the human reference sequence, a mapping is created. Default is True. use_cache : boolean If True, a cache will be created/used from the laction specified by SITEMAPPER_CACHE_PATH, defined in your INDRA config or the environment. If False, no cache is used. For more details on the cache, see the SiteMapper class definition. save : Optional[str] The name of a pickle file to save the results (stmts_out) into. Returns ------- stmts_out : list[indra.statements.Statement] A list of mapped statements.
[ "Map", "sequences", "using", "the", "SiteMapper", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/assemble_corpus.py#L275-L331
19,207
sorgerlab/indra
indra/tools/assemble_corpus.py
run_preassembly
def run_preassembly(stmts_in, **kwargs): """Run preassembly on a list of statements. Parameters ---------- stmts_in : list[indra.statements.Statement] A list of statements to preassemble. return_toplevel : Optional[bool] If True, only the top-level statements are returned. If False, all statements are returned irrespective of level of specificity. Default: True poolsize : Optional[int] The number of worker processes to use to parallelize the comparisons performed by the function. If None (default), no parallelization is performed. NOTE: Parallelization is only available on Python 3.4 and above. size_cutoff : Optional[int] Groups with size_cutoff or more statements are sent to worker processes, while smaller groups are compared in the parent process. Default value is 100. Not relevant when parallelization is not used. belief_scorer : Optional[indra.belief.BeliefScorer] Instance of BeliefScorer class to use in calculating Statement probabilities. If None is provided (default), then the default scorer is used. hierarchies : Optional[dict] Dict of hierarchy managers to use for preassembly flatten_evidence : Optional[bool] If True, evidences are collected and flattened via supports/supported_by links. Default: False flatten_evidence_collect_from : Optional[str] String indicating whether to collect and flatten evidence from the `supports` attribute of each statement or the `supported_by` attribute. If not set, defaults to 'supported_by'. Only relevant when flatten_evidence is True. save : Optional[str] The name of a pickle file to save the results (stmts_out) into. save_unique : Optional[str] The name of a pickle file to save the unique statements into. Returns ------- stmts_out : list[indra.statements.Statement] A list of preassembled top-level statements. """ dump_pkl_unique = kwargs.get('save_unique') belief_scorer = kwargs.get('belief_scorer') use_hierarchies = kwargs['hierarchies'] if 'hierarchies' in kwargs else \ hierarchies be = BeliefEngine(scorer=belief_scorer) pa = Preassembler(hierarchies, stmts_in) run_preassembly_duplicate(pa, be, save=dump_pkl_unique) dump_pkl = kwargs.get('save') return_toplevel = kwargs.get('return_toplevel', True) poolsize = kwargs.get('poolsize', None) size_cutoff = kwargs.get('size_cutoff', 100) options = {'save': dump_pkl, 'return_toplevel': return_toplevel, 'poolsize': poolsize, 'size_cutoff': size_cutoff, 'flatten_evidence': kwargs.get('flatten_evidence', False), 'flatten_evidence_collect_from': kwargs.get('flatten_evidence_collect_from', 'supported_by') } stmts_out = run_preassembly_related(pa, be, **options) return stmts_out
python
def run_preassembly(stmts_in, **kwargs): dump_pkl_unique = kwargs.get('save_unique') belief_scorer = kwargs.get('belief_scorer') use_hierarchies = kwargs['hierarchies'] if 'hierarchies' in kwargs else \ hierarchies be = BeliefEngine(scorer=belief_scorer) pa = Preassembler(hierarchies, stmts_in) run_preassembly_duplicate(pa, be, save=dump_pkl_unique) dump_pkl = kwargs.get('save') return_toplevel = kwargs.get('return_toplevel', True) poolsize = kwargs.get('poolsize', None) size_cutoff = kwargs.get('size_cutoff', 100) options = {'save': dump_pkl, 'return_toplevel': return_toplevel, 'poolsize': poolsize, 'size_cutoff': size_cutoff, 'flatten_evidence': kwargs.get('flatten_evidence', False), 'flatten_evidence_collect_from': kwargs.get('flatten_evidence_collect_from', 'supported_by') } stmts_out = run_preassembly_related(pa, be, **options) return stmts_out
[ "def", "run_preassembly", "(", "stmts_in", ",", "*", "*", "kwargs", ")", ":", "dump_pkl_unique", "=", "kwargs", ".", "get", "(", "'save_unique'", ")", "belief_scorer", "=", "kwargs", ".", "get", "(", "'belief_scorer'", ")", "use_hierarchies", "=", "kwargs", ...
Run preassembly on a list of statements. Parameters ---------- stmts_in : list[indra.statements.Statement] A list of statements to preassemble. return_toplevel : Optional[bool] If True, only the top-level statements are returned. If False, all statements are returned irrespective of level of specificity. Default: True poolsize : Optional[int] The number of worker processes to use to parallelize the comparisons performed by the function. If None (default), no parallelization is performed. NOTE: Parallelization is only available on Python 3.4 and above. size_cutoff : Optional[int] Groups with size_cutoff or more statements are sent to worker processes, while smaller groups are compared in the parent process. Default value is 100. Not relevant when parallelization is not used. belief_scorer : Optional[indra.belief.BeliefScorer] Instance of BeliefScorer class to use in calculating Statement probabilities. If None is provided (default), then the default scorer is used. hierarchies : Optional[dict] Dict of hierarchy managers to use for preassembly flatten_evidence : Optional[bool] If True, evidences are collected and flattened via supports/supported_by links. Default: False flatten_evidence_collect_from : Optional[str] String indicating whether to collect and flatten evidence from the `supports` attribute of each statement or the `supported_by` attribute. If not set, defaults to 'supported_by'. Only relevant when flatten_evidence is True. save : Optional[str] The name of a pickle file to save the results (stmts_out) into. save_unique : Optional[str] The name of a pickle file to save the unique statements into. Returns ------- stmts_out : list[indra.statements.Statement] A list of preassembled top-level statements.
[ "Run", "preassembly", "on", "a", "list", "of", "statements", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/assemble_corpus.py#L334-L398
19,208
sorgerlab/indra
indra/tools/assemble_corpus.py
run_preassembly_duplicate
def run_preassembly_duplicate(preassembler, beliefengine, **kwargs): """Run deduplication stage of preassembly on a list of statements. Parameters ---------- preassembler : indra.preassembler.Preassembler A Preassembler instance beliefengine : indra.belief.BeliefEngine A BeliefEngine instance. save : Optional[str] The name of a pickle file to save the results (stmts_out) into. Returns ------- stmts_out : list[indra.statements.Statement] A list of unique statements. """ logger.info('Combining duplicates on %d statements...' % len(preassembler.stmts)) dump_pkl = kwargs.get('save') stmts_out = preassembler.combine_duplicates() beliefengine.set_prior_probs(stmts_out) logger.info('%d unique statements' % len(stmts_out)) if dump_pkl: dump_statements(stmts_out, dump_pkl) return stmts_out
python
def run_preassembly_duplicate(preassembler, beliefengine, **kwargs): logger.info('Combining duplicates on %d statements...' % len(preassembler.stmts)) dump_pkl = kwargs.get('save') stmts_out = preassembler.combine_duplicates() beliefengine.set_prior_probs(stmts_out) logger.info('%d unique statements' % len(stmts_out)) if dump_pkl: dump_statements(stmts_out, dump_pkl) return stmts_out
[ "def", "run_preassembly_duplicate", "(", "preassembler", ",", "beliefengine", ",", "*", "*", "kwargs", ")", ":", "logger", ".", "info", "(", "'Combining duplicates on %d statements...'", "%", "len", "(", "preassembler", ".", "stmts", ")", ")", "dump_pkl", "=", "...
Run deduplication stage of preassembly on a list of statements. Parameters ---------- preassembler : indra.preassembler.Preassembler A Preassembler instance beliefengine : indra.belief.BeliefEngine A BeliefEngine instance. save : Optional[str] The name of a pickle file to save the results (stmts_out) into. Returns ------- stmts_out : list[indra.statements.Statement] A list of unique statements.
[ "Run", "deduplication", "stage", "of", "preassembly", "on", "a", "list", "of", "statements", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/assemble_corpus.py#L401-L426
19,209
sorgerlab/indra
indra/tools/assemble_corpus.py
run_preassembly_related
def run_preassembly_related(preassembler, beliefengine, **kwargs): """Run related stage of preassembly on a list of statements. Parameters ---------- preassembler : indra.preassembler.Preassembler A Preassembler instance which already has a set of unique statements internally. beliefengine : indra.belief.BeliefEngine A BeliefEngine instance. return_toplevel : Optional[bool] If True, only the top-level statements are returned. If False, all statements are returned irrespective of level of specificity. Default: True poolsize : Optional[int] The number of worker processes to use to parallelize the comparisons performed by the function. If None (default), no parallelization is performed. NOTE: Parallelization is only available on Python 3.4 and above. size_cutoff : Optional[int] Groups with size_cutoff or more statements are sent to worker processes, while smaller groups are compared in the parent process. Default value is 100. Not relevant when parallelization is not used. flatten_evidence : Optional[bool] If True, evidences are collected and flattened via supports/supported_by links. Default: False flatten_evidence_collect_from : Optional[str] String indicating whether to collect and flatten evidence from the `supports` attribute of each statement or the `supported_by` attribute. If not set, defaults to 'supported_by'. Only relevant when flatten_evidence is True. save : Optional[str] The name of a pickle file to save the results (stmts_out) into. Returns ------- stmts_out : list[indra.statements.Statement] A list of preassembled top-level statements. """ logger.info('Combining related on %d statements...' % len(preassembler.unique_stmts)) return_toplevel = kwargs.get('return_toplevel', True) poolsize = kwargs.get('poolsize', None) size_cutoff = kwargs.get('size_cutoff', 100) stmts_out = preassembler.combine_related(return_toplevel=False, poolsize=poolsize, size_cutoff=size_cutoff) # Calculate beliefs beliefengine.set_hierarchy_probs(stmts_out) # Flatten evidence if needed do_flatten_evidence = kwargs.get('flatten_evidence', False) if do_flatten_evidence: flatten_evidences_collect_from = \ kwargs.get('flatten_evidence_collect_from', 'supported_by') stmts_out = flatten_evidence(stmts_out, flatten_evidences_collect_from) # Filter to top if needed stmts_top = filter_top_level(stmts_out) if return_toplevel: stmts_out = stmts_top logger.info('%d top-level statements' % len(stmts_out)) else: logger.info('%d statements out of which %d are top-level' % (len(stmts_out), len(stmts_top))) dump_pkl = kwargs.get('save') if dump_pkl: dump_statements(stmts_out, dump_pkl) return stmts_out
python
def run_preassembly_related(preassembler, beliefengine, **kwargs): logger.info('Combining related on %d statements...' % len(preassembler.unique_stmts)) return_toplevel = kwargs.get('return_toplevel', True) poolsize = kwargs.get('poolsize', None) size_cutoff = kwargs.get('size_cutoff', 100) stmts_out = preassembler.combine_related(return_toplevel=False, poolsize=poolsize, size_cutoff=size_cutoff) # Calculate beliefs beliefengine.set_hierarchy_probs(stmts_out) # Flatten evidence if needed do_flatten_evidence = kwargs.get('flatten_evidence', False) if do_flatten_evidence: flatten_evidences_collect_from = \ kwargs.get('flatten_evidence_collect_from', 'supported_by') stmts_out = flatten_evidence(stmts_out, flatten_evidences_collect_from) # Filter to top if needed stmts_top = filter_top_level(stmts_out) if return_toplevel: stmts_out = stmts_top logger.info('%d top-level statements' % len(stmts_out)) else: logger.info('%d statements out of which %d are top-level' % (len(stmts_out), len(stmts_top))) dump_pkl = kwargs.get('save') if dump_pkl: dump_statements(stmts_out, dump_pkl) return stmts_out
[ "def", "run_preassembly_related", "(", "preassembler", ",", "beliefengine", ",", "*", "*", "kwargs", ")", ":", "logger", ".", "info", "(", "'Combining related on %d statements...'", "%", "len", "(", "preassembler", ".", "unique_stmts", ")", ")", "return_toplevel", ...
Run related stage of preassembly on a list of statements. Parameters ---------- preassembler : indra.preassembler.Preassembler A Preassembler instance which already has a set of unique statements internally. beliefengine : indra.belief.BeliefEngine A BeliefEngine instance. return_toplevel : Optional[bool] If True, only the top-level statements are returned. If False, all statements are returned irrespective of level of specificity. Default: True poolsize : Optional[int] The number of worker processes to use to parallelize the comparisons performed by the function. If None (default), no parallelization is performed. NOTE: Parallelization is only available on Python 3.4 and above. size_cutoff : Optional[int] Groups with size_cutoff or more statements are sent to worker processes, while smaller groups are compared in the parent process. Default value is 100. Not relevant when parallelization is not used. flatten_evidence : Optional[bool] If True, evidences are collected and flattened via supports/supported_by links. Default: False flatten_evidence_collect_from : Optional[str] String indicating whether to collect and flatten evidence from the `supports` attribute of each statement or the `supported_by` attribute. If not set, defaults to 'supported_by'. Only relevant when flatten_evidence is True. save : Optional[str] The name of a pickle file to save the results (stmts_out) into. Returns ------- stmts_out : list[indra.statements.Statement] A list of preassembled top-level statements.
[ "Run", "related", "stage", "of", "preassembly", "on", "a", "list", "of", "statements", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/assemble_corpus.py#L429-L499
19,210
sorgerlab/indra
indra/tools/assemble_corpus.py
filter_by_type
def filter_by_type(stmts_in, stmt_type, **kwargs): """Filter to a given statement type. Parameters ---------- stmts_in : list[indra.statements.Statement] A list of statements to filter. stmt_type : indra.statements.Statement The class of the statement type to filter for. Example: indra.statements.Modification invert : Optional[bool] If True, the statements that are not of the given type are returned. Default: False save : Optional[str] The name of a pickle file to save the results (stmts_out) into. Returns ------- stmts_out : list[indra.statements.Statement] A list of filtered statements. """ invert = kwargs.get('invert', False) logger.info('Filtering %d statements for type %s%s...' % (len(stmts_in), 'not ' if invert else '', stmt_type.__name__)) if not invert: stmts_out = [st for st in stmts_in if isinstance(st, stmt_type)] else: stmts_out = [st for st in stmts_in if not isinstance(st, stmt_type)] logger.info('%d statements after filter...' % len(stmts_out)) dump_pkl = kwargs.get('save') if dump_pkl: dump_statements(stmts_out, dump_pkl) return stmts_out
python
def filter_by_type(stmts_in, stmt_type, **kwargs): invert = kwargs.get('invert', False) logger.info('Filtering %d statements for type %s%s...' % (len(stmts_in), 'not ' if invert else '', stmt_type.__name__)) if not invert: stmts_out = [st for st in stmts_in if isinstance(st, stmt_type)] else: stmts_out = [st for st in stmts_in if not isinstance(st, stmt_type)] logger.info('%d statements after filter...' % len(stmts_out)) dump_pkl = kwargs.get('save') if dump_pkl: dump_statements(stmts_out, dump_pkl) return stmts_out
[ "def", "filter_by_type", "(", "stmts_in", ",", "stmt_type", ",", "*", "*", "kwargs", ")", ":", "invert", "=", "kwargs", ".", "get", "(", "'invert'", ",", "False", ")", "logger", ".", "info", "(", "'Filtering %d statements for type %s%s...'", "%", "(", "len",...
Filter to a given statement type. Parameters ---------- stmts_in : list[indra.statements.Statement] A list of statements to filter. stmt_type : indra.statements.Statement The class of the statement type to filter for. Example: indra.statements.Modification invert : Optional[bool] If True, the statements that are not of the given type are returned. Default: False save : Optional[str] The name of a pickle file to save the results (stmts_out) into. Returns ------- stmts_out : list[indra.statements.Statement] A list of filtered statements.
[ "Filter", "to", "a", "given", "statement", "type", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/assemble_corpus.py#L502-L536
19,211
sorgerlab/indra
indra/tools/assemble_corpus.py
_remove_bound_conditions
def _remove_bound_conditions(agent, keep_criterion): """Removes bound conditions of agent such that keep_criterion is False. Parameters ---------- agent: Agent The agent whose bound conditions we evaluate keep_criterion: function Evaluates removal_criterion(a) for each agent a in a bound condition and if it evaluates to False, removes a from agent's bound_conditions """ new_bc = [] for ind in range(len(agent.bound_conditions)): if keep_criterion(agent.bound_conditions[ind].agent): new_bc.append(agent.bound_conditions[ind]) agent.bound_conditions = new_bc
python
def _remove_bound_conditions(agent, keep_criterion): new_bc = [] for ind in range(len(agent.bound_conditions)): if keep_criterion(agent.bound_conditions[ind].agent): new_bc.append(agent.bound_conditions[ind]) agent.bound_conditions = new_bc
[ "def", "_remove_bound_conditions", "(", "agent", ",", "keep_criterion", ")", ":", "new_bc", "=", "[", "]", "for", "ind", "in", "range", "(", "len", "(", "agent", ".", "bound_conditions", ")", ")", ":", "if", "keep_criterion", "(", "agent", ".", "bound_cond...
Removes bound conditions of agent such that keep_criterion is False. Parameters ---------- agent: Agent The agent whose bound conditions we evaluate keep_criterion: function Evaluates removal_criterion(a) for each agent a in a bound condition and if it evaluates to False, removes a from agent's bound_conditions
[ "Removes", "bound", "conditions", "of", "agent", "such", "that", "keep_criterion", "is", "False", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/assemble_corpus.py#L566-L581
19,212
sorgerlab/indra
indra/tools/assemble_corpus.py
_any_bound_condition_fails_criterion
def _any_bound_condition_fails_criterion(agent, criterion): """Returns True if any bound condition fails to meet the specified criterion. Parameters ---------- agent: Agent The agent whose bound conditions we evaluate criterion: function Evaluates criterion(a) for each a in a bound condition and returns True if any agents fail to meet the criterion. Returns ------- any_meets: bool True if and only if any of the agents in a bound condition fail to match the specified criteria """ bc_agents = [bc.agent for bc in agent.bound_conditions] for b in bc_agents: if not criterion(b): return True return False
python
def _any_bound_condition_fails_criterion(agent, criterion): bc_agents = [bc.agent for bc in agent.bound_conditions] for b in bc_agents: if not criterion(b): return True return False
[ "def", "_any_bound_condition_fails_criterion", "(", "agent", ",", "criterion", ")", ":", "bc_agents", "=", "[", "bc", ".", "agent", "for", "bc", "in", "agent", ".", "bound_conditions", "]", "for", "b", "in", "bc_agents", ":", "if", "not", "criterion", "(", ...
Returns True if any bound condition fails to meet the specified criterion. Parameters ---------- agent: Agent The agent whose bound conditions we evaluate criterion: function Evaluates criterion(a) for each a in a bound condition and returns True if any agents fail to meet the criterion. Returns ------- any_meets: bool True if and only if any of the agents in a bound condition fail to match the specified criteria
[ "Returns", "True", "if", "any", "bound", "condition", "fails", "to", "meet", "the", "specified", "criterion", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/assemble_corpus.py#L584-L606
19,213
sorgerlab/indra
indra/tools/assemble_corpus.py
filter_grounded_only
def filter_grounded_only(stmts_in, **kwargs): """Filter to statements that have grounded agents. Parameters ---------- stmts_in : list[indra.statements.Statement] A list of statements to filter. score_threshold : Optional[float] If scored groundings are available in a list and the highest score if below this threshold, the Statement is filtered out. save : Optional[str] The name of a pickle file to save the results (stmts_out) into. remove_bound: Optional[bool] If true, removes ungrounded bound conditions from a statement. If false (default), filters out statements with ungrounded bound conditions. Returns ------- stmts_out : list[indra.statements.Statement] A list of filtered statements. """ remove_bound = kwargs.get('remove_bound', False) logger.info('Filtering %d statements for grounded agents...' % len(stmts_in)) stmts_out = [] score_threshold = kwargs.get('score_threshold') for st in stmts_in: grounded = True for agent in st.agent_list(): if agent is not None: criterion = lambda x: _agent_is_grounded(x, score_threshold) if not criterion(agent): grounded = False break if not isinstance(agent, Agent): continue if remove_bound: _remove_bound_conditions(agent, criterion) elif _any_bound_condition_fails_criterion(agent, criterion): grounded = False break if grounded: stmts_out.append(st) logger.info('%d statements after filter...' % len(stmts_out)) dump_pkl = kwargs.get('save') if dump_pkl: dump_statements(stmts_out, dump_pkl) return stmts_out
python
def filter_grounded_only(stmts_in, **kwargs): remove_bound = kwargs.get('remove_bound', False) logger.info('Filtering %d statements for grounded agents...' % len(stmts_in)) stmts_out = [] score_threshold = kwargs.get('score_threshold') for st in stmts_in: grounded = True for agent in st.agent_list(): if agent is not None: criterion = lambda x: _agent_is_grounded(x, score_threshold) if not criterion(agent): grounded = False break if not isinstance(agent, Agent): continue if remove_bound: _remove_bound_conditions(agent, criterion) elif _any_bound_condition_fails_criterion(agent, criterion): grounded = False break if grounded: stmts_out.append(st) logger.info('%d statements after filter...' % len(stmts_out)) dump_pkl = kwargs.get('save') if dump_pkl: dump_statements(stmts_out, dump_pkl) return stmts_out
[ "def", "filter_grounded_only", "(", "stmts_in", ",", "*", "*", "kwargs", ")", ":", "remove_bound", "=", "kwargs", ".", "get", "(", "'remove_bound'", ",", "False", ")", "logger", ".", "info", "(", "'Filtering %d statements for grounded agents...'", "%", "len", "(...
Filter to statements that have grounded agents. Parameters ---------- stmts_in : list[indra.statements.Statement] A list of statements to filter. score_threshold : Optional[float] If scored groundings are available in a list and the highest score if below this threshold, the Statement is filtered out. save : Optional[str] The name of a pickle file to save the results (stmts_out) into. remove_bound: Optional[bool] If true, removes ungrounded bound conditions from a statement. If false (default), filters out statements with ungrounded bound conditions. Returns ------- stmts_out : list[indra.statements.Statement] A list of filtered statements.
[ "Filter", "to", "statements", "that", "have", "grounded", "agents", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/assemble_corpus.py#L609-L658
19,214
sorgerlab/indra
indra/tools/assemble_corpus.py
_agent_is_gene
def _agent_is_gene(agent, specific_only): """Returns whether an agent is for a gene. Parameters ---------- agent: Agent The agent to evaluate specific_only : Optional[bool] If True, only elementary genes/proteins evaluate as genes and families will be filtered out. If False, families are also included. Returns ------- is_gene: bool Whether the agent is a gene """ if not specific_only: if not(agent.db_refs.get('HGNC') or \ agent.db_refs.get('UP') or \ agent.db_refs.get('FPLX')): return False else: if not(agent.db_refs.get('HGNC') or \ agent.db_refs.get('UP')): return False return True
python
def _agent_is_gene(agent, specific_only): if not specific_only: if not(agent.db_refs.get('HGNC') or \ agent.db_refs.get('UP') or \ agent.db_refs.get('FPLX')): return False else: if not(agent.db_refs.get('HGNC') or \ agent.db_refs.get('UP')): return False return True
[ "def", "_agent_is_gene", "(", "agent", ",", "specific_only", ")", ":", "if", "not", "specific_only", ":", "if", "not", "(", "agent", ".", "db_refs", ".", "get", "(", "'HGNC'", ")", "or", "agent", ".", "db_refs", ".", "get", "(", "'UP'", ")", "or", "a...
Returns whether an agent is for a gene. Parameters ---------- agent: Agent The agent to evaluate specific_only : Optional[bool] If True, only elementary genes/proteins evaluate as genes and families will be filtered out. If False, families are also included. Returns ------- is_gene: bool Whether the agent is a gene
[ "Returns", "whether", "an", "agent", "is", "for", "a", "gene", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/assemble_corpus.py#L661-L686
19,215
sorgerlab/indra
indra/tools/assemble_corpus.py
filter_genes_only
def filter_genes_only(stmts_in, **kwargs): """Filter to statements containing genes only. Parameters ---------- stmts_in : list[indra.statements.Statement] A list of statements to filter. specific_only : Optional[bool] If True, only elementary genes/proteins will be kept and families will be filtered out. If False, families are also included in the output. Default: False save : Optional[str] The name of a pickle file to save the results (stmts_out) into. remove_bound: Optional[bool] If true, removes bound conditions that are not genes If false (default), filters out statements with non-gene bound conditions Returns ------- stmts_out : list[indra.statements.Statement] A list of filtered statements. """ remove_bound = 'remove_bound' in kwargs and kwargs['remove_bound'] specific_only = kwargs.get('specific_only') logger.info('Filtering %d statements for ones containing genes only...' % len(stmts_in)) stmts_out = [] for st in stmts_in: genes_only = True for agent in st.agent_list(): if agent is not None: criterion = lambda a: _agent_is_gene(a, specific_only) if not criterion(agent): genes_only = False break if remove_bound: _remove_bound_conditions(agent, criterion) else: if _any_bound_condition_fails_criterion(agent, criterion): genes_only = False break if genes_only: stmts_out.append(st) logger.info('%d statements after filter...' % len(stmts_out)) dump_pkl = kwargs.get('save') if dump_pkl: dump_statements(stmts_out, dump_pkl) return stmts_out
python
def filter_genes_only(stmts_in, **kwargs): remove_bound = 'remove_bound' in kwargs and kwargs['remove_bound'] specific_only = kwargs.get('specific_only') logger.info('Filtering %d statements for ones containing genes only...' % len(stmts_in)) stmts_out = [] for st in stmts_in: genes_only = True for agent in st.agent_list(): if agent is not None: criterion = lambda a: _agent_is_gene(a, specific_only) if not criterion(agent): genes_only = False break if remove_bound: _remove_bound_conditions(agent, criterion) else: if _any_bound_condition_fails_criterion(agent, criterion): genes_only = False break if genes_only: stmts_out.append(st) logger.info('%d statements after filter...' % len(stmts_out)) dump_pkl = kwargs.get('save') if dump_pkl: dump_statements(stmts_out, dump_pkl) return stmts_out
[ "def", "filter_genes_only", "(", "stmts_in", ",", "*", "*", "kwargs", ")", ":", "remove_bound", "=", "'remove_bound'", "in", "kwargs", "and", "kwargs", "[", "'remove_bound'", "]", "specific_only", "=", "kwargs", ".", "get", "(", "'specific_only'", ")", "logger...
Filter to statements containing genes only. Parameters ---------- stmts_in : list[indra.statements.Statement] A list of statements to filter. specific_only : Optional[bool] If True, only elementary genes/proteins will be kept and families will be filtered out. If False, families are also included in the output. Default: False save : Optional[str] The name of a pickle file to save the results (stmts_out) into. remove_bound: Optional[bool] If true, removes bound conditions that are not genes If false (default), filters out statements with non-gene bound conditions Returns ------- stmts_out : list[indra.statements.Statement] A list of filtered statements.
[ "Filter", "to", "statements", "containing", "genes", "only", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/assemble_corpus.py#L689-L739
19,216
sorgerlab/indra
indra/tools/assemble_corpus.py
filter_belief
def filter_belief(stmts_in, belief_cutoff, **kwargs): """Filter to statements with belief above a given cutoff. Parameters ---------- stmts_in : list[indra.statements.Statement] A list of statements to filter. belief_cutoff : float Only statements with belief above the belief_cutoff will be returned. Here 0 < belief_cutoff < 1. save : Optional[str] The name of a pickle file to save the results (stmts_out) into. Returns ------- stmts_out : list[indra.statements.Statement] A list of filtered statements. """ dump_pkl = kwargs.get('save') logger.info('Filtering %d statements to above %f belief' % (len(stmts_in), belief_cutoff)) # The first round of filtering is in the top-level list stmts_out = [] # Now we eliminate supports/supported-by for stmt in stmts_in: if stmt.belief < belief_cutoff: continue stmts_out.append(stmt) supp_by = [] supp = [] for st in stmt.supports: if st.belief >= belief_cutoff: supp.append(st) for st in stmt.supported_by: if st.belief >= belief_cutoff: supp_by.append(st) stmt.supports = supp stmt.supported_by = supp_by logger.info('%d statements after filter...' % len(stmts_out)) if dump_pkl: dump_statements(stmts_out, dump_pkl) return stmts_out
python
def filter_belief(stmts_in, belief_cutoff, **kwargs): dump_pkl = kwargs.get('save') logger.info('Filtering %d statements to above %f belief' % (len(stmts_in), belief_cutoff)) # The first round of filtering is in the top-level list stmts_out = [] # Now we eliminate supports/supported-by for stmt in stmts_in: if stmt.belief < belief_cutoff: continue stmts_out.append(stmt) supp_by = [] supp = [] for st in stmt.supports: if st.belief >= belief_cutoff: supp.append(st) for st in stmt.supported_by: if st.belief >= belief_cutoff: supp_by.append(st) stmt.supports = supp stmt.supported_by = supp_by logger.info('%d statements after filter...' % len(stmts_out)) if dump_pkl: dump_statements(stmts_out, dump_pkl) return stmts_out
[ "def", "filter_belief", "(", "stmts_in", ",", "belief_cutoff", ",", "*", "*", "kwargs", ")", ":", "dump_pkl", "=", "kwargs", ".", "get", "(", "'save'", ")", "logger", ".", "info", "(", "'Filtering %d statements to above %f belief'", "%", "(", "len", "(", "st...
Filter to statements with belief above a given cutoff. Parameters ---------- stmts_in : list[indra.statements.Statement] A list of statements to filter. belief_cutoff : float Only statements with belief above the belief_cutoff will be returned. Here 0 < belief_cutoff < 1. save : Optional[str] The name of a pickle file to save the results (stmts_out) into. Returns ------- stmts_out : list[indra.statements.Statement] A list of filtered statements.
[ "Filter", "to", "statements", "with", "belief", "above", "a", "given", "cutoff", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/assemble_corpus.py#L742-L783
19,217
sorgerlab/indra
indra/tools/assemble_corpus.py
filter_gene_list
def filter_gene_list(stmts_in, gene_list, policy, allow_families=False, **kwargs): """Return statements that contain genes given in a list. Parameters ---------- stmts_in : list[indra.statements.Statement] A list of statements to filter. gene_list : list[str] A list of gene symbols to filter for. policy : str The policy to apply when filtering for the list of genes. "one": keep statements that contain at least one of the list of genes and possibly others not in the list "all": keep statements that only contain genes given in the list allow_families : Optional[bool] Will include statements involving FamPlex families containing one of the genes in the gene list. Default: False save : Optional[str] The name of a pickle file to save the results (stmts_out) into. remove_bound: Optional[str] If true, removes bound conditions that are not genes in the list If false (default), looks at agents in the bound conditions in addition to those participating in the statement directly when applying the specified policy. invert : Optional[bool] If True, the statements that do not match according to the policy are returned. Default: False Returns ------- stmts_out : list[indra.statements.Statement] A list of filtered statements. """ invert = kwargs.get('invert', False) remove_bound = kwargs.get('remove_bound', False) if policy not in ('one', 'all'): logger.error('Policy %s is invalid, not applying filter.' % policy) else: genes_str = ', '.join(gene_list) inv_str = 'not ' if invert else '' logger.info(('Filtering %d statements for ones %scontaining "%s" of: ' '%s...') % (len(stmts_in), inv_str, policy, genes_str)) # If we're allowing families, make a list of all FamPlex IDs that # contain members of the gene list, and add them to the filter list filter_list = copy(gene_list) if allow_families: for hgnc_name in gene_list: gene_uri = hierarchies['entity'].get_uri('HGNC', hgnc_name) parents = hierarchies['entity'].get_parents(gene_uri) for par_uri in parents: ns, id = hierarchies['entity'].ns_id_from_uri(par_uri) filter_list.append(id) stmts_out = [] if remove_bound: # If requested, remove agents whose names are not in the list from # all bound conditions if not invert: keep_criterion = lambda a: a.name in filter_list else: keep_criterion = lambda a: a.name not in filter_list for st in stmts_in: for agent in st.agent_list(): _remove_bound_conditions(agent, keep_criterion) if policy == 'one': for st in stmts_in: found_gene = False if not remove_bound: agent_list = st.agent_list_with_bound_condition_agents() else: agent_list = st.agent_list() for agent in agent_list: if agent is not None: if agent.name in filter_list: found_gene = True break if (found_gene and not invert) or (not found_gene and invert): stmts_out.append(st) elif policy == 'all': for st in stmts_in: found_genes = True if not remove_bound: agent_list = st.agent_list_with_bound_condition_agents() else: agent_list = st.agent_list() for agent in agent_list: if agent is not None: if agent.name not in filter_list: found_genes = False break if (found_genes and not invert) or (not found_genes and invert): stmts_out.append(st) else: stmts_out = stmts_in logger.info('%d statements after filter...' % len(stmts_out)) dump_pkl = kwargs.get('save') if dump_pkl: dump_statements(stmts_out, dump_pkl) return stmts_out
python
def filter_gene_list(stmts_in, gene_list, policy, allow_families=False, **kwargs): invert = kwargs.get('invert', False) remove_bound = kwargs.get('remove_bound', False) if policy not in ('one', 'all'): logger.error('Policy %s is invalid, not applying filter.' % policy) else: genes_str = ', '.join(gene_list) inv_str = 'not ' if invert else '' logger.info(('Filtering %d statements for ones %scontaining "%s" of: ' '%s...') % (len(stmts_in), inv_str, policy, genes_str)) # If we're allowing families, make a list of all FamPlex IDs that # contain members of the gene list, and add them to the filter list filter_list = copy(gene_list) if allow_families: for hgnc_name in gene_list: gene_uri = hierarchies['entity'].get_uri('HGNC', hgnc_name) parents = hierarchies['entity'].get_parents(gene_uri) for par_uri in parents: ns, id = hierarchies['entity'].ns_id_from_uri(par_uri) filter_list.append(id) stmts_out = [] if remove_bound: # If requested, remove agents whose names are not in the list from # all bound conditions if not invert: keep_criterion = lambda a: a.name in filter_list else: keep_criterion = lambda a: a.name not in filter_list for st in stmts_in: for agent in st.agent_list(): _remove_bound_conditions(agent, keep_criterion) if policy == 'one': for st in stmts_in: found_gene = False if not remove_bound: agent_list = st.agent_list_with_bound_condition_agents() else: agent_list = st.agent_list() for agent in agent_list: if agent is not None: if agent.name in filter_list: found_gene = True break if (found_gene and not invert) or (not found_gene and invert): stmts_out.append(st) elif policy == 'all': for st in stmts_in: found_genes = True if not remove_bound: agent_list = st.agent_list_with_bound_condition_agents() else: agent_list = st.agent_list() for agent in agent_list: if agent is not None: if agent.name not in filter_list: found_genes = False break if (found_genes and not invert) or (not found_genes and invert): stmts_out.append(st) else: stmts_out = stmts_in logger.info('%d statements after filter...' % len(stmts_out)) dump_pkl = kwargs.get('save') if dump_pkl: dump_statements(stmts_out, dump_pkl) return stmts_out
[ "def", "filter_gene_list", "(", "stmts_in", ",", "gene_list", ",", "policy", ",", "allow_families", "=", "False", ",", "*", "*", "kwargs", ")", ":", "invert", "=", "kwargs", ".", "get", "(", "'invert'", ",", "False", ")", "remove_bound", "=", "kwargs", "...
Return statements that contain genes given in a list. Parameters ---------- stmts_in : list[indra.statements.Statement] A list of statements to filter. gene_list : list[str] A list of gene symbols to filter for. policy : str The policy to apply when filtering for the list of genes. "one": keep statements that contain at least one of the list of genes and possibly others not in the list "all": keep statements that only contain genes given in the list allow_families : Optional[bool] Will include statements involving FamPlex families containing one of the genes in the gene list. Default: False save : Optional[str] The name of a pickle file to save the results (stmts_out) into. remove_bound: Optional[str] If true, removes bound conditions that are not genes in the list If false (default), looks at agents in the bound conditions in addition to those participating in the statement directly when applying the specified policy. invert : Optional[bool] If True, the statements that do not match according to the policy are returned. Default: False Returns ------- stmts_out : list[indra.statements.Statement] A list of filtered statements.
[ "Return", "statements", "that", "contain", "genes", "given", "in", "a", "list", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/assemble_corpus.py#L786-L890
19,218
sorgerlab/indra
indra/tools/assemble_corpus.py
filter_by_db_refs
def filter_by_db_refs(stmts_in, namespace, values, policy, **kwargs): """Filter to Statements whose agents are grounded to a matching entry. Statements are filtered so that the db_refs entry (of the given namespace) of their Agent/Concept arguments take a value in the given list of values. Parameters ---------- stmts_in : list[indra.statements.Statement] A list of Statements to filter. namespace : str The namespace in db_refs to which the filter should apply. values : list[str] A list of values in the given namespace to which the filter should apply. policy : str The policy to apply when filtering for the db_refs. "one": keep Statements that contain at least one of the list of db_refs and possibly others not in the list "all": keep Statements that only contain db_refs given in the list save : Optional[str] The name of a pickle file to save the results (stmts_out) into. invert : Optional[bool] If True, the Statements that do not match according to the policy are returned. Default: False match_suffix : Optional[bool] If True, the suffix of the db_refs entry is matches agains the list of entries Returns ------- stmts_out : list[indra.statements.Statement] A list of filtered Statements. """ invert = kwargs.get('invert', False) match_suffix = kwargs.get('match_suffix', False) if policy not in ('one', 'all'): logger.error('Policy %s is invalid, not applying filter.' % policy) return else: name_str = ', '.join(values) rev_mod = 'not ' if invert else '' logger.info(('Filtering %d statements for those with %s agents %s' 'grounded to: %s in the %s namespace...') % (len(stmts_in), policy, rev_mod, name_str, namespace)) def meets_criterion(agent): if namespace not in agent.db_refs: return False entry = agent.db_refs[namespace] if isinstance(entry, list): entry = entry[0][0] ret = False # Match suffix or entire entry if match_suffix: if any([entry.endswith(e) for e in values]): ret = True else: if entry in values: ret = True # Invert if needed if invert: return not ret else: return ret enough = all if policy == 'all' else any stmts_out = [s for s in stmts_in if enough([meets_criterion(ag) for ag in s.agent_list() if ag is not None])] logger.info('%d Statements after filter...' % len(stmts_out)) dump_pkl = kwargs.get('save') if dump_pkl: dump_statements(stmts_out, dump_pkl) return stmts_out
python
def filter_by_db_refs(stmts_in, namespace, values, policy, **kwargs): invert = kwargs.get('invert', False) match_suffix = kwargs.get('match_suffix', False) if policy not in ('one', 'all'): logger.error('Policy %s is invalid, not applying filter.' % policy) return else: name_str = ', '.join(values) rev_mod = 'not ' if invert else '' logger.info(('Filtering %d statements for those with %s agents %s' 'grounded to: %s in the %s namespace...') % (len(stmts_in), policy, rev_mod, name_str, namespace)) def meets_criterion(agent): if namespace not in agent.db_refs: return False entry = agent.db_refs[namespace] if isinstance(entry, list): entry = entry[0][0] ret = False # Match suffix or entire entry if match_suffix: if any([entry.endswith(e) for e in values]): ret = True else: if entry in values: ret = True # Invert if needed if invert: return not ret else: return ret enough = all if policy == 'all' else any stmts_out = [s for s in stmts_in if enough([meets_criterion(ag) for ag in s.agent_list() if ag is not None])] logger.info('%d Statements after filter...' % len(stmts_out)) dump_pkl = kwargs.get('save') if dump_pkl: dump_statements(stmts_out, dump_pkl) return stmts_out
[ "def", "filter_by_db_refs", "(", "stmts_in", ",", "namespace", ",", "values", ",", "policy", ",", "*", "*", "kwargs", ")", ":", "invert", "=", "kwargs", ".", "get", "(", "'invert'", ",", "False", ")", "match_suffix", "=", "kwargs", ".", "get", "(", "'m...
Filter to Statements whose agents are grounded to a matching entry. Statements are filtered so that the db_refs entry (of the given namespace) of their Agent/Concept arguments take a value in the given list of values. Parameters ---------- stmts_in : list[indra.statements.Statement] A list of Statements to filter. namespace : str The namespace in db_refs to which the filter should apply. values : list[str] A list of values in the given namespace to which the filter should apply. policy : str The policy to apply when filtering for the db_refs. "one": keep Statements that contain at least one of the list of db_refs and possibly others not in the list "all": keep Statements that only contain db_refs given in the list save : Optional[str] The name of a pickle file to save the results (stmts_out) into. invert : Optional[bool] If True, the Statements that do not match according to the policy are returned. Default: False match_suffix : Optional[bool] If True, the suffix of the db_refs entry is matches agains the list of entries Returns ------- stmts_out : list[indra.statements.Statement] A list of filtered Statements.
[ "Filter", "to", "Statements", "whose", "agents", "are", "grounded", "to", "a", "matching", "entry", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/assemble_corpus.py#L962-L1039
19,219
sorgerlab/indra
indra/tools/assemble_corpus.py
filter_human_only
def filter_human_only(stmts_in, **kwargs): """Filter out statements that are grounded, but not to a human gene. Parameters ---------- stmts_in : list[indra.statements.Statement] A list of statements to filter. save : Optional[str] The name of a pickle file to save the results (stmts_out) into. remove_bound: Optional[bool] If true, removes all bound conditions that are grounded but not to human genes. If false (default), filters out statements with boundary conditions that are grounded to non-human genes. Returns ------- stmts_out : list[indra.statements.Statement] A list of filtered statements. """ from indra.databases import uniprot_client if 'remove_bound' in kwargs and kwargs['remove_bound']: remove_bound = True else: remove_bound = False dump_pkl = kwargs.get('save') logger.info('Filtering %d statements for human genes only...' % len(stmts_in)) stmts_out = [] def criterion(agent): upid = agent.db_refs.get('UP') if upid and not uniprot_client.is_human(upid): return False else: return True for st in stmts_in: human_genes = True for agent in st.agent_list(): if agent is not None: if not criterion(agent): human_genes = False break if remove_bound: _remove_bound_conditions(agent, criterion) elif _any_bound_condition_fails_criterion(agent, criterion): human_genes = False break if human_genes: stmts_out.append(st) logger.info('%d statements after filter...' % len(stmts_out)) if dump_pkl: dump_statements(stmts_out, dump_pkl) return stmts_out
python
def filter_human_only(stmts_in, **kwargs): from indra.databases import uniprot_client if 'remove_bound' in kwargs and kwargs['remove_bound']: remove_bound = True else: remove_bound = False dump_pkl = kwargs.get('save') logger.info('Filtering %d statements for human genes only...' % len(stmts_in)) stmts_out = [] def criterion(agent): upid = agent.db_refs.get('UP') if upid and not uniprot_client.is_human(upid): return False else: return True for st in stmts_in: human_genes = True for agent in st.agent_list(): if agent is not None: if not criterion(agent): human_genes = False break if remove_bound: _remove_bound_conditions(agent, criterion) elif _any_bound_condition_fails_criterion(agent, criterion): human_genes = False break if human_genes: stmts_out.append(st) logger.info('%d statements after filter...' % len(stmts_out)) if dump_pkl: dump_statements(stmts_out, dump_pkl) return stmts_out
[ "def", "filter_human_only", "(", "stmts_in", ",", "*", "*", "kwargs", ")", ":", "from", "indra", ".", "databases", "import", "uniprot_client", "if", "'remove_bound'", "in", "kwargs", "and", "kwargs", "[", "'remove_bound'", "]", ":", "remove_bound", "=", "True"...
Filter out statements that are grounded, but not to a human gene. Parameters ---------- stmts_in : list[indra.statements.Statement] A list of statements to filter. save : Optional[str] The name of a pickle file to save the results (stmts_out) into. remove_bound: Optional[bool] If true, removes all bound conditions that are grounded but not to human genes. If false (default), filters out statements with boundary conditions that are grounded to non-human genes. Returns ------- stmts_out : list[indra.statements.Statement] A list of filtered statements.
[ "Filter", "out", "statements", "that", "are", "grounded", "but", "not", "to", "a", "human", "gene", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/assemble_corpus.py#L1042-L1097
19,220
sorgerlab/indra
indra/tools/assemble_corpus.py
filter_direct
def filter_direct(stmts_in, **kwargs): """Filter to statements that are direct interactions Parameters ---------- stmts_in : list[indra.statements.Statement] A list of statements to filter. save : Optional[str] The name of a pickle file to save the results (stmts_out) into. Returns ------- stmts_out : list[indra.statements.Statement] A list of filtered statements. """ def get_is_direct(stmt): """Returns true if there is evidence that the statement is a direct interaction. If any of the evidences associated with the statement indicates a direct interatcion then we assume the interaction is direct. If there is no evidence for the interaction being indirect then we default to direct. """ any_indirect = False for ev in stmt.evidence: if ev.epistemics.get('direct') is True: return True elif ev.epistemics.get('direct') is False: # This guarantees that we have seen at least # some evidence that the statement is indirect any_indirect = True if any_indirect: return False return True logger.info('Filtering %d statements to direct ones...' % len(stmts_in)) stmts_out = [] for st in stmts_in: if get_is_direct(st): stmts_out.append(st) logger.info('%d statements after filter...' % len(stmts_out)) dump_pkl = kwargs.get('save') if dump_pkl: dump_statements(stmts_out, dump_pkl) return stmts_out
python
def filter_direct(stmts_in, **kwargs): def get_is_direct(stmt): """Returns true if there is evidence that the statement is a direct interaction. If any of the evidences associated with the statement indicates a direct interatcion then we assume the interaction is direct. If there is no evidence for the interaction being indirect then we default to direct. """ any_indirect = False for ev in stmt.evidence: if ev.epistemics.get('direct') is True: return True elif ev.epistemics.get('direct') is False: # This guarantees that we have seen at least # some evidence that the statement is indirect any_indirect = True if any_indirect: return False return True logger.info('Filtering %d statements to direct ones...' % len(stmts_in)) stmts_out = [] for st in stmts_in: if get_is_direct(st): stmts_out.append(st) logger.info('%d statements after filter...' % len(stmts_out)) dump_pkl = kwargs.get('save') if dump_pkl: dump_statements(stmts_out, dump_pkl) return stmts_out
[ "def", "filter_direct", "(", "stmts_in", ",", "*", "*", "kwargs", ")", ":", "def", "get_is_direct", "(", "stmt", ")", ":", "\"\"\"Returns true if there is evidence that the statement is a direct\n interaction.\n\n If any of the evidences associated with the statement\n ...
Filter to statements that are direct interactions Parameters ---------- stmts_in : list[indra.statements.Statement] A list of statements to filter. save : Optional[str] The name of a pickle file to save the results (stmts_out) into. Returns ------- stmts_out : list[indra.statements.Statement] A list of filtered statements.
[ "Filter", "to", "statements", "that", "are", "direct", "interactions" ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/assemble_corpus.py#L1100-L1144
19,221
sorgerlab/indra
indra/tools/assemble_corpus.py
filter_no_hypothesis
def filter_no_hypothesis(stmts_in, **kwargs): """Filter to statements that are not marked as hypothesis in epistemics. Parameters ---------- stmts_in : list[indra.statements.Statement] A list of statements to filter. save : Optional[str] The name of a pickle file to save the results (stmts_out) into. Returns ------- stmts_out : list[indra.statements.Statement] A list of filtered statements. """ logger.info('Filtering %d statements to no hypothesis...' % len(stmts_in)) stmts_out = [] for st in stmts_in: all_hypotheses = True ev = None for ev in st.evidence: if not ev.epistemics.get('hypothesis', False): all_hypotheses = False break if ev is None: all_hypotheses = False if not all_hypotheses: stmts_out.append(st) logger.info('%d statements after filter...' % len(stmts_out)) dump_pkl = kwargs.get('save') if dump_pkl: dump_statements(stmts_out, dump_pkl) return stmts_out
python
def filter_no_hypothesis(stmts_in, **kwargs): logger.info('Filtering %d statements to no hypothesis...' % len(stmts_in)) stmts_out = [] for st in stmts_in: all_hypotheses = True ev = None for ev in st.evidence: if not ev.epistemics.get('hypothesis', False): all_hypotheses = False break if ev is None: all_hypotheses = False if not all_hypotheses: stmts_out.append(st) logger.info('%d statements after filter...' % len(stmts_out)) dump_pkl = kwargs.get('save') if dump_pkl: dump_statements(stmts_out, dump_pkl) return stmts_out
[ "def", "filter_no_hypothesis", "(", "stmts_in", ",", "*", "*", "kwargs", ")", ":", "logger", ".", "info", "(", "'Filtering %d statements to no hypothesis...'", "%", "len", "(", "stmts_in", ")", ")", "stmts_out", "=", "[", "]", "for", "st", "in", "stmts_in", ...
Filter to statements that are not marked as hypothesis in epistemics. Parameters ---------- stmts_in : list[indra.statements.Statement] A list of statements to filter. save : Optional[str] The name of a pickle file to save the results (stmts_out) into. Returns ------- stmts_out : list[indra.statements.Statement] A list of filtered statements.
[ "Filter", "to", "statements", "that", "are", "not", "marked", "as", "hypothesis", "in", "epistemics", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/assemble_corpus.py#L1147-L1179
19,222
sorgerlab/indra
indra/tools/assemble_corpus.py
filter_evidence_source
def filter_evidence_source(stmts_in, source_apis, policy='one', **kwargs): """Filter to statements that have evidence from a given set of sources. Parameters ---------- stmts_in : list[indra.statements.Statement] A list of statements to filter. source_apis : list[str] A list of sources to filter for. Examples: biopax, bel, reach policy : Optional[str] If 'one', a statement that hase evidence from any of the sources is kept. If 'all', only those statements are kept which have evidence from all the input sources specified in source_apis. If 'none', only those statements are kept that don't have evidence from any of the sources specified in source_apis. save : Optional[str] The name of a pickle file to save the results (stmts_out) into. Returns ------- stmts_out : list[indra.statements.Statement] A list of filtered statements. """ logger.info('Filtering %d statements to evidence source "%s" of: %s...' % (len(stmts_in), policy, ', '.join(source_apis))) stmts_out = [] for st in stmts_in: sources = set([ev.source_api for ev in st.evidence]) if policy == 'one': if sources.intersection(source_apis): stmts_out.append(st) if policy == 'all': if sources.intersection(source_apis) == set(source_apis): stmts_out.append(st) if policy == 'none': if not sources.intersection(source_apis): stmts_out.append(st) logger.info('%d statements after filter...' % len(stmts_out)) dump_pkl = kwargs.get('save') if dump_pkl: dump_statements(stmts_out, dump_pkl) return stmts_out
python
def filter_evidence_source(stmts_in, source_apis, policy='one', **kwargs): logger.info('Filtering %d statements to evidence source "%s" of: %s...' % (len(stmts_in), policy, ', '.join(source_apis))) stmts_out = [] for st in stmts_in: sources = set([ev.source_api for ev in st.evidence]) if policy == 'one': if sources.intersection(source_apis): stmts_out.append(st) if policy == 'all': if sources.intersection(source_apis) == set(source_apis): stmts_out.append(st) if policy == 'none': if not sources.intersection(source_apis): stmts_out.append(st) logger.info('%d statements after filter...' % len(stmts_out)) dump_pkl = kwargs.get('save') if dump_pkl: dump_statements(stmts_out, dump_pkl) return stmts_out
[ "def", "filter_evidence_source", "(", "stmts_in", ",", "source_apis", ",", "policy", "=", "'one'", ",", "*", "*", "kwargs", ")", ":", "logger", ".", "info", "(", "'Filtering %d statements to evidence source \"%s\" of: %s...'", "%", "(", "len", "(", "stmts_in", ")"...
Filter to statements that have evidence from a given set of sources. Parameters ---------- stmts_in : list[indra.statements.Statement] A list of statements to filter. source_apis : list[str] A list of sources to filter for. Examples: biopax, bel, reach policy : Optional[str] If 'one', a statement that hase evidence from any of the sources is kept. If 'all', only those statements are kept which have evidence from all the input sources specified in source_apis. If 'none', only those statements are kept that don't have evidence from any of the sources specified in source_apis. save : Optional[str] The name of a pickle file to save the results (stmts_out) into. Returns ------- stmts_out : list[indra.statements.Statement] A list of filtered statements.
[ "Filter", "to", "statements", "that", "have", "evidence", "from", "a", "given", "set", "of", "sources", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/assemble_corpus.py#L1217-L1258
19,223
sorgerlab/indra
indra/tools/assemble_corpus.py
filter_top_level
def filter_top_level(stmts_in, **kwargs): """Filter to statements that are at the top-level of the hierarchy. Here top-level statements correspond to most specific ones. Parameters ---------- stmts_in : list[indra.statements.Statement] A list of statements to filter. save : Optional[str] The name of a pickle file to save the results (stmts_out) into. Returns ------- stmts_out : list[indra.statements.Statement] A list of filtered statements. """ logger.info('Filtering %d statements for top-level...' % len(stmts_in)) stmts_out = [st for st in stmts_in if not st.supports] logger.info('%d statements after filter...' % len(stmts_out)) dump_pkl = kwargs.get('save') if dump_pkl: dump_statements(stmts_out, dump_pkl) return stmts_out
python
def filter_top_level(stmts_in, **kwargs): logger.info('Filtering %d statements for top-level...' % len(stmts_in)) stmts_out = [st for st in stmts_in if not st.supports] logger.info('%d statements after filter...' % len(stmts_out)) dump_pkl = kwargs.get('save') if dump_pkl: dump_statements(stmts_out, dump_pkl) return stmts_out
[ "def", "filter_top_level", "(", "stmts_in", ",", "*", "*", "kwargs", ")", ":", "logger", ".", "info", "(", "'Filtering %d statements for top-level...'", "%", "len", "(", "stmts_in", ")", ")", "stmts_out", "=", "[", "st", "for", "st", "in", "stmts_in", "if", ...
Filter to statements that are at the top-level of the hierarchy. Here top-level statements correspond to most specific ones. Parameters ---------- stmts_in : list[indra.statements.Statement] A list of statements to filter. save : Optional[str] The name of a pickle file to save the results (stmts_out) into. Returns ------- stmts_out : list[indra.statements.Statement] A list of filtered statements.
[ "Filter", "to", "statements", "that", "are", "at", "the", "top", "-", "level", "of", "the", "hierarchy", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/assemble_corpus.py#L1261-L1284
19,224
sorgerlab/indra
indra/tools/assemble_corpus.py
filter_inconsequential_mods
def filter_inconsequential_mods(stmts_in, whitelist=None, **kwargs): """Filter out Modifications that modify inconsequential sites Inconsequential here means that the site is not mentioned / tested in any other statement. In some cases specific sites should be preserved, for instance, to be used as readouts in a model. In this case, the given sites can be passed in a whitelist. Parameters ---------- stmts_in : list[indra.statements.Statement] A list of statements to filter. whitelist : Optional[dict] A whitelist containing agent modification sites whose modifications should be preserved even if no other statement refers to them. The whitelist parameter is a dictionary in which the key is a gene name and the value is a list of tuples of (modification_type, residue, position). Example: whitelist = {'MAP2K1': [('phosphorylation', 'S', '222')]} save : Optional[str] The name of a pickle file to save the results (stmts_out) into. Returns ------- stmts_out : list[indra.statements.Statement] A list of filtered statements. """ if whitelist is None: whitelist = {} logger.info('Filtering %d statements to remove' % len(stmts_in) + ' inconsequential modifications...') states_used = whitelist for stmt in stmts_in: for agent in stmt.agent_list(): if agent is not None: if agent.mods: for mc in agent.mods: mod = (mc.mod_type, mc.residue, mc.position) try: states_used[agent.name].append(mod) except KeyError: states_used[agent.name] = [mod] for k, v in states_used.items(): states_used[k] = list(set(v)) stmts_out = [] for stmt in stmts_in: skip = False if isinstance(stmt, Modification): mod_type = modclass_to_modtype[stmt.__class__] if isinstance(stmt, RemoveModification): mod_type = modtype_to_inverse[mod_type] mod = (mod_type, stmt.residue, stmt.position) used = states_used.get(stmt.sub.name, []) if mod not in used: skip = True if not skip: stmts_out.append(stmt) logger.info('%d statements after filter...' % len(stmts_out)) dump_pkl = kwargs.get('save') if dump_pkl: dump_statements(stmts_out, dump_pkl) return stmts_out
python
def filter_inconsequential_mods(stmts_in, whitelist=None, **kwargs): if whitelist is None: whitelist = {} logger.info('Filtering %d statements to remove' % len(stmts_in) + ' inconsequential modifications...') states_used = whitelist for stmt in stmts_in: for agent in stmt.agent_list(): if agent is not None: if agent.mods: for mc in agent.mods: mod = (mc.mod_type, mc.residue, mc.position) try: states_used[agent.name].append(mod) except KeyError: states_used[agent.name] = [mod] for k, v in states_used.items(): states_used[k] = list(set(v)) stmts_out = [] for stmt in stmts_in: skip = False if isinstance(stmt, Modification): mod_type = modclass_to_modtype[stmt.__class__] if isinstance(stmt, RemoveModification): mod_type = modtype_to_inverse[mod_type] mod = (mod_type, stmt.residue, stmt.position) used = states_used.get(stmt.sub.name, []) if mod not in used: skip = True if not skip: stmts_out.append(stmt) logger.info('%d statements after filter...' % len(stmts_out)) dump_pkl = kwargs.get('save') if dump_pkl: dump_statements(stmts_out, dump_pkl) return stmts_out
[ "def", "filter_inconsequential_mods", "(", "stmts_in", ",", "whitelist", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "whitelist", "is", "None", ":", "whitelist", "=", "{", "}", "logger", ".", "info", "(", "'Filtering %d statements to remove'", "%", ...
Filter out Modifications that modify inconsequential sites Inconsequential here means that the site is not mentioned / tested in any other statement. In some cases specific sites should be preserved, for instance, to be used as readouts in a model. In this case, the given sites can be passed in a whitelist. Parameters ---------- stmts_in : list[indra.statements.Statement] A list of statements to filter. whitelist : Optional[dict] A whitelist containing agent modification sites whose modifications should be preserved even if no other statement refers to them. The whitelist parameter is a dictionary in which the key is a gene name and the value is a list of tuples of (modification_type, residue, position). Example: whitelist = {'MAP2K1': [('phosphorylation', 'S', '222')]} save : Optional[str] The name of a pickle file to save the results (stmts_out) into. Returns ------- stmts_out : list[indra.statements.Statement] A list of filtered statements.
[ "Filter", "out", "Modifications", "that", "modify", "inconsequential", "sites" ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/assemble_corpus.py#L1287-L1348
19,225
sorgerlab/indra
indra/tools/assemble_corpus.py
filter_inconsequential_acts
def filter_inconsequential_acts(stmts_in, whitelist=None, **kwargs): """Filter out Activations that modify inconsequential activities Inconsequential here means that the site is not mentioned / tested in any other statement. In some cases specific activity types should be preserved, for instance, to be used as readouts in a model. In this case, the given activities can be passed in a whitelist. Parameters ---------- stmts_in : list[indra.statements.Statement] A list of statements to filter. whitelist : Optional[dict] A whitelist containing agent activity types which should be preserved even if no other statement refers to them. The whitelist parameter is a dictionary in which the key is a gene name and the value is a list of activity types. Example: whitelist = {'MAP2K1': ['kinase']} save : Optional[str] The name of a pickle file to save the results (stmts_out) into. Returns ------- stmts_out : list[indra.statements.Statement] A list of filtered statements. """ if whitelist is None: whitelist = {} logger.info('Filtering %d statements to remove' % len(stmts_in) + ' inconsequential activations...') states_used = whitelist for stmt in stmts_in: for agent in stmt.agent_list(): if agent is not None: if agent.activity: act = agent.activity.activity_type try: states_used[agent.name].append(act) except KeyError: states_used[agent.name] = [act] for k, v in states_used.items(): states_used[k] = list(set(v)) stmts_out = [] for stmt in stmts_in: skip = False if isinstance(stmt, RegulateActivity): used = states_used.get(stmt.obj.name, []) if stmt.obj_activity not in used: skip = True if not skip: stmts_out.append(stmt) logger.info('%d statements after filter...' % len(stmts_out)) dump_pkl = kwargs.get('save') if dump_pkl: dump_statements(stmts_out, dump_pkl) return stmts_out
python
def filter_inconsequential_acts(stmts_in, whitelist=None, **kwargs): if whitelist is None: whitelist = {} logger.info('Filtering %d statements to remove' % len(stmts_in) + ' inconsequential activations...') states_used = whitelist for stmt in stmts_in: for agent in stmt.agent_list(): if agent is not None: if agent.activity: act = agent.activity.activity_type try: states_used[agent.name].append(act) except KeyError: states_used[agent.name] = [act] for k, v in states_used.items(): states_used[k] = list(set(v)) stmts_out = [] for stmt in stmts_in: skip = False if isinstance(stmt, RegulateActivity): used = states_used.get(stmt.obj.name, []) if stmt.obj_activity not in used: skip = True if not skip: stmts_out.append(stmt) logger.info('%d statements after filter...' % len(stmts_out)) dump_pkl = kwargs.get('save') if dump_pkl: dump_statements(stmts_out, dump_pkl) return stmts_out
[ "def", "filter_inconsequential_acts", "(", "stmts_in", ",", "whitelist", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "whitelist", "is", "None", ":", "whitelist", "=", "{", "}", "logger", ".", "info", "(", "'Filtering %d statements to remove'", "%", ...
Filter out Activations that modify inconsequential activities Inconsequential here means that the site is not mentioned / tested in any other statement. In some cases specific activity types should be preserved, for instance, to be used as readouts in a model. In this case, the given activities can be passed in a whitelist. Parameters ---------- stmts_in : list[indra.statements.Statement] A list of statements to filter. whitelist : Optional[dict] A whitelist containing agent activity types which should be preserved even if no other statement refers to them. The whitelist parameter is a dictionary in which the key is a gene name and the value is a list of activity types. Example: whitelist = {'MAP2K1': ['kinase']} save : Optional[str] The name of a pickle file to save the results (stmts_out) into. Returns ------- stmts_out : list[indra.statements.Statement] A list of filtered statements.
[ "Filter", "out", "Activations", "that", "modify", "inconsequential", "activities" ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/assemble_corpus.py#L1351-L1406
19,226
sorgerlab/indra
indra/tools/assemble_corpus.py
filter_enzyme_kinase
def filter_enzyme_kinase(stmts_in, **kwargs): """Filter Phosphorylations to ones where the enzyme is a known kinase. Parameters ---------- stmts_in : list[indra.statements.Statement] A list of statements to filter. save : Optional[str] The name of a pickle file to save the results (stmts_out) into. Returns ------- stmts_out : list[indra.statements.Statement] A list of filtered statements. """ logger.info('Filtering %d statements to remove ' % len(stmts_in) + 'phosphorylation by non-kinases...') path = os.path.dirname(os.path.abspath(__file__)) kinase_table = read_unicode_csv(path + '/../resources/kinases.tsv', delimiter='\t') gene_names = [lin[1] for lin in list(kinase_table)[1:]] stmts_out = [] for st in stmts_in: if isinstance(st, Phosphorylation): if st.enz is not None: if st.enz.name in gene_names: stmts_out.append(st) else: stmts_out.append(st) logger.info('%d statements after filter...' % len(stmts_out)) dump_pkl = kwargs.get('save') if dump_pkl: dump_statements(stmts_out, dump_pkl) return stmts_out
python
def filter_enzyme_kinase(stmts_in, **kwargs): logger.info('Filtering %d statements to remove ' % len(stmts_in) + 'phosphorylation by non-kinases...') path = os.path.dirname(os.path.abspath(__file__)) kinase_table = read_unicode_csv(path + '/../resources/kinases.tsv', delimiter='\t') gene_names = [lin[1] for lin in list(kinase_table)[1:]] stmts_out = [] for st in stmts_in: if isinstance(st, Phosphorylation): if st.enz is not None: if st.enz.name in gene_names: stmts_out.append(st) else: stmts_out.append(st) logger.info('%d statements after filter...' % len(stmts_out)) dump_pkl = kwargs.get('save') if dump_pkl: dump_statements(stmts_out, dump_pkl) return stmts_out
[ "def", "filter_enzyme_kinase", "(", "stmts_in", ",", "*", "*", "kwargs", ")", ":", "logger", ".", "info", "(", "'Filtering %d statements to remove '", "%", "len", "(", "stmts_in", ")", "+", "'phosphorylation by non-kinases...'", ")", "path", "=", "os", ".", "pat...
Filter Phosphorylations to ones where the enzyme is a known kinase. Parameters ---------- stmts_in : list[indra.statements.Statement] A list of statements to filter. save : Optional[str] The name of a pickle file to save the results (stmts_out) into. Returns ------- stmts_out : list[indra.statements.Statement] A list of filtered statements.
[ "Filter", "Phosphorylations", "to", "ones", "where", "the", "enzyme", "is", "a", "known", "kinase", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/assemble_corpus.py#L1506-L1539
19,227
sorgerlab/indra
indra/tools/assemble_corpus.py
filter_transcription_factor
def filter_transcription_factor(stmts_in, **kwargs): """Filter out RegulateAmounts where subject is not a transcription factor. Parameters ---------- stmts_in : list[indra.statements.Statement] A list of statements to filter. save : Optional[str] The name of a pickle file to save the results (stmts_out) into. Returns ------- stmts_out : list[indra.statements.Statement] A list of filtered statements. """ logger.info('Filtering %d statements to remove ' % len(stmts_in) + 'amount regulations by non-transcription-factors...') path = os.path.dirname(os.path.abspath(__file__)) tf_table = \ read_unicode_csv(path + '/../resources/transcription_factors.csv') gene_names = [lin[1] for lin in list(tf_table)[1:]] stmts_out = [] for st in stmts_in: if isinstance(st, RegulateAmount): if st.subj is not None: if st.subj.name in gene_names: stmts_out.append(st) else: stmts_out.append(st) logger.info('%d statements after filter...' % len(stmts_out)) dump_pkl = kwargs.get('save') if dump_pkl: dump_statements(stmts_out, dump_pkl) return stmts_out
python
def filter_transcription_factor(stmts_in, **kwargs): logger.info('Filtering %d statements to remove ' % len(stmts_in) + 'amount regulations by non-transcription-factors...') path = os.path.dirname(os.path.abspath(__file__)) tf_table = \ read_unicode_csv(path + '/../resources/transcription_factors.csv') gene_names = [lin[1] for lin in list(tf_table)[1:]] stmts_out = [] for st in stmts_in: if isinstance(st, RegulateAmount): if st.subj is not None: if st.subj.name in gene_names: stmts_out.append(st) else: stmts_out.append(st) logger.info('%d statements after filter...' % len(stmts_out)) dump_pkl = kwargs.get('save') if dump_pkl: dump_statements(stmts_out, dump_pkl) return stmts_out
[ "def", "filter_transcription_factor", "(", "stmts_in", ",", "*", "*", "kwargs", ")", ":", "logger", ".", "info", "(", "'Filtering %d statements to remove '", "%", "len", "(", "stmts_in", ")", "+", "'amount regulations by non-transcription-factors...'", ")", "path", "=...
Filter out RegulateAmounts where subject is not a transcription factor. Parameters ---------- stmts_in : list[indra.statements.Statement] A list of statements to filter. save : Optional[str] The name of a pickle file to save the results (stmts_out) into. Returns ------- stmts_out : list[indra.statements.Statement] A list of filtered statements.
[ "Filter", "out", "RegulateAmounts", "where", "subject", "is", "not", "a", "transcription", "factor", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/assemble_corpus.py#L1579-L1612
19,228
sorgerlab/indra
indra/tools/assemble_corpus.py
filter_uuid_list
def filter_uuid_list(stmts_in, uuids, **kwargs): """Filter to Statements corresponding to given UUIDs Parameters ---------- stmts_in : list[indra.statements.Statement] A list of statements to filter. uuids : list[str] A list of UUIDs to filter for. save : Optional[str] The name of a pickle file to save the results (stmts_out) into. invert : Optional[bool] Invert the filter to remove the Statements corresponding to the given UUIDs. Returns ------- stmts_out : list[indra.statements.Statement] A list of filtered statements. """ invert = kwargs.get('invert', False) logger.info('Filtering %d statements for %d UUID%s...' % (len(stmts_in), len(uuids), 's' if len(uuids) > 1 else '')) stmts_out = [] for st in stmts_in: if not invert: if st.uuid in uuids: stmts_out.append(st) else: if st.uuid not in uuids: stmts_out.append(st) logger.info('%d statements after filter...' % len(stmts_out)) dump_pkl = kwargs.get('save') if dump_pkl: dump_statements(stmts_out, dump_pkl) return stmts_out
python
def filter_uuid_list(stmts_in, uuids, **kwargs): invert = kwargs.get('invert', False) logger.info('Filtering %d statements for %d UUID%s...' % (len(stmts_in), len(uuids), 's' if len(uuids) > 1 else '')) stmts_out = [] for st in stmts_in: if not invert: if st.uuid in uuids: stmts_out.append(st) else: if st.uuid not in uuids: stmts_out.append(st) logger.info('%d statements after filter...' % len(stmts_out)) dump_pkl = kwargs.get('save') if dump_pkl: dump_statements(stmts_out, dump_pkl) return stmts_out
[ "def", "filter_uuid_list", "(", "stmts_in", ",", "uuids", ",", "*", "*", "kwargs", ")", ":", "invert", "=", "kwargs", ".", "get", "(", "'invert'", ",", "False", ")", "logger", ".", "info", "(", "'Filtering %d statements for %d UUID%s...'", "%", "(", "len", ...
Filter to Statements corresponding to given UUIDs Parameters ---------- stmts_in : list[indra.statements.Statement] A list of statements to filter. uuids : list[str] A list of UUIDs to filter for. save : Optional[str] The name of a pickle file to save the results (stmts_out) into. invert : Optional[bool] Invert the filter to remove the Statements corresponding to the given UUIDs. Returns ------- stmts_out : list[indra.statements.Statement] A list of filtered statements.
[ "Filter", "to", "Statements", "corresponding", "to", "given", "UUIDs" ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/assemble_corpus.py#L1615-L1651
19,229
sorgerlab/indra
indra/tools/assemble_corpus.py
expand_families
def expand_families(stmts_in, **kwargs): """Expand FamPlex Agents to individual genes. Parameters ---------- stmts_in : list[indra.statements.Statement] A list of statements to expand. save : Optional[str] The name of a pickle file to save the results (stmts_out) into. Returns ------- stmts_out : list[indra.statements.Statement] A list of expanded statements. """ from indra.tools.expand_families import Expander logger.info('Expanding families on %d statements...' % len(stmts_in)) expander = Expander(hierarchies) stmts_out = expander.expand_families(stmts_in) logger.info('%d statements after expanding families...' % len(stmts_out)) dump_pkl = kwargs.get('save') if dump_pkl: dump_statements(stmts_out, dump_pkl) return stmts_out
python
def expand_families(stmts_in, **kwargs): from indra.tools.expand_families import Expander logger.info('Expanding families on %d statements...' % len(stmts_in)) expander = Expander(hierarchies) stmts_out = expander.expand_families(stmts_in) logger.info('%d statements after expanding families...' % len(stmts_out)) dump_pkl = kwargs.get('save') if dump_pkl: dump_statements(stmts_out, dump_pkl) return stmts_out
[ "def", "expand_families", "(", "stmts_in", ",", "*", "*", "kwargs", ")", ":", "from", "indra", ".", "tools", ".", "expand_families", "import", "Expander", "logger", ".", "info", "(", "'Expanding families on %d statements...'", "%", "len", "(", "stmts_in", ")", ...
Expand FamPlex Agents to individual genes. Parameters ---------- stmts_in : list[indra.statements.Statement] A list of statements to expand. save : Optional[str] The name of a pickle file to save the results (stmts_out) into. Returns ------- stmts_out : list[indra.statements.Statement] A list of expanded statements.
[ "Expand", "FamPlex", "Agents", "to", "individual", "genes", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/assemble_corpus.py#L1654-L1677
19,230
sorgerlab/indra
indra/tools/assemble_corpus.py
reduce_activities
def reduce_activities(stmts_in, **kwargs): """Reduce the activity types in a list of statements Parameters ---------- stmts_in : list[indra.statements.Statement] A list of statements to reduce activity types in. save : Optional[str] The name of a pickle file to save the results (stmts_out) into. Returns ------- stmts_out : list[indra.statements.Statement] A list of reduced activity statements. """ logger.info('Reducing activities on %d statements...' % len(stmts_in)) stmts_out = [deepcopy(st) for st in stmts_in] ml = MechLinker(stmts_out) ml.gather_explicit_activities() ml.reduce_activities() stmts_out = ml.statements dump_pkl = kwargs.get('save') if dump_pkl: dump_statements(stmts_out, dump_pkl) return stmts_out
python
def reduce_activities(stmts_in, **kwargs): logger.info('Reducing activities on %d statements...' % len(stmts_in)) stmts_out = [deepcopy(st) for st in stmts_in] ml = MechLinker(stmts_out) ml.gather_explicit_activities() ml.reduce_activities() stmts_out = ml.statements dump_pkl = kwargs.get('save') if dump_pkl: dump_statements(stmts_out, dump_pkl) return stmts_out
[ "def", "reduce_activities", "(", "stmts_in", ",", "*", "*", "kwargs", ")", ":", "logger", ".", "info", "(", "'Reducing activities on %d statements...'", "%", "len", "(", "stmts_in", ")", ")", "stmts_out", "=", "[", "deepcopy", "(", "st", ")", "for", "st", ...
Reduce the activity types in a list of statements Parameters ---------- stmts_in : list[indra.statements.Statement] A list of statements to reduce activity types in. save : Optional[str] The name of a pickle file to save the results (stmts_out) into. Returns ------- stmts_out : list[indra.statements.Statement] A list of reduced activity statements.
[ "Reduce", "the", "activity", "types", "in", "a", "list", "of", "statements" ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/assemble_corpus.py#L1680-L1704
19,231
sorgerlab/indra
indra/tools/assemble_corpus.py
strip_agent_context
def strip_agent_context(stmts_in, **kwargs): """Strip any context on agents within each statement. Parameters ---------- stmts_in : list[indra.statements.Statement] A list of statements whose agent context should be stripped. save : Optional[str] The name of a pickle file to save the results (stmts_out) into. Returns ------- stmts_out : list[indra.statements.Statement] A list of stripped statements. """ logger.info('Stripping agent context on %d statements...' % len(stmts_in)) stmts_out = [] for st in stmts_in: new_st = deepcopy(st) for agent in new_st.agent_list(): if agent is None: continue agent.mods = [] agent.mutations = [] agent.activity = None agent.location = None agent.bound_conditions = [] stmts_out.append(new_st) dump_pkl = kwargs.get('save') if dump_pkl: dump_statements(stmts_out, dump_pkl) return stmts_out
python
def strip_agent_context(stmts_in, **kwargs): logger.info('Stripping agent context on %d statements...' % len(stmts_in)) stmts_out = [] for st in stmts_in: new_st = deepcopy(st) for agent in new_st.agent_list(): if agent is None: continue agent.mods = [] agent.mutations = [] agent.activity = None agent.location = None agent.bound_conditions = [] stmts_out.append(new_st) dump_pkl = kwargs.get('save') if dump_pkl: dump_statements(stmts_out, dump_pkl) return stmts_out
[ "def", "strip_agent_context", "(", "stmts_in", ",", "*", "*", "kwargs", ")", ":", "logger", ".", "info", "(", "'Stripping agent context on %d statements...'", "%", "len", "(", "stmts_in", ")", ")", "stmts_out", "=", "[", "]", "for", "st", "in", "stmts_in", "...
Strip any context on agents within each statement. Parameters ---------- stmts_in : list[indra.statements.Statement] A list of statements whose agent context should be stripped. save : Optional[str] The name of a pickle file to save the results (stmts_out) into. Returns ------- stmts_out : list[indra.statements.Statement] A list of stripped statements.
[ "Strip", "any", "context", "on", "agents", "within", "each", "statement", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/assemble_corpus.py#L1707-L1738
19,232
sorgerlab/indra
indra/tools/assemble_corpus.py
standardize_names_groundings
def standardize_names_groundings(stmts): """Standardize the names of Concepts with respect to an ontology. NOTE: this function is currently optimized for Influence Statements obtained from Eidos, Hume, Sofia and CWMS. It will possibly yield unexpected results for biology-specific Statements. """ print('Standardize names to groundings') for stmt in stmts: for concept in stmt.agent_list(): db_ns, db_id = concept.get_grounding() if db_id is not None: if isinstance(db_id, list): db_id = db_id[0][0].split('/')[-1] else: db_id = db_id.split('/')[-1] db_id = db_id.replace('|', ' ') db_id = db_id.replace('_', ' ') db_id = db_id.replace('ONT::', '') db_id = db_id.capitalize() concept.name = db_id return stmts
python
def standardize_names_groundings(stmts): print('Standardize names to groundings') for stmt in stmts: for concept in stmt.agent_list(): db_ns, db_id = concept.get_grounding() if db_id is not None: if isinstance(db_id, list): db_id = db_id[0][0].split('/')[-1] else: db_id = db_id.split('/')[-1] db_id = db_id.replace('|', ' ') db_id = db_id.replace('_', ' ') db_id = db_id.replace('ONT::', '') db_id = db_id.capitalize() concept.name = db_id return stmts
[ "def", "standardize_names_groundings", "(", "stmts", ")", ":", "print", "(", "'Standardize names to groundings'", ")", "for", "stmt", "in", "stmts", ":", "for", "concept", "in", "stmt", ".", "agent_list", "(", ")", ":", "db_ns", ",", "db_id", "=", "concept", ...
Standardize the names of Concepts with respect to an ontology. NOTE: this function is currently optimized for Influence Statements obtained from Eidos, Hume, Sofia and CWMS. It will possibly yield unexpected results for biology-specific Statements.
[ "Standardize", "the", "names", "of", "Concepts", "with", "respect", "to", "an", "ontology", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/assemble_corpus.py#L1741-L1762
19,233
sorgerlab/indra
indra/tools/assemble_corpus.py
dump_stmt_strings
def dump_stmt_strings(stmts, fname): """Save printed statements in a file. Parameters ---------- stmts_in : list[indra.statements.Statement] A list of statements to save in a text file. fname : Optional[str] The name of a text file to save the printed statements into. """ with open(fname, 'wb') as fh: for st in stmts: fh.write(('%s\n' % st).encode('utf-8'))
python
def dump_stmt_strings(stmts, fname): with open(fname, 'wb') as fh: for st in stmts: fh.write(('%s\n' % st).encode('utf-8'))
[ "def", "dump_stmt_strings", "(", "stmts", ",", "fname", ")", ":", "with", "open", "(", "fname", ",", "'wb'", ")", "as", "fh", ":", "for", "st", "in", "stmts", ":", "fh", ".", "write", "(", "(", "'%s\\n'", "%", "st", ")", ".", "encode", "(", "'utf...
Save printed statements in a file. Parameters ---------- stmts_in : list[indra.statements.Statement] A list of statements to save in a text file. fname : Optional[str] The name of a text file to save the printed statements into.
[ "Save", "printed", "statements", "in", "a", "file", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/assemble_corpus.py#L1765-L1777
19,234
sorgerlab/indra
indra/tools/assemble_corpus.py
rename_db_ref
def rename_db_ref(stmts_in, ns_from, ns_to, **kwargs): """Rename an entry in the db_refs of each Agent. This is particularly useful when old Statements in pickle files need to be updated after a namespace was changed such as 'BE' to 'FPLX'. Parameters ---------- stmts_in : list[indra.statements.Statement] A list of statements whose Agents' db_refs need to be changed ns_from : str The namespace identifier to replace ns_to : str The namespace identifier to replace to save : Optional[str] The name of a pickle file to save the results (stmts_out) into. Returns ------- stmts_out : list[indra.statements.Statement] A list of Statements with Agents' db_refs changed. """ logger.info('Remapping "%s" to "%s" in db_refs on %d statements...' % (ns_from, ns_to, len(stmts_in))) stmts_out = [deepcopy(st) for st in stmts_in] for stmt in stmts_out: for agent in stmt.agent_list(): if agent is not None and ns_from in agent.db_refs: agent.db_refs[ns_to] = agent.db_refs.pop(ns_from) dump_pkl = kwargs.get('save') if dump_pkl: dump_statements(stmts_out, dump_pkl) return stmts_out
python
def rename_db_ref(stmts_in, ns_from, ns_to, **kwargs): logger.info('Remapping "%s" to "%s" in db_refs on %d statements...' % (ns_from, ns_to, len(stmts_in))) stmts_out = [deepcopy(st) for st in stmts_in] for stmt in stmts_out: for agent in stmt.agent_list(): if agent is not None and ns_from in agent.db_refs: agent.db_refs[ns_to] = agent.db_refs.pop(ns_from) dump_pkl = kwargs.get('save') if dump_pkl: dump_statements(stmts_out, dump_pkl) return stmts_out
[ "def", "rename_db_ref", "(", "stmts_in", ",", "ns_from", ",", "ns_to", ",", "*", "*", "kwargs", ")", ":", "logger", ".", "info", "(", "'Remapping \"%s\" to \"%s\" in db_refs on %d statements...'", "%", "(", "ns_from", ",", "ns_to", ",", "len", "(", "stmts_in", ...
Rename an entry in the db_refs of each Agent. This is particularly useful when old Statements in pickle files need to be updated after a namespace was changed such as 'BE' to 'FPLX'. Parameters ---------- stmts_in : list[indra.statements.Statement] A list of statements whose Agents' db_refs need to be changed ns_from : str The namespace identifier to replace ns_to : str The namespace identifier to replace to save : Optional[str] The name of a pickle file to save the results (stmts_out) into. Returns ------- stmts_out : list[indra.statements.Statement] A list of Statements with Agents' db_refs changed.
[ "Rename", "an", "entry", "in", "the", "db_refs", "of", "each", "Agent", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/assemble_corpus.py#L1780-L1813
19,235
sorgerlab/indra
indra/tools/assemble_corpus.py
align_statements
def align_statements(stmts1, stmts2, keyfun=None): """Return alignment of two lists of statements by key. Parameters ---------- stmts1 : list[indra.statements.Statement] A list of INDRA Statements to align stmts2 : list[indra.statements.Statement] A list of INDRA Statements to align keyfun : Optional[function] A function that takes a Statement as an argument and returns a key to align by. If not given, the default key function is a tuble of the names of the Agents in the Statement. Return ------ matches : list(tuple) A list of tuples where each tuple has two elements, the first corresponding to an element of the stmts1 list and the second corresponding to an element of the stmts2 list. If a given element is not matched, its corresponding pair in the tuple is None. """ def name_keyfun(stmt): return tuple(a.name if a is not None else None for a in stmt.agent_list()) if not keyfun: keyfun = name_keyfun matches = [] keys1 = [keyfun(s) for s in stmts1] keys2 = [keyfun(s) for s in stmts2] for stmt, key in zip(stmts1, keys1): try: match_idx = keys2.index(key) match_stmt = stmts2[match_idx] matches.append((stmt, match_stmt)) except ValueError: matches.append((stmt, None)) for stmt, key in zip(stmts2, keys2): try: match_idx = keys1.index(key) except ValueError: matches.append((None, stmt)) return matches
python
def align_statements(stmts1, stmts2, keyfun=None): def name_keyfun(stmt): return tuple(a.name if a is not None else None for a in stmt.agent_list()) if not keyfun: keyfun = name_keyfun matches = [] keys1 = [keyfun(s) for s in stmts1] keys2 = [keyfun(s) for s in stmts2] for stmt, key in zip(stmts1, keys1): try: match_idx = keys2.index(key) match_stmt = stmts2[match_idx] matches.append((stmt, match_stmt)) except ValueError: matches.append((stmt, None)) for stmt, key in zip(stmts2, keys2): try: match_idx = keys1.index(key) except ValueError: matches.append((None, stmt)) return matches
[ "def", "align_statements", "(", "stmts1", ",", "stmts2", ",", "keyfun", "=", "None", ")", ":", "def", "name_keyfun", "(", "stmt", ")", ":", "return", "tuple", "(", "a", ".", "name", "if", "a", "is", "not", "None", "else", "None", "for", "a", "in", ...
Return alignment of two lists of statements by key. Parameters ---------- stmts1 : list[indra.statements.Statement] A list of INDRA Statements to align stmts2 : list[indra.statements.Statement] A list of INDRA Statements to align keyfun : Optional[function] A function that takes a Statement as an argument and returns a key to align by. If not given, the default key function is a tuble of the names of the Agents in the Statement. Return ------ matches : list(tuple) A list of tuples where each tuple has two elements, the first corresponding to an element of the stmts1 list and the second corresponding to an element of the stmts2 list. If a given element is not matched, its corresponding pair in the tuple is None.
[ "Return", "alignment", "of", "two", "lists", "of", "statements", "by", "key", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/assemble_corpus.py#L1816-L1860
19,236
sorgerlab/indra
indra/sources/indra_db_rest/util.py
submit_query_request
def submit_query_request(end_point, *args, **kwargs): """Low level function to format the query string.""" ev_limit = kwargs.pop('ev_limit', 10) best_first = kwargs.pop('best_first', True) tries = kwargs.pop('tries', 2) # This isn't handled by requests because of the multiple identical agent # keys, e.g. {'agent': 'MEK', 'agent': 'ERK'} which is not supported in # python, but is allowed and necessary in these query strings. # TODO because we use the API Gateway, this feature is not longer needed. # We should just use the requests parameters dict. query_str = '?' + '&'.join(['%s=%s' % (k, v) for k, v in kwargs.items() if v is not None] + list(args)) return submit_statement_request('get', end_point, query_str, ev_limit=ev_limit, best_first=best_first, tries=tries)
python
def submit_query_request(end_point, *args, **kwargs): ev_limit = kwargs.pop('ev_limit', 10) best_first = kwargs.pop('best_first', True) tries = kwargs.pop('tries', 2) # This isn't handled by requests because of the multiple identical agent # keys, e.g. {'agent': 'MEK', 'agent': 'ERK'} which is not supported in # python, but is allowed and necessary in these query strings. # TODO because we use the API Gateway, this feature is not longer needed. # We should just use the requests parameters dict. query_str = '?' + '&'.join(['%s=%s' % (k, v) for k, v in kwargs.items() if v is not None] + list(args)) return submit_statement_request('get', end_point, query_str, ev_limit=ev_limit, best_first=best_first, tries=tries)
[ "def", "submit_query_request", "(", "end_point", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "ev_limit", "=", "kwargs", ".", "pop", "(", "'ev_limit'", ",", "10", ")", "best_first", "=", "kwargs", ".", "pop", "(", "'best_first'", ",", "True", "...
Low level function to format the query string.
[ "Low", "level", "function", "to", "format", "the", "query", "string", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/indra_db_rest/util.py#L11-L26
19,237
sorgerlab/indra
indra/sources/indra_db_rest/util.py
submit_statement_request
def submit_statement_request(meth, end_point, query_str='', data=None, tries=2, **params): """Even lower level function to make the request.""" full_end_point = 'statements/' + end_point.lstrip('/') return make_db_rest_request(meth, full_end_point, query_str, data, params, tries)
python
def submit_statement_request(meth, end_point, query_str='', data=None, tries=2, **params): full_end_point = 'statements/' + end_point.lstrip('/') return make_db_rest_request(meth, full_end_point, query_str, data, params, tries)
[ "def", "submit_statement_request", "(", "meth", ",", "end_point", ",", "query_str", "=", "''", ",", "data", "=", "None", ",", "tries", "=", "2", ",", "*", "*", "params", ")", ":", "full_end_point", "=", "'statements/'", "+", "end_point", ".", "lstrip", "...
Even lower level function to make the request.
[ "Even", "lower", "level", "function", "to", "make", "the", "request", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/indra_db_rest/util.py#L29-L33
19,238
sorgerlab/indra
indra/preassembler/__init__.py
render_stmt_graph
def render_stmt_graph(statements, reduce=True, english=False, rankdir=None, agent_style=None): """Render the statement hierarchy as a pygraphviz graph. Parameters ---------- stmts : list of :py:class:`indra.statements.Statement` A list of top-level statements with associated supporting statements resulting from building a statement hierarchy with :py:meth:`combine_related`. reduce : bool Whether to perform a transitive reduction of the edges in the graph. Default is True. english : bool If True, the statements in the graph are represented by their English-assembled equivalent; otherwise they are represented as text-formatted Statements. rank_dir : str or None Argument to pass through to the pygraphviz `AGraph` constructor specifying graph layout direction. In particular, a value of 'LR' specifies a left-to-right direction. If None, the pygraphviz default is used. agent_style : dict or None Dict of attributes specifying the visual properties of nodes. If None, the following default attributes are used:: agent_style = {'color': 'lightgray', 'style': 'filled', 'fontname': 'arial'} Returns ------- pygraphviz.AGraph Pygraphviz graph with nodes representing statements and edges pointing from supported statements to supported_by statements. Examples -------- Pattern for getting statements and rendering as a Graphviz graph: >>> from indra.preassembler.hierarchy_manager import hierarchies >>> braf = Agent('BRAF') >>> map2k1 = Agent('MAP2K1') >>> st1 = Phosphorylation(braf, map2k1) >>> st2 = Phosphorylation(braf, map2k1, residue='S') >>> pa = Preassembler(hierarchies, [st1, st2]) >>> pa.combine_related() # doctest:+ELLIPSIS [Phosphorylation(BRAF(), MAP2K1(), S)] >>> graph = render_stmt_graph(pa.related_stmts) >>> graph.write('example_graph.dot') # To make the DOT file >>> graph.draw('example_graph.png', prog='dot') # To make an image Resulting graph: .. image:: /images/example_graph.png :align: center :alt: Example statement graph rendered by Graphviz """ from indra.assemblers.english import EnglishAssembler # Set the default agent formatting properties if agent_style is None: agent_style = {'color': 'lightgray', 'style': 'filled', 'fontname': 'arial'} # Sets to store all of the nodes and edges as we recursively process all # of the statements nodes = set([]) edges = set([]) stmt_dict = {} # Recursive function for processing all statements def process_stmt(stmt): nodes.add(str(stmt.matches_key())) stmt_dict[str(stmt.matches_key())] = stmt for sby_ix, sby_stmt in enumerate(stmt.supported_by): edges.add((str(stmt.matches_key()), str(sby_stmt.matches_key()))) process_stmt(sby_stmt) # Process all of the top-level statements, getting the supporting statements # recursively for stmt in statements: process_stmt(stmt) # Create a networkx graph from the nodes nx_graph = nx.DiGraph() nx_graph.add_edges_from(edges) # Perform transitive reduction if desired if reduce: nx_graph = nx.algorithms.dag.transitive_reduction(nx_graph) # Create a pygraphviz graph from the nx graph try: pgv_graph = pgv.AGraph(name='statements', directed=True, rankdir=rankdir) except NameError: logger.error('Cannot generate graph because ' 'pygraphviz could not be imported.') return None for node in nx_graph.nodes(): stmt = stmt_dict[node] if english: ea = EnglishAssembler([stmt]) stmt_str = ea.make_model() else: stmt_str = str(stmt) pgv_graph.add_node(node, label='%s (%d)' % (stmt_str, len(stmt.evidence)), **agent_style) pgv_graph.add_edges_from(nx_graph.edges()) return pgv_graph
python
def render_stmt_graph(statements, reduce=True, english=False, rankdir=None, agent_style=None): from indra.assemblers.english import EnglishAssembler # Set the default agent formatting properties if agent_style is None: agent_style = {'color': 'lightgray', 'style': 'filled', 'fontname': 'arial'} # Sets to store all of the nodes and edges as we recursively process all # of the statements nodes = set([]) edges = set([]) stmt_dict = {} # Recursive function for processing all statements def process_stmt(stmt): nodes.add(str(stmt.matches_key())) stmt_dict[str(stmt.matches_key())] = stmt for sby_ix, sby_stmt in enumerate(stmt.supported_by): edges.add((str(stmt.matches_key()), str(sby_stmt.matches_key()))) process_stmt(sby_stmt) # Process all of the top-level statements, getting the supporting statements # recursively for stmt in statements: process_stmt(stmt) # Create a networkx graph from the nodes nx_graph = nx.DiGraph() nx_graph.add_edges_from(edges) # Perform transitive reduction if desired if reduce: nx_graph = nx.algorithms.dag.transitive_reduction(nx_graph) # Create a pygraphviz graph from the nx graph try: pgv_graph = pgv.AGraph(name='statements', directed=True, rankdir=rankdir) except NameError: logger.error('Cannot generate graph because ' 'pygraphviz could not be imported.') return None for node in nx_graph.nodes(): stmt = stmt_dict[node] if english: ea = EnglishAssembler([stmt]) stmt_str = ea.make_model() else: stmt_str = str(stmt) pgv_graph.add_node(node, label='%s (%d)' % (stmt_str, len(stmt.evidence)), **agent_style) pgv_graph.add_edges_from(nx_graph.edges()) return pgv_graph
[ "def", "render_stmt_graph", "(", "statements", ",", "reduce", "=", "True", ",", "english", "=", "False", ",", "rankdir", "=", "None", ",", "agent_style", "=", "None", ")", ":", "from", "indra", ".", "assemblers", ".", "english", "import", "EnglishAssembler",...
Render the statement hierarchy as a pygraphviz graph. Parameters ---------- stmts : list of :py:class:`indra.statements.Statement` A list of top-level statements with associated supporting statements resulting from building a statement hierarchy with :py:meth:`combine_related`. reduce : bool Whether to perform a transitive reduction of the edges in the graph. Default is True. english : bool If True, the statements in the graph are represented by their English-assembled equivalent; otherwise they are represented as text-formatted Statements. rank_dir : str or None Argument to pass through to the pygraphviz `AGraph` constructor specifying graph layout direction. In particular, a value of 'LR' specifies a left-to-right direction. If None, the pygraphviz default is used. agent_style : dict or None Dict of attributes specifying the visual properties of nodes. If None, the following default attributes are used:: agent_style = {'color': 'lightgray', 'style': 'filled', 'fontname': 'arial'} Returns ------- pygraphviz.AGraph Pygraphviz graph with nodes representing statements and edges pointing from supported statements to supported_by statements. Examples -------- Pattern for getting statements and rendering as a Graphviz graph: >>> from indra.preassembler.hierarchy_manager import hierarchies >>> braf = Agent('BRAF') >>> map2k1 = Agent('MAP2K1') >>> st1 = Phosphorylation(braf, map2k1) >>> st2 = Phosphorylation(braf, map2k1, residue='S') >>> pa = Preassembler(hierarchies, [st1, st2]) >>> pa.combine_related() # doctest:+ELLIPSIS [Phosphorylation(BRAF(), MAP2K1(), S)] >>> graph = render_stmt_graph(pa.related_stmts) >>> graph.write('example_graph.dot') # To make the DOT file >>> graph.draw('example_graph.png', prog='dot') # To make an image Resulting graph: .. image:: /images/example_graph.png :align: center :alt: Example statement graph rendered by Graphviz
[ "Render", "the", "statement", "hierarchy", "as", "a", "pygraphviz", "graph", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/preassembler/__init__.py#L646-L752
19,239
sorgerlab/indra
indra/preassembler/__init__.py
flatten_stmts
def flatten_stmts(stmts): """Return the full set of unique stms in a pre-assembled stmt graph. The flattened list of statements returned by this function can be compared to the original set of unique statements to make sure no statements have been lost during the preassembly process. Parameters ---------- stmts : list of :py:class:`indra.statements.Statement` A list of top-level statements with associated supporting statements resulting from building a statement hierarchy with :py:meth:`combine_related`. Returns ------- stmts : list of :py:class:`indra.statements.Statement` List of all statements contained in the hierarchical statement graph. Examples -------- Calling :py:meth:`combine_related` on two statements results in one top-level statement; calling :py:func:`flatten_stmts` recovers both: >>> from indra.preassembler.hierarchy_manager import hierarchies >>> braf = Agent('BRAF') >>> map2k1 = Agent('MAP2K1') >>> st1 = Phosphorylation(braf, map2k1) >>> st2 = Phosphorylation(braf, map2k1, residue='S') >>> pa = Preassembler(hierarchies, [st1, st2]) >>> pa.combine_related() # doctest:+ELLIPSIS [Phosphorylation(BRAF(), MAP2K1(), S)] >>> flattened = flatten_stmts(pa.related_stmts) >>> flattened.sort(key=lambda x: x.matches_key()) >>> flattened [Phosphorylation(BRAF(), MAP2K1()), Phosphorylation(BRAF(), MAP2K1(), S)] """ total_stmts = set(stmts) for stmt in stmts: if stmt.supported_by: children = flatten_stmts(stmt.supported_by) total_stmts = total_stmts.union(children) return list(total_stmts)
python
def flatten_stmts(stmts): total_stmts = set(stmts) for stmt in stmts: if stmt.supported_by: children = flatten_stmts(stmt.supported_by) total_stmts = total_stmts.union(children) return list(total_stmts)
[ "def", "flatten_stmts", "(", "stmts", ")", ":", "total_stmts", "=", "set", "(", "stmts", ")", "for", "stmt", "in", "stmts", ":", "if", "stmt", ".", "supported_by", ":", "children", "=", "flatten_stmts", "(", "stmt", ".", "supported_by", ")", "total_stmts",...
Return the full set of unique stms in a pre-assembled stmt graph. The flattened list of statements returned by this function can be compared to the original set of unique statements to make sure no statements have been lost during the preassembly process. Parameters ---------- stmts : list of :py:class:`indra.statements.Statement` A list of top-level statements with associated supporting statements resulting from building a statement hierarchy with :py:meth:`combine_related`. Returns ------- stmts : list of :py:class:`indra.statements.Statement` List of all statements contained in the hierarchical statement graph. Examples -------- Calling :py:meth:`combine_related` on two statements results in one top-level statement; calling :py:func:`flatten_stmts` recovers both: >>> from indra.preassembler.hierarchy_manager import hierarchies >>> braf = Agent('BRAF') >>> map2k1 = Agent('MAP2K1') >>> st1 = Phosphorylation(braf, map2k1) >>> st2 = Phosphorylation(braf, map2k1, residue='S') >>> pa = Preassembler(hierarchies, [st1, st2]) >>> pa.combine_related() # doctest:+ELLIPSIS [Phosphorylation(BRAF(), MAP2K1(), S)] >>> flattened = flatten_stmts(pa.related_stmts) >>> flattened.sort(key=lambda x: x.matches_key()) >>> flattened [Phosphorylation(BRAF(), MAP2K1()), Phosphorylation(BRAF(), MAP2K1(), S)]
[ "Return", "the", "full", "set", "of", "unique", "stms", "in", "a", "pre", "-", "assembled", "stmt", "graph", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/preassembler/__init__.py#L755-L797
19,240
sorgerlab/indra
indra/preassembler/__init__.py
Preassembler.combine_duplicates
def combine_duplicates(self): """Combine duplicates among `stmts` and save result in `unique_stmts`. A wrapper around the static method :py:meth:`combine_duplicate_stmts`. """ if self.unique_stmts is None: self.unique_stmts = self.combine_duplicate_stmts(self.stmts) return self.unique_stmts
python
def combine_duplicates(self): if self.unique_stmts is None: self.unique_stmts = self.combine_duplicate_stmts(self.stmts) return self.unique_stmts
[ "def", "combine_duplicates", "(", "self", ")", ":", "if", "self", ".", "unique_stmts", "is", "None", ":", "self", ".", "unique_stmts", "=", "self", ".", "combine_duplicate_stmts", "(", "self", ".", "stmts", ")", "return", "self", ".", "unique_stmts" ]
Combine duplicates among `stmts` and save result in `unique_stmts`. A wrapper around the static method :py:meth:`combine_duplicate_stmts`.
[ "Combine", "duplicates", "among", "stmts", "and", "save", "result", "in", "unique_stmts", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/preassembler/__init__.py#L68-L75
19,241
sorgerlab/indra
indra/preassembler/__init__.py
Preassembler._get_stmt_matching_groups
def _get_stmt_matching_groups(stmts): """Use the matches_key method to get sets of matching statements.""" def match_func(x): return x.matches_key() # Remove exact duplicates using a set() call, then make copies: logger.debug('%d statements before removing object duplicates.' % len(stmts)) st = list(set(stmts)) logger.debug('%d statements after removing object duplicates.' % len(stmts)) # Group statements according to whether they are matches (differing # only in their evidence). # Sort the statements in place by matches_key() st.sort(key=match_func) return itertools.groupby(st, key=match_func)
python
def _get_stmt_matching_groups(stmts): def match_func(x): return x.matches_key() # Remove exact duplicates using a set() call, then make copies: logger.debug('%d statements before removing object duplicates.' % len(stmts)) st = list(set(stmts)) logger.debug('%d statements after removing object duplicates.' % len(stmts)) # Group statements according to whether they are matches (differing # only in their evidence). # Sort the statements in place by matches_key() st.sort(key=match_func) return itertools.groupby(st, key=match_func)
[ "def", "_get_stmt_matching_groups", "(", "stmts", ")", ":", "def", "match_func", "(", "x", ")", ":", "return", "x", ".", "matches_key", "(", ")", "# Remove exact duplicates using a set() call, then make copies:", "logger", ".", "debug", "(", "'%d statements before remov...
Use the matches_key method to get sets of matching statements.
[ "Use", "the", "matches_key", "method", "to", "get", "sets", "of", "matching", "statements", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/preassembler/__init__.py#L78-L93
19,242
sorgerlab/indra
indra/preassembler/__init__.py
Preassembler.combine_duplicate_stmts
def combine_duplicate_stmts(stmts): """Combine evidence from duplicate Statements. Statements are deemed to be duplicates if they have the same key returned by the `matches_key()` method of the Statement class. This generally means that statements must be identical in terms of their arguments and can differ only in their associated `Evidence` objects. This function keeps the first instance of each set of duplicate statements and merges the lists of Evidence from all of the other statements. Parameters ---------- stmts : list of :py:class:`indra.statements.Statement` Set of statements to de-duplicate. Returns ------- list of :py:class:`indra.statements.Statement` Unique statements with accumulated evidence across duplicates. Examples -------- De-duplicate and combine evidence for two statements differing only in their evidence lists: >>> map2k1 = Agent('MAP2K1') >>> mapk1 = Agent('MAPK1') >>> stmt1 = Phosphorylation(map2k1, mapk1, 'T', '185', ... evidence=[Evidence(text='evidence 1')]) >>> stmt2 = Phosphorylation(map2k1, mapk1, 'T', '185', ... evidence=[Evidence(text='evidence 2')]) >>> uniq_stmts = Preassembler.combine_duplicate_stmts([stmt1, stmt2]) >>> uniq_stmts [Phosphorylation(MAP2K1(), MAPK1(), T, 185)] >>> sorted([e.text for e in uniq_stmts[0].evidence]) # doctest:+IGNORE_UNICODE ['evidence 1', 'evidence 2'] """ # Helper function to get a list of evidence matches keys def _ev_keys(sts): ev_keys = [] for stmt in sts: for ev in stmt.evidence: ev_keys.append(ev.matches_key()) return ev_keys # Iterate over groups of duplicate statements unique_stmts = [] for _, duplicates in Preassembler._get_stmt_matching_groups(stmts): ev_keys = set() # Get the first statement and add the evidence of all subsequent # Statements to it duplicates = list(duplicates) start_ev_keys = _ev_keys(duplicates) for stmt_ix, stmt in enumerate(duplicates): if stmt_ix is 0: new_stmt = stmt.make_generic_copy() if len(duplicates) == 1: new_stmt.uuid = stmt.uuid raw_text = [None if ag is None else ag.db_refs.get('TEXT') for ag in stmt.agent_list(deep_sorted=True)] raw_grounding = [None if ag is None else ag.db_refs for ag in stmt.agent_list(deep_sorted=True)] for ev in stmt.evidence: ev_key = ev.matches_key() + str(raw_text) + \ str(raw_grounding) if ev_key not in ev_keys: # In case there are already agents annotations, we # just add a new key for raw_text, otherwise create # a new key if 'agents' in ev.annotations: ev.annotations['agents']['raw_text'] = raw_text ev.annotations['agents']['raw_grounding'] = \ raw_grounding else: ev.annotations['agents'] = \ {'raw_text': raw_text, 'raw_grounding': raw_grounding} if 'prior_uuids' not in ev.annotations: ev.annotations['prior_uuids'] = [] ev.annotations['prior_uuids'].append(stmt.uuid) new_stmt.evidence.append(ev) ev_keys.add(ev_key) end_ev_keys = _ev_keys([new_stmt]) if len(end_ev_keys) != len(start_ev_keys): logger.debug('%d redundant evidences eliminated.' % (len(start_ev_keys) - len(end_ev_keys))) # This should never be None or anything else assert isinstance(new_stmt, Statement) unique_stmts.append(new_stmt) return unique_stmts
python
def combine_duplicate_stmts(stmts): # Helper function to get a list of evidence matches keys def _ev_keys(sts): ev_keys = [] for stmt in sts: for ev in stmt.evidence: ev_keys.append(ev.matches_key()) return ev_keys # Iterate over groups of duplicate statements unique_stmts = [] for _, duplicates in Preassembler._get_stmt_matching_groups(stmts): ev_keys = set() # Get the first statement and add the evidence of all subsequent # Statements to it duplicates = list(duplicates) start_ev_keys = _ev_keys(duplicates) for stmt_ix, stmt in enumerate(duplicates): if stmt_ix is 0: new_stmt = stmt.make_generic_copy() if len(duplicates) == 1: new_stmt.uuid = stmt.uuid raw_text = [None if ag is None else ag.db_refs.get('TEXT') for ag in stmt.agent_list(deep_sorted=True)] raw_grounding = [None if ag is None else ag.db_refs for ag in stmt.agent_list(deep_sorted=True)] for ev in stmt.evidence: ev_key = ev.matches_key() + str(raw_text) + \ str(raw_grounding) if ev_key not in ev_keys: # In case there are already agents annotations, we # just add a new key for raw_text, otherwise create # a new key if 'agents' in ev.annotations: ev.annotations['agents']['raw_text'] = raw_text ev.annotations['agents']['raw_grounding'] = \ raw_grounding else: ev.annotations['agents'] = \ {'raw_text': raw_text, 'raw_grounding': raw_grounding} if 'prior_uuids' not in ev.annotations: ev.annotations['prior_uuids'] = [] ev.annotations['prior_uuids'].append(stmt.uuid) new_stmt.evidence.append(ev) ev_keys.add(ev_key) end_ev_keys = _ev_keys([new_stmt]) if len(end_ev_keys) != len(start_ev_keys): logger.debug('%d redundant evidences eliminated.' % (len(start_ev_keys) - len(end_ev_keys))) # This should never be None or anything else assert isinstance(new_stmt, Statement) unique_stmts.append(new_stmt) return unique_stmts
[ "def", "combine_duplicate_stmts", "(", "stmts", ")", ":", "# Helper function to get a list of evidence matches keys", "def", "_ev_keys", "(", "sts", ")", ":", "ev_keys", "=", "[", "]", "for", "stmt", "in", "sts", ":", "for", "ev", "in", "stmt", ".", "evidence", ...
Combine evidence from duplicate Statements. Statements are deemed to be duplicates if they have the same key returned by the `matches_key()` method of the Statement class. This generally means that statements must be identical in terms of their arguments and can differ only in their associated `Evidence` objects. This function keeps the first instance of each set of duplicate statements and merges the lists of Evidence from all of the other statements. Parameters ---------- stmts : list of :py:class:`indra.statements.Statement` Set of statements to de-duplicate. Returns ------- list of :py:class:`indra.statements.Statement` Unique statements with accumulated evidence across duplicates. Examples -------- De-duplicate and combine evidence for two statements differing only in their evidence lists: >>> map2k1 = Agent('MAP2K1') >>> mapk1 = Agent('MAPK1') >>> stmt1 = Phosphorylation(map2k1, mapk1, 'T', '185', ... evidence=[Evidence(text='evidence 1')]) >>> stmt2 = Phosphorylation(map2k1, mapk1, 'T', '185', ... evidence=[Evidence(text='evidence 2')]) >>> uniq_stmts = Preassembler.combine_duplicate_stmts([stmt1, stmt2]) >>> uniq_stmts [Phosphorylation(MAP2K1(), MAPK1(), T, 185)] >>> sorted([e.text for e in uniq_stmts[0].evidence]) # doctest:+IGNORE_UNICODE ['evidence 1', 'evidence 2']
[ "Combine", "evidence", "from", "duplicate", "Statements", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/preassembler/__init__.py#L96-L186
19,243
sorgerlab/indra
indra/preassembler/__init__.py
Preassembler._get_stmt_by_group
def _get_stmt_by_group(self, stmt_type, stmts_this_type, eh): """Group Statements of `stmt_type` by their hierarchical relations.""" # Dict of stmt group key tuples, indexed by their first Agent stmt_by_first = collections.defaultdict(lambda: []) # Dict of stmt group key tuples, indexed by their second Agent stmt_by_second = collections.defaultdict(lambda: []) # Dict of statements with None first, with second Agent as keys none_first = collections.defaultdict(lambda: []) # Dict of statements with None second, with first Agent as keys none_second = collections.defaultdict(lambda: []) # The dict of all statement groups, with tuples of components # or entity_matches_keys as keys stmt_by_group = collections.defaultdict(lambda: []) # Here we group Statements according to the hierarchy graph # components that their agents are part of for stmt_tuple in stmts_this_type: _, stmt = stmt_tuple entities = self._get_entities(stmt, stmt_type, eh) # At this point we have an entity list # If we're dealing with Complexes, sort the entities and use # as dict key if stmt_type == Complex: # There shouldn't be any statements of the type # e.g., Complex([Foo, None, Bar]) assert None not in entities assert len(entities) > 0 entities.sort() key = tuple(entities) if stmt_tuple not in stmt_by_group[key]: stmt_by_group[key].append(stmt_tuple) elif stmt_type == Conversion: assert len(entities) > 0 key = (entities[0], tuple(sorted(entities[1:len(stmt.obj_from)+1])), tuple(sorted(entities[-len(stmt.obj_to):]))) if stmt_tuple not in stmt_by_group[key]: stmt_by_group[key].append(stmt_tuple) # Now look at all other statement types # All other statements will have one or two entities elif len(entities) == 1: # If only one entity, we only need the one key # It should not be None! assert None not in entities key = tuple(entities) if stmt_tuple not in stmt_by_group[key]: stmt_by_group[key].append(stmt_tuple) else: # Make sure we only have two entities, and they are not both # None key = tuple(entities) assert len(key) == 2 assert key != (None, None) # First agent is None; add in the statements, indexed by # 2nd if key[0] is None and stmt_tuple not in none_first[key[1]]: none_first[key[1]].append(stmt_tuple) # Second agent is None; add in the statements, indexed by # 1st elif key[1] is None and stmt_tuple not in none_second[key[0]]: none_second[key[0]].append(stmt_tuple) # Neither entity is None! elif None not in key: if stmt_tuple not in stmt_by_group[key]: stmt_by_group[key].append(stmt_tuple) if key not in stmt_by_first[key[0]]: stmt_by_first[key[0]].append(key) if key not in stmt_by_second[key[1]]: stmt_by_second[key[1]].append(key) # When we've gotten here, we should have stmt_by_group entries, and # we may or may not have stmt_by_first/second dicts filled out # (depending on the statement type). if none_first: # Get the keys associated with stmts having a None first # argument for second_arg, stmts in none_first.items(): # Look for any statements with this second arg second_arg_keys = stmt_by_second[second_arg] # If there are no more specific statements matching this # set of statements with a None first arg, then the # statements with the None first arg deserve to be in # their own group. if not second_arg_keys: stmt_by_group[(None, second_arg)] = stmts # On the other hand, if there are statements with a matching # second arg component, we need to add the None first # statements to all groups with the matching second arg for second_arg_key in second_arg_keys: stmt_by_group[second_arg_key] += stmts # Now do the corresponding steps for the statements with None as the # second argument: if none_second: for first_arg, stmts in none_second.items(): # Look for any statements with this first arg first_arg_keys = stmt_by_first[first_arg] # If there are no more specific statements matching this # set of statements with a None second arg, then the # statements with the None second arg deserve to be in # their own group. if not first_arg_keys: stmt_by_group[(first_arg, None)] = stmts # On the other hand, if there are statements with a matching # first arg component, we need to add the None second # statements to all groups with the matching first arg for first_arg_key in first_arg_keys: stmt_by_group[first_arg_key] += stmts return stmt_by_group
python
def _get_stmt_by_group(self, stmt_type, stmts_this_type, eh): # Dict of stmt group key tuples, indexed by their first Agent stmt_by_first = collections.defaultdict(lambda: []) # Dict of stmt group key tuples, indexed by their second Agent stmt_by_second = collections.defaultdict(lambda: []) # Dict of statements with None first, with second Agent as keys none_first = collections.defaultdict(lambda: []) # Dict of statements with None second, with first Agent as keys none_second = collections.defaultdict(lambda: []) # The dict of all statement groups, with tuples of components # or entity_matches_keys as keys stmt_by_group = collections.defaultdict(lambda: []) # Here we group Statements according to the hierarchy graph # components that their agents are part of for stmt_tuple in stmts_this_type: _, stmt = stmt_tuple entities = self._get_entities(stmt, stmt_type, eh) # At this point we have an entity list # If we're dealing with Complexes, sort the entities and use # as dict key if stmt_type == Complex: # There shouldn't be any statements of the type # e.g., Complex([Foo, None, Bar]) assert None not in entities assert len(entities) > 0 entities.sort() key = tuple(entities) if stmt_tuple not in stmt_by_group[key]: stmt_by_group[key].append(stmt_tuple) elif stmt_type == Conversion: assert len(entities) > 0 key = (entities[0], tuple(sorted(entities[1:len(stmt.obj_from)+1])), tuple(sorted(entities[-len(stmt.obj_to):]))) if stmt_tuple not in stmt_by_group[key]: stmt_by_group[key].append(stmt_tuple) # Now look at all other statement types # All other statements will have one or two entities elif len(entities) == 1: # If only one entity, we only need the one key # It should not be None! assert None not in entities key = tuple(entities) if stmt_tuple not in stmt_by_group[key]: stmt_by_group[key].append(stmt_tuple) else: # Make sure we only have two entities, and they are not both # None key = tuple(entities) assert len(key) == 2 assert key != (None, None) # First agent is None; add in the statements, indexed by # 2nd if key[0] is None and stmt_tuple not in none_first[key[1]]: none_first[key[1]].append(stmt_tuple) # Second agent is None; add in the statements, indexed by # 1st elif key[1] is None and stmt_tuple not in none_second[key[0]]: none_second[key[0]].append(stmt_tuple) # Neither entity is None! elif None not in key: if stmt_tuple not in stmt_by_group[key]: stmt_by_group[key].append(stmt_tuple) if key not in stmt_by_first[key[0]]: stmt_by_first[key[0]].append(key) if key not in stmt_by_second[key[1]]: stmt_by_second[key[1]].append(key) # When we've gotten here, we should have stmt_by_group entries, and # we may or may not have stmt_by_first/second dicts filled out # (depending on the statement type). if none_first: # Get the keys associated with stmts having a None first # argument for second_arg, stmts in none_first.items(): # Look for any statements with this second arg second_arg_keys = stmt_by_second[second_arg] # If there are no more specific statements matching this # set of statements with a None first arg, then the # statements with the None first arg deserve to be in # their own group. if not second_arg_keys: stmt_by_group[(None, second_arg)] = stmts # On the other hand, if there are statements with a matching # second arg component, we need to add the None first # statements to all groups with the matching second arg for second_arg_key in second_arg_keys: stmt_by_group[second_arg_key] += stmts # Now do the corresponding steps for the statements with None as the # second argument: if none_second: for first_arg, stmts in none_second.items(): # Look for any statements with this first arg first_arg_keys = stmt_by_first[first_arg] # If there are no more specific statements matching this # set of statements with a None second arg, then the # statements with the None second arg deserve to be in # their own group. if not first_arg_keys: stmt_by_group[(first_arg, None)] = stmts # On the other hand, if there are statements with a matching # first arg component, we need to add the None second # statements to all groups with the matching first arg for first_arg_key in first_arg_keys: stmt_by_group[first_arg_key] += stmts return stmt_by_group
[ "def", "_get_stmt_by_group", "(", "self", ",", "stmt_type", ",", "stmts_this_type", ",", "eh", ")", ":", "# Dict of stmt group key tuples, indexed by their first Agent", "stmt_by_first", "=", "collections", ".", "defaultdict", "(", "lambda", ":", "[", "]", ")", "# Dic...
Group Statements of `stmt_type` by their hierarchical relations.
[ "Group", "Statements", "of", "stmt_type", "by", "their", "hierarchical", "relations", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/preassembler/__init__.py#L220-L326
19,244
sorgerlab/indra
indra/preassembler/__init__.py
Preassembler.combine_related
def combine_related(self, return_toplevel=True, poolsize=None, size_cutoff=100): """Connect related statements based on their refinement relationships. This function takes as a starting point the unique statements (with duplicates removed) and returns a modified flat list of statements containing only those statements which do not represent a refinement of other existing statements. In other words, the more general versions of a given statement do not appear at the top level, but instead are listed in the `supports` field of the top-level statements. If :py:attr:`unique_stmts` has not been initialized with the de-duplicated statements, :py:meth:`combine_duplicates` is called internally. After this function is called the attribute :py:attr:`related_stmts` is set as a side-effect. The procedure for combining statements in this way involves a series of steps: 1. The statements are grouped by type (e.g., Phosphorylation) and each type is iterated over independently. 2. Statements of the same type are then grouped according to their Agents' entity hierarchy component identifiers. For instance, ERK, MAPK1 and MAPK3 are all in the same connected component in the entity hierarchy and therefore all Statements of the same type referencing these entities will be grouped. This grouping assures that relations are only possible within Statement groups and not among groups. For two Statements to be in the same group at this step, the Statements must be the same type and the Agents at each position in the Agent lists must either be in the same hierarchy component, or if they are not in the hierarchy, must have identical entity_matches_keys. Statements with None in one of the Agent list positions are collected separately at this stage. 3. Statements with None at either the first or second position are iterated over. For a statement with a None as the first Agent, the second Agent is examined; then the Statement with None is added to all Statement groups with a corresponding component or entity_matches_key in the second position. The same procedure is performed for Statements with None at the second Agent position. 4. The statements within each group are then compared; if one statement represents a refinement of the other (as defined by the `refinement_of()` method implemented for the Statement), then the more refined statement is added to the `supports` field of the more general statement, and the more general statement is added to the `supported_by` field of the more refined statement. 5. A new flat list of statements is created that contains only those statements that have no `supports` entries (statements containing such entries are not eliminated, because they will be retrievable from the `supported_by` fields of other statements). This list is returned to the caller. On multi-core machines, the algorithm can be parallelized by setting the poolsize argument to the desired number of worker processes. This feature is only available in Python > 3.4. .. note:: Subfamily relationships must be consistent across arguments For now, we require that merges can only occur if the *isa* relationships are all in the *same direction for all the agents* in a Statement. For example, the two statement groups: `RAF_family -> MEK1` and `BRAF -> MEK_family` would not be merged, since BRAF *isa* RAF_family, but MEK_family is not a MEK1. In the future this restriction could be revisited. Parameters ---------- return_toplevel : Optional[bool] If True only the top level statements are returned. If False, all statements are returned. Default: True poolsize : Optional[int] The number of worker processes to use to parallelize the comparisons performed by the function. If None (default), no parallelization is performed. NOTE: Parallelization is only available on Python 3.4 and above. size_cutoff : Optional[int] Groups with size_cutoff or more statements are sent to worker processes, while smaller groups are compared in the parent process. Default value is 100. Not relevant when parallelization is not used. Returns ------- list of :py:class:`indra.statement.Statement` The returned list contains Statements representing the more concrete/refined versions of the Statements involving particular entities. The attribute :py:attr:`related_stmts` is also set to this list. However, if return_toplevel is False then all statements are returned, irrespective of level of specificity. In this case the relationships between statements can be accessed via the supports/supported_by attributes. Examples -------- A more general statement with no information about a Phosphorylation site is identified as supporting a more specific statement: >>> from indra.preassembler.hierarchy_manager import hierarchies >>> braf = Agent('BRAF') >>> map2k1 = Agent('MAP2K1') >>> st1 = Phosphorylation(braf, map2k1) >>> st2 = Phosphorylation(braf, map2k1, residue='S') >>> pa = Preassembler(hierarchies, [st1, st2]) >>> combined_stmts = pa.combine_related() # doctest:+ELLIPSIS >>> combined_stmts [Phosphorylation(BRAF(), MAP2K1(), S)] >>> combined_stmts[0].supported_by [Phosphorylation(BRAF(), MAP2K1())] >>> combined_stmts[0].supported_by[0].supports [Phosphorylation(BRAF(), MAP2K1(), S)] """ if self.related_stmts is not None: if return_toplevel: return self.related_stmts else: assert self.unique_stmts is not None return self.unique_stmts # Call combine_duplicates, which lazily initializes self.unique_stmts unique_stmts = self.combine_duplicates() # Generate the index map, linking related statements. idx_map = self._generate_id_maps(unique_stmts, poolsize, size_cutoff) # Now iterate over all indices and set supports/supported by for ix1, ix2 in idx_map: unique_stmts[ix1].supported_by.append(unique_stmts[ix2]) unique_stmts[ix2].supports.append(unique_stmts[ix1]) # Get the top level statements self.related_stmts = [st for st in unique_stmts if not st.supports] logger.debug('%d top level' % len(self.related_stmts)) if return_toplevel: return self.related_stmts else: return unique_stmts
python
def combine_related(self, return_toplevel=True, poolsize=None, size_cutoff=100): if self.related_stmts is not None: if return_toplevel: return self.related_stmts else: assert self.unique_stmts is not None return self.unique_stmts # Call combine_duplicates, which lazily initializes self.unique_stmts unique_stmts = self.combine_duplicates() # Generate the index map, linking related statements. idx_map = self._generate_id_maps(unique_stmts, poolsize, size_cutoff) # Now iterate over all indices and set supports/supported by for ix1, ix2 in idx_map: unique_stmts[ix1].supported_by.append(unique_stmts[ix2]) unique_stmts[ix2].supports.append(unique_stmts[ix1]) # Get the top level statements self.related_stmts = [st for st in unique_stmts if not st.supports] logger.debug('%d top level' % len(self.related_stmts)) if return_toplevel: return self.related_stmts else: return unique_stmts
[ "def", "combine_related", "(", "self", ",", "return_toplevel", "=", "True", ",", "poolsize", "=", "None", ",", "size_cutoff", "=", "100", ")", ":", "if", "self", ".", "related_stmts", "is", "not", "None", ":", "if", "return_toplevel", ":", "return", "self"...
Connect related statements based on their refinement relationships. This function takes as a starting point the unique statements (with duplicates removed) and returns a modified flat list of statements containing only those statements which do not represent a refinement of other existing statements. In other words, the more general versions of a given statement do not appear at the top level, but instead are listed in the `supports` field of the top-level statements. If :py:attr:`unique_stmts` has not been initialized with the de-duplicated statements, :py:meth:`combine_duplicates` is called internally. After this function is called the attribute :py:attr:`related_stmts` is set as a side-effect. The procedure for combining statements in this way involves a series of steps: 1. The statements are grouped by type (e.g., Phosphorylation) and each type is iterated over independently. 2. Statements of the same type are then grouped according to their Agents' entity hierarchy component identifiers. For instance, ERK, MAPK1 and MAPK3 are all in the same connected component in the entity hierarchy and therefore all Statements of the same type referencing these entities will be grouped. This grouping assures that relations are only possible within Statement groups and not among groups. For two Statements to be in the same group at this step, the Statements must be the same type and the Agents at each position in the Agent lists must either be in the same hierarchy component, or if they are not in the hierarchy, must have identical entity_matches_keys. Statements with None in one of the Agent list positions are collected separately at this stage. 3. Statements with None at either the first or second position are iterated over. For a statement with a None as the first Agent, the second Agent is examined; then the Statement with None is added to all Statement groups with a corresponding component or entity_matches_key in the second position. The same procedure is performed for Statements with None at the second Agent position. 4. The statements within each group are then compared; if one statement represents a refinement of the other (as defined by the `refinement_of()` method implemented for the Statement), then the more refined statement is added to the `supports` field of the more general statement, and the more general statement is added to the `supported_by` field of the more refined statement. 5. A new flat list of statements is created that contains only those statements that have no `supports` entries (statements containing such entries are not eliminated, because they will be retrievable from the `supported_by` fields of other statements). This list is returned to the caller. On multi-core machines, the algorithm can be parallelized by setting the poolsize argument to the desired number of worker processes. This feature is only available in Python > 3.4. .. note:: Subfamily relationships must be consistent across arguments For now, we require that merges can only occur if the *isa* relationships are all in the *same direction for all the agents* in a Statement. For example, the two statement groups: `RAF_family -> MEK1` and `BRAF -> MEK_family` would not be merged, since BRAF *isa* RAF_family, but MEK_family is not a MEK1. In the future this restriction could be revisited. Parameters ---------- return_toplevel : Optional[bool] If True only the top level statements are returned. If False, all statements are returned. Default: True poolsize : Optional[int] The number of worker processes to use to parallelize the comparisons performed by the function. If None (default), no parallelization is performed. NOTE: Parallelization is only available on Python 3.4 and above. size_cutoff : Optional[int] Groups with size_cutoff or more statements are sent to worker processes, while smaller groups are compared in the parent process. Default value is 100. Not relevant when parallelization is not used. Returns ------- list of :py:class:`indra.statement.Statement` The returned list contains Statements representing the more concrete/refined versions of the Statements involving particular entities. The attribute :py:attr:`related_stmts` is also set to this list. However, if return_toplevel is False then all statements are returned, irrespective of level of specificity. In this case the relationships between statements can be accessed via the supports/supported_by attributes. Examples -------- A more general statement with no information about a Phosphorylation site is identified as supporting a more specific statement: >>> from indra.preassembler.hierarchy_manager import hierarchies >>> braf = Agent('BRAF') >>> map2k1 = Agent('MAP2K1') >>> st1 = Phosphorylation(braf, map2k1) >>> st2 = Phosphorylation(braf, map2k1, residue='S') >>> pa = Preassembler(hierarchies, [st1, st2]) >>> combined_stmts = pa.combine_related() # doctest:+ELLIPSIS >>> combined_stmts [Phosphorylation(BRAF(), MAP2K1(), S)] >>> combined_stmts[0].supported_by [Phosphorylation(BRAF(), MAP2K1())] >>> combined_stmts[0].supported_by[0].supports [Phosphorylation(BRAF(), MAP2K1(), S)]
[ "Connect", "related", "statements", "based", "on", "their", "refinement", "relationships", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/preassembler/__init__.py#L428-L563
19,245
sorgerlab/indra
indra/preassembler/__init__.py
Preassembler.find_contradicts
def find_contradicts(self): """Return pairs of contradicting Statements. Returns ------- contradicts : list(tuple(Statement, Statement)) A list of Statement pairs that are contradicting. """ eh = self.hierarchies['entity'] # Make a dict of Statement by type stmts_by_type = collections.defaultdict(lambda: []) for idx, stmt in enumerate(self.stmts): stmts_by_type[indra_stmt_type(stmt)].append((idx, stmt)) # Handle Statements with polarity first pos_stmts = AddModification.__subclasses__() neg_stmts = [modclass_to_inverse[c] for c in pos_stmts] pos_stmts += [Activation, IncreaseAmount] neg_stmts += [Inhibition, DecreaseAmount] contradicts = [] for pst, nst in zip(pos_stmts, neg_stmts): poss = stmts_by_type.get(pst, []) negs = stmts_by_type.get(nst, []) pos_stmt_by_group = self._get_stmt_by_group(pst, poss, eh) neg_stmt_by_group = self._get_stmt_by_group(nst, negs, eh) for key, pg in pos_stmt_by_group.items(): ng = neg_stmt_by_group.get(key, []) for (_, st1), (_, st2) in itertools.product(pg, ng): if st1.contradicts(st2, self.hierarchies): contradicts.append((st1, st2)) # Handle neutral Statements next neu_stmts = [Influence, ActiveForm] for stt in neu_stmts: stmts = stmts_by_type.get(stt, []) for (_, st1), (_, st2) in itertools.combinations(stmts, 2): if st1.contradicts(st2, self.hierarchies): contradicts.append((st1, st2)) return contradicts
python
def find_contradicts(self): eh = self.hierarchies['entity'] # Make a dict of Statement by type stmts_by_type = collections.defaultdict(lambda: []) for idx, stmt in enumerate(self.stmts): stmts_by_type[indra_stmt_type(stmt)].append((idx, stmt)) # Handle Statements with polarity first pos_stmts = AddModification.__subclasses__() neg_stmts = [modclass_to_inverse[c] for c in pos_stmts] pos_stmts += [Activation, IncreaseAmount] neg_stmts += [Inhibition, DecreaseAmount] contradicts = [] for pst, nst in zip(pos_stmts, neg_stmts): poss = stmts_by_type.get(pst, []) negs = stmts_by_type.get(nst, []) pos_stmt_by_group = self._get_stmt_by_group(pst, poss, eh) neg_stmt_by_group = self._get_stmt_by_group(nst, negs, eh) for key, pg in pos_stmt_by_group.items(): ng = neg_stmt_by_group.get(key, []) for (_, st1), (_, st2) in itertools.product(pg, ng): if st1.contradicts(st2, self.hierarchies): contradicts.append((st1, st2)) # Handle neutral Statements next neu_stmts = [Influence, ActiveForm] for stt in neu_stmts: stmts = stmts_by_type.get(stt, []) for (_, st1), (_, st2) in itertools.combinations(stmts, 2): if st1.contradicts(st2, self.hierarchies): contradicts.append((st1, st2)) return contradicts
[ "def", "find_contradicts", "(", "self", ")", ":", "eh", "=", "self", ".", "hierarchies", "[", "'entity'", "]", "# Make a dict of Statement by type", "stmts_by_type", "=", "collections", ".", "defaultdict", "(", "lambda", ":", "[", "]", ")", "for", "idx", ",", ...
Return pairs of contradicting Statements. Returns ------- contradicts : list(tuple(Statement, Statement)) A list of Statement pairs that are contradicting.
[ "Return", "pairs", "of", "contradicting", "Statements", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/preassembler/__init__.py#L565-L608
19,246
sorgerlab/indra
indra/literature/deft_tools.py
get_text_content_for_pmids
def get_text_content_for_pmids(pmids): """Get text content for articles given a list of their pmids Parameters ---------- pmids : list of str Returns ------- text_content : list of str """ pmc_pmids = set(pmc_client.filter_pmids(pmids, source_type='fulltext')) pmc_ids = [] for pmid in pmc_pmids: pmc_id = pmc_client.id_lookup(pmid, idtype='pmid')['pmcid'] if pmc_id: pmc_ids.append(pmc_id) else: pmc_pmids.discard(pmid) pmc_xmls = [] failed = set() for pmc_id in pmc_ids: if pmc_id is not None: pmc_xmls.append(pmc_client.get_xml(pmc_id)) else: failed.append(pmid) time.sleep(0.5) remaining_pmids = set(pmids) - pmc_pmids | failed abstracts = [] for pmid in remaining_pmids: abstract = pubmed_client.get_abstract(pmid) abstracts.append(abstract) time.sleep(0.5) return [text_content for source in (pmc_xmls, abstracts) for text_content in source if text_content is not None]
python
def get_text_content_for_pmids(pmids): pmc_pmids = set(pmc_client.filter_pmids(pmids, source_type='fulltext')) pmc_ids = [] for pmid in pmc_pmids: pmc_id = pmc_client.id_lookup(pmid, idtype='pmid')['pmcid'] if pmc_id: pmc_ids.append(pmc_id) else: pmc_pmids.discard(pmid) pmc_xmls = [] failed = set() for pmc_id in pmc_ids: if pmc_id is not None: pmc_xmls.append(pmc_client.get_xml(pmc_id)) else: failed.append(pmid) time.sleep(0.5) remaining_pmids = set(pmids) - pmc_pmids | failed abstracts = [] for pmid in remaining_pmids: abstract = pubmed_client.get_abstract(pmid) abstracts.append(abstract) time.sleep(0.5) return [text_content for source in (pmc_xmls, abstracts) for text_content in source if text_content is not None]
[ "def", "get_text_content_for_pmids", "(", "pmids", ")", ":", "pmc_pmids", "=", "set", "(", "pmc_client", ".", "filter_pmids", "(", "pmids", ",", "source_type", "=", "'fulltext'", ")", ")", "pmc_ids", "=", "[", "]", "for", "pmid", "in", "pmc_pmids", ":", "p...
Get text content for articles given a list of their pmids Parameters ---------- pmids : list of str Returns ------- text_content : list of str
[ "Get", "text", "content", "for", "articles", "given", "a", "list", "of", "their", "pmids" ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/literature/deft_tools.py#L46-L84
19,247
sorgerlab/indra
indra/literature/deft_tools.py
universal_extract_paragraphs
def universal_extract_paragraphs(xml): """Extract paragraphs from xml that could be from different sources First try to parse the xml as if it came from elsevier. if we do not have valid elsevier xml this will throw an exception. the text extraction function in the pmc client may not throw an exception when parsing elsevier xml, silently processing the xml incorrectly Parameters ---------- xml : str Either an NLM xml, Elsevier xml or plaintext Returns ------- paragraphs : str Extracted plaintext paragraphs from NLM or Elsevier XML """ try: paragraphs = elsevier_client.extract_paragraphs(xml) except Exception: paragraphs = None if paragraphs is None: try: paragraphs = pmc_client.extract_paragraphs(xml) except Exception: paragraphs = [xml] return paragraphs
python
def universal_extract_paragraphs(xml): try: paragraphs = elsevier_client.extract_paragraphs(xml) except Exception: paragraphs = None if paragraphs is None: try: paragraphs = pmc_client.extract_paragraphs(xml) except Exception: paragraphs = [xml] return paragraphs
[ "def", "universal_extract_paragraphs", "(", "xml", ")", ":", "try", ":", "paragraphs", "=", "elsevier_client", ".", "extract_paragraphs", "(", "xml", ")", "except", "Exception", ":", "paragraphs", "=", "None", "if", "paragraphs", "is", "None", ":", "try", ":",...
Extract paragraphs from xml that could be from different sources First try to parse the xml as if it came from elsevier. if we do not have valid elsevier xml this will throw an exception. the text extraction function in the pmc client may not throw an exception when parsing elsevier xml, silently processing the xml incorrectly Parameters ---------- xml : str Either an NLM xml, Elsevier xml or plaintext Returns ------- paragraphs : str Extracted plaintext paragraphs from NLM or Elsevier XML
[ "Extract", "paragraphs", "from", "xml", "that", "could", "be", "from", "different", "sources" ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/literature/deft_tools.py#L87-L114
19,248
sorgerlab/indra
indra/literature/deft_tools.py
filter_paragraphs
def filter_paragraphs(paragraphs, contains=None): """Filter paragraphs to only those containing one of a list of strings Parameters ---------- paragraphs : list of str List of plaintext paragraphs from an article contains : str or list of str Exclude paragraphs not containing this string as a token, or at least one of the strings in contains if it is a list Returns ------- str Plaintext consisting of all input paragraphs containing at least one of the supplied tokens. """ if contains is None: pattern = '' else: if isinstance(contains, str): contains = [contains] pattern = '|'.join(r'[^\w]%s[^\w]' % shortform for shortform in contains) paragraphs = [p for p in paragraphs if re.search(pattern, p)] return '\n'.join(paragraphs) + '\n'
python
def filter_paragraphs(paragraphs, contains=None): if contains is None: pattern = '' else: if isinstance(contains, str): contains = [contains] pattern = '|'.join(r'[^\w]%s[^\w]' % shortform for shortform in contains) paragraphs = [p for p in paragraphs if re.search(pattern, p)] return '\n'.join(paragraphs) + '\n'
[ "def", "filter_paragraphs", "(", "paragraphs", ",", "contains", "=", "None", ")", ":", "if", "contains", "is", "None", ":", "pattern", "=", "''", "else", ":", "if", "isinstance", "(", "contains", ",", "str", ")", ":", "contains", "=", "[", "contains", ...
Filter paragraphs to only those containing one of a list of strings Parameters ---------- paragraphs : list of str List of plaintext paragraphs from an article contains : str or list of str Exclude paragraphs not containing this string as a token, or at least one of the strings in contains if it is a list Returns ------- str Plaintext consisting of all input paragraphs containing at least one of the supplied tokens.
[ "Filter", "paragraphs", "to", "only", "those", "containing", "one", "of", "a", "list", "of", "strings" ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/literature/deft_tools.py#L117-L143
19,249
sorgerlab/indra
indra/statements/resources.py
get_valid_residue
def get_valid_residue(residue): """Check if the given string represents a valid amino acid residue.""" if residue is not None and amino_acids.get(residue) is None: res = amino_acids_reverse.get(residue.lower()) if res is None: raise InvalidResidueError(residue) else: return res return residue
python
def get_valid_residue(residue): if residue is not None and amino_acids.get(residue) is None: res = amino_acids_reverse.get(residue.lower()) if res is None: raise InvalidResidueError(residue) else: return res return residue
[ "def", "get_valid_residue", "(", "residue", ")", ":", "if", "residue", "is", "not", "None", "and", "amino_acids", ".", "get", "(", "residue", ")", "is", "None", ":", "res", "=", "amino_acids_reverse", ".", "get", "(", "residue", ".", "lower", "(", ")", ...
Check if the given string represents a valid amino acid residue.
[ "Check", "if", "the", "given", "string", "represents", "a", "valid", "amino", "acid", "residue", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/statements/resources.py#L15-L23
19,250
sorgerlab/indra
indra/statements/resources.py
get_valid_location
def get_valid_location(location): """Check if the given location represents a valid cellular component.""" # If we're given None, return None if location is not None and cellular_components.get(location) is None: loc = cellular_components_reverse.get(location) if loc is None: raise InvalidLocationError(location) else: return loc return location
python
def get_valid_location(location): # If we're given None, return None if location is not None and cellular_components.get(location) is None: loc = cellular_components_reverse.get(location) if loc is None: raise InvalidLocationError(location) else: return loc return location
[ "def", "get_valid_location", "(", "location", ")", ":", "# If we're given None, return None", "if", "location", "is", "not", "None", "and", "cellular_components", ".", "get", "(", "location", ")", "is", "None", ":", "loc", "=", "cellular_components_reverse", ".", ...
Check if the given location represents a valid cellular component.
[ "Check", "if", "the", "given", "location", "represents", "a", "valid", "cellular", "component", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/statements/resources.py#L26-L35
19,251
sorgerlab/indra
indra/statements/resources.py
_read_activity_types
def _read_activity_types(): """Read types of valid activities from a resource file.""" this_dir = os.path.dirname(os.path.abspath(__file__)) ac_file = os.path.join(this_dir, os.pardir, 'resources', 'activity_hierarchy.rdf') g = rdflib.Graph() with open(ac_file, 'r'): g.parse(ac_file, format='nt') act_types = set() for s, _, o in g: subj = s.rpartition('/')[-1] obj = o.rpartition('/')[-1] act_types.add(subj) act_types.add(obj) return sorted(list(act_types))
python
def _read_activity_types(): this_dir = os.path.dirname(os.path.abspath(__file__)) ac_file = os.path.join(this_dir, os.pardir, 'resources', 'activity_hierarchy.rdf') g = rdflib.Graph() with open(ac_file, 'r'): g.parse(ac_file, format='nt') act_types = set() for s, _, o in g: subj = s.rpartition('/')[-1] obj = o.rpartition('/')[-1] act_types.add(subj) act_types.add(obj) return sorted(list(act_types))
[ "def", "_read_activity_types", "(", ")", ":", "this_dir", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "__file__", ")", ")", "ac_file", "=", "os", ".", "path", ".", "join", "(", "this_dir", ",", "os", ".", "p...
Read types of valid activities from a resource file.
[ "Read", "types", "of", "valid", "activities", "from", "a", "resource", "file", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/statements/resources.py#L38-L52
19,252
sorgerlab/indra
indra/statements/resources.py
_read_cellular_components
def _read_cellular_components(): """Read cellular components from a resource file.""" # Here we load a patch file in addition to the current cellular components # file to make sure we don't error with InvalidLocationError with some # deprecated cellular location names this_dir = os.path.dirname(os.path.abspath(__file__)) cc_file = os.path.join(this_dir, os.pardir, 'resources', 'cellular_components.tsv') cc_patch_file = os.path.join(this_dir, os.pardir, 'resources', 'cellular_components_patch.tsv') cellular_components = {} cellular_components_reverse = {} with open(cc_file, 'rt') as fh: lines = list(fh.readlines()) # We add the patch to the end of the lines list with open(cc_patch_file, 'rt') as fh: lines += list(fh.readlines()) for lin in lines[1:]: terms = lin.strip().split('\t') cellular_components[terms[1]] = terms[0] # If the GO -> name mapping doesn't exist yet, we add a mapping # but if it already exists (i.e. the try doesn't error) then # we don't add the GO -> name mapping. This ensures that names from # the patch file aren't mapped to in the reverse list. try: cellular_components_reverse[terms[0]] except KeyError: cellular_components_reverse[terms[0]] = terms[1] return cellular_components, cellular_components_reverse
python
def _read_cellular_components(): # Here we load a patch file in addition to the current cellular components # file to make sure we don't error with InvalidLocationError with some # deprecated cellular location names this_dir = os.path.dirname(os.path.abspath(__file__)) cc_file = os.path.join(this_dir, os.pardir, 'resources', 'cellular_components.tsv') cc_patch_file = os.path.join(this_dir, os.pardir, 'resources', 'cellular_components_patch.tsv') cellular_components = {} cellular_components_reverse = {} with open(cc_file, 'rt') as fh: lines = list(fh.readlines()) # We add the patch to the end of the lines list with open(cc_patch_file, 'rt') as fh: lines += list(fh.readlines()) for lin in lines[1:]: terms = lin.strip().split('\t') cellular_components[terms[1]] = terms[0] # If the GO -> name mapping doesn't exist yet, we add a mapping # but if it already exists (i.e. the try doesn't error) then # we don't add the GO -> name mapping. This ensures that names from # the patch file aren't mapped to in the reverse list. try: cellular_components_reverse[terms[0]] except KeyError: cellular_components_reverse[terms[0]] = terms[1] return cellular_components, cellular_components_reverse
[ "def", "_read_cellular_components", "(", ")", ":", "# Here we load a patch file in addition to the current cellular components", "# file to make sure we don't error with InvalidLocationError with some", "# deprecated cellular location names", "this_dir", "=", "os", ".", "path", ".", "dir...
Read cellular components from a resource file.
[ "Read", "cellular", "components", "from", "a", "resource", "file", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/statements/resources.py#L58-L86
19,253
sorgerlab/indra
indra/statements/resources.py
_read_amino_acids
def _read_amino_acids(): """Read the amino acid information from a resource file.""" this_dir = os.path.dirname(os.path.abspath(__file__)) aa_file = os.path.join(this_dir, os.pardir, 'resources', 'amino_acids.tsv') amino_acids = {} amino_acids_reverse = {} with open(aa_file, 'rt') as fh: lines = fh.readlines() for lin in lines[1:]: terms = lin.strip().split('\t') key = terms[2] val = {'full_name': terms[0], 'short_name': terms[1], 'indra_name': terms[3]} amino_acids[key] = val for v in val.values(): amino_acids_reverse[v] = key return amino_acids, amino_acids_reverse
python
def _read_amino_acids(): this_dir = os.path.dirname(os.path.abspath(__file__)) aa_file = os.path.join(this_dir, os.pardir, 'resources', 'amino_acids.tsv') amino_acids = {} amino_acids_reverse = {} with open(aa_file, 'rt') as fh: lines = fh.readlines() for lin in lines[1:]: terms = lin.strip().split('\t') key = terms[2] val = {'full_name': terms[0], 'short_name': terms[1], 'indra_name': terms[3]} amino_acids[key] = val for v in val.values(): amino_acids_reverse[v] = key return amino_acids, amino_acids_reverse
[ "def", "_read_amino_acids", "(", ")", ":", "this_dir", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "__file__", ")", ")", "aa_file", "=", "os", ".", "path", ".", "join", "(", "this_dir", ",", "os", ".", "pard...
Read the amino acid information from a resource file.
[ "Read", "the", "amino", "acid", "information", "from", "a", "resource", "file", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/statements/resources.py#L92-L109
19,254
sorgerlab/indra
indra/assemblers/pysb/export.py
export_sbgn
def export_sbgn(model): """Return an SBGN model string corresponding to the PySB model. This function first calls generate_equations on the PySB model to obtain a reaction network (i.e. individual species, reactions). It then iterates over each reaction and and instantiates its reactants, products, and the process itself as SBGN glyphs and arcs. Parameters ---------- model : pysb.core.Model A PySB model to be exported into SBGN Returns ------- sbgn_str : str An SBGN model as string """ import lxml.etree import lxml.builder from pysb.bng import generate_equations from indra.assemblers.sbgn import SBGNAssembler logger.info('Generating reaction network with BNG for SBGN export. ' + 'This could take a long time.') generate_equations(model) sa = SBGNAssembler() glyphs = {} for idx, species in enumerate(model.species): glyph = sa._glyph_for_complex_pattern(species) if glyph is None: continue sa._map.append(glyph) glyphs[idx] = glyph for reaction in model.reactions: # Get all the reactions / products / controllers of the reaction reactants = set(reaction['reactants']) - set(reaction['products']) products = set(reaction['products']) - set(reaction['reactants']) controllers = set(reaction['reactants']) & set(reaction['products']) # Add glyph for reaction process_glyph = sa._process_glyph('process') # Connect reactants with arcs if not reactants: glyph_id = sa._none_glyph() sa._arc('consumption', glyph_id, process_glyph) else: for r in reactants: glyph = glyphs.get(r) if glyph is None: glyph_id = sa._none_glyph() else: glyph_id = glyph.attrib['id'] sa._arc('consumption', glyph_id, process_glyph) # Connect products with arcs if not products: glyph_id = sa._none_glyph() sa._arc('production', process_glyph, glyph_id) else: for p in products: glyph = glyphs.get(p) if glyph is None: glyph_id = sa._none_glyph() else: glyph_id = glyph.attrib['id'] sa._arc('production', process_glyph, glyph_id) # Connect controllers with arcs for c in controllers: glyph = glyphs[c] sa._arc('catalysis', glyph.attrib['id'], process_glyph) sbgn_str = sa.print_model().decode('utf-8') return sbgn_str
python
def export_sbgn(model): import lxml.etree import lxml.builder from pysb.bng import generate_equations from indra.assemblers.sbgn import SBGNAssembler logger.info('Generating reaction network with BNG for SBGN export. ' + 'This could take a long time.') generate_equations(model) sa = SBGNAssembler() glyphs = {} for idx, species in enumerate(model.species): glyph = sa._glyph_for_complex_pattern(species) if glyph is None: continue sa._map.append(glyph) glyphs[idx] = glyph for reaction in model.reactions: # Get all the reactions / products / controllers of the reaction reactants = set(reaction['reactants']) - set(reaction['products']) products = set(reaction['products']) - set(reaction['reactants']) controllers = set(reaction['reactants']) & set(reaction['products']) # Add glyph for reaction process_glyph = sa._process_glyph('process') # Connect reactants with arcs if not reactants: glyph_id = sa._none_glyph() sa._arc('consumption', glyph_id, process_glyph) else: for r in reactants: glyph = glyphs.get(r) if glyph is None: glyph_id = sa._none_glyph() else: glyph_id = glyph.attrib['id'] sa._arc('consumption', glyph_id, process_glyph) # Connect products with arcs if not products: glyph_id = sa._none_glyph() sa._arc('production', process_glyph, glyph_id) else: for p in products: glyph = glyphs.get(p) if glyph is None: glyph_id = sa._none_glyph() else: glyph_id = glyph.attrib['id'] sa._arc('production', process_glyph, glyph_id) # Connect controllers with arcs for c in controllers: glyph = glyphs[c] sa._arc('catalysis', glyph.attrib['id'], process_glyph) sbgn_str = sa.print_model().decode('utf-8') return sbgn_str
[ "def", "export_sbgn", "(", "model", ")", ":", "import", "lxml", ".", "etree", "import", "lxml", ".", "builder", "from", "pysb", ".", "bng", "import", "generate_equations", "from", "indra", ".", "assemblers", ".", "sbgn", "import", "SBGNAssembler", "logger", ...
Return an SBGN model string corresponding to the PySB model. This function first calls generate_equations on the PySB model to obtain a reaction network (i.e. individual species, reactions). It then iterates over each reaction and and instantiates its reactants, products, and the process itself as SBGN glyphs and arcs. Parameters ---------- model : pysb.core.Model A PySB model to be exported into SBGN Returns ------- sbgn_str : str An SBGN model as string
[ "Return", "an", "SBGN", "model", "string", "corresponding", "to", "the", "PySB", "model", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/pysb/export.py#L9-L82
19,255
sorgerlab/indra
indra/assemblers/pysb/export.py
export_kappa_im
def export_kappa_im(model, fname=None): """Return a networkx graph representing the model's Kappa influence map. Parameters ---------- model : pysb.core.Model A PySB model to be exported into a Kappa IM. fname : Optional[str] A file name, typically with .png or .pdf extension in which the IM is rendered using pygraphviz. Returns ------- networkx.MultiDiGraph A graph object representing the influence map. """ from .kappa_util import im_json_to_graph kappa = _prepare_kappa(model) imap = kappa.analyses_influence_map() im = im_json_to_graph(imap) for param in model.parameters: try: im.remove_node(param.name) except: pass if fname: agraph = networkx.nx_agraph.to_agraph(im) agraph.draw(fname, prog='dot') return im
python
def export_kappa_im(model, fname=None): from .kappa_util import im_json_to_graph kappa = _prepare_kappa(model) imap = kappa.analyses_influence_map() im = im_json_to_graph(imap) for param in model.parameters: try: im.remove_node(param.name) except: pass if fname: agraph = networkx.nx_agraph.to_agraph(im) agraph.draw(fname, prog='dot') return im
[ "def", "export_kappa_im", "(", "model", ",", "fname", "=", "None", ")", ":", "from", ".", "kappa_util", "import", "im_json_to_graph", "kappa", "=", "_prepare_kappa", "(", "model", ")", "imap", "=", "kappa", ".", "analyses_influence_map", "(", ")", "im", "=",...
Return a networkx graph representing the model's Kappa influence map. Parameters ---------- model : pysb.core.Model A PySB model to be exported into a Kappa IM. fname : Optional[str] A file name, typically with .png or .pdf extension in which the IM is rendered using pygraphviz. Returns ------- networkx.MultiDiGraph A graph object representing the influence map.
[ "Return", "a", "networkx", "graph", "representing", "the", "model", "s", "Kappa", "influence", "map", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/pysb/export.py#L85-L113
19,256
sorgerlab/indra
indra/assemblers/pysb/export.py
export_kappa_cm
def export_kappa_cm(model, fname=None): """Return a networkx graph representing the model's Kappa contact map. Parameters ---------- model : pysb.core.Model A PySB model to be exported into a Kappa CM. fname : Optional[str] A file name, typically with .png or .pdf extension in which the CM is rendered using pygraphviz. Returns ------- npygraphviz.Agraph A graph object representing the contact map. """ from .kappa_util import cm_json_to_graph kappa = _prepare_kappa(model) cmap = kappa.analyses_contact_map() cm = cm_json_to_graph(cmap) if fname: cm.draw(fname, prog='dot') return cm
python
def export_kappa_cm(model, fname=None): from .kappa_util import cm_json_to_graph kappa = _prepare_kappa(model) cmap = kappa.analyses_contact_map() cm = cm_json_to_graph(cmap) if fname: cm.draw(fname, prog='dot') return cm
[ "def", "export_kappa_cm", "(", "model", ",", "fname", "=", "None", ")", ":", "from", ".", "kappa_util", "import", "cm_json_to_graph", "kappa", "=", "_prepare_kappa", "(", "model", ")", "cmap", "=", "kappa", ".", "analyses_contact_map", "(", ")", "cm", "=", ...
Return a networkx graph representing the model's Kappa contact map. Parameters ---------- model : pysb.core.Model A PySB model to be exported into a Kappa CM. fname : Optional[str] A file name, typically with .png or .pdf extension in which the CM is rendered using pygraphviz. Returns ------- npygraphviz.Agraph A graph object representing the contact map.
[ "Return", "a", "networkx", "graph", "representing", "the", "model", "s", "Kappa", "contact", "map", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/pysb/export.py#L116-L138
19,257
sorgerlab/indra
indra/assemblers/pysb/export.py
_prepare_kappa
def _prepare_kappa(model): """Return a Kappa STD with the model loaded.""" import kappy kappa = kappy.KappaStd() model_str = export(model, 'kappa') kappa.add_model_string(model_str) kappa.project_parse() return kappa
python
def _prepare_kappa(model): import kappy kappa = kappy.KappaStd() model_str = export(model, 'kappa') kappa.add_model_string(model_str) kappa.project_parse() return kappa
[ "def", "_prepare_kappa", "(", "model", ")", ":", "import", "kappy", "kappa", "=", "kappy", ".", "KappaStd", "(", ")", "model_str", "=", "export", "(", "model", ",", "'kappa'", ")", "kappa", ".", "add_model_string", "(", "model_str", ")", "kappa", ".", "p...
Return a Kappa STD with the model loaded.
[ "Return", "a", "Kappa", "STD", "with", "the", "model", "loaded", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/pysb/export.py#L141-L148
19,258
sorgerlab/indra
indra/databases/cbio_client.py
send_request
def send_request(**kwargs): """Return a data frame from a web service request to cBio portal. Sends a web service requrest to the cBio portal with arguments given in the dictionary data and returns a Pandas data frame on success. More information about the service here: http://www.cbioportal.org/web_api.jsp Parameters ---------- kwargs : dict A dict of parameters for the query. Entries map directly to web service calls with the exception of the optional 'skiprows' entry, whose value is used as the number of rows to skip when reading the result data frame. Returns ------- df : pandas.DataFrame Response from cBioPortal as a Pandas DataFrame. """ skiprows = kwargs.pop('skiprows', None) res = requests.get(cbio_url, params=kwargs) if res.status_code == 200: # Adaptively skip rows based on number of comment lines if skiprows == -1: lines = res.text.split('\n') skiprows = 0 for line in lines: if line.startswith('#'): skiprows += 1 else: break csv_StringIO = StringIO(res.text) df = pandas.read_csv(csv_StringIO, sep='\t', skiprows=skiprows) return df else: logger.error('Request returned with code %d' % res.status_code)
python
def send_request(**kwargs): skiprows = kwargs.pop('skiprows', None) res = requests.get(cbio_url, params=kwargs) if res.status_code == 200: # Adaptively skip rows based on number of comment lines if skiprows == -1: lines = res.text.split('\n') skiprows = 0 for line in lines: if line.startswith('#'): skiprows += 1 else: break csv_StringIO = StringIO(res.text) df = pandas.read_csv(csv_StringIO, sep='\t', skiprows=skiprows) return df else: logger.error('Request returned with code %d' % res.status_code)
[ "def", "send_request", "(", "*", "*", "kwargs", ")", ":", "skiprows", "=", "kwargs", ".", "pop", "(", "'skiprows'", ",", "None", ")", "res", "=", "requests", ".", "get", "(", "cbio_url", ",", "params", "=", "kwargs", ")", "if", "res", ".", "status_co...
Return a data frame from a web service request to cBio portal. Sends a web service requrest to the cBio portal with arguments given in the dictionary data and returns a Pandas data frame on success. More information about the service here: http://www.cbioportal.org/web_api.jsp Parameters ---------- kwargs : dict A dict of parameters for the query. Entries map directly to web service calls with the exception of the optional 'skiprows' entry, whose value is used as the number of rows to skip when reading the result data frame. Returns ------- df : pandas.DataFrame Response from cBioPortal as a Pandas DataFrame.
[ "Return", "a", "data", "frame", "from", "a", "web", "service", "request", "to", "cBio", "portal", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/databases/cbio_client.py#L25-L63
19,259
sorgerlab/indra
indra/databases/cbio_client.py
get_mutations
def get_mutations(study_id, gene_list, mutation_type=None, case_id=None): """Return mutations as a list of genes and list of amino acid changes. Parameters ---------- study_id : str The ID of the cBio study. Example: 'cellline_ccle_broad' or 'paad_icgc' gene_list : list[str] A list of genes with their HGNC symbols. Example: ['BRAF', 'KRAS'] mutation_type : Optional[str] The type of mutation to filter to. mutation_type can be one of: missense, nonsense, frame_shift_ins, frame_shift_del, splice_site case_id : Optional[str] The case ID within the study to filter to. Returns ------- mutations : tuple[list] A tuple of two lists, the first one containing a list of genes, and the second one a list of amino acid changes in those genes. """ genetic_profile = get_genetic_profiles(study_id, 'mutation')[0] gene_list_str = ','.join(gene_list) data = {'cmd': 'getMutationData', 'case_set_id': study_id, 'genetic_profile_id': genetic_profile, 'gene_list': gene_list_str, 'skiprows': -1} df = send_request(**data) if case_id: df = df[df['case_id'] == case_id] res = _filter_data_frame(df, ['gene_symbol', 'amino_acid_change'], 'mutation_type', mutation_type) mutations = {'gene_symbol': list(res['gene_symbol'].values()), 'amino_acid_change': list(res['amino_acid_change'].values())} return mutations
python
def get_mutations(study_id, gene_list, mutation_type=None, case_id=None): genetic_profile = get_genetic_profiles(study_id, 'mutation')[0] gene_list_str = ','.join(gene_list) data = {'cmd': 'getMutationData', 'case_set_id': study_id, 'genetic_profile_id': genetic_profile, 'gene_list': gene_list_str, 'skiprows': -1} df = send_request(**data) if case_id: df = df[df['case_id'] == case_id] res = _filter_data_frame(df, ['gene_symbol', 'amino_acid_change'], 'mutation_type', mutation_type) mutations = {'gene_symbol': list(res['gene_symbol'].values()), 'amino_acid_change': list(res['amino_acid_change'].values())} return mutations
[ "def", "get_mutations", "(", "study_id", ",", "gene_list", ",", "mutation_type", "=", "None", ",", "case_id", "=", "None", ")", ":", "genetic_profile", "=", "get_genetic_profiles", "(", "study_id", ",", "'mutation'", ")", "[", "0", "]", "gene_list_str", "=", ...
Return mutations as a list of genes and list of amino acid changes. Parameters ---------- study_id : str The ID of the cBio study. Example: 'cellline_ccle_broad' or 'paad_icgc' gene_list : list[str] A list of genes with their HGNC symbols. Example: ['BRAF', 'KRAS'] mutation_type : Optional[str] The type of mutation to filter to. mutation_type can be one of: missense, nonsense, frame_shift_ins, frame_shift_del, splice_site case_id : Optional[str] The case ID within the study to filter to. Returns ------- mutations : tuple[list] A tuple of two lists, the first one containing a list of genes, and the second one a list of amino acid changes in those genes.
[ "Return", "mutations", "as", "a", "list", "of", "genes", "and", "list", "of", "amino", "acid", "changes", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/databases/cbio_client.py#L66-L106
19,260
sorgerlab/indra
indra/databases/cbio_client.py
get_case_lists
def get_case_lists(study_id): """Return a list of the case set ids for a particular study. TAKE NOTE the "case_list_id" are the same thing as "case_set_id" Within the data, this string is referred to as a "case_list_id". Within API calls it is referred to as a 'case_set_id'. The documentation does not make this explicitly clear. Parameters ---------- study_id : str The ID of the cBio study. Example: 'cellline_ccle_broad' or 'paad_icgc' Returns ------- case_set_ids : dict[dict[int]] A dict keyed to cases containing a dict keyed to genes containing int """ data = {'cmd': 'getCaseLists', 'cancer_study_id': study_id} df = send_request(**data) case_set_ids = df['case_list_id'].tolist() return case_set_ids
python
def get_case_lists(study_id): data = {'cmd': 'getCaseLists', 'cancer_study_id': study_id} df = send_request(**data) case_set_ids = df['case_list_id'].tolist() return case_set_ids
[ "def", "get_case_lists", "(", "study_id", ")", ":", "data", "=", "{", "'cmd'", ":", "'getCaseLists'", ",", "'cancer_study_id'", ":", "study_id", "}", "df", "=", "send_request", "(", "*", "*", "data", ")", "case_set_ids", "=", "df", "[", "'case_list_id'", "...
Return a list of the case set ids for a particular study. TAKE NOTE the "case_list_id" are the same thing as "case_set_id" Within the data, this string is referred to as a "case_list_id". Within API calls it is referred to as a 'case_set_id'. The documentation does not make this explicitly clear. Parameters ---------- study_id : str The ID of the cBio study. Example: 'cellline_ccle_broad' or 'paad_icgc' Returns ------- case_set_ids : dict[dict[int]] A dict keyed to cases containing a dict keyed to genes containing int
[ "Return", "a", "list", "of", "the", "case", "set", "ids", "for", "a", "particular", "study", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/databases/cbio_client.py#L109-L133
19,261
sorgerlab/indra
indra/databases/cbio_client.py
get_profile_data
def get_profile_data(study_id, gene_list, profile_filter, case_set_filter=None): """Return dict of cases and genes and their respective values. Parameters ---------- study_id : str The ID of the cBio study. Example: 'cellline_ccle_broad' or 'paad_icgc' gene_list : list[str] A list of genes with their HGNC symbols. Example: ['BRAF', 'KRAS'] profile_filter : str A string used to filter the profiles to return. Will be one of: - MUTATION - MUTATION_EXTENDED - COPY_NUMBER_ALTERATION - MRNA_EXPRESSION - METHYLATION case_set_filter : Optional[str] A string that specifices which case_set_id to use, based on a complete or partial match. If not provided, will look for study_id + '_all' Returns ------- profile_data : dict[dict[int]] A dict keyed to cases containing a dict keyed to genes containing int """ genetic_profiles = get_genetic_profiles(study_id, profile_filter) if genetic_profiles: genetic_profile = genetic_profiles[0] else: return {} gene_list_str = ','.join(gene_list) case_set_ids = get_case_lists(study_id) if case_set_filter: case_set_id = [x for x in case_set_ids if case_set_filter in x][0] else: case_set_id = study_id + '_all' # based on looking at the cBioPortal, this is a common case_set_id data = {'cmd': 'getProfileData', 'case_set_id': case_set_id, 'genetic_profile_id': genetic_profile, 'gene_list': gene_list_str, 'skiprows': -1} df = send_request(**data) case_list_df = [x for x in df.columns.tolist() if x not in ['GENE_ID', 'COMMON']] profile_data = {case: {g: None for g in gene_list} for case in case_list_df} for case in case_list_df: profile_values = df[case].tolist() df_gene_list = df['COMMON'].tolist() for g, cv in zip(df_gene_list, profile_values): if not pandas.isnull(cv): profile_data[case][g] = cv return profile_data
python
def get_profile_data(study_id, gene_list, profile_filter, case_set_filter=None): genetic_profiles = get_genetic_profiles(study_id, profile_filter) if genetic_profiles: genetic_profile = genetic_profiles[0] else: return {} gene_list_str = ','.join(gene_list) case_set_ids = get_case_lists(study_id) if case_set_filter: case_set_id = [x for x in case_set_ids if case_set_filter in x][0] else: case_set_id = study_id + '_all' # based on looking at the cBioPortal, this is a common case_set_id data = {'cmd': 'getProfileData', 'case_set_id': case_set_id, 'genetic_profile_id': genetic_profile, 'gene_list': gene_list_str, 'skiprows': -1} df = send_request(**data) case_list_df = [x for x in df.columns.tolist() if x not in ['GENE_ID', 'COMMON']] profile_data = {case: {g: None for g in gene_list} for case in case_list_df} for case in case_list_df: profile_values = df[case].tolist() df_gene_list = df['COMMON'].tolist() for g, cv in zip(df_gene_list, profile_values): if not pandas.isnull(cv): profile_data[case][g] = cv return profile_data
[ "def", "get_profile_data", "(", "study_id", ",", "gene_list", ",", "profile_filter", ",", "case_set_filter", "=", "None", ")", ":", "genetic_profiles", "=", "get_genetic_profiles", "(", "study_id", ",", "profile_filter", ")", "if", "genetic_profiles", ":", "genetic_...
Return dict of cases and genes and their respective values. Parameters ---------- study_id : str The ID of the cBio study. Example: 'cellline_ccle_broad' or 'paad_icgc' gene_list : list[str] A list of genes with their HGNC symbols. Example: ['BRAF', 'KRAS'] profile_filter : str A string used to filter the profiles to return. Will be one of: - MUTATION - MUTATION_EXTENDED - COPY_NUMBER_ALTERATION - MRNA_EXPRESSION - METHYLATION case_set_filter : Optional[str] A string that specifices which case_set_id to use, based on a complete or partial match. If not provided, will look for study_id + '_all' Returns ------- profile_data : dict[dict[int]] A dict keyed to cases containing a dict keyed to genes containing int
[ "Return", "dict", "of", "cases", "and", "genes", "and", "their", "respective", "values", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/databases/cbio_client.py#L136-L193
19,262
sorgerlab/indra
indra/databases/cbio_client.py
get_num_sequenced
def get_num_sequenced(study_id): """Return number of sequenced tumors for given study. This is useful for calculating mutation statistics in terms of the prevalence of certain mutations within a type of cancer. Parameters ---------- study_id : str The ID of the cBio study. Example: 'paad_icgc' Returns ------- num_case : int The number of sequenced tumors in the given study """ data = {'cmd': 'getCaseLists', 'cancer_study_id': study_id} df = send_request(**data) if df.empty: return 0 row_filter = df['case_list_id'].str.contains('sequenced', case=False) num_case = len(df[row_filter]['case_ids'].tolist()[0].split(' ')) return num_case
python
def get_num_sequenced(study_id): data = {'cmd': 'getCaseLists', 'cancer_study_id': study_id} df = send_request(**data) if df.empty: return 0 row_filter = df['case_list_id'].str.contains('sequenced', case=False) num_case = len(df[row_filter]['case_ids'].tolist()[0].split(' ')) return num_case
[ "def", "get_num_sequenced", "(", "study_id", ")", ":", "data", "=", "{", "'cmd'", ":", "'getCaseLists'", ",", "'cancer_study_id'", ":", "study_id", "}", "df", "=", "send_request", "(", "*", "*", "data", ")", "if", "df", ".", "empty", ":", "return", "0", ...
Return number of sequenced tumors for given study. This is useful for calculating mutation statistics in terms of the prevalence of certain mutations within a type of cancer. Parameters ---------- study_id : str The ID of the cBio study. Example: 'paad_icgc' Returns ------- num_case : int The number of sequenced tumors in the given study
[ "Return", "number", "of", "sequenced", "tumors", "for", "given", "study", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/databases/cbio_client.py#L196-L220
19,263
sorgerlab/indra
indra/databases/cbio_client.py
get_cancer_studies
def get_cancer_studies(study_filter=None): """Return a list of cancer study identifiers, optionally filtered. There are typically multiple studies for a given type of cancer and a filter can be used to constrain the returned list. Parameters ---------- study_filter : Optional[str] A string used to filter the study IDs to return. Example: "paad" Returns ------- study_ids : list[str] A list of study IDs. For instance "paad" as a filter would result in a list of study IDs with paad in their name like "paad_icgc", "paad_tcga", etc. """ data = {'cmd': 'getCancerStudies'} df = send_request(**data) res = _filter_data_frame(df, ['cancer_study_id'], 'cancer_study_id', study_filter) study_ids = list(res['cancer_study_id'].values()) return study_ids
python
def get_cancer_studies(study_filter=None): data = {'cmd': 'getCancerStudies'} df = send_request(**data) res = _filter_data_frame(df, ['cancer_study_id'], 'cancer_study_id', study_filter) study_ids = list(res['cancer_study_id'].values()) return study_ids
[ "def", "get_cancer_studies", "(", "study_filter", "=", "None", ")", ":", "data", "=", "{", "'cmd'", ":", "'getCancerStudies'", "}", "df", "=", "send_request", "(", "*", "*", "data", ")", "res", "=", "_filter_data_frame", "(", "df", ",", "[", "'cancer_study...
Return a list of cancer study identifiers, optionally filtered. There are typically multiple studies for a given type of cancer and a filter can be used to constrain the returned list. Parameters ---------- study_filter : Optional[str] A string used to filter the study IDs to return. Example: "paad" Returns ------- study_ids : list[str] A list of study IDs. For instance "paad" as a filter would result in a list of study IDs with paad in their name like "paad_icgc", "paad_tcga", etc.
[ "Return", "a", "list", "of", "cancer", "study", "identifiers", "optionally", "filtered", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/databases/cbio_client.py#L261-L285
19,264
sorgerlab/indra
indra/databases/cbio_client.py
get_cancer_types
def get_cancer_types(cancer_filter=None): """Return a list of cancer types, optionally filtered. Parameters ---------- cancer_filter : Optional[str] A string used to filter cancer types. Its value is the name or part of the name of a type of cancer. Example: "melanoma", "pancreatic", "non-small cell lung" Returns ------- type_ids : list[str] A list of cancer types matching the filter. Example: for cancer_filter="pancreatic", the result includes "panet" (neuro-endocrine) and "paad" (adenocarcinoma) """ data = {'cmd': 'getTypesOfCancer'} df = send_request(**data) res = _filter_data_frame(df, ['type_of_cancer_id'], 'name', cancer_filter) type_ids = list(res['type_of_cancer_id'].values()) return type_ids
python
def get_cancer_types(cancer_filter=None): data = {'cmd': 'getTypesOfCancer'} df = send_request(**data) res = _filter_data_frame(df, ['type_of_cancer_id'], 'name', cancer_filter) type_ids = list(res['type_of_cancer_id'].values()) return type_ids
[ "def", "get_cancer_types", "(", "cancer_filter", "=", "None", ")", ":", "data", "=", "{", "'cmd'", ":", "'getTypesOfCancer'", "}", "df", "=", "send_request", "(", "*", "*", "data", ")", "res", "=", "_filter_data_frame", "(", "df", ",", "[", "'type_of_cance...
Return a list of cancer types, optionally filtered. Parameters ---------- cancer_filter : Optional[str] A string used to filter cancer types. Its value is the name or part of the name of a type of cancer. Example: "melanoma", "pancreatic", "non-small cell lung" Returns ------- type_ids : list[str] A list of cancer types matching the filter. Example: for cancer_filter="pancreatic", the result includes "panet" (neuro-endocrine) and "paad" (adenocarcinoma)
[ "Return", "a", "list", "of", "cancer", "types", "optionally", "filtered", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/databases/cbio_client.py#L288-L309
19,265
sorgerlab/indra
indra/databases/cbio_client.py
get_ccle_mutations
def get_ccle_mutations(gene_list, cell_lines, mutation_type=None): """Return a dict of mutations in given genes and cell lines from CCLE. This is a specialized call to get_mutations tailored to CCLE cell lines. Parameters ---------- gene_list : list[str] A list of HGNC gene symbols to get mutations in cell_lines : list[str] A list of CCLE cell line names to get mutations for. mutation_type : Optional[str] The type of mutation to filter to. mutation_type can be one of: missense, nonsense, frame_shift_ins, frame_shift_del, splice_site Returns ------- mutations : dict The result from cBioPortal as a dict in the format {cell_line : {gene : [mutation1, mutation2, ...] }} Example: {'LOXIMVI_SKIN': {'BRAF': ['V600E', 'I208V']}, 'SKMEL30_SKIN': {'BRAF': ['D287H', 'E275K']}} """ mutations = {cl: {g: [] for g in gene_list} for cl in cell_lines} for cell_line in cell_lines: mutations_cl = get_mutations(ccle_study, gene_list, mutation_type=mutation_type, case_id=cell_line) for gene, aa_change in zip(mutations_cl['gene_symbol'], mutations_cl['amino_acid_change']): aa_change = str(aa_change) mutations[cell_line][gene].append(aa_change) return mutations
python
def get_ccle_mutations(gene_list, cell_lines, mutation_type=None): mutations = {cl: {g: [] for g in gene_list} for cl in cell_lines} for cell_line in cell_lines: mutations_cl = get_mutations(ccle_study, gene_list, mutation_type=mutation_type, case_id=cell_line) for gene, aa_change in zip(mutations_cl['gene_symbol'], mutations_cl['amino_acid_change']): aa_change = str(aa_change) mutations[cell_line][gene].append(aa_change) return mutations
[ "def", "get_ccle_mutations", "(", "gene_list", ",", "cell_lines", ",", "mutation_type", "=", "None", ")", ":", "mutations", "=", "{", "cl", ":", "{", "g", ":", "[", "]", "for", "g", "in", "gene_list", "}", "for", "cl", "in", "cell_lines", "}", "for", ...
Return a dict of mutations in given genes and cell lines from CCLE. This is a specialized call to get_mutations tailored to CCLE cell lines. Parameters ---------- gene_list : list[str] A list of HGNC gene symbols to get mutations in cell_lines : list[str] A list of CCLE cell line names to get mutations for. mutation_type : Optional[str] The type of mutation to filter to. mutation_type can be one of: missense, nonsense, frame_shift_ins, frame_shift_del, splice_site Returns ------- mutations : dict The result from cBioPortal as a dict in the format {cell_line : {gene : [mutation1, mutation2, ...] }} Example: {'LOXIMVI_SKIN': {'BRAF': ['V600E', 'I208V']}, 'SKMEL30_SKIN': {'BRAF': ['D287H', 'E275K']}}
[ "Return", "a", "dict", "of", "mutations", "in", "given", "genes", "and", "cell", "lines", "from", "CCLE", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/databases/cbio_client.py#L312-L347
19,266
sorgerlab/indra
indra/databases/cbio_client.py
get_ccle_lines_for_mutation
def get_ccle_lines_for_mutation(gene, amino_acid_change): """Return cell lines with a given point mutation in a given gene. Checks which cell lines in CCLE have a particular point mutation in a given gene and return their names in a list. Parameters ---------- gene : str The HGNC symbol of the mutated gene in whose product the amino acid change occurs. Example: "BRAF" amino_acid_change : str The amino acid change of interest. Example: "V600E" Returns ------- cell_lines : list A list of CCLE cell lines in which the given mutation occurs. """ data = {'cmd': 'getMutationData', 'case_set_id': ccle_study, 'genetic_profile_id': ccle_study + '_mutations', 'gene_list': gene, 'skiprows': 1} df = send_request(**data) df = df[df['amino_acid_change'] == amino_acid_change] cell_lines = df['case_id'].unique().tolist() return cell_lines
python
def get_ccle_lines_for_mutation(gene, amino_acid_change): data = {'cmd': 'getMutationData', 'case_set_id': ccle_study, 'genetic_profile_id': ccle_study + '_mutations', 'gene_list': gene, 'skiprows': 1} df = send_request(**data) df = df[df['amino_acid_change'] == amino_acid_change] cell_lines = df['case_id'].unique().tolist() return cell_lines
[ "def", "get_ccle_lines_for_mutation", "(", "gene", ",", "amino_acid_change", ")", ":", "data", "=", "{", "'cmd'", ":", "'getMutationData'", ",", "'case_set_id'", ":", "ccle_study", ",", "'genetic_profile_id'", ":", "ccle_study", "+", "'_mutations'", ",", "'gene_list...
Return cell lines with a given point mutation in a given gene. Checks which cell lines in CCLE have a particular point mutation in a given gene and return their names in a list. Parameters ---------- gene : str The HGNC symbol of the mutated gene in whose product the amino acid change occurs. Example: "BRAF" amino_acid_change : str The amino acid change of interest. Example: "V600E" Returns ------- cell_lines : list A list of CCLE cell lines in which the given mutation occurs.
[ "Return", "cell", "lines", "with", "a", "given", "point", "mutation", "in", "a", "given", "gene", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/databases/cbio_client.py#L350-L377
19,267
sorgerlab/indra
indra/databases/cbio_client.py
get_ccle_cna
def get_ccle_cna(gene_list, cell_lines): """Return a dict of CNAs in given genes and cell lines from CCLE. CNA values correspond to the following alterations -2 = homozygous deletion -1 = hemizygous deletion 0 = neutral / no change 1 = gain 2 = high level amplification Parameters ---------- gene_list : list[str] A list of HGNC gene symbols to get mutations in cell_lines : list[str] A list of CCLE cell line names to get mutations for. Returns ------- profile_data : dict[dict[int]] A dict keyed to cases containing a dict keyed to genes containing int """ profile_data = get_profile_data(ccle_study, gene_list, 'COPY_NUMBER_ALTERATION', 'all') profile_data = dict((key, value) for key, value in profile_data.items() if key in cell_lines) return profile_data
python
def get_ccle_cna(gene_list, cell_lines): profile_data = get_profile_data(ccle_study, gene_list, 'COPY_NUMBER_ALTERATION', 'all') profile_data = dict((key, value) for key, value in profile_data.items() if key in cell_lines) return profile_data
[ "def", "get_ccle_cna", "(", "gene_list", ",", "cell_lines", ")", ":", "profile_data", "=", "get_profile_data", "(", "ccle_study", ",", "gene_list", ",", "'COPY_NUMBER_ALTERATION'", ",", "'all'", ")", "profile_data", "=", "dict", "(", "(", "key", ",", "value", ...
Return a dict of CNAs in given genes and cell lines from CCLE. CNA values correspond to the following alterations -2 = homozygous deletion -1 = hemizygous deletion 0 = neutral / no change 1 = gain 2 = high level amplification Parameters ---------- gene_list : list[str] A list of HGNC gene symbols to get mutations in cell_lines : list[str] A list of CCLE cell line names to get mutations for. Returns ------- profile_data : dict[dict[int]] A dict keyed to cases containing a dict keyed to genes containing int
[ "Return", "a", "dict", "of", "CNAs", "in", "given", "genes", "and", "cell", "lines", "from", "CCLE", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/databases/cbio_client.py#L380-L412
19,268
sorgerlab/indra
indra/databases/cbio_client.py
get_ccle_mrna
def get_ccle_mrna(gene_list, cell_lines): """Return a dict of mRNA amounts in given genes and cell lines from CCLE. Parameters ---------- gene_list : list[str] A list of HGNC gene symbols to get mRNA amounts for. cell_lines : list[str] A list of CCLE cell line names to get mRNA amounts for. Returns ------- mrna_amounts : dict[dict[float]] A dict keyed to cell lines containing a dict keyed to genes containing float """ gene_list_str = ','.join(gene_list) data = {'cmd': 'getProfileData', 'case_set_id': ccle_study + '_mrna', 'genetic_profile_id': ccle_study + '_mrna', 'gene_list': gene_list_str, 'skiprows': -1} df = send_request(**data) mrna_amounts = {cl: {g: [] for g in gene_list} for cl in cell_lines} for cell_line in cell_lines: if cell_line in df.columns: for gene in gene_list: value_cell = df[cell_line][df['COMMON'] == gene] if value_cell.empty: mrna_amounts[cell_line][gene] = None elif pandas.isnull(value_cell.values[0]): mrna_amounts[cell_line][gene] = None else: value = value_cell.values[0] mrna_amounts[cell_line][gene] = value else: mrna_amounts[cell_line] = None return mrna_amounts
python
def get_ccle_mrna(gene_list, cell_lines): gene_list_str = ','.join(gene_list) data = {'cmd': 'getProfileData', 'case_set_id': ccle_study + '_mrna', 'genetic_profile_id': ccle_study + '_mrna', 'gene_list': gene_list_str, 'skiprows': -1} df = send_request(**data) mrna_amounts = {cl: {g: [] for g in gene_list} for cl in cell_lines} for cell_line in cell_lines: if cell_line in df.columns: for gene in gene_list: value_cell = df[cell_line][df['COMMON'] == gene] if value_cell.empty: mrna_amounts[cell_line][gene] = None elif pandas.isnull(value_cell.values[0]): mrna_amounts[cell_line][gene] = None else: value = value_cell.values[0] mrna_amounts[cell_line][gene] = value else: mrna_amounts[cell_line] = None return mrna_amounts
[ "def", "get_ccle_mrna", "(", "gene_list", ",", "cell_lines", ")", ":", "gene_list_str", "=", "','", ".", "join", "(", "gene_list", ")", "data", "=", "{", "'cmd'", ":", "'getProfileData'", ",", "'case_set_id'", ":", "ccle_study", "+", "'_mrna'", ",", "'geneti...
Return a dict of mRNA amounts in given genes and cell lines from CCLE. Parameters ---------- gene_list : list[str] A list of HGNC gene symbols to get mRNA amounts for. cell_lines : list[str] A list of CCLE cell line names to get mRNA amounts for. Returns ------- mrna_amounts : dict[dict[float]] A dict keyed to cell lines containing a dict keyed to genes containing float
[ "Return", "a", "dict", "of", "mRNA", "amounts", "in", "given", "genes", "and", "cell", "lines", "from", "CCLE", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/databases/cbio_client.py#L415-L452
19,269
sorgerlab/indra
indra/databases/cbio_client.py
_filter_data_frame
def _filter_data_frame(df, data_col, filter_col, filter_str=None): """Return a filtered data frame as a dictionary.""" if filter_str is not None: relevant_cols = data_col + [filter_col] df.dropna(inplace=True, subset=relevant_cols) row_filter = df[filter_col].str.contains(filter_str, case=False) data_list = df[row_filter][data_col].to_dict() else: data_list = df[data_col].to_dict() return data_list
python
def _filter_data_frame(df, data_col, filter_col, filter_str=None): if filter_str is not None: relevant_cols = data_col + [filter_col] df.dropna(inplace=True, subset=relevant_cols) row_filter = df[filter_col].str.contains(filter_str, case=False) data_list = df[row_filter][data_col].to_dict() else: data_list = df[data_col].to_dict() return data_list
[ "def", "_filter_data_frame", "(", "df", ",", "data_col", ",", "filter_col", ",", "filter_str", "=", "None", ")", ":", "if", "filter_str", "is", "not", "None", ":", "relevant_cols", "=", "data_col", "+", "[", "filter_col", "]", "df", ".", "dropna", "(", "...
Return a filtered data frame as a dictionary.
[ "Return", "a", "filtered", "data", "frame", "as", "a", "dictionary", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/databases/cbio_client.py#L455-L464
19,270
sorgerlab/indra
rest_api/api.py
allow_cors
def allow_cors(func): """This is a decorator which enable CORS for the specified endpoint.""" def wrapper(*args, **kwargs): response.headers['Access-Control-Allow-Origin'] = '*' response.headers['Access-Control-Allow-Methods'] = \ 'PUT, GET, POST, DELETE, OPTIONS' response.headers['Access-Control-Allow-Headers'] = \ 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token' return func(*args, **kwargs) return wrapper
python
def allow_cors(func): def wrapper(*args, **kwargs): response.headers['Access-Control-Allow-Origin'] = '*' response.headers['Access-Control-Allow-Methods'] = \ 'PUT, GET, POST, DELETE, OPTIONS' response.headers['Access-Control-Allow-Headers'] = \ 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token' return func(*args, **kwargs) return wrapper
[ "def", "allow_cors", "(", "func", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "response", ".", "headers", "[", "'Access-Control-Allow-Origin'", "]", "=", "'*'", "response", ".", "headers", "[", "'Access-Control-Allow-Meth...
This is a decorator which enable CORS for the specified endpoint.
[ "This", "is", "a", "decorator", "which", "enable", "CORS", "for", "the", "specified", "endpoint", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/rest_api/api.py#L50-L59
19,271
sorgerlab/indra
rest_api/api.py
trips_process_text
def trips_process_text(): """Process text with TRIPS and return INDRA Statements.""" if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) text = body.get('text') tp = trips.process_text(text) return _stmts_from_proc(tp)
python
def trips_process_text(): if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) text = body.get('text') tp = trips.process_text(text) return _stmts_from_proc(tp)
[ "def", "trips_process_text", "(", ")", ":", "if", "request", ".", "method", "==", "'OPTIONS'", ":", "return", "{", "}", "response", "=", "request", ".", "body", ".", "read", "(", ")", ".", "decode", "(", "'utf-8'", ")", "body", "=", "json", ".", "loa...
Process text with TRIPS and return INDRA Statements.
[ "Process", "text", "with", "TRIPS", "and", "return", "INDRA", "Statements", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/rest_api/api.py#L76-L84
19,272
sorgerlab/indra
rest_api/api.py
trips_process_xml
def trips_process_xml(): """Process TRIPS EKB XML and return INDRA Statements.""" if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) xml_str = body.get('xml_str') tp = trips.process_xml(xml_str) return _stmts_from_proc(tp)
python
def trips_process_xml(): if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) xml_str = body.get('xml_str') tp = trips.process_xml(xml_str) return _stmts_from_proc(tp)
[ "def", "trips_process_xml", "(", ")", ":", "if", "request", ".", "method", "==", "'OPTIONS'", ":", "return", "{", "}", "response", "=", "request", ".", "body", ".", "read", "(", ")", ".", "decode", "(", "'utf-8'", ")", "body", "=", "json", ".", "load...
Process TRIPS EKB XML and return INDRA Statements.
[ "Process", "TRIPS", "EKB", "XML", "and", "return", "INDRA", "Statements", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/rest_api/api.py#L89-L97
19,273
sorgerlab/indra
rest_api/api.py
reach_process_text
def reach_process_text(): """Process text with REACH and return INDRA Statements.""" if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) text = body.get('text') offline = True if body.get('offline') else False rp = reach.process_text(text, offline=offline) return _stmts_from_proc(rp)
python
def reach_process_text(): if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) text = body.get('text') offline = True if body.get('offline') else False rp = reach.process_text(text, offline=offline) return _stmts_from_proc(rp)
[ "def", "reach_process_text", "(", ")", ":", "if", "request", ".", "method", "==", "'OPTIONS'", ":", "return", "{", "}", "response", "=", "request", ".", "body", ".", "read", "(", ")", ".", "decode", "(", "'utf-8'", ")", "body", "=", "json", ".", "loa...
Process text with REACH and return INDRA Statements.
[ "Process", "text", "with", "REACH", "and", "return", "INDRA", "Statements", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/rest_api/api.py#L104-L113
19,274
sorgerlab/indra
rest_api/api.py
reach_process_json
def reach_process_json(): """Process REACH json and return INDRA Statements.""" if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) json_str = body.get('json') rp = reach.process_json_str(json_str) return _stmts_from_proc(rp)
python
def reach_process_json(): if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) json_str = body.get('json') rp = reach.process_json_str(json_str) return _stmts_from_proc(rp)
[ "def", "reach_process_json", "(", ")", ":", "if", "request", ".", "method", "==", "'OPTIONS'", ":", "return", "{", "}", "response", "=", "request", ".", "body", ".", "read", "(", ")", ".", "decode", "(", "'utf-8'", ")", "body", "=", "json", ".", "loa...
Process REACH json and return INDRA Statements.
[ "Process", "REACH", "json", "and", "return", "INDRA", "Statements", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/rest_api/api.py#L118-L126
19,275
sorgerlab/indra
rest_api/api.py
reach_process_pmc
def reach_process_pmc(): """Process PubMedCentral article and return INDRA Statements.""" if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) pmcid = body.get('pmcid') rp = reach.process_pmc(pmcid) return _stmts_from_proc(rp)
python
def reach_process_pmc(): if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) pmcid = body.get('pmcid') rp = reach.process_pmc(pmcid) return _stmts_from_proc(rp)
[ "def", "reach_process_pmc", "(", ")", ":", "if", "request", ".", "method", "==", "'OPTIONS'", ":", "return", "{", "}", "response", "=", "request", ".", "body", ".", "read", "(", ")", ".", "decode", "(", "'utf-8'", ")", "body", "=", "json", ".", "load...
Process PubMedCentral article and return INDRA Statements.
[ "Process", "PubMedCentral", "article", "and", "return", "INDRA", "Statements", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/rest_api/api.py#L131-L139
19,276
sorgerlab/indra
rest_api/api.py
bel_process_pybel_neighborhood
def bel_process_pybel_neighborhood(): """Process BEL Large Corpus neighborhood and return INDRA Statements.""" if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) genes = body.get('genes') bp = bel.process_pybel_neighborhood(genes) return _stmts_from_proc(bp)
python
def bel_process_pybel_neighborhood(): if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) genes = body.get('genes') bp = bel.process_pybel_neighborhood(genes) return _stmts_from_proc(bp)
[ "def", "bel_process_pybel_neighborhood", "(", ")", ":", "if", "request", ".", "method", "==", "'OPTIONS'", ":", "return", "{", "}", "response", "=", "request", ".", "body", ".", "read", "(", ")", ".", "decode", "(", "'utf-8'", ")", "body", "=", "json", ...
Process BEL Large Corpus neighborhood and return INDRA Statements.
[ "Process", "BEL", "Large", "Corpus", "neighborhood", "and", "return", "INDRA", "Statements", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/rest_api/api.py#L147-L155
19,277
sorgerlab/indra
rest_api/api.py
bel_process_belrdf
def bel_process_belrdf(): """Process BEL RDF and return INDRA Statements.""" if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) belrdf = body.get('belrdf') bp = bel.process_belrdf(belrdf) return _stmts_from_proc(bp)
python
def bel_process_belrdf(): if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) belrdf = body.get('belrdf') bp = bel.process_belrdf(belrdf) return _stmts_from_proc(bp)
[ "def", "bel_process_belrdf", "(", ")", ":", "if", "request", ".", "method", "==", "'OPTIONS'", ":", "return", "{", "}", "response", "=", "request", ".", "body", ".", "read", "(", ")", ".", "decode", "(", "'utf-8'", ")", "body", "=", "json", ".", "loa...
Process BEL RDF and return INDRA Statements.
[ "Process", "BEL", "RDF", "and", "return", "INDRA", "Statements", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/rest_api/api.py#L160-L168
19,278
sorgerlab/indra
rest_api/api.py
biopax_process_pc_pathsbetween
def biopax_process_pc_pathsbetween(): """Process PathwayCommons paths between genes, return INDRA Statements.""" if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) genes = body.get('genes') bp = biopax.process_pc_pathsbetween(genes) return _stmts_from_proc(bp)
python
def biopax_process_pc_pathsbetween(): if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) genes = body.get('genes') bp = biopax.process_pc_pathsbetween(genes) return _stmts_from_proc(bp)
[ "def", "biopax_process_pc_pathsbetween", "(", ")", ":", "if", "request", ".", "method", "==", "'OPTIONS'", ":", "return", "{", "}", "response", "=", "request", ".", "body", ".", "read", "(", ")", ".", "decode", "(", "'utf-8'", ")", "body", "=", "json", ...
Process PathwayCommons paths between genes, return INDRA Statements.
[ "Process", "PathwayCommons", "paths", "between", "genes", "return", "INDRA", "Statements", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/rest_api/api.py#L174-L182
19,279
sorgerlab/indra
rest_api/api.py
biopax_process_pc_pathsfromto
def biopax_process_pc_pathsfromto(): """Process PathwayCommons paths from-to genes, return INDRA Statements.""" if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) source = body.get('source') target = body.get('target') bp = biopax.process_pc_pathsfromto(source, target) return _stmts_from_proc(bp)
python
def biopax_process_pc_pathsfromto(): if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) source = body.get('source') target = body.get('target') bp = biopax.process_pc_pathsfromto(source, target) return _stmts_from_proc(bp)
[ "def", "biopax_process_pc_pathsfromto", "(", ")", ":", "if", "request", ".", "method", "==", "'OPTIONS'", ":", "return", "{", "}", "response", "=", "request", ".", "body", ".", "read", "(", ")", ".", "decode", "(", "'utf-8'", ")", "body", "=", "json", ...
Process PathwayCommons paths from-to genes, return INDRA Statements.
[ "Process", "PathwayCommons", "paths", "from", "-", "to", "genes", "return", "INDRA", "Statements", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/rest_api/api.py#L187-L196
19,280
sorgerlab/indra
rest_api/api.py
biopax_process_pc_neighborhood
def biopax_process_pc_neighborhood(): """Process PathwayCommons neighborhood, return INDRA Statements.""" if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) genes = body.get('genes') bp = biopax.process_pc_neighborhood(genes) return _stmts_from_proc(bp)
python
def biopax_process_pc_neighborhood(): if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) genes = body.get('genes') bp = biopax.process_pc_neighborhood(genes) return _stmts_from_proc(bp)
[ "def", "biopax_process_pc_neighborhood", "(", ")", ":", "if", "request", ".", "method", "==", "'OPTIONS'", ":", "return", "{", "}", "response", "=", "request", ".", "body", ".", "read", "(", ")", ".", "decode", "(", "'utf-8'", ")", "body", "=", "json", ...
Process PathwayCommons neighborhood, return INDRA Statements.
[ "Process", "PathwayCommons", "neighborhood", "return", "INDRA", "Statements", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/rest_api/api.py#L201-L209
19,281
sorgerlab/indra
rest_api/api.py
eidos_process_text
def eidos_process_text(): """Process text with EIDOS and return INDRA Statements.""" if request.method == 'OPTIONS': return {} req = request.body.read().decode('utf-8') body = json.loads(req) text = body.get('text') webservice = body.get('webservice') if not webservice: response.status = 400 response.content_type = 'application/json' return json.dumps({'error': 'No web service address provided.'}) ep = eidos.process_text(text, webservice=webservice) return _stmts_from_proc(ep)
python
def eidos_process_text(): if request.method == 'OPTIONS': return {} req = request.body.read().decode('utf-8') body = json.loads(req) text = body.get('text') webservice = body.get('webservice') if not webservice: response.status = 400 response.content_type = 'application/json' return json.dumps({'error': 'No web service address provided.'}) ep = eidos.process_text(text, webservice=webservice) return _stmts_from_proc(ep)
[ "def", "eidos_process_text", "(", ")", ":", "if", "request", ".", "method", "==", "'OPTIONS'", ":", "return", "{", "}", "req", "=", "request", ".", "body", ".", "read", "(", ")", ".", "decode", "(", "'utf-8'", ")", "body", "=", "json", ".", "loads", ...
Process text with EIDOS and return INDRA Statements.
[ "Process", "text", "with", "EIDOS", "and", "return", "INDRA", "Statements", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/rest_api/api.py#L215-L228
19,282
sorgerlab/indra
rest_api/api.py
eidos_process_jsonld
def eidos_process_jsonld(): """Process an EIDOS JSON-LD and return INDRA Statements.""" if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) eidos_json = body.get('jsonld') ep = eidos.process_json_str(eidos_json) return _stmts_from_proc(ep)
python
def eidos_process_jsonld(): if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) eidos_json = body.get('jsonld') ep = eidos.process_json_str(eidos_json) return _stmts_from_proc(ep)
[ "def", "eidos_process_jsonld", "(", ")", ":", "if", "request", ".", "method", "==", "'OPTIONS'", ":", "return", "{", "}", "response", "=", "request", ".", "body", ".", "read", "(", ")", ".", "decode", "(", "'utf-8'", ")", "body", "=", "json", ".", "l...
Process an EIDOS JSON-LD and return INDRA Statements.
[ "Process", "an", "EIDOS", "JSON", "-", "LD", "and", "return", "INDRA", "Statements", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/rest_api/api.py#L233-L241
19,283
sorgerlab/indra
rest_api/api.py
cwms_process_text
def cwms_process_text(): """Process text with CWMS and return INDRA Statements.""" if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) text = body.get('text') cp = cwms.process_text(text) return _stmts_from_proc(cp)
python
def cwms_process_text(): if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) text = body.get('text') cp = cwms.process_text(text) return _stmts_from_proc(cp)
[ "def", "cwms_process_text", "(", ")", ":", "if", "request", ".", "method", "==", "'OPTIONS'", ":", "return", "{", "}", "response", "=", "request", ".", "body", ".", "read", "(", ")", ".", "decode", "(", "'utf-8'", ")", "body", "=", "json", ".", "load...
Process text with CWMS and return INDRA Statements.
[ "Process", "text", "with", "CWMS", "and", "return", "INDRA", "Statements", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/rest_api/api.py#L246-L254
19,284
sorgerlab/indra
rest_api/api.py
hume_process_jsonld
def hume_process_jsonld(): """Process Hume JSON-LD and return INDRA Statements.""" if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) jsonld_str = body.get('jsonld') jsonld = json.loads(jsonld_str) hp = hume.process_jsonld(jsonld) return _stmts_from_proc(hp)
python
def hume_process_jsonld(): if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) jsonld_str = body.get('jsonld') jsonld = json.loads(jsonld_str) hp = hume.process_jsonld(jsonld) return _stmts_from_proc(hp)
[ "def", "hume_process_jsonld", "(", ")", ":", "if", "request", ".", "method", "==", "'OPTIONS'", ":", "return", "{", "}", "response", "=", "request", ".", "body", ".", "read", "(", ")", ".", "decode", "(", "'utf-8'", ")", "body", "=", "json", ".", "lo...
Process Hume JSON-LD and return INDRA Statements.
[ "Process", "Hume", "JSON", "-", "LD", "and", "return", "INDRA", "Statements", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/rest_api/api.py#L259-L268
19,285
sorgerlab/indra
rest_api/api.py
sofia_process_text
def sofia_process_text(): """Process text with Sofia and return INDRA Statements.""" if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) text = body.get('text') auth = body.get('auth') sp = sofia.process_text(text, auth=auth) return _stmts_from_proc(sp)
python
def sofia_process_text(): if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) text = body.get('text') auth = body.get('auth') sp = sofia.process_text(text, auth=auth) return _stmts_from_proc(sp)
[ "def", "sofia_process_text", "(", ")", ":", "if", "request", ".", "method", "==", "'OPTIONS'", ":", "return", "{", "}", "response", "=", "request", ".", "body", ".", "read", "(", ")", ".", "decode", "(", "'utf-8'", ")", "body", "=", "json", ".", "loa...
Process text with Sofia and return INDRA Statements.
[ "Process", "text", "with", "Sofia", "and", "return", "INDRA", "Statements", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/rest_api/api.py#L288-L297
19,286
sorgerlab/indra
rest_api/api.py
assemble_pysb
def assemble_pysb(): """Assemble INDRA Statements and return PySB model string.""" if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) stmts_json = body.get('statements') export_format = body.get('export_format') stmts = stmts_from_json(stmts_json) pa = PysbAssembler() pa.add_statements(stmts) pa.make_model() try: for m in pa.model.monomers: pysb_assembler.set_extended_initial_condition(pa.model, m, 0) except Exception as e: logger.exception(e) if not export_format: model_str = pa.print_model() elif export_format in ('kappa_im', 'kappa_cm'): fname = 'model_%s.png' % export_format root = os.path.dirname(os.path.abspath(fname)) graph = pa.export_model(format=export_format, file_name=fname) with open(fname, 'rb') as fh: data = 'data:image/png;base64,%s' % \ base64.b64encode(fh.read()).decode() return {'image': data} else: try: model_str = pa.export_model(format=export_format) except Exception as e: logger.exception(e) model_str = '' res = {'model': model_str} return res
python
def assemble_pysb(): if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) stmts_json = body.get('statements') export_format = body.get('export_format') stmts = stmts_from_json(stmts_json) pa = PysbAssembler() pa.add_statements(stmts) pa.make_model() try: for m in pa.model.monomers: pysb_assembler.set_extended_initial_condition(pa.model, m, 0) except Exception as e: logger.exception(e) if not export_format: model_str = pa.print_model() elif export_format in ('kappa_im', 'kappa_cm'): fname = 'model_%s.png' % export_format root = os.path.dirname(os.path.abspath(fname)) graph = pa.export_model(format=export_format, file_name=fname) with open(fname, 'rb') as fh: data = 'data:image/png;base64,%s' % \ base64.b64encode(fh.read()).decode() return {'image': data} else: try: model_str = pa.export_model(format=export_format) except Exception as e: logger.exception(e) model_str = '' res = {'model': model_str} return res
[ "def", "assemble_pysb", "(", ")", ":", "if", "request", ".", "method", "==", "'OPTIONS'", ":", "return", "{", "}", "response", "=", "request", ".", "body", ".", "read", "(", ")", ".", "decode", "(", "'utf-8'", ")", "body", "=", "json", ".", "loads", ...
Assemble INDRA Statements and return PySB model string.
[ "Assemble", "INDRA", "Statements", "and", "return", "PySB", "model", "string", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/rest_api/api.py#L307-L342
19,287
sorgerlab/indra
rest_api/api.py
assemble_cx
def assemble_cx(): """Assemble INDRA Statements and return CX network json.""" if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) stmts_json = body.get('statements') stmts = stmts_from_json(stmts_json) ca = CxAssembler(stmts) model_str = ca.make_model() res = {'model': model_str} return res
python
def assemble_cx(): if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) stmts_json = body.get('statements') stmts = stmts_from_json(stmts_json) ca = CxAssembler(stmts) model_str = ca.make_model() res = {'model': model_str} return res
[ "def", "assemble_cx", "(", ")", ":", "if", "request", ".", "method", "==", "'OPTIONS'", ":", "return", "{", "}", "response", "=", "request", ".", "body", ".", "read", "(", ")", ".", "decode", "(", "'utf-8'", ")", "body", "=", "json", ".", "loads", ...
Assemble INDRA Statements and return CX network json.
[ "Assemble", "INDRA", "Statements", "and", "return", "CX", "network", "json", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/rest_api/api.py#L348-L359
19,288
sorgerlab/indra
rest_api/api.py
share_model_ndex
def share_model_ndex(): """Upload the model to NDEX""" if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) stmts_str = body.get('stmts') stmts_json = json.loads(stmts_str) stmts = stmts_from_json(stmts_json["statements"]) ca = CxAssembler(stmts) for n, v in body.items(): ca.cx['networkAttributes'].append({'n': n, 'v': v, 'd': 'string'}) ca.make_model() network_id = ca.upload_model(private=False) return {'network_id': network_id}
python
def share_model_ndex(): if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) stmts_str = body.get('stmts') stmts_json = json.loads(stmts_str) stmts = stmts_from_json(stmts_json["statements"]) ca = CxAssembler(stmts) for n, v in body.items(): ca.cx['networkAttributes'].append({'n': n, 'v': v, 'd': 'string'}) ca.make_model() network_id = ca.upload_model(private=False) return {'network_id': network_id}
[ "def", "share_model_ndex", "(", ")", ":", "if", "request", ".", "method", "==", "'OPTIONS'", ":", "return", "{", "}", "response", "=", "request", ".", "body", ".", "read", "(", ")", ".", "decode", "(", "'utf-8'", ")", "body", "=", "json", ".", "loads...
Upload the model to NDEX
[ "Upload", "the", "model", "to", "NDEX" ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/rest_api/api.py#L365-L379
19,289
sorgerlab/indra
rest_api/api.py
fetch_model_ndex
def fetch_model_ndex(): """Download model and associated pieces from NDEX""" if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) network_id = body.get('network_id') cx = process_ndex_network(network_id) network_attr = [x for x in cx.cx if x.get('networkAttributes')] network_attr = network_attr[0]['networkAttributes'] keep_keys = ['txt_input', 'parser', 'model_elements', 'preset_pos', 'stmts', 'sentences', 'evidence', 'cell_line', 'mrna', 'mutations'] stored_data = {} for d in network_attr: if d['n'] in keep_keys: stored_data[d['n']] = d['v'] return stored_data
python
def fetch_model_ndex(): if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) network_id = body.get('network_id') cx = process_ndex_network(network_id) network_attr = [x for x in cx.cx if x.get('networkAttributes')] network_attr = network_attr[0]['networkAttributes'] keep_keys = ['txt_input', 'parser', 'model_elements', 'preset_pos', 'stmts', 'sentences', 'evidence', 'cell_line', 'mrna', 'mutations'] stored_data = {} for d in network_attr: if d['n'] in keep_keys: stored_data[d['n']] = d['v'] return stored_data
[ "def", "fetch_model_ndex", "(", ")", ":", "if", "request", ".", "method", "==", "'OPTIONS'", ":", "return", "{", "}", "response", "=", "request", ".", "body", ".", "read", "(", ")", ".", "decode", "(", "'utf-8'", ")", "body", "=", "json", ".", "loads...
Download model and associated pieces from NDEX
[ "Download", "model", "and", "associated", "pieces", "from", "NDEX" ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/rest_api/api.py#L384-L401
19,290
sorgerlab/indra
rest_api/api.py
assemble_graph
def assemble_graph(): """Assemble INDRA Statements and return Graphviz graph dot string.""" if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) stmts_json = body.get('statements') stmts = stmts_from_json(stmts_json) ga = GraphAssembler(stmts) model_str = ga.make_model() res = {'model': model_str} return res
python
def assemble_graph(): if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) stmts_json = body.get('statements') stmts = stmts_from_json(stmts_json) ga = GraphAssembler(stmts) model_str = ga.make_model() res = {'model': model_str} return res
[ "def", "assemble_graph", "(", ")", ":", "if", "request", ".", "method", "==", "'OPTIONS'", ":", "return", "{", "}", "response", "=", "request", ".", "body", ".", "read", "(", ")", ".", "decode", "(", "'utf-8'", ")", "body", "=", "json", ".", "loads",...
Assemble INDRA Statements and return Graphviz graph dot string.
[ "Assemble", "INDRA", "Statements", "and", "return", "Graphviz", "graph", "dot", "string", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/rest_api/api.py#L407-L418
19,291
sorgerlab/indra
rest_api/api.py
assemble_cyjs
def assemble_cyjs(): """Assemble INDRA Statements and return Cytoscape JS network.""" if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) stmts_json = body.get('statements') stmts = stmts_from_json(stmts_json) cja = CyJSAssembler() cja.add_statements(stmts) cja.make_model(grouping=True) model_str = cja.print_cyjs_graph() return model_str
python
def assemble_cyjs(): if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) stmts_json = body.get('statements') stmts = stmts_from_json(stmts_json) cja = CyJSAssembler() cja.add_statements(stmts) cja.make_model(grouping=True) model_str = cja.print_cyjs_graph() return model_str
[ "def", "assemble_cyjs", "(", ")", ":", "if", "request", ".", "method", "==", "'OPTIONS'", ":", "return", "{", "}", "response", "=", "request", ".", "body", ".", "read", "(", ")", ".", "decode", "(", "'utf-8'", ")", "body", "=", "json", ".", "loads", ...
Assemble INDRA Statements and return Cytoscape JS network.
[ "Assemble", "INDRA", "Statements", "and", "return", "Cytoscape", "JS", "network", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/rest_api/api.py#L424-L436
19,292
sorgerlab/indra
rest_api/api.py
assemble_english
def assemble_english(): """Assemble each statement into """ if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) stmts_json = body.get('statements') stmts = stmts_from_json(stmts_json) sentences = {} for st in stmts: enga = EnglishAssembler() enga.add_statements([st]) model_str = enga.make_model() sentences[st.uuid] = model_str res = {'sentences': sentences} return res
python
def assemble_english(): if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) stmts_json = body.get('statements') stmts = stmts_from_json(stmts_json) sentences = {} for st in stmts: enga = EnglishAssembler() enga.add_statements([st]) model_str = enga.make_model() sentences[st.uuid] = model_str res = {'sentences': sentences} return res
[ "def", "assemble_english", "(", ")", ":", "if", "request", ".", "method", "==", "'OPTIONS'", ":", "return", "{", "}", "response", "=", "request", ".", "body", ".", "read", "(", ")", ".", "decode", "(", "'utf-8'", ")", "body", "=", "json", ".", "loads...
Assemble each statement into
[ "Assemble", "each", "statement", "into" ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/rest_api/api.py#L442-L457
19,293
sorgerlab/indra
rest_api/api.py
assemble_loopy
def assemble_loopy(): """Assemble INDRA Statements into a Loopy model using SIF Assembler.""" if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) stmts_json = body.get('statements') stmts = stmts_from_json(stmts_json) sa = SifAssembler(stmts) sa.make_model(use_name_as_key=True) model_str = sa.print_loopy(as_url=True) res = {'loopy_url': model_str} return res
python
def assemble_loopy(): if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) stmts_json = body.get('statements') stmts = stmts_from_json(stmts_json) sa = SifAssembler(stmts) sa.make_model(use_name_as_key=True) model_str = sa.print_loopy(as_url=True) res = {'loopy_url': model_str} return res
[ "def", "assemble_loopy", "(", ")", ":", "if", "request", ".", "method", "==", "'OPTIONS'", ":", "return", "{", "}", "response", "=", "request", ".", "body", ".", "read", "(", ")", ".", "decode", "(", "'utf-8'", ")", "body", "=", "json", ".", "loads",...
Assemble INDRA Statements into a Loopy model using SIF Assembler.
[ "Assemble", "INDRA", "Statements", "into", "a", "Loopy", "model", "using", "SIF", "Assembler", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/rest_api/api.py#L462-L474
19,294
sorgerlab/indra
rest_api/api.py
get_ccle_mrna_levels
def get_ccle_mrna_levels(): """Get CCLE mRNA amounts using cBioClient""" if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) gene_list = body.get('gene_list') cell_lines = body.get('cell_lines') mrna_amounts = cbio_client.get_ccle_mrna(gene_list, cell_lines) res = {'mrna_amounts': mrna_amounts} return res
python
def get_ccle_mrna_levels(): if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) gene_list = body.get('gene_list') cell_lines = body.get('cell_lines') mrna_amounts = cbio_client.get_ccle_mrna(gene_list, cell_lines) res = {'mrna_amounts': mrna_amounts} return res
[ "def", "get_ccle_mrna_levels", "(", ")", ":", "if", "request", ".", "method", "==", "'OPTIONS'", ":", "return", "{", "}", "response", "=", "request", ".", "body", ".", "read", "(", ")", ".", "decode", "(", "'utf-8'", ")", "body", "=", "json", ".", "l...
Get CCLE mRNA amounts using cBioClient
[ "Get", "CCLE", "mRNA", "amounts", "using", "cBioClient" ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/rest_api/api.py#L480-L490
19,295
sorgerlab/indra
rest_api/api.py
get_ccle_mutations
def get_ccle_mutations(): """Get CCLE mutations returns the amino acid changes for a given list of genes and cell lines """ if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) gene_list = body.get('gene_list') cell_lines = body.get('cell_lines') mutations = cbio_client.get_ccle_mutations(gene_list, cell_lines) res = {'mutations': mutations} return res
python
def get_ccle_mutations(): if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) gene_list = body.get('gene_list') cell_lines = body.get('cell_lines') mutations = cbio_client.get_ccle_mutations(gene_list, cell_lines) res = {'mutations': mutations} return res
[ "def", "get_ccle_mutations", "(", ")", ":", "if", "request", ".", "method", "==", "'OPTIONS'", ":", "return", "{", "}", "response", "=", "request", ".", "body", ".", "read", "(", ")", ".", "decode", "(", "'utf-8'", ")", "body", "=", "json", ".", "loa...
Get CCLE mutations returns the amino acid changes for a given list of genes and cell lines
[ "Get", "CCLE", "mutations", "returns", "the", "amino", "acid", "changes", "for", "a", "given", "list", "of", "genes", "and", "cell", "lines" ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/rest_api/api.py#L517-L529
19,296
sorgerlab/indra
rest_api/api.py
map_grounding
def map_grounding(): """Map grounding on a list of INDRA Statements.""" if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) stmts_json = body.get('statements') stmts = stmts_from_json(stmts_json) stmts_out = ac.map_grounding(stmts) return _return_stmts(stmts_out)
python
def map_grounding(): if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) stmts_json = body.get('statements') stmts = stmts_from_json(stmts_json) stmts_out = ac.map_grounding(stmts) return _return_stmts(stmts_out)
[ "def", "map_grounding", "(", ")", ":", "if", "request", ".", "method", "==", "'OPTIONS'", ":", "return", "{", "}", "response", "=", "request", ".", "body", ".", "read", "(", ")", ".", "decode", "(", "'utf-8'", ")", "body", "=", "json", ".", "loads", ...
Map grounding on a list of INDRA Statements.
[ "Map", "grounding", "on", "a", "list", "of", "INDRA", "Statements", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/rest_api/api.py#L534-L543
19,297
sorgerlab/indra
rest_api/api.py
run_preassembly
def run_preassembly(): """Run preassembly on a list of INDRA Statements.""" if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) stmts_json = body.get('statements') stmts = stmts_from_json(stmts_json) scorer = body.get('scorer') return_toplevel = body.get('return_toplevel') if scorer == 'wm': belief_scorer = get_eidos_scorer() else: belief_scorer = None stmts_out = ac.run_preassembly(stmts, belief_scorer=belief_scorer, return_toplevel=return_toplevel) return _return_stmts(stmts_out)
python
def run_preassembly(): if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) stmts_json = body.get('statements') stmts = stmts_from_json(stmts_json) scorer = body.get('scorer') return_toplevel = body.get('return_toplevel') if scorer == 'wm': belief_scorer = get_eidos_scorer() else: belief_scorer = None stmts_out = ac.run_preassembly(stmts, belief_scorer=belief_scorer, return_toplevel=return_toplevel) return _return_stmts(stmts_out)
[ "def", "run_preassembly", "(", ")", ":", "if", "request", ".", "method", "==", "'OPTIONS'", ":", "return", "{", "}", "response", "=", "request", ".", "body", ".", "read", "(", ")", ".", "decode", "(", "'utf-8'", ")", "body", "=", "json", ".", "loads"...
Run preassembly on a list of INDRA Statements.
[ "Run", "preassembly", "on", "a", "list", "of", "INDRA", "Statements", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/rest_api/api.py#L562-L578
19,298
sorgerlab/indra
rest_api/api.py
map_ontologies
def map_ontologies(): """Run ontology mapping on a list of INDRA Statements.""" if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) stmts_json = body.get('statements') stmts = stmts_from_json(stmts_json) om = OntologyMapper(stmts, wm_ontomap, scored=True, symmetric=False) om.map_statements() return _return_stmts(stmts)
python
def map_ontologies(): if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) stmts_json = body.get('statements') stmts = stmts_from_json(stmts_json) om = OntologyMapper(stmts, wm_ontomap, scored=True, symmetric=False) om.map_statements() return _return_stmts(stmts)
[ "def", "map_ontologies", "(", ")", ":", "if", "request", ".", "method", "==", "'OPTIONS'", ":", "return", "{", "}", "response", "=", "request", ".", "body", ".", "read", "(", ")", ".", "decode", "(", "'utf-8'", ")", "body", "=", "json", ".", "loads",...
Run ontology mapping on a list of INDRA Statements.
[ "Run", "ontology", "mapping", "on", "a", "list", "of", "INDRA", "Statements", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/rest_api/api.py#L583-L593
19,299
sorgerlab/indra
rest_api/api.py
filter_by_type
def filter_by_type(): """Filter to a given INDRA Statement type.""" if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) stmts_json = body.get('statements') stmt_type_str = body.get('type') stmt_type_str = stmt_type_str.capitalize() stmt_type = getattr(sys.modules[__name__], stmt_type_str) stmts = stmts_from_json(stmts_json) stmts_out = ac.filter_by_type(stmts, stmt_type) return _return_stmts(stmts_out)
python
def filter_by_type(): if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) stmts_json = body.get('statements') stmt_type_str = body.get('type') stmt_type_str = stmt_type_str.capitalize() stmt_type = getattr(sys.modules[__name__], stmt_type_str) stmts = stmts_from_json(stmts_json) stmts_out = ac.filter_by_type(stmts, stmt_type) return _return_stmts(stmts_out)
[ "def", "filter_by_type", "(", ")", ":", "if", "request", ".", "method", "==", "'OPTIONS'", ":", "return", "{", "}", "response", "=", "request", ".", "body", ".", "read", "(", ")", ".", "decode", "(", "'utf-8'", ")", "body", "=", "json", ".", "loads",...
Filter to a given INDRA Statement type.
[ "Filter", "to", "a", "given", "INDRA", "Statement", "type", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/rest_api/api.py#L598-L610