id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
18,700 | dbcli/athenacli | athenacli/packages/special/iocommands.py | get_editor_query | def get_editor_query(sql):
"""Get the query part of an editor command."""
sql = sql.strip()
# The reason we can't simply do .strip('\e') is that it strips characters,
# not a substring. So it'll strip "e" in the end of the sql also!
# Ex: "select * from style\e" -> "select * from styl".
pattern = re.compile('(^\\\e|\\\e$)')
while pattern.search(sql):
sql = pattern.sub('', sql)
return sql | python | def get_editor_query(sql):
sql = sql.strip()
# The reason we can't simply do .strip('\e') is that it strips characters,
# not a substring. So it'll strip "e" in the end of the sql also!
# Ex: "select * from style\e" -> "select * from styl".
pattern = re.compile('(^\\\e|\\\e$)')
while pattern.search(sql):
sql = pattern.sub('', sql)
return sql | [
"def",
"get_editor_query",
"(",
"sql",
")",
":",
"sql",
"=",
"sql",
".",
"strip",
"(",
")",
"# The reason we can't simply do .strip('\\e') is that it strips characters,",
"# not a substring. So it'll strip \"e\" in the end of the sql also!",
"# Ex: \"select * from style\\e\" -> \"selec... | Get the query part of an editor command. | [
"Get",
"the",
"query",
"part",
"of",
"an",
"editor",
"command",
"."
] | bcab59e4953145866430083e902ed4d042d4ebba | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/packages/special/iocommands.py#L108-L119 |
18,701 | dbcli/athenacli | athenacli/packages/special/iocommands.py | delete_favorite_query | def delete_favorite_query(arg, **_):
"""Delete an existing favorite query.
"""
usage = 'Syntax: \\fd name.\n\n' + favoritequeries.usage
if not arg:
return [(None, None, None, usage)]
status = favoritequeries.delete(arg)
return [(None, None, None, status)] | python | def delete_favorite_query(arg, **_):
usage = 'Syntax: \\fd name.\n\n' + favoritequeries.usage
if not arg:
return [(None, None, None, usage)]
status = favoritequeries.delete(arg)
return [(None, None, None, status)] | [
"def",
"delete_favorite_query",
"(",
"arg",
",",
"*",
"*",
"_",
")",
":",
"usage",
"=",
"'Syntax: \\\\fd name.\\n\\n'",
"+",
"favoritequeries",
".",
"usage",
"if",
"not",
"arg",
":",
"return",
"[",
"(",
"None",
",",
"None",
",",
"None",
",",
"usage",
")"... | Delete an existing favorite query. | [
"Delete",
"an",
"existing",
"favorite",
"query",
"."
] | bcab59e4953145866430083e902ed4d042d4ebba | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/packages/special/iocommands.py#L239-L248 |
18,702 | dbcli/athenacli | athenacli/packages/special/iocommands.py | execute_system_command | def execute_system_command(arg, **_):
"""Execute a system shell command."""
usage = "Syntax: system [command].\n"
if not arg:
return [(None, None, None, usage)]
try:
command = arg.strip()
if command.startswith('cd'):
ok, error_message = handle_cd_command(arg)
if not ok:
return [(None, None, None, error_message)]
return [(None, None, None, '')]
args = arg.split(' ')
process = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = process.communicate()
response = output if not error else error
# Python 3 returns bytes. This needs to be decoded to a string.
if isinstance(response, bytes):
encoding = locale.getpreferredencoding(False)
response = response.decode(encoding)
return [(None, None, None, response)]
except OSError as e:
return [(None, None, None, 'OSError: %s' % e.strerror)] | python | def execute_system_command(arg, **_):
usage = "Syntax: system [command].\n"
if not arg:
return [(None, None, None, usage)]
try:
command = arg.strip()
if command.startswith('cd'):
ok, error_message = handle_cd_command(arg)
if not ok:
return [(None, None, None, error_message)]
return [(None, None, None, '')]
args = arg.split(' ')
process = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = process.communicate()
response = output if not error else error
# Python 3 returns bytes. This needs to be decoded to a string.
if isinstance(response, bytes):
encoding = locale.getpreferredencoding(False)
response = response.decode(encoding)
return [(None, None, None, response)]
except OSError as e:
return [(None, None, None, 'OSError: %s' % e.strerror)] | [
"def",
"execute_system_command",
"(",
"arg",
",",
"*",
"*",
"_",
")",
":",
"usage",
"=",
"\"Syntax: system [command].\\n\"",
"if",
"not",
"arg",
":",
"return",
"[",
"(",
"None",
",",
"None",
",",
"None",
",",
"usage",
")",
"]",
"try",
":",
"command",
"... | Execute a system shell command. | [
"Execute",
"a",
"system",
"shell",
"command",
"."
] | bcab59e4953145866430083e902ed4d042d4ebba | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/packages/special/iocommands.py#L253-L280 |
18,703 | dbcli/athenacli | athenacli/main.py | need_completion_refresh | def need_completion_refresh(queries):
"""Determines if the completion needs a refresh by checking if the sql
statement is an alter, create, drop or change db."""
tokens = {
'use', '\\u',
'create',
'drop'
}
for query in sqlparse.split(queries):
try:
first_token = query.split()[0]
if first_token.lower() in tokens:
return True
except Exception:
return False | python | def need_completion_refresh(queries):
tokens = {
'use', '\\u',
'create',
'drop'
}
for query in sqlparse.split(queries):
try:
first_token = query.split()[0]
if first_token.lower() in tokens:
return True
except Exception:
return False | [
"def",
"need_completion_refresh",
"(",
"queries",
")",
":",
"tokens",
"=",
"{",
"'use'",
",",
"'\\\\u'",
",",
"'create'",
",",
"'drop'",
"}",
"for",
"query",
"in",
"sqlparse",
".",
"split",
"(",
"queries",
")",
":",
"try",
":",
"first_token",
"=",
"query... | Determines if the completion needs a refresh by checking if the sql
statement is an alter, create, drop or change db. | [
"Determines",
"if",
"the",
"completion",
"needs",
"a",
"refresh",
"by",
"checking",
"if",
"the",
"sql",
"statement",
"is",
"an",
"alter",
"create",
"drop",
"or",
"change",
"db",
"."
] | bcab59e4953145866430083e902ed4d042d4ebba | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/main.py#L607-L622 |
18,704 | dbcli/athenacli | athenacli/main.py | is_mutating | def is_mutating(status):
"""Determines if the statement is mutating based on the status."""
if not status:
return False
mutating = set(['insert', 'update', 'delete', 'alter', 'create', 'drop',
'replace', 'truncate', 'load'])
return status.split(None, 1)[0].lower() in mutating | python | def is_mutating(status):
if not status:
return False
mutating = set(['insert', 'update', 'delete', 'alter', 'create', 'drop',
'replace', 'truncate', 'load'])
return status.split(None, 1)[0].lower() in mutating | [
"def",
"is_mutating",
"(",
"status",
")",
":",
"if",
"not",
"status",
":",
"return",
"False",
"mutating",
"=",
"set",
"(",
"[",
"'insert'",
",",
"'update'",
",",
"'delete'",
",",
"'alter'",
",",
"'create'",
",",
"'drop'",
",",
"'replace'",
",",
"'truncat... | Determines if the statement is mutating based on the status. | [
"Determines",
"if",
"the",
"statement",
"is",
"mutating",
"based",
"on",
"the",
"status",
"."
] | bcab59e4953145866430083e902ed4d042d4ebba | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/main.py#L625-L632 |
18,705 | dbcli/athenacli | athenacli/main.py | AthenaCli.change_prompt_format | def change_prompt_format(self, arg, **_):
"""
Change the prompt format.
"""
if not arg:
message = 'Missing required argument, format.'
return [(None, None, None, message)]
self.prompt = self.get_prompt(arg)
return [(None, None, None, "Changed prompt format to %s" % arg)] | python | def change_prompt_format(self, arg, **_):
if not arg:
message = 'Missing required argument, format.'
return [(None, None, None, message)]
self.prompt = self.get_prompt(arg)
return [(None, None, None, "Changed prompt format to %s" % arg)] | [
"def",
"change_prompt_format",
"(",
"self",
",",
"arg",
",",
"*",
"*",
"_",
")",
":",
"if",
"not",
"arg",
":",
"message",
"=",
"'Missing required argument, format.'",
"return",
"[",
"(",
"None",
",",
"None",
",",
"None",
",",
"message",
")",
"]",
"self",... | Change the prompt format. | [
"Change",
"the",
"prompt",
"format",
"."
] | bcab59e4953145866430083e902ed4d042d4ebba | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/main.py#L184-L193 |
18,706 | dbcli/athenacli | athenacli/main.py | AthenaCli.get_output_margin | def get_output_margin(self, status=None):
"""Get the output margin (number of rows for the prompt, footer and
timing message."""
margin = self.get_reserved_space() + self.get_prompt(self.prompt).count('\n') + 1
if special.is_timing_enabled():
margin += 1
if status:
margin += 1 + status.count('\n')
return margin | python | def get_output_margin(self, status=None):
margin = self.get_reserved_space() + self.get_prompt(self.prompt).count('\n') + 1
if special.is_timing_enabled():
margin += 1
if status:
margin += 1 + status.count('\n')
return margin | [
"def",
"get_output_margin",
"(",
"self",
",",
"status",
"=",
"None",
")",
":",
"margin",
"=",
"self",
".",
"get_reserved_space",
"(",
")",
"+",
"self",
".",
"get_prompt",
"(",
"self",
".",
"prompt",
")",
".",
"count",
"(",
"'\\n'",
")",
"+",
"1",
"if... | Get the output margin (number of rows for the prompt, footer and
timing message. | [
"Get",
"the",
"output",
"margin",
"(",
"number",
"of",
"rows",
"for",
"the",
"prompt",
"footer",
"and",
"timing",
"message",
"."
] | bcab59e4953145866430083e902ed4d042d4ebba | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/main.py#L362-L371 |
18,707 | dbcli/athenacli | athenacli/main.py | AthenaCli.output | def output(self, output, status=None):
"""Output text to stdout or a pager command.
The status text is not outputted to pager or files.
The message will be logged in the audit log, if enabled. The
message will be written to the tee file, if enabled. The
message will be written to the output file, if enabled.
"""
if output:
size = self.cli.output.get_size()
margin = self.get_output_margin(status)
fits = True
buf = []
output_via_pager = self.explicit_pager and special.is_pager_enabled()
for i, line in enumerate(output, 1):
special.write_tee(line)
special.write_once(line)
if fits or output_via_pager:
# buffering
buf.append(line)
if len(line) > size.columns or i > (size.rows - margin):
fits = False
if not self.explicit_pager and special.is_pager_enabled():
# doesn't fit, use pager
output_via_pager = True
if not output_via_pager:
# doesn't fit, flush buffer
for line in buf:
click.secho(line)
buf = []
else:
click.secho(line)
if buf:
if output_via_pager:
# sadly click.echo_via_pager doesn't accept generators
click.echo_via_pager("\n".join(buf))
else:
for line in buf:
click.secho(line)
if status:
click.secho(status) | python | def output(self, output, status=None):
if output:
size = self.cli.output.get_size()
margin = self.get_output_margin(status)
fits = True
buf = []
output_via_pager = self.explicit_pager and special.is_pager_enabled()
for i, line in enumerate(output, 1):
special.write_tee(line)
special.write_once(line)
if fits or output_via_pager:
# buffering
buf.append(line)
if len(line) > size.columns or i > (size.rows - margin):
fits = False
if not self.explicit_pager and special.is_pager_enabled():
# doesn't fit, use pager
output_via_pager = True
if not output_via_pager:
# doesn't fit, flush buffer
for line in buf:
click.secho(line)
buf = []
else:
click.secho(line)
if buf:
if output_via_pager:
# sadly click.echo_via_pager doesn't accept generators
click.echo_via_pager("\n".join(buf))
else:
for line in buf:
click.secho(line)
if status:
click.secho(status) | [
"def",
"output",
"(",
"self",
",",
"output",
",",
"status",
"=",
"None",
")",
":",
"if",
"output",
":",
"size",
"=",
"self",
".",
"cli",
".",
"output",
".",
"get_size",
"(",
")",
"margin",
"=",
"self",
".",
"get_output_margin",
"(",
"status",
")",
... | Output text to stdout or a pager command.
The status text is not outputted to pager or files.
The message will be logged in the audit log, if enabled. The
message will be written to the tee file, if enabled. The
message will be written to the output file, if enabled. | [
"Output",
"text",
"to",
"stdout",
"or",
"a",
"pager",
"command",
".",
"The",
"status",
"text",
"is",
"not",
"outputted",
"to",
"pager",
"or",
"files",
".",
"The",
"message",
"will",
"be",
"logged",
"in",
"the",
"audit",
"log",
"if",
"enabled",
".",
"Th... | bcab59e4953145866430083e902ed4d042d4ebba | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/main.py#L373-L418 |
18,708 | dbcli/athenacli | athenacli/main.py | AthenaCli._on_completions_refreshed | def _on_completions_refreshed(self, new_completer):
"""Swap the completer object in cli with the newly created completer.
"""
with self._completer_lock:
self.completer = new_completer
# When cli is first launched we call refresh_completions before
# instantiating the cli object. So it is necessary to check if cli
# exists before trying the replace the completer object in cli.
if self.cli:
self.cli.current_buffer.completer = new_completer
if self.cli:
# After refreshing, redraw the CLI to clear the statusbar
# "Refreshing completions..." indicator
self.cli.request_redraw() | python | def _on_completions_refreshed(self, new_completer):
with self._completer_lock:
self.completer = new_completer
# When cli is first launched we call refresh_completions before
# instantiating the cli object. So it is necessary to check if cli
# exists before trying the replace the completer object in cli.
if self.cli:
self.cli.current_buffer.completer = new_completer
if self.cli:
# After refreshing, redraw the CLI to clear the statusbar
# "Refreshing completions..." indicator
self.cli.request_redraw() | [
"def",
"_on_completions_refreshed",
"(",
"self",
",",
"new_completer",
")",
":",
"with",
"self",
".",
"_completer_lock",
":",
"self",
".",
"completer",
"=",
"new_completer",
"# When cli is first launched we call refresh_completions before",
"# instantiating the cli object. So i... | Swap the completer object in cli with the newly created completer. | [
"Swap",
"the",
"completer",
"object",
"in",
"cli",
"with",
"the",
"newly",
"created",
"completer",
"."
] | bcab59e4953145866430083e902ed4d042d4ebba | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/main.py#L497-L511 |
18,709 | dbcli/athenacli | athenacli/main.py | AthenaCli.get_reserved_space | def get_reserved_space(self):
"""Get the number of lines to reserve for the completion menu."""
reserved_space_ratio = .45
max_reserved_space = 8
_, height = click.get_terminal_size()
return min(int(round(height * reserved_space_ratio)), max_reserved_space) | python | def get_reserved_space(self):
reserved_space_ratio = .45
max_reserved_space = 8
_, height = click.get_terminal_size()
return min(int(round(height * reserved_space_ratio)), max_reserved_space) | [
"def",
"get_reserved_space",
"(",
"self",
")",
":",
"reserved_space_ratio",
"=",
".45",
"max_reserved_space",
"=",
"8",
"_",
",",
"height",
"=",
"click",
".",
"get_terminal_size",
"(",
")",
"return",
"min",
"(",
"int",
"(",
"round",
"(",
"height",
"*",
"re... | Get the number of lines to reserve for the completion menu. | [
"Get",
"the",
"number",
"of",
"lines",
"to",
"reserve",
"for",
"the",
"completion",
"menu",
"."
] | bcab59e4953145866430083e902ed4d042d4ebba | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/main.py#L595-L600 |
18,710 | dbcli/athenacli | athenacli/completer.py | AthenaCompleter.find_matches | def find_matches(text, collection, start_only=False, fuzzy=True, casing=None):
"""Find completion matches for the given text.
Given the user's input text and a collection of available
completions, find completions matching the last word of the
text.
If `start_only` is True, the text will match an available
completion only at the beginning. Otherwise, a completion is
considered a match if the text appears anywhere within it.
yields prompt_toolkit Completion instances for any matches found
in the collection of available completions.
"""
last = last_word(text, include='most_punctuations')
text = last.lower()
completions = []
if fuzzy:
regex = '.*?'.join(map(escape, text))
pat = compile('(%s)' % regex)
for item in sorted(collection):
r = pat.search(item.lower())
if r:
completions.append((len(r.group()), r.start(), item))
else:
match_end_limit = len(text) if start_only else None
for item in sorted(collection):
match_point = item.lower().find(text, 0, match_end_limit)
if match_point >= 0:
completions.append((len(text), match_point, item))
if casing == 'auto':
casing = 'lower' if last and last[-1].islower() else 'upper'
def apply_case(kw):
if casing == 'upper':
return kw.upper()
return kw.lower()
return (Completion(z if casing is None else apply_case(z), -len(text))
for x, y, z in sorted(completions)) | python | def find_matches(text, collection, start_only=False, fuzzy=True, casing=None):
last = last_word(text, include='most_punctuations')
text = last.lower()
completions = []
if fuzzy:
regex = '.*?'.join(map(escape, text))
pat = compile('(%s)' % regex)
for item in sorted(collection):
r = pat.search(item.lower())
if r:
completions.append((len(r.group()), r.start(), item))
else:
match_end_limit = len(text) if start_only else None
for item in sorted(collection):
match_point = item.lower().find(text, 0, match_end_limit)
if match_point >= 0:
completions.append((len(text), match_point, item))
if casing == 'auto':
casing = 'lower' if last and last[-1].islower() else 'upper'
def apply_case(kw):
if casing == 'upper':
return kw.upper()
return kw.lower()
return (Completion(z if casing is None else apply_case(z), -len(text))
for x, y, z in sorted(completions)) | [
"def",
"find_matches",
"(",
"text",
",",
"collection",
",",
"start_only",
"=",
"False",
",",
"fuzzy",
"=",
"True",
",",
"casing",
"=",
"None",
")",
":",
"last",
"=",
"last_word",
"(",
"text",
",",
"include",
"=",
"'most_punctuations'",
")",
"text",
"=",
... | Find completion matches for the given text.
Given the user's input text and a collection of available
completions, find completions matching the last word of the
text.
If `start_only` is True, the text will match an available
completion only at the beginning. Otherwise, a completion is
considered a match if the text appears anywhere within it.
yields prompt_toolkit Completion instances for any matches found
in the collection of available completions. | [
"Find",
"completion",
"matches",
"for",
"the",
"given",
"text",
".",
"Given",
"the",
"user",
"s",
"input",
"text",
"and",
"a",
"collection",
"of",
"available",
"completions",
"find",
"completions",
"matching",
"the",
"last",
"word",
"of",
"the",
"text",
".",... | bcab59e4953145866430083e902ed4d042d4ebba | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/completer.py#L157-L196 |
18,711 | dbcli/athenacli | athenacli/config.py | log | def log(logger, level, message):
"""Logs message to stderr if logging isn't initialized."""
if logger.parent.name != 'root':
logger.log(level, message)
else:
print(message, file=sys.stderr) | python | def log(logger, level, message):
if logger.parent.name != 'root':
logger.log(level, message)
else:
print(message, file=sys.stderr) | [
"def",
"log",
"(",
"logger",
",",
"level",
",",
"message",
")",
":",
"if",
"logger",
".",
"parent",
".",
"name",
"!=",
"'root'",
":",
"logger",
".",
"log",
"(",
"level",
",",
"message",
")",
"else",
":",
"print",
"(",
"message",
",",
"file",
"=",
... | Logs message to stderr if logging isn't initialized. | [
"Logs",
"message",
"to",
"stderr",
"if",
"logging",
"isn",
"t",
"initialized",
"."
] | bcab59e4953145866430083e902ed4d042d4ebba | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/config.py#L42-L48 |
18,712 | dbcli/athenacli | athenacli/config.py | read_config_file | def read_config_file(f):
"""Read a config file."""
if isinstance(f, basestring):
f = os.path.expanduser(f)
try:
config = ConfigObj(f, interpolation=False, encoding='utf8')
except ConfigObjError as e:
log(LOGGER, logging.ERROR, "Unable to parse line {0} of config file "
"'{1}'.".format(e.line_number, f))
log(LOGGER, logging.ERROR, "Using successfully parsed config values.")
return e.config
except (IOError, OSError) as e:
log(LOGGER, logging.WARNING, "You don't have permission to read "
"config file '{0}'.".format(e.filename))
return None
return config | python | def read_config_file(f):
if isinstance(f, basestring):
f = os.path.expanduser(f)
try:
config = ConfigObj(f, interpolation=False, encoding='utf8')
except ConfigObjError as e:
log(LOGGER, logging.ERROR, "Unable to parse line {0} of config file "
"'{1}'.".format(e.line_number, f))
log(LOGGER, logging.ERROR, "Using successfully parsed config values.")
return e.config
except (IOError, OSError) as e:
log(LOGGER, logging.WARNING, "You don't have permission to read "
"config file '{0}'.".format(e.filename))
return None
return config | [
"def",
"read_config_file",
"(",
"f",
")",
":",
"if",
"isinstance",
"(",
"f",
",",
"basestring",
")",
":",
"f",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"f",
")",
"try",
":",
"config",
"=",
"ConfigObj",
"(",
"f",
",",
"interpolation",
"=",
"F... | Read a config file. | [
"Read",
"a",
"config",
"file",
"."
] | bcab59e4953145866430083e902ed4d042d4ebba | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/config.py#L51-L69 |
18,713 | dbcli/athenacli | athenacli/config.py | read_config_files | def read_config_files(files):
"""Read and merge a list of config files."""
config = ConfigObj()
for _file in files:
_config = read_config_file(_file)
if bool(_config) is True:
config.merge(_config)
config.filename = _config.filename
return config | python | def read_config_files(files):
config = ConfigObj()
for _file in files:
_config = read_config_file(_file)
if bool(_config) is True:
config.merge(_config)
config.filename = _config.filename
return config | [
"def",
"read_config_files",
"(",
"files",
")",
":",
"config",
"=",
"ConfigObj",
"(",
")",
"for",
"_file",
"in",
"files",
":",
"_config",
"=",
"read_config_file",
"(",
"_file",
")",
"if",
"bool",
"(",
"_config",
")",
"is",
"True",
":",
"config",
".",
"m... | Read and merge a list of config files. | [
"Read",
"and",
"merge",
"a",
"list",
"of",
"config",
"files",
"."
] | bcab59e4953145866430083e902ed4d042d4ebba | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/config.py#L72-L83 |
18,714 | dbcli/athenacli | athenacli/key_bindings.py | cli_bindings | def cli_bindings():
"""
Custom key bindings for cli.
"""
key_binding_manager = KeyBindingManager(
enable_open_in_editor=True,
enable_system_bindings=True,
enable_auto_suggest_bindings=True,
enable_search=True,
enable_abort_and_exit_bindings=True)
@key_binding_manager.registry.add_binding(Keys.F2)
def _(event):
"""
Enable/Disable SmartCompletion Mode.
"""
_logger.debug('Detected F2 key.')
buf = event.cli.current_buffer
buf.completer.smart_completion = not buf.completer.smart_completion
@key_binding_manager.registry.add_binding(Keys.F3)
def _(event):
"""
Enable/Disable Multiline Mode.
"""
_logger.debug('Detected F3 key.')
buf = event.cli.current_buffer
buf.always_multiline = not buf.always_multiline
@key_binding_manager.registry.add_binding(Keys.F4)
def _(event):
"""
Toggle between Vi and Emacs mode.
"""
_logger.debug('Detected F4 key.')
if event.cli.editing_mode == EditingMode.VI:
event.cli.editing_mode = EditingMode.EMACS
else:
event.cli.editing_mode = EditingMode.VI
@key_binding_manager.registry.add_binding(Keys.Tab)
def _(event):
"""
Force autocompletion at cursor.
"""
_logger.debug('Detected <Tab> key.')
b = event.cli.current_buffer
if b.complete_state:
b.complete_next()
else:
event.cli.start_completion(select_first=True)
@key_binding_manager.registry.add_binding(Keys.ControlSpace)
def _(event):
"""
Initialize autocompletion at cursor.
If the autocompletion menu is not showing, display it with the
appropriate completions for the context.
If the menu is showing, select the next completion.
"""
_logger.debug('Detected <C-Space> key.')
b = event.cli.current_buffer
if b.complete_state:
b.complete_next()
else:
event.cli.start_completion(select_first=False)
@key_binding_manager.registry.add_binding(Keys.ControlJ, filter=HasSelectedCompletion())
def _(event):
"""
Makes the enter key work as the tab key only when showing the menu.
"""
_logger.debug('Detected <C-J> key.')
event.current_buffer.complete_state = None
b = event.cli.current_buffer
b.complete_state = None
return key_binding_manager | python | def cli_bindings():
key_binding_manager = KeyBindingManager(
enable_open_in_editor=True,
enable_system_bindings=True,
enable_auto_suggest_bindings=True,
enable_search=True,
enable_abort_and_exit_bindings=True)
@key_binding_manager.registry.add_binding(Keys.F2)
def _(event):
"""
Enable/Disable SmartCompletion Mode.
"""
_logger.debug('Detected F2 key.')
buf = event.cli.current_buffer
buf.completer.smart_completion = not buf.completer.smart_completion
@key_binding_manager.registry.add_binding(Keys.F3)
def _(event):
"""
Enable/Disable Multiline Mode.
"""
_logger.debug('Detected F3 key.')
buf = event.cli.current_buffer
buf.always_multiline = not buf.always_multiline
@key_binding_manager.registry.add_binding(Keys.F4)
def _(event):
"""
Toggle between Vi and Emacs mode.
"""
_logger.debug('Detected F4 key.')
if event.cli.editing_mode == EditingMode.VI:
event.cli.editing_mode = EditingMode.EMACS
else:
event.cli.editing_mode = EditingMode.VI
@key_binding_manager.registry.add_binding(Keys.Tab)
def _(event):
"""
Force autocompletion at cursor.
"""
_logger.debug('Detected <Tab> key.')
b = event.cli.current_buffer
if b.complete_state:
b.complete_next()
else:
event.cli.start_completion(select_first=True)
@key_binding_manager.registry.add_binding(Keys.ControlSpace)
def _(event):
"""
Initialize autocompletion at cursor.
If the autocompletion menu is not showing, display it with the
appropriate completions for the context.
If the menu is showing, select the next completion.
"""
_logger.debug('Detected <C-Space> key.')
b = event.cli.current_buffer
if b.complete_state:
b.complete_next()
else:
event.cli.start_completion(select_first=False)
@key_binding_manager.registry.add_binding(Keys.ControlJ, filter=HasSelectedCompletion())
def _(event):
"""
Makes the enter key work as the tab key only when showing the menu.
"""
_logger.debug('Detected <C-J> key.')
event.current_buffer.complete_state = None
b = event.cli.current_buffer
b.complete_state = None
return key_binding_manager | [
"def",
"cli_bindings",
"(",
")",
":",
"key_binding_manager",
"=",
"KeyBindingManager",
"(",
"enable_open_in_editor",
"=",
"True",
",",
"enable_system_bindings",
"=",
"True",
",",
"enable_auto_suggest_bindings",
"=",
"True",
",",
"enable_search",
"=",
"True",
",",
"e... | Custom key bindings for cli. | [
"Custom",
"key",
"bindings",
"for",
"cli",
"."
] | bcab59e4953145866430083e902ed4d042d4ebba | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/key_bindings.py#L10-L89 |
18,715 | dbcli/athenacli | athenacli/packages/prompt_utils.py | prompt | def prompt(*args, **kwargs):
"""Prompt the user for input and handle any abort exceptions."""
try:
return click.prompt(*args, **kwargs)
except click.Abort:
return False | python | def prompt(*args, **kwargs):
try:
return click.prompt(*args, **kwargs)
except click.Abort:
return False | [
"def",
"prompt",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"click",
".",
"prompt",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"click",
".",
"Abort",
":",
"return",
"False"
] | Prompt the user for input and handle any abort exceptions. | [
"Prompt",
"the",
"user",
"for",
"input",
"and",
"handle",
"any",
"abort",
"exceptions",
"."
] | bcab59e4953145866430083e902ed4d042d4ebba | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/packages/prompt_utils.py#L30-L35 |
18,716 | dbcli/athenacli | athenacli/sqlexecute.py | SQLExecute.run | def run(self, statement):
'''Execute the sql in the database and return the results.
The results are a list of tuples. Each tuple has 4 values
(title, rows, headers, status).
'''
# Remove spaces and EOL
statement = statement.strip()
if not statement: # Empty string
yield (None, None, None, None)
# Split the sql into separate queries and run each one.
components = sqlparse.split(statement)
for sql in components:
# Remove spaces, eol and semi-colons.
sql = sql.rstrip(';')
# \G is treated specially since we have to set the expanded output.
if sql.endswith('\\G'):
special.set_expanded_output(True)
sql = sql[:-2].strip()
cur = self.conn.cursor()
try:
for result in special.execute(cur, sql):
yield result
except special.CommandNotFound: # Regular SQL
cur.execute(sql)
yield self.get_result(cur) | python | def run(self, statement):
'''Execute the sql in the database and return the results.
The results are a list of tuples. Each tuple has 4 values
(title, rows, headers, status).
'''
# Remove spaces and EOL
statement = statement.strip()
if not statement: # Empty string
yield (None, None, None, None)
# Split the sql into separate queries and run each one.
components = sqlparse.split(statement)
for sql in components:
# Remove spaces, eol and semi-colons.
sql = sql.rstrip(';')
# \G is treated specially since we have to set the expanded output.
if sql.endswith('\\G'):
special.set_expanded_output(True)
sql = sql[:-2].strip()
cur = self.conn.cursor()
try:
for result in special.execute(cur, sql):
yield result
except special.CommandNotFound: # Regular SQL
cur.execute(sql)
yield self.get_result(cur) | [
"def",
"run",
"(",
"self",
",",
"statement",
")",
":",
"# Remove spaces and EOL",
"statement",
"=",
"statement",
".",
"strip",
"(",
")",
"if",
"not",
"statement",
":",
"# Empty string",
"yield",
"(",
"None",
",",
"None",
",",
"None",
",",
"None",
")",
"#... | Execute the sql in the database and return the results.
The results are a list of tuples. Each tuple has 4 values
(title, rows, headers, status). | [
"Execute",
"the",
"sql",
"in",
"the",
"database",
"and",
"return",
"the",
"results",
"."
] | bcab59e4953145866430083e902ed4d042d4ebba | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/sqlexecute.py#L52-L82 |
18,717 | dbcli/athenacli | athenacli/sqlexecute.py | SQLExecute.get_result | def get_result(self, cursor):
'''Get the current result's data from the cursor.'''
title = headers = None
# cursor.description is not None for queries that return result sets,
# e.g. SELECT or SHOW.
if cursor.description is not None:
headers = [x[0] for x in cursor.description]
rows = cursor.fetchall()
status = '%d row%s in set' % (len(rows), '' if len(rows) == 1 else 's')
else:
logger.debug('No rows in result.')
rows = None
status = 'Query OK'
return (title, rows, headers, status) | python | def get_result(self, cursor):
'''Get the current result's data from the cursor.'''
title = headers = None
# cursor.description is not None for queries that return result sets,
# e.g. SELECT or SHOW.
if cursor.description is not None:
headers = [x[0] for x in cursor.description]
rows = cursor.fetchall()
status = '%d row%s in set' % (len(rows), '' if len(rows) == 1 else 's')
else:
logger.debug('No rows in result.')
rows = None
status = 'Query OK'
return (title, rows, headers, status) | [
"def",
"get_result",
"(",
"self",
",",
"cursor",
")",
":",
"title",
"=",
"headers",
"=",
"None",
"# cursor.description is not None for queries that return result sets,",
"# e.g. SELECT or SHOW.",
"if",
"cursor",
".",
"description",
"is",
"not",
"None",
":",
"headers",
... | Get the current result's data from the cursor. | [
"Get",
"the",
"current",
"result",
"s",
"data",
"from",
"the",
"cursor",
"."
] | bcab59e4953145866430083e902ed4d042d4ebba | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/sqlexecute.py#L84-L98 |
18,718 | dbcli/athenacli | athenacli/sqlexecute.py | SQLExecute.tables | def tables(self):
'''Yields table names.'''
with self.conn.cursor() as cur:
cur.execute(self.TABLES_QUERY)
for row in cur:
yield row | python | def tables(self):
'''Yields table names.'''
with self.conn.cursor() as cur:
cur.execute(self.TABLES_QUERY)
for row in cur:
yield row | [
"def",
"tables",
"(",
"self",
")",
":",
"with",
"self",
".",
"conn",
".",
"cursor",
"(",
")",
"as",
"cur",
":",
"cur",
".",
"execute",
"(",
"self",
".",
"TABLES_QUERY",
")",
"for",
"row",
"in",
"cur",
":",
"yield",
"row"
] | Yields table names. | [
"Yields",
"table",
"names",
"."
] | bcab59e4953145866430083e902ed4d042d4ebba | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/sqlexecute.py#L100-L105 |
18,719 | dbcli/athenacli | athenacli/sqlexecute.py | SQLExecute.table_columns | def table_columns(self):
'''Yields column names.'''
with self.conn.cursor() as cur:
cur.execute(self.TABLE_COLUMNS_QUERY % self.database)
for row in cur:
yield row | python | def table_columns(self):
'''Yields column names.'''
with self.conn.cursor() as cur:
cur.execute(self.TABLE_COLUMNS_QUERY % self.database)
for row in cur:
yield row | [
"def",
"table_columns",
"(",
"self",
")",
":",
"with",
"self",
".",
"conn",
".",
"cursor",
"(",
")",
"as",
"cur",
":",
"cur",
".",
"execute",
"(",
"self",
".",
"TABLE_COLUMNS_QUERY",
"%",
"self",
".",
"database",
")",
"for",
"row",
"in",
"cur",
":",
... | Yields column names. | [
"Yields",
"column",
"names",
"."
] | bcab59e4953145866430083e902ed4d042d4ebba | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/sqlexecute.py#L107-L112 |
18,720 | dbcli/athenacli | athenacli/clitoolbar.py | create_toolbar_tokens_func | def create_toolbar_tokens_func(get_is_refreshing, show_fish_help):
"""
Return a function that generates the toolbar tokens.
"""
token = Token.Toolbar
def get_toolbar_tokens(cli):
result = []
result.append((token, ' '))
if cli.buffers[DEFAULT_BUFFER].always_multiline:
result.append((token.On, '[F3] Multiline: ON '))
else:
result.append((token.Off, '[F3] Multiline: OFF '))
if cli.buffers[DEFAULT_BUFFER].always_multiline:
result.append((token,
' (Semi-colon [;] will end the line)'))
if cli.editing_mode == EditingMode.VI:
result.append((
token.On,
'Vi-mode ({})'.format(_get_vi_mode(cli))
))
if show_fish_help():
result.append((token, ' Right-arrow to complete suggestion'))
if get_is_refreshing():
result.append((token, ' Refreshing completions...'))
return result
return get_toolbar_tokens | python | def create_toolbar_tokens_func(get_is_refreshing, show_fish_help):
token = Token.Toolbar
def get_toolbar_tokens(cli):
result = []
result.append((token, ' '))
if cli.buffers[DEFAULT_BUFFER].always_multiline:
result.append((token.On, '[F3] Multiline: ON '))
else:
result.append((token.Off, '[F3] Multiline: OFF '))
if cli.buffers[DEFAULT_BUFFER].always_multiline:
result.append((token,
' (Semi-colon [;] will end the line)'))
if cli.editing_mode == EditingMode.VI:
result.append((
token.On,
'Vi-mode ({})'.format(_get_vi_mode(cli))
))
if show_fish_help():
result.append((token, ' Right-arrow to complete suggestion'))
if get_is_refreshing():
result.append((token, ' Refreshing completions...'))
return result
return get_toolbar_tokens | [
"def",
"create_toolbar_tokens_func",
"(",
"get_is_refreshing",
",",
"show_fish_help",
")",
":",
"token",
"=",
"Token",
".",
"Toolbar",
"def",
"get_toolbar_tokens",
"(",
"cli",
")",
":",
"result",
"=",
"[",
"]",
"result",
".",
"append",
"(",
"(",
"token",
","... | Return a function that generates the toolbar tokens. | [
"Return",
"a",
"function",
"that",
"generates",
"the",
"toolbar",
"tokens",
"."
] | bcab59e4953145866430083e902ed4d042d4ebba | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/clitoolbar.py#L6-L38 |
18,721 | dbcli/athenacli | athenacli/clitoolbar.py | _get_vi_mode | def _get_vi_mode(cli):
"""Get the current vi mode for display."""
return {
InputMode.INSERT: 'I',
InputMode.NAVIGATION: 'N',
InputMode.REPLACE: 'R',
InputMode.INSERT_MULTIPLE: 'M'
}[cli.vi_state.input_mode] | python | def _get_vi_mode(cli):
return {
InputMode.INSERT: 'I',
InputMode.NAVIGATION: 'N',
InputMode.REPLACE: 'R',
InputMode.INSERT_MULTIPLE: 'M'
}[cli.vi_state.input_mode] | [
"def",
"_get_vi_mode",
"(",
"cli",
")",
":",
"return",
"{",
"InputMode",
".",
"INSERT",
":",
"'I'",
",",
"InputMode",
".",
"NAVIGATION",
":",
"'N'",
",",
"InputMode",
".",
"REPLACE",
":",
"'R'",
",",
"InputMode",
".",
"INSERT_MULTIPLE",
":",
"'M'",
"}",
... | Get the current vi mode for display. | [
"Get",
"the",
"current",
"vi",
"mode",
"for",
"display",
"."
] | bcab59e4953145866430083e902ed4d042d4ebba | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/clitoolbar.py#L41-L48 |
18,722 | dbcli/athenacli | athenacli/packages/special/__init__.py | export | def export(defn):
"""Decorator to explicitly mark functions that are exposed in a lib."""
globals()[defn.__name__] = defn
__all__.append(defn.__name__)
return defn | python | def export(defn):
globals()[defn.__name__] = defn
__all__.append(defn.__name__)
return defn | [
"def",
"export",
"(",
"defn",
")",
":",
"globals",
"(",
")",
"[",
"defn",
".",
"__name__",
"]",
"=",
"defn",
"__all__",
".",
"append",
"(",
"defn",
".",
"__name__",
")",
"return",
"defn"
] | Decorator to explicitly mark functions that are exposed in a lib. | [
"Decorator",
"to",
"explicitly",
"mark",
"functions",
"that",
"are",
"exposed",
"in",
"a",
"lib",
"."
] | bcab59e4953145866430083e902ed4d042d4ebba | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/packages/special/__init__.py#L5-L9 |
18,723 | dbcli/athenacli | athenacli/packages/special/main.py | execute | def execute(cur, sql):
"""Execute a special command and return the results. If the special command
is not supported a KeyError will be raised.
"""
command, verbose, arg = parse_special_command(sql)
if (command not in COMMANDS) and (command.lower() not in COMMANDS):
raise CommandNotFound
try:
special_cmd = COMMANDS[command]
except KeyError:
special_cmd = COMMANDS[command.lower()]
if special_cmd.case_sensitive:
raise CommandNotFound('Command not found: %s' % command)
# "help <SQL KEYWORD> is a special case.
if command == 'help' and arg:
return show_keyword_help(cur=cur, arg=arg)
if special_cmd.arg_type == NO_QUERY:
return special_cmd.handler()
elif special_cmd.arg_type == PARSED_QUERY:
return special_cmd.handler(cur=cur, arg=arg, verbose=verbose)
elif special_cmd.arg_type == RAW_QUERY:
return special_cmd.handler(cur=cur, query=sql) | python | def execute(cur, sql):
command, verbose, arg = parse_special_command(sql)
if (command not in COMMANDS) and (command.lower() not in COMMANDS):
raise CommandNotFound
try:
special_cmd = COMMANDS[command]
except KeyError:
special_cmd = COMMANDS[command.lower()]
if special_cmd.case_sensitive:
raise CommandNotFound('Command not found: %s' % command)
# "help <SQL KEYWORD> is a special case.
if command == 'help' and arg:
return show_keyword_help(cur=cur, arg=arg)
if special_cmd.arg_type == NO_QUERY:
return special_cmd.handler()
elif special_cmd.arg_type == PARSED_QUERY:
return special_cmd.handler(cur=cur, arg=arg, verbose=verbose)
elif special_cmd.arg_type == RAW_QUERY:
return special_cmd.handler(cur=cur, query=sql) | [
"def",
"execute",
"(",
"cur",
",",
"sql",
")",
":",
"command",
",",
"verbose",
",",
"arg",
"=",
"parse_special_command",
"(",
"sql",
")",
"if",
"(",
"command",
"not",
"in",
"COMMANDS",
")",
"and",
"(",
"command",
".",
"lower",
"(",
")",
"not",
"in",
... | Execute a special command and return the results. If the special command
is not supported a KeyError will be raised. | [
"Execute",
"a",
"special",
"command",
"and",
"return",
"the",
"results",
".",
"If",
"the",
"special",
"command",
"is",
"not",
"supported",
"a",
"KeyError",
"will",
"be",
"raised",
"."
] | bcab59e4953145866430083e902ed4d042d4ebba | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/packages/special/main.py#L51-L76 |
18,724 | dbcli/athenacli | athenacli/packages/parseutils.py | find_prev_keyword | def find_prev_keyword(sql):
""" Find the last sql keyword in an SQL statement
Returns the value of the last keyword, and the text of the query with
everything after the last keyword stripped
"""
if not sql.strip():
return None, ''
parsed = sqlparse.parse(sql)[0]
flattened = list(parsed.flatten())
logical_operators = ('AND', 'OR', 'NOT', 'BETWEEN')
for t in reversed(flattened):
if t.value == '(' or (t.is_keyword and (
t.value.upper() not in logical_operators)):
# Find the location of token t in the original parsed statement
# We can't use parsed.token_index(t) because t may be a child token
# inside a TokenList, in which case token_index thows an error
# Minimal example:
# p = sqlparse.parse('select * from foo where bar')
# t = list(p.flatten())[-3] # The "Where" token
# p.token_index(t) # Throws ValueError: not in list
idx = flattened.index(t)
# Combine the string values of all tokens in the original list
# up to and including the target keyword token t, to produce a
# query string with everything after the keyword token removed
text = ''.join(tok.value for tok in flattened[:idx+1])
return t, text
return None, '' | python | def find_prev_keyword(sql):
if not sql.strip():
return None, ''
parsed = sqlparse.parse(sql)[0]
flattened = list(parsed.flatten())
logical_operators = ('AND', 'OR', 'NOT', 'BETWEEN')
for t in reversed(flattened):
if t.value == '(' or (t.is_keyword and (
t.value.upper() not in logical_operators)):
# Find the location of token t in the original parsed statement
# We can't use parsed.token_index(t) because t may be a child token
# inside a TokenList, in which case token_index thows an error
# Minimal example:
# p = sqlparse.parse('select * from foo where bar')
# t = list(p.flatten())[-3] # The "Where" token
# p.token_index(t) # Throws ValueError: not in list
idx = flattened.index(t)
# Combine the string values of all tokens in the original list
# up to and including the target keyword token t, to produce a
# query string with everything after the keyword token removed
text = ''.join(tok.value for tok in flattened[:idx+1])
return t, text
return None, '' | [
"def",
"find_prev_keyword",
"(",
"sql",
")",
":",
"if",
"not",
"sql",
".",
"strip",
"(",
")",
":",
"return",
"None",
",",
"''",
"parsed",
"=",
"sqlparse",
".",
"parse",
"(",
"sql",
")",
"[",
"0",
"]",
"flattened",
"=",
"list",
"(",
"parsed",
".",
... | Find the last sql keyword in an SQL statement
Returns the value of the last keyword, and the text of the query with
everything after the last keyword stripped | [
"Find",
"the",
"last",
"sql",
"keyword",
"in",
"an",
"SQL",
"statement",
"Returns",
"the",
"value",
"of",
"the",
"last",
"keyword",
"and",
"the",
"text",
"of",
"the",
"query",
"with",
"everything",
"after",
"the",
"last",
"keyword",
"stripped"
] | bcab59e4953145866430083e902ed4d042d4ebba | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/packages/parseutils.py#L153-L184 |
18,725 | divio/cmsplugin-filer | cmsplugin_filer_teaser/cms_plugins.py | FilerTeaserPlugin._get_thumbnail_options | def _get_thumbnail_options(self, context, instance):
"""
Return the size and options of the thumbnail that should be inserted
"""
width, height = None, None
subject_location = False
placeholder_width = context.get('width', None)
placeholder_height = context.get('height', None)
if instance.use_autoscale and placeholder_width:
# use the placeholder width as a hint for sizing
width = int(placeholder_width)
if instance.use_autoscale and placeholder_height:
height = int(placeholder_height)
elif instance.width:
width = instance.width
if instance.height:
height = instance.height
if instance.image:
if instance.image.subject_location:
subject_location = instance.image.subject_location
if not height and width:
# height was not externally defined: use ratio to scale it by the width
height = int(float(width) * float(instance.image.height) / float(instance.image.width))
if not width and height:
# width was not externally defined: use ratio to scale it by the height
width = int(float(height) * float(instance.image.width) / float(instance.image.height))
if not width:
# width is still not defined. fallback the actual image width
width = instance.image.width
if not height:
# height is still not defined. fallback the actual image height
height = instance.image.height
return {'size': (width, height),
'subject_location': subject_location} | python | def _get_thumbnail_options(self, context, instance):
width, height = None, None
subject_location = False
placeholder_width = context.get('width', None)
placeholder_height = context.get('height', None)
if instance.use_autoscale and placeholder_width:
# use the placeholder width as a hint for sizing
width = int(placeholder_width)
if instance.use_autoscale and placeholder_height:
height = int(placeholder_height)
elif instance.width:
width = instance.width
if instance.height:
height = instance.height
if instance.image:
if instance.image.subject_location:
subject_location = instance.image.subject_location
if not height and width:
# height was not externally defined: use ratio to scale it by the width
height = int(float(width) * float(instance.image.height) / float(instance.image.width))
if not width and height:
# width was not externally defined: use ratio to scale it by the height
width = int(float(height) * float(instance.image.width) / float(instance.image.height))
if not width:
# width is still not defined. fallback the actual image width
width = instance.image.width
if not height:
# height is still not defined. fallback the actual image height
height = instance.image.height
return {'size': (width, height),
'subject_location': subject_location} | [
"def",
"_get_thumbnail_options",
"(",
"self",
",",
"context",
",",
"instance",
")",
":",
"width",
",",
"height",
"=",
"None",
",",
"None",
"subject_location",
"=",
"False",
"placeholder_width",
"=",
"context",
".",
"get",
"(",
"'width'",
",",
"None",
")",
... | Return the size and options of the thumbnail that should be inserted | [
"Return",
"the",
"size",
"and",
"options",
"of",
"the",
"thumbnail",
"that",
"should",
"be",
"inserted"
] | 4f9b0307dd768852ead64e651b743a165b3efccb | https://github.com/divio/cmsplugin-filer/blob/4f9b0307dd768852ead64e651b743a165b3efccb/cmsplugin_filer_teaser/cms_plugins.py#L42-L75 |
18,726 | divio/cmsplugin-filer | cmsplugin_filer_image/integrations/ckeditor.py | create_image_plugin | def create_image_plugin(filename, image, parent_plugin, **kwargs):
"""
Used for drag-n-drop image insertion with djangocms-text-ckeditor.
Set TEXT_SAVE_IMAGE_FUNCTION='cmsplugin_filer_image.integrations.ckeditor.create_image_plugin' to enable.
"""
from cmsplugin_filer_image.models import FilerImage
from filer.models import Image
image_plugin = FilerImage()
image_plugin.placeholder = parent_plugin.placeholder
image_plugin.parent = CMSPlugin.objects.get(pk=parent_plugin.id)
image_plugin.position = CMSPlugin.objects.filter(parent=parent_plugin).count()
image_plugin.language = parent_plugin.language
image_plugin.plugin_type = 'FilerImagePlugin'
image.seek(0)
image_model = Image.objects.create(file=SimpleUploadedFile(name=filename, content=image.read()))
image_plugin.image = image_model
image_plugin.save()
return image_plugin | python | def create_image_plugin(filename, image, parent_plugin, **kwargs):
from cmsplugin_filer_image.models import FilerImage
from filer.models import Image
image_plugin = FilerImage()
image_plugin.placeholder = parent_plugin.placeholder
image_plugin.parent = CMSPlugin.objects.get(pk=parent_plugin.id)
image_plugin.position = CMSPlugin.objects.filter(parent=parent_plugin).count()
image_plugin.language = parent_plugin.language
image_plugin.plugin_type = 'FilerImagePlugin'
image.seek(0)
image_model = Image.objects.create(file=SimpleUploadedFile(name=filename, content=image.read()))
image_plugin.image = image_model
image_plugin.save()
return image_plugin | [
"def",
"create_image_plugin",
"(",
"filename",
",",
"image",
",",
"parent_plugin",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"cmsplugin_filer_image",
".",
"models",
"import",
"FilerImage",
"from",
"filer",
".",
"models",
"import",
"Image",
"image_plugin",
"=",
... | Used for drag-n-drop image insertion with djangocms-text-ckeditor.
Set TEXT_SAVE_IMAGE_FUNCTION='cmsplugin_filer_image.integrations.ckeditor.create_image_plugin' to enable. | [
"Used",
"for",
"drag",
"-",
"n",
"-",
"drop",
"image",
"insertion",
"with",
"djangocms",
"-",
"text",
"-",
"ckeditor",
".",
"Set",
"TEXT_SAVE_IMAGE_FUNCTION",
"=",
"cmsplugin_filer_image",
".",
"integrations",
".",
"ckeditor",
".",
"create_image_plugin",
"to",
"... | 4f9b0307dd768852ead64e651b743a165b3efccb | https://github.com/divio/cmsplugin-filer/blob/4f9b0307dd768852ead64e651b743a165b3efccb/cmsplugin_filer_image/integrations/ckeditor.py#L6-L23 |
18,727 | divio/cmsplugin-filer | cmsplugin_filer_utils/migration.py | rename_tables | def rename_tables(db, table_mapping, reverse=False):
"""
renames tables from source to destination name, if the source exists and the destination does
not exist yet.
"""
from django.db import connection
if reverse:
table_mapping = [(dst, src) for src, dst in table_mapping]
table_names = connection.introspection.table_names()
for source, destination in table_mapping:
if source in table_names and destination in table_names:
print(u" WARNING: not renaming {0} to {1}, because both tables already exist.".format(source, destination))
elif source in table_names and destination not in table_names:
print(u" - renaming {0} to {1}".format(source, destination))
db.rename_table(source, destination) | python | def rename_tables(db, table_mapping, reverse=False):
from django.db import connection
if reverse:
table_mapping = [(dst, src) for src, dst in table_mapping]
table_names = connection.introspection.table_names()
for source, destination in table_mapping:
if source in table_names and destination in table_names:
print(u" WARNING: not renaming {0} to {1}, because both tables already exist.".format(source, destination))
elif source in table_names and destination not in table_names:
print(u" - renaming {0} to {1}".format(source, destination))
db.rename_table(source, destination) | [
"def",
"rename_tables",
"(",
"db",
",",
"table_mapping",
",",
"reverse",
"=",
"False",
")",
":",
"from",
"django",
".",
"db",
"import",
"connection",
"if",
"reverse",
":",
"table_mapping",
"=",
"[",
"(",
"dst",
",",
"src",
")",
"for",
"src",
",",
"dst"... | renames tables from source to destination name, if the source exists and the destination does
not exist yet. | [
"renames",
"tables",
"from",
"source",
"to",
"destination",
"name",
"if",
"the",
"source",
"exists",
"and",
"the",
"destination",
"does",
"not",
"exist",
"yet",
"."
] | 4f9b0307dd768852ead64e651b743a165b3efccb | https://github.com/divio/cmsplugin-filer/blob/4f9b0307dd768852ead64e651b743a165b3efccb/cmsplugin_filer_utils/migration.py#L4-L18 |
18,728 | sorgerlab/indra | indra/util/statement_presentation.py | group_and_sort_statements | def group_and_sort_statements(stmt_list, ev_totals=None):
"""Group statements by type and arguments, and sort by prevalence.
Parameters
----------
stmt_list : list[Statement]
A list of INDRA statements.
ev_totals : dict{int: int}
A dictionary, keyed by statement hash (shallow) with counts of total
evidence as the values. Including this will allow statements to be
better sorted.
Returns
-------
sorted_groups : list[tuple]
A list of tuples containing a sort key, the statement type, and a list
of statements, also sorted by evidence count, for that key and type.
The sort key contains a count of statements with those argument, the
arguments (normalized strings), the count of statements with those
arguements and type, and then the statement type.
"""
def _count(stmt):
if ev_totals is None:
return len(stmt.evidence)
else:
return ev_totals[stmt.get_hash()]
stmt_rows = defaultdict(list)
stmt_counts = defaultdict(lambda: 0)
arg_counts = defaultdict(lambda: 0)
for key, s in _get_keyed_stmts(stmt_list):
# Update the counts, and add key if needed.
stmt_rows[key].append(s)
# Keep track of the total evidence counts for this statement and the
# arguments.
stmt_counts[key] += _count(s)
# Add up the counts for the arguments, pairwise for Complexes and
# Conversions. This allows, for example, a complex between MEK, ERK,
# and something else to lend weight to the interactions between MEK
# and ERK.
if key[0] == 'Conversion':
subj = key[1]
for obj in key[2] + key[3]:
arg_counts[(subj, obj)] += _count(s)
else:
arg_counts[key[1:]] += _count(s)
# Sort the rows by count and agent names.
def process_rows(stmt_rows):
for key, stmts in stmt_rows.items():
verb = key[0]
inps = key[1:]
sub_count = stmt_counts[key]
arg_count = arg_counts[inps]
if verb == 'Complex' and sub_count == arg_count and len(inps) <= 2:
if all([len(set(ag.name for ag in s.agent_list())) > 2
for s in stmts]):
continue
new_key = (arg_count, inps, sub_count, verb)
stmts = sorted(stmts,
key=lambda s: _count(s) + 1/(1+len(s.agent_list())),
reverse=True)
yield new_key, verb, stmts
sorted_groups = sorted(process_rows(stmt_rows),
key=lambda tpl: tpl[0], reverse=True)
return sorted_groups | python | def group_and_sort_statements(stmt_list, ev_totals=None):
def _count(stmt):
if ev_totals is None:
return len(stmt.evidence)
else:
return ev_totals[stmt.get_hash()]
stmt_rows = defaultdict(list)
stmt_counts = defaultdict(lambda: 0)
arg_counts = defaultdict(lambda: 0)
for key, s in _get_keyed_stmts(stmt_list):
# Update the counts, and add key if needed.
stmt_rows[key].append(s)
# Keep track of the total evidence counts for this statement and the
# arguments.
stmt_counts[key] += _count(s)
# Add up the counts for the arguments, pairwise for Complexes and
# Conversions. This allows, for example, a complex between MEK, ERK,
# and something else to lend weight to the interactions between MEK
# and ERK.
if key[0] == 'Conversion':
subj = key[1]
for obj in key[2] + key[3]:
arg_counts[(subj, obj)] += _count(s)
else:
arg_counts[key[1:]] += _count(s)
# Sort the rows by count and agent names.
def process_rows(stmt_rows):
for key, stmts in stmt_rows.items():
verb = key[0]
inps = key[1:]
sub_count = stmt_counts[key]
arg_count = arg_counts[inps]
if verb == 'Complex' and sub_count == arg_count and len(inps) <= 2:
if all([len(set(ag.name for ag in s.agent_list())) > 2
for s in stmts]):
continue
new_key = (arg_count, inps, sub_count, verb)
stmts = sorted(stmts,
key=lambda s: _count(s) + 1/(1+len(s.agent_list())),
reverse=True)
yield new_key, verb, stmts
sorted_groups = sorted(process_rows(stmt_rows),
key=lambda tpl: tpl[0], reverse=True)
return sorted_groups | [
"def",
"group_and_sort_statements",
"(",
"stmt_list",
",",
"ev_totals",
"=",
"None",
")",
":",
"def",
"_count",
"(",
"stmt",
")",
":",
"if",
"ev_totals",
"is",
"None",
":",
"return",
"len",
"(",
"stmt",
".",
"evidence",
")",
"else",
":",
"return",
"ev_to... | Group statements by type and arguments, and sort by prevalence.
Parameters
----------
stmt_list : list[Statement]
A list of INDRA statements.
ev_totals : dict{int: int}
A dictionary, keyed by statement hash (shallow) with counts of total
evidence as the values. Including this will allow statements to be
better sorted.
Returns
-------
sorted_groups : list[tuple]
A list of tuples containing a sort key, the statement type, and a list
of statements, also sorted by evidence count, for that key and type.
The sort key contains a count of statements with those argument, the
arguments (normalized strings), the count of statements with those
arguements and type, and then the statement type. | [
"Group",
"statements",
"by",
"type",
"and",
"arguments",
"and",
"sort",
"by",
"prevalence",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/util/statement_presentation.py#L40-L109 |
18,729 | sorgerlab/indra | indra/util/statement_presentation.py | make_stmt_from_sort_key | def make_stmt_from_sort_key(key, verb):
"""Make a Statement from the sort key.
Specifically, the sort key used by `group_and_sort_statements`.
"""
def make_agent(name):
if name == 'None' or name is None:
return None
return Agent(name)
StmtClass = get_statement_by_name(verb)
inps = list(key[1])
if verb == 'Complex':
stmt = StmtClass([make_agent(name) for name in inps])
elif verb == 'Conversion':
stmt = StmtClass(make_agent(inps[0]),
[make_agent(name) for name in inps[1]],
[make_agent(name) for name in inps[2]])
elif verb == 'ActiveForm' or verb == 'HasActivity':
stmt = StmtClass(make_agent(inps[0]), inps[1], inps[2])
else:
stmt = StmtClass(*[make_agent(name) for name in inps])
return stmt | python | def make_stmt_from_sort_key(key, verb):
def make_agent(name):
if name == 'None' or name is None:
return None
return Agent(name)
StmtClass = get_statement_by_name(verb)
inps = list(key[1])
if verb == 'Complex':
stmt = StmtClass([make_agent(name) for name in inps])
elif verb == 'Conversion':
stmt = StmtClass(make_agent(inps[0]),
[make_agent(name) for name in inps[1]],
[make_agent(name) for name in inps[2]])
elif verb == 'ActiveForm' or verb == 'HasActivity':
stmt = StmtClass(make_agent(inps[0]), inps[1], inps[2])
else:
stmt = StmtClass(*[make_agent(name) for name in inps])
return stmt | [
"def",
"make_stmt_from_sort_key",
"(",
"key",
",",
"verb",
")",
":",
"def",
"make_agent",
"(",
"name",
")",
":",
"if",
"name",
"==",
"'None'",
"or",
"name",
"is",
"None",
":",
"return",
"None",
"return",
"Agent",
"(",
"name",
")",
"StmtClass",
"=",
"ge... | Make a Statement from the sort key.
Specifically, the sort key used by `group_and_sort_statements`. | [
"Make",
"a",
"Statement",
"from",
"the",
"sort",
"key",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/util/statement_presentation.py#L112-L134 |
18,730 | sorgerlab/indra | indra/tools/reading/submit_reading_pipeline.py | get_ecs_cluster_for_queue | def get_ecs_cluster_for_queue(queue_name, batch_client=None):
"""Get the name of the ecs cluster using the batch client."""
if batch_client is None:
batch_client = boto3.client('batch')
queue_resp = batch_client.describe_job_queues(jobQueues=[queue_name])
if len(queue_resp['jobQueues']) == 1:
queue = queue_resp['jobQueues'][0]
else:
raise BatchReadingError('Error finding queue with name %s.'
% queue_name)
compute_env_names = queue['computeEnvironmentOrder']
if len(compute_env_names) == 1:
compute_env_name = compute_env_names[0]['computeEnvironment']
else:
raise BatchReadingError('Error finding the compute environment name '
'for %s.' % queue_name)
compute_envs = batch_client.describe_compute_environments(
computeEnvironments=[compute_env_name]
)['computeEnvironments']
if len(compute_envs) == 1:
compute_env = compute_envs[0]
else:
raise BatchReadingError("Error getting compute environment %s for %s. "
"Got %d environments instead of 1."
% (compute_env_name, queue_name,
len(compute_envs)))
ecs_cluster_name = os.path.basename(compute_env['ecsClusterArn'])
return ecs_cluster_name | python | def get_ecs_cluster_for_queue(queue_name, batch_client=None):
if batch_client is None:
batch_client = boto3.client('batch')
queue_resp = batch_client.describe_job_queues(jobQueues=[queue_name])
if len(queue_resp['jobQueues']) == 1:
queue = queue_resp['jobQueues'][0]
else:
raise BatchReadingError('Error finding queue with name %s.'
% queue_name)
compute_env_names = queue['computeEnvironmentOrder']
if len(compute_env_names) == 1:
compute_env_name = compute_env_names[0]['computeEnvironment']
else:
raise BatchReadingError('Error finding the compute environment name '
'for %s.' % queue_name)
compute_envs = batch_client.describe_compute_environments(
computeEnvironments=[compute_env_name]
)['computeEnvironments']
if len(compute_envs) == 1:
compute_env = compute_envs[0]
else:
raise BatchReadingError("Error getting compute environment %s for %s. "
"Got %d environments instead of 1."
% (compute_env_name, queue_name,
len(compute_envs)))
ecs_cluster_name = os.path.basename(compute_env['ecsClusterArn'])
return ecs_cluster_name | [
"def",
"get_ecs_cluster_for_queue",
"(",
"queue_name",
",",
"batch_client",
"=",
"None",
")",
":",
"if",
"batch_client",
"is",
"None",
":",
"batch_client",
"=",
"boto3",
".",
"client",
"(",
"'batch'",
")",
"queue_resp",
"=",
"batch_client",
".",
"describe_job_qu... | Get the name of the ecs cluster using the batch client. | [
"Get",
"the",
"name",
"of",
"the",
"ecs",
"cluster",
"using",
"the",
"batch",
"client",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/reading/submit_reading_pipeline.py#L275-L306 |
18,731 | sorgerlab/indra | indra/tools/reading/submit_reading_pipeline.py | tag_instances_on_cluster | def tag_instances_on_cluster(cluster_name, project='cwc'):
"""Adds project tag to untagged instances in a given cluster.
Parameters
----------
cluster_name : str
The name of the AWS ECS cluster in which running instances
should be tagged.
project : str
The name of the project to tag instances with.
"""
# Get the relevant instance ids from the ecs cluster
ecs = boto3.client('ecs')
task_arns = ecs.list_tasks(cluster=cluster_name)['taskArns']
if not task_arns:
return
tasks = ecs.describe_tasks(cluster=cluster_name, tasks=task_arns)['tasks']
container_instances = ecs.describe_container_instances(
cluster=cluster_name,
containerInstances=[task['containerInstanceArn'] for task in tasks]
)['containerInstances']
ec2_instance_ids = [ci['ec2InstanceId'] for ci in container_instances]
# Instantiate each instance to tag as a resource and create project tag
for instance_id in ec2_instance_ids:
tag_instance(instance_id, project=project)
return | python | def tag_instances_on_cluster(cluster_name, project='cwc'):
# Get the relevant instance ids from the ecs cluster
ecs = boto3.client('ecs')
task_arns = ecs.list_tasks(cluster=cluster_name)['taskArns']
if not task_arns:
return
tasks = ecs.describe_tasks(cluster=cluster_name, tasks=task_arns)['tasks']
container_instances = ecs.describe_container_instances(
cluster=cluster_name,
containerInstances=[task['containerInstanceArn'] for task in tasks]
)['containerInstances']
ec2_instance_ids = [ci['ec2InstanceId'] for ci in container_instances]
# Instantiate each instance to tag as a resource and create project tag
for instance_id in ec2_instance_ids:
tag_instance(instance_id, project=project)
return | [
"def",
"tag_instances_on_cluster",
"(",
"cluster_name",
",",
"project",
"=",
"'cwc'",
")",
":",
"# Get the relevant instance ids from the ecs cluster",
"ecs",
"=",
"boto3",
".",
"client",
"(",
"'ecs'",
")",
"task_arns",
"=",
"ecs",
".",
"list_tasks",
"(",
"cluster",... | Adds project tag to untagged instances in a given cluster.
Parameters
----------
cluster_name : str
The name of the AWS ECS cluster in which running instances
should be tagged.
project : str
The name of the project to tag instances with. | [
"Adds",
"project",
"tag",
"to",
"untagged",
"instances",
"in",
"a",
"given",
"cluster",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/reading/submit_reading_pipeline.py#L309-L335 |
18,732 | sorgerlab/indra | indra/tools/reading/submit_reading_pipeline.py | submit_reading | def submit_reading(basename, pmid_list_filename, readers, start_ix=None,
end_ix=None, pmids_per_job=3000, num_tries=2,
force_read=False, force_fulltext=False, project_name=None):
"""Submit an old-style pmid-centered no-database s3 only reading job.
This function is provided for the sake of backward compatibility. It is
preferred that you use the object-oriented PmidSubmitter and the
submit_reading job going forward.
"""
sub = PmidSubmitter(basename, readers, project_name)
sub.set_options(force_read, force_fulltext)
sub.submit_reading(pmid_list_filename, start_ix, end_ix, pmids_per_job,
num_tries)
return sub.job_list | python | def submit_reading(basename, pmid_list_filename, readers, start_ix=None,
end_ix=None, pmids_per_job=3000, num_tries=2,
force_read=False, force_fulltext=False, project_name=None):
sub = PmidSubmitter(basename, readers, project_name)
sub.set_options(force_read, force_fulltext)
sub.submit_reading(pmid_list_filename, start_ix, end_ix, pmids_per_job,
num_tries)
return sub.job_list | [
"def",
"submit_reading",
"(",
"basename",
",",
"pmid_list_filename",
",",
"readers",
",",
"start_ix",
"=",
"None",
",",
"end_ix",
"=",
"None",
",",
"pmids_per_job",
"=",
"3000",
",",
"num_tries",
"=",
"2",
",",
"force_read",
"=",
"False",
",",
"force_fulltex... | Submit an old-style pmid-centered no-database s3 only reading job.
This function is provided for the sake of backward compatibility. It is
preferred that you use the object-oriented PmidSubmitter and the
submit_reading job going forward. | [
"Submit",
"an",
"old",
"-",
"style",
"pmid",
"-",
"centered",
"no",
"-",
"database",
"s3",
"only",
"reading",
"job",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/reading/submit_reading_pipeline.py#L555-L568 |
18,733 | sorgerlab/indra | indra/tools/reading/submit_reading_pipeline.py | submit_combine | def submit_combine(basename, readers, job_ids=None, project_name=None):
"""Submit a batch job to combine the outputs of a reading job.
This function is provided for backwards compatibility. You should use the
PmidSubmitter and submit_combine methods.
"""
sub = PmidSubmitter(basename, readers, project_name)
sub.job_list = job_ids
sub.submit_combine()
return sub | python | def submit_combine(basename, readers, job_ids=None, project_name=None):
sub = PmidSubmitter(basename, readers, project_name)
sub.job_list = job_ids
sub.submit_combine()
return sub | [
"def",
"submit_combine",
"(",
"basename",
",",
"readers",
",",
"job_ids",
"=",
"None",
",",
"project_name",
"=",
"None",
")",
":",
"sub",
"=",
"PmidSubmitter",
"(",
"basename",
",",
"readers",
",",
"project_name",
")",
"sub",
".",
"job_list",
"=",
"job_ids... | Submit a batch job to combine the outputs of a reading job.
This function is provided for backwards compatibility. You should use the
PmidSubmitter and submit_combine methods. | [
"Submit",
"a",
"batch",
"job",
"to",
"combine",
"the",
"outputs",
"of",
"a",
"reading",
"job",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/reading/submit_reading_pipeline.py#L571-L580 |
18,734 | sorgerlab/indra | indra/tools/reading/submit_reading_pipeline.py | Submitter.submit_reading | def submit_reading(self, input_fname, start_ix, end_ix, ids_per_job,
num_tries=1, stagger=0):
"""Submit a batch of reading jobs
Parameters
----------
input_fname : str
The name of the file containing the ids to be read.
start_ix : int
The line index of the first item in the list to read.
end_ix : int
The line index of the last item in the list to be read.
ids_per_job : int
The number of ids to be given to each job.
num_tries : int
The number of times a job may be attempted.
stagger : float
The number of seconds to wait between job submissions.
Returns
-------
job_list : list[str]
A list of job id strings.
"""
# stash this for later.
self.ids_per_job = ids_per_job
# Upload the pmid_list to Amazon S3
id_list_key = 'reading_results/%s/%s' % (self.basename,
self._s3_input_name)
s3_client = boto3.client('s3')
s3_client.upload_file(input_fname, bucket_name, id_list_key)
# If no end index is specified, read all the PMIDs
if end_ix is None:
with open(input_fname, 'rt') as f:
lines = f.readlines()
end_ix = len(lines)
if start_ix is None:
start_ix = 0
# Get environment variables
environment_vars = get_environment()
# Iterate over the list of PMIDs and submit the job in chunks
batch_client = boto3.client('batch', region_name='us-east-1')
job_list = []
for job_start_ix in range(start_ix, end_ix, ids_per_job):
sleep(stagger)
job_end_ix = job_start_ix + ids_per_job
if job_end_ix > end_ix:
job_end_ix = end_ix
job_name, cmd = self._make_command(job_start_ix, job_end_ix)
command_list = get_batch_command(cmd, purpose=self._purpose,
project=self.project_name)
logger.info('Command list: %s' % str(command_list))
job_info = batch_client.submit_job(
jobName=job_name,
jobQueue=self._job_queue,
jobDefinition=self._job_def,
containerOverrides={
'environment': environment_vars,
'command': command_list},
retryStrategy={'attempts': num_tries}
)
logger.info("submitted...")
job_list.append({'jobId': job_info['jobId']})
self.job_list = job_list
return job_list | python | def submit_reading(self, input_fname, start_ix, end_ix, ids_per_job,
num_tries=1, stagger=0):
# stash this for later.
self.ids_per_job = ids_per_job
# Upload the pmid_list to Amazon S3
id_list_key = 'reading_results/%s/%s' % (self.basename,
self._s3_input_name)
s3_client = boto3.client('s3')
s3_client.upload_file(input_fname, bucket_name, id_list_key)
# If no end index is specified, read all the PMIDs
if end_ix is None:
with open(input_fname, 'rt') as f:
lines = f.readlines()
end_ix = len(lines)
if start_ix is None:
start_ix = 0
# Get environment variables
environment_vars = get_environment()
# Iterate over the list of PMIDs and submit the job in chunks
batch_client = boto3.client('batch', region_name='us-east-1')
job_list = []
for job_start_ix in range(start_ix, end_ix, ids_per_job):
sleep(stagger)
job_end_ix = job_start_ix + ids_per_job
if job_end_ix > end_ix:
job_end_ix = end_ix
job_name, cmd = self._make_command(job_start_ix, job_end_ix)
command_list = get_batch_command(cmd, purpose=self._purpose,
project=self.project_name)
logger.info('Command list: %s' % str(command_list))
job_info = batch_client.submit_job(
jobName=job_name,
jobQueue=self._job_queue,
jobDefinition=self._job_def,
containerOverrides={
'environment': environment_vars,
'command': command_list},
retryStrategy={'attempts': num_tries}
)
logger.info("submitted...")
job_list.append({'jobId': job_info['jobId']})
self.job_list = job_list
return job_list | [
"def",
"submit_reading",
"(",
"self",
",",
"input_fname",
",",
"start_ix",
",",
"end_ix",
",",
"ids_per_job",
",",
"num_tries",
"=",
"1",
",",
"stagger",
"=",
"0",
")",
":",
"# stash this for later.",
"self",
".",
"ids_per_job",
"=",
"ids_per_job",
"# Upload t... | Submit a batch of reading jobs
Parameters
----------
input_fname : str
The name of the file containing the ids to be read.
start_ix : int
The line index of the first item in the list to read.
end_ix : int
The line index of the last item in the list to be read.
ids_per_job : int
The number of ids to be given to each job.
num_tries : int
The number of times a job may be attempted.
stagger : float
The number of seconds to wait between job submissions.
Returns
-------
job_list : list[str]
A list of job id strings. | [
"Submit",
"a",
"batch",
"of",
"reading",
"jobs"
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/reading/submit_reading_pipeline.py#L397-L466 |
18,735 | sorgerlab/indra | indra/tools/reading/submit_reading_pipeline.py | Submitter.watch_and_wait | def watch_and_wait(self, poll_interval=10, idle_log_timeout=None,
kill_on_timeout=False, stash_log_method=None,
tag_instances=False, **kwargs):
"""This provides shortcut access to the wait_for_complete_function."""
return wait_for_complete(self._job_queue, job_list=self.job_list,
job_name_prefix=self.basename,
poll_interval=poll_interval,
idle_log_timeout=idle_log_timeout,
kill_on_log_timeout=kill_on_timeout,
stash_log_method=stash_log_method,
tag_instances=tag_instances, **kwargs) | python | def watch_and_wait(self, poll_interval=10, idle_log_timeout=None,
kill_on_timeout=False, stash_log_method=None,
tag_instances=False, **kwargs):
return wait_for_complete(self._job_queue, job_list=self.job_list,
job_name_prefix=self.basename,
poll_interval=poll_interval,
idle_log_timeout=idle_log_timeout,
kill_on_log_timeout=kill_on_timeout,
stash_log_method=stash_log_method,
tag_instances=tag_instances, **kwargs) | [
"def",
"watch_and_wait",
"(",
"self",
",",
"poll_interval",
"=",
"10",
",",
"idle_log_timeout",
"=",
"None",
",",
"kill_on_timeout",
"=",
"False",
",",
"stash_log_method",
"=",
"None",
",",
"tag_instances",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
... | This provides shortcut access to the wait_for_complete_function. | [
"This",
"provides",
"shortcut",
"access",
"to",
"the",
"wait_for_complete_function",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/reading/submit_reading_pipeline.py#L468-L478 |
18,736 | sorgerlab/indra | indra/tools/reading/submit_reading_pipeline.py | Submitter.run | def run(self, input_fname, ids_per_job, stagger=0, **wait_params):
"""Run this submission all the way.
This method will run both `submit_reading` and `watch_and_wait`,
blocking on the latter.
"""
submit_thread = Thread(target=self.submit_reading,
args=(input_fname, 0, None, ids_per_job),
kwargs={'stagger': stagger},
daemon=True)
submit_thread.start()
self.watch_and_wait(**wait_params)
submit_thread.join(0)
if submit_thread.is_alive():
logger.warning("Submit thread is still running even after job"
"completion.")
return | python | def run(self, input_fname, ids_per_job, stagger=0, **wait_params):
submit_thread = Thread(target=self.submit_reading,
args=(input_fname, 0, None, ids_per_job),
kwargs={'stagger': stagger},
daemon=True)
submit_thread.start()
self.watch_and_wait(**wait_params)
submit_thread.join(0)
if submit_thread.is_alive():
logger.warning("Submit thread is still running even after job"
"completion.")
return | [
"def",
"run",
"(",
"self",
",",
"input_fname",
",",
"ids_per_job",
",",
"stagger",
"=",
"0",
",",
"*",
"*",
"wait_params",
")",
":",
"submit_thread",
"=",
"Thread",
"(",
"target",
"=",
"self",
".",
"submit_reading",
",",
"args",
"=",
"(",
"input_fname",
... | Run this submission all the way.
This method will run both `submit_reading` and `watch_and_wait`,
blocking on the latter. | [
"Run",
"this",
"submission",
"all",
"the",
"way",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/reading/submit_reading_pipeline.py#L480-L496 |
18,737 | sorgerlab/indra | indra/tools/reading/submit_reading_pipeline.py | PmidSubmitter.set_options | def set_options(self, force_read=False, force_fulltext=False):
"""Set the options for this run."""
self.options['force_read'] = force_read
self.options['force_fulltext'] = force_fulltext
return | python | def set_options(self, force_read=False, force_fulltext=False):
self.options['force_read'] = force_read
self.options['force_fulltext'] = force_fulltext
return | [
"def",
"set_options",
"(",
"self",
",",
"force_read",
"=",
"False",
",",
"force_fulltext",
"=",
"False",
")",
":",
"self",
".",
"options",
"[",
"'force_read'",
"]",
"=",
"force_read",
"self",
".",
"options",
"[",
"'force_fulltext'",
"]",
"=",
"force_fulltext... | Set the options for this run. | [
"Set",
"the",
"options",
"for",
"this",
"run",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/reading/submit_reading_pipeline.py#L517-L521 |
18,738 | sorgerlab/indra | indra/databases/chebi_client.py | get_chebi_name_from_id | def get_chebi_name_from_id(chebi_id, offline=False):
"""Return a ChEBI name corresponding to the given ChEBI ID.
Parameters
----------
chebi_id : str
The ChEBI ID whose name is to be returned.
offline : Optional[bool]
Choose whether to allow an online lookup if the local lookup fails. If
True, the online lookup is not attempted. Default: False.
Returns
-------
chebi_name : str
The name corresponding to the given ChEBI ID. If the lookup
fails, None is returned.
"""
chebi_name = chebi_id_to_name.get(chebi_id)
if chebi_name is None and not offline:
chebi_name = get_chebi_name_from_id_web(chebi_id)
return chebi_name | python | def get_chebi_name_from_id(chebi_id, offline=False):
chebi_name = chebi_id_to_name.get(chebi_id)
if chebi_name is None and not offline:
chebi_name = get_chebi_name_from_id_web(chebi_id)
return chebi_name | [
"def",
"get_chebi_name_from_id",
"(",
"chebi_id",
",",
"offline",
"=",
"False",
")",
":",
"chebi_name",
"=",
"chebi_id_to_name",
".",
"get",
"(",
"chebi_id",
")",
"if",
"chebi_name",
"is",
"None",
"and",
"not",
"offline",
":",
"chebi_name",
"=",
"get_chebi_nam... | Return a ChEBI name corresponding to the given ChEBI ID.
Parameters
----------
chebi_id : str
The ChEBI ID whose name is to be returned.
offline : Optional[bool]
Choose whether to allow an online lookup if the local lookup fails. If
True, the online lookup is not attempted. Default: False.
Returns
-------
chebi_name : str
The name corresponding to the given ChEBI ID. If the lookup
fails, None is returned. | [
"Return",
"a",
"ChEBI",
"name",
"corresponding",
"to",
"the",
"given",
"ChEBI",
"ID",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/databases/chebi_client.py#L86-L106 |
18,739 | sorgerlab/indra | indra/databases/chebi_client.py | get_chebi_name_from_id_web | def get_chebi_name_from_id_web(chebi_id):
"""Return a ChEBI mame corresponding to a given ChEBI ID using a REST API.
Parameters
----------
chebi_id : str
The ChEBI ID whose name is to be returned.
Returns
-------
chebi_name : str
The name corresponding to the given ChEBI ID. If the lookup
fails, None is returned.
"""
url_base = 'http://www.ebi.ac.uk/webservices/chebi/2.0/test/'
url_fmt = url_base + 'getCompleteEntity?chebiId=%s'
resp = requests.get(url_fmt % chebi_id)
if resp.status_code != 200:
logger.warning("Got bad code form CHEBI client: %s" % resp.status_code)
return None
tree = etree.fromstring(resp.content)
# Get rid of the namespaces.
# Credit: https://stackoverflow.com/questions/18159221/remove-namespace-and-prefix-from-xml-in-python-using-lxml
for elem in tree.getiterator():
if not hasattr(elem.tag, 'find'):
continue # (1)
i = elem.tag.find('}')
if i >= 0:
elem.tag = elem.tag[i+1:]
objectify.deannotate(tree, cleanup_namespaces=True)
elem = tree.find('Body/getCompleteEntityResponse/return/chebiAsciiName')
if elem is not None:
return elem.text
return None | python | def get_chebi_name_from_id_web(chebi_id):
url_base = 'http://www.ebi.ac.uk/webservices/chebi/2.0/test/'
url_fmt = url_base + 'getCompleteEntity?chebiId=%s'
resp = requests.get(url_fmt % chebi_id)
if resp.status_code != 200:
logger.warning("Got bad code form CHEBI client: %s" % resp.status_code)
return None
tree = etree.fromstring(resp.content)
# Get rid of the namespaces.
# Credit: https://stackoverflow.com/questions/18159221/remove-namespace-and-prefix-from-xml-in-python-using-lxml
for elem in tree.getiterator():
if not hasattr(elem.tag, 'find'):
continue # (1)
i = elem.tag.find('}')
if i >= 0:
elem.tag = elem.tag[i+1:]
objectify.deannotate(tree, cleanup_namespaces=True)
elem = tree.find('Body/getCompleteEntityResponse/return/chebiAsciiName')
if elem is not None:
return elem.text
return None | [
"def",
"get_chebi_name_from_id_web",
"(",
"chebi_id",
")",
":",
"url_base",
"=",
"'http://www.ebi.ac.uk/webservices/chebi/2.0/test/'",
"url_fmt",
"=",
"url_base",
"+",
"'getCompleteEntity?chebiId=%s'",
"resp",
"=",
"requests",
".",
"get",
"(",
"url_fmt",
"%",
"chebi_id",
... | Return a ChEBI mame corresponding to a given ChEBI ID using a REST API.
Parameters
----------
chebi_id : str
The ChEBI ID whose name is to be returned.
Returns
-------
chebi_name : str
The name corresponding to the given ChEBI ID. If the lookup
fails, None is returned. | [
"Return",
"a",
"ChEBI",
"mame",
"corresponding",
"to",
"a",
"given",
"ChEBI",
"ID",
"using",
"a",
"REST",
"API",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/databases/chebi_client.py#L179-L214 |
18,740 | sorgerlab/indra | indra/tools/executable_subnetwork.py | get_subnetwork | def get_subnetwork(statements, nodes, relevance_network=None,
relevance_node_lim=10):
"""Return a PySB model based on a subset of given INDRA Statements.
Statements are first filtered for nodes in the given list and other nodes
are optionally added based on relevance in a given network. The filtered
statements are then assembled into an executable model using INDRA's
PySB Assembler.
Parameters
----------
statements : list[indra.statements.Statement]
A list of INDRA Statements to extract a subnetwork from.
nodes : list[str]
The names of the nodes to extract the subnetwork for.
relevance_network : Optional[str]
The UUID of the NDEx network in which nodes relevant to the given
nodes are found.
relevance_node_lim : Optional[int]
The maximal number of additional nodes to add to the subnetwork
based on relevance.
Returns
-------
model : pysb.Model
A PySB model object assembled using INDRA's PySB Assembler from
the INDRA Statements corresponding to the subnetwork.
"""
if relevance_network is not None:
relevant_nodes = _find_relevant_nodes(nodes, relevance_network,
relevance_node_lim)
all_nodes = nodes + relevant_nodes
else:
all_nodes = nodes
filtered_statements = _filter_statements(statements, all_nodes)
pa = PysbAssembler()
pa.add_statements(filtered_statements)
model = pa.make_model()
return model | python | def get_subnetwork(statements, nodes, relevance_network=None,
relevance_node_lim=10):
if relevance_network is not None:
relevant_nodes = _find_relevant_nodes(nodes, relevance_network,
relevance_node_lim)
all_nodes = nodes + relevant_nodes
else:
all_nodes = nodes
filtered_statements = _filter_statements(statements, all_nodes)
pa = PysbAssembler()
pa.add_statements(filtered_statements)
model = pa.make_model()
return model | [
"def",
"get_subnetwork",
"(",
"statements",
",",
"nodes",
",",
"relevance_network",
"=",
"None",
",",
"relevance_node_lim",
"=",
"10",
")",
":",
"if",
"relevance_network",
"is",
"not",
"None",
":",
"relevant_nodes",
"=",
"_find_relevant_nodes",
"(",
"nodes",
","... | Return a PySB model based on a subset of given INDRA Statements.
Statements are first filtered for nodes in the given list and other nodes
are optionally added based on relevance in a given network. The filtered
statements are then assembled into an executable model using INDRA's
PySB Assembler.
Parameters
----------
statements : list[indra.statements.Statement]
A list of INDRA Statements to extract a subnetwork from.
nodes : list[str]
The names of the nodes to extract the subnetwork for.
relevance_network : Optional[str]
The UUID of the NDEx network in which nodes relevant to the given
nodes are found.
relevance_node_lim : Optional[int]
The maximal number of additional nodes to add to the subnetwork
based on relevance.
Returns
-------
model : pysb.Model
A PySB model object assembled using INDRA's PySB Assembler from
the INDRA Statements corresponding to the subnetwork. | [
"Return",
"a",
"PySB",
"model",
"based",
"on",
"a",
"subset",
"of",
"given",
"INDRA",
"Statements",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/executable_subnetwork.py#L7-L45 |
18,741 | sorgerlab/indra | indra/tools/executable_subnetwork.py | _filter_statements | def _filter_statements(statements, agents):
"""Return INDRA Statements which have Agents in the given list.
Only statements are returned in which all appearing Agents as in the
agents list.
Parameters
----------
statements : list[indra.statements.Statement]
A list of INDRA Statements to filter.
agents : list[str]
A list of agent names that need to appear in filtered statements.
Returns
-------
filtered_statements : list[indra.statements.Statement]
The list of filtered INDRA Statements.
"""
filtered_statements = []
for s in stmts:
if all([a is not None for a in s.agent_list()]) and \
all([a.name in agents for a in s.agent_list()]):
filtered_statements.append(s)
return filtered_statements | python | def _filter_statements(statements, agents):
filtered_statements = []
for s in stmts:
if all([a is not None for a in s.agent_list()]) and \
all([a.name in agents for a in s.agent_list()]):
filtered_statements.append(s)
return filtered_statements | [
"def",
"_filter_statements",
"(",
"statements",
",",
"agents",
")",
":",
"filtered_statements",
"=",
"[",
"]",
"for",
"s",
"in",
"stmts",
":",
"if",
"all",
"(",
"[",
"a",
"is",
"not",
"None",
"for",
"a",
"in",
"s",
".",
"agent_list",
"(",
")",
"]",
... | Return INDRA Statements which have Agents in the given list.
Only statements are returned in which all appearing Agents as in the
agents list.
Parameters
----------
statements : list[indra.statements.Statement]
A list of INDRA Statements to filter.
agents : list[str]
A list of agent names that need to appear in filtered statements.
Returns
-------
filtered_statements : list[indra.statements.Statement]
The list of filtered INDRA Statements. | [
"Return",
"INDRA",
"Statements",
"which",
"have",
"Agents",
"in",
"the",
"given",
"list",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/executable_subnetwork.py#L47-L70 |
18,742 | sorgerlab/indra | indra/tools/executable_subnetwork.py | _find_relevant_nodes | def _find_relevant_nodes(query_nodes, relevance_network, relevance_node_lim):
"""Return a list of nodes that are relevant for the query.
Parameters
----------
query_nodes : list[str]
A list of node names to query for.
relevance_network : str
The UUID of the NDEx network to query relevance in.
relevance_node_lim : int
The number of top relevant nodes to return.
Returns
-------
nodes : list[str]
A list of node names that are relevant for the query.
"""
all_nodes = relevance_client.get_relevant_nodes(relevance_network,
query_nodes)
nodes = [n[0] for n in all_nodes[:relevance_node_lim]]
return nodes | python | def _find_relevant_nodes(query_nodes, relevance_network, relevance_node_lim):
all_nodes = relevance_client.get_relevant_nodes(relevance_network,
query_nodes)
nodes = [n[0] for n in all_nodes[:relevance_node_lim]]
return nodes | [
"def",
"_find_relevant_nodes",
"(",
"query_nodes",
",",
"relevance_network",
",",
"relevance_node_lim",
")",
":",
"all_nodes",
"=",
"relevance_client",
".",
"get_relevant_nodes",
"(",
"relevance_network",
",",
"query_nodes",
")",
"nodes",
"=",
"[",
"n",
"[",
"0",
... | Return a list of nodes that are relevant for the query.
Parameters
----------
query_nodes : list[str]
A list of node names to query for.
relevance_network : str
The UUID of the NDEx network to query relevance in.
relevance_node_lim : int
The number of top relevant nodes to return.
Returns
-------
nodes : list[str]
A list of node names that are relevant for the query. | [
"Return",
"a",
"list",
"of",
"nodes",
"that",
"are",
"relevant",
"for",
"the",
"query",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/executable_subnetwork.py#L72-L92 |
18,743 | sorgerlab/indra | indra/sources/hume/api.py | process_jsonld_file | def process_jsonld_file(fname):
"""Process a JSON-LD file in the new format to extract Statements.
Parameters
----------
fname : str
The path to the JSON-LD file to be processed.
Returns
-------
indra.sources.hume.HumeProcessor
A HumeProcessor instance, which contains a list of INDRA Statements
as its statements attribute.
"""
with open(fname, 'r') as fh:
json_dict = json.load(fh)
return process_jsonld(json_dict) | python | def process_jsonld_file(fname):
with open(fname, 'r') as fh:
json_dict = json.load(fh)
return process_jsonld(json_dict) | [
"def",
"process_jsonld_file",
"(",
"fname",
")",
":",
"with",
"open",
"(",
"fname",
",",
"'r'",
")",
"as",
"fh",
":",
"json_dict",
"=",
"json",
".",
"load",
"(",
"fh",
")",
"return",
"process_jsonld",
"(",
"json_dict",
")"
] | Process a JSON-LD file in the new format to extract Statements.
Parameters
----------
fname : str
The path to the JSON-LD file to be processed.
Returns
-------
indra.sources.hume.HumeProcessor
A HumeProcessor instance, which contains a list of INDRA Statements
as its statements attribute. | [
"Process",
"a",
"JSON",
"-",
"LD",
"file",
"in",
"the",
"new",
"format",
"to",
"extract",
"Statements",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/hume/api.py#L10-L26 |
18,744 | sorgerlab/indra | indra/util/aws.py | tag_instance | def tag_instance(instance_id, **tags):
"""Tag a single ec2 instance."""
logger.debug("Got request to add tags %s to instance %s."
% (str(tags), instance_id))
ec2 = boto3.resource('ec2')
instance = ec2.Instance(instance_id)
# Remove None's from `tags`
filtered_tags = {k: v for k, v in tags.items() if v and k}
# Check for existing tags
if instance.tags is not None:
existing_tags = {tag.get('Key'): tag.get('Value')
for tag in instance.tags}
logger.debug("Ignoring existing tags; %s" % str(existing_tags))
for tag_key in existing_tags.keys():
filtered_tags.pop(tag_key, None)
# If we have new tags to add, add them.
tag_list = [{'Key': k, 'Value': v} for k, v in filtered_tags.items()]
if len(tag_list):
logger.info('Adding project tags "%s" to instance %s'
% (filtered_tags, instance_id))
instance.create_tags(Tags=tag_list)
else:
logger.info('No new tags from: %s' % str(tags))
return | python | def tag_instance(instance_id, **tags):
logger.debug("Got request to add tags %s to instance %s."
% (str(tags), instance_id))
ec2 = boto3.resource('ec2')
instance = ec2.Instance(instance_id)
# Remove None's from `tags`
filtered_tags = {k: v for k, v in tags.items() if v and k}
# Check for existing tags
if instance.tags is not None:
existing_tags = {tag.get('Key'): tag.get('Value')
for tag in instance.tags}
logger.debug("Ignoring existing tags; %s" % str(existing_tags))
for tag_key in existing_tags.keys():
filtered_tags.pop(tag_key, None)
# If we have new tags to add, add them.
tag_list = [{'Key': k, 'Value': v} for k, v in filtered_tags.items()]
if len(tag_list):
logger.info('Adding project tags "%s" to instance %s'
% (filtered_tags, instance_id))
instance.create_tags(Tags=tag_list)
else:
logger.info('No new tags from: %s' % str(tags))
return | [
"def",
"tag_instance",
"(",
"instance_id",
",",
"*",
"*",
"tags",
")",
":",
"logger",
".",
"debug",
"(",
"\"Got request to add tags %s to instance %s.\"",
"%",
"(",
"str",
"(",
"tags",
")",
",",
"instance_id",
")",
")",
"ec2",
"=",
"boto3",
".",
"resource",
... | Tag a single ec2 instance. | [
"Tag",
"a",
"single",
"ec2",
"instance",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/util/aws.py#L36-L62 |
18,745 | sorgerlab/indra | indra/util/aws.py | tag_myself | def tag_myself(project='cwc', **other_tags):
"""Function run when indra is used in an EC2 instance to apply tags."""
base_url = "http://169.254.169.254"
try:
resp = requests.get(base_url + "/latest/meta-data/instance-id")
except requests.exceptions.ConnectionError:
logger.warning("Could not connect to service. Note this should only "
"be run from within a batch job.")
return
instance_id = resp.text
tag_instance(instance_id, project=project, **other_tags)
return | python | def tag_myself(project='cwc', **other_tags):
base_url = "http://169.254.169.254"
try:
resp = requests.get(base_url + "/latest/meta-data/instance-id")
except requests.exceptions.ConnectionError:
logger.warning("Could not connect to service. Note this should only "
"be run from within a batch job.")
return
instance_id = resp.text
tag_instance(instance_id, project=project, **other_tags)
return | [
"def",
"tag_myself",
"(",
"project",
"=",
"'cwc'",
",",
"*",
"*",
"other_tags",
")",
":",
"base_url",
"=",
"\"http://169.254.169.254\"",
"try",
":",
"resp",
"=",
"requests",
".",
"get",
"(",
"base_url",
"+",
"\"/latest/meta-data/instance-id\"",
")",
"except",
... | Function run when indra is used in an EC2 instance to apply tags. | [
"Function",
"run",
"when",
"indra",
"is",
"used",
"in",
"an",
"EC2",
"instance",
"to",
"apply",
"tags",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/util/aws.py#L65-L76 |
18,746 | sorgerlab/indra | indra/util/aws.py | get_batch_command | def get_batch_command(command_list, project=None, purpose=None):
"""Get the command appropriate for running something on batch."""
command_str = ' '.join(command_list)
ret = ['python', '-m', 'indra.util.aws', 'run_in_batch', command_str]
if not project and has_config('DEFAULT_AWS_PROJECT'):
project = get_config('DEFAULT_AWS_PROJECT')
if project:
ret += ['--project', project]
if purpose:
ret += ['--purpose', purpose]
return ret | python | def get_batch_command(command_list, project=None, purpose=None):
command_str = ' '.join(command_list)
ret = ['python', '-m', 'indra.util.aws', 'run_in_batch', command_str]
if not project and has_config('DEFAULT_AWS_PROJECT'):
project = get_config('DEFAULT_AWS_PROJECT')
if project:
ret += ['--project', project]
if purpose:
ret += ['--purpose', purpose]
return ret | [
"def",
"get_batch_command",
"(",
"command_list",
",",
"project",
"=",
"None",
",",
"purpose",
"=",
"None",
")",
":",
"command_str",
"=",
"' '",
".",
"join",
"(",
"command_list",
")",
"ret",
"=",
"[",
"'python'",
",",
"'-m'",
",",
"'indra.util.aws'",
",",
... | Get the command appropriate for running something on batch. | [
"Get",
"the",
"command",
"appropriate",
"for",
"running",
"something",
"on",
"batch",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/util/aws.py#L79-L89 |
18,747 | sorgerlab/indra | indra/util/aws.py | get_jobs | def get_jobs(job_queue='run_reach_queue', job_status='RUNNING'):
"""Returns a list of dicts with jobName and jobId for each job with the
given status."""
batch = boto3.client('batch')
jobs = batch.list_jobs(jobQueue=job_queue, jobStatus=job_status)
return jobs.get('jobSummaryList') | python | def get_jobs(job_queue='run_reach_queue', job_status='RUNNING'):
batch = boto3.client('batch')
jobs = batch.list_jobs(jobQueue=job_queue, jobStatus=job_status)
return jobs.get('jobSummaryList') | [
"def",
"get_jobs",
"(",
"job_queue",
"=",
"'run_reach_queue'",
",",
"job_status",
"=",
"'RUNNING'",
")",
":",
"batch",
"=",
"boto3",
".",
"client",
"(",
"'batch'",
")",
"jobs",
"=",
"batch",
".",
"list_jobs",
"(",
"jobQueue",
"=",
"job_queue",
",",
"jobSta... | Returns a list of dicts with jobName and jobId for each job with the
given status. | [
"Returns",
"a",
"list",
"of",
"dicts",
"with",
"jobName",
"and",
"jobId",
"for",
"each",
"job",
"with",
"the",
"given",
"status",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/util/aws.py#L101-L106 |
18,748 | sorgerlab/indra | indra/util/aws.py | get_job_log | def get_job_log(job_info, log_group_name='/aws/batch/job',
write_file=True, verbose=False):
"""Gets the Cloudwatch log associated with the given job.
Parameters
----------
job_info : dict
dict containing entries for 'jobName' and 'jobId', e.g., as returned
by get_jobs()
log_group_name : string
Name of the log group; defaults to '/aws/batch/job'
write_file : boolean
If True, writes the downloaded log to a text file with the filename
'%s_%s.log' % (job_name, job_id)
Returns
-------
list of strings
The event messages in the log, with the earliest events listed first.
"""
job_name = job_info['jobName']
job_id = job_info['jobId']
logs = boto3.client('logs')
batch = boto3.client('batch')
resp = batch.describe_jobs(jobs=[job_id])
job_desc = resp['jobs'][0]
job_def_name = job_desc['jobDefinition'].split('/')[-1].split(':')[0]
task_arn_id = job_desc['container']['taskArn'].split('/')[-1]
log_stream_name = '%s/default/%s' % (job_def_name, task_arn_id)
stream_resp = logs.describe_log_streams(
logGroupName=log_group_name,
logStreamNamePrefix=log_stream_name)
streams = stream_resp.get('logStreams')
if not streams:
logger.warning('No streams for job')
return None
elif len(streams) > 1:
logger.warning('More than 1 stream for job, returning first')
log_stream_name = streams[0]['logStreamName']
if verbose:
logger.info("Getting log for %s/%s" % (job_name, job_id))
out_file = ('%s_%s.log' % (job_name, job_id)) if write_file else None
lines = get_log_by_name(log_group_name, log_stream_name, out_file, verbose)
return lines | python | def get_job_log(job_info, log_group_name='/aws/batch/job',
write_file=True, verbose=False):
job_name = job_info['jobName']
job_id = job_info['jobId']
logs = boto3.client('logs')
batch = boto3.client('batch')
resp = batch.describe_jobs(jobs=[job_id])
job_desc = resp['jobs'][0]
job_def_name = job_desc['jobDefinition'].split('/')[-1].split(':')[0]
task_arn_id = job_desc['container']['taskArn'].split('/')[-1]
log_stream_name = '%s/default/%s' % (job_def_name, task_arn_id)
stream_resp = logs.describe_log_streams(
logGroupName=log_group_name,
logStreamNamePrefix=log_stream_name)
streams = stream_resp.get('logStreams')
if not streams:
logger.warning('No streams for job')
return None
elif len(streams) > 1:
logger.warning('More than 1 stream for job, returning first')
log_stream_name = streams[0]['logStreamName']
if verbose:
logger.info("Getting log for %s/%s" % (job_name, job_id))
out_file = ('%s_%s.log' % (job_name, job_id)) if write_file else None
lines = get_log_by_name(log_group_name, log_stream_name, out_file, verbose)
return lines | [
"def",
"get_job_log",
"(",
"job_info",
",",
"log_group_name",
"=",
"'/aws/batch/job'",
",",
"write_file",
"=",
"True",
",",
"verbose",
"=",
"False",
")",
":",
"job_name",
"=",
"job_info",
"[",
"'jobName'",
"]",
"job_id",
"=",
"job_info",
"[",
"'jobId'",
"]",... | Gets the Cloudwatch log associated with the given job.
Parameters
----------
job_info : dict
dict containing entries for 'jobName' and 'jobId', e.g., as returned
by get_jobs()
log_group_name : string
Name of the log group; defaults to '/aws/batch/job'
write_file : boolean
If True, writes the downloaded log to a text file with the filename
'%s_%s.log' % (job_name, job_id)
Returns
-------
list of strings
The event messages in the log, with the earliest events listed first. | [
"Gets",
"the",
"Cloudwatch",
"log",
"associated",
"with",
"the",
"given",
"job",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/util/aws.py#L109-L153 |
18,749 | sorgerlab/indra | indra/util/aws.py | get_log_by_name | def get_log_by_name(log_group_name, log_stream_name, out_file=None,
verbose=True):
"""Download a log given the log's group and stream name.
Parameters
----------
log_group_name : str
The name of the log group, e.g. /aws/batch/job.
log_stream_name : str
The name of the log stream, e.g. run_reach_jobdef/default/<UUID>
Returns
-------
lines : list[str]
The lines of the log as a list.
"""
logs = boto3.client('logs')
kwargs = {'logGroupName': log_group_name,
'logStreamName': log_stream_name,
'startFromHead': True}
lines = []
while True:
response = logs.get_log_events(**kwargs)
# If we've gotten all the events already, the nextForwardToken for
# this call will be the same as the last one
if response.get('nextForwardToken') == kwargs.get('nextToken'):
break
else:
events = response.get('events')
if events:
lines += ['%s: %s\n' % (evt['timestamp'], evt['message'])
for evt in events]
kwargs['nextToken'] = response.get('nextForwardToken')
if verbose:
logger.info('%d %s' % (len(lines), lines[-1]))
if out_file:
with open(out_file, 'wt') as f:
for line in lines:
f.write(line)
return lines | python | def get_log_by_name(log_group_name, log_stream_name, out_file=None,
verbose=True):
logs = boto3.client('logs')
kwargs = {'logGroupName': log_group_name,
'logStreamName': log_stream_name,
'startFromHead': True}
lines = []
while True:
response = logs.get_log_events(**kwargs)
# If we've gotten all the events already, the nextForwardToken for
# this call will be the same as the last one
if response.get('nextForwardToken') == kwargs.get('nextToken'):
break
else:
events = response.get('events')
if events:
lines += ['%s: %s\n' % (evt['timestamp'], evt['message'])
for evt in events]
kwargs['nextToken'] = response.get('nextForwardToken')
if verbose:
logger.info('%d %s' % (len(lines), lines[-1]))
if out_file:
with open(out_file, 'wt') as f:
for line in lines:
f.write(line)
return lines | [
"def",
"get_log_by_name",
"(",
"log_group_name",
",",
"log_stream_name",
",",
"out_file",
"=",
"None",
",",
"verbose",
"=",
"True",
")",
":",
"logs",
"=",
"boto3",
".",
"client",
"(",
"'logs'",
")",
"kwargs",
"=",
"{",
"'logGroupName'",
":",
"log_group_name"... | Download a log given the log's group and stream name.
Parameters
----------
log_group_name : str
The name of the log group, e.g. /aws/batch/job.
log_stream_name : str
The name of the log stream, e.g. run_reach_jobdef/default/<UUID>
Returns
-------
lines : list[str]
The lines of the log as a list. | [
"Download",
"a",
"log",
"given",
"the",
"log",
"s",
"group",
"and",
"stream",
"name",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/util/aws.py#L156-L196 |
18,750 | sorgerlab/indra | indra/util/aws.py | dump_logs | def dump_logs(job_queue='run_reach_queue', job_status='RUNNING'):
"""Write logs for all jobs with given the status to files."""
jobs = get_jobs(job_queue, job_status)
for job in jobs:
get_job_log(job, write_file=True) | python | def dump_logs(job_queue='run_reach_queue', job_status='RUNNING'):
jobs = get_jobs(job_queue, job_status)
for job in jobs:
get_job_log(job, write_file=True) | [
"def",
"dump_logs",
"(",
"job_queue",
"=",
"'run_reach_queue'",
",",
"job_status",
"=",
"'RUNNING'",
")",
":",
"jobs",
"=",
"get_jobs",
"(",
"job_queue",
",",
"job_status",
")",
"for",
"job",
"in",
"jobs",
":",
"get_job_log",
"(",
"job",
",",
"write_file",
... | Write logs for all jobs with given the status to files. | [
"Write",
"logs",
"for",
"all",
"jobs",
"with",
"given",
"the",
"status",
"to",
"files",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/util/aws.py#L199-L203 |
18,751 | sorgerlab/indra | indra/util/aws.py | get_s3_file_tree | def get_s3_file_tree(s3, bucket, prefix):
"""Overcome s3 response limit and return NestedDict tree of paths.
The NestedDict object also allows the user to search by the ends of a path.
The tree mimics a file directory structure, with the leave nodes being the
full unbroken key. For example, 'path/to/file.txt' would be retrieved by
ret['path']['to']['file.txt']['key']
The NestedDict object returned also has the capability to get paths that
lead to a certain value. So if you wanted all paths that lead to something
called 'file.txt', you could use
ret.get_paths('file.txt')
For more details, see the NestedDict docs.
"""
def get_some_keys(keys, marker=None):
if marker:
relevant_files = s3.list_objects(Bucket=bucket, Prefix=prefix,
Marker=marker)
else:
relevant_files = s3.list_objects(Bucket=bucket, Prefix=prefix)
keys.extend([entry['Key'] for entry in relevant_files['Contents']
if entry['Key'] != marker])
return relevant_files['IsTruncated']
file_keys = []
marker = None
while get_some_keys(file_keys, marker):
marker = file_keys[-1]
file_tree = NestedDict()
pref_path = prefix.split('/')[:-1] # avoid the trailing empty str.
for key in file_keys:
full_path = key.split('/')
relevant_path = full_path[len(pref_path):]
curr = file_tree
for step in relevant_path:
curr = curr[step]
curr['key'] = key
return file_tree | python | def get_s3_file_tree(s3, bucket, prefix):
def get_some_keys(keys, marker=None):
if marker:
relevant_files = s3.list_objects(Bucket=bucket, Prefix=prefix,
Marker=marker)
else:
relevant_files = s3.list_objects(Bucket=bucket, Prefix=prefix)
keys.extend([entry['Key'] for entry in relevant_files['Contents']
if entry['Key'] != marker])
return relevant_files['IsTruncated']
file_keys = []
marker = None
while get_some_keys(file_keys, marker):
marker = file_keys[-1]
file_tree = NestedDict()
pref_path = prefix.split('/')[:-1] # avoid the trailing empty str.
for key in file_keys:
full_path = key.split('/')
relevant_path = full_path[len(pref_path):]
curr = file_tree
for step in relevant_path:
curr = curr[step]
curr['key'] = key
return file_tree | [
"def",
"get_s3_file_tree",
"(",
"s3",
",",
"bucket",
",",
"prefix",
")",
":",
"def",
"get_some_keys",
"(",
"keys",
",",
"marker",
"=",
"None",
")",
":",
"if",
"marker",
":",
"relevant_files",
"=",
"s3",
".",
"list_objects",
"(",
"Bucket",
"=",
"bucket",
... | Overcome s3 response limit and return NestedDict tree of paths.
The NestedDict object also allows the user to search by the ends of a path.
The tree mimics a file directory structure, with the leave nodes being the
full unbroken key. For example, 'path/to/file.txt' would be retrieved by
ret['path']['to']['file.txt']['key']
The NestedDict object returned also has the capability to get paths that
lead to a certain value. So if you wanted all paths that lead to something
called 'file.txt', you could use
ret.get_paths('file.txt')
For more details, see the NestedDict docs. | [
"Overcome",
"s3",
"response",
"limit",
"and",
"return",
"NestedDict",
"tree",
"of",
"paths",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/util/aws.py#L206-L248 |
18,752 | sorgerlab/indra | indra/assemblers/sif/assembler.py | SifAssembler.print_model | def print_model(self, include_unsigned_edges=False):
"""Return a SIF string of the assembled model.
Parameters
----------
include_unsigned_edges : bool
If True, includes edges with an unknown activating/inactivating
relationship (e.g., most PTMs). Default is False.
"""
sif_str = ''
for edge in self.graph.edges(data=True):
n1 = edge[0]
n2 = edge[1]
data = edge[2]
polarity = data.get('polarity')
if polarity == 'negative':
rel = '-1'
elif polarity == 'positive':
rel = '1'
elif include_unsigned_edges:
rel = '0'
else:
continue
sif_str += '%s %s %s\n' % (n1, rel, n2)
return sif_str | python | def print_model(self, include_unsigned_edges=False):
sif_str = ''
for edge in self.graph.edges(data=True):
n1 = edge[0]
n2 = edge[1]
data = edge[2]
polarity = data.get('polarity')
if polarity == 'negative':
rel = '-1'
elif polarity == 'positive':
rel = '1'
elif include_unsigned_edges:
rel = '0'
else:
continue
sif_str += '%s %s %s\n' % (n1, rel, n2)
return sif_str | [
"def",
"print_model",
"(",
"self",
",",
"include_unsigned_edges",
"=",
"False",
")",
":",
"sif_str",
"=",
"''",
"for",
"edge",
"in",
"self",
".",
"graph",
".",
"edges",
"(",
"data",
"=",
"True",
")",
":",
"n1",
"=",
"edge",
"[",
"0",
"]",
"n2",
"="... | Return a SIF string of the assembled model.
Parameters
----------
include_unsigned_edges : bool
If True, includes edges with an unknown activating/inactivating
relationship (e.g., most PTMs). Default is False. | [
"Return",
"a",
"SIF",
"string",
"of",
"the",
"assembled",
"model",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/sif/assembler.py#L98-L122 |
18,753 | sorgerlab/indra | indra/assemblers/sif/assembler.py | SifAssembler.save_model | def save_model(self, fname, include_unsigned_edges=False):
"""Save the assembled model's SIF string into a file.
Parameters
----------
fname : str
The name of the file to save the SIF into.
include_unsigned_edges : bool
If True, includes edges with an unknown activating/inactivating
relationship (e.g., most PTMs). Default is False.
"""
sif_str = self.print_model(include_unsigned_edges)
with open(fname, 'wb') as fh:
fh.write(sif_str.encode('utf-8')) | python | def save_model(self, fname, include_unsigned_edges=False):
sif_str = self.print_model(include_unsigned_edges)
with open(fname, 'wb') as fh:
fh.write(sif_str.encode('utf-8')) | [
"def",
"save_model",
"(",
"self",
",",
"fname",
",",
"include_unsigned_edges",
"=",
"False",
")",
":",
"sif_str",
"=",
"self",
".",
"print_model",
"(",
"include_unsigned_edges",
")",
"with",
"open",
"(",
"fname",
",",
"'wb'",
")",
"as",
"fh",
":",
"fh",
... | Save the assembled model's SIF string into a file.
Parameters
----------
fname : str
The name of the file to save the SIF into.
include_unsigned_edges : bool
If True, includes edges with an unknown activating/inactivating
relationship (e.g., most PTMs). Default is False. | [
"Save",
"the",
"assembled",
"model",
"s",
"SIF",
"string",
"into",
"a",
"file",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/sif/assembler.py#L124-L137 |
18,754 | sorgerlab/indra | indra/assemblers/sif/assembler.py | SifAssembler.print_boolean_net | def print_boolean_net(self, out_file=None):
"""Return a Boolean network from the assembled graph.
See https://github.com/ialbert/booleannet for details about
the format used to encode the Boolean rules.
Parameters
----------
out_file : Optional[str]
A file name in which the Boolean network is saved.
Returns
-------
full_str : str
The string representing the Boolean network.
"""
init_str = ''
for node_key in self.graph.nodes():
node_name = self.graph.node[node_key]['name']
init_str += '%s = False\n' % node_name
rule_str = ''
for node_key in self.graph.nodes():
node_name = self.graph.node[node_key]['name']
in_edges = self.graph.in_edges(node_key)
if not in_edges:
continue
parents = [e[0] for e in in_edges]
polarities = [self.graph.edge[e[0]][node_key]['polarity']
for e in in_edges]
pos_parents = [par for par, pol in zip(parents, polarities) if
pol == 'positive']
neg_parents = [par for par, pol in zip(parents, polarities) if
pol == 'negative']
rhs_pos_parts = []
for par in pos_parents:
rhs_pos_parts.append(self.graph.node[par]['name'])
rhs_pos_str = ' or '.join(rhs_pos_parts)
rhs_neg_parts = []
for par in neg_parents:
rhs_neg_parts.append(self.graph.node[par]['name'])
rhs_neg_str = ' or '.join(rhs_neg_parts)
if rhs_pos_str:
if rhs_neg_str:
rhs_str = '(' + rhs_pos_str + \
') and not (' + rhs_neg_str + ')'
else:
rhs_str = rhs_pos_str
else:
rhs_str = 'not (' + rhs_neg_str + ')'
node_eq = '%s* = %s\n' % (node_name, rhs_str)
rule_str += node_eq
full_str = init_str + '\n' + rule_str
if out_file is not None:
with open(out_file, 'wt') as fh:
fh.write(full_str)
return full_str | python | def print_boolean_net(self, out_file=None):
init_str = ''
for node_key in self.graph.nodes():
node_name = self.graph.node[node_key]['name']
init_str += '%s = False\n' % node_name
rule_str = ''
for node_key in self.graph.nodes():
node_name = self.graph.node[node_key]['name']
in_edges = self.graph.in_edges(node_key)
if not in_edges:
continue
parents = [e[0] for e in in_edges]
polarities = [self.graph.edge[e[0]][node_key]['polarity']
for e in in_edges]
pos_parents = [par for par, pol in zip(parents, polarities) if
pol == 'positive']
neg_parents = [par for par, pol in zip(parents, polarities) if
pol == 'negative']
rhs_pos_parts = []
for par in pos_parents:
rhs_pos_parts.append(self.graph.node[par]['name'])
rhs_pos_str = ' or '.join(rhs_pos_parts)
rhs_neg_parts = []
for par in neg_parents:
rhs_neg_parts.append(self.graph.node[par]['name'])
rhs_neg_str = ' or '.join(rhs_neg_parts)
if rhs_pos_str:
if rhs_neg_str:
rhs_str = '(' + rhs_pos_str + \
') and not (' + rhs_neg_str + ')'
else:
rhs_str = rhs_pos_str
else:
rhs_str = 'not (' + rhs_neg_str + ')'
node_eq = '%s* = %s\n' % (node_name, rhs_str)
rule_str += node_eq
full_str = init_str + '\n' + rule_str
if out_file is not None:
with open(out_file, 'wt') as fh:
fh.write(full_str)
return full_str | [
"def",
"print_boolean_net",
"(",
"self",
",",
"out_file",
"=",
"None",
")",
":",
"init_str",
"=",
"''",
"for",
"node_key",
"in",
"self",
".",
"graph",
".",
"nodes",
"(",
")",
":",
"node_name",
"=",
"self",
".",
"graph",
".",
"node",
"[",
"node_key",
... | Return a Boolean network from the assembled graph.
See https://github.com/ialbert/booleannet for details about
the format used to encode the Boolean rules.
Parameters
----------
out_file : Optional[str]
A file name in which the Boolean network is saved.
Returns
-------
full_str : str
The string representing the Boolean network. | [
"Return",
"a",
"Boolean",
"network",
"from",
"the",
"assembled",
"graph",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/sif/assembler.py#L183-L242 |
18,755 | sorgerlab/indra | indra/literature/elsevier_client.py | _ensure_api_keys | def _ensure_api_keys(task_desc, failure_ret=None):
"""Wrap Elsevier methods which directly use the API keys.
Ensure that the keys are retrieved from the environment or config file when
first called, and store global scope. Subsequently use globally stashed
results and check for required ids.
"""
def check_func_wrapper(func):
@wraps(func)
def check_api_keys(*args, **kwargs):
global ELSEVIER_KEYS
if ELSEVIER_KEYS is None:
ELSEVIER_KEYS = {}
# Try to read in Elsevier API keys. For each key, first check
# the environment variables, then check the INDRA config file.
if not has_config(INST_KEY_ENV_NAME):
logger.warning('Institution API key %s not found in config '
'file or environment variable: this will '
'limit access for %s'
% (INST_KEY_ENV_NAME, task_desc))
ELSEVIER_KEYS['X-ELS-Insttoken'] = get_config(INST_KEY_ENV_NAME)
if not has_config(API_KEY_ENV_NAME):
logger.error('API key %s not found in configuration file '
'or environment variable: cannot %s'
% (API_KEY_ENV_NAME, task_desc))
return failure_ret
ELSEVIER_KEYS['X-ELS-APIKey'] = get_config(API_KEY_ENV_NAME)
elif 'X-ELS-APIKey' not in ELSEVIER_KEYS.keys():
logger.error('No Elsevier API key %s found: cannot %s'
% (API_KEY_ENV_NAME, task_desc))
return failure_ret
return func(*args, **kwargs)
return check_api_keys
return check_func_wrapper | python | def _ensure_api_keys(task_desc, failure_ret=None):
def check_func_wrapper(func):
@wraps(func)
def check_api_keys(*args, **kwargs):
global ELSEVIER_KEYS
if ELSEVIER_KEYS is None:
ELSEVIER_KEYS = {}
# Try to read in Elsevier API keys. For each key, first check
# the environment variables, then check the INDRA config file.
if not has_config(INST_KEY_ENV_NAME):
logger.warning('Institution API key %s not found in config '
'file or environment variable: this will '
'limit access for %s'
% (INST_KEY_ENV_NAME, task_desc))
ELSEVIER_KEYS['X-ELS-Insttoken'] = get_config(INST_KEY_ENV_NAME)
if not has_config(API_KEY_ENV_NAME):
logger.error('API key %s not found in configuration file '
'or environment variable: cannot %s'
% (API_KEY_ENV_NAME, task_desc))
return failure_ret
ELSEVIER_KEYS['X-ELS-APIKey'] = get_config(API_KEY_ENV_NAME)
elif 'X-ELS-APIKey' not in ELSEVIER_KEYS.keys():
logger.error('No Elsevier API key %s found: cannot %s'
% (API_KEY_ENV_NAME, task_desc))
return failure_ret
return func(*args, **kwargs)
return check_api_keys
return check_func_wrapper | [
"def",
"_ensure_api_keys",
"(",
"task_desc",
",",
"failure_ret",
"=",
"None",
")",
":",
"def",
"check_func_wrapper",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"check_api_keys",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"g... | Wrap Elsevier methods which directly use the API keys.
Ensure that the keys are retrieved from the environment or config file when
first called, and store global scope. Subsequently use globally stashed
results and check for required ids. | [
"Wrap",
"Elsevier",
"methods",
"which",
"directly",
"use",
"the",
"API",
"keys",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/literature/elsevier_client.py#L51-L85 |
18,756 | sorgerlab/indra | indra/literature/elsevier_client.py | check_entitlement | def check_entitlement(doi):
"""Check whether IP and credentials enable access to content for a doi.
This function uses the entitlement endpoint of the Elsevier API to check
whether an article is available to a given institution. Note that this
feature of the API is itself not available for all institution keys.
"""
if doi.lower().startswith('doi:'):
doi = doi[4:]
url = '%s/%s' % (elsevier_entitlement_url, doi)
params = {'httpAccept': 'text/xml'}
res = requests.get(url, params, headers=ELSEVIER_KEYS)
if not res.status_code == 200:
logger.error('Could not check entitlements for article %s: '
'status code %d' % (doi, res.status_code))
logger.error('Response content: %s' % res.text)
return False
return True | python | def check_entitlement(doi):
if doi.lower().startswith('doi:'):
doi = doi[4:]
url = '%s/%s' % (elsevier_entitlement_url, doi)
params = {'httpAccept': 'text/xml'}
res = requests.get(url, params, headers=ELSEVIER_KEYS)
if not res.status_code == 200:
logger.error('Could not check entitlements for article %s: '
'status code %d' % (doi, res.status_code))
logger.error('Response content: %s' % res.text)
return False
return True | [
"def",
"check_entitlement",
"(",
"doi",
")",
":",
"if",
"doi",
".",
"lower",
"(",
")",
".",
"startswith",
"(",
"'doi:'",
")",
":",
"doi",
"=",
"doi",
"[",
"4",
":",
"]",
"url",
"=",
"'%s/%s'",
"%",
"(",
"elsevier_entitlement_url",
",",
"doi",
")",
... | Check whether IP and credentials enable access to content for a doi.
This function uses the entitlement endpoint of the Elsevier API to check
whether an article is available to a given institution. Note that this
feature of the API is itself not available for all institution keys. | [
"Check",
"whether",
"IP",
"and",
"credentials",
"enable",
"access",
"to",
"content",
"for",
"a",
"doi",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/literature/elsevier_client.py#L89-L106 |
18,757 | sorgerlab/indra | indra/literature/elsevier_client.py | download_article | def download_article(id_val, id_type='doi', on_retry=False):
"""Low level function to get an XML article for a particular id.
Parameters
----------
id_val : str
The value of the id.
id_type : str
The type of id, such as pmid (a.k.a. pubmed_id), doi, or eid.
on_retry : bool
This function has a recursive retry feature, and this is the only time
this parameter should be used.
Returns
-------
content : str or None
If found, the content string is returned, otherwise, None is returned.
"""
if id_type == 'pmid':
id_type = 'pubmed_id'
url = '%s/%s' % (elsevier_article_url_fmt % id_type, id_val)
params = {'httpAccept': 'text/xml'}
res = requests.get(url, params, headers=ELSEVIER_KEYS)
if res.status_code == 404:
logger.info("Resource for %s not available on elsevier." % url)
return None
elif res.status_code == 429:
if not on_retry:
logger.warning("Broke the speed limit. Waiting half a second then "
"trying again...")
sleep(0.5)
return download_article(id_val, id_type, True)
else:
logger.error("Still breaking speed limit after waiting.")
logger.error("Elsevier response: %s" % res.text)
return None
elif res.status_code != 200:
logger.error('Could not download article %s: status code %d' %
(url, res.status_code))
logger.error('Elsevier response: %s' % res.text)
return None
else:
content_str = res.content.decode('utf-8')
if content_str.startswith('<service-error>'):
logger.error('Got a service error with 200 status: %s'
% content_str)
return None
# Return the XML content as a unicode string, assuming UTF-8 encoding
return content_str | python | def download_article(id_val, id_type='doi', on_retry=False):
if id_type == 'pmid':
id_type = 'pubmed_id'
url = '%s/%s' % (elsevier_article_url_fmt % id_type, id_val)
params = {'httpAccept': 'text/xml'}
res = requests.get(url, params, headers=ELSEVIER_KEYS)
if res.status_code == 404:
logger.info("Resource for %s not available on elsevier." % url)
return None
elif res.status_code == 429:
if not on_retry:
logger.warning("Broke the speed limit. Waiting half a second then "
"trying again...")
sleep(0.5)
return download_article(id_val, id_type, True)
else:
logger.error("Still breaking speed limit after waiting.")
logger.error("Elsevier response: %s" % res.text)
return None
elif res.status_code != 200:
logger.error('Could not download article %s: status code %d' %
(url, res.status_code))
logger.error('Elsevier response: %s' % res.text)
return None
else:
content_str = res.content.decode('utf-8')
if content_str.startswith('<service-error>'):
logger.error('Got a service error with 200 status: %s'
% content_str)
return None
# Return the XML content as a unicode string, assuming UTF-8 encoding
return content_str | [
"def",
"download_article",
"(",
"id_val",
",",
"id_type",
"=",
"'doi'",
",",
"on_retry",
"=",
"False",
")",
":",
"if",
"id_type",
"==",
"'pmid'",
":",
"id_type",
"=",
"'pubmed_id'",
"url",
"=",
"'%s/%s'",
"%",
"(",
"elsevier_article_url_fmt",
"%",
"id_type",... | Low level function to get an XML article for a particular id.
Parameters
----------
id_val : str
The value of the id.
id_type : str
The type of id, such as pmid (a.k.a. pubmed_id), doi, or eid.
on_retry : bool
This function has a recursive retry feature, and this is the only time
this parameter should be used.
Returns
-------
content : str or None
If found, the content string is returned, otherwise, None is returned. | [
"Low",
"level",
"function",
"to",
"get",
"an",
"XML",
"article",
"for",
"a",
"particular",
"id",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/literature/elsevier_client.py#L110-L158 |
18,758 | sorgerlab/indra | indra/literature/elsevier_client.py | download_article_from_ids | def download_article_from_ids(**id_dict):
"""Download an article in XML format from Elsevier matching the set of ids.
Parameters
----------
<id_type> : str
You can enter any combination of eid, doi, pmid, and/or pii. Ids will be
checked in that order, until either content has been found or all ids
have been checked.
Returns
-------
content : str or None
If found, the content is returned as a string, otherwise None is
returned.
"""
valid_id_types = ['eid', 'doi', 'pmid', 'pii']
assert all([k in valid_id_types for k in id_dict.keys()]),\
("One of these id keys is invalid: %s Valid keys are: %s."
% (list(id_dict.keys()), valid_id_types))
if 'doi' in id_dict.keys() and id_dict['doi'].lower().startswith('doi:'):
id_dict['doi'] = id_dict['doi'][4:]
content = None
for id_type in valid_id_types:
if id_type in id_dict.keys():
content = download_article(id_dict[id_type], id_type)
if content is not None:
break
else:
logger.error("Could not download article with any of the ids: %s."
% str(id_dict))
return content | python | def download_article_from_ids(**id_dict):
valid_id_types = ['eid', 'doi', 'pmid', 'pii']
assert all([k in valid_id_types for k in id_dict.keys()]),\
("One of these id keys is invalid: %s Valid keys are: %s."
% (list(id_dict.keys()), valid_id_types))
if 'doi' in id_dict.keys() and id_dict['doi'].lower().startswith('doi:'):
id_dict['doi'] = id_dict['doi'][4:]
content = None
for id_type in valid_id_types:
if id_type in id_dict.keys():
content = download_article(id_dict[id_type], id_type)
if content is not None:
break
else:
logger.error("Could not download article with any of the ids: %s."
% str(id_dict))
return content | [
"def",
"download_article_from_ids",
"(",
"*",
"*",
"id_dict",
")",
":",
"valid_id_types",
"=",
"[",
"'eid'",
",",
"'doi'",
",",
"'pmid'",
",",
"'pii'",
"]",
"assert",
"all",
"(",
"[",
"k",
"in",
"valid_id_types",
"for",
"k",
"in",
"id_dict",
".",
"keys",... | Download an article in XML format from Elsevier matching the set of ids.
Parameters
----------
<id_type> : str
You can enter any combination of eid, doi, pmid, and/or pii. Ids will be
checked in that order, until either content has been found or all ids
have been checked.
Returns
-------
content : str or None
If found, the content is returned as a string, otherwise None is
returned. | [
"Download",
"an",
"article",
"in",
"XML",
"format",
"from",
"Elsevier",
"matching",
"the",
"set",
"of",
"ids",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/literature/elsevier_client.py#L161-L192 |
18,759 | sorgerlab/indra | indra/literature/elsevier_client.py | get_abstract | def get_abstract(doi):
"""Get the abstract text of an article from Elsevier given a doi."""
xml_string = download_article(doi)
if xml_string is None:
return None
assert isinstance(xml_string, str)
xml_tree = ET.XML(xml_string.encode('utf-8'), parser=UTB())
if xml_tree is None:
return None
coredata = xml_tree.find('article:coredata', elsevier_ns)
abstract = coredata.find('dc:description', elsevier_ns)
abs_text = abstract.text
return abs_text | python | def get_abstract(doi):
xml_string = download_article(doi)
if xml_string is None:
return None
assert isinstance(xml_string, str)
xml_tree = ET.XML(xml_string.encode('utf-8'), parser=UTB())
if xml_tree is None:
return None
coredata = xml_tree.find('article:coredata', elsevier_ns)
abstract = coredata.find('dc:description', elsevier_ns)
abs_text = abstract.text
return abs_text | [
"def",
"get_abstract",
"(",
"doi",
")",
":",
"xml_string",
"=",
"download_article",
"(",
"doi",
")",
"if",
"xml_string",
"is",
"None",
":",
"return",
"None",
"assert",
"isinstance",
"(",
"xml_string",
",",
"str",
")",
"xml_tree",
"=",
"ET",
".",
"XML",
"... | Get the abstract text of an article from Elsevier given a doi. | [
"Get",
"the",
"abstract",
"text",
"of",
"an",
"article",
"from",
"Elsevier",
"given",
"a",
"doi",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/literature/elsevier_client.py#L195-L207 |
18,760 | sorgerlab/indra | indra/literature/elsevier_client.py | get_article | def get_article(doi, output_format='txt'):
"""Get the full body of an article from Elsevier.
Parameters
----------
doi : str
The doi for the desired article.
output_format : 'txt' or 'xml'
The desired format for the output. Selecting 'txt' (default) strips all
xml tags and joins the pieces of text in the main text, while 'xml'
simply takes the tag containing the body of the article and returns it
as is . In the latter case, downstream code needs to be able to
interpret Elsever's XML format.
Returns
-------
content : str
Either text content or xml, as described above, for the given doi.
"""
xml_string = download_article(doi)
if output_format == 'txt' and xml_string is not None:
text = extract_text(xml_string)
return text
return xml_string | python | def get_article(doi, output_format='txt'):
xml_string = download_article(doi)
if output_format == 'txt' and xml_string is not None:
text = extract_text(xml_string)
return text
return xml_string | [
"def",
"get_article",
"(",
"doi",
",",
"output_format",
"=",
"'txt'",
")",
":",
"xml_string",
"=",
"download_article",
"(",
"doi",
")",
"if",
"output_format",
"==",
"'txt'",
"and",
"xml_string",
"is",
"not",
"None",
":",
"text",
"=",
"extract_text",
"(",
"... | Get the full body of an article from Elsevier.
Parameters
----------
doi : str
The doi for the desired article.
output_format : 'txt' or 'xml'
The desired format for the output. Selecting 'txt' (default) strips all
xml tags and joins the pieces of text in the main text, while 'xml'
simply takes the tag containing the body of the article and returns it
as is . In the latter case, downstream code needs to be able to
interpret Elsever's XML format.
Returns
-------
content : str
Either text content or xml, as described above, for the given doi. | [
"Get",
"the",
"full",
"body",
"of",
"an",
"article",
"from",
"Elsevier",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/literature/elsevier_client.py#L210-L233 |
18,761 | sorgerlab/indra | indra/literature/elsevier_client.py | extract_paragraphs | def extract_paragraphs(xml_string):
"""Get paragraphs from the body of the given Elsevier xml."""
assert isinstance(xml_string, str)
xml_tree = ET.XML(xml_string.encode('utf-8'), parser=UTB())
full_text = xml_tree.find('article:originalText', elsevier_ns)
if full_text is None:
logger.info('Could not find full text element article:originalText')
return None
article_body = _get_article_body(full_text)
if article_body:
return article_body
raw_text = _get_raw_text(full_text)
if raw_text:
return [raw_text]
return None | python | def extract_paragraphs(xml_string):
assert isinstance(xml_string, str)
xml_tree = ET.XML(xml_string.encode('utf-8'), parser=UTB())
full_text = xml_tree.find('article:originalText', elsevier_ns)
if full_text is None:
logger.info('Could not find full text element article:originalText')
return None
article_body = _get_article_body(full_text)
if article_body:
return article_body
raw_text = _get_raw_text(full_text)
if raw_text:
return [raw_text]
return None | [
"def",
"extract_paragraphs",
"(",
"xml_string",
")",
":",
"assert",
"isinstance",
"(",
"xml_string",
",",
"str",
")",
"xml_tree",
"=",
"ET",
".",
"XML",
"(",
"xml_string",
".",
"encode",
"(",
"'utf-8'",
")",
",",
"parser",
"=",
"UTB",
"(",
")",
")",
"f... | Get paragraphs from the body of the given Elsevier xml. | [
"Get",
"paragraphs",
"from",
"the",
"body",
"of",
"the",
"given",
"Elsevier",
"xml",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/literature/elsevier_client.py#L245-L259 |
18,762 | sorgerlab/indra | indra/literature/elsevier_client.py | get_dois | def get_dois(query_str, count=100):
"""Search ScienceDirect through the API for articles.
See http://api.elsevier.com/content/search/fields/scidir for constructing a
query string to pass here. Example: 'abstract(BRAF) AND all("colorectal
cancer")'
"""
url = '%s/%s' % (elsevier_search_url, query_str)
params = {'query': query_str,
'count': count,
'httpAccept': 'application/xml',
'sort': '-coverdate',
'field': 'doi'}
res = requests.get(url, params)
if not res.status_code == 200:
return None
tree = ET.XML(res.content, parser=UTB())
doi_tags = tree.findall('atom:entry/prism:doi', elsevier_ns)
dois = [dt.text for dt in doi_tags]
return dois | python | def get_dois(query_str, count=100):
url = '%s/%s' % (elsevier_search_url, query_str)
params = {'query': query_str,
'count': count,
'httpAccept': 'application/xml',
'sort': '-coverdate',
'field': 'doi'}
res = requests.get(url, params)
if not res.status_code == 200:
return None
tree = ET.XML(res.content, parser=UTB())
doi_tags = tree.findall('atom:entry/prism:doi', elsevier_ns)
dois = [dt.text for dt in doi_tags]
return dois | [
"def",
"get_dois",
"(",
"query_str",
",",
"count",
"=",
"100",
")",
":",
"url",
"=",
"'%s/%s'",
"%",
"(",
"elsevier_search_url",
",",
"query_str",
")",
"params",
"=",
"{",
"'query'",
":",
"query_str",
",",
"'count'",
":",
"count",
",",
"'httpAccept'",
":... | Search ScienceDirect through the API for articles.
See http://api.elsevier.com/content/search/fields/scidir for constructing a
query string to pass here. Example: 'abstract(BRAF) AND all("colorectal
cancer")' | [
"Search",
"ScienceDirect",
"through",
"the",
"API",
"for",
"articles",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/literature/elsevier_client.py#L264-L283 |
18,763 | sorgerlab/indra | indra/literature/elsevier_client.py | get_piis | def get_piis(query_str):
"""Search ScienceDirect through the API for articles and return PIIs.
Note that ScienceDirect has a limitation in which a maximum of 6,000
PIIs can be retrieved for a given search and therefore this call is
internally broken up into multiple queries by a range of years and the
results are combined.
Parameters
----------
query_str : str
The query string to search with
Returns
-------
piis : list[str]
The list of PIIs identifying the papers returned by the search
"""
dates = range(1960, datetime.datetime.now().year)
all_piis = flatten([get_piis_for_date(query_str, date) for date in dates])
return all_piis | python | def get_piis(query_str):
dates = range(1960, datetime.datetime.now().year)
all_piis = flatten([get_piis_for_date(query_str, date) for date in dates])
return all_piis | [
"def",
"get_piis",
"(",
"query_str",
")",
":",
"dates",
"=",
"range",
"(",
"1960",
",",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
".",
"year",
")",
"all_piis",
"=",
"flatten",
"(",
"[",
"get_piis_for_date",
"(",
"query_str",
",",
"date",
")",
... | Search ScienceDirect through the API for articles and return PIIs.
Note that ScienceDirect has a limitation in which a maximum of 6,000
PIIs can be retrieved for a given search and therefore this call is
internally broken up into multiple queries by a range of years and the
results are combined.
Parameters
----------
query_str : str
The query string to search with
Returns
-------
piis : list[str]
The list of PIIs identifying the papers returned by the search | [
"Search",
"ScienceDirect",
"through",
"the",
"API",
"for",
"articles",
"and",
"return",
"PIIs",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/literature/elsevier_client.py#L286-L306 |
18,764 | sorgerlab/indra | indra/literature/elsevier_client.py | get_piis_for_date | def get_piis_for_date(query_str, date):
"""Search ScienceDirect with a query string constrained to a given year.
Parameters
----------
query_str : str
The query string to search with
date : str
The year to constrain the search to
Returns
-------
piis : list[str]
The list of PIIs identifying the papers returned by the search
"""
count = 200
params = {'query': query_str,
'count': count,
'start': 0,
'sort': '-coverdate',
'date': date,
'field': 'pii'}
all_piis = []
while True:
res = requests.get(elsevier_search_url, params, headers=ELSEVIER_KEYS)
if not res.status_code == 200:
logger.info('Got status code: %d' % res.status_code)
break
res_json = res.json()
entries = res_json['search-results']['entry']
logger.info(res_json['search-results']['opensearch:totalResults'])
if entries == [{'@_fa': 'true', 'error': 'Result set was empty'}]:
logger.info('Search result was empty')
return []
piis = [entry['pii'] for entry in entries]
all_piis += piis
# Get next batch
links = res_json['search-results'].get('link', [])
cont = False
for link in links:
if link.get('@ref') == 'next':
logger.info('Found link to next batch of results.')
params['start'] += count
cont = True
break
if not cont:
break
return all_piis | python | def get_piis_for_date(query_str, date):
count = 200
params = {'query': query_str,
'count': count,
'start': 0,
'sort': '-coverdate',
'date': date,
'field': 'pii'}
all_piis = []
while True:
res = requests.get(elsevier_search_url, params, headers=ELSEVIER_KEYS)
if not res.status_code == 200:
logger.info('Got status code: %d' % res.status_code)
break
res_json = res.json()
entries = res_json['search-results']['entry']
logger.info(res_json['search-results']['opensearch:totalResults'])
if entries == [{'@_fa': 'true', 'error': 'Result set was empty'}]:
logger.info('Search result was empty')
return []
piis = [entry['pii'] for entry in entries]
all_piis += piis
# Get next batch
links = res_json['search-results'].get('link', [])
cont = False
for link in links:
if link.get('@ref') == 'next':
logger.info('Found link to next batch of results.')
params['start'] += count
cont = True
break
if not cont:
break
return all_piis | [
"def",
"get_piis_for_date",
"(",
"query_str",
",",
"date",
")",
":",
"count",
"=",
"200",
"params",
"=",
"{",
"'query'",
":",
"query_str",
",",
"'count'",
":",
"count",
",",
"'start'",
":",
"0",
",",
"'sort'",
":",
"'-coverdate'",
",",
"'date'",
":",
"... | Search ScienceDirect with a query string constrained to a given year.
Parameters
----------
query_str : str
The query string to search with
date : str
The year to constrain the search to
Returns
-------
piis : list[str]
The list of PIIs identifying the papers returned by the search | [
"Search",
"ScienceDirect",
"with",
"a",
"query",
"string",
"constrained",
"to",
"a",
"given",
"year",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/literature/elsevier_client.py#L311-L358 |
18,765 | sorgerlab/indra | indra/literature/elsevier_client.py | download_from_search | def download_from_search(query_str, folder, do_extract_text=True,
max_results=None):
"""Save raw text files based on a search for papers on ScienceDirect.
This performs a search to get PIIs, downloads the XML corresponding to
the PII, extracts the raw text and then saves the text into a file
in the designated folder.
Parameters
----------
query_str : str
The query string to search with
folder : str
The local path to an existing folder in which the text files
will be dumped
do_extract_text : bool
Choose whether to extract text from the xml, or simply save the raw xml
files. Default is True, so text is extracted.
max_results : int or None
Default is None. If specified, limit the number of results to the given
maximum.
"""
piis = get_piis(query_str)
for pii in piis[:max_results]:
if os.path.exists(os.path.join(folder, '%s.txt' % pii)):
continue
logger.info('Downloading %s' % pii)
xml = download_article(pii, 'pii')
sleep(1)
if do_extract_text:
txt = extract_text(xml)
if not txt:
continue
with open(os.path.join(folder, '%s.txt' % pii), 'wb') as fh:
fh.write(txt.encode('utf-8'))
else:
with open(os.path.join(folder, '%s.xml' % pii), 'wb') as fh:
fh.write(xml.encode('utf-8'))
return | python | def download_from_search(query_str, folder, do_extract_text=True,
max_results=None):
piis = get_piis(query_str)
for pii in piis[:max_results]:
if os.path.exists(os.path.join(folder, '%s.txt' % pii)):
continue
logger.info('Downloading %s' % pii)
xml = download_article(pii, 'pii')
sleep(1)
if do_extract_text:
txt = extract_text(xml)
if not txt:
continue
with open(os.path.join(folder, '%s.txt' % pii), 'wb') as fh:
fh.write(txt.encode('utf-8'))
else:
with open(os.path.join(folder, '%s.xml' % pii), 'wb') as fh:
fh.write(xml.encode('utf-8'))
return | [
"def",
"download_from_search",
"(",
"query_str",
",",
"folder",
",",
"do_extract_text",
"=",
"True",
",",
"max_results",
"=",
"None",
")",
":",
"piis",
"=",
"get_piis",
"(",
"query_str",
")",
"for",
"pii",
"in",
"piis",
"[",
":",
"max_results",
"]",
":",
... | Save raw text files based on a search for papers on ScienceDirect.
This performs a search to get PIIs, downloads the XML corresponding to
the PII, extracts the raw text and then saves the text into a file
in the designated folder.
Parameters
----------
query_str : str
The query string to search with
folder : str
The local path to an existing folder in which the text files
will be dumped
do_extract_text : bool
Choose whether to extract text from the xml, or simply save the raw xml
files. Default is True, so text is extracted.
max_results : int or None
Default is None. If specified, limit the number of results to the given
maximum. | [
"Save",
"raw",
"text",
"files",
"based",
"on",
"a",
"search",
"for",
"papers",
"on",
"ScienceDirect",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/literature/elsevier_client.py#L361-L400 |
18,766 | sorgerlab/indra | indra/sources/cwms/rdf_processor.py | CWMSRDFProcessor.extract_statement_from_query_result | def extract_statement_from_query_result(self, res):
"""Adds a statement based on one element of a rdflib SPARQL query.
Parameters
----------
res: rdflib.query.ResultRow
Element of rdflib SPARQL query result
"""
agent_start, agent_end, affected_start, affected_end = res
# Convert from rdflib literals to python integers so we can use
# them to index strings
agent_start = int(agent_start)
agent_end = int(agent_end)
affected_start = int(affected_start)
affected_end = int(affected_end)
# Find the text corresponding to these indices
agent = self.text[agent_start:agent_end]
affected = self.text[affected_start:affected_end]
# Strip off surrounding whitespace
agent = agent.lstrip().rstrip()
affected = affected.lstrip().rstrip()
# Make an Agent object for both the subject and the object
subj = Agent(agent, db_refs={'TEXT': agent})
obj = Agent(affected, db_refs={'TEXT': affected})
statement = Influence(subj=subj, obj=obj)
# Add the statement to the list of statements
self.statements.append(statement) | python | def extract_statement_from_query_result(self, res):
agent_start, agent_end, affected_start, affected_end = res
# Convert from rdflib literals to python integers so we can use
# them to index strings
agent_start = int(agent_start)
agent_end = int(agent_end)
affected_start = int(affected_start)
affected_end = int(affected_end)
# Find the text corresponding to these indices
agent = self.text[agent_start:agent_end]
affected = self.text[affected_start:affected_end]
# Strip off surrounding whitespace
agent = agent.lstrip().rstrip()
affected = affected.lstrip().rstrip()
# Make an Agent object for both the subject and the object
subj = Agent(agent, db_refs={'TEXT': agent})
obj = Agent(affected, db_refs={'TEXT': affected})
statement = Influence(subj=subj, obj=obj)
# Add the statement to the list of statements
self.statements.append(statement) | [
"def",
"extract_statement_from_query_result",
"(",
"self",
",",
"res",
")",
":",
"agent_start",
",",
"agent_end",
",",
"affected_start",
",",
"affected_end",
"=",
"res",
"# Convert from rdflib literals to python integers so we can use",
"# them to index strings",
"agent_start",... | Adds a statement based on one element of a rdflib SPARQL query.
Parameters
----------
res: rdflib.query.ResultRow
Element of rdflib SPARQL query result | [
"Adds",
"a",
"statement",
"based",
"on",
"one",
"element",
"of",
"a",
"rdflib",
"SPARQL",
"query",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/cwms/rdf_processor.py#L45-L77 |
18,767 | sorgerlab/indra | indra/sources/cwms/rdf_processor.py | CWMSRDFProcessor.extract_statements | def extract_statements(self):
"""Extracts INDRA statements from the RDF graph via SPARQL queries.
"""
# Look for events that have an AGENT and an AFFECTED, and get the
# start and ending text indices for each.
query = prefixes + """
SELECT
?agent_start
?agent_end
?affected_start
?affected_end
WHERE {
?rel role:AGENT ?agent .
?rel role:AFFECTED ?affected .
?agent lf:start ?agent_start .
?agent lf:end ?agent_end .
?affected lf:start ?affected_start .
?affected lf:end ?affected_end .
}
"""
results = self.graph.query(query)
for res in results:
# Make a statement for each query match
self.extract_statement_from_query_result(res)
# Look for events that have an AGENT and a RESULT, and get the start
# and ending text indices for each.
query = query.replace('role:AFFECTED', 'role:RESULT')
results = self.graph.query(query)
for res in results:
# Make a statement for each query match
self.extract_statement_from_query_result(res) | python | def extract_statements(self):
# Look for events that have an AGENT and an AFFECTED, and get the
# start and ending text indices for each.
query = prefixes + """
SELECT
?agent_start
?agent_end
?affected_start
?affected_end
WHERE {
?rel role:AGENT ?agent .
?rel role:AFFECTED ?affected .
?agent lf:start ?agent_start .
?agent lf:end ?agent_end .
?affected lf:start ?affected_start .
?affected lf:end ?affected_end .
}
"""
results = self.graph.query(query)
for res in results:
# Make a statement for each query match
self.extract_statement_from_query_result(res)
# Look for events that have an AGENT and a RESULT, and get the start
# and ending text indices for each.
query = query.replace('role:AFFECTED', 'role:RESULT')
results = self.graph.query(query)
for res in results:
# Make a statement for each query match
self.extract_statement_from_query_result(res) | [
"def",
"extract_statements",
"(",
"self",
")",
":",
"# Look for events that have an AGENT and an AFFECTED, and get the",
"# start and ending text indices for each.",
"query",
"=",
"prefixes",
"+",
"\"\"\"\n SELECT\n ?agent_start\n ?agent_end\n ?affecte... | Extracts INDRA statements from the RDF graph via SPARQL queries. | [
"Extracts",
"INDRA",
"statements",
"from",
"the",
"RDF",
"graph",
"via",
"SPARQL",
"queries",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/cwms/rdf_processor.py#L79-L111 |
18,768 | sorgerlab/indra | indra/sources/signor/processor.py | SignorProcessor._recursively_lookup_complex | def _recursively_lookup_complex(self, complex_id):
"""Looks up the constitutents of a complex. If any constituent is
itself a complex, recursively expands until all constituents are
not complexes."""
assert complex_id in self.complex_map
expanded_agent_strings = []
expand_these_next = [complex_id]
while len(expand_these_next) > 0:
# Pop next element
c = expand_these_next[0]
expand_these_next = expand_these_next[1:]
# If a complex, add expanding it to the end of the queue
# If an agent string, add it to the agent string list immediately
assert c in self.complex_map
for s in self.complex_map[c]:
if s in self.complex_map:
expand_these_next.append(s)
else:
expanded_agent_strings.append(s)
return expanded_agent_strings | python | def _recursively_lookup_complex(self, complex_id):
assert complex_id in self.complex_map
expanded_agent_strings = []
expand_these_next = [complex_id]
while len(expand_these_next) > 0:
# Pop next element
c = expand_these_next[0]
expand_these_next = expand_these_next[1:]
# If a complex, add expanding it to the end of the queue
# If an agent string, add it to the agent string list immediately
assert c in self.complex_map
for s in self.complex_map[c]:
if s in self.complex_map:
expand_these_next.append(s)
else:
expanded_agent_strings.append(s)
return expanded_agent_strings | [
"def",
"_recursively_lookup_complex",
"(",
"self",
",",
"complex_id",
")",
":",
"assert",
"complex_id",
"in",
"self",
".",
"complex_map",
"expanded_agent_strings",
"=",
"[",
"]",
"expand_these_next",
"=",
"[",
"complex_id",
"]",
"while",
"len",
"(",
"expand_these_... | Looks up the constitutents of a complex. If any constituent is
itself a complex, recursively expands until all constituents are
not complexes. | [
"Looks",
"up",
"the",
"constitutents",
"of",
"a",
"complex",
".",
"If",
"any",
"constituent",
"is",
"itself",
"a",
"complex",
"recursively",
"expands",
"until",
"all",
"constituents",
"are",
"not",
"complexes",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/signor/processor.py#L223-L244 |
18,769 | sorgerlab/indra | indra/sources/signor/processor.py | SignorProcessor._get_complex_agents | def _get_complex_agents(self, complex_id):
"""Returns a list of agents corresponding to each of the constituents
in a SIGNOR complex."""
agents = []
components = self._recursively_lookup_complex(complex_id)
for c in components:
db_refs = {}
name = uniprot_client.get_gene_name(c)
if name is None:
db_refs['SIGNOR'] = c
else:
db_refs['UP'] = c
hgnc_id = hgnc_client.get_hgnc_id(name)
if hgnc_id:
db_refs['HGNC'] = hgnc_id
famplex_key = ('SIGNOR', c)
if famplex_key in famplex_map:
db_refs['FPLX'] = famplex_map[famplex_key]
if not name:
name = db_refs['FPLX'] # Set agent name to Famplex name if
# the Uniprot name is not available
elif not name:
# We neither have a Uniprot nor Famplex grounding
logger.info('Have neither a Uniprot nor Famplex grounding ' + \
'for ' + c)
if not name:
name = db_refs['SIGNOR'] # Set the agent name to the
# Signor name if neither the
# Uniprot nor Famplex names are
# available
assert(name is not None)
agents.append(Agent(name, db_refs=db_refs))
return agents | python | def _get_complex_agents(self, complex_id):
agents = []
components = self._recursively_lookup_complex(complex_id)
for c in components:
db_refs = {}
name = uniprot_client.get_gene_name(c)
if name is None:
db_refs['SIGNOR'] = c
else:
db_refs['UP'] = c
hgnc_id = hgnc_client.get_hgnc_id(name)
if hgnc_id:
db_refs['HGNC'] = hgnc_id
famplex_key = ('SIGNOR', c)
if famplex_key in famplex_map:
db_refs['FPLX'] = famplex_map[famplex_key]
if not name:
name = db_refs['FPLX'] # Set agent name to Famplex name if
# the Uniprot name is not available
elif not name:
# We neither have a Uniprot nor Famplex grounding
logger.info('Have neither a Uniprot nor Famplex grounding ' + \
'for ' + c)
if not name:
name = db_refs['SIGNOR'] # Set the agent name to the
# Signor name if neither the
# Uniprot nor Famplex names are
# available
assert(name is not None)
agents.append(Agent(name, db_refs=db_refs))
return agents | [
"def",
"_get_complex_agents",
"(",
"self",
",",
"complex_id",
")",
":",
"agents",
"=",
"[",
"]",
"components",
"=",
"self",
".",
"_recursively_lookup_complex",
"(",
"complex_id",
")",
"for",
"c",
"in",
"components",
":",
"db_refs",
"=",
"{",
"}",
"name",
"... | Returns a list of agents corresponding to each of the constituents
in a SIGNOR complex. | [
"Returns",
"a",
"list",
"of",
"agents",
"corresponding",
"to",
"each",
"of",
"the",
"constituents",
"in",
"a",
"SIGNOR",
"complex",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/signor/processor.py#L246-L280 |
18,770 | sorgerlab/indra | indra/statements/io.py | stmts_from_json | def stmts_from_json(json_in, on_missing_support='handle'):
"""Get a list of Statements from Statement jsons.
In the case of pre-assembled Statements which have `supports` and
`supported_by` lists, the uuids will be replaced with references to
Statement objects from the json, where possible. The method of handling
missing support is controled by the `on_missing_support` key-word argument.
Parameters
----------
json_in : iterable[dict]
A json list containing json dict representations of INDRA Statements,
as produced by the `to_json` methods of subclasses of Statement, or
equivalently by `stmts_to_json`.
on_missing_support : Optional[str]
Handles the behavior when a uuid reference in `supports` or
`supported_by` attribute cannot be resolved. This happens because uuids
can only be linked to Statements contained in the `json_in` list, and
some may be missing if only some of all the Statements from pre-
assembly are contained in the list.
Options:
- *'handle'* : (default) convert unresolved uuids into `Unresolved`
Statement objects.
- *'ignore'* : Simply omit any uuids that cannot be linked to any
Statements in the list.
- *'error'* : Raise an error upon hitting an un-linkable uuid.
Returns
-------
stmts : list[:py:class:`Statement`]
A list of INDRA Statements.
"""
stmts = []
uuid_dict = {}
for json_stmt in json_in:
try:
st = Statement._from_json(json_stmt)
except Exception as e:
logger.warning("Error creating statement: %s" % e)
continue
stmts.append(st)
uuid_dict[st.uuid] = st
for st in stmts:
_promote_support(st.supports, uuid_dict, on_missing_support)
_promote_support(st.supported_by, uuid_dict, on_missing_support)
return stmts | python | def stmts_from_json(json_in, on_missing_support='handle'):
stmts = []
uuid_dict = {}
for json_stmt in json_in:
try:
st = Statement._from_json(json_stmt)
except Exception as e:
logger.warning("Error creating statement: %s" % e)
continue
stmts.append(st)
uuid_dict[st.uuid] = st
for st in stmts:
_promote_support(st.supports, uuid_dict, on_missing_support)
_promote_support(st.supported_by, uuid_dict, on_missing_support)
return stmts | [
"def",
"stmts_from_json",
"(",
"json_in",
",",
"on_missing_support",
"=",
"'handle'",
")",
":",
"stmts",
"=",
"[",
"]",
"uuid_dict",
"=",
"{",
"}",
"for",
"json_stmt",
"in",
"json_in",
":",
"try",
":",
"st",
"=",
"Statement",
".",
"_from_json",
"(",
"jso... | Get a list of Statements from Statement jsons.
In the case of pre-assembled Statements which have `supports` and
`supported_by` lists, the uuids will be replaced with references to
Statement objects from the json, where possible. The method of handling
missing support is controled by the `on_missing_support` key-word argument.
Parameters
----------
json_in : iterable[dict]
A json list containing json dict representations of INDRA Statements,
as produced by the `to_json` methods of subclasses of Statement, or
equivalently by `stmts_to_json`.
on_missing_support : Optional[str]
Handles the behavior when a uuid reference in `supports` or
`supported_by` attribute cannot be resolved. This happens because uuids
can only be linked to Statements contained in the `json_in` list, and
some may be missing if only some of all the Statements from pre-
assembly are contained in the list.
Options:
- *'handle'* : (default) convert unresolved uuids into `Unresolved`
Statement objects.
- *'ignore'* : Simply omit any uuids that cannot be linked to any
Statements in the list.
- *'error'* : Raise an error upon hitting an un-linkable uuid.
Returns
-------
stmts : list[:py:class:`Statement`]
A list of INDRA Statements. | [
"Get",
"a",
"list",
"of",
"Statements",
"from",
"Statement",
"jsons",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/statements/io.py#L16-L64 |
18,771 | sorgerlab/indra | indra/statements/io.py | stmts_to_json_file | def stmts_to_json_file(stmts, fname):
"""Serialize a list of INDRA Statements into a JSON file.
Parameters
----------
stmts : list[indra.statement.Statements]
The list of INDRA Statements to serialize into the JSON file.
fname : str
Path to the JSON file to serialize Statements into.
"""
with open(fname, 'w') as fh:
json.dump(stmts_to_json(stmts), fh, indent=1) | python | def stmts_to_json_file(stmts, fname):
with open(fname, 'w') as fh:
json.dump(stmts_to_json(stmts), fh, indent=1) | [
"def",
"stmts_to_json_file",
"(",
"stmts",
",",
"fname",
")",
":",
"with",
"open",
"(",
"fname",
",",
"'w'",
")",
"as",
"fh",
":",
"json",
".",
"dump",
"(",
"stmts_to_json",
"(",
"stmts",
")",
",",
"fh",
",",
"indent",
"=",
"1",
")"
] | Serialize a list of INDRA Statements into a JSON file.
Parameters
----------
stmts : list[indra.statement.Statements]
The list of INDRA Statements to serialize into the JSON file.
fname : str
Path to the JSON file to serialize Statements into. | [
"Serialize",
"a",
"list",
"of",
"INDRA",
"Statements",
"into",
"a",
"JSON",
"file",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/statements/io.py#L84-L95 |
18,772 | sorgerlab/indra | indra/statements/io.py | stmts_to_json | def stmts_to_json(stmts_in, use_sbo=False):
"""Return the JSON-serialized form of one or more INDRA Statements.
Parameters
----------
stmts_in : Statement or list[Statement]
A Statement or list of Statement objects to serialize into JSON.
use_sbo : Optional[bool]
If True, SBO annotations are added to each applicable element of the
JSON. Default: False
Returns
-------
json_dict : dict
JSON-serialized INDRA Statements.
"""
if not isinstance(stmts_in, list):
json_dict = stmts_in.to_json(use_sbo=use_sbo)
return json_dict
else:
json_dict = [st.to_json(use_sbo=use_sbo) for st in stmts_in]
return json_dict | python | def stmts_to_json(stmts_in, use_sbo=False):
if not isinstance(stmts_in, list):
json_dict = stmts_in.to_json(use_sbo=use_sbo)
return json_dict
else:
json_dict = [st.to_json(use_sbo=use_sbo) for st in stmts_in]
return json_dict | [
"def",
"stmts_to_json",
"(",
"stmts_in",
",",
"use_sbo",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"stmts_in",
",",
"list",
")",
":",
"json_dict",
"=",
"stmts_in",
".",
"to_json",
"(",
"use_sbo",
"=",
"use_sbo",
")",
"return",
"json_dict",
... | Return the JSON-serialized form of one or more INDRA Statements.
Parameters
----------
stmts_in : Statement or list[Statement]
A Statement or list of Statement objects to serialize into JSON.
use_sbo : Optional[bool]
If True, SBO annotations are added to each applicable element of the
JSON. Default: False
Returns
-------
json_dict : dict
JSON-serialized INDRA Statements. | [
"Return",
"the",
"JSON",
"-",
"serialized",
"form",
"of",
"one",
"or",
"more",
"INDRA",
"Statements",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/statements/io.py#L98-L119 |
18,773 | sorgerlab/indra | indra/statements/io.py | _promote_support | def _promote_support(sup_list, uuid_dict, on_missing='handle'):
"""Promote the list of support-related uuids to Statements, if possible."""
valid_handling_choices = ['handle', 'error', 'ignore']
if on_missing not in valid_handling_choices:
raise InputError('Invalid option for `on_missing_support`: \'%s\'\n'
'Choices are: %s.'
% (on_missing, str(valid_handling_choices)))
for idx, uuid in enumerate(sup_list):
if uuid in uuid_dict.keys():
sup_list[idx] = uuid_dict[uuid]
elif on_missing == 'handle':
sup_list[idx] = Unresolved(uuid)
elif on_missing == 'ignore':
sup_list.remove(uuid)
elif on_missing == 'error':
raise UnresolvedUuidError("Uuid %s not found in stmt jsons."
% uuid)
return | python | def _promote_support(sup_list, uuid_dict, on_missing='handle'):
valid_handling_choices = ['handle', 'error', 'ignore']
if on_missing not in valid_handling_choices:
raise InputError('Invalid option for `on_missing_support`: \'%s\'\n'
'Choices are: %s.'
% (on_missing, str(valid_handling_choices)))
for idx, uuid in enumerate(sup_list):
if uuid in uuid_dict.keys():
sup_list[idx] = uuid_dict[uuid]
elif on_missing == 'handle':
sup_list[idx] = Unresolved(uuid)
elif on_missing == 'ignore':
sup_list.remove(uuid)
elif on_missing == 'error':
raise UnresolvedUuidError("Uuid %s not found in stmt jsons."
% uuid)
return | [
"def",
"_promote_support",
"(",
"sup_list",
",",
"uuid_dict",
",",
"on_missing",
"=",
"'handle'",
")",
":",
"valid_handling_choices",
"=",
"[",
"'handle'",
",",
"'error'",
",",
"'ignore'",
"]",
"if",
"on_missing",
"not",
"in",
"valid_handling_choices",
":",
"rai... | Promote the list of support-related uuids to Statements, if possible. | [
"Promote",
"the",
"list",
"of",
"support",
"-",
"related",
"uuids",
"to",
"Statements",
"if",
"possible",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/statements/io.py#L122-L139 |
18,774 | sorgerlab/indra | indra/statements/io.py | draw_stmt_graph | def draw_stmt_graph(stmts):
"""Render the attributes of a list of Statements as directed graphs.
The layout works well for a single Statement or a few Statements at a time.
This function displays the plot of the graph using plt.show().
Parameters
----------
stmts : list[indra.statements.Statement]
A list of one or more INDRA Statements whose attribute graph should
be drawn.
"""
import networkx
try:
import matplotlib.pyplot as plt
except Exception:
logger.error('Could not import matplotlib, not drawing graph.')
return
try: # This checks whether networkx has this package to work with.
import pygraphviz
except Exception:
logger.error('Could not import pygraphviz, not drawing graph.')
return
import numpy
g = networkx.compose_all([stmt.to_graph() for stmt in stmts])
plt.figure()
plt.ion()
g.graph['graph'] = {'rankdir': 'LR'}
pos = networkx.drawing.nx_agraph.graphviz_layout(g, prog='dot')
g = g.to_undirected()
# Draw nodes
options = {
'marker': 'o',
's': 200,
'c': [0.85, 0.85, 1],
'facecolor': '0.5',
'lw': 0,
}
ax = plt.gca()
nodelist = list(g)
xy = numpy.asarray([pos[v] for v in nodelist])
node_collection = ax.scatter(xy[:, 0], xy[:, 1], **options)
node_collection.set_zorder(2)
# Draw edges
networkx.draw_networkx_edges(g, pos, arrows=False, edge_color='0.5')
# Draw labels
edge_labels = {(e[0], e[1]): e[2].get('label') for e in g.edges(data=True)}
networkx.draw_networkx_edge_labels(g, pos, edge_labels=edge_labels)
node_labels = {n[0]: n[1].get('label') for n in g.nodes(data=True)}
for key, label in node_labels.items():
if len(label) > 25:
parts = label.split(' ')
parts.insert(int(len(parts)/2), '\n')
label = ' '.join(parts)
node_labels[key] = label
networkx.draw_networkx_labels(g, pos, labels=node_labels)
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
plt.show() | python | def draw_stmt_graph(stmts):
import networkx
try:
import matplotlib.pyplot as plt
except Exception:
logger.error('Could not import matplotlib, not drawing graph.')
return
try: # This checks whether networkx has this package to work with.
import pygraphviz
except Exception:
logger.error('Could not import pygraphviz, not drawing graph.')
return
import numpy
g = networkx.compose_all([stmt.to_graph() for stmt in stmts])
plt.figure()
plt.ion()
g.graph['graph'] = {'rankdir': 'LR'}
pos = networkx.drawing.nx_agraph.graphviz_layout(g, prog='dot')
g = g.to_undirected()
# Draw nodes
options = {
'marker': 'o',
's': 200,
'c': [0.85, 0.85, 1],
'facecolor': '0.5',
'lw': 0,
}
ax = plt.gca()
nodelist = list(g)
xy = numpy.asarray([pos[v] for v in nodelist])
node_collection = ax.scatter(xy[:, 0], xy[:, 1], **options)
node_collection.set_zorder(2)
# Draw edges
networkx.draw_networkx_edges(g, pos, arrows=False, edge_color='0.5')
# Draw labels
edge_labels = {(e[0], e[1]): e[2].get('label') for e in g.edges(data=True)}
networkx.draw_networkx_edge_labels(g, pos, edge_labels=edge_labels)
node_labels = {n[0]: n[1].get('label') for n in g.nodes(data=True)}
for key, label in node_labels.items():
if len(label) > 25:
parts = label.split(' ')
parts.insert(int(len(parts)/2), '\n')
label = ' '.join(parts)
node_labels[key] = label
networkx.draw_networkx_labels(g, pos, labels=node_labels)
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
plt.show() | [
"def",
"draw_stmt_graph",
"(",
"stmts",
")",
":",
"import",
"networkx",
"try",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"except",
"Exception",
":",
"logger",
".",
"error",
"(",
"'Could not import matplotlib, not drawing graph.'",
")",
"return",
"tr... | Render the attributes of a list of Statements as directed graphs.
The layout works well for a single Statement or a few Statements at a time.
This function displays the plot of the graph using plt.show().
Parameters
----------
stmts : list[indra.statements.Statement]
A list of one or more INDRA Statements whose attribute graph should
be drawn. | [
"Render",
"the",
"attributes",
"of",
"a",
"list",
"of",
"Statements",
"as",
"directed",
"graphs",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/statements/io.py#L142-L201 |
18,775 | sorgerlab/indra | indra/sources/sparser/processor.py | _fix_json_agents | def _fix_json_agents(ag_obj):
"""Fix the json representation of an agent."""
if isinstance(ag_obj, str):
logger.info("Fixing string agent: %s." % ag_obj)
ret = {'name': ag_obj, 'db_refs': {'TEXT': ag_obj}}
elif isinstance(ag_obj, list):
# Recursive for complexes and similar.
ret = [_fix_json_agents(ag) for ag in ag_obj]
elif isinstance(ag_obj, dict) and 'TEXT' in ag_obj.keys():
ret = deepcopy(ag_obj)
text = ret.pop('TEXT')
ret['db_refs']['TEXT'] = text
else:
ret = ag_obj
return ret | python | def _fix_json_agents(ag_obj):
if isinstance(ag_obj, str):
logger.info("Fixing string agent: %s." % ag_obj)
ret = {'name': ag_obj, 'db_refs': {'TEXT': ag_obj}}
elif isinstance(ag_obj, list):
# Recursive for complexes and similar.
ret = [_fix_json_agents(ag) for ag in ag_obj]
elif isinstance(ag_obj, dict) and 'TEXT' in ag_obj.keys():
ret = deepcopy(ag_obj)
text = ret.pop('TEXT')
ret['db_refs']['TEXT'] = text
else:
ret = ag_obj
return ret | [
"def",
"_fix_json_agents",
"(",
"ag_obj",
")",
":",
"if",
"isinstance",
"(",
"ag_obj",
",",
"str",
")",
":",
"logger",
".",
"info",
"(",
"\"Fixing string agent: %s.\"",
"%",
"ag_obj",
")",
"ret",
"=",
"{",
"'name'",
":",
"ag_obj",
",",
"'db_refs'",
":",
... | Fix the json representation of an agent. | [
"Fix",
"the",
"json",
"representation",
"of",
"an",
"agent",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/sparser/processor.py#L23-L37 |
18,776 | sorgerlab/indra | indra/sources/sparser/processor.py | SparserJSONProcessor.set_statements_pmid | def set_statements_pmid(self, pmid):
"""Set the evidence PMID of Statements that have been extracted.
Parameters
----------
pmid : str or None
The PMID to be used in the Evidence objects of the Statements
that were extracted by the processor.
"""
# Replace PMID value in JSON dict first
for stmt in self.json_stmts:
evs = stmt.get('evidence', [])
for ev in evs:
ev['pmid'] = pmid
# Replace PMID value in extracted Statements next
for stmt in self.statements:
for ev in stmt.evidence:
ev.pmid = pmid | python | def set_statements_pmid(self, pmid):
# Replace PMID value in JSON dict first
for stmt in self.json_stmts:
evs = stmt.get('evidence', [])
for ev in evs:
ev['pmid'] = pmid
# Replace PMID value in extracted Statements next
for stmt in self.statements:
for ev in stmt.evidence:
ev.pmid = pmid | [
"def",
"set_statements_pmid",
"(",
"self",
",",
"pmid",
")",
":",
"# Replace PMID value in JSON dict first",
"for",
"stmt",
"in",
"self",
".",
"json_stmts",
":",
"evs",
"=",
"stmt",
".",
"get",
"(",
"'evidence'",
",",
"[",
"]",
")",
"for",
"ev",
"in",
"evs... | Set the evidence PMID of Statements that have been extracted.
Parameters
----------
pmid : str or None
The PMID to be used in the Evidence objects of the Statements
that were extracted by the processor. | [
"Set",
"the",
"evidence",
"PMID",
"of",
"Statements",
"that",
"have",
"been",
"extracted",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/sparser/processor.py#L155-L172 |
18,777 | sorgerlab/indra | indra/sources/trips/analyze_ekbs.py | get_args | def get_args(node):
"""Return the arguments of a node in the event graph."""
arg_roles = {}
args = node.findall('arg') + \
[node.find('arg1'), node.find('arg2'), node.find('arg3')]
for arg in args:
if arg is not None:
id = arg.attrib.get('id')
if id is not None:
arg_roles[arg.attrib['role']] = (arg.attrib['id'], arg)
# Now look at possible inevent links
if node.find('features') is not None:
inevents = node.findall('features/inevent')
for inevent in inevents:
if 'id' in inevent.attrib:
arg_roles['inevent'] = (inevent.attrib['id'], inevent)
ptms = node.findall('features/ptm') + node.findall('features/no-ptm')
for ptm in ptms:
if 'id' in inevent.attrib:
arg_roles['ptm'] = (inevent.attrib['id'], ptm)
# And also look for assoc-with links
aw = node.find('assoc-with')
if aw is not None:
aw_id = aw.attrib['id']
arg_roles['assoc-with'] = (aw_id, aw)
return arg_roles | python | def get_args(node):
arg_roles = {}
args = node.findall('arg') + \
[node.find('arg1'), node.find('arg2'), node.find('arg3')]
for arg in args:
if arg is not None:
id = arg.attrib.get('id')
if id is not None:
arg_roles[arg.attrib['role']] = (arg.attrib['id'], arg)
# Now look at possible inevent links
if node.find('features') is not None:
inevents = node.findall('features/inevent')
for inevent in inevents:
if 'id' in inevent.attrib:
arg_roles['inevent'] = (inevent.attrib['id'], inevent)
ptms = node.findall('features/ptm') + node.findall('features/no-ptm')
for ptm in ptms:
if 'id' in inevent.attrib:
arg_roles['ptm'] = (inevent.attrib['id'], ptm)
# And also look for assoc-with links
aw = node.find('assoc-with')
if aw is not None:
aw_id = aw.attrib['id']
arg_roles['assoc-with'] = (aw_id, aw)
return arg_roles | [
"def",
"get_args",
"(",
"node",
")",
":",
"arg_roles",
"=",
"{",
"}",
"args",
"=",
"node",
".",
"findall",
"(",
"'arg'",
")",
"+",
"[",
"node",
".",
"find",
"(",
"'arg1'",
")",
",",
"node",
".",
"find",
"(",
"'arg2'",
")",
",",
"node",
".",
"fi... | Return the arguments of a node in the event graph. | [
"Return",
"the",
"arguments",
"of",
"a",
"node",
"in",
"the",
"event",
"graph",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/trips/analyze_ekbs.py#L20-L47 |
18,778 | sorgerlab/indra | indra/sources/trips/analyze_ekbs.py | type_match | def type_match(a, b):
"""Return True of the types of a and b are compatible, False otherwise."""
# If the types are the same, return True
if a['type'] == b['type']:
return True
# Otherwise, look at some special cases
eq_groups = [
{'ONT::GENE-PROTEIN', 'ONT::GENE', 'ONT::PROTEIN'},
{'ONT::PHARMACOLOGIC-SUBSTANCE', 'ONT::CHEMICAL'}
]
for eq_group in eq_groups:
if a['type'] in eq_group and b['type'] in eq_group:
return True
return False | python | def type_match(a, b):
# If the types are the same, return True
if a['type'] == b['type']:
return True
# Otherwise, look at some special cases
eq_groups = [
{'ONT::GENE-PROTEIN', 'ONT::GENE', 'ONT::PROTEIN'},
{'ONT::PHARMACOLOGIC-SUBSTANCE', 'ONT::CHEMICAL'}
]
for eq_group in eq_groups:
if a['type'] in eq_group and b['type'] in eq_group:
return True
return False | [
"def",
"type_match",
"(",
"a",
",",
"b",
")",
":",
"# If the types are the same, return True",
"if",
"a",
"[",
"'type'",
"]",
"==",
"b",
"[",
"'type'",
"]",
":",
"return",
"True",
"# Otherwise, look at some special cases",
"eq_groups",
"=",
"[",
"{",
"'ONT::GENE... | Return True of the types of a and b are compatible, False otherwise. | [
"Return",
"True",
"of",
"the",
"types",
"of",
"a",
"and",
"b",
"are",
"compatible",
"False",
"otherwise",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/trips/analyze_ekbs.py#L58-L71 |
18,779 | sorgerlab/indra | indra/sources/trips/analyze_ekbs.py | add_graph | def add_graph(patterns, G):
"""Add a graph to a set of unique patterns."""
if not patterns:
patterns.append([G])
return
for i, graphs in enumerate(patterns):
if networkx.is_isomorphic(graphs[0], G, node_match=type_match,
edge_match=type_match):
patterns[i].append(G)
return
patterns.append([G]) | python | def add_graph(patterns, G):
if not patterns:
patterns.append([G])
return
for i, graphs in enumerate(patterns):
if networkx.is_isomorphic(graphs[0], G, node_match=type_match,
edge_match=type_match):
patterns[i].append(G)
return
patterns.append([G]) | [
"def",
"add_graph",
"(",
"patterns",
",",
"G",
")",
":",
"if",
"not",
"patterns",
":",
"patterns",
".",
"append",
"(",
"[",
"G",
"]",
")",
"return",
"for",
"i",
",",
"graphs",
"in",
"enumerate",
"(",
"patterns",
")",
":",
"if",
"networkx",
".",
"is... | Add a graph to a set of unique patterns. | [
"Add",
"a",
"graph",
"to",
"a",
"set",
"of",
"unique",
"patterns",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/trips/analyze_ekbs.py#L74-L84 |
18,780 | sorgerlab/indra | indra/sources/trips/analyze_ekbs.py | draw | def draw(graph, fname):
"""Draw a graph and save it into a file"""
ag = networkx.nx_agraph.to_agraph(graph)
ag.draw(fname, prog='dot') | python | def draw(graph, fname):
ag = networkx.nx_agraph.to_agraph(graph)
ag.draw(fname, prog='dot') | [
"def",
"draw",
"(",
"graph",
",",
"fname",
")",
":",
"ag",
"=",
"networkx",
".",
"nx_agraph",
".",
"to_agraph",
"(",
"graph",
")",
"ag",
".",
"draw",
"(",
"fname",
",",
"prog",
"=",
"'dot'",
")"
] | Draw a graph and save it into a file | [
"Draw",
"a",
"graph",
"and",
"save",
"it",
"into",
"a",
"file"
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/trips/analyze_ekbs.py#L87-L90 |
18,781 | sorgerlab/indra | indra/sources/trips/analyze_ekbs.py | build_event_graph | def build_event_graph(graph, tree, node):
"""Return a DiGraph of a specific event structure, built recursively"""
# If we have already added this node then let's return
if node_key(node) in graph:
return
type = get_type(node)
text = get_text(node)
label = '%s (%s)' % (type, text)
graph.add_node(node_key(node), type=type, label=label, text=text)
args = get_args(node)
for arg_role, (arg_id, arg_tag) in args.items():
arg = get_node_by_id(tree, arg_id)
if arg is None:
arg = arg_tag
build_event_graph(graph, tree, arg)
graph.add_edge(node_key(node), node_key(arg), type=arg_role,
label=arg_role) | python | def build_event_graph(graph, tree, node):
# If we have already added this node then let's return
if node_key(node) in graph:
return
type = get_type(node)
text = get_text(node)
label = '%s (%s)' % (type, text)
graph.add_node(node_key(node), type=type, label=label, text=text)
args = get_args(node)
for arg_role, (arg_id, arg_tag) in args.items():
arg = get_node_by_id(tree, arg_id)
if arg is None:
arg = arg_tag
build_event_graph(graph, tree, arg)
graph.add_edge(node_key(node), node_key(arg), type=arg_role,
label=arg_role) | [
"def",
"build_event_graph",
"(",
"graph",
",",
"tree",
",",
"node",
")",
":",
"# If we have already added this node then let's return",
"if",
"node_key",
"(",
"node",
")",
"in",
"graph",
":",
"return",
"type",
"=",
"get_type",
"(",
"node",
")",
"text",
"=",
"g... | Return a DiGraph of a specific event structure, built recursively | [
"Return",
"a",
"DiGraph",
"of",
"a",
"specific",
"event",
"structure",
"built",
"recursively"
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/trips/analyze_ekbs.py#L107-L123 |
18,782 | sorgerlab/indra | indra/sources/trips/analyze_ekbs.py | get_extracted_events | def get_extracted_events(fnames):
"""Get a full list of all extracted event IDs from a list of EKB files"""
event_list = []
for fn in fnames:
tp = trips.process_xml_file(fn)
ed = tp.extracted_events
for k, v in ed.items():
event_list += v
return event_list | python | def get_extracted_events(fnames):
event_list = []
for fn in fnames:
tp = trips.process_xml_file(fn)
ed = tp.extracted_events
for k, v in ed.items():
event_list += v
return event_list | [
"def",
"get_extracted_events",
"(",
"fnames",
")",
":",
"event_list",
"=",
"[",
"]",
"for",
"fn",
"in",
"fnames",
":",
"tp",
"=",
"trips",
".",
"process_xml_file",
"(",
"fn",
")",
"ed",
"=",
"tp",
".",
"extracted_events",
"for",
"k",
",",
"v",
"in",
... | Get a full list of all extracted event IDs from a list of EKB files | [
"Get",
"a",
"full",
"list",
"of",
"all",
"extracted",
"event",
"IDs",
"from",
"a",
"list",
"of",
"EKB",
"files"
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/trips/analyze_ekbs.py#L126-L134 |
18,783 | sorgerlab/indra | indra/sources/trips/analyze_ekbs.py | check_event_coverage | def check_event_coverage(patterns, event_list):
"""Calculate the ratio of patterns that were extracted."""
proportions = []
for pattern_list in patterns:
proportion = 0
for pattern in pattern_list:
for node in pattern.nodes():
if node in event_list:
proportion += 1.0 / len(pattern_list)
break
proportions.append(proportion)
return proportions | python | def check_event_coverage(patterns, event_list):
proportions = []
for pattern_list in patterns:
proportion = 0
for pattern in pattern_list:
for node in pattern.nodes():
if node in event_list:
proportion += 1.0 / len(pattern_list)
break
proportions.append(proportion)
return proportions | [
"def",
"check_event_coverage",
"(",
"patterns",
",",
"event_list",
")",
":",
"proportions",
"=",
"[",
"]",
"for",
"pattern_list",
"in",
"patterns",
":",
"proportion",
"=",
"0",
"for",
"pattern",
"in",
"pattern_list",
":",
"for",
"node",
"in",
"pattern",
".",... | Calculate the ratio of patterns that were extracted. | [
"Calculate",
"the",
"ratio",
"of",
"patterns",
"that",
"were",
"extracted",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/trips/analyze_ekbs.py#L137-L148 |
18,784 | sorgerlab/indra | indra/preassembler/ontology_mapper.py | OntologyMapper.map_statements | def map_statements(self):
"""Run the ontology mapping on the statements."""
for stmt in self.statements:
for agent in stmt.agent_list():
if agent is None:
continue
all_mappings = []
for db_name, db_id in agent.db_refs.items():
if isinstance(db_id, list):
db_id = db_id[0][0]
mappings = self._map_id(db_name, db_id)
all_mappings += mappings
for map_db_name, map_db_id, score, orig_db_name in all_mappings:
if map_db_name in agent.db_refs:
continue
if self.scored:
# If the original one is a scored grounding,
# we take that score and multiply it with the mapping
# score. Otherwise we assume the original score is 1.
try:
orig_score = agent.db_refs[orig_db_name][0][1]
except Exception:
orig_score = 1.0
agent.db_refs[map_db_name] = \
[(map_db_id, score * orig_score)]
else:
if map_db_name in ('UN', 'HUME'):
agent.db_refs[map_db_name] = [(map_db_id, 1.0)]
else:
agent.db_refs[map_db_name] = map_db_id | python | def map_statements(self):
for stmt in self.statements:
for agent in stmt.agent_list():
if agent is None:
continue
all_mappings = []
for db_name, db_id in agent.db_refs.items():
if isinstance(db_id, list):
db_id = db_id[0][0]
mappings = self._map_id(db_name, db_id)
all_mappings += mappings
for map_db_name, map_db_id, score, orig_db_name in all_mappings:
if map_db_name in agent.db_refs:
continue
if self.scored:
# If the original one is a scored grounding,
# we take that score and multiply it with the mapping
# score. Otherwise we assume the original score is 1.
try:
orig_score = agent.db_refs[orig_db_name][0][1]
except Exception:
orig_score = 1.0
agent.db_refs[map_db_name] = \
[(map_db_id, score * orig_score)]
else:
if map_db_name in ('UN', 'HUME'):
agent.db_refs[map_db_name] = [(map_db_id, 1.0)]
else:
agent.db_refs[map_db_name] = map_db_id | [
"def",
"map_statements",
"(",
"self",
")",
":",
"for",
"stmt",
"in",
"self",
".",
"statements",
":",
"for",
"agent",
"in",
"stmt",
".",
"agent_list",
"(",
")",
":",
"if",
"agent",
"is",
"None",
":",
"continue",
"all_mappings",
"=",
"[",
"]",
"for",
"... | Run the ontology mapping on the statements. | [
"Run",
"the",
"ontology",
"mapping",
"on",
"the",
"statements",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/preassembler/ontology_mapper.py#L45-L74 |
18,785 | sorgerlab/indra | indra/preassembler/grounding_mapper.py | load_grounding_map | def load_grounding_map(grounding_map_path, ignore_path=None,
lineterminator='\r\n'):
"""Return a grounding map dictionary loaded from a csv file.
In the file pointed to by grounding_map_path, the number of name_space ID
pairs can vary per row and commas are
used to pad out entries containing fewer than the maximum amount of
name spaces appearing in the file. Lines should be terminated with \r\n
both a carriage return and a new line by default.
Optionally, one can specify another csv file (pointed to by ignore_path)
containing agent texts that are degenerate and should be filtered out.
Parameters
----------
grounding_map_path : str
Path to csv file containing grounding map information. Rows of the file
should be of the form <agent_text>,<name_space_1>,<ID_1>,...
<name_space_n>,<ID_n>
ignore_path : Optional[str]
Path to csv file containing terms that should be filtered out during
the grounding mapping process. The file Should be of the form
<agent_text>,,..., where the number of commas that
appear is the same as in the csv file at grounding_map_path.
Default: None
lineterminator : Optional[str]
Line terminator used in input csv file. Default: \r\n
Returns
-------
g_map : dict
The grounding map constructed from the given files.
"""
g_map = {}
map_rows = read_unicode_csv(grounding_map_path, delimiter=',',
quotechar='"',
quoting=csv.QUOTE_MINIMAL,
lineterminator='\r\n')
if ignore_path and os.path.exists(ignore_path):
ignore_rows = read_unicode_csv(ignore_path, delimiter=',',
quotechar='"',
quoting=csv.QUOTE_MINIMAL,
lineterminator=lineterminator)
else:
ignore_rows = []
csv_rows = chain(map_rows, ignore_rows)
for row in csv_rows:
key = row[0]
db_refs = {'TEXT': key}
keys = [entry for entry in row[1::2] if entry != '']
values = [entry for entry in row[2::2] if entry != '']
if len(keys) != len(values):
logger.info('ERROR: Mismatched keys and values in row %s' %
str(row))
continue
else:
db_refs.update(dict(zip(keys, values)))
if len(db_refs.keys()) > 1:
g_map[key] = db_refs
else:
g_map[key] = None
return g_map | python | def load_grounding_map(grounding_map_path, ignore_path=None,
lineterminator='\r\n'):
g_map = {}
map_rows = read_unicode_csv(grounding_map_path, delimiter=',',
quotechar='"',
quoting=csv.QUOTE_MINIMAL,
lineterminator='\r\n')
if ignore_path and os.path.exists(ignore_path):
ignore_rows = read_unicode_csv(ignore_path, delimiter=',',
quotechar='"',
quoting=csv.QUOTE_MINIMAL,
lineterminator=lineterminator)
else:
ignore_rows = []
csv_rows = chain(map_rows, ignore_rows)
for row in csv_rows:
key = row[0]
db_refs = {'TEXT': key}
keys = [entry for entry in row[1::2] if entry != '']
values = [entry for entry in row[2::2] if entry != '']
if len(keys) != len(values):
logger.info('ERROR: Mismatched keys and values in row %s' %
str(row))
continue
else:
db_refs.update(dict(zip(keys, values)))
if len(db_refs.keys()) > 1:
g_map[key] = db_refs
else:
g_map[key] = None
return g_map | [
"def",
"load_grounding_map",
"(",
"grounding_map_path",
",",
"ignore_path",
"=",
"None",
",",
"lineterminator",
"=",
"'\\r\\n'",
")",
":",
"g_map",
"=",
"{",
"}",
"map_rows",
"=",
"read_unicode_csv",
"(",
"grounding_map_path",
",",
"delimiter",
"=",
"','",
",",
... | Return a grounding map dictionary loaded from a csv file.
In the file pointed to by grounding_map_path, the number of name_space ID
pairs can vary per row and commas are
used to pad out entries containing fewer than the maximum amount of
name spaces appearing in the file. Lines should be terminated with \r\n
both a carriage return and a new line by default.
Optionally, one can specify another csv file (pointed to by ignore_path)
containing agent texts that are degenerate and should be filtered out.
Parameters
----------
grounding_map_path : str
Path to csv file containing grounding map information. Rows of the file
should be of the form <agent_text>,<name_space_1>,<ID_1>,...
<name_space_n>,<ID_n>
ignore_path : Optional[str]
Path to csv file containing terms that should be filtered out during
the grounding mapping process. The file Should be of the form
<agent_text>,,..., where the number of commas that
appear is the same as in the csv file at grounding_map_path.
Default: None
lineterminator : Optional[str]
Line terminator used in input csv file. Default: \r\n
Returns
-------
g_map : dict
The grounding map constructed from the given files. | [
"Return",
"a",
"grounding",
"map",
"dictionary",
"loaded",
"from",
"a",
"csv",
"file",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/preassembler/grounding_mapper.py#L360-L421 |
18,786 | sorgerlab/indra | indra/preassembler/grounding_mapper.py | all_agents | def all_agents(stmts):
"""Return a list of all of the agents from a list of statements.
Only agents that are not None and have a TEXT entry are returned.
Parameters
----------
stmts : list of :py:class:`indra.statements.Statement`
Returns
-------
agents : list of :py:class:`indra.statements.Agent`
List of agents that appear in the input list of indra statements.
"""
agents = []
for stmt in stmts:
for agent in stmt.agent_list():
# Agents don't always have a TEXT db_refs entry (for instance
# in the case of Statements from databases) so we check for this.
if agent is not None and agent.db_refs.get('TEXT') is not None:
agents.append(agent)
return agents | python | def all_agents(stmts):
agents = []
for stmt in stmts:
for agent in stmt.agent_list():
# Agents don't always have a TEXT db_refs entry (for instance
# in the case of Statements from databases) so we check for this.
if agent is not None and agent.db_refs.get('TEXT') is not None:
agents.append(agent)
return agents | [
"def",
"all_agents",
"(",
"stmts",
")",
":",
"agents",
"=",
"[",
"]",
"for",
"stmt",
"in",
"stmts",
":",
"for",
"agent",
"in",
"stmt",
".",
"agent_list",
"(",
")",
":",
"# Agents don't always have a TEXT db_refs entry (for instance",
"# in the case of Statements fro... | Return a list of all of the agents from a list of statements.
Only agents that are not None and have a TEXT entry are returned.
Parameters
----------
stmts : list of :py:class:`indra.statements.Statement`
Returns
-------
agents : list of :py:class:`indra.statements.Agent`
List of agents that appear in the input list of indra statements. | [
"Return",
"a",
"list",
"of",
"all",
"of",
"the",
"agents",
"from",
"a",
"list",
"of",
"statements",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/preassembler/grounding_mapper.py#L426-L447 |
18,787 | sorgerlab/indra | indra/preassembler/grounding_mapper.py | get_sentences_for_agent | def get_sentences_for_agent(text, stmts, max_sentences=None):
"""Returns evidence sentences with a given agent text from a list of statements
Parameters
----------
text : str
An agent text
stmts : list of :py:class:`indra.statements.Statement`
INDRA Statements to search in for evidence statements.
max_sentences : Optional[int/None]
Cap on the number of evidence sentences to return. Default: None
Returns
-------
sentences : list of str
Evidence sentences from the list of statements containing
the given agent text.
"""
sentences = []
for stmt in stmts:
for agent in stmt.agent_list():
if agent is not None and agent.db_refs.get('TEXT') == text:
sentences.append((stmt.evidence[0].pmid,
stmt.evidence[0].text))
if max_sentences is not None and \
len(sentences) >= max_sentences:
return sentences
return sentences | python | def get_sentences_for_agent(text, stmts, max_sentences=None):
sentences = []
for stmt in stmts:
for agent in stmt.agent_list():
if agent is not None and agent.db_refs.get('TEXT') == text:
sentences.append((stmt.evidence[0].pmid,
stmt.evidence[0].text))
if max_sentences is not None and \
len(sentences) >= max_sentences:
return sentences
return sentences | [
"def",
"get_sentences_for_agent",
"(",
"text",
",",
"stmts",
",",
"max_sentences",
"=",
"None",
")",
":",
"sentences",
"=",
"[",
"]",
"for",
"stmt",
"in",
"stmts",
":",
"for",
"agent",
"in",
"stmt",
".",
"agent_list",
"(",
")",
":",
"if",
"agent",
"is"... | Returns evidence sentences with a given agent text from a list of statements
Parameters
----------
text : str
An agent text
stmts : list of :py:class:`indra.statements.Statement`
INDRA Statements to search in for evidence statements.
max_sentences : Optional[int/None]
Cap on the number of evidence sentences to return. Default: None
Returns
-------
sentences : list of str
Evidence sentences from the list of statements containing
the given agent text. | [
"Returns",
"evidence",
"sentences",
"with",
"a",
"given",
"agent",
"text",
"from",
"a",
"list",
"of",
"statements"
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/preassembler/grounding_mapper.py#L467-L496 |
18,788 | sorgerlab/indra | indra/preassembler/grounding_mapper.py | agent_texts_with_grounding | def agent_texts_with_grounding(stmts):
"""Return agent text groundings in a list of statements with their counts
Parameters
----------
stmts: list of :py:class:`indra.statements.Statement`
Returns
-------
list of tuple
List of tuples of the form
(text: str, ((name_space: str, ID: str, count: int)...),
total_count: int)
Where the counts within the tuple of groundings give the number of
times an agent with the given agent_text appears grounded with the
particular name space and ID. The total_count gives the total number
of times an agent with text appears in the list of statements.
"""
allag = all_agents(stmts)
# Convert PFAM-DEF lists into tuples so that they are hashable and can
# be tabulated with a Counter
for ag in allag:
pfam_def = ag.db_refs.get('PFAM-DEF')
if pfam_def is not None:
ag.db_refs['PFAM-DEF'] = tuple(pfam_def)
refs = [tuple(ag.db_refs.items()) for ag in allag]
refs_counter = Counter(refs)
refs_counter_dict = [(dict(entry[0]), entry[1])
for entry in refs_counter.items()]
# First, sort by text so that we can do a groupby
refs_counter_dict.sort(key=lambda x: x[0].get('TEXT'))
# Then group by text
grouped_by_text = []
for k, g in groupby(refs_counter_dict, key=lambda x: x[0].get('TEXT')):
# Total occurrences of this agent text
total = 0
entry = [k]
db_ref_list = []
for db_refs, count in g:
# Check if TEXT is our only key, indicating no grounding
if list(db_refs.keys()) == ['TEXT']:
db_ref_list.append((None, None, count))
# Add any other db_refs (not TEXT)
for db, db_id in db_refs.items():
if db == 'TEXT':
continue
else:
db_ref_list.append((db, db_id, count))
total += count
# Sort the db_ref_list by the occurrences of each grounding
entry.append(tuple(sorted(db_ref_list, key=lambda x: x[2],
reverse=True)))
# Now add the total frequency to the entry
entry.append(total)
# And add the entry to the overall list
grouped_by_text.append(tuple(entry))
# Sort the list by the total number of occurrences of each unique key
grouped_by_text.sort(key=lambda x: x[2], reverse=True)
return grouped_by_text | python | def agent_texts_with_grounding(stmts):
allag = all_agents(stmts)
# Convert PFAM-DEF lists into tuples so that they are hashable and can
# be tabulated with a Counter
for ag in allag:
pfam_def = ag.db_refs.get('PFAM-DEF')
if pfam_def is not None:
ag.db_refs['PFAM-DEF'] = tuple(pfam_def)
refs = [tuple(ag.db_refs.items()) for ag in allag]
refs_counter = Counter(refs)
refs_counter_dict = [(dict(entry[0]), entry[1])
for entry in refs_counter.items()]
# First, sort by text so that we can do a groupby
refs_counter_dict.sort(key=lambda x: x[0].get('TEXT'))
# Then group by text
grouped_by_text = []
for k, g in groupby(refs_counter_dict, key=lambda x: x[0].get('TEXT')):
# Total occurrences of this agent text
total = 0
entry = [k]
db_ref_list = []
for db_refs, count in g:
# Check if TEXT is our only key, indicating no grounding
if list(db_refs.keys()) == ['TEXT']:
db_ref_list.append((None, None, count))
# Add any other db_refs (not TEXT)
for db, db_id in db_refs.items():
if db == 'TEXT':
continue
else:
db_ref_list.append((db, db_id, count))
total += count
# Sort the db_ref_list by the occurrences of each grounding
entry.append(tuple(sorted(db_ref_list, key=lambda x: x[2],
reverse=True)))
# Now add the total frequency to the entry
entry.append(total)
# And add the entry to the overall list
grouped_by_text.append(tuple(entry))
# Sort the list by the total number of occurrences of each unique key
grouped_by_text.sort(key=lambda x: x[2], reverse=True)
return grouped_by_text | [
"def",
"agent_texts_with_grounding",
"(",
"stmts",
")",
":",
"allag",
"=",
"all_agents",
"(",
"stmts",
")",
"# Convert PFAM-DEF lists into tuples so that they are hashable and can",
"# be tabulated with a Counter",
"for",
"ag",
"in",
"allag",
":",
"pfam_def",
"=",
"ag",
"... | Return agent text groundings in a list of statements with their counts
Parameters
----------
stmts: list of :py:class:`indra.statements.Statement`
Returns
-------
list of tuple
List of tuples of the form
(text: str, ((name_space: str, ID: str, count: int)...),
total_count: int)
Where the counts within the tuple of groundings give the number of
times an agent with the given agent_text appears grounded with the
particular name space and ID. The total_count gives the total number
of times an agent with text appears in the list of statements. | [
"Return",
"agent",
"text",
"groundings",
"in",
"a",
"list",
"of",
"statements",
"with",
"their",
"counts"
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/preassembler/grounding_mapper.py#L499-L559 |
18,789 | sorgerlab/indra | indra/preassembler/grounding_mapper.py | ungrounded_texts | def ungrounded_texts(stmts):
"""Return a list of all ungrounded entities ordered by number of mentions
Parameters
----------
stmts : list of :py:class:`indra.statements.Statement`
Returns
-------
ungroundc : list of tuple
list of tuples of the form (text: str, count: int) sorted in descending
order by count.
"""
ungrounded = [ag.db_refs['TEXT']
for s in stmts
for ag in s.agent_list()
if ag is not None and list(ag.db_refs.keys()) == ['TEXT']]
ungroundc = Counter(ungrounded)
ungroundc = ungroundc.items()
ungroundc = sorted(ungroundc, key=lambda x: x[1], reverse=True)
return ungroundc | python | def ungrounded_texts(stmts):
ungrounded = [ag.db_refs['TEXT']
for s in stmts
for ag in s.agent_list()
if ag is not None and list(ag.db_refs.keys()) == ['TEXT']]
ungroundc = Counter(ungrounded)
ungroundc = ungroundc.items()
ungroundc = sorted(ungroundc, key=lambda x: x[1], reverse=True)
return ungroundc | [
"def",
"ungrounded_texts",
"(",
"stmts",
")",
":",
"ungrounded",
"=",
"[",
"ag",
".",
"db_refs",
"[",
"'TEXT'",
"]",
"for",
"s",
"in",
"stmts",
"for",
"ag",
"in",
"s",
".",
"agent_list",
"(",
")",
"if",
"ag",
"is",
"not",
"None",
"and",
"list",
"("... | Return a list of all ungrounded entities ordered by number of mentions
Parameters
----------
stmts : list of :py:class:`indra.statements.Statement`
Returns
-------
ungroundc : list of tuple
list of tuples of the form (text: str, count: int) sorted in descending
order by count. | [
"Return",
"a",
"list",
"of",
"all",
"ungrounded",
"entities",
"ordered",
"by",
"number",
"of",
"mentions"
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/preassembler/grounding_mapper.py#L563-L583 |
18,790 | sorgerlab/indra | indra/preassembler/grounding_mapper.py | get_agents_with_name | def get_agents_with_name(name, stmts):
"""Return all agents within a list of statements with a particular name."""
return [ag for stmt in stmts for ag in stmt.agent_list()
if ag is not None and ag.name == name] | python | def get_agents_with_name(name, stmts):
return [ag for stmt in stmts for ag in stmt.agent_list()
if ag is not None and ag.name == name] | [
"def",
"get_agents_with_name",
"(",
"name",
",",
"stmts",
")",
":",
"return",
"[",
"ag",
"for",
"stmt",
"in",
"stmts",
"for",
"ag",
"in",
"stmt",
".",
"agent_list",
"(",
")",
"if",
"ag",
"is",
"not",
"None",
"and",
"ag",
".",
"name",
"==",
"name",
... | Return all agents within a list of statements with a particular name. | [
"Return",
"all",
"agents",
"within",
"a",
"list",
"of",
"statements",
"with",
"a",
"particular",
"name",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/preassembler/grounding_mapper.py#L586-L589 |
18,791 | sorgerlab/indra | indra/preassembler/grounding_mapper.py | save_base_map | def save_base_map(filename, grouped_by_text):
"""Dump a list of agents along with groundings and counts into a csv file
Parameters
----------
filename : str
Filepath for output file
grouped_by_text : list of tuple
List of tuples of the form output by agent_texts_with_grounding
"""
rows = []
for group in grouped_by_text:
text_string = group[0]
for db, db_id, count in group[1]:
if db == 'UP':
name = uniprot_client.get_mnemonic(db_id)
else:
name = ''
row = [text_string, db, db_id, count, name]
rows.append(row)
write_unicode_csv(filename, rows, delimiter=',', quotechar='"',
quoting=csv.QUOTE_MINIMAL, lineterminator='\r\n') | python | def save_base_map(filename, grouped_by_text):
rows = []
for group in grouped_by_text:
text_string = group[0]
for db, db_id, count in group[1]:
if db == 'UP':
name = uniprot_client.get_mnemonic(db_id)
else:
name = ''
row = [text_string, db, db_id, count, name]
rows.append(row)
write_unicode_csv(filename, rows, delimiter=',', quotechar='"',
quoting=csv.QUOTE_MINIMAL, lineterminator='\r\n') | [
"def",
"save_base_map",
"(",
"filename",
",",
"grouped_by_text",
")",
":",
"rows",
"=",
"[",
"]",
"for",
"group",
"in",
"grouped_by_text",
":",
"text_string",
"=",
"group",
"[",
"0",
"]",
"for",
"db",
",",
"db_id",
",",
"count",
"in",
"group",
"[",
"1"... | Dump a list of agents along with groundings and counts into a csv file
Parameters
----------
filename : str
Filepath for output file
grouped_by_text : list of tuple
List of tuples of the form output by agent_texts_with_grounding | [
"Dump",
"a",
"list",
"of",
"agents",
"along",
"with",
"groundings",
"and",
"counts",
"into",
"a",
"csv",
"file"
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/preassembler/grounding_mapper.py#L592-L614 |
18,792 | sorgerlab/indra | indra/preassembler/grounding_mapper.py | protein_map_from_twg | def protein_map_from_twg(twg):
"""Build map of entity texts to validate protein grounding.
Looks at the grounding of the entity texts extracted from the statements
and finds proteins where there is grounding to a human protein that maps to
an HGNC name that is an exact match to the entity text. Returns a dict that
can be used to update/expand the grounding map.
Parameters
----------
twg : list of tuple
list of tuples of the form output by agent_texts_with_grounding
Returns
-------
protein_map : dict
dict keyed on agent text with associated values
{'TEXT': agent_text, 'UP': uniprot_id}. Entries are for agent texts
where the grounding map was able to find human protein grounded to
this agent_text in Uniprot.
"""
protein_map = {}
unmatched = 0
matched = 0
logger.info('Building grounding map for human proteins')
for agent_text, grounding_list, _ in twg:
# If 'UP' (Uniprot) not one of the grounding entries for this text,
# then we skip it.
if 'UP' not in [entry[0] for entry in grounding_list]:
continue
# Otherwise, collect all the Uniprot IDs for this protein.
uniprot_ids = [entry[1] for entry in grounding_list
if entry[0] == 'UP']
# For each Uniprot ID, look up the species
for uniprot_id in uniprot_ids:
# If it's not a human protein, skip it
mnemonic = uniprot_client.get_mnemonic(uniprot_id)
if mnemonic is None or not mnemonic.endswith('_HUMAN'):
continue
# Otherwise, look up the gene name in HGNC and match against the
# agent text
gene_name = uniprot_client.get_gene_name(uniprot_id)
if gene_name is None:
unmatched += 1
continue
if agent_text.upper() == gene_name.upper():
matched += 1
protein_map[agent_text] = {'TEXT': agent_text,
'UP': uniprot_id}
else:
unmatched += 1
logger.info('Exact matches for %d proteins' % matched)
logger.info('No match (or no gene name) for %d proteins' % unmatched)
return protein_map | python | def protein_map_from_twg(twg):
protein_map = {}
unmatched = 0
matched = 0
logger.info('Building grounding map for human proteins')
for agent_text, grounding_list, _ in twg:
# If 'UP' (Uniprot) not one of the grounding entries for this text,
# then we skip it.
if 'UP' not in [entry[0] for entry in grounding_list]:
continue
# Otherwise, collect all the Uniprot IDs for this protein.
uniprot_ids = [entry[1] for entry in grounding_list
if entry[0] == 'UP']
# For each Uniprot ID, look up the species
for uniprot_id in uniprot_ids:
# If it's not a human protein, skip it
mnemonic = uniprot_client.get_mnemonic(uniprot_id)
if mnemonic is None or not mnemonic.endswith('_HUMAN'):
continue
# Otherwise, look up the gene name in HGNC and match against the
# agent text
gene_name = uniprot_client.get_gene_name(uniprot_id)
if gene_name is None:
unmatched += 1
continue
if agent_text.upper() == gene_name.upper():
matched += 1
protein_map[agent_text] = {'TEXT': agent_text,
'UP': uniprot_id}
else:
unmatched += 1
logger.info('Exact matches for %d proteins' % matched)
logger.info('No match (or no gene name) for %d proteins' % unmatched)
return protein_map | [
"def",
"protein_map_from_twg",
"(",
"twg",
")",
":",
"protein_map",
"=",
"{",
"}",
"unmatched",
"=",
"0",
"matched",
"=",
"0",
"logger",
".",
"info",
"(",
"'Building grounding map for human proteins'",
")",
"for",
"agent_text",
",",
"grounding_list",
",",
"_",
... | Build map of entity texts to validate protein grounding.
Looks at the grounding of the entity texts extracted from the statements
and finds proteins where there is grounding to a human protein that maps to
an HGNC name that is an exact match to the entity text. Returns a dict that
can be used to update/expand the grounding map.
Parameters
----------
twg : list of tuple
list of tuples of the form output by agent_texts_with_grounding
Returns
-------
protein_map : dict
dict keyed on agent text with associated values
{'TEXT': agent_text, 'UP': uniprot_id}. Entries are for agent texts
where the grounding map was able to find human protein grounded to
this agent_text in Uniprot. | [
"Build",
"map",
"of",
"entity",
"texts",
"to",
"validate",
"protein",
"grounding",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/preassembler/grounding_mapper.py#L617-L671 |
18,793 | sorgerlab/indra | indra/preassembler/grounding_mapper.py | save_sentences | def save_sentences(twg, stmts, filename, agent_limit=300):
"""Write evidence sentences for stmts with ungrounded agents to csv file.
Parameters
----------
twg: list of tuple
list of tuples of ungrounded agent_texts with counts of the
number of times they are mentioned in the list of statements.
Should be sorted in descending order by the counts.
This is of the form output by the function ungrounded texts.
stmts: list of :py:class:`indra.statements.Statement`
filename : str
Path to output file
agent_limit : Optional[int]
Number of agents to include in output file. Takes the top agents
by count.
"""
sentences = []
unmapped_texts = [t[0] for t in twg]
counter = 0
logger.info('Getting sentences for top %d unmapped agent texts.' %
agent_limit)
for text in unmapped_texts:
agent_sentences = get_sentences_for_agent(text, stmts)
sentences += map(lambda tup: (text,) + tup, agent_sentences)
counter += 1
if counter >= agent_limit:
break
# Write sentences to CSV file
write_unicode_csv(filename, sentences, delimiter=',', quotechar='"',
quoting=csv.QUOTE_MINIMAL, lineterminator='\r\n') | python | def save_sentences(twg, stmts, filename, agent_limit=300):
sentences = []
unmapped_texts = [t[0] for t in twg]
counter = 0
logger.info('Getting sentences for top %d unmapped agent texts.' %
agent_limit)
for text in unmapped_texts:
agent_sentences = get_sentences_for_agent(text, stmts)
sentences += map(lambda tup: (text,) + tup, agent_sentences)
counter += 1
if counter >= agent_limit:
break
# Write sentences to CSV file
write_unicode_csv(filename, sentences, delimiter=',', quotechar='"',
quoting=csv.QUOTE_MINIMAL, lineterminator='\r\n') | [
"def",
"save_sentences",
"(",
"twg",
",",
"stmts",
",",
"filename",
",",
"agent_limit",
"=",
"300",
")",
":",
"sentences",
"=",
"[",
"]",
"unmapped_texts",
"=",
"[",
"t",
"[",
"0",
"]",
"for",
"t",
"in",
"twg",
"]",
"counter",
"=",
"0",
"logger",
"... | Write evidence sentences for stmts with ungrounded agents to csv file.
Parameters
----------
twg: list of tuple
list of tuples of ungrounded agent_texts with counts of the
number of times they are mentioned in the list of statements.
Should be sorted in descending order by the counts.
This is of the form output by the function ungrounded texts.
stmts: list of :py:class:`indra.statements.Statement`
filename : str
Path to output file
agent_limit : Optional[int]
Number of agents to include in output file. Takes the top agents
by count. | [
"Write",
"evidence",
"sentences",
"for",
"stmts",
"with",
"ungrounded",
"agents",
"to",
"csv",
"file",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/preassembler/grounding_mapper.py#L674-L707 |
18,794 | sorgerlab/indra | indra/preassembler/grounding_mapper.py | _get_text_for_grounding | def _get_text_for_grounding(stmt, agent_text):
"""Get text context for Deft disambiguation
If the INDRA database is available, attempts to get the fulltext from
which the statement was extracted. If the fulltext is not available, the
abstract is returned. If the indra database is not available, uses the
pubmed client to get the abstract. If no abstract can be found, falls back
on returning the evidence text for the statement.
Parameters
----------
stmt : py:class:`indra.statements.Statement`
Statement with agent we seek to disambiguate.
agent_text : str
Agent text that needs to be disambiguated
Returns
-------
text : str
Text for Feft disambiguation
"""
text = None
# First we will try to get content from the DB
try:
from indra_db.util.content_scripts \
import get_text_content_from_text_refs
from indra.literature.deft_tools import universal_extract_text
refs = stmt.evidence[0].text_refs
# Prioritize the pmid attribute if given
if stmt.evidence[0].pmid:
refs['PMID'] = stmt.evidence[0].pmid
logger.info('Obtaining text for disambiguation with refs: %s' %
refs)
content = get_text_content_from_text_refs(refs)
text = universal_extract_text(content, contains=agent_text)
if text:
return text
except Exception as e:
logger.info('Could not get text for disambiguation from DB.')
# If that doesn't work, we try PubMed next
if text is None:
from indra.literature import pubmed_client
pmid = stmt.evidence[0].pmid
if pmid:
logger.info('Obtaining abstract for disambiguation for PMID%s' %
pmid)
text = pubmed_client.get_abstract(pmid)
if text:
return text
# Finally, falling back on the evidence sentence
if text is None:
logger.info('Falling back on sentence-based disambiguation')
text = stmt.evidence[0].text
return text
return None | python | def _get_text_for_grounding(stmt, agent_text):
text = None
# First we will try to get content from the DB
try:
from indra_db.util.content_scripts \
import get_text_content_from_text_refs
from indra.literature.deft_tools import universal_extract_text
refs = stmt.evidence[0].text_refs
# Prioritize the pmid attribute if given
if stmt.evidence[0].pmid:
refs['PMID'] = stmt.evidence[0].pmid
logger.info('Obtaining text for disambiguation with refs: %s' %
refs)
content = get_text_content_from_text_refs(refs)
text = universal_extract_text(content, contains=agent_text)
if text:
return text
except Exception as e:
logger.info('Could not get text for disambiguation from DB.')
# If that doesn't work, we try PubMed next
if text is None:
from indra.literature import pubmed_client
pmid = stmt.evidence[0].pmid
if pmid:
logger.info('Obtaining abstract for disambiguation for PMID%s' %
pmid)
text = pubmed_client.get_abstract(pmid)
if text:
return text
# Finally, falling back on the evidence sentence
if text is None:
logger.info('Falling back on sentence-based disambiguation')
text = stmt.evidence[0].text
return text
return None | [
"def",
"_get_text_for_grounding",
"(",
"stmt",
",",
"agent_text",
")",
":",
"text",
"=",
"None",
"# First we will try to get content from the DB",
"try",
":",
"from",
"indra_db",
".",
"util",
".",
"content_scripts",
"import",
"get_text_content_from_text_refs",
"from",
"... | Get text context for Deft disambiguation
If the INDRA database is available, attempts to get the fulltext from
which the statement was extracted. If the fulltext is not available, the
abstract is returned. If the indra database is not available, uses the
pubmed client to get the abstract. If no abstract can be found, falls back
on returning the evidence text for the statement.
Parameters
----------
stmt : py:class:`indra.statements.Statement`
Statement with agent we seek to disambiguate.
agent_text : str
Agent text that needs to be disambiguated
Returns
-------
text : str
Text for Feft disambiguation | [
"Get",
"text",
"context",
"for",
"Deft",
"disambiguation"
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/preassembler/grounding_mapper.py#L743-L798 |
18,795 | sorgerlab/indra | indra/preassembler/grounding_mapper.py | GroundingMapper.update_agent_db_refs | def update_agent_db_refs(self, agent, agent_text, do_rename=True):
"""Update db_refs of agent using the grounding map
If the grounding map is missing one of the HGNC symbol or Uniprot ID,
attempts to reconstruct one from the other.
Parameters
----------
agent : :py:class:`indra.statements.Agent`
The agent whose db_refs will be updated
agent_text : str
The agent_text to find a grounding for in the grounding map
dictionary. Typically this will be agent.db_refs['TEXT'] but
there may be situations where a different value should be used.
do_rename: Optional[bool]
If True, the Agent name is updated based on the mapped grounding.
If do_rename is True the priority for setting the name is
FamPlex ID, HGNC symbol, then the gene name
from Uniprot. Default: True
Raises
------
ValueError
If the the grounding map contains and HGNC symbol for
agent_text but no HGNC ID can be found for it.
ValueError
If the grounding map contains both an HGNC symbol and a
Uniprot ID, but the HGNC symbol and the gene name associated with
the gene in Uniprot do not match or if there is no associated gene
name in Uniprot.
"""
map_db_refs = deepcopy(self.gm.get(agent_text))
self.standardize_agent_db_refs(agent, map_db_refs, do_rename) | python | def update_agent_db_refs(self, agent, agent_text, do_rename=True):
map_db_refs = deepcopy(self.gm.get(agent_text))
self.standardize_agent_db_refs(agent, map_db_refs, do_rename) | [
"def",
"update_agent_db_refs",
"(",
"self",
",",
"agent",
",",
"agent_text",
",",
"do_rename",
"=",
"True",
")",
":",
"map_db_refs",
"=",
"deepcopy",
"(",
"self",
".",
"gm",
".",
"get",
"(",
"agent_text",
")",
")",
"self",
".",
"standardize_agent_db_refs",
... | Update db_refs of agent using the grounding map
If the grounding map is missing one of the HGNC symbol or Uniprot ID,
attempts to reconstruct one from the other.
Parameters
----------
agent : :py:class:`indra.statements.Agent`
The agent whose db_refs will be updated
agent_text : str
The agent_text to find a grounding for in the grounding map
dictionary. Typically this will be agent.db_refs['TEXT'] but
there may be situations where a different value should be used.
do_rename: Optional[bool]
If True, the Agent name is updated based on the mapped grounding.
If do_rename is True the priority for setting the name is
FamPlex ID, HGNC symbol, then the gene name
from Uniprot. Default: True
Raises
------
ValueError
If the the grounding map contains and HGNC symbol for
agent_text but no HGNC ID can be found for it.
ValueError
If the grounding map contains both an HGNC symbol and a
Uniprot ID, but the HGNC symbol and the gene name associated with
the gene in Uniprot do not match or if there is no associated gene
name in Uniprot. | [
"Update",
"db_refs",
"of",
"agent",
"using",
"the",
"grounding",
"map"
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/preassembler/grounding_mapper.py#L51-L83 |
18,796 | sorgerlab/indra | indra/preassembler/grounding_mapper.py | GroundingMapper.map_agents_for_stmt | def map_agents_for_stmt(self, stmt, do_rename=True):
"""Return a new Statement whose agents have been grounding mapped.
Parameters
----------
stmt : :py:class:`indra.statements.Statement`
The Statement whose agents need mapping.
do_rename: Optional[bool]
If True, the Agent name is updated based on the mapped grounding.
If do_rename is True the priority for setting the name is
FamPlex ID, HGNC symbol, then the gene name
from Uniprot. Default: True
Returns
-------
mapped_stmt : :py:class:`indra.statements.Statement`
The mapped Statement.
"""
mapped_stmt = deepcopy(stmt)
# Iterate over the agents
# Update agents directly participating in the statement
agent_list = mapped_stmt.agent_list()
for idx, agent in enumerate(agent_list):
if agent is None:
continue
agent_txt = agent.db_refs.get('TEXT')
if agent_txt is None:
continue
new_agent, maps_to_none = self.map_agent(agent, do_rename)
# Check if a deft model exists for agent text
if self.use_deft and agent_txt in deft_disambiguators:
try:
run_deft_disambiguation(mapped_stmt, agent_list, idx,
new_agent, agent_txt)
except Exception as e:
logger.error('There was an error during Deft'
' disambiguation.')
logger.error(e)
if maps_to_none:
# Skip the entire statement if the agent maps to None in the
# grounding map
return None
# If the old agent had bound conditions, but the new agent does
# not, copy the bound conditions over
if new_agent is not None and len(new_agent.bound_conditions) == 0:
new_agent.bound_conditions = agent.bound_conditions
agent_list[idx] = new_agent
mapped_stmt.set_agent_list(agent_list)
# Update agents in the bound conditions
for agent in agent_list:
if agent is not None:
for bc in agent.bound_conditions:
bc.agent, maps_to_none = self.map_agent(bc.agent,
do_rename)
if maps_to_none:
# Skip the entire statement if the agent maps to None
# in the grounding map
return None
return mapped_stmt | python | def map_agents_for_stmt(self, stmt, do_rename=True):
mapped_stmt = deepcopy(stmt)
# Iterate over the agents
# Update agents directly participating in the statement
agent_list = mapped_stmt.agent_list()
for idx, agent in enumerate(agent_list):
if agent is None:
continue
agent_txt = agent.db_refs.get('TEXT')
if agent_txt is None:
continue
new_agent, maps_to_none = self.map_agent(agent, do_rename)
# Check if a deft model exists for agent text
if self.use_deft and agent_txt in deft_disambiguators:
try:
run_deft_disambiguation(mapped_stmt, agent_list, idx,
new_agent, agent_txt)
except Exception as e:
logger.error('There was an error during Deft'
' disambiguation.')
logger.error(e)
if maps_to_none:
# Skip the entire statement if the agent maps to None in the
# grounding map
return None
# If the old agent had bound conditions, but the new agent does
# not, copy the bound conditions over
if new_agent is not None and len(new_agent.bound_conditions) == 0:
new_agent.bound_conditions = agent.bound_conditions
agent_list[idx] = new_agent
mapped_stmt.set_agent_list(agent_list)
# Update agents in the bound conditions
for agent in agent_list:
if agent is not None:
for bc in agent.bound_conditions:
bc.agent, maps_to_none = self.map_agent(bc.agent,
do_rename)
if maps_to_none:
# Skip the entire statement if the agent maps to None
# in the grounding map
return None
return mapped_stmt | [
"def",
"map_agents_for_stmt",
"(",
"self",
",",
"stmt",
",",
"do_rename",
"=",
"True",
")",
":",
"mapped_stmt",
"=",
"deepcopy",
"(",
"stmt",
")",
"# Iterate over the agents",
"# Update agents directly participating in the statement",
"agent_list",
"=",
"mapped_stmt",
"... | Return a new Statement whose agents have been grounding mapped.
Parameters
----------
stmt : :py:class:`indra.statements.Statement`
The Statement whose agents need mapping.
do_rename: Optional[bool]
If True, the Agent name is updated based on the mapped grounding.
If do_rename is True the priority for setting the name is
FamPlex ID, HGNC symbol, then the gene name
from Uniprot. Default: True
Returns
-------
mapped_stmt : :py:class:`indra.statements.Statement`
The mapped Statement. | [
"Return",
"a",
"new",
"Statement",
"whose",
"agents",
"have",
"been",
"grounding",
"mapped",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/preassembler/grounding_mapper.py#L150-L217 |
18,797 | sorgerlab/indra | indra/preassembler/grounding_mapper.py | GroundingMapper.map_agent | def map_agent(self, agent, do_rename):
"""Return the given Agent with its grounding mapped.
This function grounds a single agent. It returns the new Agent object
(which might be a different object if we load a new agent state
from json) or the same object otherwise.
Parameters
----------
agent : :py:class:`indra.statements.Agent`
The Agent to map.
do_rename: bool
If True, the Agent name is updated based on the mapped grounding.
If do_rename is True the priority for setting the name is
FamPlex ID, HGNC symbol, then the gene name
from Uniprot.
Returns
-------
grounded_agent : :py:class:`indra.statements.Agent`
The grounded Agent.
maps_to_none : bool
True if the Agent is in the grounding map and maps to None.
"""
agent_text = agent.db_refs.get('TEXT')
mapped_to_agent_json = self.agent_map.get(agent_text)
if mapped_to_agent_json:
mapped_to_agent = \
Agent._from_json(mapped_to_agent_json['agent'])
return mapped_to_agent, False
# Look this string up in the grounding map
# If not in the map, leave agent alone and continue
if agent_text in self.gm.keys():
map_db_refs = self.gm[agent_text]
else:
return agent, False
# If it's in the map but it maps to None, then filter out
# this statement by skipping it
if map_db_refs is None:
# Increase counter if this statement has not already
# been skipped via another agent
logger.debug("Skipping %s" % agent_text)
return None, True
# If it has a value that's not None, map it and add it
else:
# Otherwise, update the agent's db_refs field
self.update_agent_db_refs(agent, agent_text, do_rename)
return agent, False | python | def map_agent(self, agent, do_rename):
agent_text = agent.db_refs.get('TEXT')
mapped_to_agent_json = self.agent_map.get(agent_text)
if mapped_to_agent_json:
mapped_to_agent = \
Agent._from_json(mapped_to_agent_json['agent'])
return mapped_to_agent, False
# Look this string up in the grounding map
# If not in the map, leave agent alone and continue
if agent_text in self.gm.keys():
map_db_refs = self.gm[agent_text]
else:
return agent, False
# If it's in the map but it maps to None, then filter out
# this statement by skipping it
if map_db_refs is None:
# Increase counter if this statement has not already
# been skipped via another agent
logger.debug("Skipping %s" % agent_text)
return None, True
# If it has a value that's not None, map it and add it
else:
# Otherwise, update the agent's db_refs field
self.update_agent_db_refs(agent, agent_text, do_rename)
return agent, False | [
"def",
"map_agent",
"(",
"self",
",",
"agent",
",",
"do_rename",
")",
":",
"agent_text",
"=",
"agent",
".",
"db_refs",
".",
"get",
"(",
"'TEXT'",
")",
"mapped_to_agent_json",
"=",
"self",
".",
"agent_map",
".",
"get",
"(",
"agent_text",
")",
"if",
"mappe... | Return the given Agent with its grounding mapped.
This function grounds a single agent. It returns the new Agent object
(which might be a different object if we load a new agent state
from json) or the same object otherwise.
Parameters
----------
agent : :py:class:`indra.statements.Agent`
The Agent to map.
do_rename: bool
If True, the Agent name is updated based on the mapped grounding.
If do_rename is True the priority for setting the name is
FamPlex ID, HGNC symbol, then the gene name
from Uniprot.
Returns
-------
grounded_agent : :py:class:`indra.statements.Agent`
The grounded Agent.
maps_to_none : bool
True if the Agent is in the grounding map and maps to None. | [
"Return",
"the",
"given",
"Agent",
"with",
"its",
"grounding",
"mapped",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/preassembler/grounding_mapper.py#L219-L268 |
18,798 | sorgerlab/indra | indra/preassembler/grounding_mapper.py | GroundingMapper.map_agents | def map_agents(self, stmts, do_rename=True):
"""Return a new list of statements whose agents have been mapped
Parameters
----------
stmts : list of :py:class:`indra.statements.Statement`
The statements whose agents need mapping
do_rename: Optional[bool]
If True, the Agent name is updated based on the mapped grounding.
If do_rename is True the priority for setting the name is
FamPlex ID, HGNC symbol, then the gene name
from Uniprot. Default: True
Returns
-------
mapped_stmts : list of :py:class:`indra.statements.Statement`
A list of statements given by mapping the agents from each
statement in the input list
"""
# Make a copy of the stmts
mapped_stmts = []
num_skipped = 0
# Iterate over the statements
for stmt in stmts:
mapped_stmt = self.map_agents_for_stmt(stmt, do_rename)
# Check if we should skip the statement
if mapped_stmt is not None:
mapped_stmts.append(mapped_stmt)
else:
num_skipped += 1
logger.info('%s statements filtered out' % num_skipped)
return mapped_stmts | python | def map_agents(self, stmts, do_rename=True):
# Make a copy of the stmts
mapped_stmts = []
num_skipped = 0
# Iterate over the statements
for stmt in stmts:
mapped_stmt = self.map_agents_for_stmt(stmt, do_rename)
# Check if we should skip the statement
if mapped_stmt is not None:
mapped_stmts.append(mapped_stmt)
else:
num_skipped += 1
logger.info('%s statements filtered out' % num_skipped)
return mapped_stmts | [
"def",
"map_agents",
"(",
"self",
",",
"stmts",
",",
"do_rename",
"=",
"True",
")",
":",
"# Make a copy of the stmts",
"mapped_stmts",
"=",
"[",
"]",
"num_skipped",
"=",
"0",
"# Iterate over the statements",
"for",
"stmt",
"in",
"stmts",
":",
"mapped_stmt",
"=",... | Return a new list of statements whose agents have been mapped
Parameters
----------
stmts : list of :py:class:`indra.statements.Statement`
The statements whose agents need mapping
do_rename: Optional[bool]
If True, the Agent name is updated based on the mapped grounding.
If do_rename is True the priority for setting the name is
FamPlex ID, HGNC symbol, then the gene name
from Uniprot. Default: True
Returns
-------
mapped_stmts : list of :py:class:`indra.statements.Statement`
A list of statements given by mapping the agents from each
statement in the input list | [
"Return",
"a",
"new",
"list",
"of",
"statements",
"whose",
"agents",
"have",
"been",
"mapped"
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/preassembler/grounding_mapper.py#L270-L301 |
18,799 | sorgerlab/indra | indra/preassembler/grounding_mapper.py | GroundingMapper.rename_agents | def rename_agents(self, stmts):
"""Return a list of mapped statements with updated agent names.
Creates a new list of statements without modifying the original list.
The agents in a statement should be renamed if the grounding map has
updated their db_refs. If an agent contains a FamPlex grounding, the
FamPlex ID is used as a name. Otherwise if it contains a Uniprot ID,
an attempt is made to find the associated HGNC gene name. If one can
be found it is used as the agent name and the associated HGNC ID is
added as an entry to the db_refs. If neither a FamPlex ID or HGNC name
can be found, falls back to the original name.
Parameters
----------
stmts : list of :py:class:`indra.statements.Statement`
List of statements whose Agents need their names updated.
Returns
-------
mapped_stmts : list of :py:class:`indra.statements.Statement`
A new list of Statements with updated Agent names
"""
# Make a copy of the stmts
mapped_stmts = deepcopy(stmts)
# Iterate over the statements
for _, stmt in enumerate(mapped_stmts):
# Iterate over the agents
for agent in stmt.agent_list():
if agent is None:
continue
# If there's a FamPlex ID, prefer that for the name
if agent.db_refs.get('FPLX'):
agent.name = agent.db_refs.get('FPLX')
# Take a HGNC name from Uniprot next
elif agent.db_refs.get('UP'):
# Try for the gene name
gene_name = uniprot_client.get_gene_name(
agent.db_refs.get('UP'),
web_fallback=False)
if gene_name:
agent.name = gene_name
hgnc_id = hgnc_client.get_hgnc_id(gene_name)
if hgnc_id:
agent.db_refs['HGNC'] = hgnc_id
# Take the text string
#if agent.db_refs.get('TEXT'):
# agent.name = agent.db_refs.get('TEXT')
# If this fails, then we continue with no change
# Fall back to the text string
#elif agent.db_refs.get('TEXT'):
# agent.name = agent.db_refs.get('TEXT')
return mapped_stmts | python | def rename_agents(self, stmts):
# Make a copy of the stmts
mapped_stmts = deepcopy(stmts)
# Iterate over the statements
for _, stmt in enumerate(mapped_stmts):
# Iterate over the agents
for agent in stmt.agent_list():
if agent is None:
continue
# If there's a FamPlex ID, prefer that for the name
if agent.db_refs.get('FPLX'):
agent.name = agent.db_refs.get('FPLX')
# Take a HGNC name from Uniprot next
elif agent.db_refs.get('UP'):
# Try for the gene name
gene_name = uniprot_client.get_gene_name(
agent.db_refs.get('UP'),
web_fallback=False)
if gene_name:
agent.name = gene_name
hgnc_id = hgnc_client.get_hgnc_id(gene_name)
if hgnc_id:
agent.db_refs['HGNC'] = hgnc_id
# Take the text string
#if agent.db_refs.get('TEXT'):
# agent.name = agent.db_refs.get('TEXT')
# If this fails, then we continue with no change
# Fall back to the text string
#elif agent.db_refs.get('TEXT'):
# agent.name = agent.db_refs.get('TEXT')
return mapped_stmts | [
"def",
"rename_agents",
"(",
"self",
",",
"stmts",
")",
":",
"# Make a copy of the stmts",
"mapped_stmts",
"=",
"deepcopy",
"(",
"stmts",
")",
"# Iterate over the statements",
"for",
"_",
",",
"stmt",
"in",
"enumerate",
"(",
"mapped_stmts",
")",
":",
"# Iterate ov... | Return a list of mapped statements with updated agent names.
Creates a new list of statements without modifying the original list.
The agents in a statement should be renamed if the grounding map has
updated their db_refs. If an agent contains a FamPlex grounding, the
FamPlex ID is used as a name. Otherwise if it contains a Uniprot ID,
an attempt is made to find the associated HGNC gene name. If one can
be found it is used as the agent name and the associated HGNC ID is
added as an entry to the db_refs. If neither a FamPlex ID or HGNC name
can be found, falls back to the original name.
Parameters
----------
stmts : list of :py:class:`indra.statements.Statement`
List of statements whose Agents need their names updated.
Returns
-------
mapped_stmts : list of :py:class:`indra.statements.Statement`
A new list of Statements with updated Agent names | [
"Return",
"a",
"list",
"of",
"mapped",
"statements",
"with",
"updated",
"agent",
"names",
"."
] | 79a70415832c5702d7a820c7c9ccc8e25010124b | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/preassembler/grounding_mapper.py#L303-L355 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.