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,300
sorgerlab/indra
rest_api/api.py
filter_grounded_only
def filter_grounded_only(): """Filter to grounded Statements only.""" if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) stmts_json = body.get('statements') score_threshold = body.get('score_threshold') if score_threshold is not None: score_threshold = float(score_threshold) stmts = stmts_from_json(stmts_json) stmts_out = ac.filter_grounded_only(stmts, score_threshold=score_threshold) return _return_stmts(stmts_out)
python
def filter_grounded_only(): if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) stmts_json = body.get('statements') score_threshold = body.get('score_threshold') if score_threshold is not None: score_threshold = float(score_threshold) stmts = stmts_from_json(stmts_json) stmts_out = ac.filter_grounded_only(stmts, score_threshold=score_threshold) return _return_stmts(stmts_out)
[ "def", "filter_grounded_only", "(", ")", ":", "if", "request", ".", "method", "==", "'OPTIONS'", ":", "return", "{", "}", "response", "=", "request", ".", "body", ".", "read", "(", ")", ".", "decode", "(", "'utf-8'", ")", "body", "=", "json", ".", "l...
Filter to grounded Statements only.
[ "Filter", "to", "grounded", "Statements", "only", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/rest_api/api.py#L615-L627
19,301
sorgerlab/indra
rest_api/api.py
filter_belief
def filter_belief(): """Filter to beliefs above a given threshold.""" if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) stmts_json = body.get('statements') belief_cutoff = body.get('belief_cutoff') if belief_cutoff is not None: belief_cutoff = float(belief_cutoff) stmts = stmts_from_json(stmts_json) stmts_out = ac.filter_belief(stmts, belief_cutoff) return _return_stmts(stmts_out)
python
def filter_belief(): if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) stmts_json = body.get('statements') belief_cutoff = body.get('belief_cutoff') if belief_cutoff is not None: belief_cutoff = float(belief_cutoff) stmts = stmts_from_json(stmts_json) stmts_out = ac.filter_belief(stmts, belief_cutoff) return _return_stmts(stmts_out)
[ "def", "filter_belief", "(", ")", ":", "if", "request", ".", "method", "==", "'OPTIONS'", ":", "return", "{", "}", "response", "=", "request", ".", "body", ".", "read", "(", ")", ".", "decode", "(", "'utf-8'", ")", "body", "=", "json", ".", "loads", ...
Filter to beliefs above a given threshold.
[ "Filter", "to", "beliefs", "above", "a", "given", "threshold", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/rest_api/api.py#L632-L644
19,302
sorgerlab/indra
indra/util/get_version.py
get_git_info
def get_git_info(): """Get a dict with useful git info.""" start_dir = abspath(curdir) try: chdir(dirname(abspath(__file__))) re_patt_str = (r'commit\s+(?P<commit_hash>\w+).*?Author:\s+' r'(?P<author_name>.*?)\s+<(?P<author_email>.*?)>\s+Date:\s+' r'(?P<date>.*?)\n\s+(?P<commit_msg>.*?)(?:\ndiff.*?)?$') show_out = check_output(['git', 'show']).decode('ascii') revp_out = check_output(['git', 'rev-parse', '--abbrev-ref', 'HEAD']) revp_out = revp_out.decode('ascii').strip() m = re.search(re_patt_str, show_out, re.DOTALL) assert m is not None, \ "Regex pattern:\n\n\"%s\"\n\n failed to match string:\n\n\"%s\"" \ % (re_patt_str, show_out) ret_dict = m.groupdict() ret_dict['branch_name'] = revp_out finally: chdir(start_dir) return ret_dict
python
def get_git_info(): start_dir = abspath(curdir) try: chdir(dirname(abspath(__file__))) re_patt_str = (r'commit\s+(?P<commit_hash>\w+).*?Author:\s+' r'(?P<author_name>.*?)\s+<(?P<author_email>.*?)>\s+Date:\s+' r'(?P<date>.*?)\n\s+(?P<commit_msg>.*?)(?:\ndiff.*?)?$') show_out = check_output(['git', 'show']).decode('ascii') revp_out = check_output(['git', 'rev-parse', '--abbrev-ref', 'HEAD']) revp_out = revp_out.decode('ascii').strip() m = re.search(re_patt_str, show_out, re.DOTALL) assert m is not None, \ "Regex pattern:\n\n\"%s\"\n\n failed to match string:\n\n\"%s\"" \ % (re_patt_str, show_out) ret_dict = m.groupdict() ret_dict['branch_name'] = revp_out finally: chdir(start_dir) return ret_dict
[ "def", "get_git_info", "(", ")", ":", "start_dir", "=", "abspath", "(", "curdir", ")", "try", ":", "chdir", "(", "dirname", "(", "abspath", "(", "__file__", ")", ")", ")", "re_patt_str", "=", "(", "r'commit\\s+(?P<commit_hash>\\w+).*?Author:\\s+'", "r'(?P<author...
Get a dict with useful git info.
[ "Get", "a", "dict", "with", "useful", "git", "info", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/util/get_version.py#L18-L37
19,303
sorgerlab/indra
indra/util/get_version.py
get_version
def get_version(with_git_hash=True, refresh_hash=False): """Get an indra version string, including a git hash.""" version = __version__ if with_git_hash: global INDRA_GITHASH if INDRA_GITHASH is None or refresh_hash: with open(devnull, 'w') as nul: try: ret = check_output(['git', 'rev-parse', 'HEAD'], cwd=dirname(__file__), stderr=nul) except CalledProcessError: ret = 'UNHASHED' INDRA_GITHASH = ret.strip().decode('utf-8') version = '%s-%s' % (version, INDRA_GITHASH) return version
python
def get_version(with_git_hash=True, refresh_hash=False): version = __version__ if with_git_hash: global INDRA_GITHASH if INDRA_GITHASH is None or refresh_hash: with open(devnull, 'w') as nul: try: ret = check_output(['git', 'rev-parse', 'HEAD'], cwd=dirname(__file__), stderr=nul) except CalledProcessError: ret = 'UNHASHED' INDRA_GITHASH = ret.strip().decode('utf-8') version = '%s-%s' % (version, INDRA_GITHASH) return version
[ "def", "get_version", "(", "with_git_hash", "=", "True", ",", "refresh_hash", "=", "False", ")", ":", "version", "=", "__version__", "if", "with_git_hash", ":", "global", "INDRA_GITHASH", "if", "INDRA_GITHASH", "is", "None", "or", "refresh_hash", ":", "with", ...
Get an indra version string, including a git hash.
[ "Get", "an", "indra", "version", "string", "including", "a", "git", "hash", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/util/get_version.py#L40-L54
19,304
sorgerlab/indra
indra/assemblers/cx/assembler.py
_fix_evidence_text
def _fix_evidence_text(txt): """Eliminate some symbols to have cleaner supporting text.""" txt = re.sub('[ ]?\( xref \)', '', txt) # This is to make [ xref ] become [] to match the two readers txt = re.sub('\[ xref \]', '[]', txt) txt = re.sub('[\(]?XREF_BIBR[\)]?[,]?', '', txt) txt = re.sub('[\(]?XREF_FIG[\)]?[,]?', '', txt) txt = re.sub('[\(]?XREF_SUPPLEMENT[\)]?[,]?', '', txt) txt = txt.strip() return txt
python
def _fix_evidence_text(txt): txt = re.sub('[ ]?\( xref \)', '', txt) # This is to make [ xref ] become [] to match the two readers txt = re.sub('\[ xref \]', '[]', txt) txt = re.sub('[\(]?XREF_BIBR[\)]?[,]?', '', txt) txt = re.sub('[\(]?XREF_FIG[\)]?[,]?', '', txt) txt = re.sub('[\(]?XREF_SUPPLEMENT[\)]?[,]?', '', txt) txt = txt.strip() return txt
[ "def", "_fix_evidence_text", "(", "txt", ")", ":", "txt", "=", "re", ".", "sub", "(", "'[ ]?\\( xref \\)'", ",", "''", ",", "txt", ")", "# This is to make [ xref ] become [] to match the two readers", "txt", "=", "re", ".", "sub", "(", "'\\[ xref \\]'", ",", "'[...
Eliminate some symbols to have cleaner supporting text.
[ "Eliminate", "some", "symbols", "to", "have", "cleaner", "supporting", "text", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/cx/assembler.py#L562-L571
19,305
sorgerlab/indra
indra/assemblers/cx/assembler.py
CxAssembler.make_model
def make_model(self, add_indra_json=True): """Assemble the CX network from the collected INDRA Statements. This method assembles a CX network from the set of INDRA Statements. The assembled network is set as the assembler's cx argument. Parameters ---------- add_indra_json : Optional[bool] If True, the INDRA Statement JSON annotation is added to each edge in the network. Default: True Returns ------- cx_str : str The json serialized CX model. """ self.add_indra_json = add_indra_json for stmt in self.statements: if isinstance(stmt, Modification): self._add_modification(stmt) if isinstance(stmt, SelfModification): self._add_self_modification(stmt) elif isinstance(stmt, RegulateActivity) or \ isinstance(stmt, RegulateAmount): self._add_regulation(stmt) elif isinstance(stmt, Complex): self._add_complex(stmt) elif isinstance(stmt, Gef): self._add_gef(stmt) elif isinstance(stmt, Gap): self._add_gap(stmt) elif isinstance(stmt, Influence): self._add_influence(stmt) network_description = '' self.cx['networkAttributes'].append({'n': 'name', 'v': self.network_name}) self.cx['networkAttributes'].append({'n': 'description', 'v': network_description}) cx_str = self.print_cx() return cx_str
python
def make_model(self, add_indra_json=True): self.add_indra_json = add_indra_json for stmt in self.statements: if isinstance(stmt, Modification): self._add_modification(stmt) if isinstance(stmt, SelfModification): self._add_self_modification(stmt) elif isinstance(stmt, RegulateActivity) or \ isinstance(stmt, RegulateAmount): self._add_regulation(stmt) elif isinstance(stmt, Complex): self._add_complex(stmt) elif isinstance(stmt, Gef): self._add_gef(stmt) elif isinstance(stmt, Gap): self._add_gap(stmt) elif isinstance(stmt, Influence): self._add_influence(stmt) network_description = '' self.cx['networkAttributes'].append({'n': 'name', 'v': self.network_name}) self.cx['networkAttributes'].append({'n': 'description', 'v': network_description}) cx_str = self.print_cx() return cx_str
[ "def", "make_model", "(", "self", ",", "add_indra_json", "=", "True", ")", ":", "self", ".", "add_indra_json", "=", "add_indra_json", "for", "stmt", "in", "self", ".", "statements", ":", "if", "isinstance", "(", "stmt", ",", "Modification", ")", ":", "self...
Assemble the CX network from the collected INDRA Statements. This method assembles a CX network from the set of INDRA Statements. The assembled network is set as the assembler's cx argument. Parameters ---------- add_indra_json : Optional[bool] If True, the INDRA Statement JSON annotation is added to each edge in the network. Default: True Returns ------- cx_str : str The json serialized CX model.
[ "Assemble", "the", "CX", "network", "from", "the", "collected", "INDRA", "Statements", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/cx/assembler.py#L75-L115
19,306
sorgerlab/indra
indra/assemblers/cx/assembler.py
CxAssembler.print_cx
def print_cx(self, pretty=True): """Return the assembled CX network as a json string. Parameters ---------- pretty : bool If True, the CX string is formatted with indentation (for human viewing) otherwise no indentation is used. Returns ------- json_str : str A json formatted string representation of the CX network. """ def _get_aspect_metadata(aspect): count = len(self.cx.get(aspect)) if self.cx.get(aspect) else 0 if not count: return None data = {'name': aspect, 'idCounter': self._id_counter, 'consistencyGroup': 1, 'elementCount': count} return data full_cx = OrderedDict() full_cx['numberVerification'] = [{'longNumber': 281474976710655}] aspects = ['nodes', 'edges', 'supports', 'citations', 'edgeAttributes', 'edgeCitations', 'edgeSupports', 'networkAttributes', 'nodeAttributes', 'cartesianLayout'] full_cx['metaData'] = [] for aspect in aspects: metadata = _get_aspect_metadata(aspect) if metadata: full_cx['metaData'].append(metadata) for k, v in self.cx.items(): full_cx[k] = v full_cx['status'] = [{'error': '', 'success': True}] full_cx = [{k: v} for k, v in full_cx.items()] if pretty: json_str = json.dumps(full_cx, indent=2) else: json_str = json.dumps(full_cx) return json_str
python
def print_cx(self, pretty=True): def _get_aspect_metadata(aspect): count = len(self.cx.get(aspect)) if self.cx.get(aspect) else 0 if not count: return None data = {'name': aspect, 'idCounter': self._id_counter, 'consistencyGroup': 1, 'elementCount': count} return data full_cx = OrderedDict() full_cx['numberVerification'] = [{'longNumber': 281474976710655}] aspects = ['nodes', 'edges', 'supports', 'citations', 'edgeAttributes', 'edgeCitations', 'edgeSupports', 'networkAttributes', 'nodeAttributes', 'cartesianLayout'] full_cx['metaData'] = [] for aspect in aspects: metadata = _get_aspect_metadata(aspect) if metadata: full_cx['metaData'].append(metadata) for k, v in self.cx.items(): full_cx[k] = v full_cx['status'] = [{'error': '', 'success': True}] full_cx = [{k: v} for k, v in full_cx.items()] if pretty: json_str = json.dumps(full_cx, indent=2) else: json_str = json.dumps(full_cx) return json_str
[ "def", "print_cx", "(", "self", ",", "pretty", "=", "True", ")", ":", "def", "_get_aspect_metadata", "(", "aspect", ")", ":", "count", "=", "len", "(", "self", ".", "cx", ".", "get", "(", "aspect", ")", ")", "if", "self", ".", "cx", ".", "get", "...
Return the assembled CX network as a json string. Parameters ---------- pretty : bool If True, the CX string is formatted with indentation (for human viewing) otherwise no indentation is used. Returns ------- json_str : str A json formatted string representation of the CX network.
[ "Return", "the", "assembled", "CX", "network", "as", "a", "json", "string", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/cx/assembler.py#L117-L158
19,307
sorgerlab/indra
indra/assemblers/cx/assembler.py
CxAssembler.save_model
def save_model(self, file_name='model.cx'): """Save the assembled CX network in a file. Parameters ---------- file_name : Optional[str] The name of the file to save the CX network to. Default: model.cx """ with open(file_name, 'wt') as fh: cx_str = self.print_cx() fh.write(cx_str)
python
def save_model(self, file_name='model.cx'): with open(file_name, 'wt') as fh: cx_str = self.print_cx() fh.write(cx_str)
[ "def", "save_model", "(", "self", ",", "file_name", "=", "'model.cx'", ")", ":", "with", "open", "(", "file_name", ",", "'wt'", ")", "as", "fh", ":", "cx_str", "=", "self", ".", "print_cx", "(", ")", "fh", ".", "write", "(", "cx_str", ")" ]
Save the assembled CX network in a file. Parameters ---------- file_name : Optional[str] The name of the file to save the CX network to. Default: model.cx
[ "Save", "the", "assembled", "CX", "network", "in", "a", "file", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/cx/assembler.py#L160-L170
19,308
sorgerlab/indra
indra/assemblers/cx/assembler.py
CxAssembler.set_context
def set_context(self, cell_type): """Set protein expression data and mutational status as node attribute This method uses :py:mod:`indra.databases.context_client` to get protein expression levels and mutational status for a given cell type and set a node attribute for proteins accordingly. Parameters ---------- cell_type : str Cell type name for which expression levels are queried. The cell type name follows the CCLE database conventions. Example: LOXIMVI_SKIN, BT20_BREAST """ node_names = [node['n'] for node in self.cx['nodes']] res_expr = context_client.get_protein_expression(node_names, [cell_type]) res_mut = context_client.get_mutations(node_names, [cell_type]) res_expr = res_expr.get(cell_type) res_mut = res_mut.get(cell_type) if not res_expr: msg = 'Could not get protein expression for %s cell type.' % \ cell_type logger.warning(msg) if not res_mut: msg = 'Could not get mutational status for %s cell type.' % \ cell_type logger.warning(msg) if not res_expr and not res_mut: return self.cx['networkAttributes'].append({'n': 'cellular_context', 'v': cell_type}) counter = 0 for node in self.cx['nodes']: amount = res_expr.get(node['n']) mut = res_mut.get(node['n']) if amount is not None: node_attribute = {'po': node['@id'], 'n': 'expression_amount', 'v': int(amount)} self.cx['nodeAttributes'].append(node_attribute) if mut is not None: is_mutated = 1 if mut else 0 node_attribute = {'po': node['@id'], 'n': 'is_mutated', 'v': is_mutated} self.cx['nodeAttributes'].append(node_attribute) if mut is not None or amount is not None: counter += 1 logger.info('Set context for %d nodes.' % counter)
python
def set_context(self, cell_type): node_names = [node['n'] for node in self.cx['nodes']] res_expr = context_client.get_protein_expression(node_names, [cell_type]) res_mut = context_client.get_mutations(node_names, [cell_type]) res_expr = res_expr.get(cell_type) res_mut = res_mut.get(cell_type) if not res_expr: msg = 'Could not get protein expression for %s cell type.' % \ cell_type logger.warning(msg) if not res_mut: msg = 'Could not get mutational status for %s cell type.' % \ cell_type logger.warning(msg) if not res_expr and not res_mut: return self.cx['networkAttributes'].append({'n': 'cellular_context', 'v': cell_type}) counter = 0 for node in self.cx['nodes']: amount = res_expr.get(node['n']) mut = res_mut.get(node['n']) if amount is not None: node_attribute = {'po': node['@id'], 'n': 'expression_amount', 'v': int(amount)} self.cx['nodeAttributes'].append(node_attribute) if mut is not None: is_mutated = 1 if mut else 0 node_attribute = {'po': node['@id'], 'n': 'is_mutated', 'v': is_mutated} self.cx['nodeAttributes'].append(node_attribute) if mut is not None or amount is not None: counter += 1 logger.info('Set context for %d nodes.' % counter)
[ "def", "set_context", "(", "self", ",", "cell_type", ")", ":", "node_names", "=", "[", "node", "[", "'n'", "]", "for", "node", "in", "self", ".", "cx", "[", "'nodes'", "]", "]", "res_expr", "=", "context_client", ".", "get_protein_expression", "(", "node...
Set protein expression data and mutational status as node attribute This method uses :py:mod:`indra.databases.context_client` to get protein expression levels and mutational status for a given cell type and set a node attribute for proteins accordingly. Parameters ---------- cell_type : str Cell type name for which expression levels are queried. The cell type name follows the CCLE database conventions. Example: LOXIMVI_SKIN, BT20_BREAST
[ "Set", "protein", "expression", "data", "and", "mutational", "status", "as", "node", "attribute" ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/cx/assembler.py#L212-L265
19,309
sorgerlab/indra
indra/databases/biogrid_client.py
get_publications
def get_publications(gene_names, save_json_name=None): """Return evidence publications for interaction between the given genes. Parameters ---------- gene_names : list[str] A list of gene names (HGNC symbols) to query interactions between. Currently supports exactly two genes only. save_json_name : Optional[str] A file name to save the raw BioGRID web service output in. By default, the raw output is not saved. Return ------ publications : list[Publication] A list of Publication objects that provide evidence for interactions between the given list of genes. """ if len(gene_names) != 2: logger.warning('Other than 2 gene names given.') return [] res_dict = _send_request(gene_names) if not res_dict: return [] if save_json_name is not None: # The json module produces strings, not bytes, so the file should be # opened in text mode with open(save_json_name, 'wt') as fh: json.dump(res_dict, fh, indent=1) publications = _extract_publications(res_dict, gene_names) return publications
python
def get_publications(gene_names, save_json_name=None): if len(gene_names) != 2: logger.warning('Other than 2 gene names given.') return [] res_dict = _send_request(gene_names) if not res_dict: return [] if save_json_name is not None: # The json module produces strings, not bytes, so the file should be # opened in text mode with open(save_json_name, 'wt') as fh: json.dump(res_dict, fh, indent=1) publications = _extract_publications(res_dict, gene_names) return publications
[ "def", "get_publications", "(", "gene_names", ",", "save_json_name", "=", "None", ")", ":", "if", "len", "(", "gene_names", ")", "!=", "2", ":", "logger", ".", "warning", "(", "'Other than 2 gene names given.'", ")", "return", "[", "]", "res_dict", "=", "_se...
Return evidence publications for interaction between the given genes. Parameters ---------- gene_names : list[str] A list of gene names (HGNC symbols) to query interactions between. Currently supports exactly two genes only. save_json_name : Optional[str] A file name to save the raw BioGRID web service output in. By default, the raw output is not saved. Return ------ publications : list[Publication] A list of Publication objects that provide evidence for interactions between the given list of genes.
[ "Return", "evidence", "publications", "for", "interaction", "between", "the", "given", "genes", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/databases/biogrid_client.py#L90-L120
19,310
sorgerlab/indra
indra/assemblers/pysb/common.py
_n
def _n(name): """Return valid PySB name.""" n = name.encode('ascii', errors='ignore').decode('ascii') n = re.sub('[^A-Za-z0-9_]', '_', n) n = re.sub(r'(^[0-9].*)', r'p\1', n) return n
python
def _n(name): n = name.encode('ascii', errors='ignore').decode('ascii') n = re.sub('[^A-Za-z0-9_]', '_', n) n = re.sub(r'(^[0-9].*)', r'p\1', n) return n
[ "def", "_n", "(", "name", ")", ":", "n", "=", "name", ".", "encode", "(", "'ascii'", ",", "errors", "=", "'ignore'", ")", ".", "decode", "(", "'ascii'", ")", "n", "=", "re", ".", "sub", "(", "'[^A-Za-z0-9_]'", ",", "'_'", ",", "n", ")", "n", "=...
Return valid PySB name.
[ "Return", "valid", "PySB", "name", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/pysb/common.py#L5-L10
19,311
sorgerlab/indra
indra/sources/indra_db_rest/processor.py
IndraDBRestProcessor.get_hash_statements_dict
def get_hash_statements_dict(self): """Return a dict of Statements keyed by hashes.""" res = {stmt_hash: stmts_from_json([stmt])[0] for stmt_hash, stmt in self.__statement_jsons.items()} return res
python
def get_hash_statements_dict(self): res = {stmt_hash: stmts_from_json([stmt])[0] for stmt_hash, stmt in self.__statement_jsons.items()} return res
[ "def", "get_hash_statements_dict", "(", "self", ")", ":", "res", "=", "{", "stmt_hash", ":", "stmts_from_json", "(", "[", "stmt", "]", ")", "[", "0", "]", "for", "stmt_hash", ",", "stmt", "in", "self", ".", "__statement_jsons", ".", "items", "(", ")", ...
Return a dict of Statements keyed by hashes.
[ "Return", "a", "dict", "of", "Statements", "keyed", "by", "hashes", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/indra_db_rest/processor.py#L159-L163
19,312
sorgerlab/indra
indra/sources/indra_db_rest/processor.py
IndraDBRestProcessor.merge_results
def merge_results(self, other_processor): """Merge the results of this processor with those of another.""" if not isinstance(other_processor, self.__class__): raise ValueError("Can only extend with another %s instance." % self.__class__.__name__) self.statements.extend(other_processor.statements) if other_processor.statements_sample is not None: if self.statements_sample is None: self.statements_sample = other_processor.statements_sample else: self.statements_sample.extend(other_processor.statements_sample) self._merge_json(other_processor.__statement_jsons, other_processor.__evidence_counts) return
python
def merge_results(self, other_processor): if not isinstance(other_processor, self.__class__): raise ValueError("Can only extend with another %s instance." % self.__class__.__name__) self.statements.extend(other_processor.statements) if other_processor.statements_sample is not None: if self.statements_sample is None: self.statements_sample = other_processor.statements_sample else: self.statements_sample.extend(other_processor.statements_sample) self._merge_json(other_processor.__statement_jsons, other_processor.__evidence_counts) return
[ "def", "merge_results", "(", "self", ",", "other_processor", ")", ":", "if", "not", "isinstance", "(", "other_processor", ",", "self", ".", "__class__", ")", ":", "raise", "ValueError", "(", "\"Can only extend with another %s instance.\"", "%", "self", ".", "__cla...
Merge the results of this processor with those of another.
[ "Merge", "the", "results", "of", "this", "processor", "with", "those", "of", "another", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/indra_db_rest/processor.py#L165-L179
19,313
sorgerlab/indra
indra/sources/indra_db_rest/processor.py
IndraDBRestProcessor.wait_until_done
def wait_until_done(self, timeout=None): """Wait for the background load to complete.""" start = datetime.now() if not self.__th: raise IndraDBRestResponseError("There is no thread waiting to " "complete.") self.__th.join(timeout) now = datetime.now() dt = now - start if self.__th.is_alive(): logger.warning("Timed out after %0.3f seconds waiting for " "statement load to complete." % dt.total_seconds()) ret = False else: logger.info("Waited %0.3f seconds for statements to finish loading." % dt.total_seconds()) ret = True return ret
python
def wait_until_done(self, timeout=None): start = datetime.now() if not self.__th: raise IndraDBRestResponseError("There is no thread waiting to " "complete.") self.__th.join(timeout) now = datetime.now() dt = now - start if self.__th.is_alive(): logger.warning("Timed out after %0.3f seconds waiting for " "statement load to complete." % dt.total_seconds()) ret = False else: logger.info("Waited %0.3f seconds for statements to finish loading." % dt.total_seconds()) ret = True return ret
[ "def", "wait_until_done", "(", "self", ",", "timeout", "=", "None", ")", ":", "start", "=", "datetime", ".", "now", "(", ")", "if", "not", "self", ".", "__th", ":", "raise", "IndraDBRestResponseError", "(", "\"There is no thread waiting to \"", "\"complete.\"", ...
Wait for the background load to complete.
[ "Wait", "for", "the", "background", "load", "to", "complete", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/indra_db_rest/processor.py#L181-L198
19,314
sorgerlab/indra
indra/sources/indra_db_rest/processor.py
IndraDBRestProcessor._merge_json
def _merge_json(self, stmt_json, ev_counts): """Merge these statement jsons with new jsons.""" # Where there is overlap, there _should_ be agreement. self.__evidence_counts.update(ev_counts) for k, sj in stmt_json.items(): if k not in self.__statement_jsons: self.__statement_jsons[k] = sj # This should be most of them else: # This should only happen rarely. for evj in sj['evidence']: self.__statement_jsons[k]['evidence'].append(evj) if not self.__started: self.statements_sample = stmts_from_json( self.__statement_jsons.values()) self.__started = True return
python
def _merge_json(self, stmt_json, ev_counts): # Where there is overlap, there _should_ be agreement. self.__evidence_counts.update(ev_counts) for k, sj in stmt_json.items(): if k not in self.__statement_jsons: self.__statement_jsons[k] = sj # This should be most of them else: # This should only happen rarely. for evj in sj['evidence']: self.__statement_jsons[k]['evidence'].append(evj) if not self.__started: self.statements_sample = stmts_from_json( self.__statement_jsons.values()) self.__started = True return
[ "def", "_merge_json", "(", "self", ",", "stmt_json", ",", "ev_counts", ")", ":", "# Where there is overlap, there _should_ be agreement.", "self", ".", "__evidence_counts", ".", "update", "(", "ev_counts", ")", "for", "k", ",", "sj", "in", "stmt_json", ".", "items...
Merge these statement jsons with new jsons.
[ "Merge", "these", "statement", "jsons", "with", "new", "jsons", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/indra_db_rest/processor.py#L200-L217
19,315
sorgerlab/indra
indra/sources/indra_db_rest/processor.py
IndraDBRestProcessor._run_queries
def _run_queries(self, agent_strs, stmt_types, params, persist): """Use paging to get all statements requested.""" self._query_over_statement_types(agent_strs, stmt_types, params) assert len(self.__done_dict) == len(stmt_types) \ or None in self.__done_dict.keys(), \ "Done dict was not initiated for all stmt_type's." # Check if we want to keep going. if not persist: self._compile_statements() return # Get the rest of the content. while not self._all_done(): self._query_over_statement_types(agent_strs, stmt_types, params) # Create the actual statements. self._compile_statements() return
python
def _run_queries(self, agent_strs, stmt_types, params, persist): self._query_over_statement_types(agent_strs, stmt_types, params) assert len(self.__done_dict) == len(stmt_types) \ or None in self.__done_dict.keys(), \ "Done dict was not initiated for all stmt_type's." # Check if we want to keep going. if not persist: self._compile_statements() return # Get the rest of the content. while not self._all_done(): self._query_over_statement_types(agent_strs, stmt_types, params) # Create the actual statements. self._compile_statements() return
[ "def", "_run_queries", "(", "self", ",", "agent_strs", ",", "stmt_types", ",", "params", ",", "persist", ")", ":", "self", ".", "_query_over_statement_types", "(", "agent_strs", ",", "stmt_types", ",", "params", ")", "assert", "len", "(", "self", ".", "__don...
Use paging to get all statements requested.
[ "Use", "paging", "to", "get", "all", "statements", "requested", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/indra_db_rest/processor.py#L274-L293
19,316
sorgerlab/indra
indra/literature/pubmed_client.py
get_ids
def get_ids(search_term, **kwargs): """Search Pubmed for paper IDs given a search term. Search options can be passed as keyword arguments, some of which are custom keywords identified by this function, while others are passed on as parameters for the request to the PubMed web service For details on parameters that can be used in PubMed searches, see https://www.ncbi.nlm.nih.gov/books/NBK25499/#chapter4.ESearch Some useful parameters to pass are db='pmc' to search PMC instead of pubmed reldate=2 to search for papers within the last 2 days mindate='2016/03/01', maxdate='2016/03/31' to search for papers in March 2016. PubMed, by default, limits returned PMIDs to a small number, and this number can be controlled by the "retmax" parameter. This function uses a retmax value of 100,000 by default that can be changed via the corresponding keyword argument. Parameters ---------- search_term : str A term for which the PubMed search should be performed. use_text_word : Optional[bool] If True, the "[tw]" string is appended to the search term to constrain the search to "text words", that is words that appear as whole in relevant parts of the PubMed entry (excl. for instance the journal name or publication date) like the title and abstract. Using this option can eliminate spurious search results such as all articles published in June for a search for the "JUN" gene, or journal names that contain Acad for a search for the "ACAD" gene. See also: https://www.nlm.nih.gov/bsd/disted/pubmedtutorial/020_760.html Default : True kwargs : kwargs Additional keyword arguments to pass to the PubMed search as parameters. """ use_text_word = kwargs.pop('use_text_word', True) if use_text_word: search_term += '[tw]' params = {'term': search_term, 'retmax': 100000, 'retstart': 0, 'db': 'pubmed', 'sort': 'pub+date'} params.update(kwargs) tree = send_request(pubmed_search, params) if tree is None: return [] if tree.find('ERROR') is not None: logger.error(tree.find('ERROR').text) return [] if tree.find('ErrorList') is not None: for err in tree.find('ErrorList').getchildren(): logger.error('Error - %s: %s' % (err.tag, err.text)) return [] count = int(tree.find('Count').text) id_terms = tree.findall('IdList/Id') if id_terms is None: return [] ids = [idt.text for idt in id_terms] if count != len(ids): logger.warning('Not all ids were retrieved for search %s;\n' 'limited at %d.' % (search_term, params['retmax'])) return ids
python
def get_ids(search_term, **kwargs): use_text_word = kwargs.pop('use_text_word', True) if use_text_word: search_term += '[tw]' params = {'term': search_term, 'retmax': 100000, 'retstart': 0, 'db': 'pubmed', 'sort': 'pub+date'} params.update(kwargs) tree = send_request(pubmed_search, params) if tree is None: return [] if tree.find('ERROR') is not None: logger.error(tree.find('ERROR').text) return [] if tree.find('ErrorList') is not None: for err in tree.find('ErrorList').getchildren(): logger.error('Error - %s: %s' % (err.tag, err.text)) return [] count = int(tree.find('Count').text) id_terms = tree.findall('IdList/Id') if id_terms is None: return [] ids = [idt.text for idt in id_terms] if count != len(ids): logger.warning('Not all ids were retrieved for search %s;\n' 'limited at %d.' % (search_term, params['retmax'])) return ids
[ "def", "get_ids", "(", "search_term", ",", "*", "*", "kwargs", ")", ":", "use_text_word", "=", "kwargs", ".", "pop", "(", "'use_text_word'", ",", "True", ")", "if", "use_text_word", ":", "search_term", "+=", "'[tw]'", "params", "=", "{", "'term'", ":", "...
Search Pubmed for paper IDs given a search term. Search options can be passed as keyword arguments, some of which are custom keywords identified by this function, while others are passed on as parameters for the request to the PubMed web service For details on parameters that can be used in PubMed searches, see https://www.ncbi.nlm.nih.gov/books/NBK25499/#chapter4.ESearch Some useful parameters to pass are db='pmc' to search PMC instead of pubmed reldate=2 to search for papers within the last 2 days mindate='2016/03/01', maxdate='2016/03/31' to search for papers in March 2016. PubMed, by default, limits returned PMIDs to a small number, and this number can be controlled by the "retmax" parameter. This function uses a retmax value of 100,000 by default that can be changed via the corresponding keyword argument. Parameters ---------- search_term : str A term for which the PubMed search should be performed. use_text_word : Optional[bool] If True, the "[tw]" string is appended to the search term to constrain the search to "text words", that is words that appear as whole in relevant parts of the PubMed entry (excl. for instance the journal name or publication date) like the title and abstract. Using this option can eliminate spurious search results such as all articles published in June for a search for the "JUN" gene, or journal names that contain Acad for a search for the "ACAD" gene. See also: https://www.nlm.nih.gov/bsd/disted/pubmedtutorial/020_760.html Default : True kwargs : kwargs Additional keyword arguments to pass to the PubMed search as parameters.
[ "Search", "Pubmed", "for", "paper", "IDs", "given", "a", "search", "term", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/literature/pubmed_client.py#L41-L103
19,317
sorgerlab/indra
indra/literature/pubmed_client.py
get_id_count
def get_id_count(search_term): """Get the number of citations in Pubmed for a search query. Parameters ---------- search_term : str A term for which the PubMed search should be performed. Returns ------- int or None The number of citations for the query, or None if the query fails. """ params = {'term': search_term, 'rettype': 'count', 'db': 'pubmed'} tree = send_request(pubmed_search, params) if tree is None: return None else: count = tree.getchildren()[0].text return int(count)
python
def get_id_count(search_term): params = {'term': search_term, 'rettype': 'count', 'db': 'pubmed'} tree = send_request(pubmed_search, params) if tree is None: return None else: count = tree.getchildren()[0].text return int(count)
[ "def", "get_id_count", "(", "search_term", ")", ":", "params", "=", "{", "'term'", ":", "search_term", ",", "'rettype'", ":", "'count'", ",", "'db'", ":", "'pubmed'", "}", "tree", "=", "send_request", "(", "pubmed_search", ",", "params", ")", "if", "tree",...
Get the number of citations in Pubmed for a search query. Parameters ---------- search_term : str A term for which the PubMed search should be performed. Returns ------- int or None The number of citations for the query, or None if the query fails.
[ "Get", "the", "number", "of", "citations", "in", "Pubmed", "for", "a", "search", "query", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/literature/pubmed_client.py#L106-L127
19,318
sorgerlab/indra
indra/literature/pubmed_client.py
get_ids_for_gene
def get_ids_for_gene(hgnc_name, **kwargs): """Get the curated set of articles for a gene in the Entrez database. Search parameters for the Gene database query can be passed in as keyword arguments. Parameters ---------- hgnc_name : string The HGNC name of the gene. This is used to obtain the HGNC ID (using the hgnc_client module) and in turn used to obtain the Entrez ID associated with the gene. Entrez is then queried for that ID. """ # Get the HGNC ID for the HGNC name hgnc_id = hgnc_client.get_hgnc_id(hgnc_name) if hgnc_id is None: raise ValueError('Invalid HGNC name.') # Get the Entrez ID entrez_id = hgnc_client.get_entrez_id(hgnc_id) if entrez_id is None: raise ValueError('Entrez ID not found in HGNC table.') # Query the Entrez Gene database params = {'db': 'gene', 'retmode': 'xml', 'id': entrez_id} params.update(kwargs) tree = send_request(pubmed_fetch, params) if tree is None: return [] if tree.find('ERROR') is not None: logger.error(tree.find('ERROR').text) return [] # Get all PMIDs from the XML tree id_terms = tree.findall('.//PubMedId') if id_terms is None: return [] # Use a set to remove duplicate IDs ids = list(set([idt.text for idt in id_terms])) return ids
python
def get_ids_for_gene(hgnc_name, **kwargs): # Get the HGNC ID for the HGNC name hgnc_id = hgnc_client.get_hgnc_id(hgnc_name) if hgnc_id is None: raise ValueError('Invalid HGNC name.') # Get the Entrez ID entrez_id = hgnc_client.get_entrez_id(hgnc_id) if entrez_id is None: raise ValueError('Entrez ID not found in HGNC table.') # Query the Entrez Gene database params = {'db': 'gene', 'retmode': 'xml', 'id': entrez_id} params.update(kwargs) tree = send_request(pubmed_fetch, params) if tree is None: return [] if tree.find('ERROR') is not None: logger.error(tree.find('ERROR').text) return [] # Get all PMIDs from the XML tree id_terms = tree.findall('.//PubMedId') if id_terms is None: return [] # Use a set to remove duplicate IDs ids = list(set([idt.text for idt in id_terms])) return ids
[ "def", "get_ids_for_gene", "(", "hgnc_name", ",", "*", "*", "kwargs", ")", ":", "# Get the HGNC ID for the HGNC name", "hgnc_id", "=", "hgnc_client", ".", "get_hgnc_id", "(", "hgnc_name", ")", "if", "hgnc_id", "is", "None", ":", "raise", "ValueError", "(", "'Inv...
Get the curated set of articles for a gene in the Entrez database. Search parameters for the Gene database query can be passed in as keyword arguments. Parameters ---------- hgnc_name : string The HGNC name of the gene. This is used to obtain the HGNC ID (using the hgnc_client module) and in turn used to obtain the Entrez ID associated with the gene. Entrez is then queried for that ID.
[ "Get", "the", "curated", "set", "of", "articles", "for", "a", "gene", "in", "the", "Entrez", "database", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/literature/pubmed_client.py#L131-L170
19,319
sorgerlab/indra
indra/literature/pubmed_client.py
get_article_xml
def get_article_xml(pubmed_id): """Get the XML metadata for a single article from the Pubmed database. """ if pubmed_id.upper().startswith('PMID'): pubmed_id = pubmed_id[4:] params = {'db': 'pubmed', 'retmode': 'xml', 'id': pubmed_id} tree = send_request(pubmed_fetch, params) if tree is None: return None article = tree.find('PubmedArticle/MedlineCitation/Article') return article
python
def get_article_xml(pubmed_id): if pubmed_id.upper().startswith('PMID'): pubmed_id = pubmed_id[4:] params = {'db': 'pubmed', 'retmode': 'xml', 'id': pubmed_id} tree = send_request(pubmed_fetch, params) if tree is None: return None article = tree.find('PubmedArticle/MedlineCitation/Article') return article
[ "def", "get_article_xml", "(", "pubmed_id", ")", ":", "if", "pubmed_id", ".", "upper", "(", ")", ".", "startswith", "(", "'PMID'", ")", ":", "pubmed_id", "=", "pubmed_id", "[", "4", ":", "]", "params", "=", "{", "'db'", ":", "'pubmed'", ",", "'retmode'...
Get the XML metadata for a single article from the Pubmed database.
[ "Get", "the", "XML", "metadata", "for", "a", "single", "article", "from", "the", "Pubmed", "database", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/literature/pubmed_client.py#L174-L186
19,320
sorgerlab/indra
indra/literature/pubmed_client.py
get_abstract
def get_abstract(pubmed_id, prepend_title=True): """Get the abstract of an article in the Pubmed database.""" article = get_article_xml(pubmed_id) if article is None: return None return _abstract_from_article_element(article, prepend_title)
python
def get_abstract(pubmed_id, prepend_title=True): article = get_article_xml(pubmed_id) if article is None: return None return _abstract_from_article_element(article, prepend_title)
[ "def", "get_abstract", "(", "pubmed_id", ",", "prepend_title", "=", "True", ")", ":", "article", "=", "get_article_xml", "(", "pubmed_id", ")", "if", "article", "is", "None", ":", "return", "None", "return", "_abstract_from_article_element", "(", "article", ",",...
Get the abstract of an article in the Pubmed database.
[ "Get", "the", "abstract", "of", "an", "article", "in", "the", "Pubmed", "database", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/literature/pubmed_client.py#L224-L229
19,321
sorgerlab/indra
indra/literature/pubmed_client.py
get_metadata_from_xml_tree
def get_metadata_from_xml_tree(tree, get_issns_from_nlm=False, get_abstracts=False, prepend_title=False, mesh_annotations=False): """Get metadata for an XML tree containing PubmedArticle elements. Documentation on the XML structure can be found at: - https://www.nlm.nih.gov/bsd/licensee/elements_descriptions.html - https://www.nlm.nih.gov/bsd/licensee/elements_alphabetical.html Parameters ---------- tree : xml.etree.ElementTree ElementTree containing one or more PubmedArticle elements. get_issns_from_nlm : boolean Look up the full list of ISSN number for the journal associated with the article, which helps to match articles to CrossRef search results. Defaults to False, since it slows down performance. get_abstracts : boolean Indicates whether to include the Pubmed abstract in the results. prepend_title : boolean If get_abstracts is True, specifies whether the article title should be prepended to the abstract text. mesh_annotations : boolean If True, extract mesh annotations from the pubmed entries and include in the returned data. If false, don't. Returns ------- dict of dicts Dictionary indexed by PMID. Each value is a dict containing the following fields: 'doi', 'title', 'authors', 'journal_title', 'journal_abbrev', 'journal_nlm_id', 'issn_list', 'page'. """ # Iterate over the articles and build the results dict results = {} pm_articles = tree.findall('./PubmedArticle') for art_ix, pm_article in enumerate(pm_articles): medline_citation = pm_article.find('./MedlineCitation') article_info = _get_article_info(medline_citation, pm_article.find('PubmedData')) journal_info = _get_journal_info(medline_citation, get_issns_from_nlm) context_info = _get_annotations(medline_citation) # Build the result result = {} result.update(article_info) result.update(journal_info) result.update(context_info) # Get the abstracts if requested if get_abstracts: abstract = _abstract_from_article_element( medline_citation.find('Article'), prepend_title=prepend_title ) result['abstract'] = abstract # Add to dict results[article_info['pmid']] = result return results
python
def get_metadata_from_xml_tree(tree, get_issns_from_nlm=False, get_abstracts=False, prepend_title=False, mesh_annotations=False): # Iterate over the articles and build the results dict results = {} pm_articles = tree.findall('./PubmedArticle') for art_ix, pm_article in enumerate(pm_articles): medline_citation = pm_article.find('./MedlineCitation') article_info = _get_article_info(medline_citation, pm_article.find('PubmedData')) journal_info = _get_journal_info(medline_citation, get_issns_from_nlm) context_info = _get_annotations(medline_citation) # Build the result result = {} result.update(article_info) result.update(journal_info) result.update(context_info) # Get the abstracts if requested if get_abstracts: abstract = _abstract_from_article_element( medline_citation.find('Article'), prepend_title=prepend_title ) result['abstract'] = abstract # Add to dict results[article_info['pmid']] = result return results
[ "def", "get_metadata_from_xml_tree", "(", "tree", ",", "get_issns_from_nlm", "=", "False", ",", "get_abstracts", "=", "False", ",", "prepend_title", "=", "False", ",", "mesh_annotations", "=", "False", ")", ":", "# Iterate over the articles and build the results dict", ...
Get metadata for an XML tree containing PubmedArticle elements. Documentation on the XML structure can be found at: - https://www.nlm.nih.gov/bsd/licensee/elements_descriptions.html - https://www.nlm.nih.gov/bsd/licensee/elements_alphabetical.html Parameters ---------- tree : xml.etree.ElementTree ElementTree containing one or more PubmedArticle elements. get_issns_from_nlm : boolean Look up the full list of ISSN number for the journal associated with the article, which helps to match articles to CrossRef search results. Defaults to False, since it slows down performance. get_abstracts : boolean Indicates whether to include the Pubmed abstract in the results. prepend_title : boolean If get_abstracts is True, specifies whether the article title should be prepended to the abstract text. mesh_annotations : boolean If True, extract mesh annotations from the pubmed entries and include in the returned data. If false, don't. Returns ------- dict of dicts Dictionary indexed by PMID. Each value is a dict containing the following fields: 'doi', 'title', 'authors', 'journal_title', 'journal_abbrev', 'journal_nlm_id', 'issn_list', 'page'.
[ "Get", "metadata", "for", "an", "XML", "tree", "containing", "PubmedArticle", "elements", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/literature/pubmed_client.py#L303-L364
19,322
sorgerlab/indra
indra/literature/pubmed_client.py
get_metadata_for_ids
def get_metadata_for_ids(pmid_list, get_issns_from_nlm=False, get_abstracts=False, prepend_title=False): """Get article metadata for up to 200 PMIDs from the Pubmed database. Parameters ---------- pmid_list : list of PMIDs as strings Can contain 1-200 PMIDs. get_issns_from_nlm : boolean Look up the full list of ISSN number for the journal associated with the article, which helps to match articles to CrossRef search results. Defaults to False, since it slows down performance. get_abstracts : boolean Indicates whether to include the Pubmed abstract in the results. prepend_title : boolean If get_abstracts is True, specifies whether the article title should be prepended to the abstract text. Returns ------- dict of dicts Dictionary indexed by PMID. Each value is a dict containing the following fields: 'doi', 'title', 'authors', 'journal_title', 'journal_abbrev', 'journal_nlm_id', 'issn_list', 'page'. """ if len(pmid_list) > 200: raise ValueError("Metadata query is limited to 200 PMIDs at a time.") params = {'db': 'pubmed', 'retmode': 'xml', 'id': pmid_list} tree = send_request(pubmed_fetch, params) if tree is None: return None return get_metadata_from_xml_tree(tree, get_issns_from_nlm, get_abstracts, prepend_title)
python
def get_metadata_for_ids(pmid_list, get_issns_from_nlm=False, get_abstracts=False, prepend_title=False): if len(pmid_list) > 200: raise ValueError("Metadata query is limited to 200 PMIDs at a time.") params = {'db': 'pubmed', 'retmode': 'xml', 'id': pmid_list} tree = send_request(pubmed_fetch, params) if tree is None: return None return get_metadata_from_xml_tree(tree, get_issns_from_nlm, get_abstracts, prepend_title)
[ "def", "get_metadata_for_ids", "(", "pmid_list", ",", "get_issns_from_nlm", "=", "False", ",", "get_abstracts", "=", "False", ",", "prepend_title", "=", "False", ")", ":", "if", "len", "(", "pmid_list", ")", ">", "200", ":", "raise", "ValueError", "(", "\"Me...
Get article metadata for up to 200 PMIDs from the Pubmed database. Parameters ---------- pmid_list : list of PMIDs as strings Can contain 1-200 PMIDs. get_issns_from_nlm : boolean Look up the full list of ISSN number for the journal associated with the article, which helps to match articles to CrossRef search results. Defaults to False, since it slows down performance. get_abstracts : boolean Indicates whether to include the Pubmed abstract in the results. prepend_title : boolean If get_abstracts is True, specifies whether the article title should be prepended to the abstract text. Returns ------- dict of dicts Dictionary indexed by PMID. Each value is a dict containing the following fields: 'doi', 'title', 'authors', 'journal_title', 'journal_abbrev', 'journal_nlm_id', 'issn_list', 'page'.
[ "Get", "article", "metadata", "for", "up", "to", "200", "PMIDs", "from", "the", "Pubmed", "database", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/literature/pubmed_client.py#L391-L425
19,323
sorgerlab/indra
indra/literature/pubmed_client.py
get_issns_for_journal
def get_issns_for_journal(nlm_id): """Get a list of the ISSN numbers for a journal given its NLM ID. Information on NLM XML DTDs is available at https://www.nlm.nih.gov/databases/dtd/ """ params = {'db': 'nlmcatalog', 'retmode': 'xml', 'id': nlm_id} tree = send_request(pubmed_fetch, params) if tree is None: return None issn_list = tree.findall('.//ISSN') issn_linking = tree.findall('.//ISSNLinking') issns = issn_list + issn_linking # No ISSNs found! if not issns: return None else: return [issn.text for issn in issns]
python
def get_issns_for_journal(nlm_id): params = {'db': 'nlmcatalog', 'retmode': 'xml', 'id': nlm_id} tree = send_request(pubmed_fetch, params) if tree is None: return None issn_list = tree.findall('.//ISSN') issn_linking = tree.findall('.//ISSNLinking') issns = issn_list + issn_linking # No ISSNs found! if not issns: return None else: return [issn.text for issn in issns]
[ "def", "get_issns_for_journal", "(", "nlm_id", ")", ":", "params", "=", "{", "'db'", ":", "'nlmcatalog'", ",", "'retmode'", ":", "'xml'", ",", "'id'", ":", "nlm_id", "}", "tree", "=", "send_request", "(", "pubmed_fetch", ",", "params", ")", "if", "tree", ...
Get a list of the ISSN numbers for a journal given its NLM ID. Information on NLM XML DTDs is available at https://www.nlm.nih.gov/databases/dtd/
[ "Get", "a", "list", "of", "the", "ISSN", "numbers", "for", "a", "journal", "given", "its", "NLM", "ID", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/literature/pubmed_client.py#L429-L448
19,324
sorgerlab/indra
indra/explanation/model_checker.py
remove_im_params
def remove_im_params(model, im): """Remove parameter nodes from the influence map. Parameters ---------- model : pysb.core.Model PySB model. im : networkx.MultiDiGraph Influence map. Returns ------- networkx.MultiDiGraph Influence map with the parameter nodes removed. """ for param in model.parameters: # If the node doesn't exist e.g., it may have already been removed), # skip over the parameter without error try: im.remove_node(param.name) except: pass
python
def remove_im_params(model, im): for param in model.parameters: # If the node doesn't exist e.g., it may have already been removed), # skip over the parameter without error try: im.remove_node(param.name) except: pass
[ "def", "remove_im_params", "(", "model", ",", "im", ")", ":", "for", "param", "in", "model", ".", "parameters", ":", "# If the node doesn't exist e.g., it may have already been removed),", "# skip over the parameter without error", "try", ":", "im", ".", "remove_node", "(...
Remove parameter nodes from the influence map. Parameters ---------- model : pysb.core.Model PySB model. im : networkx.MultiDiGraph Influence map. Returns ------- networkx.MultiDiGraph Influence map with the parameter nodes removed.
[ "Remove", "parameter", "nodes", "from", "the", "influence", "map", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/explanation/model_checker.py#L919-L940
19,325
sorgerlab/indra
indra/explanation/model_checker.py
_get_signed_predecessors
def _get_signed_predecessors(im, node, polarity): """Get upstream nodes in the influence map. Return the upstream nodes along with the overall polarity of the path to that node by account for the polarity of the path to the given node and the polarity of the edge between the given node and its immediate predecessors. Parameters ---------- im : networkx.MultiDiGraph Graph containing the influence map. node : str The node (rule name) in the influence map to get predecessors (upstream nodes) for. polarity : int Polarity of the overall path to the given node. Returns ------- generator of tuples, (node, polarity) Each tuple returned contains two elements, a node (string) and the polarity of the overall path (int) to that node. """ signed_pred_list = [] for pred in im.predecessors(node): pred_edge = (pred, node) yield (pred, _get_edge_sign(im, pred_edge) * polarity)
python
def _get_signed_predecessors(im, node, polarity): signed_pred_list = [] for pred in im.predecessors(node): pred_edge = (pred, node) yield (pred, _get_edge_sign(im, pred_edge) * polarity)
[ "def", "_get_signed_predecessors", "(", "im", ",", "node", ",", "polarity", ")", ":", "signed_pred_list", "=", "[", "]", "for", "pred", "in", "im", ".", "predecessors", "(", "node", ")", ":", "pred_edge", "=", "(", "pred", ",", "node", ")", "yield", "(...
Get upstream nodes in the influence map. Return the upstream nodes along with the overall polarity of the path to that node by account for the polarity of the path to the given node and the polarity of the edge between the given node and its immediate predecessors. Parameters ---------- im : networkx.MultiDiGraph Graph containing the influence map. node : str The node (rule name) in the influence map to get predecessors (upstream nodes) for. polarity : int Polarity of the overall path to the given node. Returns ------- generator of tuples, (node, polarity) Each tuple returned contains two elements, a node (string) and the polarity of the overall path (int) to that node.
[ "Get", "upstream", "nodes", "in", "the", "influence", "map", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/explanation/model_checker.py#L1009-L1037
19,326
sorgerlab/indra
indra/explanation/model_checker.py
_get_edge_sign
def _get_edge_sign(im, edge): """Get the polarity of the influence by examining the edge sign.""" edge_data = im[edge[0]][edge[1]] # Handle possible multiple edges between nodes signs = list(set([v['sign'] for v in edge_data.values() if v.get('sign')])) if len(signs) > 1: logger.warning("Edge %s has conflicting polarities; choosing " "positive polarity by default" % str(edge)) sign = 1 else: sign = signs[0] if sign is None: raise Exception('No sign attribute for edge.') elif abs(sign) == 1: return sign else: raise Exception('Unexpected edge sign: %s' % edge.attr['sign'])
python
def _get_edge_sign(im, edge): edge_data = im[edge[0]][edge[1]] # Handle possible multiple edges between nodes signs = list(set([v['sign'] for v in edge_data.values() if v.get('sign')])) if len(signs) > 1: logger.warning("Edge %s has conflicting polarities; choosing " "positive polarity by default" % str(edge)) sign = 1 else: sign = signs[0] if sign is None: raise Exception('No sign attribute for edge.') elif abs(sign) == 1: return sign else: raise Exception('Unexpected edge sign: %s' % edge.attr['sign'])
[ "def", "_get_edge_sign", "(", "im", ",", "edge", ")", ":", "edge_data", "=", "im", "[", "edge", "[", "0", "]", "]", "[", "edge", "[", "1", "]", "]", "# Handle possible multiple edges between nodes", "signs", "=", "list", "(", "set", "(", "[", "v", "[",...
Get the polarity of the influence by examining the edge sign.
[ "Get", "the", "polarity", "of", "the", "influence", "by", "examining", "the", "edge", "sign", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/explanation/model_checker.py#L1040-L1057
19,327
sorgerlab/indra
indra/explanation/model_checker.py
_add_modification_to_agent
def _add_modification_to_agent(agent, mod_type, residue, position): """Add a modification condition to an Agent.""" new_mod = ModCondition(mod_type, residue, position) # Check if this modification already exists for old_mod in agent.mods: if old_mod.equals(new_mod): return agent new_agent = deepcopy(agent) new_agent.mods.append(new_mod) return new_agent
python
def _add_modification_to_agent(agent, mod_type, residue, position): new_mod = ModCondition(mod_type, residue, position) # Check if this modification already exists for old_mod in agent.mods: if old_mod.equals(new_mod): return agent new_agent = deepcopy(agent) new_agent.mods.append(new_mod) return new_agent
[ "def", "_add_modification_to_agent", "(", "agent", ",", "mod_type", ",", "residue", ",", "position", ")", ":", "new_mod", "=", "ModCondition", "(", "mod_type", ",", "residue", ",", "position", ")", "# Check if this modification already exists", "for", "old_mod", "in...
Add a modification condition to an Agent.
[ "Add", "a", "modification", "condition", "to", "an", "Agent", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/explanation/model_checker.py#L1060-L1069
19,328
sorgerlab/indra
indra/explanation/model_checker.py
_match_lhs
def _match_lhs(cp, rules): """Get rules with a left-hand side matching the given ComplexPattern.""" rule_matches = [] for rule in rules: reactant_pattern = rule.rule_expression.reactant_pattern for rule_cp in reactant_pattern.complex_patterns: if _cp_embeds_into(rule_cp, cp): rule_matches.append(rule) break return rule_matches
python
def _match_lhs(cp, rules): rule_matches = [] for rule in rules: reactant_pattern = rule.rule_expression.reactant_pattern for rule_cp in reactant_pattern.complex_patterns: if _cp_embeds_into(rule_cp, cp): rule_matches.append(rule) break return rule_matches
[ "def", "_match_lhs", "(", "cp", ",", "rules", ")", ":", "rule_matches", "=", "[", "]", "for", "rule", "in", "rules", ":", "reactant_pattern", "=", "rule", ".", "rule_expression", ".", "reactant_pattern", "for", "rule_cp", "in", "reactant_pattern", ".", "comp...
Get rules with a left-hand side matching the given ComplexPattern.
[ "Get", "rules", "with", "a", "left", "-", "hand", "side", "matching", "the", "given", "ComplexPattern", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/explanation/model_checker.py#L1084-L1093
19,329
sorgerlab/indra
indra/explanation/model_checker.py
_cp_embeds_into
def _cp_embeds_into(cp1, cp2): """Check that any state in ComplexPattern2 is matched in ComplexPattern1. """ # Check that any state in cp2 is matched in cp1 # If the thing we're matching to is just a monomer pattern, that makes # things easier--we just need to find the corresponding monomer pattern # in cp1 if cp1 is None or cp2 is None: return False cp1 = as_complex_pattern(cp1) cp2 = as_complex_pattern(cp2) if len(cp2.monomer_patterns) == 1: mp2 = cp2.monomer_patterns[0] # Iterate over the monomer patterns in cp1 and see if there is one # that has the same name for mp1 in cp1.monomer_patterns: if _mp_embeds_into(mp1, mp2): return True return False
python
def _cp_embeds_into(cp1, cp2): # Check that any state in cp2 is matched in cp1 # If the thing we're matching to is just a monomer pattern, that makes # things easier--we just need to find the corresponding monomer pattern # in cp1 if cp1 is None or cp2 is None: return False cp1 = as_complex_pattern(cp1) cp2 = as_complex_pattern(cp2) if len(cp2.monomer_patterns) == 1: mp2 = cp2.monomer_patterns[0] # Iterate over the monomer patterns in cp1 and see if there is one # that has the same name for mp1 in cp1.monomer_patterns: if _mp_embeds_into(mp1, mp2): return True return False
[ "def", "_cp_embeds_into", "(", "cp1", ",", "cp2", ")", ":", "# Check that any state in cp2 is matched in cp1", "# If the thing we're matching to is just a monomer pattern, that makes", "# things easier--we just need to find the corresponding monomer pattern", "# in cp1", "if", "cp1", "is...
Check that any state in ComplexPattern2 is matched in ComplexPattern1.
[ "Check", "that", "any", "state", "in", "ComplexPattern2", "is", "matched", "in", "ComplexPattern1", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/explanation/model_checker.py#L1096-L1114
19,330
sorgerlab/indra
indra/explanation/model_checker.py
_mp_embeds_into
def _mp_embeds_into(mp1, mp2): """Check that conditions in MonomerPattern2 are met in MonomerPattern1.""" sc_matches = [] if mp1.monomer.name != mp2.monomer.name: return False # Check that all conditions in mp2 are met in mp1 for site_name, site_state in mp2.site_conditions.items(): if site_name not in mp1.site_conditions or \ site_state != mp1.site_conditions[site_name]: return False return True
python
def _mp_embeds_into(mp1, mp2): sc_matches = [] if mp1.monomer.name != mp2.monomer.name: return False # Check that all conditions in mp2 are met in mp1 for site_name, site_state in mp2.site_conditions.items(): if site_name not in mp1.site_conditions or \ site_state != mp1.site_conditions[site_name]: return False return True
[ "def", "_mp_embeds_into", "(", "mp1", ",", "mp2", ")", ":", "sc_matches", "=", "[", "]", "if", "mp1", ".", "monomer", ".", "name", "!=", "mp2", ".", "monomer", ".", "name", ":", "return", "False", "# Check that all conditions in mp2 are met in mp1", "for", "...
Check that conditions in MonomerPattern2 are met in MonomerPattern1.
[ "Check", "that", "conditions", "in", "MonomerPattern2", "are", "met", "in", "MonomerPattern1", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/explanation/model_checker.py#L1117-L1127
19,331
sorgerlab/indra
indra/explanation/model_checker.py
_monomer_pattern_label
def _monomer_pattern_label(mp): """Return a string label for a MonomerPattern.""" site_strs = [] for site, cond in mp.site_conditions.items(): if isinstance(cond, tuple) or isinstance(cond, list): assert len(cond) == 2 if cond[1] == WILD: site_str = '%s_%s' % (site, cond[0]) else: site_str = '%s_%s%s' % (site, cond[0], cond[1]) elif isinstance(cond, numbers.Real): continue else: site_str = '%s_%s' % (site, cond) site_strs.append(site_str) return '%s_%s' % (mp.monomer.name, '_'.join(site_strs))
python
def _monomer_pattern_label(mp): site_strs = [] for site, cond in mp.site_conditions.items(): if isinstance(cond, tuple) or isinstance(cond, list): assert len(cond) == 2 if cond[1] == WILD: site_str = '%s_%s' % (site, cond[0]) else: site_str = '%s_%s%s' % (site, cond[0], cond[1]) elif isinstance(cond, numbers.Real): continue else: site_str = '%s_%s' % (site, cond) site_strs.append(site_str) return '%s_%s' % (mp.monomer.name, '_'.join(site_strs))
[ "def", "_monomer_pattern_label", "(", "mp", ")", ":", "site_strs", "=", "[", "]", "for", "site", ",", "cond", "in", "mp", ".", "site_conditions", ".", "items", "(", ")", ":", "if", "isinstance", "(", "cond", ",", "tuple", ")", "or", "isinstance", "(", ...
Return a string label for a MonomerPattern.
[ "Return", "a", "string", "label", "for", "a", "MonomerPattern", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/explanation/model_checker.py#L1224-L1239
19,332
sorgerlab/indra
indra/explanation/model_checker.py
_stmt_from_rule
def _stmt_from_rule(model, rule_name, stmts): """Return the INDRA Statement corresponding to a given rule by name.""" stmt_uuid = None for ann in model.annotations: if ann.predicate == 'from_indra_statement': if ann.subject == rule_name: stmt_uuid = ann.object break if stmt_uuid: for stmt in stmts: if stmt.uuid == stmt_uuid: return stmt
python
def _stmt_from_rule(model, rule_name, stmts): stmt_uuid = None for ann in model.annotations: if ann.predicate == 'from_indra_statement': if ann.subject == rule_name: stmt_uuid = ann.object break if stmt_uuid: for stmt in stmts: if stmt.uuid == stmt_uuid: return stmt
[ "def", "_stmt_from_rule", "(", "model", ",", "rule_name", ",", "stmts", ")", ":", "stmt_uuid", "=", "None", "for", "ann", "in", "model", ".", "annotations", ":", "if", "ann", ".", "predicate", "==", "'from_indra_statement'", ":", "if", "ann", ".", "subject...
Return the INDRA Statement corresponding to a given rule by name.
[ "Return", "the", "INDRA", "Statement", "corresponding", "to", "a", "given", "rule", "by", "name", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/explanation/model_checker.py#L1263-L1274
19,333
sorgerlab/indra
indra/explanation/model_checker.py
ModelChecker.generate_im
def generate_im(self, model): """Return a graph representing the influence map generated by Kappa Parameters ---------- model : pysb.Model The PySB model whose influence map is to be generated Returns ------- graph : networkx.MultiDiGraph A MultiDiGraph representing the influence map """ kappa = kappy.KappaStd() model_str = export.export(model, 'kappa') kappa.add_model_string(model_str) kappa.project_parse() imap = kappa.analyses_influence_map(accuracy='medium') graph = im_json_to_graph(imap) return graph
python
def generate_im(self, model): kappa = kappy.KappaStd() model_str = export.export(model, 'kappa') kappa.add_model_string(model_str) kappa.project_parse() imap = kappa.analyses_influence_map(accuracy='medium') graph = im_json_to_graph(imap) return graph
[ "def", "generate_im", "(", "self", ",", "model", ")", ":", "kappa", "=", "kappy", ".", "KappaStd", "(", ")", "model_str", "=", "export", ".", "export", "(", "model", ",", "'kappa'", ")", "kappa", ".", "add_model_string", "(", "model_str", ")", "kappa", ...
Return a graph representing the influence map generated by Kappa Parameters ---------- model : pysb.Model The PySB model whose influence map is to be generated Returns ------- graph : networkx.MultiDiGraph A MultiDiGraph representing the influence map
[ "Return", "a", "graph", "representing", "the", "influence", "map", "generated", "by", "Kappa" ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/explanation/model_checker.py#L196-L215
19,334
sorgerlab/indra
indra/explanation/model_checker.py
ModelChecker.draw_im
def draw_im(self, fname): """Draw and save the influence map in a file. Parameters ---------- fname : str The name of the file to save the influence map in. The extension of the file will determine the file format, typically png or pdf. """ im = self.get_im() im_agraph = nx.nx_agraph.to_agraph(im) im_agraph.draw(fname, prog='dot')
python
def draw_im(self, fname): im = self.get_im() im_agraph = nx.nx_agraph.to_agraph(im) im_agraph.draw(fname, prog='dot')
[ "def", "draw_im", "(", "self", ",", "fname", ")", ":", "im", "=", "self", ".", "get_im", "(", ")", "im_agraph", "=", "nx", ".", "nx_agraph", ".", "to_agraph", "(", "im", ")", "im_agraph", ".", "draw", "(", "fname", ",", "prog", "=", "'dot'", ")" ]
Draw and save the influence map in a file. Parameters ---------- fname : str The name of the file to save the influence map in. The extension of the file will determine the file format, typically png or pdf.
[ "Draw", "and", "save", "the", "influence", "map", "in", "a", "file", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/explanation/model_checker.py#L217-L229
19,335
sorgerlab/indra
indra/explanation/model_checker.py
ModelChecker.get_im
def get_im(self, force_update=False): """Get the influence map for the model, generating it if necessary. Parameters ---------- force_update : bool Whether to generate the influence map when the function is called. If False, returns the previously generated influence map if available. Defaults to True. Returns ------- networkx MultiDiGraph object containing the influence map. The influence map can be rendered as a pdf using the dot layout program as follows:: im_agraph = nx.nx_agraph.to_agraph(influence_map) im_agraph.draw('influence_map.pdf', prog='dot') """ if self._im and not force_update: return self._im if not self.model: raise Exception("Cannot get influence map if there is no model.") def add_obs_for_agent(agent): obj_mps = list(pa.grounded_monomer_patterns(self.model, agent)) if not obj_mps: logger.debug('No monomer patterns found in model for agent %s, ' 'skipping' % agent) return obs_list = [] for obj_mp in obj_mps: obs_name = _monomer_pattern_label(obj_mp) + '_obs' # Add the observable obj_obs = Observable(obs_name, obj_mp, _export=False) obs_list.append(obs_name) try: self.model.add_component(obj_obs) except ComponentDuplicateNameError as e: pass return obs_list # Create observables for all statements to check, and add to model # Remove any existing observables in the model self.model.observables = ComponentSet([]) for stmt in self.statements: # Generate observables for Modification statements if isinstance(stmt, Modification): mod_condition_name = modclass_to_modtype[stmt.__class__] if isinstance(stmt, RemoveModification): mod_condition_name = modtype_to_inverse[mod_condition_name] # Add modification to substrate agent modified_sub = _add_modification_to_agent(stmt.sub, mod_condition_name, stmt.residue, stmt.position) obs_list = add_obs_for_agent(modified_sub) # Associate this statement with this observable self.stmt_to_obs[stmt] = obs_list # Generate observables for Activation/Inhibition statements elif isinstance(stmt, RegulateActivity): regulated_obj, polarity = \ _add_activity_to_agent(stmt.obj, stmt.obj_activity, stmt.is_activation) obs_list = add_obs_for_agent(regulated_obj) # Associate this statement with this observable self.stmt_to_obs[stmt] = obs_list elif isinstance(stmt, RegulateAmount): obs_list = add_obs_for_agent(stmt.obj) self.stmt_to_obs[stmt] = obs_list elif isinstance(stmt, Influence): obs_list = add_obs_for_agent(stmt.obj.concept) self.stmt_to_obs[stmt] = obs_list # Add observables for each agent for ag in self.agent_obs: obs_list = add_obs_for_agent(ag) self.agent_to_obs[ag] = obs_list logger.info("Generating influence map") self._im = self.generate_im(self.model) #self._im.is_multigraph = lambda: False # Now, for every rule in the model, check if there are any observables # downstream; alternatively, for every observable in the model, get a # list of rules. # We'll need the dictionary to check if nodes are observables node_attributes = nx.get_node_attributes(self._im, 'node_type') for rule in self.model.rules: obs_list = [] # Get successors of the rule node for neighb in self._im.neighbors(rule.name): # Check if the node is an observable if node_attributes[neighb] != 'variable': continue # Get the edge and check the polarity edge_sign = _get_edge_sign(self._im, (rule.name, neighb)) obs_list.append((neighb, edge_sign)) self.rule_obs_dict[rule.name] = obs_list return self._im
python
def get_im(self, force_update=False): if self._im and not force_update: return self._im if not self.model: raise Exception("Cannot get influence map if there is no model.") def add_obs_for_agent(agent): obj_mps = list(pa.grounded_monomer_patterns(self.model, agent)) if not obj_mps: logger.debug('No monomer patterns found in model for agent %s, ' 'skipping' % agent) return obs_list = [] for obj_mp in obj_mps: obs_name = _monomer_pattern_label(obj_mp) + '_obs' # Add the observable obj_obs = Observable(obs_name, obj_mp, _export=False) obs_list.append(obs_name) try: self.model.add_component(obj_obs) except ComponentDuplicateNameError as e: pass return obs_list # Create observables for all statements to check, and add to model # Remove any existing observables in the model self.model.observables = ComponentSet([]) for stmt in self.statements: # Generate observables for Modification statements if isinstance(stmt, Modification): mod_condition_name = modclass_to_modtype[stmt.__class__] if isinstance(stmt, RemoveModification): mod_condition_name = modtype_to_inverse[mod_condition_name] # Add modification to substrate agent modified_sub = _add_modification_to_agent(stmt.sub, mod_condition_name, stmt.residue, stmt.position) obs_list = add_obs_for_agent(modified_sub) # Associate this statement with this observable self.stmt_to_obs[stmt] = obs_list # Generate observables for Activation/Inhibition statements elif isinstance(stmt, RegulateActivity): regulated_obj, polarity = \ _add_activity_to_agent(stmt.obj, stmt.obj_activity, stmt.is_activation) obs_list = add_obs_for_agent(regulated_obj) # Associate this statement with this observable self.stmt_to_obs[stmt] = obs_list elif isinstance(stmt, RegulateAmount): obs_list = add_obs_for_agent(stmt.obj) self.stmt_to_obs[stmt] = obs_list elif isinstance(stmt, Influence): obs_list = add_obs_for_agent(stmt.obj.concept) self.stmt_to_obs[stmt] = obs_list # Add observables for each agent for ag in self.agent_obs: obs_list = add_obs_for_agent(ag) self.agent_to_obs[ag] = obs_list logger.info("Generating influence map") self._im = self.generate_im(self.model) #self._im.is_multigraph = lambda: False # Now, for every rule in the model, check if there are any observables # downstream; alternatively, for every observable in the model, get a # list of rules. # We'll need the dictionary to check if nodes are observables node_attributes = nx.get_node_attributes(self._im, 'node_type') for rule in self.model.rules: obs_list = [] # Get successors of the rule node for neighb in self._im.neighbors(rule.name): # Check if the node is an observable if node_attributes[neighb] != 'variable': continue # Get the edge and check the polarity edge_sign = _get_edge_sign(self._im, (rule.name, neighb)) obs_list.append((neighb, edge_sign)) self.rule_obs_dict[rule.name] = obs_list return self._im
[ "def", "get_im", "(", "self", ",", "force_update", "=", "False", ")", ":", "if", "self", ".", "_im", "and", "not", "force_update", ":", "return", "self", ".", "_im", "if", "not", "self", ".", "model", ":", "raise", "Exception", "(", "\"Cannot get influen...
Get the influence map for the model, generating it if necessary. Parameters ---------- force_update : bool Whether to generate the influence map when the function is called. If False, returns the previously generated influence map if available. Defaults to True. Returns ------- networkx MultiDiGraph object containing the influence map. The influence map can be rendered as a pdf using the dot layout program as follows:: im_agraph = nx.nx_agraph.to_agraph(influence_map) im_agraph.draw('influence_map.pdf', prog='dot')
[ "Get", "the", "influence", "map", "for", "the", "model", "generating", "it", "if", "necessary", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/explanation/model_checker.py#L231-L327
19,336
sorgerlab/indra
indra/explanation/model_checker.py
ModelChecker.check_model
def check_model(self, max_paths=1, max_path_length=5): """Check all the statements added to the ModelChecker. Parameters ---------- max_paths : Optional[int] The maximum number of specific paths to return for each Statement to be explained. Default: 1 max_path_length : Optional[int] The maximum length of specific paths to return. Default: 5 Returns ------- list of (Statement, PathResult) Each tuple contains the Statement checked against the model and a PathResult object describing the results of model checking. """ results = [] for stmt in self.statements: result = self.check_statement(stmt, max_paths, max_path_length) results.append((stmt, result)) return results
python
def check_model(self, max_paths=1, max_path_length=5): results = [] for stmt in self.statements: result = self.check_statement(stmt, max_paths, max_path_length) results.append((stmt, result)) return results
[ "def", "check_model", "(", "self", ",", "max_paths", "=", "1", ",", "max_path_length", "=", "5", ")", ":", "results", "=", "[", "]", "for", "stmt", "in", "self", ".", "statements", ":", "result", "=", "self", ".", "check_statement", "(", "stmt", ",", ...
Check all the statements added to the ModelChecker. Parameters ---------- max_paths : Optional[int] The maximum number of specific paths to return for each Statement to be explained. Default: 1 max_path_length : Optional[int] The maximum length of specific paths to return. Default: 5 Returns ------- list of (Statement, PathResult) Each tuple contains the Statement checked against the model and a PathResult object describing the results of model checking.
[ "Check", "all", "the", "statements", "added", "to", "the", "ModelChecker", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/explanation/model_checker.py#L329-L350
19,337
sorgerlab/indra
indra/explanation/model_checker.py
ModelChecker.check_statement
def check_statement(self, stmt, max_paths=1, max_path_length=5): """Check a single Statement against the model. Parameters ---------- stmt : indra.statements.Statement The Statement to check. max_paths : Optional[int] The maximum number of specific paths to return for each Statement to be explained. Default: 1 max_path_length : Optional[int] The maximum length of specific paths to return. Default: 5 Returns ------- boolean True if the model satisfies the Statement. """ # Make sure the influence map is initialized self.get_im() # Check if this is one of the statement types that we can check if not isinstance(stmt, (Modification, RegulateAmount, RegulateActivity, Influence)): return PathResult(False, 'STATEMENT_TYPE_NOT_HANDLED', max_paths, max_path_length) # Get the polarity for the statement if isinstance(stmt, Modification): target_polarity = -1 if isinstance(stmt, RemoveModification) else 1 elif isinstance(stmt, RegulateActivity): target_polarity = 1 if stmt.is_activation else -1 elif isinstance(stmt, RegulateAmount): target_polarity = -1 if isinstance(stmt, DecreaseAmount) else 1 elif isinstance(stmt, Influence): target_polarity = -1 if stmt.overall_polarity() == -1 else 1 # Get the subject and object (works also for Modifications) subj, obj = stmt.agent_list() # Get a list of monomer patterns matching the subject FIXME Currently # this will match rules with the corresponding monomer pattern on it. # In future, this statement should (possibly) also match rules in which # 1) the agent is in its active form, or 2) the agent is tagged as the # enzyme in a rule of the appropriate activity (e.g., a phosphorylation # rule) FIXME if subj is not None: subj_mps = list(pa.grounded_monomer_patterns(self.model, subj, ignore_activities=True)) if not subj_mps: logger.debug('No monomers found corresponding to agent %s' % subj) return PathResult(False, 'SUBJECT_MONOMERS_NOT_FOUND', max_paths, max_path_length) else: subj_mps = [None] # Observables may not be found for an activation since there may be no # rule in the model activating the object, and the object may not have # an "active" site of the appropriate type obs_names = self.stmt_to_obs[stmt] if not obs_names: logger.debug("No observables for stmt %s, returning False" % stmt) return PathResult(False, 'OBSERVABLES_NOT_FOUND', max_paths, max_path_length) for subj_mp, obs_name in itertools.product(subj_mps, obs_names): # NOTE: Returns on the path found for the first enz_mp/obs combo result = self._find_im_paths(subj_mp, obs_name, target_polarity, max_paths, max_path_length) # If a path was found, then we return it; otherwise, that means # there was no path for this observable, so we have to try the next # one if result.path_found: return result # If we got here, then there was no path for any observable return PathResult(False, 'NO_PATHS_FOUND', max_paths, max_path_length)
python
def check_statement(self, stmt, max_paths=1, max_path_length=5): # Make sure the influence map is initialized self.get_im() # Check if this is one of the statement types that we can check if not isinstance(stmt, (Modification, RegulateAmount, RegulateActivity, Influence)): return PathResult(False, 'STATEMENT_TYPE_NOT_HANDLED', max_paths, max_path_length) # Get the polarity for the statement if isinstance(stmt, Modification): target_polarity = -1 if isinstance(stmt, RemoveModification) else 1 elif isinstance(stmt, RegulateActivity): target_polarity = 1 if stmt.is_activation else -1 elif isinstance(stmt, RegulateAmount): target_polarity = -1 if isinstance(stmt, DecreaseAmount) else 1 elif isinstance(stmt, Influence): target_polarity = -1 if stmt.overall_polarity() == -1 else 1 # Get the subject and object (works also for Modifications) subj, obj = stmt.agent_list() # Get a list of monomer patterns matching the subject FIXME Currently # this will match rules with the corresponding monomer pattern on it. # In future, this statement should (possibly) also match rules in which # 1) the agent is in its active form, or 2) the agent is tagged as the # enzyme in a rule of the appropriate activity (e.g., a phosphorylation # rule) FIXME if subj is not None: subj_mps = list(pa.grounded_monomer_patterns(self.model, subj, ignore_activities=True)) if not subj_mps: logger.debug('No monomers found corresponding to agent %s' % subj) return PathResult(False, 'SUBJECT_MONOMERS_NOT_FOUND', max_paths, max_path_length) else: subj_mps = [None] # Observables may not be found for an activation since there may be no # rule in the model activating the object, and the object may not have # an "active" site of the appropriate type obs_names = self.stmt_to_obs[stmt] if not obs_names: logger.debug("No observables for stmt %s, returning False" % stmt) return PathResult(False, 'OBSERVABLES_NOT_FOUND', max_paths, max_path_length) for subj_mp, obs_name in itertools.product(subj_mps, obs_names): # NOTE: Returns on the path found for the first enz_mp/obs combo result = self._find_im_paths(subj_mp, obs_name, target_polarity, max_paths, max_path_length) # If a path was found, then we return it; otherwise, that means # there was no path for this observable, so we have to try the next # one if result.path_found: return result # If we got here, then there was no path for any observable return PathResult(False, 'NO_PATHS_FOUND', max_paths, max_path_length)
[ "def", "check_statement", "(", "self", ",", "stmt", ",", "max_paths", "=", "1", ",", "max_path_length", "=", "5", ")", ":", "# Make sure the influence map is initialized", "self", ".", "get_im", "(", ")", "# Check if this is one of the statement types that we can check", ...
Check a single Statement against the model. Parameters ---------- stmt : indra.statements.Statement The Statement to check. max_paths : Optional[int] The maximum number of specific paths to return for each Statement to be explained. Default: 1 max_path_length : Optional[int] The maximum length of specific paths to return. Default: 5 Returns ------- boolean True if the model satisfies the Statement.
[ "Check", "a", "single", "Statement", "against", "the", "model", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/explanation/model_checker.py#L352-L423
19,338
sorgerlab/indra
indra/explanation/model_checker.py
ModelChecker.score_paths
def score_paths(self, paths, agents_values, loss_of_function=False, sigma=0.15, include_final_node=False): """Return scores associated with a given set of paths. Parameters ---------- paths : list[list[tuple[str, int]]] A list of paths obtained from path finding. Each path is a list of tuples (which are edges in the path), with the first element of the tuple the name of a rule, and the second element its polarity in the path. agents_values : dict[indra.statements.Agent, float] A dictionary of INDRA Agents and their corresponding measured value in a given experimental condition. loss_of_function : Optional[boolean] If True, flip the polarity of the path. For instance, if the effect of an inhibitory drug is explained, set this to True. Default: False sigma : Optional[float] The estimated standard deviation for the normally distributed measurement error in the observation model used to score paths with respect to data. Default: 0.15 include_final_node : Optional[boolean] Determines whether the final node of the path is included in the score. Default: False """ obs_model = lambda x: scipy.stats.norm(x, sigma) # Build up dict mapping observables to values obs_dict = {} for ag, val in agents_values.items(): obs_list = self.agent_to_obs[ag] if obs_list is not None: for obs in obs_list: obs_dict[obs] = val # For every path... path_scores = [] for path in paths: logger.info('------') logger.info("Scoring path:") logger.info(path) # Look at every node in the path, excluding the final # observable... path_score = 0 last_path_node_index = -1 if include_final_node else -2 for node, sign in path[:last_path_node_index]: # ...and for each node check the sign to see if it matches the # data. So the first thing is to look at what's downstream # of the rule # affected_obs is a list of observable names alogn for affected_obs, rule_obs_sign in self.rule_obs_dict[node]: flip_polarity = -1 if loss_of_function else 1 pred_sign = sign * rule_obs_sign * flip_polarity # Check to see if this observable is in the data logger.info('%s %s: effect %s %s' % (node, sign, affected_obs, pred_sign)) measured_val = obs_dict.get(affected_obs) if measured_val: # For negative predictions use CDF (prob that given # measured value, true value lies below 0) if pred_sign <= 0: prob_correct = obs_model(measured_val).logcdf(0) # For positive predictions, use log survival function # (SF = 1 - CDF, i.e., prob that true value is # above 0) else: prob_correct = obs_model(measured_val).logsf(0) logger.info('Actual: %s, Log Probability: %s' % (measured_val, prob_correct)) path_score += prob_correct if not self.rule_obs_dict[node]: logger.info('%s %s' % (node, sign)) prob_correct = obs_model(0).logcdf(0) logger.info('Unmeasured node, Log Probability: %s' % (prob_correct)) path_score += prob_correct # Normalized path #path_score = path_score / len(path) logger.info("Path score: %s" % path_score) path_scores.append(path_score) path_tuples = list(zip(paths, path_scores)) # Sort first by path length sorted_by_length = sorted(path_tuples, key=lambda x: len(x[0])) # Sort by probability; sort in reverse order to large values # (higher probabilities) are ranked higher scored_paths = sorted(sorted_by_length, key=lambda x: x[1], reverse=True) return scored_paths
python
def score_paths(self, paths, agents_values, loss_of_function=False, sigma=0.15, include_final_node=False): obs_model = lambda x: scipy.stats.norm(x, sigma) # Build up dict mapping observables to values obs_dict = {} for ag, val in agents_values.items(): obs_list = self.agent_to_obs[ag] if obs_list is not None: for obs in obs_list: obs_dict[obs] = val # For every path... path_scores = [] for path in paths: logger.info('------') logger.info("Scoring path:") logger.info(path) # Look at every node in the path, excluding the final # observable... path_score = 0 last_path_node_index = -1 if include_final_node else -2 for node, sign in path[:last_path_node_index]: # ...and for each node check the sign to see if it matches the # data. So the first thing is to look at what's downstream # of the rule # affected_obs is a list of observable names alogn for affected_obs, rule_obs_sign in self.rule_obs_dict[node]: flip_polarity = -1 if loss_of_function else 1 pred_sign = sign * rule_obs_sign * flip_polarity # Check to see if this observable is in the data logger.info('%s %s: effect %s %s' % (node, sign, affected_obs, pred_sign)) measured_val = obs_dict.get(affected_obs) if measured_val: # For negative predictions use CDF (prob that given # measured value, true value lies below 0) if pred_sign <= 0: prob_correct = obs_model(measured_val).logcdf(0) # For positive predictions, use log survival function # (SF = 1 - CDF, i.e., prob that true value is # above 0) else: prob_correct = obs_model(measured_val).logsf(0) logger.info('Actual: %s, Log Probability: %s' % (measured_val, prob_correct)) path_score += prob_correct if not self.rule_obs_dict[node]: logger.info('%s %s' % (node, sign)) prob_correct = obs_model(0).logcdf(0) logger.info('Unmeasured node, Log Probability: %s' % (prob_correct)) path_score += prob_correct # Normalized path #path_score = path_score / len(path) logger.info("Path score: %s" % path_score) path_scores.append(path_score) path_tuples = list(zip(paths, path_scores)) # Sort first by path length sorted_by_length = sorted(path_tuples, key=lambda x: len(x[0])) # Sort by probability; sort in reverse order to large values # (higher probabilities) are ranked higher scored_paths = sorted(sorted_by_length, key=lambda x: x[1], reverse=True) return scored_paths
[ "def", "score_paths", "(", "self", ",", "paths", ",", "agents_values", ",", "loss_of_function", "=", "False", ",", "sigma", "=", "0.15", ",", "include_final_node", "=", "False", ")", ":", "obs_model", "=", "lambda", "x", ":", "scipy", ".", "stats", ".", ...
Return scores associated with a given set of paths. Parameters ---------- paths : list[list[tuple[str, int]]] A list of paths obtained from path finding. Each path is a list of tuples (which are edges in the path), with the first element of the tuple the name of a rule, and the second element its polarity in the path. agents_values : dict[indra.statements.Agent, float] A dictionary of INDRA Agents and their corresponding measured value in a given experimental condition. loss_of_function : Optional[boolean] If True, flip the polarity of the path. For instance, if the effect of an inhibitory drug is explained, set this to True. Default: False sigma : Optional[float] The estimated standard deviation for the normally distributed measurement error in the observation model used to score paths with respect to data. Default: 0.15 include_final_node : Optional[boolean] Determines whether the final node of the path is included in the score. Default: False
[ "Return", "scores", "associated", "with", "a", "given", "set", "of", "paths", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/explanation/model_checker.py#L642-L728
19,339
sorgerlab/indra
indra/explanation/model_checker.py
ModelChecker.prune_influence_map
def prune_influence_map(self): """Remove edges between rules causing problematic non-transitivity. First, all self-loops are removed. After this initial step, edges are removed between rules when they share *all* child nodes except for each other; that is, they have a mutual relationship with each other and share all of the same children. Note that edges must be removed in batch at the end to prevent edge removal from affecting the lists of rule children during the comparison process. """ im = self.get_im() # First, remove all self-loops logger.info('Removing self loops') edges_to_remove = [] for e in im.edges(): if e[0] == e[1]: logger.info('Removing self loop: %s', e) edges_to_remove.append((e[0], e[1])) # Now remove all the edges to be removed with a single call im.remove_edges_from(edges_to_remove) # Remove parameter nodes from influence map remove_im_params(self.model, im) # Now compare nodes pairwise and look for overlap between child nodes logger.info('Get successorts of each node') succ_dict = {} for node in im.nodes(): succ_dict[node] = set(im.successors(node)) # Sort and then group nodes by number of successors logger.info('Compare combinations of successors') group_key_fun = lambda x: len(succ_dict[x]) nodes_sorted = sorted(im.nodes(), key=group_key_fun) groups = itertools.groupby(nodes_sorted, key=group_key_fun) # Now iterate over each group and then construct combinations # within the group to check for shared sucessors edges_to_remove = [] for gix, group in groups: combos = itertools.combinations(group, 2) for ix, (p1, p2) in enumerate(combos): # Children are identical except for mutual relationship if succ_dict[p1].difference(succ_dict[p2]) == set([p2]) and \ succ_dict[p2].difference(succ_dict[p1]) == set([p1]): for u, v in ((p1, p2), (p2, p1)): edges_to_remove.append((u, v)) logger.debug('Will remove edge (%s, %s)', u, v) logger.info('Removing %d edges from influence map' % len(edges_to_remove)) # Now remove all the edges to be removed with a single call im.remove_edges_from(edges_to_remove)
python
def prune_influence_map(self): im = self.get_im() # First, remove all self-loops logger.info('Removing self loops') edges_to_remove = [] for e in im.edges(): if e[0] == e[1]: logger.info('Removing self loop: %s', e) edges_to_remove.append((e[0], e[1])) # Now remove all the edges to be removed with a single call im.remove_edges_from(edges_to_remove) # Remove parameter nodes from influence map remove_im_params(self.model, im) # Now compare nodes pairwise and look for overlap between child nodes logger.info('Get successorts of each node') succ_dict = {} for node in im.nodes(): succ_dict[node] = set(im.successors(node)) # Sort and then group nodes by number of successors logger.info('Compare combinations of successors') group_key_fun = lambda x: len(succ_dict[x]) nodes_sorted = sorted(im.nodes(), key=group_key_fun) groups = itertools.groupby(nodes_sorted, key=group_key_fun) # Now iterate over each group and then construct combinations # within the group to check for shared sucessors edges_to_remove = [] for gix, group in groups: combos = itertools.combinations(group, 2) for ix, (p1, p2) in enumerate(combos): # Children are identical except for mutual relationship if succ_dict[p1].difference(succ_dict[p2]) == set([p2]) and \ succ_dict[p2].difference(succ_dict[p1]) == set([p1]): for u, v in ((p1, p2), (p2, p1)): edges_to_remove.append((u, v)) logger.debug('Will remove edge (%s, %s)', u, v) logger.info('Removing %d edges from influence map' % len(edges_to_remove)) # Now remove all the edges to be removed with a single call im.remove_edges_from(edges_to_remove)
[ "def", "prune_influence_map", "(", "self", ")", ":", "im", "=", "self", ".", "get_im", "(", ")", "# First, remove all self-loops", "logger", ".", "info", "(", "'Removing self loops'", ")", "edges_to_remove", "=", "[", "]", "for", "e", "in", "im", ".", "edges...
Remove edges between rules causing problematic non-transitivity. First, all self-loops are removed. After this initial step, edges are removed between rules when they share *all* child nodes except for each other; that is, they have a mutual relationship with each other and share all of the same children. Note that edges must be removed in batch at the end to prevent edge removal from affecting the lists of rule children during the comparison process.
[ "Remove", "edges", "between", "rules", "causing", "problematic", "non", "-", "transitivity", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/explanation/model_checker.py#L730-L782
19,340
sorgerlab/indra
indra/explanation/model_checker.py
ModelChecker.prune_influence_map_subj_obj
def prune_influence_map_subj_obj(self): """Prune influence map to include only edges where the object of the upstream rule matches the subject of the downstream rule.""" def get_rule_info(r): result = {} for ann in self.model.annotations: if ann.subject == r: if ann.predicate == 'rule_has_subject': result['subject'] = ann.object elif ann.predicate == 'rule_has_object': result['object'] = ann.object return result im = self.get_im() rules = im.nodes() edges_to_prune = [] for r1, r2 in itertools.permutations(rules, 2): if (r1, r2) not in im.edges(): continue r1_info = get_rule_info(r1) r2_info = get_rule_info(r2) if 'object' not in r1_info or 'subject' not in r2_info: continue if r1_info['object'] != r2_info['subject']: logger.info("Removing edge %s --> %s" % (r1, r2)) edges_to_prune.append((r1, r2)) im.remove_edges_from(edges_to_prune)
python
def prune_influence_map_subj_obj(self): def get_rule_info(r): result = {} for ann in self.model.annotations: if ann.subject == r: if ann.predicate == 'rule_has_subject': result['subject'] = ann.object elif ann.predicate == 'rule_has_object': result['object'] = ann.object return result im = self.get_im() rules = im.nodes() edges_to_prune = [] for r1, r2 in itertools.permutations(rules, 2): if (r1, r2) not in im.edges(): continue r1_info = get_rule_info(r1) r2_info = get_rule_info(r2) if 'object' not in r1_info or 'subject' not in r2_info: continue if r1_info['object'] != r2_info['subject']: logger.info("Removing edge %s --> %s" % (r1, r2)) edges_to_prune.append((r1, r2)) im.remove_edges_from(edges_to_prune)
[ "def", "prune_influence_map_subj_obj", "(", "self", ")", ":", "def", "get_rule_info", "(", "r", ")", ":", "result", "=", "{", "}", "for", "ann", "in", "self", ".", "model", ".", "annotations", ":", "if", "ann", ".", "subject", "==", "r", ":", "if", "...
Prune influence map to include only edges where the object of the upstream rule matches the subject of the downstream rule.
[ "Prune", "influence", "map", "to", "include", "only", "edges", "where", "the", "object", "of", "the", "upstream", "rule", "matches", "the", "subject", "of", "the", "downstream", "rule", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/explanation/model_checker.py#L784-L809
19,341
sorgerlab/indra
indra/tools/reading/util/reporter.py
Reporter.add_section
def add_section(self, section_name): """Create a section of the report, to be headed by section_name Text and images can be added by using the `section` argument of the `add_text` and `add_image` methods. Sections can also be ordered by using the `set_section_order` method. By default, text and images that have no section will be placed after all the sections, in the order they were added. This behavior may be altered using the `sections_first` attribute of the `make_report` method. """ self.section_headings.append(section_name) if section_name in self.sections: raise ValueError("Section %s already exists." % section_name) self.sections[section_name] = [] return
python
def add_section(self, section_name): self.section_headings.append(section_name) if section_name in self.sections: raise ValueError("Section %s already exists." % section_name) self.sections[section_name] = [] return
[ "def", "add_section", "(", "self", ",", "section_name", ")", ":", "self", ".", "section_headings", ".", "append", "(", "section_name", ")", "if", "section_name", "in", "self", ".", "sections", ":", "raise", "ValueError", "(", "\"Section %s already exists.\"", "%...
Create a section of the report, to be headed by section_name Text and images can be added by using the `section` argument of the `add_text` and `add_image` methods. Sections can also be ordered by using the `set_section_order` method. By default, text and images that have no section will be placed after all the sections, in the order they were added. This behavior may be altered using the `sections_first` attribute of the `make_report` method.
[ "Create", "a", "section", "of", "the", "report", "to", "be", "headed", "by", "section_name" ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/reading/util/reporter.py#L31-L47
19,342
sorgerlab/indra
indra/tools/reading/util/reporter.py
Reporter.set_section_order
def set_section_order(self, section_name_list): """Set the order of the sections, which are by default unorderd. Any unlisted sections that exist will be placed at the end of the document in no particular order. """ self.section_headings = section_name_list[:] for section_name in self.sections.keys(): if section_name not in section_name_list: self.section_headings.append(section_name) return
python
def set_section_order(self, section_name_list): self.section_headings = section_name_list[:] for section_name in self.sections.keys(): if section_name not in section_name_list: self.section_headings.append(section_name) return
[ "def", "set_section_order", "(", "self", ",", "section_name_list", ")", ":", "self", ".", "section_headings", "=", "section_name_list", "[", ":", "]", "for", "section_name", "in", "self", ".", "sections", ".", "keys", "(", ")", ":", "if", "section_name", "no...
Set the order of the sections, which are by default unorderd. Any unlisted sections that exist will be placed at the end of the document in no particular order.
[ "Set", "the", "order", "of", "the", "sections", "which", "are", "by", "default", "unorderd", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/reading/util/reporter.py#L49-L59
19,343
sorgerlab/indra
indra/tools/reading/util/reporter.py
Reporter.add_text
def add_text(self, text, *args, **kwargs): """Add text to the document. Text is shown on the final document in the order it is added, either within the given section or as part of the un-sectioned list of content. Parameters ---------- text : str The text to be added. style : str Choose the style of the text. Options include 'Normal', 'Code', 'Title', 'h1'. For others, see `getSampleStyleSheet` from `reportlab.lib.styles`. space : tuple (num spaces, font size) The number and size of spaces to follow this section of text. Default is (1, 12). fontsize : int The integer font size of the text (e.g. 12 for 12 point font). Default is 12. alignment : str The alignment of the text. Options include 'left', 'right', and 'center'. Default is 'left'. section : str (This must be a keyword) Select a section in which to place this text. Default is None, in which case the text will be simply be added to a default list of text and images. """ # Pull down some kwargs. section_name = kwargs.pop('section', None) # Actually do the formatting. para, sp = self._preformat_text(text, *args, **kwargs) # Select the appropriate list to update if section_name is None: relevant_list = self.story else: relevant_list = self.sections[section_name] # Add the new content to list. relevant_list.append(para) relevant_list.append(sp) return
python
def add_text(self, text, *args, **kwargs): # Pull down some kwargs. section_name = kwargs.pop('section', None) # Actually do the formatting. para, sp = self._preformat_text(text, *args, **kwargs) # Select the appropriate list to update if section_name is None: relevant_list = self.story else: relevant_list = self.sections[section_name] # Add the new content to list. relevant_list.append(para) relevant_list.append(sp) return
[ "def", "add_text", "(", "self", ",", "text", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Pull down some kwargs.", "section_name", "=", "kwargs", ".", "pop", "(", "'section'", ",", "None", ")", "# Actually do the formatting.", "para", ",", "sp", ...
Add text to the document. Text is shown on the final document in the order it is added, either within the given section or as part of the un-sectioned list of content. Parameters ---------- text : str The text to be added. style : str Choose the style of the text. Options include 'Normal', 'Code', 'Title', 'h1'. For others, see `getSampleStyleSheet` from `reportlab.lib.styles`. space : tuple (num spaces, font size) The number and size of spaces to follow this section of text. Default is (1, 12). fontsize : int The integer font size of the text (e.g. 12 for 12 point font). Default is 12. alignment : str The alignment of the text. Options include 'left', 'right', and 'center'. Default is 'left'. section : str (This must be a keyword) Select a section in which to place this text. Default is None, in which case the text will be simply be added to a default list of text and images.
[ "Add", "text", "to", "the", "document", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/reading/util/reporter.py#L61-L104
19,344
sorgerlab/indra
indra/tools/reading/util/reporter.py
Reporter.add_image
def add_image(self, image_path, width=None, height=None, section=None): """Add an image to the document. Images are shown on the final document in the order they are added, either within the given section or as part of the un-sectioned list of content. Parameters ---------- image_path : str A path to the image on the local file system. width : int or float The width of the image in the document in inches. height : int or float The height of the image in the document in incehs. section : str (This must be a keyword) Select a section in which to place this image. Default is None, in which case the image will be simply be added to a default list of text and images. """ if width is not None: width = width*inch if height is not None: height = height*inch im = Image(image_path, width, height) if section is None: self.story.append(im) else: self.sections[section].append(im) return
python
def add_image(self, image_path, width=None, height=None, section=None): if width is not None: width = width*inch if height is not None: height = height*inch im = Image(image_path, width, height) if section is None: self.story.append(im) else: self.sections[section].append(im) return
[ "def", "add_image", "(", "self", ",", "image_path", ",", "width", "=", "None", ",", "height", "=", "None", ",", "section", "=", "None", ")", ":", "if", "width", "is", "not", "None", ":", "width", "=", "width", "*", "inch", "if", "height", "is", "no...
Add an image to the document. Images are shown on the final document in the order they are added, either within the given section or as part of the un-sectioned list of content. Parameters ---------- image_path : str A path to the image on the local file system. width : int or float The width of the image in the document in inches. height : int or float The height of the image in the document in incehs. section : str (This must be a keyword) Select a section in which to place this image. Default is None, in which case the image will be simply be added to a default list of text and images.
[ "Add", "an", "image", "to", "the", "document", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/reading/util/reporter.py#L106-L135
19,345
sorgerlab/indra
indra/tools/reading/util/reporter.py
Reporter.make_report
def make_report(self, sections_first=True, section_header_params=None): """Create the pdf document with name `self.name + '.pdf'`. Parameters ---------- sections_first : bool If True (default), text and images with sections are presented first and un-sectioned content is appended afterword. If False, sectioned text and images will be placed before the sections. section_header_params : dict or None Optionally overwrite/extend the default formatting for the section headers. Default is None. """ full_story = list(self._preformat_text(self.title, style='Title', fontsize=18, alignment='center')) # Set the default section header parameters if section_header_params is None: section_header_params = {'style': 'h1', 'fontsize': 14, 'alignment': 'center'} # Merge the sections and the rest of the story. if sections_first: full_story += self._make_sections(**section_header_params) full_story += self.story else: full_story += self.story full_story += self._make_sections(**section_header_params) fname = self.name + '.pdf' doc = SimpleDocTemplate(fname, pagesize=letter, rightMargin=72, leftMargin=72, topMargin=72, bottomMargin=18) doc.build(full_story) return fname
python
def make_report(self, sections_first=True, section_header_params=None): full_story = list(self._preformat_text(self.title, style='Title', fontsize=18, alignment='center')) # Set the default section header parameters if section_header_params is None: section_header_params = {'style': 'h1', 'fontsize': 14, 'alignment': 'center'} # Merge the sections and the rest of the story. if sections_first: full_story += self._make_sections(**section_header_params) full_story += self.story else: full_story += self.story full_story += self._make_sections(**section_header_params) fname = self.name + '.pdf' doc = SimpleDocTemplate(fname, pagesize=letter, rightMargin=72, leftMargin=72, topMargin=72, bottomMargin=18) doc.build(full_story) return fname
[ "def", "make_report", "(", "self", ",", "sections_first", "=", "True", ",", "section_header_params", "=", "None", ")", ":", "full_story", "=", "list", "(", "self", ".", "_preformat_text", "(", "self", ".", "title", ",", "style", "=", "'Title'", ",", "fonts...
Create the pdf document with name `self.name + '.pdf'`. Parameters ---------- sections_first : bool If True (default), text and images with sections are presented first and un-sectioned content is appended afterword. If False, sectioned text and images will be placed before the sections. section_header_params : dict or None Optionally overwrite/extend the default formatting for the section headers. Default is None.
[ "Create", "the", "pdf", "document", "with", "name", "self", ".", "name", "+", ".", "pdf", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/reading/util/reporter.py#L137-L171
19,346
sorgerlab/indra
indra/tools/reading/util/reporter.py
Reporter._make_sections
def _make_sections(self, **section_hdr_params): """Flatten the sections into a single story list.""" sect_story = [] if not self.section_headings and len(self.sections): self.section_headings = self.sections.keys() for section_name in self.section_headings: section_story = self.sections[section_name] line = '-'*20 section_head_text = '%s %s %s' % (line, section_name, line) title, title_sp = self._preformat_text(section_head_text, **section_hdr_params) sect_story += [title, title_sp] + section_story return sect_story
python
def _make_sections(self, **section_hdr_params): sect_story = [] if not self.section_headings and len(self.sections): self.section_headings = self.sections.keys() for section_name in self.section_headings: section_story = self.sections[section_name] line = '-'*20 section_head_text = '%s %s %s' % (line, section_name, line) title, title_sp = self._preformat_text(section_head_text, **section_hdr_params) sect_story += [title, title_sp] + section_story return sect_story
[ "def", "_make_sections", "(", "self", ",", "*", "*", "section_hdr_params", ")", ":", "sect_story", "=", "[", "]", "if", "not", "self", ".", "section_headings", "and", "len", "(", "self", ".", "sections", ")", ":", "self", ".", "section_headings", "=", "s...
Flatten the sections into a single story list.
[ "Flatten", "the", "sections", "into", "a", "single", "story", "list", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/reading/util/reporter.py#L173-L186
19,347
sorgerlab/indra
indra/tools/reading/util/reporter.py
Reporter._preformat_text
def _preformat_text(self, text, style='Normal', space=None, fontsize=12, alignment='left'): """Format the text for addition to a story list.""" if space is None: space=(1,12) ptext = ('<para alignment=\"%s\"><font size=%d>%s</font></para>' % (alignment, fontsize, text)) para = Paragraph(ptext, self.styles[style]) sp = Spacer(*space) return para, sp
python
def _preformat_text(self, text, style='Normal', space=None, fontsize=12, alignment='left'): if space is None: space=(1,12) ptext = ('<para alignment=\"%s\"><font size=%d>%s</font></para>' % (alignment, fontsize, text)) para = Paragraph(ptext, self.styles[style]) sp = Spacer(*space) return para, sp
[ "def", "_preformat_text", "(", "self", ",", "text", ",", "style", "=", "'Normal'", ",", "space", "=", "None", ",", "fontsize", "=", "12", ",", "alignment", "=", "'left'", ")", ":", "if", "space", "is", "None", ":", "space", "=", "(", "1", ",", "12"...
Format the text for addition to a story list.
[ "Format", "the", "text", "for", "addition", "to", "a", "story", "list", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/reading/util/reporter.py#L188-L197
19,348
sorgerlab/indra
indra/databases/mesh_client.py
get_mesh_name_from_web
def get_mesh_name_from_web(mesh_id): """Get the MESH label for the given MESH ID using the NLM REST API. Parameters ---------- mesh_id : str MESH Identifier, e.g. 'D003094'. Returns ------- str Label for the MESH ID, or None if the query failed or no label was found. """ url = MESH_URL + mesh_id + '.json' resp = requests.get(url) if resp.status_code != 200: return None mesh_json = resp.json() try: label = mesh_json['@graph'][0]['label']['@value'] except (KeyError, IndexError) as e: return None return label
python
def get_mesh_name_from_web(mesh_id): url = MESH_URL + mesh_id + '.json' resp = requests.get(url) if resp.status_code != 200: return None mesh_json = resp.json() try: label = mesh_json['@graph'][0]['label']['@value'] except (KeyError, IndexError) as e: return None return label
[ "def", "get_mesh_name_from_web", "(", "mesh_id", ")", ":", "url", "=", "MESH_URL", "+", "mesh_id", "+", "'.json'", "resp", "=", "requests", ".", "get", "(", "url", ")", "if", "resp", ".", "status_code", "!=", "200", ":", "return", "None", "mesh_json", "=...
Get the MESH label for the given MESH ID using the NLM REST API. Parameters ---------- mesh_id : str MESH Identifier, e.g. 'D003094'. Returns ------- str Label for the MESH ID, or None if the query failed or no label was found.
[ "Get", "the", "MESH", "label", "for", "the", "given", "MESH", "ID", "using", "the", "NLM", "REST", "API", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/databases/mesh_client.py#L28-L51
19,349
sorgerlab/indra
indra/databases/mesh_client.py
get_mesh_name
def get_mesh_name(mesh_id, offline=False): """Get the MESH label for the given MESH ID. Uses the mappings table in `indra/resources`; if the MESH ID is not listed there, falls back on the NLM REST API. Parameters ---------- mesh_id : str MESH Identifier, e.g. 'D003094'. offline : bool Whether to allow queries to the NLM REST API if the given MESH ID is not contained in INDRA's internal MESH mappings file. Default is False (allows REST API queries). Returns ------- str Label for the MESH ID, or None if the query failed or no label was found. """ indra_mesh_mapping = mesh_id_to_name.get(mesh_id) if offline or indra_mesh_mapping is not None: return indra_mesh_mapping # Look up the MESH mapping from NLM if we don't have it locally return get_mesh_name_from_web(mesh_id)
python
def get_mesh_name(mesh_id, offline=False): indra_mesh_mapping = mesh_id_to_name.get(mesh_id) if offline or indra_mesh_mapping is not None: return indra_mesh_mapping # Look up the MESH mapping from NLM if we don't have it locally return get_mesh_name_from_web(mesh_id)
[ "def", "get_mesh_name", "(", "mesh_id", ",", "offline", "=", "False", ")", ":", "indra_mesh_mapping", "=", "mesh_id_to_name", ".", "get", "(", "mesh_id", ")", "if", "offline", "or", "indra_mesh_mapping", "is", "not", "None", ":", "return", "indra_mesh_mapping", ...
Get the MESH label for the given MESH ID. Uses the mappings table in `indra/resources`; if the MESH ID is not listed there, falls back on the NLM REST API. Parameters ---------- mesh_id : str MESH Identifier, e.g. 'D003094'. offline : bool Whether to allow queries to the NLM REST API if the given MESH ID is not contained in INDRA's internal MESH mappings file. Default is False (allows REST API queries). Returns ------- str Label for the MESH ID, or None if the query failed or no label was found.
[ "Get", "the", "MESH", "label", "for", "the", "given", "MESH", "ID", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/databases/mesh_client.py#L54-L79
19,350
sorgerlab/indra
indra/databases/mesh_client.py
get_mesh_id_name
def get_mesh_id_name(mesh_term, offline=False): """Get the MESH ID and name for the given MESH term. Uses the mappings table in `indra/resources`; if the MESH term is not listed there, falls back on the NLM REST API. Parameters ---------- mesh_term : str MESH Descriptor or Concept name, e.g. 'Breast Cancer'. offline : bool Whether to allow queries to the NLM REST API if the given MESH term is not contained in INDRA's internal MESH mappings file. Default is False (allows REST API queries). Returns ------- tuple of strs Returns a 2-tuple of the form `(id, name)` with the ID of the descriptor corresponding to the MESH label, and the descriptor name (which may not exactly match the name provided as an argument if it is a Concept name). If the query failed, or no descriptor corresponding to the name was found, returns a tuple of (None, None). """ indra_mesh_id = mesh_name_to_id.get(mesh_term) if indra_mesh_id is not None: return indra_mesh_id, mesh_term indra_mesh_id, new_term = \ mesh_name_to_id_name.get(mesh_term, (None, None)) if indra_mesh_id is not None: return indra_mesh_id, new_term if offline: return None, None # Look up the MESH mapping from NLM if we don't have it locally return get_mesh_id_name_from_web(mesh_term)
python
def get_mesh_id_name(mesh_term, offline=False): indra_mesh_id = mesh_name_to_id.get(mesh_term) if indra_mesh_id is not None: return indra_mesh_id, mesh_term indra_mesh_id, new_term = \ mesh_name_to_id_name.get(mesh_term, (None, None)) if indra_mesh_id is not None: return indra_mesh_id, new_term if offline: return None, None # Look up the MESH mapping from NLM if we don't have it locally return get_mesh_id_name_from_web(mesh_term)
[ "def", "get_mesh_id_name", "(", "mesh_term", ",", "offline", "=", "False", ")", ":", "indra_mesh_id", "=", "mesh_name_to_id", ".", "get", "(", "mesh_term", ")", "if", "indra_mesh_id", "is", "not", "None", ":", "return", "indra_mesh_id", ",", "mesh_term", "indr...
Get the MESH ID and name for the given MESH term. Uses the mappings table in `indra/resources`; if the MESH term is not listed there, falls back on the NLM REST API. Parameters ---------- mesh_term : str MESH Descriptor or Concept name, e.g. 'Breast Cancer'. offline : bool Whether to allow queries to the NLM REST API if the given MESH term is not contained in INDRA's internal MESH mappings file. Default is False (allows REST API queries). Returns ------- tuple of strs Returns a 2-tuple of the form `(id, name)` with the ID of the descriptor corresponding to the MESH label, and the descriptor name (which may not exactly match the name provided as an argument if it is a Concept name). If the query failed, or no descriptor corresponding to the name was found, returns a tuple of (None, None).
[ "Get", "the", "MESH", "ID", "and", "name", "for", "the", "given", "MESH", "term", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/databases/mesh_client.py#L82-L119
19,351
sorgerlab/indra
indra/tools/machine/cli.py
make
def make(directory): """Makes a RAS Machine directory""" if os.path.exists(directory): if os.path.isdir(directory): click.echo('Directory already exists') else: click.echo('Path exists and is not a directory') sys.exit() os.makedirs(directory) os.mkdir(os.path.join(directory, 'jsons')) copy_default_config(os.path.join(directory, 'config.yaml'))
python
def make(directory): if os.path.exists(directory): if os.path.isdir(directory): click.echo('Directory already exists') else: click.echo('Path exists and is not a directory') sys.exit() os.makedirs(directory) os.mkdir(os.path.join(directory, 'jsons')) copy_default_config(os.path.join(directory, 'config.yaml'))
[ "def", "make", "(", "directory", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "directory", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "directory", ")", ":", "click", ".", "echo", "(", "'Directory already exists'", ")", "else", ":...
Makes a RAS Machine directory
[ "Makes", "a", "RAS", "Machine", "directory" ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/machine/cli.py#L30-L42
19,352
sorgerlab/indra
indra/tools/machine/cli.py
run_with_search
def run_with_search(model_path, config, num_days): """Run with PubMed search for new papers.""" from indra.tools.machine.machine import run_with_search_helper run_with_search_helper(model_path, config, num_days=num_days)
python
def run_with_search(model_path, config, num_days): from indra.tools.machine.machine import run_with_search_helper run_with_search_helper(model_path, config, num_days=num_days)
[ "def", "run_with_search", "(", "model_path", ",", "config", ",", "num_days", ")", ":", "from", "indra", ".", "tools", ".", "machine", ".", "machine", "import", "run_with_search_helper", "run_with_search_helper", "(", "model_path", ",", "config", ",", "num_days", ...
Run with PubMed search for new papers.
[ "Run", "with", "PubMed", "search", "for", "new", "papers", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/machine/cli.py#L50-L53
19,353
sorgerlab/indra
indra/tools/machine/cli.py
run_with_pmids
def run_with_pmids(model_path, pmids): """Run with given list of PMIDs.""" from indra.tools.machine.machine import run_with_pmids_helper run_with_pmids_helper(model_path, pmids)
python
def run_with_pmids(model_path, pmids): from indra.tools.machine.machine import run_with_pmids_helper run_with_pmids_helper(model_path, pmids)
[ "def", "run_with_pmids", "(", "model_path", ",", "pmids", ")", ":", "from", "indra", ".", "tools", ".", "machine", ".", "machine", "import", "run_with_pmids_helper", "run_with_pmids_helper", "(", "model_path", ",", "pmids", ")" ]
Run with given list of PMIDs.
[ "Run", "with", "given", "list", "of", "PMIDs", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/machine/cli.py#L68-L71
19,354
sorgerlab/indra
indra/literature/pmc_client.py
id_lookup
def id_lookup(paper_id, idtype=None): """This function takes a Pubmed ID, Pubmed Central ID, or DOI and use the Pubmed ID mapping service and looks up all other IDs from one of these. The IDs are returned in a dictionary.""" if idtype is not None and idtype not in ('pmid', 'pmcid', 'doi'): raise ValueError("Invalid idtype %s; must be 'pmid', 'pmcid', " "or 'doi'." % idtype) if paper_id.upper().startswith('PMC'): idtype = 'pmcid' # Strip off any prefix if paper_id.upper().startswith('PMID'): paper_id = paper_id[4:] elif paper_id.upper().startswith('DOI'): paper_id = paper_id[3:] data = {'ids': paper_id} if idtype is not None: data['idtype'] = idtype try: tree = pubmed_client.send_request(pmid_convert_url, data) except Exception as e: logger.error('Error looking up PMID in PMC: %s' % e) return {} if tree is None: return {} record = tree.find('record') if record is None: return {} doi = record.attrib.get('doi') pmid = record.attrib.get('pmid') pmcid = record.attrib.get('pmcid') ids = {'doi': doi, 'pmid': pmid, 'pmcid': pmcid} return ids
python
def id_lookup(paper_id, idtype=None): if idtype is not None and idtype not in ('pmid', 'pmcid', 'doi'): raise ValueError("Invalid idtype %s; must be 'pmid', 'pmcid', " "or 'doi'." % idtype) if paper_id.upper().startswith('PMC'): idtype = 'pmcid' # Strip off any prefix if paper_id.upper().startswith('PMID'): paper_id = paper_id[4:] elif paper_id.upper().startswith('DOI'): paper_id = paper_id[3:] data = {'ids': paper_id} if idtype is not None: data['idtype'] = idtype try: tree = pubmed_client.send_request(pmid_convert_url, data) except Exception as e: logger.error('Error looking up PMID in PMC: %s' % e) return {} if tree is None: return {} record = tree.find('record') if record is None: return {} doi = record.attrib.get('doi') pmid = record.attrib.get('pmid') pmcid = record.attrib.get('pmcid') ids = {'doi': doi, 'pmid': pmid, 'pmcid': pmcid} return ids
[ "def", "id_lookup", "(", "paper_id", ",", "idtype", "=", "None", ")", ":", "if", "idtype", "is", "not", "None", "and", "idtype", "not", "in", "(", "'pmid'", ",", "'pmcid'", ",", "'doi'", ")", ":", "raise", "ValueError", "(", "\"Invalid idtype %s; must be '...
This function takes a Pubmed ID, Pubmed Central ID, or DOI and use the Pubmed ID mapping service and looks up all other IDs from one of these. The IDs are returned in a dictionary.
[ "This", "function", "takes", "a", "Pubmed", "ID", "Pubmed", "Central", "ID", "or", "DOI", "and", "use", "the", "Pubmed", "ID", "mapping", "service", "and", "looks", "up", "all", "other", "IDs", "from", "one", "of", "these", ".", "The", "IDs", "are", "r...
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/literature/pmc_client.py#L40-L74
19,355
sorgerlab/indra
indra/literature/pmc_client.py
get_xml
def get_xml(pmc_id): """Returns XML for the article corresponding to a PMC ID.""" if pmc_id.upper().startswith('PMC'): pmc_id = pmc_id[3:] # Request params params = {} params['verb'] = 'GetRecord' params['identifier'] = 'oai:pubmedcentral.nih.gov:%s' % pmc_id params['metadataPrefix'] = 'pmc' # Submit the request res = requests.get(pmc_url, params) if not res.status_code == 200: logger.warning("Couldn't download %s" % pmc_id) return None # Read the bytestream xml_bytes = res.content # Check for any XML errors; xml_str should still be bytes tree = ET.XML(xml_bytes, parser=UTB()) xmlns = "http://www.openarchives.org/OAI/2.0/" err_tag = tree.find('{%s}error' % xmlns) if err_tag is not None: err_code = err_tag.attrib['code'] err_text = err_tag.text logger.warning('PMC client returned with error %s: %s' % (err_code, err_text)) return None # If no error, return the XML as a unicode string else: return xml_bytes.decode('utf-8')
python
def get_xml(pmc_id): if pmc_id.upper().startswith('PMC'): pmc_id = pmc_id[3:] # Request params params = {} params['verb'] = 'GetRecord' params['identifier'] = 'oai:pubmedcentral.nih.gov:%s' % pmc_id params['metadataPrefix'] = 'pmc' # Submit the request res = requests.get(pmc_url, params) if not res.status_code == 200: logger.warning("Couldn't download %s" % pmc_id) return None # Read the bytestream xml_bytes = res.content # Check for any XML errors; xml_str should still be bytes tree = ET.XML(xml_bytes, parser=UTB()) xmlns = "http://www.openarchives.org/OAI/2.0/" err_tag = tree.find('{%s}error' % xmlns) if err_tag is not None: err_code = err_tag.attrib['code'] err_text = err_tag.text logger.warning('PMC client returned with error %s: %s' % (err_code, err_text)) return None # If no error, return the XML as a unicode string else: return xml_bytes.decode('utf-8')
[ "def", "get_xml", "(", "pmc_id", ")", ":", "if", "pmc_id", ".", "upper", "(", ")", ".", "startswith", "(", "'PMC'", ")", ":", "pmc_id", "=", "pmc_id", "[", "3", ":", "]", "# Request params", "params", "=", "{", "}", "params", "[", "'verb'", "]", "=...
Returns XML for the article corresponding to a PMC ID.
[ "Returns", "XML", "for", "the", "article", "corresponding", "to", "a", "PMC", "ID", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/literature/pmc_client.py#L81-L109
19,356
sorgerlab/indra
indra/literature/pmc_client.py
extract_paragraphs
def extract_paragraphs(xml_string): """Returns list of paragraphs in an NLM XML. Parameters ---------- xml_string : str String containing valid NLM XML. Returns ------- list of str List of extracted paragraphs in an NLM XML """ tree = etree.fromstring(xml_string.encode('utf-8')) paragraphs = [] # In NLM xml, all plaintext is within <p> tags, and is the only thing # that can be contained in <p> tags. To handle to possibility of namespaces # uses regex to search for tags either of the form 'p' or '{<namespace>}p' for element in tree.iter(): if isinstance(element.tag, basestring) and \ re.search('(^|})[p|title]$', element.tag) and element.text: paragraph = ' '.join(element.itertext()) paragraphs.append(paragraph) return paragraphs
python
def extract_paragraphs(xml_string): tree = etree.fromstring(xml_string.encode('utf-8')) paragraphs = [] # In NLM xml, all plaintext is within <p> tags, and is the only thing # that can be contained in <p> tags. To handle to possibility of namespaces # uses regex to search for tags either of the form 'p' or '{<namespace>}p' for element in tree.iter(): if isinstance(element.tag, basestring) and \ re.search('(^|})[p|title]$', element.tag) and element.text: paragraph = ' '.join(element.itertext()) paragraphs.append(paragraph) return paragraphs
[ "def", "extract_paragraphs", "(", "xml_string", ")", ":", "tree", "=", "etree", ".", "fromstring", "(", "xml_string", ".", "encode", "(", "'utf-8'", ")", ")", "paragraphs", "=", "[", "]", "# In NLM xml, all plaintext is within <p> tags, and is the only thing", "# that...
Returns list of paragraphs in an NLM XML. Parameters ---------- xml_string : str String containing valid NLM XML. Returns ------- list of str List of extracted paragraphs in an NLM XML
[ "Returns", "list", "of", "paragraphs", "in", "an", "NLM", "XML", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/literature/pmc_client.py#L132-L156
19,357
sorgerlab/indra
indra/literature/pmc_client.py
filter_pmids
def filter_pmids(pmid_list, source_type): """Filter a list of PMIDs for ones with full text from PMC. Parameters ---------- pmid_list : list of str List of PMIDs to filter. source_type : string One of 'fulltext', 'oa_xml', 'oa_txt', or 'auth_xml'. Returns ------- list of str PMIDs available in the specified source/format type. """ global pmids_fulltext_dict # Check args if source_type not in ('fulltext', 'oa_xml', 'oa_txt', 'auth_xml'): raise ValueError("source_type must be one of: 'fulltext', 'oa_xml', " "'oa_txt', or 'auth_xml'.") # Check if we've loaded this type, and lazily initialize if pmids_fulltext_dict.get(source_type) is None: fulltext_list_path = os.path.join(os.path.dirname(__file__), 'pmids_%s.txt' % source_type) with open(fulltext_list_path, 'rb') as f: fulltext_list = set([line.strip().decode('utf-8') for line in f.readlines()]) pmids_fulltext_dict[source_type] = fulltext_list return list(set(pmid_list).intersection( pmids_fulltext_dict.get(source_type)))
python
def filter_pmids(pmid_list, source_type): global pmids_fulltext_dict # Check args if source_type not in ('fulltext', 'oa_xml', 'oa_txt', 'auth_xml'): raise ValueError("source_type must be one of: 'fulltext', 'oa_xml', " "'oa_txt', or 'auth_xml'.") # Check if we've loaded this type, and lazily initialize if pmids_fulltext_dict.get(source_type) is None: fulltext_list_path = os.path.join(os.path.dirname(__file__), 'pmids_%s.txt' % source_type) with open(fulltext_list_path, 'rb') as f: fulltext_list = set([line.strip().decode('utf-8') for line in f.readlines()]) pmids_fulltext_dict[source_type] = fulltext_list return list(set(pmid_list).intersection( pmids_fulltext_dict.get(source_type)))
[ "def", "filter_pmids", "(", "pmid_list", ",", "source_type", ")", ":", "global", "pmids_fulltext_dict", "# Check args", "if", "source_type", "not", "in", "(", "'fulltext'", ",", "'oa_xml'", ",", "'oa_txt'", ",", "'auth_xml'", ")", ":", "raise", "ValueError", "("...
Filter a list of PMIDs for ones with full text from PMC. Parameters ---------- pmid_list : list of str List of PMIDs to filter. source_type : string One of 'fulltext', 'oa_xml', 'oa_txt', or 'auth_xml'. Returns ------- list of str PMIDs available in the specified source/format type.
[ "Filter", "a", "list", "of", "PMIDs", "for", "ones", "with", "full", "text", "from", "PMC", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/literature/pmc_client.py#L159-L188
19,358
sorgerlab/indra
indra/sources/cwms/util.py
get_example_extractions
def get_example_extractions(fname): "Get extractions from one of the examples in `cag_examples`." with open(fname, 'r') as f: sentences = f.read().splitlines() rdf_xml_dict = {} for sentence in sentences: logger.info("Reading \"%s\"..." % sentence) html = tc.send_query(sentence, 'cwms') try: rdf_xml_dict[sentence] = tc.get_xml(html, 'rdf:RDF', fail_if_empty=True) except AssertionError as e: logger.error("Got error for %s." % sentence) logger.exception(e) return rdf_xml_dict
python
def get_example_extractions(fname): "Get extractions from one of the examples in `cag_examples`." with open(fname, 'r') as f: sentences = f.read().splitlines() rdf_xml_dict = {} for sentence in sentences: logger.info("Reading \"%s\"..." % sentence) html = tc.send_query(sentence, 'cwms') try: rdf_xml_dict[sentence] = tc.get_xml(html, 'rdf:RDF', fail_if_empty=True) except AssertionError as e: logger.error("Got error for %s." % sentence) logger.exception(e) return rdf_xml_dict
[ "def", "get_example_extractions", "(", "fname", ")", ":", "with", "open", "(", "fname", ",", "'r'", ")", "as", "f", ":", "sentences", "=", "f", ".", "read", "(", ")", ".", "splitlines", "(", ")", "rdf_xml_dict", "=", "{", "}", "for", "sentence", "in"...
Get extractions from one of the examples in `cag_examples`.
[ "Get", "extractions", "from", "one", "of", "the", "examples", "in", "cag_examples", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/cwms/util.py#L63-L77
19,359
sorgerlab/indra
indra/sources/cwms/util.py
make_example_graphs
def make_example_graphs(): "Make graphs from all the examples in cag_examples." cag_example_rdfs = {} for i, fname in enumerate(os.listdir('cag_examples')): cag_example_rdfs[i+1] = get_example_extractions(fname) return make_cag_graphs(cag_example_rdfs)
python
def make_example_graphs(): "Make graphs from all the examples in cag_examples." cag_example_rdfs = {} for i, fname in enumerate(os.listdir('cag_examples')): cag_example_rdfs[i+1] = get_example_extractions(fname) return make_cag_graphs(cag_example_rdfs)
[ "def", "make_example_graphs", "(", ")", ":", "cag_example_rdfs", "=", "{", "}", "for", "i", ",", "fname", "in", "enumerate", "(", "os", ".", "listdir", "(", "'cag_examples'", ")", ")", ":", "cag_example_rdfs", "[", "i", "+", "1", "]", "=", "get_example_e...
Make graphs from all the examples in cag_examples.
[ "Make", "graphs", "from", "all", "the", "examples", "in", "cag_examples", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/cwms/util.py#L80-L85
19,360
sorgerlab/indra
indra/assemblers/english/assembler.py
_join_list
def _join_list(lst, oxford=False): """Join a list of words in a gramatically correct way.""" if len(lst) > 2: s = ', '.join(lst[:-1]) if oxford: s += ',' s += ' and ' + lst[-1] elif len(lst) == 2: s = lst[0] + ' and ' + lst[1] elif len(lst) == 1: s = lst[0] else: s = '' return s
python
def _join_list(lst, oxford=False): if len(lst) > 2: s = ', '.join(lst[:-1]) if oxford: s += ',' s += ' and ' + lst[-1] elif len(lst) == 2: s = lst[0] + ' and ' + lst[1] elif len(lst) == 1: s = lst[0] else: s = '' return s
[ "def", "_join_list", "(", "lst", ",", "oxford", "=", "False", ")", ":", "if", "len", "(", "lst", ")", ">", "2", ":", "s", "=", "', '", ".", "join", "(", "lst", "[", ":", "-", "1", "]", ")", "if", "oxford", ":", "s", "+=", "','", "s", "+=", ...
Join a list of words in a gramatically correct way.
[ "Join", "a", "list", "of", "words", "in", "a", "gramatically", "correct", "way", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/english/assembler.py#L184-L197
19,361
sorgerlab/indra
indra/assemblers/english/assembler.py
_assemble_activeform
def _assemble_activeform(stmt): """Assemble ActiveForm statements into text.""" subj_str = _assemble_agent_str(stmt.agent) if stmt.is_active: is_active_str = 'active' else: is_active_str = 'inactive' if stmt.activity == 'activity': stmt_str = subj_str + ' is ' + is_active_str elif stmt.activity == 'kinase': stmt_str = subj_str + ' is kinase-' + is_active_str elif stmt.activity == 'phosphatase': stmt_str = subj_str + ' is phosphatase-' + is_active_str elif stmt.activity == 'catalytic': stmt_str = subj_str + ' is catalytically ' + is_active_str elif stmt.activity == 'transcription': stmt_str = subj_str + ' is transcriptionally ' + is_active_str elif stmt.activity == 'gtpbound': stmt_str = subj_str + ' is GTP-bound ' + is_active_str return _make_sentence(stmt_str)
python
def _assemble_activeform(stmt): subj_str = _assemble_agent_str(stmt.agent) if stmt.is_active: is_active_str = 'active' else: is_active_str = 'inactive' if stmt.activity == 'activity': stmt_str = subj_str + ' is ' + is_active_str elif stmt.activity == 'kinase': stmt_str = subj_str + ' is kinase-' + is_active_str elif stmt.activity == 'phosphatase': stmt_str = subj_str + ' is phosphatase-' + is_active_str elif stmt.activity == 'catalytic': stmt_str = subj_str + ' is catalytically ' + is_active_str elif stmt.activity == 'transcription': stmt_str = subj_str + ' is transcriptionally ' + is_active_str elif stmt.activity == 'gtpbound': stmt_str = subj_str + ' is GTP-bound ' + is_active_str return _make_sentence(stmt_str)
[ "def", "_assemble_activeform", "(", "stmt", ")", ":", "subj_str", "=", "_assemble_agent_str", "(", "stmt", ".", "agent", ")", "if", "stmt", ".", "is_active", ":", "is_active_str", "=", "'active'", "else", ":", "is_active_str", "=", "'inactive'", "if", "stmt", ...
Assemble ActiveForm statements into text.
[ "Assemble", "ActiveForm", "statements", "into", "text", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/english/assembler.py#L200-L219
19,362
sorgerlab/indra
indra/assemblers/english/assembler.py
_assemble_modification
def _assemble_modification(stmt): """Assemble Modification statements into text.""" sub_str = _assemble_agent_str(stmt.sub) if stmt.enz is not None: enz_str = _assemble_agent_str(stmt.enz) if _get_is_direct(stmt): mod_str = ' ' + _mod_process_verb(stmt) + ' ' else: mod_str = ' leads to the ' + _mod_process_noun(stmt) + ' of ' stmt_str = enz_str + mod_str + sub_str else: stmt_str = sub_str + ' is ' + _mod_state_stmt(stmt) if stmt.residue is not None: if stmt.position is None: mod_str = 'on ' + ist.amino_acids[stmt.residue]['full_name'] else: mod_str = 'on ' + stmt.residue + stmt.position else: mod_str = '' stmt_str += ' ' + mod_str return _make_sentence(stmt_str)
python
def _assemble_modification(stmt): sub_str = _assemble_agent_str(stmt.sub) if stmt.enz is not None: enz_str = _assemble_agent_str(stmt.enz) if _get_is_direct(stmt): mod_str = ' ' + _mod_process_verb(stmt) + ' ' else: mod_str = ' leads to the ' + _mod_process_noun(stmt) + ' of ' stmt_str = enz_str + mod_str + sub_str else: stmt_str = sub_str + ' is ' + _mod_state_stmt(stmt) if stmt.residue is not None: if stmt.position is None: mod_str = 'on ' + ist.amino_acids[stmt.residue]['full_name'] else: mod_str = 'on ' + stmt.residue + stmt.position else: mod_str = '' stmt_str += ' ' + mod_str return _make_sentence(stmt_str)
[ "def", "_assemble_modification", "(", "stmt", ")", ":", "sub_str", "=", "_assemble_agent_str", "(", "stmt", ".", "sub", ")", "if", "stmt", ".", "enz", "is", "not", "None", ":", "enz_str", "=", "_assemble_agent_str", "(", "stmt", ".", "enz", ")", "if", "_...
Assemble Modification statements into text.
[ "Assemble", "Modification", "statements", "into", "text", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/english/assembler.py#L222-L243
19,363
sorgerlab/indra
indra/assemblers/english/assembler.py
_assemble_association
def _assemble_association(stmt): """Assemble Association statements into text.""" member_strs = [_assemble_agent_str(m.concept) for m in stmt.members] stmt_str = member_strs[0] + ' is associated with ' + \ _join_list(member_strs[1:]) return _make_sentence(stmt_str)
python
def _assemble_association(stmt): member_strs = [_assemble_agent_str(m.concept) for m in stmt.members] stmt_str = member_strs[0] + ' is associated with ' + \ _join_list(member_strs[1:]) return _make_sentence(stmt_str)
[ "def", "_assemble_association", "(", "stmt", ")", ":", "member_strs", "=", "[", "_assemble_agent_str", "(", "m", ".", "concept", ")", "for", "m", "in", "stmt", ".", "members", "]", "stmt_str", "=", "member_strs", "[", "0", "]", "+", "' is associated with '",...
Assemble Association statements into text.
[ "Assemble", "Association", "statements", "into", "text", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/english/assembler.py#L246-L251
19,364
sorgerlab/indra
indra/assemblers/english/assembler.py
_assemble_complex
def _assemble_complex(stmt): """Assemble Complex statements into text.""" member_strs = [_assemble_agent_str(m) for m in stmt.members] stmt_str = member_strs[0] + ' binds ' + _join_list(member_strs[1:]) return _make_sentence(stmt_str)
python
def _assemble_complex(stmt): member_strs = [_assemble_agent_str(m) for m in stmt.members] stmt_str = member_strs[0] + ' binds ' + _join_list(member_strs[1:]) return _make_sentence(stmt_str)
[ "def", "_assemble_complex", "(", "stmt", ")", ":", "member_strs", "=", "[", "_assemble_agent_str", "(", "m", ")", "for", "m", "in", "stmt", ".", "members", "]", "stmt_str", "=", "member_strs", "[", "0", "]", "+", "' binds '", "+", "_join_list", "(", "mem...
Assemble Complex statements into text.
[ "Assemble", "Complex", "statements", "into", "text", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/english/assembler.py#L254-L258
19,365
sorgerlab/indra
indra/assemblers/english/assembler.py
_assemble_autophosphorylation
def _assemble_autophosphorylation(stmt): """Assemble Autophosphorylation statements into text.""" enz_str = _assemble_agent_str(stmt.enz) stmt_str = enz_str + ' phosphorylates itself' if stmt.residue is not None: if stmt.position is None: mod_str = 'on ' + ist.amino_acids[stmt.residue]['full_name'] else: mod_str = 'on ' + stmt.residue + stmt.position else: mod_str = '' stmt_str += ' ' + mod_str return _make_sentence(stmt_str)
python
def _assemble_autophosphorylation(stmt): enz_str = _assemble_agent_str(stmt.enz) stmt_str = enz_str + ' phosphorylates itself' if stmt.residue is not None: if stmt.position is None: mod_str = 'on ' + ist.amino_acids[stmt.residue]['full_name'] else: mod_str = 'on ' + stmt.residue + stmt.position else: mod_str = '' stmt_str += ' ' + mod_str return _make_sentence(stmt_str)
[ "def", "_assemble_autophosphorylation", "(", "stmt", ")", ":", "enz_str", "=", "_assemble_agent_str", "(", "stmt", ".", "enz", ")", "stmt_str", "=", "enz_str", "+", "' phosphorylates itself'", "if", "stmt", ".", "residue", "is", "not", "None", ":", "if", "stmt...
Assemble Autophosphorylation statements into text.
[ "Assemble", "Autophosphorylation", "statements", "into", "text", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/english/assembler.py#L261-L273
19,366
sorgerlab/indra
indra/assemblers/english/assembler.py
_assemble_regulate_activity
def _assemble_regulate_activity(stmt): """Assemble RegulateActivity statements into text.""" subj_str = _assemble_agent_str(stmt.subj) obj_str = _assemble_agent_str(stmt.obj) if stmt.is_activation: rel_str = ' activates ' else: rel_str = ' inhibits ' stmt_str = subj_str + rel_str + obj_str return _make_sentence(stmt_str)
python
def _assemble_regulate_activity(stmt): subj_str = _assemble_agent_str(stmt.subj) obj_str = _assemble_agent_str(stmt.obj) if stmt.is_activation: rel_str = ' activates ' else: rel_str = ' inhibits ' stmt_str = subj_str + rel_str + obj_str return _make_sentence(stmt_str)
[ "def", "_assemble_regulate_activity", "(", "stmt", ")", ":", "subj_str", "=", "_assemble_agent_str", "(", "stmt", ".", "subj", ")", "obj_str", "=", "_assemble_agent_str", "(", "stmt", ".", "obj", ")", "if", "stmt", ".", "is_activation", ":", "rel_str", "=", ...
Assemble RegulateActivity statements into text.
[ "Assemble", "RegulateActivity", "statements", "into", "text", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/english/assembler.py#L276-L285
19,367
sorgerlab/indra
indra/assemblers/english/assembler.py
_assemble_regulate_amount
def _assemble_regulate_amount(stmt): """Assemble RegulateAmount statements into text.""" obj_str = _assemble_agent_str(stmt.obj) if stmt.subj is not None: subj_str = _assemble_agent_str(stmt.subj) if isinstance(stmt, ist.IncreaseAmount): rel_str = ' increases the amount of ' elif isinstance(stmt, ist.DecreaseAmount): rel_str = ' decreases the amount of ' stmt_str = subj_str + rel_str + obj_str else: if isinstance(stmt, ist.IncreaseAmount): stmt_str = obj_str + ' is produced' elif isinstance(stmt, ist.DecreaseAmount): stmt_str = obj_str + ' is degraded' return _make_sentence(stmt_str)
python
def _assemble_regulate_amount(stmt): obj_str = _assemble_agent_str(stmt.obj) if stmt.subj is not None: subj_str = _assemble_agent_str(stmt.subj) if isinstance(stmt, ist.IncreaseAmount): rel_str = ' increases the amount of ' elif isinstance(stmt, ist.DecreaseAmount): rel_str = ' decreases the amount of ' stmt_str = subj_str + rel_str + obj_str else: if isinstance(stmt, ist.IncreaseAmount): stmt_str = obj_str + ' is produced' elif isinstance(stmt, ist.DecreaseAmount): stmt_str = obj_str + ' is degraded' return _make_sentence(stmt_str)
[ "def", "_assemble_regulate_amount", "(", "stmt", ")", ":", "obj_str", "=", "_assemble_agent_str", "(", "stmt", ".", "obj", ")", "if", "stmt", ".", "subj", "is", "not", "None", ":", "subj_str", "=", "_assemble_agent_str", "(", "stmt", ".", "subj", ")", "if"...
Assemble RegulateAmount statements into text.
[ "Assemble", "RegulateAmount", "statements", "into", "text", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/english/assembler.py#L288-L303
19,368
sorgerlab/indra
indra/assemblers/english/assembler.py
_assemble_translocation
def _assemble_translocation(stmt): """Assemble Translocation statements into text.""" agent_str = _assemble_agent_str(stmt.agent) stmt_str = agent_str + ' translocates' if stmt.from_location is not None: stmt_str += ' from the ' + stmt.from_location if stmt.to_location is not None: stmt_str += ' to the ' + stmt.to_location return _make_sentence(stmt_str)
python
def _assemble_translocation(stmt): agent_str = _assemble_agent_str(stmt.agent) stmt_str = agent_str + ' translocates' if stmt.from_location is not None: stmt_str += ' from the ' + stmt.from_location if stmt.to_location is not None: stmt_str += ' to the ' + stmt.to_location return _make_sentence(stmt_str)
[ "def", "_assemble_translocation", "(", "stmt", ")", ":", "agent_str", "=", "_assemble_agent_str", "(", "stmt", ".", "agent", ")", "stmt_str", "=", "agent_str", "+", "' translocates'", "if", "stmt", ".", "from_location", "is", "not", "None", ":", "stmt_str", "+...
Assemble Translocation statements into text.
[ "Assemble", "Translocation", "statements", "into", "text", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/english/assembler.py#L306-L314
19,369
sorgerlab/indra
indra/assemblers/english/assembler.py
_assemble_gap
def _assemble_gap(stmt): """Assemble Gap statements into text.""" subj_str = _assemble_agent_str(stmt.gap) obj_str = _assemble_agent_str(stmt.ras) stmt_str = subj_str + ' is a GAP for ' + obj_str return _make_sentence(stmt_str)
python
def _assemble_gap(stmt): subj_str = _assemble_agent_str(stmt.gap) obj_str = _assemble_agent_str(stmt.ras) stmt_str = subj_str + ' is a GAP for ' + obj_str return _make_sentence(stmt_str)
[ "def", "_assemble_gap", "(", "stmt", ")", ":", "subj_str", "=", "_assemble_agent_str", "(", "stmt", ".", "gap", ")", "obj_str", "=", "_assemble_agent_str", "(", "stmt", ".", "ras", ")", "stmt_str", "=", "subj_str", "+", "' is a GAP for '", "+", "obj_str", "r...
Assemble Gap statements into text.
[ "Assemble", "Gap", "statements", "into", "text", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/english/assembler.py#L317-L322
19,370
sorgerlab/indra
indra/assemblers/english/assembler.py
_assemble_gef
def _assemble_gef(stmt): """Assemble Gef statements into text.""" subj_str = _assemble_agent_str(stmt.gef) obj_str = _assemble_agent_str(stmt.ras) stmt_str = subj_str + ' is a GEF for ' + obj_str return _make_sentence(stmt_str)
python
def _assemble_gef(stmt): subj_str = _assemble_agent_str(stmt.gef) obj_str = _assemble_agent_str(stmt.ras) stmt_str = subj_str + ' is a GEF for ' + obj_str return _make_sentence(stmt_str)
[ "def", "_assemble_gef", "(", "stmt", ")", ":", "subj_str", "=", "_assemble_agent_str", "(", "stmt", ".", "gef", ")", "obj_str", "=", "_assemble_agent_str", "(", "stmt", ".", "ras", ")", "stmt_str", "=", "subj_str", "+", "' is a GEF for '", "+", "obj_str", "r...
Assemble Gef statements into text.
[ "Assemble", "Gef", "statements", "into", "text", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/english/assembler.py#L325-L330
19,371
sorgerlab/indra
indra/assemblers/english/assembler.py
_assemble_conversion
def _assemble_conversion(stmt): """Assemble a Conversion statement into text.""" reactants = _join_list([_assemble_agent_str(r) for r in stmt.obj_from]) products = _join_list([_assemble_agent_str(r) for r in stmt.obj_to]) if stmt.subj is not None: subj_str = _assemble_agent_str(stmt.subj) stmt_str = '%s catalyzes the conversion of %s into %s' % \ (subj_str, reactants, products) else: stmt_str = '%s is converted into %s' % (reactants, products) return _make_sentence(stmt_str)
python
def _assemble_conversion(stmt): reactants = _join_list([_assemble_agent_str(r) for r in stmt.obj_from]) products = _join_list([_assemble_agent_str(r) for r in stmt.obj_to]) if stmt.subj is not None: subj_str = _assemble_agent_str(stmt.subj) stmt_str = '%s catalyzes the conversion of %s into %s' % \ (subj_str, reactants, products) else: stmt_str = '%s is converted into %s' % (reactants, products) return _make_sentence(stmt_str)
[ "def", "_assemble_conversion", "(", "stmt", ")", ":", "reactants", "=", "_join_list", "(", "[", "_assemble_agent_str", "(", "r", ")", "for", "r", "in", "stmt", ".", "obj_from", "]", ")", "products", "=", "_join_list", "(", "[", "_assemble_agent_str", "(", ...
Assemble a Conversion statement into text.
[ "Assemble", "a", "Conversion", "statement", "into", "text", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/english/assembler.py#L333-L344
19,372
sorgerlab/indra
indra/assemblers/english/assembler.py
_assemble_influence
def _assemble_influence(stmt): """Assemble an Influence statement into text.""" subj_str = _assemble_agent_str(stmt.subj.concept) obj_str = _assemble_agent_str(stmt.obj.concept) # Note that n is prepended to increase to make it "an increase" if stmt.subj.delta['polarity'] is not None: subj_delta_str = ' decrease' if stmt.subj.delta['polarity'] == -1 \ else 'n increase' subj_str = 'a%s in %s' % (subj_delta_str, subj_str) if stmt.obj.delta['polarity'] is not None: obj_delta_str = ' decrease' if stmt.obj.delta['polarity'] == -1 \ else 'n increase' obj_str = 'a%s in %s' % (obj_delta_str, obj_str) stmt_str = '%s causes %s' % (subj_str, obj_str) return _make_sentence(stmt_str)
python
def _assemble_influence(stmt): subj_str = _assemble_agent_str(stmt.subj.concept) obj_str = _assemble_agent_str(stmt.obj.concept) # Note that n is prepended to increase to make it "an increase" if stmt.subj.delta['polarity'] is not None: subj_delta_str = ' decrease' if stmt.subj.delta['polarity'] == -1 \ else 'n increase' subj_str = 'a%s in %s' % (subj_delta_str, subj_str) if stmt.obj.delta['polarity'] is not None: obj_delta_str = ' decrease' if stmt.obj.delta['polarity'] == -1 \ else 'n increase' obj_str = 'a%s in %s' % (obj_delta_str, obj_str) stmt_str = '%s causes %s' % (subj_str, obj_str) return _make_sentence(stmt_str)
[ "def", "_assemble_influence", "(", "stmt", ")", ":", "subj_str", "=", "_assemble_agent_str", "(", "stmt", ".", "subj", ".", "concept", ")", "obj_str", "=", "_assemble_agent_str", "(", "stmt", ".", "obj", ".", "concept", ")", "# Note that n is prepended to increase...
Assemble an Influence statement into text.
[ "Assemble", "an", "Influence", "statement", "into", "text", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/english/assembler.py#L347-L364
19,373
sorgerlab/indra
indra/assemblers/english/assembler.py
_make_sentence
def _make_sentence(txt): """Make a sentence from a piece of text.""" #Make sure first letter is capitalized txt = txt.strip(' ') txt = txt[0].upper() + txt[1:] + '.' return txt
python
def _make_sentence(txt): #Make sure first letter is capitalized txt = txt.strip(' ') txt = txt[0].upper() + txt[1:] + '.' return txt
[ "def", "_make_sentence", "(", "txt", ")", ":", "#Make sure first letter is capitalized", "txt", "=", "txt", ".", "strip", "(", "' '", ")", "txt", "=", "txt", "[", "0", "]", ".", "upper", "(", ")", "+", "txt", "[", "1", ":", "]", "+", "'.'", "return",...
Make a sentence from a piece of text.
[ "Make", "a", "sentence", "from", "a", "piece", "of", "text", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/english/assembler.py#L367-L372
19,374
sorgerlab/indra
indra/assemblers/english/assembler.py
_get_is_hypothesis
def _get_is_hypothesis(stmt): '''Returns true if there is evidence that the statement is only hypothetical. If all of the evidences associated with the statement indicate a hypothetical interaction then we assume the interaction is hypothetical.''' for ev in stmt.evidence: if not ev.epistemics.get('hypothesis') is True: return True return False
python
def _get_is_hypothesis(stmt): '''Returns true if there is evidence that the statement is only hypothetical. If all of the evidences associated with the statement indicate a hypothetical interaction then we assume the interaction is hypothetical.''' for ev in stmt.evidence: if not ev.epistemics.get('hypothesis') is True: return True return False
[ "def", "_get_is_hypothesis", "(", "stmt", ")", ":", "for", "ev", "in", "stmt", ".", "evidence", ":", "if", "not", "ev", ".", "epistemics", ".", "get", "(", "'hypothesis'", ")", "is", "True", ":", "return", "True", "return", "False" ]
Returns true if there is evidence that the statement is only hypothetical. If all of the evidences associated with the statement indicate a hypothetical interaction then we assume the interaction is hypothetical.
[ "Returns", "true", "if", "there", "is", "evidence", "that", "the", "statement", "is", "only", "hypothetical", ".", "If", "all", "of", "the", "evidences", "associated", "with", "the", "statement", "indicate", "a", "hypothetical", "interaction", "then", "we", "a...
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/english/assembler.py#L394-L402
19,375
sorgerlab/indra
indra/assemblers/english/assembler.py
EnglishAssembler.make_model
def make_model(self): """Assemble text from the set of collected INDRA Statements. Returns ------- stmt_strs : str Return the assembled text as unicode string. By default, the text is a single string consisting of one or more sentences with periods at the end. """ stmt_strs = [] for stmt in self.statements: if isinstance(stmt, ist.Modification): stmt_strs.append(_assemble_modification(stmt)) elif isinstance(stmt, ist.Autophosphorylation): stmt_strs.append(_assemble_autophosphorylation(stmt)) elif isinstance(stmt, ist.Association): stmt_strs.append(_assemble_association(stmt)) elif isinstance(stmt, ist.Complex): stmt_strs.append(_assemble_complex(stmt)) elif isinstance(stmt, ist.Influence): stmt_strs.append(_assemble_influence(stmt)) elif isinstance(stmt, ist.RegulateActivity): stmt_strs.append(_assemble_regulate_activity(stmt)) elif isinstance(stmt, ist.RegulateAmount): stmt_strs.append(_assemble_regulate_amount(stmt)) elif isinstance(stmt, ist.ActiveForm): stmt_strs.append(_assemble_activeform(stmt)) elif isinstance(stmt, ist.Translocation): stmt_strs.append(_assemble_translocation(stmt)) elif isinstance(stmt, ist.Gef): stmt_strs.append(_assemble_gef(stmt)) elif isinstance(stmt, ist.Gap): stmt_strs.append(_assemble_gap(stmt)) elif isinstance(stmt, ist.Conversion): stmt_strs.append(_assemble_conversion(stmt)) else: logger.warning('Unhandled statement type: %s.' % type(stmt)) if stmt_strs: return ' '.join(stmt_strs) else: return ''
python
def make_model(self): stmt_strs = [] for stmt in self.statements: if isinstance(stmt, ist.Modification): stmt_strs.append(_assemble_modification(stmt)) elif isinstance(stmt, ist.Autophosphorylation): stmt_strs.append(_assemble_autophosphorylation(stmt)) elif isinstance(stmt, ist.Association): stmt_strs.append(_assemble_association(stmt)) elif isinstance(stmt, ist.Complex): stmt_strs.append(_assemble_complex(stmt)) elif isinstance(stmt, ist.Influence): stmt_strs.append(_assemble_influence(stmt)) elif isinstance(stmt, ist.RegulateActivity): stmt_strs.append(_assemble_regulate_activity(stmt)) elif isinstance(stmt, ist.RegulateAmount): stmt_strs.append(_assemble_regulate_amount(stmt)) elif isinstance(stmt, ist.ActiveForm): stmt_strs.append(_assemble_activeform(stmt)) elif isinstance(stmt, ist.Translocation): stmt_strs.append(_assemble_translocation(stmt)) elif isinstance(stmt, ist.Gef): stmt_strs.append(_assemble_gef(stmt)) elif isinstance(stmt, ist.Gap): stmt_strs.append(_assemble_gap(stmt)) elif isinstance(stmt, ist.Conversion): stmt_strs.append(_assemble_conversion(stmt)) else: logger.warning('Unhandled statement type: %s.' % type(stmt)) if stmt_strs: return ' '.join(stmt_strs) else: return ''
[ "def", "make_model", "(", "self", ")", ":", "stmt_strs", "=", "[", "]", "for", "stmt", "in", "self", ".", "statements", ":", "if", "isinstance", "(", "stmt", ",", "ist", ".", "Modification", ")", ":", "stmt_strs", ".", "append", "(", "_assemble_modificat...
Assemble text from the set of collected INDRA Statements. Returns ------- stmt_strs : str Return the assembled text as unicode string. By default, the text is a single string consisting of one or more sentences with periods at the end.
[ "Assemble", "text", "from", "the", "set", "of", "collected", "INDRA", "Statements", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/english/assembler.py#L41-L82
19,376
sorgerlab/indra
indra/assemblers/sbgn/assembler.py
SBGNAssembler.add_statements
def add_statements(self, stmts): """Add INDRA Statements to the assembler's list of statements. Parameters ---------- stmts : list[indra.statements.Statement] A list of :py:class:`indra.statements.Statement` to be added to the statement list of the assembler. """ for stmt in stmts: if not self.statement_exists(stmt): self.statements.append(stmt)
python
def add_statements(self, stmts): for stmt in stmts: if not self.statement_exists(stmt): self.statements.append(stmt)
[ "def", "add_statements", "(", "self", ",", "stmts", ")", ":", "for", "stmt", "in", "stmts", ":", "if", "not", "self", ".", "statement_exists", "(", "stmt", ")", ":", "self", ".", "statements", ".", "append", "(", "stmt", ")" ]
Add INDRA Statements to the assembler's list of statements. Parameters ---------- stmts : list[indra.statements.Statement] A list of :py:class:`indra.statements.Statement` to be added to the statement list of the assembler.
[ "Add", "INDRA", "Statements", "to", "the", "assembler", "s", "list", "of", "statements", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/sbgn/assembler.py#L58-L69
19,377
sorgerlab/indra
indra/assemblers/sbgn/assembler.py
SBGNAssembler.make_model
def make_model(self): """Assemble the SBGN model from the collected INDRA Statements. This method assembles an SBGN model from the set of INDRA Statements. The assembled model is set as the assembler's sbgn attribute (it is represented as an XML ElementTree internally). The model is returned as a serialized XML string. Returns ------- sbgn_str : str The XML serialized SBGN model. """ ppa = PysbPreassembler(self.statements) ppa.replace_activities() self.statements = ppa.statements self.sbgn = emaker.sbgn() self._map = emaker.map() self.sbgn.append(self._map) for stmt in self.statements: if isinstance(stmt, Modification): self._assemble_modification(stmt) elif isinstance(stmt, RegulateActivity): self._assemble_regulateactivity(stmt) elif isinstance(stmt, RegulateAmount): self._assemble_regulateamount(stmt) elif isinstance(stmt, Complex): self._assemble_complex(stmt) elif isinstance(stmt, ActiveForm): #self._assemble_activeform(stmt) pass else: logger.warning("Unhandled Statement type %s" % type(stmt)) continue sbgn_str = self.print_model() return sbgn_str
python
def make_model(self): ppa = PysbPreassembler(self.statements) ppa.replace_activities() self.statements = ppa.statements self.sbgn = emaker.sbgn() self._map = emaker.map() self.sbgn.append(self._map) for stmt in self.statements: if isinstance(stmt, Modification): self._assemble_modification(stmt) elif isinstance(stmt, RegulateActivity): self._assemble_regulateactivity(stmt) elif isinstance(stmt, RegulateAmount): self._assemble_regulateamount(stmt) elif isinstance(stmt, Complex): self._assemble_complex(stmt) elif isinstance(stmt, ActiveForm): #self._assemble_activeform(stmt) pass else: logger.warning("Unhandled Statement type %s" % type(stmt)) continue sbgn_str = self.print_model() return sbgn_str
[ "def", "make_model", "(", "self", ")", ":", "ppa", "=", "PysbPreassembler", "(", "self", ".", "statements", ")", "ppa", ".", "replace_activities", "(", ")", "self", ".", "statements", "=", "ppa", ".", "statements", "self", ".", "sbgn", "=", "emaker", "."...
Assemble the SBGN model from the collected INDRA Statements. This method assembles an SBGN model from the set of INDRA Statements. The assembled model is set as the assembler's sbgn attribute (it is represented as an XML ElementTree internally). The model is returned as a serialized XML string. Returns ------- sbgn_str : str The XML serialized SBGN model.
[ "Assemble", "the", "SBGN", "model", "from", "the", "collected", "INDRA", "Statements", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/sbgn/assembler.py#L71-L106
19,378
sorgerlab/indra
indra/assemblers/sbgn/assembler.py
SBGNAssembler.print_model
def print_model(self, pretty=True, encoding='utf8'): """Return the assembled SBGN model as an XML string. Parameters ---------- pretty : Optional[bool] If True, the SBGN string is formatted with indentation (for human viewing) otherwise no indentation is used. Default: True Returns ------- sbgn_str : bytes (str in Python 2) An XML string representation of the SBGN model. """ return lxml.etree.tostring(self.sbgn, pretty_print=pretty, encoding=encoding, xml_declaration=True)
python
def print_model(self, pretty=True, encoding='utf8'): return lxml.etree.tostring(self.sbgn, pretty_print=pretty, encoding=encoding, xml_declaration=True)
[ "def", "print_model", "(", "self", ",", "pretty", "=", "True", ",", "encoding", "=", "'utf8'", ")", ":", "return", "lxml", ".", "etree", ".", "tostring", "(", "self", ".", "sbgn", ",", "pretty_print", "=", "pretty", ",", "encoding", "=", "encoding", ",...
Return the assembled SBGN model as an XML string. Parameters ---------- pretty : Optional[bool] If True, the SBGN string is formatted with indentation (for human viewing) otherwise no indentation is used. Default: True Returns ------- sbgn_str : bytes (str in Python 2) An XML string representation of the SBGN model.
[ "Return", "the", "assembled", "SBGN", "model", "as", "an", "XML", "string", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/sbgn/assembler.py#L108-L123
19,379
sorgerlab/indra
indra/assemblers/sbgn/assembler.py
SBGNAssembler.save_model
def save_model(self, file_name='model.sbgn'): """Save the assembled SBGN model in a file. Parameters ---------- file_name : Optional[str] The name of the file to save the SBGN network to. Default: model.sbgn """ model = self.print_model() with open(file_name, 'wb') as fh: fh.write(model)
python
def save_model(self, file_name='model.sbgn'): model = self.print_model() with open(file_name, 'wb') as fh: fh.write(model)
[ "def", "save_model", "(", "self", ",", "file_name", "=", "'model.sbgn'", ")", ":", "model", "=", "self", ".", "print_model", "(", ")", "with", "open", "(", "file_name", ",", "'wb'", ")", "as", "fh", ":", "fh", ".", "write", "(", "model", ")" ]
Save the assembled SBGN model in a file. Parameters ---------- file_name : Optional[str] The name of the file to save the SBGN network to. Default: model.sbgn
[ "Save", "the", "assembled", "SBGN", "model", "in", "a", "file", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/sbgn/assembler.py#L125-L136
19,380
sorgerlab/indra
indra/assemblers/sbgn/assembler.py
SBGNAssembler._glyph_for_complex_pattern
def _glyph_for_complex_pattern(self, pattern): """Add glyph and member glyphs for a PySB ComplexPattern.""" # Make the main glyph for the agent monomer_glyphs = [] for monomer_pattern in pattern.monomer_patterns: glyph = self._glyph_for_monomer_pattern(monomer_pattern) monomer_glyphs.append(glyph) if len(monomer_glyphs) > 1: pattern.matches_key = lambda: str(pattern) agent_id = self._make_agent_id(pattern) complex_glyph = \ emaker.glyph(emaker.bbox(**self.complex_style), class_('complex'), id=agent_id) for glyph in monomer_glyphs: glyph.attrib['id'] = agent_id + glyph.attrib['id'] complex_glyph.append(glyph) return complex_glyph return monomer_glyphs[0]
python
def _glyph_for_complex_pattern(self, pattern): # Make the main glyph for the agent monomer_glyphs = [] for monomer_pattern in pattern.monomer_patterns: glyph = self._glyph_for_monomer_pattern(monomer_pattern) monomer_glyphs.append(glyph) if len(monomer_glyphs) > 1: pattern.matches_key = lambda: str(pattern) agent_id = self._make_agent_id(pattern) complex_glyph = \ emaker.glyph(emaker.bbox(**self.complex_style), class_('complex'), id=agent_id) for glyph in monomer_glyphs: glyph.attrib['id'] = agent_id + glyph.attrib['id'] complex_glyph.append(glyph) return complex_glyph return monomer_glyphs[0]
[ "def", "_glyph_for_complex_pattern", "(", "self", ",", "pattern", ")", ":", "# Make the main glyph for the agent", "monomer_glyphs", "=", "[", "]", "for", "monomer_pattern", "in", "pattern", ".", "monomer_patterns", ":", "glyph", "=", "self", ".", "_glyph_for_monomer_...
Add glyph and member glyphs for a PySB ComplexPattern.
[ "Add", "glyph", "and", "member", "glyphs", "for", "a", "PySB", "ComplexPattern", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/sbgn/assembler.py#L317-L335
19,381
sorgerlab/indra
indra/assemblers/sbgn/assembler.py
SBGNAssembler._glyph_for_monomer_pattern
def _glyph_for_monomer_pattern(self, pattern): """Add glyph for a PySB MonomerPattern.""" pattern.matches_key = lambda: str(pattern) agent_id = self._make_agent_id(pattern) # Handle sources and sinks if pattern.monomer.name in ('__source', '__sink'): return None # Handle molecules glyph = emaker.glyph(emaker.label(text=pattern.monomer.name), emaker.bbox(**self.monomer_style), class_('macromolecule'), id=agent_id) # Temporarily remove this # Add a glyph for type #type_glyph = emaker.glyph(emaker.label(text='mt:prot'), # class_('unit of information'), # emaker.bbox(**self.entity_type_style), # id=self._make_id()) #glyph.append(type_glyph) for site, value in pattern.site_conditions.items(): if value is None or isinstance(value, int): continue # Make some common abbreviations if site == 'phospho': site = 'p' elif site == 'activity': site = 'act' if value == 'active': value = 'a' elif value == 'inactive': value = 'i' state = emaker.state(variable=site, value=value) state_glyph = \ emaker.glyph(state, emaker.bbox(**self.entity_state_style), class_('state variable'), id=self._make_id()) glyph.append(state_glyph) return glyph
python
def _glyph_for_monomer_pattern(self, pattern): pattern.matches_key = lambda: str(pattern) agent_id = self._make_agent_id(pattern) # Handle sources and sinks if pattern.monomer.name in ('__source', '__sink'): return None # Handle molecules glyph = emaker.glyph(emaker.label(text=pattern.monomer.name), emaker.bbox(**self.monomer_style), class_('macromolecule'), id=agent_id) # Temporarily remove this # Add a glyph for type #type_glyph = emaker.glyph(emaker.label(text='mt:prot'), # class_('unit of information'), # emaker.bbox(**self.entity_type_style), # id=self._make_id()) #glyph.append(type_glyph) for site, value in pattern.site_conditions.items(): if value is None or isinstance(value, int): continue # Make some common abbreviations if site == 'phospho': site = 'p' elif site == 'activity': site = 'act' if value == 'active': value = 'a' elif value == 'inactive': value = 'i' state = emaker.state(variable=site, value=value) state_glyph = \ emaker.glyph(state, emaker.bbox(**self.entity_state_style), class_('state variable'), id=self._make_id()) glyph.append(state_glyph) return glyph
[ "def", "_glyph_for_monomer_pattern", "(", "self", ",", "pattern", ")", ":", "pattern", ".", "matches_key", "=", "lambda", ":", "str", "(", "pattern", ")", "agent_id", "=", "self", ".", "_make_agent_id", "(", "pattern", ")", "# Handle sources and sinks", "if", ...
Add glyph for a PySB MonomerPattern.
[ "Add", "glyph", "for", "a", "PySB", "MonomerPattern", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/sbgn/assembler.py#L337-L372
19,382
sorgerlab/indra
indra/databases/go_client.py
load_go_graph
def load_go_graph(go_fname): """Load the GO data from an OWL file and parse into an RDF graph. Parameters ---------- go_fname : str Path to the GO OWL file. Can be downloaded from http://geneontology.org/ontology/go.owl. Returns ------- rdflib.Graph RDF graph containing GO data. """ global _go_graph if _go_graph is None: _go_graph = rdflib.Graph() logger.info("Parsing GO OWL file") _go_graph.parse(os.path.abspath(go_fname)) return _go_graph
python
def load_go_graph(go_fname): global _go_graph if _go_graph is None: _go_graph = rdflib.Graph() logger.info("Parsing GO OWL file") _go_graph.parse(os.path.abspath(go_fname)) return _go_graph
[ "def", "load_go_graph", "(", "go_fname", ")", ":", "global", "_go_graph", "if", "_go_graph", "is", "None", ":", "_go_graph", "=", "rdflib", ".", "Graph", "(", ")", "logger", ".", "info", "(", "\"Parsing GO OWL file\"", ")", "_go_graph", ".", "parse", "(", ...
Load the GO data from an OWL file and parse into an RDF graph. Parameters ---------- go_fname : str Path to the GO OWL file. Can be downloaded from http://geneontology.org/ontology/go.owl. Returns ------- rdflib.Graph RDF graph containing GO data.
[ "Load", "the", "GO", "data", "from", "an", "OWL", "file", "and", "parse", "into", "an", "RDF", "graph", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/databases/go_client.py#L41-L60
19,383
sorgerlab/indra
indra/databases/go_client.py
update_id_mappings
def update_id_mappings(g): """Compile all ID->label mappings and save to a TSV file. Parameters ---------- g : rdflib.Graph RDF graph containing GO data. """ g = load_go_graph(go_owl_path) query = _prefixes + """ SELECT ?id ?label WHERE { ?class oboInOwl:id ?id . ?class rdfs:label ?label } """ logger.info("Querying for GO ID mappings") res = g.query(query) mappings = [] for id_lit, label_lit in sorted(res, key=lambda x: x[0]): mappings.append((id_lit.value, label_lit.value)) # Write to file write_unicode_csv(go_mappings_file, mappings, delimiter='\t')
python
def update_id_mappings(g): g = load_go_graph(go_owl_path) query = _prefixes + """ SELECT ?id ?label WHERE { ?class oboInOwl:id ?id . ?class rdfs:label ?label } """ logger.info("Querying for GO ID mappings") res = g.query(query) mappings = [] for id_lit, label_lit in sorted(res, key=lambda x: x[0]): mappings.append((id_lit.value, label_lit.value)) # Write to file write_unicode_csv(go_mappings_file, mappings, delimiter='\t')
[ "def", "update_id_mappings", "(", "g", ")", ":", "g", "=", "load_go_graph", "(", "go_owl_path", ")", "query", "=", "_prefixes", "+", "\"\"\"\n SELECT ?id ?label\n WHERE {\n ?class oboInOwl:id ?id .\n ?class rdfs:label ?label\n }\n \"\"\""...
Compile all ID->label mappings and save to a TSV file. Parameters ---------- g : rdflib.Graph RDF graph containing GO data.
[ "Compile", "all", "ID", "-", ">", "label", "mappings", "and", "save", "to", "a", "TSV", "file", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/databases/go_client.py#L80-L103
19,384
sorgerlab/indra
indra/databases/ndex_client.py
get_default_ndex_cred
def get_default_ndex_cred(ndex_cred): """Gets the NDEx credentials from the dict, or tries the environment if None""" if ndex_cred: username = ndex_cred.get('user') password = ndex_cred.get('password') if username is not None and password is not None: return username, password username = get_config('NDEX_USERNAME') password = get_config('NDEX_PASSWORD') return username, password
python
def get_default_ndex_cred(ndex_cred): if ndex_cred: username = ndex_cred.get('user') password = ndex_cred.get('password') if username is not None and password is not None: return username, password username = get_config('NDEX_USERNAME') password = get_config('NDEX_PASSWORD') return username, password
[ "def", "get_default_ndex_cred", "(", "ndex_cred", ")", ":", "if", "ndex_cred", ":", "username", "=", "ndex_cred", ".", "get", "(", "'user'", ")", "password", "=", "ndex_cred", ".", "get", "(", "'password'", ")", "if", "username", "is", "not", "None", "and"...
Gets the NDEx credentials from the dict, or tries the environment if None
[ "Gets", "the", "NDEx", "credentials", "from", "the", "dict", "or", "tries", "the", "environment", "if", "None" ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/databases/ndex_client.py#L17-L29
19,385
sorgerlab/indra
indra/databases/ndex_client.py
send_request
def send_request(ndex_service_url, params, is_json=True, use_get=False): """Send a request to the NDEx server. Parameters ---------- ndex_service_url : str The URL of the service to use for the request. params : dict A dictionary of parameters to send with the request. Parameter keys differ based on the type of request. is_json : bool True if the response is in json format, otherwise it is assumed to be text. Default: False use_get : bool True if the request needs to use GET instead of POST. Returns ------- res : str Depending on the type of service and the is_json parameter, this function either returns a text string or a json dict. """ if use_get: res = requests.get(ndex_service_url, json=params) else: res = requests.post(ndex_service_url, json=params) status = res.status_code # If response is immediate, we get 200 if status == 200: if is_json: return res.json() else: return res.text # If there is a continuation of the message we get status 300, handled below. # Otherwise we return None. elif status != 300: logger.error('Request returned with code %d' % status) return None # In case the response is not immediate, a task ID can be used to get # the result. task_id = res.json().get('task_id') logger.info('NDEx task submitted...') time_used = 0 try: while status != 200: res = requests.get(ndex_base_url + '/task/' + task_id) status = res.status_code if status != 200: time.sleep(5) time_used += 5 except KeyError: next return None logger.info('NDEx task complete.') if is_json: return res.json() else: return res.text
python
def send_request(ndex_service_url, params, is_json=True, use_get=False): if use_get: res = requests.get(ndex_service_url, json=params) else: res = requests.post(ndex_service_url, json=params) status = res.status_code # If response is immediate, we get 200 if status == 200: if is_json: return res.json() else: return res.text # If there is a continuation of the message we get status 300, handled below. # Otherwise we return None. elif status != 300: logger.error('Request returned with code %d' % status) return None # In case the response is not immediate, a task ID can be used to get # the result. task_id = res.json().get('task_id') logger.info('NDEx task submitted...') time_used = 0 try: while status != 200: res = requests.get(ndex_base_url + '/task/' + task_id) status = res.status_code if status != 200: time.sleep(5) time_used += 5 except KeyError: next return None logger.info('NDEx task complete.') if is_json: return res.json() else: return res.text
[ "def", "send_request", "(", "ndex_service_url", ",", "params", ",", "is_json", "=", "True", ",", "use_get", "=", "False", ")", ":", "if", "use_get", ":", "res", "=", "requests", ".", "get", "(", "ndex_service_url", ",", "json", "=", "params", ")", "else"...
Send a request to the NDEx server. Parameters ---------- ndex_service_url : str The URL of the service to use for the request. params : dict A dictionary of parameters to send with the request. Parameter keys differ based on the type of request. is_json : bool True if the response is in json format, otherwise it is assumed to be text. Default: False use_get : bool True if the request needs to use GET instead of POST. Returns ------- res : str Depending on the type of service and the is_json parameter, this function either returns a text string or a json dict.
[ "Send", "a", "request", "to", "the", "NDEx", "server", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/databases/ndex_client.py#L32-L89
19,386
sorgerlab/indra
indra/databases/ndex_client.py
update_network
def update_network(cx_str, network_id, ndex_cred=None): """Update an existing CX network on NDEx with new CX content. Parameters ---------- cx_str : str String containing the CX content. network_id : str UUID of the network on NDEx. ndex_cred : dict A dictionary with the following entries: 'user': NDEx user name 'password': NDEx password """ server = 'http://public.ndexbio.org' username, password = get_default_ndex_cred(ndex_cred) nd = ndex2.client.Ndex2(server, username, password) try: logger.info('Getting network summary...') summary = nd.get_network_summary(network_id) except Exception as e: logger.error('Could not get NDEx network summary.') logger.error(e) return # Update network content try: logger.info('Updating network...') cx_stream = io.BytesIO(cx_str.encode('utf-8')) nd.update_cx_network(cx_stream, network_id) except Exception as e: logger.error('Could not update NDEx network.') logger.error(e) return # Update network profile ver_str = summary.get('version') new_ver = _increment_ndex_ver(ver_str) profile = {'name': summary.get('name'), 'description': summary.get('description'), 'version': new_ver, } logger.info('Updating NDEx network (%s) profile to %s', network_id, profile) profile_retries = 5 for _ in range(profile_retries): try: time.sleep(5) nd.update_network_profile(network_id, profile) break except Exception as e: logger.error('Could not update NDEx network profile.') logger.error(e) set_style(network_id, ndex_cred)
python
def update_network(cx_str, network_id, ndex_cred=None): server = 'http://public.ndexbio.org' username, password = get_default_ndex_cred(ndex_cred) nd = ndex2.client.Ndex2(server, username, password) try: logger.info('Getting network summary...') summary = nd.get_network_summary(network_id) except Exception as e: logger.error('Could not get NDEx network summary.') logger.error(e) return # Update network content try: logger.info('Updating network...') cx_stream = io.BytesIO(cx_str.encode('utf-8')) nd.update_cx_network(cx_stream, network_id) except Exception as e: logger.error('Could not update NDEx network.') logger.error(e) return # Update network profile ver_str = summary.get('version') new_ver = _increment_ndex_ver(ver_str) profile = {'name': summary.get('name'), 'description': summary.get('description'), 'version': new_ver, } logger.info('Updating NDEx network (%s) profile to %s', network_id, profile) profile_retries = 5 for _ in range(profile_retries): try: time.sleep(5) nd.update_network_profile(network_id, profile) break except Exception as e: logger.error('Could not update NDEx network profile.') logger.error(e) set_style(network_id, ndex_cred)
[ "def", "update_network", "(", "cx_str", ",", "network_id", ",", "ndex_cred", "=", "None", ")", ":", "server", "=", "'http://public.ndexbio.org'", "username", ",", "password", "=", "get_default_ndex_cred", "(", "ndex_cred", ")", "nd", "=", "ndex2", ".", "client",...
Update an existing CX network on NDEx with new CX content. Parameters ---------- cx_str : str String containing the CX content. network_id : str UUID of the network on NDEx. ndex_cred : dict A dictionary with the following entries: 'user': NDEx user name 'password': NDEx password
[ "Update", "an", "existing", "CX", "network", "on", "NDEx", "with", "new", "CX", "content", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/databases/ndex_client.py#L134-L189
19,387
sorgerlab/indra
indra/databases/ndex_client.py
set_style
def set_style(network_id, ndex_cred=None, template_id=None): """Set the style of the network to a given template network's style Parameters ---------- network_id : str The UUID of the NDEx network whose style is to be changed. ndex_cred : dict A dictionary of NDEx credentials. template_id : Optional[str] The UUID of the NDEx network whose style is used on the network specified in the first argument. """ if not template_id: template_id = "ea4ea3b7-6903-11e7-961c-0ac135e8bacf" server = 'http://public.ndexbio.org' username, password = get_default_ndex_cred(ndex_cred) source_network = ndex2.create_nice_cx_from_server(username=username, password=password, uuid=network_id, server=server) source_network.apply_template(server, template_id) source_network.update_to(network_id, server=server, username=username, password=password)
python
def set_style(network_id, ndex_cred=None, template_id=None): if not template_id: template_id = "ea4ea3b7-6903-11e7-961c-0ac135e8bacf" server = 'http://public.ndexbio.org' username, password = get_default_ndex_cred(ndex_cred) source_network = ndex2.create_nice_cx_from_server(username=username, password=password, uuid=network_id, server=server) source_network.apply_template(server, template_id) source_network.update_to(network_id, server=server, username=username, password=password)
[ "def", "set_style", "(", "network_id", ",", "ndex_cred", "=", "None", ",", "template_id", "=", "None", ")", ":", "if", "not", "template_id", ":", "template_id", "=", "\"ea4ea3b7-6903-11e7-961c-0ac135e8bacf\"", "server", "=", "'http://public.ndexbio.org'", "username", ...
Set the style of the network to a given template network's style Parameters ---------- network_id : str The UUID of the NDEx network whose style is to be changed. ndex_cred : dict A dictionary of NDEx credentials. template_id : Optional[str] The UUID of the NDEx network whose style is used on the network specified in the first argument.
[ "Set", "the", "style", "of", "the", "network", "to", "a", "given", "template", "network", "s", "style" ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/databases/ndex_client.py#L192-L219
19,388
sorgerlab/indra
indra/assemblers/pysb/bmi_wrapper.py
BMIModel.initialize
def initialize(self, cfg_file=None, mode=None): """Initialize the model for simulation, possibly given a config file. Parameters ---------- cfg_file : Optional[str] The name of the configuration file to load, optional. """ self.sim = ScipyOdeSimulator(self.model) self.state = numpy.array(copy.copy(self.sim.initials)[0]) self.time = numpy.array(0.0) self.status = 'initialized'
python
def initialize(self, cfg_file=None, mode=None): self.sim = ScipyOdeSimulator(self.model) self.state = numpy.array(copy.copy(self.sim.initials)[0]) self.time = numpy.array(0.0) self.status = 'initialized'
[ "def", "initialize", "(", "self", ",", "cfg_file", "=", "None", ",", "mode", "=", "None", ")", ":", "self", ".", "sim", "=", "ScipyOdeSimulator", "(", "self", ".", "model", ")", "self", ".", "state", "=", "numpy", ".", "array", "(", "copy", ".", "c...
Initialize the model for simulation, possibly given a config file. Parameters ---------- cfg_file : Optional[str] The name of the configuration file to load, optional.
[ "Initialize", "the", "model", "for", "simulation", "possibly", "given", "a", "config", "file", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/pysb/bmi_wrapper.py#L74-L85
19,389
sorgerlab/indra
indra/assemblers/pysb/bmi_wrapper.py
BMIModel.update
def update(self, dt=None): """Simulate the model for a given time interval. Parameters ---------- dt : Optional[float] The time step to simulate, if None, the default built-in time step is used. """ # EMELI passes dt = -1 so we need to handle that here dt = dt if (dt is not None and dt > 0) else self.dt tspan = [0, dt] # Run simulaton with initials set to current state res = self.sim.run(tspan=tspan, initials=self.state) # Set the state based on the result here self.state = res.species[-1] self.time += dt if self.time > self.stop_time: self.DONE = True print((self.time, self.state)) self.time_course.append((self.time.copy(), self.state.copy()))
python
def update(self, dt=None): # EMELI passes dt = -1 so we need to handle that here dt = dt if (dt is not None and dt > 0) else self.dt tspan = [0, dt] # Run simulaton with initials set to current state res = self.sim.run(tspan=tspan, initials=self.state) # Set the state based on the result here self.state = res.species[-1] self.time += dt if self.time > self.stop_time: self.DONE = True print((self.time, self.state)) self.time_course.append((self.time.copy(), self.state.copy()))
[ "def", "update", "(", "self", ",", "dt", "=", "None", ")", ":", "# EMELI passes dt = -1 so we need to handle that here", "dt", "=", "dt", "if", "(", "dt", "is", "not", "None", "and", "dt", ">", "0", ")", "else", "self", ".", "dt", "tspan", "=", "[", "0...
Simulate the model for a given time interval. Parameters ---------- dt : Optional[float] The time step to simulate, if None, the default built-in time step is used.
[ "Simulate", "the", "model", "for", "a", "given", "time", "interval", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/pysb/bmi_wrapper.py#L87-L107
19,390
sorgerlab/indra
indra/assemblers/pysb/bmi_wrapper.py
BMIModel.set_value
def set_value(self, var_name, value): """Set the value of a given variable to a given value. Parameters ---------- var_name : str The name of the variable in the model whose value should be set. value : float The value the variable should be set to """ if var_name in self.outside_name_map: var_name = self.outside_name_map[var_name] print('%s=%.5f' % (var_name, 1e9*value)) if var_name == 'Precipitation': value = 1e9*value species_idx = self.species_name_map[var_name] self.state[species_idx] = value
python
def set_value(self, var_name, value): if var_name in self.outside_name_map: var_name = self.outside_name_map[var_name] print('%s=%.5f' % (var_name, 1e9*value)) if var_name == 'Precipitation': value = 1e9*value species_idx = self.species_name_map[var_name] self.state[species_idx] = value
[ "def", "set_value", "(", "self", ",", "var_name", ",", "value", ")", ":", "if", "var_name", "in", "self", ".", "outside_name_map", ":", "var_name", "=", "self", ".", "outside_name_map", "[", "var_name", "]", "print", "(", "'%s=%.5f'", "%", "(", "var_name",...
Set the value of a given variable to a given value. Parameters ---------- var_name : str The name of the variable in the model whose value should be set. value : float The value the variable should be set to
[ "Set", "the", "value", "of", "a", "given", "variable", "to", "a", "given", "value", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/pysb/bmi_wrapper.py#L114-L131
19,391
sorgerlab/indra
indra/assemblers/pysb/bmi_wrapper.py
BMIModel.get_value
def get_value(self, var_name): """Return the value of a given variable. Parameters ---------- var_name : str The name of the variable whose value should be returned Returns ------- value : float The value of the given variable in the current state """ if var_name in self.outside_name_map: var_name = self.outside_name_map[var_name] species_idx = self.species_name_map[var_name] return self.state[species_idx]
python
def get_value(self, var_name): if var_name in self.outside_name_map: var_name = self.outside_name_map[var_name] species_idx = self.species_name_map[var_name] return self.state[species_idx]
[ "def", "get_value", "(", "self", ",", "var_name", ")", ":", "if", "var_name", "in", "self", ".", "outside_name_map", ":", "var_name", "=", "self", ".", "outside_name_map", "[", "var_name", "]", "species_idx", "=", "self", ".", "species_name_map", "[", "var_n...
Return the value of a given variable. Parameters ---------- var_name : str The name of the variable whose value should be returned Returns ------- value : float The value of the given variable in the current state
[ "Return", "the", "value", "of", "a", "given", "variable", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/pysb/bmi_wrapper.py#L147-L163
19,392
sorgerlab/indra
indra/assemblers/pysb/bmi_wrapper.py
BMIModel.get_input_var_names
def get_input_var_names(self): """Return a list of variables names that can be set as input. Returns ------- var_names : list[str] A list of variable names that can be set from the outside """ in_vars = copy.copy(self.input_vars) for idx, var in enumerate(in_vars): if self._map_in_out(var) is not None: in_vars[idx] = self._map_in_out(var) return in_vars
python
def get_input_var_names(self): in_vars = copy.copy(self.input_vars) for idx, var in enumerate(in_vars): if self._map_in_out(var) is not None: in_vars[idx] = self._map_in_out(var) return in_vars
[ "def", "get_input_var_names", "(", "self", ")", ":", "in_vars", "=", "copy", ".", "copy", "(", "self", ".", "input_vars", ")", "for", "idx", ",", "var", "in", "enumerate", "(", "in_vars", ")", ":", "if", "self", ".", "_map_in_out", "(", "var", ")", "...
Return a list of variables names that can be set as input. Returns ------- var_names : list[str] A list of variable names that can be set from the outside
[ "Return", "a", "list", "of", "variables", "names", "that", "can", "be", "set", "as", "input", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/pysb/bmi_wrapper.py#L203-L215
19,393
sorgerlab/indra
indra/assemblers/pysb/bmi_wrapper.py
BMIModel.get_output_var_names
def get_output_var_names(self): """Return a list of variables names that can be read as output. Returns ------- var_names : list[str] A list of variable names that can be read from the outside """ # Return all the variables that aren't input variables all_vars = list(self.species_name_map.keys()) output_vars = list(set(all_vars) - set(self.input_vars)) # Re-map to outside var names if needed for idx, var in enumerate(output_vars): if self._map_in_out(var) is not None: output_vars[idx] = self._map_in_out(var) return output_vars
python
def get_output_var_names(self): # Return all the variables that aren't input variables all_vars = list(self.species_name_map.keys()) output_vars = list(set(all_vars) - set(self.input_vars)) # Re-map to outside var names if needed for idx, var in enumerate(output_vars): if self._map_in_out(var) is not None: output_vars[idx] = self._map_in_out(var) return output_vars
[ "def", "get_output_var_names", "(", "self", ")", ":", "# Return all the variables that aren't input variables", "all_vars", "=", "list", "(", "self", ".", "species_name_map", ".", "keys", "(", ")", ")", "output_vars", "=", "list", "(", "set", "(", "all_vars", ")",...
Return a list of variables names that can be read as output. Returns ------- var_names : list[str] A list of variable names that can be read from the outside
[ "Return", "a", "list", "of", "variables", "names", "that", "can", "be", "read", "as", "output", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/pysb/bmi_wrapper.py#L217-L232
19,394
sorgerlab/indra
indra/assemblers/pysb/bmi_wrapper.py
BMIModel.make_repository_component
def make_repository_component(self): """Return an XML string representing this BMI in a workflow. This description is required by EMELI to discover and load models. Returns ------- xml : str String serialized XML representation of the component in the model repository. """ component = etree.Element('component') comp_name = etree.Element('comp_name') comp_name.text = self.model.name component.append(comp_name) mod_path = etree.Element('module_path') mod_path.text = os.getcwd() component.append(mod_path) mod_name = etree.Element('module_name') mod_name.text = self.model.name component.append(mod_name) class_name = etree.Element('class_name') class_name.text = 'model_class' component.append(class_name) model_name = etree.Element('model_name') model_name.text = self.model.name component.append(model_name) lang = etree.Element('language') lang.text = 'python' component.append(lang) ver = etree.Element('version') ver.text = self.get_attribute('version') component.append(ver) au = etree.Element('author') au.text = self.get_attribute('author_name') component.append(au) hu = etree.Element('help_url') hu.text = 'http://github.com/sorgerlab/indra' component.append(hu) for tag in ('cfg_template', 'time_step_type', 'time_units', 'grid_type', 'description', 'comp_type', 'uses_types'): elem = etree.Element(tag) elem.text = tag component.append(elem) return etree.tounicode(component, pretty_print=True)
python
def make_repository_component(self): component = etree.Element('component') comp_name = etree.Element('comp_name') comp_name.text = self.model.name component.append(comp_name) mod_path = etree.Element('module_path') mod_path.text = os.getcwd() component.append(mod_path) mod_name = etree.Element('module_name') mod_name.text = self.model.name component.append(mod_name) class_name = etree.Element('class_name') class_name.text = 'model_class' component.append(class_name) model_name = etree.Element('model_name') model_name.text = self.model.name component.append(model_name) lang = etree.Element('language') lang.text = 'python' component.append(lang) ver = etree.Element('version') ver.text = self.get_attribute('version') component.append(ver) au = etree.Element('author') au.text = self.get_attribute('author_name') component.append(au) hu = etree.Element('help_url') hu.text = 'http://github.com/sorgerlab/indra' component.append(hu) for tag in ('cfg_template', 'time_step_type', 'time_units', 'grid_type', 'description', 'comp_type', 'uses_types'): elem = etree.Element(tag) elem.text = tag component.append(elem) return etree.tounicode(component, pretty_print=True)
[ "def", "make_repository_component", "(", "self", ")", ":", "component", "=", "etree", ".", "Element", "(", "'component'", ")", "comp_name", "=", "etree", ".", "Element", "(", "'comp_name'", ")", "comp_name", ".", "text", "=", "self", ".", "model", ".", "na...
Return an XML string representing this BMI in a workflow. This description is required by EMELI to discover and load models. Returns ------- xml : str String serialized XML representation of the component in the model repository.
[ "Return", "an", "XML", "string", "representing", "this", "BMI", "in", "a", "workflow", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/pysb/bmi_wrapper.py#L336-L391
19,395
sorgerlab/indra
indra/assemblers/pysb/bmi_wrapper.py
BMIModel._map_in_out
def _map_in_out(self, inside_var_name): """Return the external name of a variable mapped from inside.""" for out_name, in_name in self.outside_name_map.items(): if inside_var_name == in_name: return out_name return None
python
def _map_in_out(self, inside_var_name): for out_name, in_name in self.outside_name_map.items(): if inside_var_name == in_name: return out_name return None
[ "def", "_map_in_out", "(", "self", ",", "inside_var_name", ")", ":", "for", "out_name", ",", "in_name", "in", "self", ".", "outside_name_map", ".", "items", "(", ")", ":", "if", "inside_var_name", "==", "in_name", ":", "return", "out_name", "return", "None" ...
Return the external name of a variable mapped from inside.
[ "Return", "the", "external", "name", "of", "a", "variable", "mapped", "from", "inside", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/pysb/bmi_wrapper.py#L417-L422
19,396
sorgerlab/indra
indra/tools/reading/pmid_reading/read_pmids.py
read_pmid
def read_pmid(pmid, source, cont_path, sparser_version, outbuf=None, cleanup=True): "Run sparser on a single pmid." signal.signal(signal.SIGALRM, _timeout_handler) signal.alarm(60) try: if (source is 'content_not_found' or source.startswith('unhandled_content_type') or source.endswith('failure')): logger.info('No content read for %s.' % pmid) return # No real content here. if cont_path.endswith('.nxml') and source.startswith('pmc'): new_fname = 'PMC%s%d.nxml' % (pmid, mp.current_process().pid) os.rename(cont_path, new_fname) try: sp = sparser.process_nxml_file( new_fname, outbuf=outbuf, cleanup=cleanup ) finally: if cleanup and os.path.exists(new_fname): os.remove(new_fname) elif cont_path.endswith('.txt'): content_str = '' with open(cont_path, 'r') as f: content_str = f.read() sp = sparser.process_text( content_str, outbuf=outbuf, cleanup=cleanup ) signal.alarm(0) except Exception as e: logger.error('Failed to process data for %s.' % pmid) logger.exception(e) signal.alarm(0) return if sp is None: logger.error('Failed to run sparser on pmid: %s.' % pmid) return # At this point, we rewrite the PMID in the Evidence of Sparser # Statements according to the actual PMID that was read. sp.set_statements_pmid(pmid) s3_client.put_reader_output('sparser', sp.json_stmts, pmid, sparser_version, source) return sp.statements
python
def read_pmid(pmid, source, cont_path, sparser_version, outbuf=None, cleanup=True): "Run sparser on a single pmid." signal.signal(signal.SIGALRM, _timeout_handler) signal.alarm(60) try: if (source is 'content_not_found' or source.startswith('unhandled_content_type') or source.endswith('failure')): logger.info('No content read for %s.' % pmid) return # No real content here. if cont_path.endswith('.nxml') and source.startswith('pmc'): new_fname = 'PMC%s%d.nxml' % (pmid, mp.current_process().pid) os.rename(cont_path, new_fname) try: sp = sparser.process_nxml_file( new_fname, outbuf=outbuf, cleanup=cleanup ) finally: if cleanup and os.path.exists(new_fname): os.remove(new_fname) elif cont_path.endswith('.txt'): content_str = '' with open(cont_path, 'r') as f: content_str = f.read() sp = sparser.process_text( content_str, outbuf=outbuf, cleanup=cleanup ) signal.alarm(0) except Exception as e: logger.error('Failed to process data for %s.' % pmid) logger.exception(e) signal.alarm(0) return if sp is None: logger.error('Failed to run sparser on pmid: %s.' % pmid) return # At this point, we rewrite the PMID in the Evidence of Sparser # Statements according to the actual PMID that was read. sp.set_statements_pmid(pmid) s3_client.put_reader_output('sparser', sp.json_stmts, pmid, sparser_version, source) return sp.statements
[ "def", "read_pmid", "(", "pmid", ",", "source", ",", "cont_path", ",", "sparser_version", ",", "outbuf", "=", "None", ",", "cleanup", "=", "True", ")", ":", "signal", ".", "signal", "(", "signal", ".", "SIGALRM", ",", "_timeout_handler", ")", "signal", "...
Run sparser on a single pmid.
[ "Run", "sparser", "on", "a", "single", "pmid", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/reading/pmid_reading/read_pmids.py#L353-L402
19,397
sorgerlab/indra
indra/tools/reading/pmid_reading/read_pmids.py
get_stmts
def get_stmts(pmids_unread, cleanup=True, sparser_version=None): "Run sparser on the pmids in pmids_unread." if sparser_version is None: sparser_version = sparser.get_version() stmts = {} now = datetime.now() outbuf_fname = 'sparser_%s_%s.log' % ( now.strftime('%Y%m%d-%H%M%S'), mp.current_process().pid, ) outbuf = open(outbuf_fname, 'wb') try: for pmid, result in pmids_unread.items(): logger.info('Reading %s' % pmid) source = result['content_source'] cont_path = result['content_path'] outbuf.write(('\nReading pmid %s from %s located at %s.\n' % ( pmid, source, cont_path )).encode('utf-8')) outbuf.flush() some_stmts = read_pmid(pmid, source, cont_path, sparser_version, outbuf, cleanup) if some_stmts is not None: stmts[pmid] = some_stmts else: continue # We didn't get any new statements. except KeyboardInterrupt as e: logger.exception(e) logger.info('Caught keyboard interrupt...stopping. \n' 'Results so far will be pickled unless ' 'Keyboard interupt is hit again.') finally: outbuf.close() print("Sparser logs may be found in %s" % outbuf_fname) return stmts
python
def get_stmts(pmids_unread, cleanup=True, sparser_version=None): "Run sparser on the pmids in pmids_unread." if sparser_version is None: sparser_version = sparser.get_version() stmts = {} now = datetime.now() outbuf_fname = 'sparser_%s_%s.log' % ( now.strftime('%Y%m%d-%H%M%S'), mp.current_process().pid, ) outbuf = open(outbuf_fname, 'wb') try: for pmid, result in pmids_unread.items(): logger.info('Reading %s' % pmid) source = result['content_source'] cont_path = result['content_path'] outbuf.write(('\nReading pmid %s from %s located at %s.\n' % ( pmid, source, cont_path )).encode('utf-8')) outbuf.flush() some_stmts = read_pmid(pmid, source, cont_path, sparser_version, outbuf, cleanup) if some_stmts is not None: stmts[pmid] = some_stmts else: continue # We didn't get any new statements. except KeyboardInterrupt as e: logger.exception(e) logger.info('Caught keyboard interrupt...stopping. \n' 'Results so far will be pickled unless ' 'Keyboard interupt is hit again.') finally: outbuf.close() print("Sparser logs may be found in %s" % outbuf_fname) return stmts
[ "def", "get_stmts", "(", "pmids_unread", ",", "cleanup", "=", "True", ",", "sparser_version", "=", "None", ")", ":", "if", "sparser_version", "is", "None", ":", "sparser_version", "=", "sparser", ".", "get_version", "(", ")", "stmts", "=", "{", "}", "now",...
Run sparser on the pmids in pmids_unread.
[ "Run", "sparser", "on", "the", "pmids", "in", "pmids_unread", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/reading/pmid_reading/read_pmids.py#L405-L441
19,398
sorgerlab/indra
indra/tools/reading/pmid_reading/read_pmids.py
run_sparser
def run_sparser(pmid_list, tmp_dir, num_cores, start_index, end_index, force_read, force_fulltext, cleanup=True, verbose=True): 'Run the sparser reader on the pmids in pmid_list.' reader_version = sparser.get_version() _, _, _, pmids_read, pmids_unread, _ =\ get_content_to_read( pmid_list, start_index, end_index, tmp_dir, num_cores, force_fulltext, force_read, 'sparser', reader_version ) logger.info('Adjusting num cores to length of pmid_list.') num_cores = min(len(pmid_list), num_cores) logger.info('Adjusted...') if num_cores is 1: stmts = get_stmts(pmids_unread, cleanup=cleanup) stmts.update({pmid: get_stmts_from_cache(pmid)[pmid] for pmid in pmids_read.keys()}) elif num_cores > 1: logger.info("Starting a pool with %d cores." % num_cores) pool = mp.Pool(num_cores) pmids_to_read = list(pmids_unread.keys()) N = len(pmids_unread) dn = int(N/num_cores) logger.info("Breaking pmids into batches.") batches = [] for i in range(num_cores): batches.append({ k: pmids_unread[k] for k in pmids_to_read[i*dn:min((i+1)*dn, N)] }) get_stmts_func = functools.partial( get_stmts, cleanup=cleanup, sparser_version=reader_version ) logger.info("Mapping get_stmts onto pool.") unread_res = pool.map(get_stmts_func, batches) logger.info('len(unread_res)=%d' % len(unread_res)) read_res = pool.map(get_stmts_from_cache, pmids_read.keys()) logger.info('len(read_res)=%d' % len(read_res)) pool.close() logger.info('Multiprocessing pool closed.') pool.join() logger.info('Multiprocessing pool joined.') stmts = { pmid: stmt_list for res_dict in unread_res + read_res for pmid, stmt_list in res_dict.items() } logger.info('len(stmts)=%d' % len(stmts)) return (stmts, pmids_unread)
python
def run_sparser(pmid_list, tmp_dir, num_cores, start_index, end_index, force_read, force_fulltext, cleanup=True, verbose=True): 'Run the sparser reader on the pmids in pmid_list.' reader_version = sparser.get_version() _, _, _, pmids_read, pmids_unread, _ =\ get_content_to_read( pmid_list, start_index, end_index, tmp_dir, num_cores, force_fulltext, force_read, 'sparser', reader_version ) logger.info('Adjusting num cores to length of pmid_list.') num_cores = min(len(pmid_list), num_cores) logger.info('Adjusted...') if num_cores is 1: stmts = get_stmts(pmids_unread, cleanup=cleanup) stmts.update({pmid: get_stmts_from_cache(pmid)[pmid] for pmid in pmids_read.keys()}) elif num_cores > 1: logger.info("Starting a pool with %d cores." % num_cores) pool = mp.Pool(num_cores) pmids_to_read = list(pmids_unread.keys()) N = len(pmids_unread) dn = int(N/num_cores) logger.info("Breaking pmids into batches.") batches = [] for i in range(num_cores): batches.append({ k: pmids_unread[k] for k in pmids_to_read[i*dn:min((i+1)*dn, N)] }) get_stmts_func = functools.partial( get_stmts, cleanup=cleanup, sparser_version=reader_version ) logger.info("Mapping get_stmts onto pool.") unread_res = pool.map(get_stmts_func, batches) logger.info('len(unread_res)=%d' % len(unread_res)) read_res = pool.map(get_stmts_from_cache, pmids_read.keys()) logger.info('len(read_res)=%d' % len(read_res)) pool.close() logger.info('Multiprocessing pool closed.') pool.join() logger.info('Multiprocessing pool joined.') stmts = { pmid: stmt_list for res_dict in unread_res + read_res for pmid, stmt_list in res_dict.items() } logger.info('len(stmts)=%d' % len(stmts)) return (stmts, pmids_unread)
[ "def", "run_sparser", "(", "pmid_list", ",", "tmp_dir", ",", "num_cores", ",", "start_index", ",", "end_index", ",", "force_read", ",", "force_fulltext", ",", "cleanup", "=", "True", ",", "verbose", "=", "True", ")", ":", "reader_version", "=", "sparser", "....
Run the sparser reader on the pmids in pmid_list.
[ "Run", "the", "sparser", "reader", "on", "the", "pmids", "in", "pmid_list", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/reading/pmid_reading/read_pmids.py#L452-L502
19,399
sorgerlab/indra
indra/statements/statements.py
get_all_descendants
def get_all_descendants(parent): """Get all the descendants of a parent class, recursively.""" children = parent.__subclasses__() descendants = children[:] for child in children: descendants += get_all_descendants(child) return descendants
python
def get_all_descendants(parent): children = parent.__subclasses__() descendants = children[:] for child in children: descendants += get_all_descendants(child) return descendants
[ "def", "get_all_descendants", "(", "parent", ")", ":", "children", "=", "parent", ".", "__subclasses__", "(", ")", "descendants", "=", "children", "[", ":", "]", "for", "child", "in", "children", ":", "descendants", "+=", "get_all_descendants", "(", "child", ...
Get all the descendants of a parent class, recursively.
[ "Get", "all", "the", "descendants", "of", "a", "parent", "class", "recursively", "." ]
79a70415832c5702d7a820c7c9ccc8e25010124b
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/statements/statements.py#L2454-L2460