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
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
shmuelamar/cbox
cbox/cli.py
cmd
def cmd(f): """wrapper for easily exposing a function as a CLI command. including help message, arguments help and type. Example Usage: >>> import cbox >>> >>> @cbox.cmd >>> def hello(name: str): >>> '''greets a person by its name. >>> >>> :param name: the name of the person >>> ''' >>> print('hello {}!'.format(name)) """ @wraps(f) def wrapper(*args, **kwargs): return f(*args, **kwargs) setattr(wrapper, executors.EXECUTOR_ATTR, executors.CMD) return wrapper
python
def cmd(f): """wrapper for easily exposing a function as a CLI command. including help message, arguments help and type. Example Usage: >>> import cbox >>> >>> @cbox.cmd >>> def hello(name: str): >>> '''greets a person by its name. >>> >>> :param name: the name of the person >>> ''' >>> print('hello {}!'.format(name)) """ @wraps(f) def wrapper(*args, **kwargs): return f(*args, **kwargs) setattr(wrapper, executors.EXECUTOR_ATTR, executors.CMD) return wrapper
[ "def", "cmd", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "f", "(", "*", "args", ",", "*", "*", "kwargs", ")", "setattr", "(", "wrapper", ",", "executors", ...
wrapper for easily exposing a function as a CLI command. including help message, arguments help and type. Example Usage: >>> import cbox >>> >>> @cbox.cmd >>> def hello(name: str): >>> '''greets a person by its name. >>> >>> :param name: the name of the person >>> ''' >>> print('hello {}!'.format(name))
[ "wrapper", "for", "easily", "exposing", "a", "function", "as", "a", "CLI", "command", ".", "including", "help", "message", "arguments", "help", "and", "type", "." ]
2d0cda5b3f61a55e530251430bf3d460dcd3732e
https://github.com/shmuelamar/cbox/blob/2d0cda5b3f61a55e530251430bf3d460dcd3732e/cbox/cli.py#L60-L82
train
34,000
shmuelamar/cbox
cbox/cli.py
main
def main(func=None, argv=None, input_stream=stdin, output_stream=stdout, error_stream=stderr, exit=True): """runs a function as a command. runs a function as a command - reading input from `input_stream`, writing output into `output_stream` and providing arguments from `argv`. Example Usage: >>> import cbox >>> >>> @cbox.cmd >>> def hello(name: str): >>> print('hello {}!'.format(name)) >>> >>> if __name__ == '__main__': >>> cbox.main(hello) more examples on `README.md` :param callable func: the function to execute, must be decorated by `@cbox.cmd` or `@cbox.stream`. :param list[str] argv: command arguments (default `sys.argv`) :param input_stream: readable file-like object (default `stdin`) :param output_stream: writable file-like object (default `stdout`) :param error_stream: writable file-like object (default `stderr`) :param bool exit: if True, exits (i.e. `sys.exit(exitcode)`) with the `exitcode`, else returns the `exitcode`. the code is 0 if no errors, else 2. :return: the exit code if `exit` is False, else raises `SystemExit(code)` """ executor = executors.get_func_executor(func) exitcode = executor(func, argv, input_stream, output_stream, error_stream) if exit: sys.exit(exitcode) return exitcode
python
def main(func=None, argv=None, input_stream=stdin, output_stream=stdout, error_stream=stderr, exit=True): """runs a function as a command. runs a function as a command - reading input from `input_stream`, writing output into `output_stream` and providing arguments from `argv`. Example Usage: >>> import cbox >>> >>> @cbox.cmd >>> def hello(name: str): >>> print('hello {}!'.format(name)) >>> >>> if __name__ == '__main__': >>> cbox.main(hello) more examples on `README.md` :param callable func: the function to execute, must be decorated by `@cbox.cmd` or `@cbox.stream`. :param list[str] argv: command arguments (default `sys.argv`) :param input_stream: readable file-like object (default `stdin`) :param output_stream: writable file-like object (default `stdout`) :param error_stream: writable file-like object (default `stderr`) :param bool exit: if True, exits (i.e. `sys.exit(exitcode)`) with the `exitcode`, else returns the `exitcode`. the code is 0 if no errors, else 2. :return: the exit code if `exit` is False, else raises `SystemExit(code)` """ executor = executors.get_func_executor(func) exitcode = executor(func, argv, input_stream, output_stream, error_stream) if exit: sys.exit(exitcode) return exitcode
[ "def", "main", "(", "func", "=", "None", ",", "argv", "=", "None", ",", "input_stream", "=", "stdin", ",", "output_stream", "=", "stdout", ",", "error_stream", "=", "stderr", ",", "exit", "=", "True", ")", ":", "executor", "=", "executors", ".", "get_f...
runs a function as a command. runs a function as a command - reading input from `input_stream`, writing output into `output_stream` and providing arguments from `argv`. Example Usage: >>> import cbox >>> >>> @cbox.cmd >>> def hello(name: str): >>> print('hello {}!'.format(name)) >>> >>> if __name__ == '__main__': >>> cbox.main(hello) more examples on `README.md` :param callable func: the function to execute, must be decorated by `@cbox.cmd` or `@cbox.stream`. :param list[str] argv: command arguments (default `sys.argv`) :param input_stream: readable file-like object (default `stdin`) :param output_stream: writable file-like object (default `stdout`) :param error_stream: writable file-like object (default `stderr`) :param bool exit: if True, exits (i.e. `sys.exit(exitcode)`) with the `exitcode`, else returns the `exitcode`. the code is 0 if no errors, else 2. :return: the exit code if `exit` is False, else raises `SystemExit(code)`
[ "runs", "a", "function", "as", "a", "command", ".", "runs", "a", "function", "as", "a", "command", "-", "reading", "input", "from", "input_stream", "writing", "output", "into", "output_stream", "and", "providing", "arguments", "from", "argv", "." ]
2d0cda5b3f61a55e530251430bf3d460dcd3732e
https://github.com/shmuelamar/cbox/blob/2d0cda5b3f61a55e530251430bf3d460dcd3732e/cbox/cli.py#L85-L121
train
34,001
shmuelamar/cbox
cbox/cliparser.py
_parse_docstring
def _parse_docstring(docstring): """parses docstring into its help message and params""" params = {} if not docstring: return None, params try: help_msg = _DOCSTRING_REGEX.search(docstring).group() help_msg = _strip_lines(help_msg) except AttributeError: help_msg = None for param in _DOCSTRING_PARAM_REGEX.finditer(docstring): param_definition = param.group(1).rsplit(' ', 1) if len(param_definition) == 2: param_type, param_name = param_definition else: param_type = None param_name = param_definition[0] param_help = param.group(2).strip() params[param_name] = param_type, _strip_lines(param_help) return help_msg, params
python
def _parse_docstring(docstring): """parses docstring into its help message and params""" params = {} if not docstring: return None, params try: help_msg = _DOCSTRING_REGEX.search(docstring).group() help_msg = _strip_lines(help_msg) except AttributeError: help_msg = None for param in _DOCSTRING_PARAM_REGEX.finditer(docstring): param_definition = param.group(1).rsplit(' ', 1) if len(param_definition) == 2: param_type, param_name = param_definition else: param_type = None param_name = param_definition[0] param_help = param.group(2).strip() params[param_name] = param_type, _strip_lines(param_help) return help_msg, params
[ "def", "_parse_docstring", "(", "docstring", ")", ":", "params", "=", "{", "}", "if", "not", "docstring", ":", "return", "None", ",", "params", "try", ":", "help_msg", "=", "_DOCSTRING_REGEX", ".", "search", "(", "docstring", ")", ".", "group", "(", ")",...
parses docstring into its help message and params
[ "parses", "docstring", "into", "its", "help", "message", "and", "params" ]
2d0cda5b3f61a55e530251430bf3d460dcd3732e
https://github.com/shmuelamar/cbox/blob/2d0cda5b3f61a55e530251430bf3d460dcd3732e/cbox/cliparser.py#L87-L110
train
34,002
shmuelamar/cbox
cbox/utils.py
error2str
def error2str(e): """returns the formatted stacktrace of the exception `e`. :param BaseException e: an exception to format into str :rtype: str """ out = StringIO() traceback.print_exception(None, e, e.__traceback__, file=out) out.seek(0) return out.read()
python
def error2str(e): """returns the formatted stacktrace of the exception `e`. :param BaseException e: an exception to format into str :rtype: str """ out = StringIO() traceback.print_exception(None, e, e.__traceback__, file=out) out.seek(0) return out.read()
[ "def", "error2str", "(", "e", ")", ":", "out", "=", "StringIO", "(", ")", "traceback", ".", "print_exception", "(", "None", ",", "e", ",", "e", ".", "__traceback__", ",", "file", "=", "out", ")", "out", ".", "seek", "(", "0", ")", "return", "out", ...
returns the formatted stacktrace of the exception `e`. :param BaseException e: an exception to format into str :rtype: str
[ "returns", "the", "formatted", "stacktrace", "of", "the", "exception", "e", "." ]
2d0cda5b3f61a55e530251430bf3d460dcd3732e
https://github.com/shmuelamar/cbox/blob/2d0cda5b3f61a55e530251430bf3d460dcd3732e/cbox/utils.py#L7-L16
train
34,003
shmuelamar/cbox
cbox/concurrency.py
get_runner
def get_runner(worker_type, max_workers=None, workers_window=None): """returns a runner callable. :param str worker_type: one of `simple` or `thread`. :param int max_workers: max workers the runner can spawn in parallel. :param in workers_window: max number of jobs waiting to be done by the workers at any given time. :return: """ worker_func = _runners_mapping[worker_type] return partial( worker_func, max_workers=max_workers, workers_window=workers_window )
python
def get_runner(worker_type, max_workers=None, workers_window=None): """returns a runner callable. :param str worker_type: one of `simple` or `thread`. :param int max_workers: max workers the runner can spawn in parallel. :param in workers_window: max number of jobs waiting to be done by the workers at any given time. :return: """ worker_func = _runners_mapping[worker_type] return partial( worker_func, max_workers=max_workers, workers_window=workers_window )
[ "def", "get_runner", "(", "worker_type", ",", "max_workers", "=", "None", ",", "workers_window", "=", "None", ")", ":", "worker_func", "=", "_runners_mapping", "[", "worker_type", "]", "return", "partial", "(", "worker_func", ",", "max_workers", "=", "max_worker...
returns a runner callable. :param str worker_type: one of `simple` or `thread`. :param int max_workers: max workers the runner can spawn in parallel. :param in workers_window: max number of jobs waiting to be done by the workers at any given time. :return:
[ "returns", "a", "runner", "callable", "." ]
2d0cda5b3f61a55e530251430bf3d460dcd3732e
https://github.com/shmuelamar/cbox/blob/2d0cda5b3f61a55e530251430bf3d460dcd3732e/cbox/concurrency.py#L21-L33
train
34,004
shmuelamar/cbox
cbox/__main__.py
get_inline_func
def get_inline_func(inline_str, modules=None, **stream_kwargs): """returns a function decorated by `cbox.stream` decorator. :param str inline_str: the inline function to execute, can use `s` - local variable as the input line/char/raw (according to `input_type` param). :param str modules: comma separated list of modules to import before running the inline function. :param dict stream_kwargs: optional arguments to `cbox.stream` decorator :rtype: callable """ if not _is_compilable(inline_str): raise ValueError( 'cannot compile the inline expression - "%s"' % inline_str ) inline_globals = _import_inline_modules(modules) func = _inline2func(inline_str, inline_globals, **stream_kwargs) return func
python
def get_inline_func(inline_str, modules=None, **stream_kwargs): """returns a function decorated by `cbox.stream` decorator. :param str inline_str: the inline function to execute, can use `s` - local variable as the input line/char/raw (according to `input_type` param). :param str modules: comma separated list of modules to import before running the inline function. :param dict stream_kwargs: optional arguments to `cbox.stream` decorator :rtype: callable """ if not _is_compilable(inline_str): raise ValueError( 'cannot compile the inline expression - "%s"' % inline_str ) inline_globals = _import_inline_modules(modules) func = _inline2func(inline_str, inline_globals, **stream_kwargs) return func
[ "def", "get_inline_func", "(", "inline_str", ",", "modules", "=", "None", ",", "*", "*", "stream_kwargs", ")", ":", "if", "not", "_is_compilable", "(", "inline_str", ")", ":", "raise", "ValueError", "(", "'cannot compile the inline expression - \"%s\"'", "%", "inl...
returns a function decorated by `cbox.stream` decorator. :param str inline_str: the inline function to execute, can use `s` - local variable as the input line/char/raw (according to `input_type` param). :param str modules: comma separated list of modules to import before running the inline function. :param dict stream_kwargs: optional arguments to `cbox.stream` decorator :rtype: callable
[ "returns", "a", "function", "decorated", "by", "cbox", ".", "stream", "decorator", "." ]
2d0cda5b3f61a55e530251430bf3d460dcd3732e
https://github.com/shmuelamar/cbox/blob/2d0cda5b3f61a55e530251430bf3d460dcd3732e/cbox/__main__.py#L77-L95
train
34,005
rm-hull/OPi.GPIO
OPi/GPIO.py
setmode
def setmode(mode): """ You must call this method prior to using all other calls. :param mode: the mode, one of :py:attr:`GPIO.BOARD`, :py:attr:`GPIO.BCM`, :py:attr:`GPIO.SUNXI`, or a `dict` or `object` representing a custom pin mapping. """ if hasattr(mode, '__getitem__'): set_custom_pin_mappings(mode) mode = CUSTOM assert mode in [BCM, BOARD, SUNXI, CUSTOM] global _mode _mode = mode
python
def setmode(mode): """ You must call this method prior to using all other calls. :param mode: the mode, one of :py:attr:`GPIO.BOARD`, :py:attr:`GPIO.BCM`, :py:attr:`GPIO.SUNXI`, or a `dict` or `object` representing a custom pin mapping. """ if hasattr(mode, '__getitem__'): set_custom_pin_mappings(mode) mode = CUSTOM assert mode in [BCM, BOARD, SUNXI, CUSTOM] global _mode _mode = mode
[ "def", "setmode", "(", "mode", ")", ":", "if", "hasattr", "(", "mode", ",", "'__getitem__'", ")", ":", "set_custom_pin_mappings", "(", "mode", ")", "mode", "=", "CUSTOM", "assert", "mode", "in", "[", "BCM", ",", "BOARD", ",", "SUNXI", ",", "CUSTOM", "]...
You must call this method prior to using all other calls. :param mode: the mode, one of :py:attr:`GPIO.BOARD`, :py:attr:`GPIO.BCM`, :py:attr:`GPIO.SUNXI`, or a `dict` or `object` representing a custom pin mapping.
[ "You", "must", "call", "this", "method", "prior", "to", "using", "all", "other", "calls", "." ]
d151885eb0f0fc25d4a86266eefebc105700f3fd
https://github.com/rm-hull/OPi.GPIO/blob/d151885eb0f0fc25d4a86266eefebc105700f3fd/OPi/GPIO.py#L276-L290
train
34,006
rm-hull/OPi.GPIO
OPi/GPIO.py
setup
def setup(channel, direction, initial=None, pull_up_down=None): """ You need to set up every channel you are using as an input or an output. :param channel: the channel based on the numbering system you have specified (:py:attr:`GPIO.BOARD`, :py:attr:`GPIO.BCM` or :py:attr:`GPIO.SUNXI`). :param direction: whether to treat the GPIO pin as input or output (use only :py:attr:`GPIO.IN` or :py:attr:`GPIO.OUT`). :param initial: (optional) When supplied and setting up an output pin, resets the pin to the value given (can be :py:attr:`0` / :py:attr:`GPIO.LOW` / :py:attr:`False` or :py:attr:`1` / :py:attr:`GPIO.HIGH` / :py:attr:`True`). :param pull_up_down: (optional) When supplied and setting up an input pin, configures the pin to 3.3V (pull-up) or 0V (pull-down) depending on the value given (can be :py:attr:`GPIO.PUD_OFF` / :py:attr:`GPIO.PUD_UP` / :py:attr:`GPIO.PUD_DOWN`) To configure a channel as an input: .. code:: python GPIO.setup(channel, GPIO.IN) To set up a channel as an output: .. code:: python GPIO.setup(channel, GPIO.OUT) You can also specify an initial value for your output channel: .. code:: python GPIO.setup(channel, GPIO.OUT, initial=GPIO.HIGH) **Setup more than one channel:** You can set up more than one channel per call. For example: .. code:: python chan_list = [11,12] # add as many channels as you want! # you can tuples instead i.e.: # chan_list = (11,12) GPIO.setup(chan_list, GPIO.OUT) """ if _mode is None: raise RuntimeError("Mode has not been set") if pull_up_down is not None: if _gpio_warnings: warnings.warn("Pull up/down setting are not (yet) fully supported, continuing anyway. Use GPIO.setwarnings(False) to disable warnings.", stacklevel=2) if isinstance(channel, list): for ch in channel: setup(ch, direction, initial) else: if channel in _exports: raise RuntimeError("Channel {0} is already configured".format(channel)) pin = get_gpio_pin(_mode, channel) try: sysfs.export(pin) except (OSError, IOError) as e: if e.errno == 16: # Device or resource busy if _gpio_warnings: warnings.warn("Channel {0} is already in use, continuing anyway. Use GPIO.setwarnings(False) to disable warnings.".format(channel), stacklevel=2) sysfs.unexport(pin) sysfs.export(pin) else: raise e sysfs.direction(pin, direction) _exports[channel] = direction if direction == OUT and initial is not None: sysfs.output(pin, initial)
python
def setup(channel, direction, initial=None, pull_up_down=None): """ You need to set up every channel you are using as an input or an output. :param channel: the channel based on the numbering system you have specified (:py:attr:`GPIO.BOARD`, :py:attr:`GPIO.BCM` or :py:attr:`GPIO.SUNXI`). :param direction: whether to treat the GPIO pin as input or output (use only :py:attr:`GPIO.IN` or :py:attr:`GPIO.OUT`). :param initial: (optional) When supplied and setting up an output pin, resets the pin to the value given (can be :py:attr:`0` / :py:attr:`GPIO.LOW` / :py:attr:`False` or :py:attr:`1` / :py:attr:`GPIO.HIGH` / :py:attr:`True`). :param pull_up_down: (optional) When supplied and setting up an input pin, configures the pin to 3.3V (pull-up) or 0V (pull-down) depending on the value given (can be :py:attr:`GPIO.PUD_OFF` / :py:attr:`GPIO.PUD_UP` / :py:attr:`GPIO.PUD_DOWN`) To configure a channel as an input: .. code:: python GPIO.setup(channel, GPIO.IN) To set up a channel as an output: .. code:: python GPIO.setup(channel, GPIO.OUT) You can also specify an initial value for your output channel: .. code:: python GPIO.setup(channel, GPIO.OUT, initial=GPIO.HIGH) **Setup more than one channel:** You can set up more than one channel per call. For example: .. code:: python chan_list = [11,12] # add as many channels as you want! # you can tuples instead i.e.: # chan_list = (11,12) GPIO.setup(chan_list, GPIO.OUT) """ if _mode is None: raise RuntimeError("Mode has not been set") if pull_up_down is not None: if _gpio_warnings: warnings.warn("Pull up/down setting are not (yet) fully supported, continuing anyway. Use GPIO.setwarnings(False) to disable warnings.", stacklevel=2) if isinstance(channel, list): for ch in channel: setup(ch, direction, initial) else: if channel in _exports: raise RuntimeError("Channel {0} is already configured".format(channel)) pin = get_gpio_pin(_mode, channel) try: sysfs.export(pin) except (OSError, IOError) as e: if e.errno == 16: # Device or resource busy if _gpio_warnings: warnings.warn("Channel {0} is already in use, continuing anyway. Use GPIO.setwarnings(False) to disable warnings.".format(channel), stacklevel=2) sysfs.unexport(pin) sysfs.export(pin) else: raise e sysfs.direction(pin, direction) _exports[channel] = direction if direction == OUT and initial is not None: sysfs.output(pin, initial)
[ "def", "setup", "(", "channel", ",", "direction", ",", "initial", "=", "None", ",", "pull_up_down", "=", "None", ")", ":", "if", "_mode", "is", "None", ":", "raise", "RuntimeError", "(", "\"Mode has not been set\"", ")", "if", "pull_up_down", "is", "not", ...
You need to set up every channel you are using as an input or an output. :param channel: the channel based on the numbering system you have specified (:py:attr:`GPIO.BOARD`, :py:attr:`GPIO.BCM` or :py:attr:`GPIO.SUNXI`). :param direction: whether to treat the GPIO pin as input or output (use only :py:attr:`GPIO.IN` or :py:attr:`GPIO.OUT`). :param initial: (optional) When supplied and setting up an output pin, resets the pin to the value given (can be :py:attr:`0` / :py:attr:`GPIO.LOW` / :py:attr:`False` or :py:attr:`1` / :py:attr:`GPIO.HIGH` / :py:attr:`True`). :param pull_up_down: (optional) When supplied and setting up an input pin, configures the pin to 3.3V (pull-up) or 0V (pull-down) depending on the value given (can be :py:attr:`GPIO.PUD_OFF` / :py:attr:`GPIO.PUD_UP` / :py:attr:`GPIO.PUD_DOWN`) To configure a channel as an input: .. code:: python GPIO.setup(channel, GPIO.IN) To set up a channel as an output: .. code:: python GPIO.setup(channel, GPIO.OUT) You can also specify an initial value for your output channel: .. code:: python GPIO.setup(channel, GPIO.OUT, initial=GPIO.HIGH) **Setup more than one channel:** You can set up more than one channel per call. For example: .. code:: python chan_list = [11,12] # add as many channels as you want! # you can tuples instead i.e.: # chan_list = (11,12) GPIO.setup(chan_list, GPIO.OUT)
[ "You", "need", "to", "set", "up", "every", "channel", "you", "are", "using", "as", "an", "input", "or", "an", "output", "." ]
d151885eb0f0fc25d4a86266eefebc105700f3fd
https://github.com/rm-hull/OPi.GPIO/blob/d151885eb0f0fc25d4a86266eefebc105700f3fd/OPi/GPIO.py#L298-L370
train
34,007
rm-hull/OPi.GPIO
OPi/GPIO.py
input
def input(channel): """ Read the value of a GPIO pin. :param channel: the channel based on the numbering system you have specified (:py:attr:`GPIO.BOARD`, :py:attr:`GPIO.BCM` or :py:attr:`GPIO.SUNXI`). :returns: This will return either :py:attr:`0` / :py:attr:`GPIO.LOW` / :py:attr:`False` or :py:attr:`1` / :py:attr:`GPIO.HIGH` / :py:attr:`True`). """ _check_configured(channel) # Can read from a pin configured for output pin = get_gpio_pin(_mode, channel) return sysfs.input(pin)
python
def input(channel): """ Read the value of a GPIO pin. :param channel: the channel based on the numbering system you have specified (:py:attr:`GPIO.BOARD`, :py:attr:`GPIO.BCM` or :py:attr:`GPIO.SUNXI`). :returns: This will return either :py:attr:`0` / :py:attr:`GPIO.LOW` / :py:attr:`False` or :py:attr:`1` / :py:attr:`GPIO.HIGH` / :py:attr:`True`). """ _check_configured(channel) # Can read from a pin configured for output pin = get_gpio_pin(_mode, channel) return sysfs.input(pin)
[ "def", "input", "(", "channel", ")", ":", "_check_configured", "(", "channel", ")", "# Can read from a pin configured for output", "pin", "=", "get_gpio_pin", "(", "_mode", ",", "channel", ")", "return", "sysfs", ".", "input", "(", "pin", ")" ]
Read the value of a GPIO pin. :param channel: the channel based on the numbering system you have specified (:py:attr:`GPIO.BOARD`, :py:attr:`GPIO.BCM` or :py:attr:`GPIO.SUNXI`). :returns: This will return either :py:attr:`0` / :py:attr:`GPIO.LOW` / :py:attr:`False` or :py:attr:`1` / :py:attr:`GPIO.HIGH` / :py:attr:`True`).
[ "Read", "the", "value", "of", "a", "GPIO", "pin", "." ]
d151885eb0f0fc25d4a86266eefebc105700f3fd
https://github.com/rm-hull/OPi.GPIO/blob/d151885eb0f0fc25d4a86266eefebc105700f3fd/OPi/GPIO.py#L373-L384
train
34,008
rm-hull/OPi.GPIO
OPi/GPIO.py
output
def output(channel, state): """ Set the output state of a GPIO pin. :param channel: the channel based on the numbering system you have specified (:py:attr:`GPIO.BOARD`, :py:attr:`GPIO.BCM` or :py:attr:`GPIO.SUNXI`). :param state: can be :py:attr:`0` / :py:attr:`GPIO.LOW` / :py:attr:`False` or :py:attr:`1` / :py:attr:`GPIO.HIGH` / :py:attr:`True`. **Output to several channels:** You can output to many channels in the same call. For example: .. code:: python chan_list = [11,12] # also works with tuples GPIO.output(chan_list, GPIO.LOW) # sets all to GPIO.LOW GPIO.output(chan_list, (GPIO.HIGH, GPIO.LOW)) # sets first HIGH and second LOW """ if isinstance(channel, list): for ch in channel: output(ch, state) else: _check_configured(channel, direction=OUT) pin = get_gpio_pin(_mode, channel) return sysfs.output(pin, state)
python
def output(channel, state): """ Set the output state of a GPIO pin. :param channel: the channel based on the numbering system you have specified (:py:attr:`GPIO.BOARD`, :py:attr:`GPIO.BCM` or :py:attr:`GPIO.SUNXI`). :param state: can be :py:attr:`0` / :py:attr:`GPIO.LOW` / :py:attr:`False` or :py:attr:`1` / :py:attr:`GPIO.HIGH` / :py:attr:`True`. **Output to several channels:** You can output to many channels in the same call. For example: .. code:: python chan_list = [11,12] # also works with tuples GPIO.output(chan_list, GPIO.LOW) # sets all to GPIO.LOW GPIO.output(chan_list, (GPIO.HIGH, GPIO.LOW)) # sets first HIGH and second LOW """ if isinstance(channel, list): for ch in channel: output(ch, state) else: _check_configured(channel, direction=OUT) pin = get_gpio_pin(_mode, channel) return sysfs.output(pin, state)
[ "def", "output", "(", "channel", ",", "state", ")", ":", "if", "isinstance", "(", "channel", ",", "list", ")", ":", "for", "ch", "in", "channel", ":", "output", "(", "ch", ",", "state", ")", "else", ":", "_check_configured", "(", "channel", ",", "dir...
Set the output state of a GPIO pin. :param channel: the channel based on the numbering system you have specified (:py:attr:`GPIO.BOARD`, :py:attr:`GPIO.BCM` or :py:attr:`GPIO.SUNXI`). :param state: can be :py:attr:`0` / :py:attr:`GPIO.LOW` / :py:attr:`False` or :py:attr:`1` / :py:attr:`GPIO.HIGH` / :py:attr:`True`. **Output to several channels:** You can output to many channels in the same call. For example: .. code:: python chan_list = [11,12] # also works with tuples GPIO.output(chan_list, GPIO.LOW) # sets all to GPIO.LOW GPIO.output(chan_list, (GPIO.HIGH, GPIO.LOW)) # sets first HIGH and second LOW
[ "Set", "the", "output", "state", "of", "a", "GPIO", "pin", "." ]
d151885eb0f0fc25d4a86266eefebc105700f3fd
https://github.com/rm-hull/OPi.GPIO/blob/d151885eb0f0fc25d4a86266eefebc105700f3fd/OPi/GPIO.py#L387-L411
train
34,009
rm-hull/OPi.GPIO
OPi/GPIO.py
wait_for_edge
def wait_for_edge(channel, trigger, timeout=-1): """ This function is designed to block execution of your program until an edge is detected. :param channel: the channel based on the numbering system you have specified (:py:attr:`GPIO.BOARD`, :py:attr:`GPIO.BCM` or :py:attr:`GPIO.SUNXI`). :param trigger: The event to detect, one of: :py:attr:`GPIO.RISING`, :py:attr:`GPIO.FALLING` or :py:attr:`GPIO.BOTH`. :param timeout: (optional) TODO In other words, the polling example above that waits for a button press could be rewritten as: .. code:: python GPIO.wait_for_edge(channel, GPIO.RISING) Note that you can detect edges of type :py:attr:`GPIO.RISING`, :py:attr`GPIO.FALLING` or :py:attr:`GPIO.BOTH`. The advantage of doing it this way is that it uses a negligible amount of CPU, so there is plenty left for other tasks. If you only want to wait for a certain length of time, you can use the timeout parameter: .. code:: python # wait for up to 5 seconds for a rising edge (timeout is in milliseconds) channel = GPIO.wait_for_edge(channel, GPIO_RISING, timeout=5000) if channel is None: print('Timeout occurred') else: print('Edge detected on channel', channel) """ _check_configured(channel, direction=IN) pin = get_gpio_pin(_mode, channel) if event.blocking_wait_for_edge(pin, trigger, timeout) is not None: return channel
python
def wait_for_edge(channel, trigger, timeout=-1): """ This function is designed to block execution of your program until an edge is detected. :param channel: the channel based on the numbering system you have specified (:py:attr:`GPIO.BOARD`, :py:attr:`GPIO.BCM` or :py:attr:`GPIO.SUNXI`). :param trigger: The event to detect, one of: :py:attr:`GPIO.RISING`, :py:attr:`GPIO.FALLING` or :py:attr:`GPIO.BOTH`. :param timeout: (optional) TODO In other words, the polling example above that waits for a button press could be rewritten as: .. code:: python GPIO.wait_for_edge(channel, GPIO.RISING) Note that you can detect edges of type :py:attr:`GPIO.RISING`, :py:attr`GPIO.FALLING` or :py:attr:`GPIO.BOTH`. The advantage of doing it this way is that it uses a negligible amount of CPU, so there is plenty left for other tasks. If you only want to wait for a certain length of time, you can use the timeout parameter: .. code:: python # wait for up to 5 seconds for a rising edge (timeout is in milliseconds) channel = GPIO.wait_for_edge(channel, GPIO_RISING, timeout=5000) if channel is None: print('Timeout occurred') else: print('Edge detected on channel', channel) """ _check_configured(channel, direction=IN) pin = get_gpio_pin(_mode, channel) if event.blocking_wait_for_edge(pin, trigger, timeout) is not None: return channel
[ "def", "wait_for_edge", "(", "channel", ",", "trigger", ",", "timeout", "=", "-", "1", ")", ":", "_check_configured", "(", "channel", ",", "direction", "=", "IN", ")", "pin", "=", "get_gpio_pin", "(", "_mode", ",", "channel", ")", "if", "event", ".", "...
This function is designed to block execution of your program until an edge is detected. :param channel: the channel based on the numbering system you have specified (:py:attr:`GPIO.BOARD`, :py:attr:`GPIO.BCM` or :py:attr:`GPIO.SUNXI`). :param trigger: The event to detect, one of: :py:attr:`GPIO.RISING`, :py:attr:`GPIO.FALLING` or :py:attr:`GPIO.BOTH`. :param timeout: (optional) TODO In other words, the polling example above that waits for a button press could be rewritten as: .. code:: python GPIO.wait_for_edge(channel, GPIO.RISING) Note that you can detect edges of type :py:attr:`GPIO.RISING`, :py:attr`GPIO.FALLING` or :py:attr:`GPIO.BOTH`. The advantage of doing it this way is that it uses a negligible amount of CPU, so there is plenty left for other tasks. If you only want to wait for a certain length of time, you can use the timeout parameter: .. code:: python # wait for up to 5 seconds for a rising edge (timeout is in milliseconds) channel = GPIO.wait_for_edge(channel, GPIO_RISING, timeout=5000) if channel is None: print('Timeout occurred') else: print('Edge detected on channel', channel)
[ "This", "function", "is", "designed", "to", "block", "execution", "of", "your", "program", "until", "an", "edge", "is", "detected", "." ]
d151885eb0f0fc25d4a86266eefebc105700f3fd
https://github.com/rm-hull/OPi.GPIO/blob/d151885eb0f0fc25d4a86266eefebc105700f3fd/OPi/GPIO.py#L414-L452
train
34,010
wq/django-swappable-models
swapper/__init__.py
is_swapped
def is_swapped(app_label, model): """ Returns the value of the swapped setting, or False if the model hasn't been swapped. """ default_model = join(app_label, model) setting = swappable_setting(app_label, model) value = getattr(settings, setting, default_model) if value != default_model: return value else: return False
python
def is_swapped(app_label, model): """ Returns the value of the swapped setting, or False if the model hasn't been swapped. """ default_model = join(app_label, model) setting = swappable_setting(app_label, model) value = getattr(settings, setting, default_model) if value != default_model: return value else: return False
[ "def", "is_swapped", "(", "app_label", ",", "model", ")", ":", "default_model", "=", "join", "(", "app_label", ",", "model", ")", "setting", "=", "swappable_setting", "(", "app_label", ",", "model", ")", "value", "=", "getattr", "(", "settings", ",", "sett...
Returns the value of the swapped setting, or False if the model hasn't been swapped.
[ "Returns", "the", "value", "of", "the", "swapped", "setting", "or", "False", "if", "the", "model", "hasn", "t", "been", "swapped", "." ]
2602265f2c972e95766d2100b84261ca761bccff
https://github.com/wq/django-swappable-models/blob/2602265f2c972e95766d2100b84261ca761bccff/swapper/__init__.py#L25-L36
train
34,011
wq/django-swappable-models
swapper/__init__.py
get_model_names
def get_model_names(app_label, models): """ Map model names to their swapped equivalents for the given app """ return dict( (model, get_model_name(app_label, model)) for model in models )
python
def get_model_names(app_label, models): """ Map model names to their swapped equivalents for the given app """ return dict( (model, get_model_name(app_label, model)) for model in models )
[ "def", "get_model_names", "(", "app_label", ",", "models", ")", ":", "return", "dict", "(", "(", "model", ",", "get_model_name", "(", "app_label", ",", "model", ")", ")", "for", "model", "in", "models", ")" ]
Map model names to their swapped equivalents for the given app
[ "Map", "model", "names", "to", "their", "swapped", "equivalents", "for", "the", "given", "app" ]
2602265f2c972e95766d2100b84261ca761bccff
https://github.com/wq/django-swappable-models/blob/2602265f2c972e95766d2100b84261ca761bccff/swapper/__init__.py#L56-L63
train
34,012
grimen/python-attributedict
attributedict/collections.py
AttributeDict.update
def update(self, entries = {}, *args, **kwargs): """ Update dictionary. @example: object.update({'foo': {'bar': 1}}) """ if isinstance(entries, dict): entries = self._reject_reserved_keys(entries) for key, value in dict(entries, *args, **kwargs).items(): if isinstance(value, dict): self.__dict__[key] = AttributeDict(value) else: self.__dict__[key] = value self._refresh()
python
def update(self, entries = {}, *args, **kwargs): """ Update dictionary. @example: object.update({'foo': {'bar': 1}}) """ if isinstance(entries, dict): entries = self._reject_reserved_keys(entries) for key, value in dict(entries, *args, **kwargs).items(): if isinstance(value, dict): self.__dict__[key] = AttributeDict(value) else: self.__dict__[key] = value self._refresh()
[ "def", "update", "(", "self", ",", "entries", "=", "{", "}", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "entries", ",", "dict", ")", ":", "entries", "=", "self", ".", "_reject_reserved_keys", "(", "entries", ")", ...
Update dictionary. @example: object.update({'foo': {'bar': 1}})
[ "Update", "dictionary", "." ]
01a0f293239642ce4da3fc694914bd13829fa887
https://github.com/grimen/python-attributedict/blob/01a0f293239642ce4da3fc694914bd13829fa887/attributedict/collections.py#L93-L111
train
34,013
elyase/geotext
geotext/geotext.py
read_table
def read_table(filename, usecols=(0, 1), sep='\t', comment='#', encoding='utf-8', skip=0): """Parse data files from the data directory Parameters ---------- filename: string Full path to file usecols: list, default [0, 1] A list of two elements representing the columns to be parsed into a dictionary. The first element will be used as keys and the second as values. Defaults to the first two columns of `filename`. sep : string, default '\t' Field delimiter. comment : str, default '#' Indicates remainder of line should not be parsed. If found at the beginning of a line, the line will be ignored altogether. This parameter must be a single character. encoding : string, default 'utf-8' Encoding to use for UTF when reading/writing (ex. `utf-8`) skip: int, default 0 Number of lines to skip at the beginning of the file Returns ------- A dictionary with the same length as the number of lines in `filename` """ with io.open(filename, 'r', encoding=encoding) as f: # skip initial lines for _ in range(skip): next(f) # filter comment lines lines = (line for line in f if not line.startswith(comment)) d = dict() for line in lines: columns = line.split(sep) key = columns[usecols[0]].lower() value = columns[usecols[1]].rstrip('\n') d[key] = value return d
python
def read_table(filename, usecols=(0, 1), sep='\t', comment='#', encoding='utf-8', skip=0): """Parse data files from the data directory Parameters ---------- filename: string Full path to file usecols: list, default [0, 1] A list of two elements representing the columns to be parsed into a dictionary. The first element will be used as keys and the second as values. Defaults to the first two columns of `filename`. sep : string, default '\t' Field delimiter. comment : str, default '#' Indicates remainder of line should not be parsed. If found at the beginning of a line, the line will be ignored altogether. This parameter must be a single character. encoding : string, default 'utf-8' Encoding to use for UTF when reading/writing (ex. `utf-8`) skip: int, default 0 Number of lines to skip at the beginning of the file Returns ------- A dictionary with the same length as the number of lines in `filename` """ with io.open(filename, 'r', encoding=encoding) as f: # skip initial lines for _ in range(skip): next(f) # filter comment lines lines = (line for line in f if not line.startswith(comment)) d = dict() for line in lines: columns = line.split(sep) key = columns[usecols[0]].lower() value = columns[usecols[1]].rstrip('\n') d[key] = value return d
[ "def", "read_table", "(", "filename", ",", "usecols", "=", "(", "0", ",", "1", ")", ",", "sep", "=", "'\\t'", ",", "comment", "=", "'#'", ",", "encoding", "=", "'utf-8'", ",", "skip", "=", "0", ")", ":", "with", "io", ".", "open", "(", "filename"...
Parse data files from the data directory Parameters ---------- filename: string Full path to file usecols: list, default [0, 1] A list of two elements representing the columns to be parsed into a dictionary. The first element will be used as keys and the second as values. Defaults to the first two columns of `filename`. sep : string, default '\t' Field delimiter. comment : str, default '#' Indicates remainder of line should not be parsed. If found at the beginning of a line, the line will be ignored altogether. This parameter must be a single character. encoding : string, default 'utf-8' Encoding to use for UTF when reading/writing (ex. `utf-8`) skip: int, default 0 Number of lines to skip at the beginning of the file Returns ------- A dictionary with the same length as the number of lines in `filename`
[ "Parse", "data", "files", "from", "the", "data", "directory" ]
21a8a7f5eebea40f270beef9ede4d9a57e3c81c3
https://github.com/elyase/geotext/blob/21a8a7f5eebea40f270beef9ede4d9a57e3c81c3/geotext/geotext.py#L15-L60
train
34,014
elyase/geotext
geotext/geotext.py
build_index
def build_index(): """Load information from the data directory Returns ------- A namedtuple with three fields: nationalities cities countries """ nationalities = read_table(get_data_path('nationalities.txt'), sep=':') # parse http://download.geonames.org/export/dump/countryInfo.txt countries = read_table( get_data_path('countryInfo.txt'), usecols=[4, 0], skip=1) # parse http://download.geonames.org/export/dump/cities15000.zip cities = read_table(get_data_path('cities15000.txt'), usecols=[1, 8]) # load and apply city patches city_patches = read_table(get_data_path('citypatches.txt')) cities.update(city_patches) Index = namedtuple('Index', 'nationalities cities countries') return Index(nationalities, cities, countries)
python
def build_index(): """Load information from the data directory Returns ------- A namedtuple with three fields: nationalities cities countries """ nationalities = read_table(get_data_path('nationalities.txt'), sep=':') # parse http://download.geonames.org/export/dump/countryInfo.txt countries = read_table( get_data_path('countryInfo.txt'), usecols=[4, 0], skip=1) # parse http://download.geonames.org/export/dump/cities15000.zip cities = read_table(get_data_path('cities15000.txt'), usecols=[1, 8]) # load and apply city patches city_patches = read_table(get_data_path('citypatches.txt')) cities.update(city_patches) Index = namedtuple('Index', 'nationalities cities countries') return Index(nationalities, cities, countries)
[ "def", "build_index", "(", ")", ":", "nationalities", "=", "read_table", "(", "get_data_path", "(", "'nationalities.txt'", ")", ",", "sep", "=", "':'", ")", "# parse http://download.geonames.org/export/dump/countryInfo.txt", "countries", "=", "read_table", "(", "get_dat...
Load information from the data directory Returns ------- A namedtuple with three fields: nationalities cities countries
[ "Load", "information", "from", "the", "data", "directory" ]
21a8a7f5eebea40f270beef9ede4d9a57e3c81c3
https://github.com/elyase/geotext/blob/21a8a7f5eebea40f270beef9ede4d9a57e3c81c3/geotext/geotext.py#L63-L85
train
34,015
almarklein/pyelastix
pyelastix.py
_find_executables
def _find_executables(name): """ Try to find an executable. """ exe_name = name + '.exe' * sys.platform.startswith('win') env_path = os.environ.get(name.upper()+ '_PATH', '') possible_locations = [] def add(*dirs): for d in dirs: if d and d not in possible_locations and os.path.isdir(d): possible_locations.append(d) # Get list of possible locations add(env_path) try: add(os.path.dirname(os.path.abspath(__file__))) except NameError: # __file__ may not exist pass add(os.path.dirname(sys.executable)) add(os.path.expanduser('~')) # Platform specific possible locations if sys.platform.startswith('win'): add('c:\\program files', os.environ.get('PROGRAMFILES'), 'c:\\program files (x86)', os.environ.get('PROGRAMFILES(x86)')) else: possible_locations.extend(['/usr/bin','/usr/local/bin','/opt/local/bin']) def do_check_version(exe): try: return subprocess.check_output([exe, '--version']).decode().strip() except Exception: # print('not a good exe', exe) return False # If env path is the exe itself ... if os.path.isfile(env_path): ver = do_check_version(env_path) if ver: return env_path, ver # First try to find obvious locations for d in possible_locations: for exe in [os.path.join(d, exe_name), os.path.join(d, name, exe_name)]: if os.path.isfile(exe): ver = do_check_version(exe) if ver: return exe, ver # Maybe the exe is on the PATH ver = do_check_version(exe_name) if ver: return exe_name, ver # Try harder for d in possible_locations: for sub in reversed(sorted(os.listdir(d))): if sub.startswith(name): exe = os.path.join(d, sub, exe_name) if os.path.isfile(exe): ver = do_check_version(exe) if ver: return exe, ver return None, None
python
def _find_executables(name): """ Try to find an executable. """ exe_name = name + '.exe' * sys.platform.startswith('win') env_path = os.environ.get(name.upper()+ '_PATH', '') possible_locations = [] def add(*dirs): for d in dirs: if d and d not in possible_locations and os.path.isdir(d): possible_locations.append(d) # Get list of possible locations add(env_path) try: add(os.path.dirname(os.path.abspath(__file__))) except NameError: # __file__ may not exist pass add(os.path.dirname(sys.executable)) add(os.path.expanduser('~')) # Platform specific possible locations if sys.platform.startswith('win'): add('c:\\program files', os.environ.get('PROGRAMFILES'), 'c:\\program files (x86)', os.environ.get('PROGRAMFILES(x86)')) else: possible_locations.extend(['/usr/bin','/usr/local/bin','/opt/local/bin']) def do_check_version(exe): try: return subprocess.check_output([exe, '--version']).decode().strip() except Exception: # print('not a good exe', exe) return False # If env path is the exe itself ... if os.path.isfile(env_path): ver = do_check_version(env_path) if ver: return env_path, ver # First try to find obvious locations for d in possible_locations: for exe in [os.path.join(d, exe_name), os.path.join(d, name, exe_name)]: if os.path.isfile(exe): ver = do_check_version(exe) if ver: return exe, ver # Maybe the exe is on the PATH ver = do_check_version(exe_name) if ver: return exe_name, ver # Try harder for d in possible_locations: for sub in reversed(sorted(os.listdir(d))): if sub.startswith(name): exe = os.path.join(d, sub, exe_name) if os.path.isfile(exe): ver = do_check_version(exe) if ver: return exe, ver return None, None
[ "def", "_find_executables", "(", "name", ")", ":", "exe_name", "=", "name", "+", "'.exe'", "*", "sys", ".", "platform", ".", "startswith", "(", "'win'", ")", "env_path", "=", "os", ".", "environ", ".", "get", "(", "name", ".", "upper", "(", ")", "+",...
Try to find an executable.
[ "Try", "to", "find", "an", "executable", "." ]
971a677ce9a3ef8eb0b95ae393db8e2506d2f8a4
https://github.com/almarklein/pyelastix/blob/971a677ce9a3ef8eb0b95ae393db8e2506d2f8a4/pyelastix.py#L76-L140
train
34,016
almarklein/pyelastix
pyelastix.py
get_elastix_exes
def get_elastix_exes(): """ Get the executables for elastix and transformix. Raises an error if they cannot be found. """ if EXES: if EXES[0]: return EXES else: raise RuntimeError('No Elastix executable.') # Find exe elastix, ver = _find_executables('elastix') if elastix: base, ext = os.path.splitext(elastix) base = os.path.dirname(base) transformix = os.path.join(base, 'transformix' + ext) EXES.extend([elastix, transformix]) print('Found %s in %r' % (ver, elastix)) return EXES else: raise RuntimeError('Could not find Elastix executable. Download ' 'Elastix from http://elastix.isi.uu.nl/. Pyelastix ' 'looks for the exe in a series of common locations. ' 'Set ELASTIX_PATH if necessary.')
python
def get_elastix_exes(): """ Get the executables for elastix and transformix. Raises an error if they cannot be found. """ if EXES: if EXES[0]: return EXES else: raise RuntimeError('No Elastix executable.') # Find exe elastix, ver = _find_executables('elastix') if elastix: base, ext = os.path.splitext(elastix) base = os.path.dirname(base) transformix = os.path.join(base, 'transformix' + ext) EXES.extend([elastix, transformix]) print('Found %s in %r' % (ver, elastix)) return EXES else: raise RuntimeError('Could not find Elastix executable. Download ' 'Elastix from http://elastix.isi.uu.nl/. Pyelastix ' 'looks for the exe in a series of common locations. ' 'Set ELASTIX_PATH if necessary.')
[ "def", "get_elastix_exes", "(", ")", ":", "if", "EXES", ":", "if", "EXES", "[", "0", "]", ":", "return", "EXES", "else", ":", "raise", "RuntimeError", "(", "'No Elastix executable.'", ")", "# Find exe", "elastix", ",", "ver", "=", "_find_executables", "(", ...
Get the executables for elastix and transformix. Raises an error if they cannot be found.
[ "Get", "the", "executables", "for", "elastix", "and", "transformix", ".", "Raises", "an", "error", "if", "they", "cannot", "be", "found", "." ]
971a677ce9a3ef8eb0b95ae393db8e2506d2f8a4
https://github.com/almarklein/pyelastix/blob/971a677ce9a3ef8eb0b95ae393db8e2506d2f8a4/pyelastix.py#L145-L168
train
34,017
almarklein/pyelastix
pyelastix.py
_clear_dir
def _clear_dir(dirName): """ Remove a directory and it contents. Ignore any failures. """ # If we got here, clear dir for fname in os.listdir(dirName): try: os.remove( os.path.join(dirName, fname) ) except Exception: pass try: os.rmdir(dirName) except Exception: pass
python
def _clear_dir(dirName): """ Remove a directory and it contents. Ignore any failures. """ # If we got here, clear dir for fname in os.listdir(dirName): try: os.remove( os.path.join(dirName, fname) ) except Exception: pass try: os.rmdir(dirName) except Exception: pass
[ "def", "_clear_dir", "(", "dirName", ")", ":", "# If we got here, clear dir ", "for", "fname", "in", "os", ".", "listdir", "(", "dirName", ")", ":", "try", ":", "os", ".", "remove", "(", "os", ".", "path", ".", "join", "(", "dirName", ",", "fname", ")...
Remove a directory and it contents. Ignore any failures.
[ "Remove", "a", "directory", "and", "it", "contents", ".", "Ignore", "any", "failures", "." ]
971a677ce9a3ef8eb0b95ae393db8e2506d2f8a4
https://github.com/almarklein/pyelastix/blob/971a677ce9a3ef8eb0b95ae393db8e2506d2f8a4/pyelastix.py#L174-L186
train
34,018
almarklein/pyelastix
pyelastix.py
get_tempdir
def get_tempdir(): """ Get the temporary directory where pyelastix stores its temporary files. The directory is specific to the current process and the calling thread. Generally, the user does not need this; directories are automatically cleaned up. Though Elastix log files are also written here. """ tempdir = os.path.join(tempfile.gettempdir(), 'pyelastix') # Make sure it exists if not os.path.isdir(tempdir): os.makedirs(tempdir) # Clean up all directories for which the process no longer exists for fname in os.listdir(tempdir): dirName = os.path.join(tempdir, fname) # Check if is right kind of dir if not (os.path.isdir(dirName) and fname.startswith('id_')): continue # Get pid and check if its running try: pid = int(fname.split('_')[1]) except Exception: continue if not _is_pid_running(pid): _clear_dir(dirName) # Select dir that included process and thread id tid = id(threading.current_thread() if hasattr(threading, 'current_thread') else threading.currentThread()) dir = os.path.join(tempdir, 'id_%i_%i' % (os.getpid(), tid)) if not os.path.isdir(dir): os.mkdir(dir) return dir
python
def get_tempdir(): """ Get the temporary directory where pyelastix stores its temporary files. The directory is specific to the current process and the calling thread. Generally, the user does not need this; directories are automatically cleaned up. Though Elastix log files are also written here. """ tempdir = os.path.join(tempfile.gettempdir(), 'pyelastix') # Make sure it exists if not os.path.isdir(tempdir): os.makedirs(tempdir) # Clean up all directories for which the process no longer exists for fname in os.listdir(tempdir): dirName = os.path.join(tempdir, fname) # Check if is right kind of dir if not (os.path.isdir(dirName) and fname.startswith('id_')): continue # Get pid and check if its running try: pid = int(fname.split('_')[1]) except Exception: continue if not _is_pid_running(pid): _clear_dir(dirName) # Select dir that included process and thread id tid = id(threading.current_thread() if hasattr(threading, 'current_thread') else threading.currentThread()) dir = os.path.join(tempdir, 'id_%i_%i' % (os.getpid(), tid)) if not os.path.isdir(dir): os.mkdir(dir) return dir
[ "def", "get_tempdir", "(", ")", ":", "tempdir", "=", "os", ".", "path", ".", "join", "(", "tempfile", ".", "gettempdir", "(", ")", ",", "'pyelastix'", ")", "# Make sure it exists", "if", "not", "os", ".", "path", ".", "isdir", "(", "tempdir", ")", ":",...
Get the temporary directory where pyelastix stores its temporary files. The directory is specific to the current process and the calling thread. Generally, the user does not need this; directories are automatically cleaned up. Though Elastix log files are also written here.
[ "Get", "the", "temporary", "directory", "where", "pyelastix", "stores", "its", "temporary", "files", ".", "The", "directory", "is", "specific", "to", "the", "current", "process", "and", "the", "calling", "thread", ".", "Generally", "the", "user", "does", "not"...
971a677ce9a3ef8eb0b95ae393db8e2506d2f8a4
https://github.com/almarklein/pyelastix/blob/971a677ce9a3ef8eb0b95ae393db8e2506d2f8a4/pyelastix.py#L189-L222
train
34,019
almarklein/pyelastix
pyelastix.py
_clear_temp_dir
def _clear_temp_dir(): """ Clear the temporary directory. """ tempdir = get_tempdir() for fname in os.listdir(tempdir): try: os.remove( os.path.join(tempdir, fname) ) except Exception: pass
python
def _clear_temp_dir(): """ Clear the temporary directory. """ tempdir = get_tempdir() for fname in os.listdir(tempdir): try: os.remove( os.path.join(tempdir, fname) ) except Exception: pass
[ "def", "_clear_temp_dir", "(", ")", ":", "tempdir", "=", "get_tempdir", "(", ")", "for", "fname", "in", "os", ".", "listdir", "(", "tempdir", ")", ":", "try", ":", "os", ".", "remove", "(", "os", ".", "path", ".", "join", "(", "tempdir", ",", "fnam...
Clear the temporary directory.
[ "Clear", "the", "temporary", "directory", "." ]
971a677ce9a3ef8eb0b95ae393db8e2506d2f8a4
https://github.com/almarklein/pyelastix/blob/971a677ce9a3ef8eb0b95ae393db8e2506d2f8a4/pyelastix.py#L225-L233
train
34,020
almarklein/pyelastix
pyelastix.py
_get_image_paths
def _get_image_paths(im1, im2): """ If the images are paths to a file, checks whether the file exist and return the paths. If the images are numpy arrays, writes them to disk and returns the paths of the new files. """ paths = [] for im in [im1, im2]: if im is None: # Groupwise registration: only one image (ndim+1 dimensions) paths.append(paths[0]) continue if isinstance(im, str): # Given a location if os.path.isfile(im1): paths.append(im) else: raise ValueError('Image location does not exist.') elif isinstance(im, np.ndarray): # Given a numpy array id = len(paths)+1 p = _write_image_data(im, id) paths.append(p) else: # Given something else ... raise ValueError('Invalid input image.') # Done return tuple(paths)
python
def _get_image_paths(im1, im2): """ If the images are paths to a file, checks whether the file exist and return the paths. If the images are numpy arrays, writes them to disk and returns the paths of the new files. """ paths = [] for im in [im1, im2]: if im is None: # Groupwise registration: only one image (ndim+1 dimensions) paths.append(paths[0]) continue if isinstance(im, str): # Given a location if os.path.isfile(im1): paths.append(im) else: raise ValueError('Image location does not exist.') elif isinstance(im, np.ndarray): # Given a numpy array id = len(paths)+1 p = _write_image_data(im, id) paths.append(p) else: # Given something else ... raise ValueError('Invalid input image.') # Done return tuple(paths)
[ "def", "_get_image_paths", "(", "im1", ",", "im2", ")", ":", "paths", "=", "[", "]", "for", "im", "in", "[", "im1", ",", "im2", "]", ":", "if", "im", "is", "None", ":", "# Groupwise registration: only one image (ndim+1 dimensions)", "paths", ".", "append", ...
If the images are paths to a file, checks whether the file exist and return the paths. If the images are numpy arrays, writes them to disk and returns the paths of the new files.
[ "If", "the", "images", "are", "paths", "to", "a", "file", "checks", "whether", "the", "file", "exist", "and", "return", "the", "paths", ".", "If", "the", "images", "are", "numpy", "arrays", "writes", "them", "to", "disk", "and", "returns", "the", "paths"...
971a677ce9a3ef8eb0b95ae393db8e2506d2f8a4
https://github.com/almarklein/pyelastix/blob/971a677ce9a3ef8eb0b95ae393db8e2506d2f8a4/pyelastix.py#L236-L267
train
34,021
almarklein/pyelastix
pyelastix.py
_system3
def _system3(cmd, verbose=False): """ Execute the given command in a subprocess and wait for it to finish. A thread is run that prints output of the process if verbose is True. """ # Init flag interrupted = False # Create progress if verbose > 0: progress = Progress() stdout = [] def poll_process(p): while not interrupted: msg = p.stdout.readline().decode() if msg: stdout.append(msg) if 'error' in msg.lower(): print(msg.rstrip()) if verbose == 1: progress.reset() elif verbose > 1: print(msg.rstrip()) elif verbose == 1: progress.update(msg) else: break time.sleep(0.01) #print("thread exit") # Start process that runs the command p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) # Keep reading stdout from it # thread.start_new_thread(poll_process, (p,)) Python 2.x my_thread = threading.Thread(target=poll_process, args=(p,)) my_thread.setDaemon(True) my_thread.start() # Wait here try: while p.poll() is None: time.sleep(0.01) except KeyboardInterrupt: # Set flag interrupted = True # Kill subprocess pid = p.pid if hasattr(os,'kill'): import signal os.kill(pid, signal.SIGKILL) elif sys.platform.startswith('win'): kernel32 = ctypes.windll.kernel32 handle = kernel32.OpenProcess(1, 0, pid) kernel32.TerminateProcess(handle, 0) #os.system("TASKKILL /PID " + str(pid) + " /F") # All good? if interrupted: raise RuntimeError('Registration process interrupted by the user.') if p.returncode: stdout.append(p.stdout.read().decode()) print(''.join(stdout)) raise RuntimeError('An error occured during the registration.')
python
def _system3(cmd, verbose=False): """ Execute the given command in a subprocess and wait for it to finish. A thread is run that prints output of the process if verbose is True. """ # Init flag interrupted = False # Create progress if verbose > 0: progress = Progress() stdout = [] def poll_process(p): while not interrupted: msg = p.stdout.readline().decode() if msg: stdout.append(msg) if 'error' in msg.lower(): print(msg.rstrip()) if verbose == 1: progress.reset() elif verbose > 1: print(msg.rstrip()) elif verbose == 1: progress.update(msg) else: break time.sleep(0.01) #print("thread exit") # Start process that runs the command p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) # Keep reading stdout from it # thread.start_new_thread(poll_process, (p,)) Python 2.x my_thread = threading.Thread(target=poll_process, args=(p,)) my_thread.setDaemon(True) my_thread.start() # Wait here try: while p.poll() is None: time.sleep(0.01) except KeyboardInterrupt: # Set flag interrupted = True # Kill subprocess pid = p.pid if hasattr(os,'kill'): import signal os.kill(pid, signal.SIGKILL) elif sys.platform.startswith('win'): kernel32 = ctypes.windll.kernel32 handle = kernel32.OpenProcess(1, 0, pid) kernel32.TerminateProcess(handle, 0) #os.system("TASKKILL /PID " + str(pid) + " /F") # All good? if interrupted: raise RuntimeError('Registration process interrupted by the user.') if p.returncode: stdout.append(p.stdout.read().decode()) print(''.join(stdout)) raise RuntimeError('An error occured during the registration.')
[ "def", "_system3", "(", "cmd", ",", "verbose", "=", "False", ")", ":", "# Init flag", "interrupted", "=", "False", "# Create progress", "if", "verbose", ">", "0", ":", "progress", "=", "Progress", "(", ")", "stdout", "=", "[", "]", "def", "poll_process", ...
Execute the given command in a subprocess and wait for it to finish. A thread is run that prints output of the process if verbose is True.
[ "Execute", "the", "given", "command", "in", "a", "subprocess", "and", "wait", "for", "it", "to", "finish", ".", "A", "thread", "is", "run", "that", "prints", "output", "of", "the", "process", "if", "verbose", "is", "True", "." ]
971a677ce9a3ef8eb0b95ae393db8e2506d2f8a4
https://github.com/almarklein/pyelastix/blob/971a677ce9a3ef8eb0b95ae393db8e2506d2f8a4/pyelastix.py#L272-L337
train
34,022
almarklein/pyelastix
pyelastix.py
_get_dtype_maps
def _get_dtype_maps(): """ Get dictionaries to map numpy data types to ITK types and the other way around. """ # Define pairs tmp = [ (np.float32, 'MET_FLOAT'), (np.float64, 'MET_DOUBLE'), (np.uint8, 'MET_UCHAR'), (np.int8, 'MET_CHAR'), (np.uint16, 'MET_USHORT'), (np.int16, 'MET_SHORT'), (np.uint32, 'MET_UINT'), (np.int32, 'MET_INT'), (np.uint64, 'MET_ULONG'), (np.int64, 'MET_LONG') ] # Create dictionaries map1, map2 = {}, {} for np_type, itk_type in tmp: map1[np_type.__name__] = itk_type map2[itk_type] = np_type.__name__ # Done return map1, map2
python
def _get_dtype_maps(): """ Get dictionaries to map numpy data types to ITK types and the other way around. """ # Define pairs tmp = [ (np.float32, 'MET_FLOAT'), (np.float64, 'MET_DOUBLE'), (np.uint8, 'MET_UCHAR'), (np.int8, 'MET_CHAR'), (np.uint16, 'MET_USHORT'), (np.int16, 'MET_SHORT'), (np.uint32, 'MET_UINT'), (np.int32, 'MET_INT'), (np.uint64, 'MET_ULONG'), (np.int64, 'MET_LONG') ] # Create dictionaries map1, map2 = {}, {} for np_type, itk_type in tmp: map1[np_type.__name__] = itk_type map2[itk_type] = np_type.__name__ # Done return map1, map2
[ "def", "_get_dtype_maps", "(", ")", ":", "# Define pairs", "tmp", "=", "[", "(", "np", ".", "float32", ",", "'MET_FLOAT'", ")", ",", "(", "np", ".", "float64", ",", "'MET_DOUBLE'", ")", ",", "(", "np", ".", "uint8", ",", "'MET_UCHAR'", ")", ",", "(",...
Get dictionaries to map numpy data types to ITK types and the other way around.
[ "Get", "dictionaries", "to", "map", "numpy", "data", "types", "to", "ITK", "types", "and", "the", "other", "way", "around", "." ]
971a677ce9a3ef8eb0b95ae393db8e2506d2f8a4
https://github.com/almarklein/pyelastix/blob/971a677ce9a3ef8eb0b95ae393db8e2506d2f8a4/pyelastix.py#L340-L359
train
34,023
almarklein/pyelastix
pyelastix.py
_read_image_data
def _read_image_data( mhd_file): """ Read the resulting image data and return it as a numpy array. """ tempdir = get_tempdir() # Load description from mhd file fname = tempdir + '/' + mhd_file des = open(fname, 'r').read() # Get data filename and load raw data match = re.findall('ElementDataFile = (.+?)\n', des) fname = tempdir + '/' + match[0] data = open(fname, 'rb').read() # Determine dtype match = re.findall('ElementType = (.+?)\n', des) dtype_itk = match[0].upper().strip() dtype = DTYPE_ITK2NP.get(dtype_itk, None) if dtype is None: raise RuntimeError('Unknown ElementType: ' + dtype_itk) # Create numpy array a = np.frombuffer(data, dtype=dtype) # Determine shape, sampling and origin of the data match = re.findall('DimSize = (.+?)\n', des) shape = [int(i) for i in match[0].split(' ')] # match = re.findall('ElementSpacing = (.+?)\n', des) sampling = [float(i) for i in match[0].split(' ')] # match = re.findall('Offset = (.+?)\n', des) origin = [float(i) for i in match[0].split(' ')] # Reverse shape stuff to make z-y-x order shape = [s for s in reversed(shape)] sampling = [s for s in reversed(sampling)] origin = [s for s in reversed(origin)] # Take vectors/colours into account N = np.prod(shape) if N != a.size: extraDim = int( a.size / N ) shape = tuple(shape) + (extraDim,) sampling = tuple(sampling) + (1.0,) origin = tuple(origin) + (0,) # Check shape N = np.prod(shape) if N != a.size: raise RuntimeError('Cannot apply shape to data.') else: a.shape = shape a = Image(a) a.sampling = sampling a.origin = origin return a
python
def _read_image_data( mhd_file): """ Read the resulting image data and return it as a numpy array. """ tempdir = get_tempdir() # Load description from mhd file fname = tempdir + '/' + mhd_file des = open(fname, 'r').read() # Get data filename and load raw data match = re.findall('ElementDataFile = (.+?)\n', des) fname = tempdir + '/' + match[0] data = open(fname, 'rb').read() # Determine dtype match = re.findall('ElementType = (.+?)\n', des) dtype_itk = match[0].upper().strip() dtype = DTYPE_ITK2NP.get(dtype_itk, None) if dtype is None: raise RuntimeError('Unknown ElementType: ' + dtype_itk) # Create numpy array a = np.frombuffer(data, dtype=dtype) # Determine shape, sampling and origin of the data match = re.findall('DimSize = (.+?)\n', des) shape = [int(i) for i in match[0].split(' ')] # match = re.findall('ElementSpacing = (.+?)\n', des) sampling = [float(i) for i in match[0].split(' ')] # match = re.findall('Offset = (.+?)\n', des) origin = [float(i) for i in match[0].split(' ')] # Reverse shape stuff to make z-y-x order shape = [s for s in reversed(shape)] sampling = [s for s in reversed(sampling)] origin = [s for s in reversed(origin)] # Take vectors/colours into account N = np.prod(shape) if N != a.size: extraDim = int( a.size / N ) shape = tuple(shape) + (extraDim,) sampling = tuple(sampling) + (1.0,) origin = tuple(origin) + (0,) # Check shape N = np.prod(shape) if N != a.size: raise RuntimeError('Cannot apply shape to data.') else: a.shape = shape a = Image(a) a.sampling = sampling a.origin = origin return a
[ "def", "_read_image_data", "(", "mhd_file", ")", ":", "tempdir", "=", "get_tempdir", "(", ")", "# Load description from mhd file", "fname", "=", "tempdir", "+", "'/'", "+", "mhd_file", "des", "=", "open", "(", "fname", ",", "'r'", ")", ".", "read", "(", ")...
Read the resulting image data and return it as a numpy array.
[ "Read", "the", "resulting", "image", "data", "and", "return", "it", "as", "a", "numpy", "array", "." ]
971a677ce9a3ef8eb0b95ae393db8e2506d2f8a4
https://github.com/almarklein/pyelastix/blob/971a677ce9a3ef8eb0b95ae393db8e2506d2f8a4/pyelastix.py#L635-L691
train
34,024
almarklein/pyelastix
pyelastix.py
_get_fixed_params
def _get_fixed_params(im): """ Parameters that the user has no influence on. Mostly chosen bases on the input images. """ p = Parameters() if not isinstance(im, np.ndarray): return p # Dimension of the inputs p.FixedImageDimension = im.ndim p.MovingImageDimension = im.ndim # Always write result, so I can verify p.WriteResultImage = True # How to write the result tmp = DTYPE_NP2ITK[im.dtype.name] p.ResultImagePixelType = tmp.split('_')[-1].lower() p.ResultImageFormat = "mhd" # Done return p
python
def _get_fixed_params(im): """ Parameters that the user has no influence on. Mostly chosen bases on the input images. """ p = Parameters() if not isinstance(im, np.ndarray): return p # Dimension of the inputs p.FixedImageDimension = im.ndim p.MovingImageDimension = im.ndim # Always write result, so I can verify p.WriteResultImage = True # How to write the result tmp = DTYPE_NP2ITK[im.dtype.name] p.ResultImagePixelType = tmp.split('_')[-1].lower() p.ResultImageFormat = "mhd" # Done return p
[ "def", "_get_fixed_params", "(", "im", ")", ":", "p", "=", "Parameters", "(", ")", "if", "not", "isinstance", "(", "im", ",", "np", ".", "ndarray", ")", ":", "return", "p", "# Dimension of the inputs", "p", ".", "FixedImageDimension", "=", "im", ".", "nd...
Parameters that the user has no influence on. Mostly chosen bases on the input images.
[ "Parameters", "that", "the", "user", "has", "no", "influence", "on", ".", "Mostly", "chosen", "bases", "on", "the", "input", "images", "." ]
971a677ce9a3ef8eb0b95ae393db8e2506d2f8a4
https://github.com/almarklein/pyelastix/blob/971a677ce9a3ef8eb0b95ae393db8e2506d2f8a4/pyelastix.py#L751-L774
train
34,025
almarklein/pyelastix
pyelastix.py
get_advanced_params
def get_advanced_params(): """ Get `Parameters` struct with parameters that most users do not want to think about. """ p = Parameters() # Internal format used during the registration process p.FixedInternalImagePixelType = "float" p.MovingInternalImagePixelType = "float" # Image direction p.UseDirectionCosines = True # In almost all cases you'd want multi resolution p.Registration = 'MultiResolutionRegistration' # Pyramid options # *RecursiveImagePyramid downsamples the images # *SmoothingImagePyramid does not downsample p.FixedImagePyramid = "FixedRecursiveImagePyramid" p.MovingImagePyramid = "MovingRecursiveImagePyramid" # Whether transforms are combined by composition or by addition. # It does not influence the results very much. p.HowToCombineTransforms = "Compose" # For out of range pixels p.DefaultPixelValue = 0 # Interpolator used during interpolation and its order # 1 means linear interpolation, 3 means cubic. p.Interpolator = "BSplineInterpolator" p.BSplineInterpolationOrder = 1 # Interpolator used during interpolation of final level, and its order p.ResampleInterpolator = "FinalBSplineInterpolator" p.FinalBSplineInterpolationOrder = 3 # According to the manual, there is currently only one resampler p.Resampler = "DefaultResampler" # Done return p
python
def get_advanced_params(): """ Get `Parameters` struct with parameters that most users do not want to think about. """ p = Parameters() # Internal format used during the registration process p.FixedInternalImagePixelType = "float" p.MovingInternalImagePixelType = "float" # Image direction p.UseDirectionCosines = True # In almost all cases you'd want multi resolution p.Registration = 'MultiResolutionRegistration' # Pyramid options # *RecursiveImagePyramid downsamples the images # *SmoothingImagePyramid does not downsample p.FixedImagePyramid = "FixedRecursiveImagePyramid" p.MovingImagePyramid = "MovingRecursiveImagePyramid" # Whether transforms are combined by composition or by addition. # It does not influence the results very much. p.HowToCombineTransforms = "Compose" # For out of range pixels p.DefaultPixelValue = 0 # Interpolator used during interpolation and its order # 1 means linear interpolation, 3 means cubic. p.Interpolator = "BSplineInterpolator" p.BSplineInterpolationOrder = 1 # Interpolator used during interpolation of final level, and its order p.ResampleInterpolator = "FinalBSplineInterpolator" p.FinalBSplineInterpolationOrder = 3 # According to the manual, there is currently only one resampler p.Resampler = "DefaultResampler" # Done return p
[ "def", "get_advanced_params", "(", ")", ":", "p", "=", "Parameters", "(", ")", "# Internal format used during the registration process", "p", ".", "FixedInternalImagePixelType", "=", "\"float\"", "p", ".", "MovingInternalImagePixelType", "=", "\"float\"", "# Image direction...
Get `Parameters` struct with parameters that most users do not want to think about.
[ "Get", "Parameters", "struct", "with", "parameters", "that", "most", "users", "do", "not", "want", "to", "think", "about", "." ]
971a677ce9a3ef8eb0b95ae393db8e2506d2f8a4
https://github.com/almarklein/pyelastix/blob/971a677ce9a3ef8eb0b95ae393db8e2506d2f8a4/pyelastix.py#L777-L820
train
34,026
almarklein/pyelastix
pyelastix.py
_write_parameter_file
def _write_parameter_file(params): """ Write the parameter file in the format that elaxtix likes. """ # Get path path = os.path.join(get_tempdir(), 'params.txt') # Define helper function def valToStr(val): if val in [True, False]: return '"%s"' % str(val).lower() elif isinstance(val, int): return str(val) elif isinstance(val, float): tmp = str(val) if not '.' in tmp: tmp += '.0' return tmp elif isinstance(val, str): return '"%s"' % val # Compile text text = '' for key in params: val = params[key] # Make a string of the values if isinstance(val, (list, tuple)): vals = [valToStr(v) for v in val] val_ = ' '.join(vals) else: val_ = valToStr(val) # Create line and add line = '(%s %s)' % (key, val_) text += line + '\n' # Write text f = open(path, 'wb') try: f.write(text.encode('utf-8')) finally: f.close() # Done return path
python
def _write_parameter_file(params): """ Write the parameter file in the format that elaxtix likes. """ # Get path path = os.path.join(get_tempdir(), 'params.txt') # Define helper function def valToStr(val): if val in [True, False]: return '"%s"' % str(val).lower() elif isinstance(val, int): return str(val) elif isinstance(val, float): tmp = str(val) if not '.' in tmp: tmp += '.0' return tmp elif isinstance(val, str): return '"%s"' % val # Compile text text = '' for key in params: val = params[key] # Make a string of the values if isinstance(val, (list, tuple)): vals = [valToStr(v) for v in val] val_ = ' '.join(vals) else: val_ = valToStr(val) # Create line and add line = '(%s %s)' % (key, val_) text += line + '\n' # Write text f = open(path, 'wb') try: f.write(text.encode('utf-8')) finally: f.close() # Done return path
[ "def", "_write_parameter_file", "(", "params", ")", ":", "# Get path", "path", "=", "os", ".", "path", ".", "join", "(", "get_tempdir", "(", ")", ",", "'params.txt'", ")", "# Define helper function", "def", "valToStr", "(", "val", ")", ":", "if", "val", "i...
Write the parameter file in the format that elaxtix likes.
[ "Write", "the", "parameter", "file", "in", "the", "format", "that", "elaxtix", "likes", "." ]
971a677ce9a3ef8eb0b95ae393db8e2506d2f8a4
https://github.com/almarklein/pyelastix/blob/971a677ce9a3ef8eb0b95ae393db8e2506d2f8a4/pyelastix.py#L970-L1013
train
34,027
pypa/readme_renderer
readme_renderer/markdown.py
_highlight
def _highlight(html): """Syntax-highlights HTML-rendered Markdown. Plucks sections to highlight that conform the the GitHub fenced code info string as defined at https://github.github.com/gfm/#info-string. Args: html (str): The rendered HTML. Returns: str: The HTML with Pygments syntax highlighting applied to all code blocks. """ formatter = pygments.formatters.HtmlFormatter(nowrap=True) code_expr = re.compile( r'<pre><code class="language-(?P<lang>.+?)">(?P<code>.+?)' r'</code></pre>', re.DOTALL) def replacer(match): try: lang = match.group('lang') lang = _LANG_ALIASES.get(lang, lang) lexer = pygments.lexers.get_lexer_by_name(lang) except ValueError: lexer = pygments.lexers.TextLexer() code = match.group('code') # Decode html entities in the code. cmark tries to be helpful and # translate '"' to '&quot;', but it confuses pygments. Pygments will # escape any html entities when re-writing the code, and we run # everything through bleach after. code = html_parser.HTMLParser().unescape(code) highlighted = pygments.highlight(code, lexer, formatter) return '<pre>{}</pre>'.format(highlighted) result = code_expr.sub(replacer, html) return result
python
def _highlight(html): """Syntax-highlights HTML-rendered Markdown. Plucks sections to highlight that conform the the GitHub fenced code info string as defined at https://github.github.com/gfm/#info-string. Args: html (str): The rendered HTML. Returns: str: The HTML with Pygments syntax highlighting applied to all code blocks. """ formatter = pygments.formatters.HtmlFormatter(nowrap=True) code_expr = re.compile( r'<pre><code class="language-(?P<lang>.+?)">(?P<code>.+?)' r'</code></pre>', re.DOTALL) def replacer(match): try: lang = match.group('lang') lang = _LANG_ALIASES.get(lang, lang) lexer = pygments.lexers.get_lexer_by_name(lang) except ValueError: lexer = pygments.lexers.TextLexer() code = match.group('code') # Decode html entities in the code. cmark tries to be helpful and # translate '"' to '&quot;', but it confuses pygments. Pygments will # escape any html entities when re-writing the code, and we run # everything through bleach after. code = html_parser.HTMLParser().unescape(code) highlighted = pygments.highlight(code, lexer, formatter) return '<pre>{}</pre>'.format(highlighted) result = code_expr.sub(replacer, html) return result
[ "def", "_highlight", "(", "html", ")", ":", "formatter", "=", "pygments", ".", "formatters", ".", "HtmlFormatter", "(", "nowrap", "=", "True", ")", "code_expr", "=", "re", ".", "compile", "(", "r'<pre><code class=\"language-(?P<lang>.+?)\">(?P<code>.+?)'", "r'</code...
Syntax-highlights HTML-rendered Markdown. Plucks sections to highlight that conform the the GitHub fenced code info string as defined at https://github.github.com/gfm/#info-string. Args: html (str): The rendered HTML. Returns: str: The HTML with Pygments syntax highlighting applied to all code blocks.
[ "Syntax", "-", "highlights", "HTML", "-", "rendered", "Markdown", "." ]
7bf7529296acfa7db0edf7914cb4571d691b63ee
https://github.com/pypa/readme_renderer/blob/7bf7529296acfa7db0edf7914cb4571d691b63ee/readme_renderer/markdown.py#L68-L110
train
34,028
pypa/readme_renderer
readme_renderer/integration/distutils.py
Check.check_restructuredtext
def check_restructuredtext(self): """ Checks if the long string fields are reST-compliant. """ # Warn that this command is deprecated # Don't use self.warn() because it will cause the check to fail. Command.warn( self, "This command has been deprecated. Use `twine check` instead: " "https://packaging.python.org/guides/making-a-pypi-friendly-readme" "#validating-restructuredtext-markup" ) data = self.distribution.get_long_description() content_type = getattr( self.distribution.metadata, 'long_description_content_type', None) if content_type: content_type, _ = cgi.parse_header(content_type) if content_type != 'text/x-rst': self.warn( "Not checking long description content type '%s', this " "command only checks 'text/x-rst'." % content_type) return # None or empty string should both trigger this branch. if not data or data == 'UNKNOWN': self.warn( "The project's long_description is either missing or empty.") return stream = _WarningStream() markup = render(data, stream=stream) if markup is None: self.warn( "The project's long_description has invalid markup which will " "not be rendered on PyPI. The following syntax errors were " "detected:\n%s" % stream) return self.announce( "The project's long description is valid RST.", level=distutils.log.INFO)
python
def check_restructuredtext(self): """ Checks if the long string fields are reST-compliant. """ # Warn that this command is deprecated # Don't use self.warn() because it will cause the check to fail. Command.warn( self, "This command has been deprecated. Use `twine check` instead: " "https://packaging.python.org/guides/making-a-pypi-friendly-readme" "#validating-restructuredtext-markup" ) data = self.distribution.get_long_description() content_type = getattr( self.distribution.metadata, 'long_description_content_type', None) if content_type: content_type, _ = cgi.parse_header(content_type) if content_type != 'text/x-rst': self.warn( "Not checking long description content type '%s', this " "command only checks 'text/x-rst'." % content_type) return # None or empty string should both trigger this branch. if not data or data == 'UNKNOWN': self.warn( "The project's long_description is either missing or empty.") return stream = _WarningStream() markup = render(data, stream=stream) if markup is None: self.warn( "The project's long_description has invalid markup which will " "not be rendered on PyPI. The following syntax errors were " "detected:\n%s" % stream) return self.announce( "The project's long description is valid RST.", level=distutils.log.INFO)
[ "def", "check_restructuredtext", "(", "self", ")", ":", "# Warn that this command is deprecated", "# Don't use self.warn() because it will cause the check to fail.", "Command", ".", "warn", "(", "self", ",", "\"This command has been deprecated. Use `twine check` instead: \"", "\"https:...
Checks if the long string fields are reST-compliant.
[ "Checks", "if", "the", "long", "string", "fields", "are", "reST", "-", "compliant", "." ]
7bf7529296acfa7db0edf7914cb4571d691b63ee
https://github.com/pypa/readme_renderer/blob/7bf7529296acfa7db0edf7914cb4571d691b63ee/readme_renderer/integration/distutils.py#L61-L104
train
34,029
streeter/pelican-gist
pelican_gist/plugin.py
render_code
def render_code(code, filetype, pygments_style): """Renders a piece of code into HTML. Highlights syntax if filetype is specfied""" if filetype: lexer = pygments.lexers.get_lexer_by_name(filetype) formatter = pygments.formatters.HtmlFormatter(style=pygments_style) return pygments.highlight(code, lexer, formatter) else: return "<pre><code>{}</code></pre>".format(code)
python
def render_code(code, filetype, pygments_style): """Renders a piece of code into HTML. Highlights syntax if filetype is specfied""" if filetype: lexer = pygments.lexers.get_lexer_by_name(filetype) formatter = pygments.formatters.HtmlFormatter(style=pygments_style) return pygments.highlight(code, lexer, formatter) else: return "<pre><code>{}</code></pre>".format(code)
[ "def", "render_code", "(", "code", ",", "filetype", ",", "pygments_style", ")", ":", "if", "filetype", ":", "lexer", "=", "pygments", ".", "lexers", ".", "get_lexer_by_name", "(", "filetype", ")", "formatter", "=", "pygments", ".", "formatters", ".", "HtmlFo...
Renders a piece of code into HTML. Highlights syntax if filetype is specfied
[ "Renders", "a", "piece", "of", "code", "into", "HTML", ".", "Highlights", "syntax", "if", "filetype", "is", "specfied" ]
395e619534b404fb2b94456dc400dc2a8a2f934a
https://github.com/streeter/pelican-gist/blob/395e619534b404fb2b94456dc400dc2a8a2f934a/pelican_gist/plugin.py#L94-L101
train
34,030
MicroPyramid/django-simple-forum
django_simple_forum/facebook.py
GraphAPI.fql
def fql(self, query, args=None, post_args=None): """FQL query. Example query: "SELECT affiliations FROM user WHERE uid = me()" """ args = args or {} if self.access_token: if post_args is not None: post_args["access_token"] = self.access_token else: args["access_token"] = self.access_token post_data = None if post_args is None else urllib.urlencode(post_args) """Check if query is a dict and use the multiquery method else use single query """ if not isinstance(query, basestring): args["queries"] = query fql_method = 'fql.multiquery' else: args["query"] = query fql_method = 'fql.query' args["format"] = "json" try: file = urllib2.urlopen("https://api.facebook.com/method/" + fql_method + "?" + urllib.urlencode(args), post_data, timeout=self.timeout) except TypeError: # Timeout support for Python <2.6 if self.timeout: socket.setdefaulttimeout(self.timeout) file = urllib2.urlopen("https://api.facebook.com/method/" + fql_method + "?" + urllib.urlencode(args), post_data) try: content = file.read() response = _parse_json(content) #Return a list if success, return a dictionary if failed if type(response) is dict and "error_code" in response: raise GraphAPIError(response) except (Exception, e): raise e finally: file.close() return response
python
def fql(self, query, args=None, post_args=None): """FQL query. Example query: "SELECT affiliations FROM user WHERE uid = me()" """ args = args or {} if self.access_token: if post_args is not None: post_args["access_token"] = self.access_token else: args["access_token"] = self.access_token post_data = None if post_args is None else urllib.urlencode(post_args) """Check if query is a dict and use the multiquery method else use single query """ if not isinstance(query, basestring): args["queries"] = query fql_method = 'fql.multiquery' else: args["query"] = query fql_method = 'fql.query' args["format"] = "json" try: file = urllib2.urlopen("https://api.facebook.com/method/" + fql_method + "?" + urllib.urlencode(args), post_data, timeout=self.timeout) except TypeError: # Timeout support for Python <2.6 if self.timeout: socket.setdefaulttimeout(self.timeout) file = urllib2.urlopen("https://api.facebook.com/method/" + fql_method + "?" + urllib.urlencode(args), post_data) try: content = file.read() response = _parse_json(content) #Return a list if success, return a dictionary if failed if type(response) is dict and "error_code" in response: raise GraphAPIError(response) except (Exception, e): raise e finally: file.close() return response
[ "def", "fql", "(", "self", ",", "query", ",", "args", "=", "None", ",", "post_args", "=", "None", ")", ":", "args", "=", "args", "or", "{", "}", "if", "self", ".", "access_token", ":", "if", "post_args", "is", "not", "None", ":", "post_args", "[", ...
FQL query. Example query: "SELECT affiliations FROM user WHERE uid = me()"
[ "FQL", "query", "." ]
73160e2522695767d18301da690614923ae8f964
https://github.com/MicroPyramid/django-simple-forum/blob/73160e2522695767d18301da690614923ae8f964/django_simple_forum/facebook.py#L105-L155
train
34,031
biosustain/optlang
optlang/gurobi_interface.py
_constraint_lb_and_ub_to_gurobi_sense_rhs_and_range_value
def _constraint_lb_and_ub_to_gurobi_sense_rhs_and_range_value(lb, ub): """Helper function used by Constraint and Model""" if lb is None and ub is None: raise Exception("Free constraint ...") elif lb is None: sense = '<' rhs = float(ub) range_value = 0. elif ub is None: sense = '>' rhs = float(lb) range_value = 0. elif lb == ub: sense = '=' rhs = float(lb) range_value = 0. elif lb > ub: raise ValueError("Lower bound is larger than upper bound.") else: sense = '=' rhs = float(lb) range_value = float(ub - lb) return sense, rhs, range_value
python
def _constraint_lb_and_ub_to_gurobi_sense_rhs_and_range_value(lb, ub): """Helper function used by Constraint and Model""" if lb is None and ub is None: raise Exception("Free constraint ...") elif lb is None: sense = '<' rhs = float(ub) range_value = 0. elif ub is None: sense = '>' rhs = float(lb) range_value = 0. elif lb == ub: sense = '=' rhs = float(lb) range_value = 0. elif lb > ub: raise ValueError("Lower bound is larger than upper bound.") else: sense = '=' rhs = float(lb) range_value = float(ub - lb) return sense, rhs, range_value
[ "def", "_constraint_lb_and_ub_to_gurobi_sense_rhs_and_range_value", "(", "lb", ",", "ub", ")", ":", "if", "lb", "is", "None", "and", "ub", "is", "None", ":", "raise", "Exception", "(", "\"Free constraint ...\"", ")", "elif", "lb", "is", "None", ":", "sense", "...
Helper function used by Constraint and Model
[ "Helper", "function", "used", "by", "Constraint", "and", "Model" ]
13673ac26f6b3ba37a2ef392489722c52e3c5ff1
https://github.com/biosustain/optlang/blob/13673ac26f6b3ba37a2ef392489722c52e3c5ff1/optlang/gurobi_interface.py#L65-L87
train
34,032
biosustain/optlang
optlang/expression_parsing.py
parse_optimization_expression
def parse_optimization_expression(obj, linear=True, quadratic=False, expression=None, **kwargs): """ Function for parsing the expression of a Constraint or Objective object. Parameters ---------- object: Constraint or Objective The optimization expression to be parsed linear: Boolean If True the expression will be assumed to be linear quadratic: Boolean If True the expression will be assumed to be quadratic expression: Sympy expression or None (optional) An expression can be passed explicitly to avoid getting the expression from the solver. If this is used then 'linear' or 'quadratic' should be True. If both linear and quadratic are False, the is_Linear and is_Quadratic methods will be used to determine how it should be parsed Returns ---------- A tuple of (linear_coefficients, quadratic_coefficients) linear_coefficients is a dictionary of {variable: coefficient} pairs quadratic_coefficients is a dictionary of {frozenset(variables): coefficient} pairs """ if expression is None: expression = obj.expression if not (linear or quadratic): if obj.is_Linear: linear = True elif obj.is_Quadratic: quadratic = True else: raise ValueError("Expression is not linear or quadratic. Other expressions are not currently supported.") assert linear or quadratic if quadratic: offset, linear_coefficients, quadratic_coefficients = _parse_quadratic_expression(expression, **kwargs) else: offset, linear_coefficients = _parse_linear_expression(expression, **kwargs) quadratic_coefficients = {} return offset, linear_coefficients, quadratic_coefficients
python
def parse_optimization_expression(obj, linear=True, quadratic=False, expression=None, **kwargs): """ Function for parsing the expression of a Constraint or Objective object. Parameters ---------- object: Constraint or Objective The optimization expression to be parsed linear: Boolean If True the expression will be assumed to be linear quadratic: Boolean If True the expression will be assumed to be quadratic expression: Sympy expression or None (optional) An expression can be passed explicitly to avoid getting the expression from the solver. If this is used then 'linear' or 'quadratic' should be True. If both linear and quadratic are False, the is_Linear and is_Quadratic methods will be used to determine how it should be parsed Returns ---------- A tuple of (linear_coefficients, quadratic_coefficients) linear_coefficients is a dictionary of {variable: coefficient} pairs quadratic_coefficients is a dictionary of {frozenset(variables): coefficient} pairs """ if expression is None: expression = obj.expression if not (linear or quadratic): if obj.is_Linear: linear = True elif obj.is_Quadratic: quadratic = True else: raise ValueError("Expression is not linear or quadratic. Other expressions are not currently supported.") assert linear or quadratic if quadratic: offset, linear_coefficients, quadratic_coefficients = _parse_quadratic_expression(expression, **kwargs) else: offset, linear_coefficients = _parse_linear_expression(expression, **kwargs) quadratic_coefficients = {} return offset, linear_coefficients, quadratic_coefficients
[ "def", "parse_optimization_expression", "(", "obj", ",", "linear", "=", "True", ",", "quadratic", "=", "False", ",", "expression", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "expression", "is", "None", ":", "expression", "=", "obj", ".", "expr...
Function for parsing the expression of a Constraint or Objective object. Parameters ---------- object: Constraint or Objective The optimization expression to be parsed linear: Boolean If True the expression will be assumed to be linear quadratic: Boolean If True the expression will be assumed to be quadratic expression: Sympy expression or None (optional) An expression can be passed explicitly to avoid getting the expression from the solver. If this is used then 'linear' or 'quadratic' should be True. If both linear and quadratic are False, the is_Linear and is_Quadratic methods will be used to determine how it should be parsed Returns ---------- A tuple of (linear_coefficients, quadratic_coefficients) linear_coefficients is a dictionary of {variable: coefficient} pairs quadratic_coefficients is a dictionary of {frozenset(variables): coefficient} pairs
[ "Function", "for", "parsing", "the", "expression", "of", "a", "Constraint", "or", "Objective", "object", "." ]
13673ac26f6b3ba37a2ef392489722c52e3c5ff1
https://github.com/biosustain/optlang/blob/13673ac26f6b3ba37a2ef392489722c52e3c5ff1/optlang/expression_parsing.py#L21-L64
train
34,033
biosustain/optlang
optlang/expression_parsing.py
_parse_quadratic_expression
def _parse_quadratic_expression(expression, expanded=False): """ Parse a quadratic expression. It is assumed that the expression is known to be quadratic or linear. The 'expanded' parameter tells whether the expression has already been expanded. If it hasn't the parsing might fail and will expand the expression and try again. """ linear_coefficients = {} quadratic_coefficients = {} offset = 0 if expression.is_Number: # Constant expression, no coefficients return float(expression), linear_coefficients, quadratic_coefficients if expression.is_Mul: terms = (expression,) elif expression.is_Add: terms = expression.args else: raise ValueError("Expression of type {} could not be parsed.".format(type(expression))) try: for term in terms: if term.is_Number: offset += float(term) continue if term.is_Pow: term = 1.0 * term assert term.is_Mul, "What is this? {}".format(type(term)) factors = term.args coef = factors[0] vars = factors[1:] assert len(vars) <= 2, "This should not happen. Is this expression quadratic?" if len(vars) == 2: key = frozenset(vars) quadratic_coefficients[key] = quadratic_coefficients.get(key, 0) + coef else: var = vars[0] if var.is_Symbol: linear_coefficients[var] = linear_coefficients.get(var, 0) + coef elif var.is_Pow: var, exponent = var.args if exponent != 2: raise ValueError("The expression is not quadratic") key = frozenset((var,)) quadratic_coefficients[key] = quadratic_coefficients.get(key, 0) + coef if quadratic_coefficients: assert all(var.is_Symbol for var in frozenset.union(*quadratic_coefficients)) # Raise an exception to trigger expand if linear_coefficients: assert all(var.is_Symbol for var in linear_coefficients) except Exception as e: if expanded: raise e else: # Try to expand the expression and parse it again return _parse_quadratic_expression(expression.expand(), expanded=True) return offset, linear_coefficients, quadratic_coefficients
python
def _parse_quadratic_expression(expression, expanded=False): """ Parse a quadratic expression. It is assumed that the expression is known to be quadratic or linear. The 'expanded' parameter tells whether the expression has already been expanded. If it hasn't the parsing might fail and will expand the expression and try again. """ linear_coefficients = {} quadratic_coefficients = {} offset = 0 if expression.is_Number: # Constant expression, no coefficients return float(expression), linear_coefficients, quadratic_coefficients if expression.is_Mul: terms = (expression,) elif expression.is_Add: terms = expression.args else: raise ValueError("Expression of type {} could not be parsed.".format(type(expression))) try: for term in terms: if term.is_Number: offset += float(term) continue if term.is_Pow: term = 1.0 * term assert term.is_Mul, "What is this? {}".format(type(term)) factors = term.args coef = factors[0] vars = factors[1:] assert len(vars) <= 2, "This should not happen. Is this expression quadratic?" if len(vars) == 2: key = frozenset(vars) quadratic_coefficients[key] = quadratic_coefficients.get(key, 0) + coef else: var = vars[0] if var.is_Symbol: linear_coefficients[var] = linear_coefficients.get(var, 0) + coef elif var.is_Pow: var, exponent = var.args if exponent != 2: raise ValueError("The expression is not quadratic") key = frozenset((var,)) quadratic_coefficients[key] = quadratic_coefficients.get(key, 0) + coef if quadratic_coefficients: assert all(var.is_Symbol for var in frozenset.union(*quadratic_coefficients)) # Raise an exception to trigger expand if linear_coefficients: assert all(var.is_Symbol for var in linear_coefficients) except Exception as e: if expanded: raise e else: # Try to expand the expression and parse it again return _parse_quadratic_expression(expression.expand(), expanded=True) return offset, linear_coefficients, quadratic_coefficients
[ "def", "_parse_quadratic_expression", "(", "expression", ",", "expanded", "=", "False", ")", ":", "linear_coefficients", "=", "{", "}", "quadratic_coefficients", "=", "{", "}", "offset", "=", "0", "if", "expression", ".", "is_Number", ":", "# Constant expression, ...
Parse a quadratic expression. It is assumed that the expression is known to be quadratic or linear. The 'expanded' parameter tells whether the expression has already been expanded. If it hasn't the parsing might fail and will expand the expression and try again.
[ "Parse", "a", "quadratic", "expression", ".", "It", "is", "assumed", "that", "the", "expression", "is", "known", "to", "be", "quadratic", "or", "linear", "." ]
13673ac26f6b3ba37a2ef392489722c52e3c5ff1
https://github.com/biosustain/optlang/blob/13673ac26f6b3ba37a2ef392489722c52e3c5ff1/optlang/expression_parsing.py#L101-L158
train
34,034
biosustain/optlang
optlang/interface.py
Variable.clone
def clone(cls, variable, **kwargs): """ Make a copy of another variable. The variable being copied can be of the same type or belong to a different solver interface. Example ---------- >>> var_copy = Variable.clone(old_var) """ return cls(variable.name, lb=variable.lb, ub=variable.ub, type=variable.type, **kwargs)
python
def clone(cls, variable, **kwargs): """ Make a copy of another variable. The variable being copied can be of the same type or belong to a different solver interface. Example ---------- >>> var_copy = Variable.clone(old_var) """ return cls(variable.name, lb=variable.lb, ub=variable.ub, type=variable.type, **kwargs)
[ "def", "clone", "(", "cls", ",", "variable", ",", "*", "*", "kwargs", ")", ":", "return", "cls", "(", "variable", ".", "name", ",", "lb", "=", "variable", ".", "lb", ",", "ub", "=", "variable", ".", "ub", ",", "type", "=", "variable", ".", "type"...
Make a copy of another variable. The variable being copied can be of the same type or belong to a different solver interface. Example ---------- >>> var_copy = Variable.clone(old_var)
[ "Make", "a", "copy", "of", "another", "variable", ".", "The", "variable", "being", "copied", "can", "be", "of", "the", "same", "type", "or", "belong", "to", "a", "different", "solver", "interface", "." ]
13673ac26f6b3ba37a2ef392489722c52e3c5ff1
https://github.com/biosustain/optlang/blob/13673ac26f6b3ba37a2ef392489722c52e3c5ff1/optlang/interface.py#L149-L158
train
34,035
biosustain/optlang
optlang/interface.py
Variable.set_bounds
def set_bounds(self, lb, ub): """ Change the lower and upper bounds of a variable. """ if lb is not None and ub is not None and lb > ub: raise ValueError( "The provided lower bound {} is larger than the provided upper bound {}".format(lb, ub) ) self._lb = lb self._ub = ub if self.problem is not None: self.problem._pending_modifications.var_lb.append((self, lb)) self.problem._pending_modifications.var_ub.append((self, ub))
python
def set_bounds(self, lb, ub): """ Change the lower and upper bounds of a variable. """ if lb is not None and ub is not None and lb > ub: raise ValueError( "The provided lower bound {} is larger than the provided upper bound {}".format(lb, ub) ) self._lb = lb self._ub = ub if self.problem is not None: self.problem._pending_modifications.var_lb.append((self, lb)) self.problem._pending_modifications.var_ub.append((self, ub))
[ "def", "set_bounds", "(", "self", ",", "lb", ",", "ub", ")", ":", "if", "lb", "is", "not", "None", "and", "ub", "is", "not", "None", "and", "lb", ">", "ub", ":", "raise", "ValueError", "(", "\"The provided lower bound {} is larger than the provided upper bound...
Change the lower and upper bounds of a variable.
[ "Change", "the", "lower", "and", "upper", "bounds", "of", "a", "variable", "." ]
13673ac26f6b3ba37a2ef392489722c52e3c5ff1
https://github.com/biosustain/optlang/blob/13673ac26f6b3ba37a2ef392489722c52e3c5ff1/optlang/interface.py#L229-L241
train
34,036
biosustain/optlang
optlang/interface.py
Variable.to_json
def to_json(self): """ Returns a json-compatible object from the Variable that can be saved using the json module. Example -------- >>> import json >>> with open("path_to_file.json", "w") as outfile: >>> json.dump(var.to_json(), outfile) """ json_obj = { "name": self.name, "lb": self.lb, "ub": self.ub, "type": self.type } return json_obj
python
def to_json(self): """ Returns a json-compatible object from the Variable that can be saved using the json module. Example -------- >>> import json >>> with open("path_to_file.json", "w") as outfile: >>> json.dump(var.to_json(), outfile) """ json_obj = { "name": self.name, "lb": self.lb, "ub": self.ub, "type": self.type } return json_obj
[ "def", "to_json", "(", "self", ")", ":", "json_obj", "=", "{", "\"name\"", ":", "self", ".", "name", ",", "\"lb\"", ":", "self", ".", "lb", ",", "\"ub\"", ":", "self", ".", "ub", ",", "\"type\"", ":", "self", ".", "type", "}", "return", "json_obj" ...
Returns a json-compatible object from the Variable that can be saved using the json module. Example -------- >>> import json >>> with open("path_to_file.json", "w") as outfile: >>> json.dump(var.to_json(), outfile)
[ "Returns", "a", "json", "-", "compatible", "object", "from", "the", "Variable", "that", "can", "be", "saved", "using", "the", "json", "module", "." ]
13673ac26f6b3ba37a2ef392489722c52e3c5ff1
https://github.com/biosustain/optlang/blob/13673ac26f6b3ba37a2ef392489722c52e3c5ff1/optlang/interface.py#L317-L333
train
34,037
biosustain/optlang
optlang/interface.py
Constraint.clone
def clone(cls, constraint, model=None, **kwargs): """ Make a copy of another constraint. The constraint being copied can be of the same type or belong to a different solver interface. Parameters ---------- constraint: interface.Constraint (or subclass) The constraint to copy model: Model or None The variables of the new constraint will be taken from this model. If None, new variables will be constructed. Example ---------- >>> const_copy = Constraint.clone(old_constraint) """ return cls(cls._substitute_variables(constraint, model=model), lb=constraint.lb, ub=constraint.ub, indicator_variable=constraint.indicator_variable, active_when=constraint.active_when, name=constraint.name, sloppy=True, **kwargs)
python
def clone(cls, constraint, model=None, **kwargs): """ Make a copy of another constraint. The constraint being copied can be of the same type or belong to a different solver interface. Parameters ---------- constraint: interface.Constraint (or subclass) The constraint to copy model: Model or None The variables of the new constraint will be taken from this model. If None, new variables will be constructed. Example ---------- >>> const_copy = Constraint.clone(old_constraint) """ return cls(cls._substitute_variables(constraint, model=model), lb=constraint.lb, ub=constraint.ub, indicator_variable=constraint.indicator_variable, active_when=constraint.active_when, name=constraint.name, sloppy=True, **kwargs)
[ "def", "clone", "(", "cls", ",", "constraint", ",", "model", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "cls", "(", "cls", ".", "_substitute_variables", "(", "constraint", ",", "model", "=", "model", ")", ",", "lb", "=", "constraint", ...
Make a copy of another constraint. The constraint being copied can be of the same type or belong to a different solver interface. Parameters ---------- constraint: interface.Constraint (or subclass) The constraint to copy model: Model or None The variables of the new constraint will be taken from this model. If None, new variables will be constructed. Example ---------- >>> const_copy = Constraint.clone(old_constraint)
[ "Make", "a", "copy", "of", "another", "constraint", ".", "The", "constraint", "being", "copied", "can", "be", "of", "the", "same", "type", "or", "belong", "to", "a", "different", "solver", "interface", "." ]
13673ac26f6b3ba37a2ef392489722c52e3c5ff1
https://github.com/biosustain/optlang/blob/13673ac26f6b3ba37a2ef392489722c52e3c5ff1/optlang/interface.py#L652-L671
train
34,038
biosustain/optlang
optlang/interface.py
Constraint.to_json
def to_json(self): """ Returns a json-compatible object from the constraint that can be saved using the json module. Example -------- >>> import json >>> with open("path_to_file.json", "w") as outfile: >>> json.dump(constraint.to_json(), outfile) """ if self.indicator_variable is None: indicator = None else: indicator = self.indicator_variable.name json_obj = { "name": self.name, "expression": expr_to_json(self.expression), "lb": self.lb, "ub": self.ub, "indicator_variable": indicator, "active_when": self.active_when } return json_obj
python
def to_json(self): """ Returns a json-compatible object from the constraint that can be saved using the json module. Example -------- >>> import json >>> with open("path_to_file.json", "w") as outfile: >>> json.dump(constraint.to_json(), outfile) """ if self.indicator_variable is None: indicator = None else: indicator = self.indicator_variable.name json_obj = { "name": self.name, "expression": expr_to_json(self.expression), "lb": self.lb, "ub": self.ub, "indicator_variable": indicator, "active_when": self.active_when } return json_obj
[ "def", "to_json", "(", "self", ")", ":", "if", "self", ".", "indicator_variable", "is", "None", ":", "indicator", "=", "None", "else", ":", "indicator", "=", "self", ".", "indicator_variable", ".", "name", "json_obj", "=", "{", "\"name\"", ":", "self", "...
Returns a json-compatible object from the constraint that can be saved using the json module. Example -------- >>> import json >>> with open("path_to_file.json", "w") as outfile: >>> json.dump(constraint.to_json(), outfile)
[ "Returns", "a", "json", "-", "compatible", "object", "from", "the", "constraint", "that", "can", "be", "saved", "using", "the", "json", "module", "." ]
13673ac26f6b3ba37a2ef392489722c52e3c5ff1
https://github.com/biosustain/optlang/blob/13673ac26f6b3ba37a2ef392489722c52e3c5ff1/optlang/interface.py#L780-L802
train
34,039
biosustain/optlang
optlang/interface.py
Objective.clone
def clone(cls, objective, model=None, **kwargs): """ Make a copy of an objective. The objective being copied can be of the same type or belong to a different solver interface. Example ---------- >>> new_objective = Objective.clone(old_objective) """ return cls(cls._substitute_variables(objective, model=model), name=objective.name, direction=objective.direction, sloppy=True, **kwargs)
python
def clone(cls, objective, model=None, **kwargs): """ Make a copy of an objective. The objective being copied can be of the same type or belong to a different solver interface. Example ---------- >>> new_objective = Objective.clone(old_objective) """ return cls(cls._substitute_variables(objective, model=model), name=objective.name, direction=objective.direction, sloppy=True, **kwargs)
[ "def", "clone", "(", "cls", ",", "objective", ",", "model", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "cls", "(", "cls", ".", "_substitute_variables", "(", "objective", ",", "model", "=", "model", ")", ",", "name", "=", "objective", "...
Make a copy of an objective. The objective being copied can be of the same type or belong to a different solver interface. Example ---------- >>> new_objective = Objective.clone(old_objective)
[ "Make", "a", "copy", "of", "an", "objective", ".", "The", "objective", "being", "copied", "can", "be", "of", "the", "same", "type", "or", "belong", "to", "a", "different", "solver", "interface", "." ]
13673ac26f6b3ba37a2ef392489722c52e3c5ff1
https://github.com/biosustain/optlang/blob/13673ac26f6b3ba37a2ef392489722c52e3c5ff1/optlang/interface.py#L857-L867
train
34,040
biosustain/optlang
optlang/interface.py
Objective.to_json
def to_json(self): """ Returns a json-compatible object from the objective that can be saved using the json module. Example -------- >>> import json >>> with open("path_to_file.json", "w") as outfile: >>> json.dump(obj.to_json(), outfile) """ json_obj = { "name": self.name, "expression": expr_to_json(self.expression), "direction": self.direction } return json_obj
python
def to_json(self): """ Returns a json-compatible object from the objective that can be saved using the json module. Example -------- >>> import json >>> with open("path_to_file.json", "w") as outfile: >>> json.dump(obj.to_json(), outfile) """ json_obj = { "name": self.name, "expression": expr_to_json(self.expression), "direction": self.direction } return json_obj
[ "def", "to_json", "(", "self", ")", ":", "json_obj", "=", "{", "\"name\"", ":", "self", ".", "name", ",", "\"expression\"", ":", "expr_to_json", "(", "self", ".", "expression", ")", ",", "\"direction\"", ":", "self", ".", "direction", "}", "return", "jso...
Returns a json-compatible object from the objective that can be saved using the json module. Example -------- >>> import json >>> with open("path_to_file.json", "w") as outfile: >>> json.dump(obj.to_json(), outfile)
[ "Returns", "a", "json", "-", "compatible", "object", "from", "the", "objective", "that", "can", "be", "saved", "using", "the", "json", "module", "." ]
13673ac26f6b3ba37a2ef392489722c52e3c5ff1
https://github.com/biosustain/optlang/blob/13673ac26f6b3ba37a2ef392489722c52e3c5ff1/optlang/interface.py#L921-L936
train
34,041
biosustain/optlang
optlang/interface.py
Objective.from_json
def from_json(cls, json_obj, variables=None): """ Constructs an Objective from the provided json-object. Example -------- >>> import json >>> with open("path_to_file.json") as infile: >>> obj = Objective.from_json(json.load(infile)) """ if variables is None: variables = {} expression = parse_expr(json_obj["expression"], variables) return cls( expression, direction=json_obj["direction"], name=json_obj["name"] )
python
def from_json(cls, json_obj, variables=None): """ Constructs an Objective from the provided json-object. Example -------- >>> import json >>> with open("path_to_file.json") as infile: >>> obj = Objective.from_json(json.load(infile)) """ if variables is None: variables = {} expression = parse_expr(json_obj["expression"], variables) return cls( expression, direction=json_obj["direction"], name=json_obj["name"] )
[ "def", "from_json", "(", "cls", ",", "json_obj", ",", "variables", "=", "None", ")", ":", "if", "variables", "is", "None", ":", "variables", "=", "{", "}", "expression", "=", "parse_expr", "(", "json_obj", "[", "\"expression\"", "]", ",", "variables", ")...
Constructs an Objective from the provided json-object. Example -------- >>> import json >>> with open("path_to_file.json") as infile: >>> obj = Objective.from_json(json.load(infile))
[ "Constructs", "an", "Objective", "from", "the", "provided", "json", "-", "object", "." ]
13673ac26f6b3ba37a2ef392489722c52e3c5ff1
https://github.com/biosustain/optlang/blob/13673ac26f6b3ba37a2ef392489722c52e3c5ff1/optlang/interface.py#L939-L956
train
34,042
biosustain/optlang
optlang/interface.py
Model.clone
def clone(cls, model, use_json=True, use_lp=False): """ Make a copy of a model. The model being copied can be of the same type or belong to a different solver interface. This is the preferred way of copying models. Example ---------- >>> new_model = Model.clone(old_model) """ model.update() interface = sys.modules[cls.__module__] if use_lp: warnings.warn("Cloning with LP formats can change variable and constraint ID's.") new_model = cls.from_lp(model.to_lp()) new_model.configuration = interface.Configuration.clone(model.configuration, problem=new_model) return new_model if use_json: new_model = cls.from_json(model.to_json()) new_model.configuration = interface.Configuration.clone(model.configuration, problem=new_model) return new_model new_model = cls() for variable in model.variables: new_variable = interface.Variable.clone(variable) new_model._add_variable(new_variable) for constraint in model.constraints: new_constraint = interface.Constraint.clone(constraint, model=new_model) new_model._add_constraint(new_constraint) if model.objective is not None: new_model.objective = interface.Objective.clone(model.objective, model=new_model) new_model.configuration = interface.Configuration.clone(model.configuration, problem=new_model) return new_model
python
def clone(cls, model, use_json=True, use_lp=False): """ Make a copy of a model. The model being copied can be of the same type or belong to a different solver interface. This is the preferred way of copying models. Example ---------- >>> new_model = Model.clone(old_model) """ model.update() interface = sys.modules[cls.__module__] if use_lp: warnings.warn("Cloning with LP formats can change variable and constraint ID's.") new_model = cls.from_lp(model.to_lp()) new_model.configuration = interface.Configuration.clone(model.configuration, problem=new_model) return new_model if use_json: new_model = cls.from_json(model.to_json()) new_model.configuration = interface.Configuration.clone(model.configuration, problem=new_model) return new_model new_model = cls() for variable in model.variables: new_variable = interface.Variable.clone(variable) new_model._add_variable(new_variable) for constraint in model.constraints: new_constraint = interface.Constraint.clone(constraint, model=new_model) new_model._add_constraint(new_constraint) if model.objective is not None: new_model.objective = interface.Objective.clone(model.objective, model=new_model) new_model.configuration = interface.Configuration.clone(model.configuration, problem=new_model) return new_model
[ "def", "clone", "(", "cls", ",", "model", ",", "use_json", "=", "True", ",", "use_lp", "=", "False", ")", ":", "model", ".", "update", "(", ")", "interface", "=", "sys", ".", "modules", "[", "cls", ".", "__module__", "]", "if", "use_lp", ":", "warn...
Make a copy of a model. The model being copied can be of the same type or belong to a different solver interface. This is the preferred way of copying models. Example ---------- >>> new_model = Model.clone(old_model)
[ "Make", "a", "copy", "of", "a", "model", ".", "The", "model", "being", "copied", "can", "be", "of", "the", "same", "type", "or", "belong", "to", "a", "different", "solver", "interface", ".", "This", "is", "the", "preferred", "way", "of", "copying", "mo...
13673ac26f6b3ba37a2ef392489722c52e3c5ff1
https://github.com/biosustain/optlang/blob/13673ac26f6b3ba37a2ef392489722c52e3c5ff1/optlang/interface.py#L1107-L1140
train
34,043
biosustain/optlang
optlang/interface.py
Model.add
def add(self, stuff, sloppy=False): """Add variables and constraints. Parameters ---------- stuff : iterable, Variable, Constraint Either an iterable containing variables and constraints or a single variable or constraint. sloppy : bool Check constraints for variables that are not part of the model yet. Returns ------- None """ if self._pending_modifications.toggle == 'remove': self.update() self._pending_modifications.toggle = 'add' if isinstance(stuff, collections.Iterable): for elem in stuff: self.add(elem, sloppy=sloppy) elif isinstance(stuff, Variable): if stuff.__module__ != self.__module__: raise TypeError("Cannot add Variable %s of interface type %s to model of type %s." % ( stuff, stuff.__module__, self.__module__)) self._pending_modifications.add_var.append(stuff) elif isinstance(stuff, Constraint): if stuff.__module__ != self.__module__: raise TypeError("Cannot add Constraint %s of interface type %s to model of type %s." % ( stuff, stuff.__module__, self.__module__)) if sloppy is True: self._pending_modifications.add_constr_sloppy.append(stuff) else: self._pending_modifications.add_constr.append(stuff) else: raise TypeError("Cannot add %s. It is neither a Variable, or Constraint." % stuff)
python
def add(self, stuff, sloppy=False): """Add variables and constraints. Parameters ---------- stuff : iterable, Variable, Constraint Either an iterable containing variables and constraints or a single variable or constraint. sloppy : bool Check constraints for variables that are not part of the model yet. Returns ------- None """ if self._pending_modifications.toggle == 'remove': self.update() self._pending_modifications.toggle = 'add' if isinstance(stuff, collections.Iterable): for elem in stuff: self.add(elem, sloppy=sloppy) elif isinstance(stuff, Variable): if stuff.__module__ != self.__module__: raise TypeError("Cannot add Variable %s of interface type %s to model of type %s." % ( stuff, stuff.__module__, self.__module__)) self._pending_modifications.add_var.append(stuff) elif isinstance(stuff, Constraint): if stuff.__module__ != self.__module__: raise TypeError("Cannot add Constraint %s of interface type %s to model of type %s." % ( stuff, stuff.__module__, self.__module__)) if sloppy is True: self._pending_modifications.add_constr_sloppy.append(stuff) else: self._pending_modifications.add_constr.append(stuff) else: raise TypeError("Cannot add %s. It is neither a Variable, or Constraint." % stuff)
[ "def", "add", "(", "self", ",", "stuff", ",", "sloppy", "=", "False", ")", ":", "if", "self", ".", "_pending_modifications", ".", "toggle", "==", "'remove'", ":", "self", ".", "update", "(", ")", "self", ".", "_pending_modifications", ".", "toggle", "=",...
Add variables and constraints. Parameters ---------- stuff : iterable, Variable, Constraint Either an iterable containing variables and constraints or a single variable or constraint. sloppy : bool Check constraints for variables that are not part of the model yet. Returns ------- None
[ "Add", "variables", "and", "constraints", "." ]
13673ac26f6b3ba37a2ef392489722c52e3c5ff1
https://github.com/biosustain/optlang/blob/13673ac26f6b3ba37a2ef392489722c52e3c5ff1/optlang/interface.py#L1340-L1375
train
34,044
biosustain/optlang
optlang/interface.py
Model.remove
def remove(self, stuff): """Remove variables and constraints. Parameters ---------- stuff : iterable, str, Variable, Constraint Either an iterable containing variables and constraints to be removed from the model or a single variable or contstraint (or their names). Returns ------- None """ if self._pending_modifications.toggle == 'add': self.update() self._pending_modifications.toggle = 'remove' if isinstance(stuff, str): try: variable = self.variables[stuff] self._pending_modifications.rm_var.append(variable) except KeyError: try: constraint = self.constraints[stuff] self._pending_modifications.rm_constr.append(constraint) except KeyError: raise LookupError( "%s is neither a variable nor a constraint in the current solver instance." % stuff) elif isinstance(stuff, Variable): self._pending_modifications.rm_var.append(stuff) elif isinstance(stuff, Constraint): self._pending_modifications.rm_constr.append(stuff) elif isinstance(stuff, collections.Iterable): for elem in stuff: self.remove(elem) elif isinstance(stuff, Objective): raise TypeError( "Cannot remove objective %s. Use model.objective = Objective(...) to change the current objective." % stuff) else: raise TypeError( "Cannot remove %s. It neither a variable or constraint." % stuff)
python
def remove(self, stuff): """Remove variables and constraints. Parameters ---------- stuff : iterable, str, Variable, Constraint Either an iterable containing variables and constraints to be removed from the model or a single variable or contstraint (or their names). Returns ------- None """ if self._pending_modifications.toggle == 'add': self.update() self._pending_modifications.toggle = 'remove' if isinstance(stuff, str): try: variable = self.variables[stuff] self._pending_modifications.rm_var.append(variable) except KeyError: try: constraint = self.constraints[stuff] self._pending_modifications.rm_constr.append(constraint) except KeyError: raise LookupError( "%s is neither a variable nor a constraint in the current solver instance." % stuff) elif isinstance(stuff, Variable): self._pending_modifications.rm_var.append(stuff) elif isinstance(stuff, Constraint): self._pending_modifications.rm_constr.append(stuff) elif isinstance(stuff, collections.Iterable): for elem in stuff: self.remove(elem) elif isinstance(stuff, Objective): raise TypeError( "Cannot remove objective %s. Use model.objective = Objective(...) to change the current objective." % stuff) else: raise TypeError( "Cannot remove %s. It neither a variable or constraint." % stuff)
[ "def", "remove", "(", "self", ",", "stuff", ")", ":", "if", "self", ".", "_pending_modifications", ".", "toggle", "==", "'add'", ":", "self", ".", "update", "(", ")", "self", ".", "_pending_modifications", ".", "toggle", "=", "'remove'", "if", "isinstance"...
Remove variables and constraints. Parameters ---------- stuff : iterable, str, Variable, Constraint Either an iterable containing variables and constraints to be removed from the model or a single variable or contstraint (or their names). Returns ------- None
[ "Remove", "variables", "and", "constraints", "." ]
13673ac26f6b3ba37a2ef392489722c52e3c5ff1
https://github.com/biosustain/optlang/blob/13673ac26f6b3ba37a2ef392489722c52e3c5ff1/optlang/interface.py#L1377-L1415
train
34,045
biosustain/optlang
optlang/interface.py
Model.update
def update(self, callback=int): """Process all pending model modifications.""" # print(self._pending_modifications) add_var = self._pending_modifications.add_var if len(add_var) > 0: self._add_variables(add_var) self._pending_modifications.add_var = [] callback() add_constr = self._pending_modifications.add_constr if len(add_constr) > 0: self._add_constraints(add_constr) self._pending_modifications.add_constr = [] add_constr_sloppy = self._pending_modifications.add_constr_sloppy if len(add_constr_sloppy) > 0: self._add_constraints(add_constr_sloppy, sloppy=True) self._pending_modifications.add_constr_sloppy = [] var_lb = self._pending_modifications.var_lb var_ub = self._pending_modifications.var_ub if len(var_lb) > 0 or len(var_ub) > 0: self._set_variable_bounds_on_problem(var_lb, var_ub) self._pending_modifications.var_lb = [] self._pending_modifications.var_ub = [] rm_var = self._pending_modifications.rm_var if len(rm_var) > 0: self._remove_variables(rm_var) self._pending_modifications.rm_var = [] callback() rm_constr = self._pending_modifications.rm_constr if len(rm_constr) > 0: self._remove_constraints(rm_constr) self._pending_modifications.rm_constr = []
python
def update(self, callback=int): """Process all pending model modifications.""" # print(self._pending_modifications) add_var = self._pending_modifications.add_var if len(add_var) > 0: self._add_variables(add_var) self._pending_modifications.add_var = [] callback() add_constr = self._pending_modifications.add_constr if len(add_constr) > 0: self._add_constraints(add_constr) self._pending_modifications.add_constr = [] add_constr_sloppy = self._pending_modifications.add_constr_sloppy if len(add_constr_sloppy) > 0: self._add_constraints(add_constr_sloppy, sloppy=True) self._pending_modifications.add_constr_sloppy = [] var_lb = self._pending_modifications.var_lb var_ub = self._pending_modifications.var_ub if len(var_lb) > 0 or len(var_ub) > 0: self._set_variable_bounds_on_problem(var_lb, var_ub) self._pending_modifications.var_lb = [] self._pending_modifications.var_ub = [] rm_var = self._pending_modifications.rm_var if len(rm_var) > 0: self._remove_variables(rm_var) self._pending_modifications.rm_var = [] callback() rm_constr = self._pending_modifications.rm_constr if len(rm_constr) > 0: self._remove_constraints(rm_constr) self._pending_modifications.rm_constr = []
[ "def", "update", "(", "self", ",", "callback", "=", "int", ")", ":", "# print(self._pending_modifications)", "add_var", "=", "self", ".", "_pending_modifications", ".", "add_var", "if", "len", "(", "add_var", ")", ">", "0", ":", "self", ".", "_add_variables", ...
Process all pending model modifications.
[ "Process", "all", "pending", "model", "modifications", "." ]
13673ac26f6b3ba37a2ef392489722c52e3c5ff1
https://github.com/biosustain/optlang/blob/13673ac26f6b3ba37a2ef392489722c52e3c5ff1/optlang/interface.py#L1417-L1452
train
34,046
biosustain/optlang
optlang/interface.py
Model.optimize
def optimize(self): """ Solve the optimization problem using the relevant solver back-end. The status returned by this method tells whether an optimal solution was found, if the problem is infeasible etc. Consult optlang.statuses for more elaborate explanations of each status. The objective value can be accessed from 'model.objective.value', while the solution can be retrieved by 'model.primal_values'. Returns ------- status: str Solution status. """ self.update() status = self._optimize() if status != OPTIMAL and self.configuration.presolve == "auto": self.configuration.presolve = True status = self._optimize() self.configuration.presolve = "auto" self._status = status return status
python
def optimize(self): """ Solve the optimization problem using the relevant solver back-end. The status returned by this method tells whether an optimal solution was found, if the problem is infeasible etc. Consult optlang.statuses for more elaborate explanations of each status. The objective value can be accessed from 'model.objective.value', while the solution can be retrieved by 'model.primal_values'. Returns ------- status: str Solution status. """ self.update() status = self._optimize() if status != OPTIMAL and self.configuration.presolve == "auto": self.configuration.presolve = True status = self._optimize() self.configuration.presolve = "auto" self._status = status return status
[ "def", "optimize", "(", "self", ")", ":", "self", ".", "update", "(", ")", "status", "=", "self", ".", "_optimize", "(", ")", "if", "status", "!=", "OPTIMAL", "and", "self", ".", "configuration", ".", "presolve", "==", "\"auto\"", ":", "self", ".", "...
Solve the optimization problem using the relevant solver back-end. The status returned by this method tells whether an optimal solution was found, if the problem is infeasible etc. Consult optlang.statuses for more elaborate explanations of each status. The objective value can be accessed from 'model.objective.value', while the solution can be retrieved by 'model.primal_values'. Returns ------- status: str Solution status.
[ "Solve", "the", "optimization", "problem", "using", "the", "relevant", "solver", "back", "-", "end", ".", "The", "status", "returned", "by", "this", "method", "tells", "whether", "an", "optimal", "solution", "was", "found", "if", "the", "problem", "is", "inf...
13673ac26f6b3ba37a2ef392489722c52e3c5ff1
https://github.com/biosustain/optlang/blob/13673ac26f6b3ba37a2ef392489722c52e3c5ff1/optlang/interface.py#L1454-L1476
train
34,047
biosustain/optlang
optlang/interface.py
Model.to_json
def to_json(self): """ Returns a json-compatible object from the model that can be saved using the json module. Variables, constraints and objective contained in the model will be saved. Configurations will not be saved. Example -------- >>> import json >>> with open("path_to_file.json", "w") as outfile: >>> json.dump(model.to_json(), outfile) """ json_obj = { "name": self.name, "variables": [var.to_json() for var in self.variables], "constraints": [const.to_json() for const in self.constraints], "objective": self.objective.to_json() } return json_obj
python
def to_json(self): """ Returns a json-compatible object from the model that can be saved using the json module. Variables, constraints and objective contained in the model will be saved. Configurations will not be saved. Example -------- >>> import json >>> with open("path_to_file.json", "w") as outfile: >>> json.dump(model.to_json(), outfile) """ json_obj = { "name": self.name, "variables": [var.to_json() for var in self.variables], "constraints": [const.to_json() for const in self.constraints], "objective": self.objective.to_json() } return json_obj
[ "def", "to_json", "(", "self", ")", ":", "json_obj", "=", "{", "\"name\"", ":", "self", ".", "name", ",", "\"variables\"", ":", "[", "var", ".", "to_json", "(", ")", "for", "var", "in", "self", ".", "variables", "]", ",", "\"constraints\"", ":", "[",...
Returns a json-compatible object from the model that can be saved using the json module. Variables, constraints and objective contained in the model will be saved. Configurations will not be saved. Example -------- >>> import json >>> with open("path_to_file.json", "w") as outfile: >>> json.dump(model.to_json(), outfile)
[ "Returns", "a", "json", "-", "compatible", "object", "from", "the", "model", "that", "can", "be", "saved", "using", "the", "json", "module", ".", "Variables", "constraints", "and", "objective", "contained", "in", "the", "model", "will", "be", "saved", ".", ...
13673ac26f6b3ba37a2ef392489722c52e3c5ff1
https://github.com/biosustain/optlang/blob/13673ac26f6b3ba37a2ef392489722c52e3c5ff1/optlang/interface.py#L1556-L1574
train
34,048
biosustain/optlang
optlang/util.py
solve_with_glpsol
def solve_with_glpsol(glp_prob): """Solve glpk problem with glpsol commandline solver. Mainly for testing purposes. # Examples # -------- # >>> problem = glp_create_prob() # ... glp_read_lp(problem, None, "../tests/data/model.lp") # ... solution = solve_with_glpsol(problem) # ... print 'asdf' # 'asdf' # >>> print solution # 0.839784 # Returns # ------- # dict # A dictionary containing the objective value (key ='objval') # and variable primals. """ from swiglpk import glp_get_row_name, glp_get_col_name, glp_write_lp, glp_get_num_rows, glp_get_num_cols row_ids = [glp_get_row_name(glp_prob, i) for i in range(1, glp_get_num_rows(glp_prob) + 1)] col_ids = [glp_get_col_name(glp_prob, i) for i in range(1, glp_get_num_cols(glp_prob) + 1)] with tempfile.NamedTemporaryFile(suffix=".lp", delete=True) as tmp_file: tmp_file_name = tmp_file.name glp_write_lp(glp_prob, None, tmp_file_name) cmd = ['glpsol', '--lp', tmp_file_name, '-w', tmp_file_name + '.sol', '--log', '/dev/null'] term = check_output(cmd) log.info(term) try: with open(tmp_file_name + '.sol') as sol_handle: # print sol_handle.read() solution = dict() for i, line in enumerate(sol_handle.readlines()): if i <= 1 or line == '\n': pass elif i <= len(row_ids): solution[row_ids[i - 2]] = line.strip().split(' ') elif i <= len(row_ids) + len(col_ids) + 1: solution[col_ids[i - 2 - len(row_ids)]] = line.strip().split(' ') else: print(i) print(line) raise Exception("Argggh!") finally: os.remove(tmp_file_name + ".sol") return solution
python
def solve_with_glpsol(glp_prob): """Solve glpk problem with glpsol commandline solver. Mainly for testing purposes. # Examples # -------- # >>> problem = glp_create_prob() # ... glp_read_lp(problem, None, "../tests/data/model.lp") # ... solution = solve_with_glpsol(problem) # ... print 'asdf' # 'asdf' # >>> print solution # 0.839784 # Returns # ------- # dict # A dictionary containing the objective value (key ='objval') # and variable primals. """ from swiglpk import glp_get_row_name, glp_get_col_name, glp_write_lp, glp_get_num_rows, glp_get_num_cols row_ids = [glp_get_row_name(glp_prob, i) for i in range(1, glp_get_num_rows(glp_prob) + 1)] col_ids = [glp_get_col_name(glp_prob, i) for i in range(1, glp_get_num_cols(glp_prob) + 1)] with tempfile.NamedTemporaryFile(suffix=".lp", delete=True) as tmp_file: tmp_file_name = tmp_file.name glp_write_lp(glp_prob, None, tmp_file_name) cmd = ['glpsol', '--lp', tmp_file_name, '-w', tmp_file_name + '.sol', '--log', '/dev/null'] term = check_output(cmd) log.info(term) try: with open(tmp_file_name + '.sol') as sol_handle: # print sol_handle.read() solution = dict() for i, line in enumerate(sol_handle.readlines()): if i <= 1 or line == '\n': pass elif i <= len(row_ids): solution[row_ids[i - 2]] = line.strip().split(' ') elif i <= len(row_ids) + len(col_ids) + 1: solution[col_ids[i - 2 - len(row_ids)]] = line.strip().split(' ') else: print(i) print(line) raise Exception("Argggh!") finally: os.remove(tmp_file_name + ".sol") return solution
[ "def", "solve_with_glpsol", "(", "glp_prob", ")", ":", "from", "swiglpk", "import", "glp_get_row_name", ",", "glp_get_col_name", ",", "glp_write_lp", ",", "glp_get_num_rows", ",", "glp_get_num_cols", "row_ids", "=", "[", "glp_get_row_name", "(", "glp_prob", ",", "i"...
Solve glpk problem with glpsol commandline solver. Mainly for testing purposes. # Examples # -------- # >>> problem = glp_create_prob() # ... glp_read_lp(problem, None, "../tests/data/model.lp") # ... solution = solve_with_glpsol(problem) # ... print 'asdf' # 'asdf' # >>> print solution # 0.839784 # Returns # ------- # dict # A dictionary containing the objective value (key ='objval') # and variable primals.
[ "Solve", "glpk", "problem", "with", "glpsol", "commandline", "solver", ".", "Mainly", "for", "testing", "purposes", "." ]
13673ac26f6b3ba37a2ef392489722c52e3c5ff1
https://github.com/biosustain/optlang/blob/13673ac26f6b3ba37a2ef392489722c52e3c5ff1/optlang/util.py#L33-L83
train
34,049
biosustain/optlang
optlang/util.py
glpk_read_cplex
def glpk_read_cplex(path): """Reads cplex file and returns glpk problem. Returns ------- glp_prob A glpk problems (same type as returned by glp_create_prob) """ from swiglpk import glp_create_prob, glp_read_lp problem = glp_create_prob() glp_read_lp(problem, None, path) return problem
python
def glpk_read_cplex(path): """Reads cplex file and returns glpk problem. Returns ------- glp_prob A glpk problems (same type as returned by glp_create_prob) """ from swiglpk import glp_create_prob, glp_read_lp problem = glp_create_prob() glp_read_lp(problem, None, path) return problem
[ "def", "glpk_read_cplex", "(", "path", ")", ":", "from", "swiglpk", "import", "glp_create_prob", ",", "glp_read_lp", "problem", "=", "glp_create_prob", "(", ")", "glp_read_lp", "(", "problem", ",", "None", ",", "path", ")", "return", "problem" ]
Reads cplex file and returns glpk problem. Returns ------- glp_prob A glpk problems (same type as returned by glp_create_prob)
[ "Reads", "cplex", "file", "and", "returns", "glpk", "problem", "." ]
13673ac26f6b3ba37a2ef392489722c52e3c5ff1
https://github.com/biosustain/optlang/blob/13673ac26f6b3ba37a2ef392489722c52e3c5ff1/optlang/util.py#L86-L98
train
34,050
biosustain/optlang
optlang/util.py
expr_to_json
def expr_to_json(expr): """ Converts a Sympy expression to a json-compatible tree-structure. """ if isinstance(expr, symbolics.Mul): return {"type": "Mul", "args": [expr_to_json(arg) for arg in expr.args]} elif isinstance(expr, symbolics.Add): return {"type": "Add", "args": [expr_to_json(arg) for arg in expr.args]} elif isinstance(expr, symbolics.Symbol): return {"type": "Symbol", "name": expr.name} elif isinstance(expr, symbolics.Pow): return {"type": "Pow", "args": [expr_to_json(arg) for arg in expr.args]} elif isinstance(expr, (float, int)): return {"type": "Number", "value": expr} elif isinstance(expr, symbolics.Real): return {"type": "Number", "value": float(expr)} elif isinstance(expr, symbolics.Integer): return {"type": "Number", "value": int(expr)} else: raise NotImplementedError("Type not implemented: " + str(type(expr)))
python
def expr_to_json(expr): """ Converts a Sympy expression to a json-compatible tree-structure. """ if isinstance(expr, symbolics.Mul): return {"type": "Mul", "args": [expr_to_json(arg) for arg in expr.args]} elif isinstance(expr, symbolics.Add): return {"type": "Add", "args": [expr_to_json(arg) for arg in expr.args]} elif isinstance(expr, symbolics.Symbol): return {"type": "Symbol", "name": expr.name} elif isinstance(expr, symbolics.Pow): return {"type": "Pow", "args": [expr_to_json(arg) for arg in expr.args]} elif isinstance(expr, (float, int)): return {"type": "Number", "value": expr} elif isinstance(expr, symbolics.Real): return {"type": "Number", "value": float(expr)} elif isinstance(expr, symbolics.Integer): return {"type": "Number", "value": int(expr)} else: raise NotImplementedError("Type not implemented: " + str(type(expr)))
[ "def", "expr_to_json", "(", "expr", ")", ":", "if", "isinstance", "(", "expr", ",", "symbolics", ".", "Mul", ")", ":", "return", "{", "\"type\"", ":", "\"Mul\"", ",", "\"args\"", ":", "[", "expr_to_json", "(", "arg", ")", "for", "arg", "in", "expr", ...
Converts a Sympy expression to a json-compatible tree-structure.
[ "Converts", "a", "Sympy", "expression", "to", "a", "json", "-", "compatible", "tree", "-", "structure", "." ]
13673ac26f6b3ba37a2ef392489722c52e3c5ff1
https://github.com/biosustain/optlang/blob/13673ac26f6b3ba37a2ef392489722c52e3c5ff1/optlang/util.py#L195-L214
train
34,051
biosustain/optlang
optlang/util.py
parse_expr
def parse_expr(expr, local_dict=None): """ Parses a json-object created with 'expr_to_json' into a Sympy expression. If a local_dict argument is passed, symbols with be looked up by name, and a new symbol will be created only if the name is not in local_dict. """ if local_dict is None: local_dict = {} if expr["type"] == "Add": return add([parse_expr(arg, local_dict) for arg in expr["args"]]) elif expr["type"] == "Mul": return mul([parse_expr(arg, local_dict) for arg in expr["args"]]) elif expr["type"] == "Pow": return Pow(parse_expr(arg, local_dict) for arg in expr["args"]) elif expr["type"] == "Symbol": try: return local_dict[expr["name"]] except KeyError: return symbolics.Symbol(expr["name"]) elif expr["type"] == "Number": return symbolics.sympify(expr["value"]) else: raise NotImplementedError(expr["type"] + " is not implemented")
python
def parse_expr(expr, local_dict=None): """ Parses a json-object created with 'expr_to_json' into a Sympy expression. If a local_dict argument is passed, symbols with be looked up by name, and a new symbol will be created only if the name is not in local_dict. """ if local_dict is None: local_dict = {} if expr["type"] == "Add": return add([parse_expr(arg, local_dict) for arg in expr["args"]]) elif expr["type"] == "Mul": return mul([parse_expr(arg, local_dict) for arg in expr["args"]]) elif expr["type"] == "Pow": return Pow(parse_expr(arg, local_dict) for arg in expr["args"]) elif expr["type"] == "Symbol": try: return local_dict[expr["name"]] except KeyError: return symbolics.Symbol(expr["name"]) elif expr["type"] == "Number": return symbolics.sympify(expr["value"]) else: raise NotImplementedError(expr["type"] + " is not implemented")
[ "def", "parse_expr", "(", "expr", ",", "local_dict", "=", "None", ")", ":", "if", "local_dict", "is", "None", ":", "local_dict", "=", "{", "}", "if", "expr", "[", "\"type\"", "]", "==", "\"Add\"", ":", "return", "add", "(", "[", "parse_expr", "(", "a...
Parses a json-object created with 'expr_to_json' into a Sympy expression. If a local_dict argument is passed, symbols with be looked up by name, and a new symbol will be created only if the name is not in local_dict.
[ "Parses", "a", "json", "-", "object", "created", "with", "expr_to_json", "into", "a", "Sympy", "expression", "." ]
13673ac26f6b3ba37a2ef392489722c52e3c5ff1
https://github.com/biosustain/optlang/blob/13673ac26f6b3ba37a2ef392489722c52e3c5ff1/optlang/util.py#L217-L240
train
34,052
biosustain/optlang
optlang/scipy_interface.py
Problem.set_variable_bounds
def set_variable_bounds(self, name, lower, upper): """Set the bounds of a variable""" self.bounds[name] = (lower, upper) self._reset_solution()
python
def set_variable_bounds(self, name, lower, upper): """Set the bounds of a variable""" self.bounds[name] = (lower, upper) self._reset_solution()
[ "def", "set_variable_bounds", "(", "self", ",", "name", ",", "lower", ",", "upper", ")", ":", "self", ".", "bounds", "[", "name", "]", "=", "(", "lower", ",", "upper", ")", "self", ".", "_reset_solution", "(", ")" ]
Set the bounds of a variable
[ "Set", "the", "bounds", "of", "a", "variable" ]
13673ac26f6b3ba37a2ef392489722c52e3c5ff1
https://github.com/biosustain/optlang/blob/13673ac26f6b3ba37a2ef392489722c52e3c5ff1/optlang/scipy_interface.py#L106-L109
train
34,053
biosustain/optlang
optlang/scipy_interface.py
Problem.add_constraint
def add_constraint(self, name, coefficients={}, ub=0): """ Add a constraint to the problem. The constrain is formulated as a dictionary of variable names to linear coefficients. The constraint can only have an upper bound. To make a constraint with a lower bound, multiply all coefficients by -1. """ if name in self._constraints: raise ValueError( "A constraint named " + name + " already exists." ) self._constraints[name] = len(self._constraints) self.upper_bounds = np.append(self.upper_bounds, ub) new_row = np.array([[coefficients.get(name, 0) for name in self._variables]]) self._add_row_to_A(new_row) self._reset_solution()
python
def add_constraint(self, name, coefficients={}, ub=0): """ Add a constraint to the problem. The constrain is formulated as a dictionary of variable names to linear coefficients. The constraint can only have an upper bound. To make a constraint with a lower bound, multiply all coefficients by -1. """ if name in self._constraints: raise ValueError( "A constraint named " + name + " already exists." ) self._constraints[name] = len(self._constraints) self.upper_bounds = np.append(self.upper_bounds, ub) new_row = np.array([[coefficients.get(name, 0) for name in self._variables]]) self._add_row_to_A(new_row) self._reset_solution()
[ "def", "add_constraint", "(", "self", ",", "name", ",", "coefficients", "=", "{", "}", ",", "ub", "=", "0", ")", ":", "if", "name", "in", "self", ".", "_constraints", ":", "raise", "ValueError", "(", "\"A constraint named \"", "+", "name", "+", "\" alrea...
Add a constraint to the problem. The constrain is formulated as a dictionary of variable names to linear coefficients. The constraint can only have an upper bound. To make a constraint with a lower bound, multiply all coefficients by -1.
[ "Add", "a", "constraint", "to", "the", "problem", ".", "The", "constrain", "is", "formulated", "as", "a", "dictionary", "of", "variable", "names", "to", "linear", "coefficients", ".", "The", "constraint", "can", "only", "have", "an", "upper", "bound", ".", ...
13673ac26f6b3ba37a2ef392489722c52e3c5ff1
https://github.com/biosustain/optlang/blob/13673ac26f6b3ba37a2ef392489722c52e3c5ff1/optlang/scipy_interface.py#L124-L140
train
34,054
biosustain/optlang
optlang/scipy_interface.py
Problem.remove_variable
def remove_variable(self, name): """Remove a variable from the problem.""" index = self._get_var_index(name) # Remove from matrix self._A = np.delete(self.A, index, 1) # Remove from bounds del self.bounds[name] # Remove from var list del self._variables[name] self._update_variable_indices() self._reset_solution()
python
def remove_variable(self, name): """Remove a variable from the problem.""" index = self._get_var_index(name) # Remove from matrix self._A = np.delete(self.A, index, 1) # Remove from bounds del self.bounds[name] # Remove from var list del self._variables[name] self._update_variable_indices() self._reset_solution()
[ "def", "remove_variable", "(", "self", ",", "name", ")", ":", "index", "=", "self", ".", "_get_var_index", "(", "name", ")", "# Remove from matrix", "self", ".", "_A", "=", "np", ".", "delete", "(", "self", ".", "A", ",", "index", ",", "1", ")", "# R...
Remove a variable from the problem.
[ "Remove", "a", "variable", "from", "the", "problem", "." ]
13673ac26f6b3ba37a2ef392489722c52e3c5ff1
https://github.com/biosustain/optlang/blob/13673ac26f6b3ba37a2ef392489722c52e3c5ff1/optlang/scipy_interface.py#L154-L164
train
34,055
biosustain/optlang
optlang/scipy_interface.py
Problem.remove_constraint
def remove_constraint(self, name): """Remove a constraint from the problem""" index = self._get_constraint_index(name) # Remove from matrix self._A = np.delete(self.A, index, 0) # Remove from upper_bounds self.upper_bounds = np.delete(self.upper_bounds, index) # Remove from constraint list del self._constraints[name] self._update_constraint_indices() self._reset_solution()
python
def remove_constraint(self, name): """Remove a constraint from the problem""" index = self._get_constraint_index(name) # Remove from matrix self._A = np.delete(self.A, index, 0) # Remove from upper_bounds self.upper_bounds = np.delete(self.upper_bounds, index) # Remove from constraint list del self._constraints[name] self._update_constraint_indices() self._reset_solution()
[ "def", "remove_constraint", "(", "self", ",", "name", ")", ":", "index", "=", "self", ".", "_get_constraint_index", "(", "name", ")", "# Remove from matrix", "self", ".", "_A", "=", "np", ".", "delete", "(", "self", ".", "A", ",", "index", ",", "0", ")...
Remove a constraint from the problem
[ "Remove", "a", "constraint", "from", "the", "problem" ]
13673ac26f6b3ba37a2ef392489722c52e3c5ff1
https://github.com/biosustain/optlang/blob/13673ac26f6b3ba37a2ef392489722c52e3c5ff1/optlang/scipy_interface.py#L166-L176
train
34,056
biosustain/optlang
optlang/scipy_interface.py
Problem.set_constraint_bound
def set_constraint_bound(self, name, value): """Set the upper bound of a constraint.""" index = self._get_constraint_index(name) self.upper_bounds[index] = value self._reset_solution()
python
def set_constraint_bound(self, name, value): """Set the upper bound of a constraint.""" index = self._get_constraint_index(name) self.upper_bounds[index] = value self._reset_solution()
[ "def", "set_constraint_bound", "(", "self", ",", "name", ",", "value", ")", ":", "index", "=", "self", ".", "_get_constraint_index", "(", "name", ")", "self", ".", "upper_bounds", "[", "index", "]", "=", "value", "self", ".", "_reset_solution", "(", ")" ]
Set the upper bound of a constraint.
[ "Set", "the", "upper", "bound", "of", "a", "constraint", "." ]
13673ac26f6b3ba37a2ef392489722c52e3c5ff1
https://github.com/biosustain/optlang/blob/13673ac26f6b3ba37a2ef392489722c52e3c5ff1/optlang/scipy_interface.py#L178-L182
train
34,057
biosustain/optlang
optlang/scipy_interface.py
Problem.get_var_primal
def get_var_primal(self, name): """Get the primal value of a variable. Returns None if the problem has not bee optimized.""" if self._var_primals is None: return None else: index = self._get_var_index(name) return self._var_primals[index]
python
def get_var_primal(self, name): """Get the primal value of a variable. Returns None if the problem has not bee optimized.""" if self._var_primals is None: return None else: index = self._get_var_index(name) return self._var_primals[index]
[ "def", "get_var_primal", "(", "self", ",", "name", ")", ":", "if", "self", ".", "_var_primals", "is", "None", ":", "return", "None", "else", ":", "index", "=", "self", ".", "_get_var_index", "(", "name", ")", "return", "self", ".", "_var_primals", "[", ...
Get the primal value of a variable. Returns None if the problem has not bee optimized.
[ "Get", "the", "primal", "value", "of", "a", "variable", ".", "Returns", "None", "if", "the", "problem", "has", "not", "bee", "optimized", "." ]
13673ac26f6b3ba37a2ef392489722c52e3c5ff1
https://github.com/biosustain/optlang/blob/13673ac26f6b3ba37a2ef392489722c52e3c5ff1/optlang/scipy_interface.py#L184-L190
train
34,058
biosustain/optlang
optlang/scipy_interface.py
Problem.get_constraint_slack
def get_constraint_slack(self, name): """Get the value of the slack variable of a constraint.""" if self._slacks is None: return None else: index = self._get_constraint_index(name) return self._slacks[index]
python
def get_constraint_slack(self, name): """Get the value of the slack variable of a constraint.""" if self._slacks is None: return None else: index = self._get_constraint_index(name) return self._slacks[index]
[ "def", "get_constraint_slack", "(", "self", ",", "name", ")", ":", "if", "self", ".", "_slacks", "is", "None", ":", "return", "None", "else", ":", "index", "=", "self", ".", "_get_constraint_index", "(", "name", ")", "return", "self", ".", "_slacks", "["...
Get the value of the slack variable of a constraint.
[ "Get", "the", "value", "of", "the", "slack", "variable", "of", "a", "constraint", "." ]
13673ac26f6b3ba37a2ef392489722c52e3c5ff1
https://github.com/biosustain/optlang/blob/13673ac26f6b3ba37a2ef392489722c52e3c5ff1/optlang/scipy_interface.py#L238-L244
train
34,059
biosustain/optlang
optlang/scipy_interface.py
Problem.optimize
def optimize(self, method="simplex", verbosity=False, tolerance=1e-9, **kwargs): """Run the linprog function on the problem. Returns None.""" c = np.array([self.objective.get(name, 0) for name in self._variables]) if self.direction == "max": c *= -1 bounds = list(six.itervalues(self.bounds)) solution = linprog(c, self.A, self.upper_bounds, bounds=bounds, method=method, options={"maxiter": 10000, "disp": verbosity, "tol": tolerance}, **kwargs) self._solution = solution self._status = solution.status if SCIPY_STATUS[self._status] == interface.OPTIMAL: self._var_primals = solution.x self._slacks = solution.slack else: self._var_primals = None self._slacks = None self._f = solution.fun
python
def optimize(self, method="simplex", verbosity=False, tolerance=1e-9, **kwargs): """Run the linprog function on the problem. Returns None.""" c = np.array([self.objective.get(name, 0) for name in self._variables]) if self.direction == "max": c *= -1 bounds = list(six.itervalues(self.bounds)) solution = linprog(c, self.A, self.upper_bounds, bounds=bounds, method=method, options={"maxiter": 10000, "disp": verbosity, "tol": tolerance}, **kwargs) self._solution = solution self._status = solution.status if SCIPY_STATUS[self._status] == interface.OPTIMAL: self._var_primals = solution.x self._slacks = solution.slack else: self._var_primals = None self._slacks = None self._f = solution.fun
[ "def", "optimize", "(", "self", ",", "method", "=", "\"simplex\"", ",", "verbosity", "=", "False", ",", "tolerance", "=", "1e-9", ",", "*", "*", "kwargs", ")", ":", "c", "=", "np", ".", "array", "(", "[", "self", ".", "objective", ".", "get", "(", ...
Run the linprog function on the problem. Returns None.
[ "Run", "the", "linprog", "function", "on", "the", "problem", ".", "Returns", "None", "." ]
13673ac26f6b3ba37a2ef392489722c52e3c5ff1
https://github.com/biosustain/optlang/blob/13673ac26f6b3ba37a2ef392489722c52e3c5ff1/optlang/scipy_interface.py#L246-L264
train
34,060
biosustain/optlang
optlang/scipy_interface.py
Problem.objective_value
def objective_value(self): """Returns the optimal objective value""" if self._f is None: raise RuntimeError("Problem has not been optimized yet") if self.direction == "max": return -self._f + self.offset else: return self._f + self.offset
python
def objective_value(self): """Returns the optimal objective value""" if self._f is None: raise RuntimeError("Problem has not been optimized yet") if self.direction == "max": return -self._f + self.offset else: return self._f + self.offset
[ "def", "objective_value", "(", "self", ")", ":", "if", "self", ".", "_f", "is", "None", ":", "raise", "RuntimeError", "(", "\"Problem has not been optimized yet\"", ")", "if", "self", ".", "direction", "==", "\"max\"", ":", "return", "-", "self", ".", "_f", ...
Returns the optimal objective value
[ "Returns", "the", "optimal", "objective", "value" ]
13673ac26f6b3ba37a2ef392489722c52e3c5ff1
https://github.com/biosustain/optlang/blob/13673ac26f6b3ba37a2ef392489722c52e3c5ff1/optlang/scipy_interface.py#L267-L274
train
34,061
sprockets/sprockets.mixins.amqp
sprockets/mixins/amqp/__init__.py
install
def install(application, io_loop=None, **kwargs): """Call this to install AMQP for the Tornado application. Additional keyword arguments are passed through to the constructor of the AMQP object. :param tornado.web.Application application: The tornado application :param tornado.ioloop.IOLoop io_loop: The current IOLoop. :rtype: bool """ if getattr(application, 'amqp', None) is not None: LOGGER.warning('AMQP is already installed') return False kwargs.setdefault('io_loop', io_loop) # Support AMQP_* and RABBITMQ_* variables for prefix in {'AMQP', 'RABBITMQ'}: key = '{}_URL'.format(prefix) if os.environ.get(key) is not None: LOGGER.debug('Setting URL to %s', os.environ[key]) kwargs.setdefault('url', os.environ[key]) key = '{}_CONFIRMATIONS'.format(prefix) if os.environ.get(key) is not None: value = os.environ[key].lower() in {'true', '1'} LOGGER.debug('Setting enable_confirmations to %s', value) kwargs.setdefault('enable_confirmations', value) key = '{}_CONNECTION_ATTEMPTS'.format(prefix) if os.environ.get(key) is not None: value = int(os.environ[key]) LOGGER.debug('Setting connection_attempts to %s', value) kwargs.setdefault('connection_attempts', value) key = '{}_RECONNECT_DELAY'.format(prefix) if os.environ.get(key) is not None: value = float(os.environ[key]) LOGGER.debug('Setting reconnect_delay to %s', value) kwargs.setdefault('reconnect_delay', value) # Set the default AMQP app_id property if application.settings.get('service') and \ application.settings.get('version'): default_app_id = '{}/{}'.format( application.settings['service'], application.settings['version']) else: default_app_id = 'sprockets.mixins.amqp/{}'.format(__version__) kwargs.setdefault('default_app_id', default_app_id) # Default the default URL value if not already set kwargs.setdefault('url', 'amqp://guest:guest@localhost:5672/%2f') LOGGER.debug('kwargs: %r', kwargs) setattr(application, 'amqp', Client(**kwargs)) return True
python
def install(application, io_loop=None, **kwargs): """Call this to install AMQP for the Tornado application. Additional keyword arguments are passed through to the constructor of the AMQP object. :param tornado.web.Application application: The tornado application :param tornado.ioloop.IOLoop io_loop: The current IOLoop. :rtype: bool """ if getattr(application, 'amqp', None) is not None: LOGGER.warning('AMQP is already installed') return False kwargs.setdefault('io_loop', io_loop) # Support AMQP_* and RABBITMQ_* variables for prefix in {'AMQP', 'RABBITMQ'}: key = '{}_URL'.format(prefix) if os.environ.get(key) is not None: LOGGER.debug('Setting URL to %s', os.environ[key]) kwargs.setdefault('url', os.environ[key]) key = '{}_CONFIRMATIONS'.format(prefix) if os.environ.get(key) is not None: value = os.environ[key].lower() in {'true', '1'} LOGGER.debug('Setting enable_confirmations to %s', value) kwargs.setdefault('enable_confirmations', value) key = '{}_CONNECTION_ATTEMPTS'.format(prefix) if os.environ.get(key) is not None: value = int(os.environ[key]) LOGGER.debug('Setting connection_attempts to %s', value) kwargs.setdefault('connection_attempts', value) key = '{}_RECONNECT_DELAY'.format(prefix) if os.environ.get(key) is not None: value = float(os.environ[key]) LOGGER.debug('Setting reconnect_delay to %s', value) kwargs.setdefault('reconnect_delay', value) # Set the default AMQP app_id property if application.settings.get('service') and \ application.settings.get('version'): default_app_id = '{}/{}'.format( application.settings['service'], application.settings['version']) else: default_app_id = 'sprockets.mixins.amqp/{}'.format(__version__) kwargs.setdefault('default_app_id', default_app_id) # Default the default URL value if not already set kwargs.setdefault('url', 'amqp://guest:guest@localhost:5672/%2f') LOGGER.debug('kwargs: %r', kwargs) setattr(application, 'amqp', Client(**kwargs)) return True
[ "def", "install", "(", "application", ",", "io_loop", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "getattr", "(", "application", ",", "'amqp'", ",", "None", ")", "is", "not", "None", ":", "LOGGER", ".", "warning", "(", "'AMQP is already install...
Call this to install AMQP for the Tornado application. Additional keyword arguments are passed through to the constructor of the AMQP object. :param tornado.web.Application application: The tornado application :param tornado.ioloop.IOLoop io_loop: The current IOLoop. :rtype: bool
[ "Call", "this", "to", "install", "AMQP", "for", "the", "Tornado", "application", ".", "Additional", "keyword", "arguments", "are", "passed", "through", "to", "the", "constructor", "of", "the", "AMQP", "object", "." ]
de22b85aec1315bc01e47774637098c34525692b
https://github.com/sprockets/sprockets.mixins.amqp/blob/de22b85aec1315bc01e47774637098c34525692b/sprockets/mixins/amqp/__init__.py#L42-L98
train
34,062
sprockets/sprockets.mixins.amqp
sprockets/mixins/amqp/__init__.py
PublishingMixin.amqp_publish
def amqp_publish(self, exchange, routing_key, body, properties=None): """Publish a message to RabbitMQ :param str exchange: The exchange to publish the message to :param str routing_key: The routing key to publish the message with :param bytes body: The message body to send :param dict properties: An optional dict of AMQP properties :rtype: tornado.concurrent.Future :raises: :exc:`sprockets.mixins.amqp.AMQPError` :raises: :exc:`sprockets.mixins.amqp.NotReadyError` :raises: :exc:`sprockets.mixins.amqp.PublishingError` """ properties = properties or {} if hasattr(self, 'correlation_id') and getattr(self, 'correlation_id'): properties.setdefault('correlation_id', self.correlation_id) return self.application.amqp.publish( exchange, routing_key, body, properties)
python
def amqp_publish(self, exchange, routing_key, body, properties=None): """Publish a message to RabbitMQ :param str exchange: The exchange to publish the message to :param str routing_key: The routing key to publish the message with :param bytes body: The message body to send :param dict properties: An optional dict of AMQP properties :rtype: tornado.concurrent.Future :raises: :exc:`sprockets.mixins.amqp.AMQPError` :raises: :exc:`sprockets.mixins.amqp.NotReadyError` :raises: :exc:`sprockets.mixins.amqp.PublishingError` """ properties = properties or {} if hasattr(self, 'correlation_id') and getattr(self, 'correlation_id'): properties.setdefault('correlation_id', self.correlation_id) return self.application.amqp.publish( exchange, routing_key, body, properties)
[ "def", "amqp_publish", "(", "self", ",", "exchange", ",", "routing_key", ",", "body", ",", "properties", "=", "None", ")", ":", "properties", "=", "properties", "or", "{", "}", "if", "hasattr", "(", "self", ",", "'correlation_id'", ")", "and", "getattr", ...
Publish a message to RabbitMQ :param str exchange: The exchange to publish the message to :param str routing_key: The routing key to publish the message with :param bytes body: The message body to send :param dict properties: An optional dict of AMQP properties :rtype: tornado.concurrent.Future :raises: :exc:`sprockets.mixins.amqp.AMQPError` :raises: :exc:`sprockets.mixins.amqp.NotReadyError` :raises: :exc:`sprockets.mixins.amqp.PublishingError`
[ "Publish", "a", "message", "to", "RabbitMQ" ]
de22b85aec1315bc01e47774637098c34525692b
https://github.com/sprockets/sprockets.mixins.amqp/blob/de22b85aec1315bc01e47774637098c34525692b/sprockets/mixins/amqp/__init__.py#L108-L126
train
34,063
sprockets/sprockets.mixins.amqp
sprockets/mixins/amqp/__init__.py
Client.publish
def publish(self, exchange, routing_key, body, properties=None): """Publish a message to RabbitMQ. If the RabbitMQ connection is not established or is blocked, attempt to wait until sending is possible. :param str exchange: The exchange to publish the message to. :param str routing_key: The routing key to publish the message with. :param bytes body: The message body to send. :param dict properties: An optional dict of additional properties to append. :rtype: tornado.concurrent.Future :raises: :exc:`sprockets.mixins.amqp.NotReadyError` :raises: :exc:`sprockets.mixins.amqp.PublishingError` """ future = concurrent.Future() properties = properties or {} properties.setdefault('app_id', self.default_app_id) properties.setdefault('message_id', str(uuid.uuid4())) properties.setdefault('timestamp', int(time.time())) if self.ready: if self.publisher_confirmations: self.message_number += 1 self.messages[self.message_number] = future else: future.set_result(None) try: self.channel.basic_publish( exchange, routing_key, body, pika.BasicProperties(**properties), True) except exceptions.AMQPError as error: future.set_exception( PublishingFailure( properties['message_id'], exchange, routing_key, error.__class__.__name__)) else: future.set_exception(NotReadyError( self.state_description, properties['message_id'])) return future
python
def publish(self, exchange, routing_key, body, properties=None): """Publish a message to RabbitMQ. If the RabbitMQ connection is not established or is blocked, attempt to wait until sending is possible. :param str exchange: The exchange to publish the message to. :param str routing_key: The routing key to publish the message with. :param bytes body: The message body to send. :param dict properties: An optional dict of additional properties to append. :rtype: tornado.concurrent.Future :raises: :exc:`sprockets.mixins.amqp.NotReadyError` :raises: :exc:`sprockets.mixins.amqp.PublishingError` """ future = concurrent.Future() properties = properties or {} properties.setdefault('app_id', self.default_app_id) properties.setdefault('message_id', str(uuid.uuid4())) properties.setdefault('timestamp', int(time.time())) if self.ready: if self.publisher_confirmations: self.message_number += 1 self.messages[self.message_number] = future else: future.set_result(None) try: self.channel.basic_publish( exchange, routing_key, body, pika.BasicProperties(**properties), True) except exceptions.AMQPError as error: future.set_exception( PublishingFailure( properties['message_id'], exchange, routing_key, error.__class__.__name__)) else: future.set_exception(NotReadyError( self.state_description, properties['message_id'])) return future
[ "def", "publish", "(", "self", ",", "exchange", ",", "routing_key", ",", "body", ",", "properties", "=", "None", ")", ":", "future", "=", "concurrent", ".", "Future", "(", ")", "properties", "=", "properties", "or", "{", "}", "properties", ".", "setdefau...
Publish a message to RabbitMQ. If the RabbitMQ connection is not established or is blocked, attempt to wait until sending is possible. :param str exchange: The exchange to publish the message to. :param str routing_key: The routing key to publish the message with. :param bytes body: The message body to send. :param dict properties: An optional dict of additional properties to append. :rtype: tornado.concurrent.Future :raises: :exc:`sprockets.mixins.amqp.NotReadyError` :raises: :exc:`sprockets.mixins.amqp.PublishingError`
[ "Publish", "a", "message", "to", "RabbitMQ", ".", "If", "the", "RabbitMQ", "connection", "is", "not", "established", "or", "is", "blocked", "attempt", "to", "wait", "until", "sending", "is", "possible", "." ]
de22b85aec1315bc01e47774637098c34525692b
https://github.com/sprockets/sprockets.mixins.amqp/blob/de22b85aec1315bc01e47774637098c34525692b/sprockets/mixins/amqp/__init__.py#L216-L257
train
34,064
sprockets/sprockets.mixins.amqp
sprockets/mixins/amqp/__init__.py
Client.on_delivery_confirmation
def on_delivery_confirmation(self, method_frame): """Invoked by pika when RabbitMQ responds to a Basic.Publish RPC command, passing in either a Basic.Ack or Basic.Nack frame with the delivery tag of the message that was published. The delivery tag is an integer counter indicating the message number that was sent on the channel via Basic.Publish. Here we're just doing house keeping to keep track of stats and remove message numbers that we expect a delivery confirmation of from the list used to keep track of messages that are pending confirmation. :param pika.frame.Method method_frame: Basic.Ack or Basic.Nack frame """ confirmation_type = method_frame.method.NAME.split('.')[1].lower() LOGGER.debug('Received %s for delivery tag: %i', confirmation_type, method_frame.method.delivery_tag) if method_frame.method.multiple: confirmed = sorted([msg for msg in self.messages if msg <= method_frame.method.delivery_tag]) else: confirmed = [method_frame.method.delivery_tag] for msg in confirmed: LOGGER.debug('RabbitMQ confirmed message %i', msg) try: if confirmation_type == 'ack': self.messages[msg].set_result(None) elif confirmation_type == 'nack': self.messages[msg].set_exception(PublishingFailure(msg)) except KeyError: LOGGER.warning('Tried to confirm a message missing in stack') else: del self.messages[msg] LOGGER.debug('Published %i messages, %i have yet to be confirmed', self.message_number, len(self.messages))
python
def on_delivery_confirmation(self, method_frame): """Invoked by pika when RabbitMQ responds to a Basic.Publish RPC command, passing in either a Basic.Ack or Basic.Nack frame with the delivery tag of the message that was published. The delivery tag is an integer counter indicating the message number that was sent on the channel via Basic.Publish. Here we're just doing house keeping to keep track of stats and remove message numbers that we expect a delivery confirmation of from the list used to keep track of messages that are pending confirmation. :param pika.frame.Method method_frame: Basic.Ack or Basic.Nack frame """ confirmation_type = method_frame.method.NAME.split('.')[1].lower() LOGGER.debug('Received %s for delivery tag: %i', confirmation_type, method_frame.method.delivery_tag) if method_frame.method.multiple: confirmed = sorted([msg for msg in self.messages if msg <= method_frame.method.delivery_tag]) else: confirmed = [method_frame.method.delivery_tag] for msg in confirmed: LOGGER.debug('RabbitMQ confirmed message %i', msg) try: if confirmation_type == 'ack': self.messages[msg].set_result(None) elif confirmation_type == 'nack': self.messages[msg].set_exception(PublishingFailure(msg)) except KeyError: LOGGER.warning('Tried to confirm a message missing in stack') else: del self.messages[msg] LOGGER.debug('Published %i messages, %i have yet to be confirmed', self.message_number, len(self.messages))
[ "def", "on_delivery_confirmation", "(", "self", ",", "method_frame", ")", ":", "confirmation_type", "=", "method_frame", ".", "method", ".", "NAME", ".", "split", "(", "'.'", ")", "[", "1", "]", ".", "lower", "(", ")", "LOGGER", ".", "debug", "(", "'Rece...
Invoked by pika when RabbitMQ responds to a Basic.Publish RPC command, passing in either a Basic.Ack or Basic.Nack frame with the delivery tag of the message that was published. The delivery tag is an integer counter indicating the message number that was sent on the channel via Basic.Publish. Here we're just doing house keeping to keep track of stats and remove message numbers that we expect a delivery confirmation of from the list used to keep track of messages that are pending confirmation. :param pika.frame.Method method_frame: Basic.Ack or Basic.Nack frame
[ "Invoked", "by", "pika", "when", "RabbitMQ", "responds", "to", "a", "Basic", ".", "Publish", "RPC", "command", "passing", "in", "either", "a", "Basic", ".", "Ack", "or", "Basic", ".", "Nack", "frame", "with", "the", "delivery", "tag", "of", "the", "messa...
de22b85aec1315bc01e47774637098c34525692b
https://github.com/sprockets/sprockets.mixins.amqp/blob/de22b85aec1315bc01e47774637098c34525692b/sprockets/mixins/amqp/__init__.py#L259-L295
train
34,065
sprockets/sprockets.mixins.amqp
sprockets/mixins/amqp/__init__.py
Client.close
def close(self): """Cleanly shutdown the connection to RabbitMQ :raises: sprockets.mixins.amqp.ConnectionStateError """ if not self.closable: LOGGER.warning('Closed called while %s', self.state_description) raise ConnectionStateError(self.state_description) self.state = self.STATE_CLOSING LOGGER.info('Closing RabbitMQ connection') self.connection.close()
python
def close(self): """Cleanly shutdown the connection to RabbitMQ :raises: sprockets.mixins.amqp.ConnectionStateError """ if not self.closable: LOGGER.warning('Closed called while %s', self.state_description) raise ConnectionStateError(self.state_description) self.state = self.STATE_CLOSING LOGGER.info('Closing RabbitMQ connection') self.connection.close()
[ "def", "close", "(", "self", ")", ":", "if", "not", "self", ".", "closable", ":", "LOGGER", ".", "warning", "(", "'Closed called while %s'", ",", "self", ".", "state_description", ")", "raise", "ConnectionStateError", "(", "self", ".", "state_description", ")"...
Cleanly shutdown the connection to RabbitMQ :raises: sprockets.mixins.amqp.ConnectionStateError
[ "Cleanly", "shutdown", "the", "connection", "to", "RabbitMQ" ]
de22b85aec1315bc01e47774637098c34525692b
https://github.com/sprockets/sprockets.mixins.amqp/blob/de22b85aec1315bc01e47774637098c34525692b/sprockets/mixins/amqp/__init__.py#L390-L401
train
34,066
sprockets/sprockets.mixins.amqp
sprockets/mixins/amqp/__init__.py
Client._reconnect
def _reconnect(self): """Schedule the next connection attempt if the class is not currently closing. """ if self.idle or self.closed: LOGGER.debug('Attempting RabbitMQ reconnect in %s seconds', self.reconnect_delay) self.io_loop.call_later(self.reconnect_delay, self.connect) return LOGGER.warning('Reconnect called while %s', self.state_description)
python
def _reconnect(self): """Schedule the next connection attempt if the class is not currently closing. """ if self.idle or self.closed: LOGGER.debug('Attempting RabbitMQ reconnect in %s seconds', self.reconnect_delay) self.io_loop.call_later(self.reconnect_delay, self.connect) return LOGGER.warning('Reconnect called while %s', self.state_description)
[ "def", "_reconnect", "(", "self", ")", ":", "if", "self", ".", "idle", "or", "self", ".", "closed", ":", "LOGGER", ".", "debug", "(", "'Attempting RabbitMQ reconnect in %s seconds'", ",", "self", ".", "reconnect_delay", ")", "self", ".", "io_loop", ".", "cal...
Schedule the next connection attempt if the class is not currently closing.
[ "Schedule", "the", "next", "connection", "attempt", "if", "the", "class", "is", "not", "currently", "closing", "." ]
de22b85aec1315bc01e47774637098c34525692b
https://github.com/sprockets/sprockets.mixins.amqp/blob/de22b85aec1315bc01e47774637098c34525692b/sprockets/mixins/amqp/__init__.py#L412-L422
train
34,067
sprockets/sprockets.mixins.amqp
sprockets/mixins/amqp/__init__.py
Client.on_connection_open
def on_connection_open(self, connection): """This method is called by pika once the connection to RabbitMQ has been established. :type connection: pika.TornadoConnection """ LOGGER.debug('Connection opened') connection.add_on_connection_blocked_callback( self.on_connection_blocked) connection.add_on_connection_unblocked_callback( self.on_connection_unblocked) connection.add_backpressure_callback(self.on_back_pressure_detected) self.channel = self._open_channel()
python
def on_connection_open(self, connection): """This method is called by pika once the connection to RabbitMQ has been established. :type connection: pika.TornadoConnection """ LOGGER.debug('Connection opened') connection.add_on_connection_blocked_callback( self.on_connection_blocked) connection.add_on_connection_unblocked_callback( self.on_connection_unblocked) connection.add_backpressure_callback(self.on_back_pressure_detected) self.channel = self._open_channel()
[ "def", "on_connection_open", "(", "self", ",", "connection", ")", ":", "LOGGER", ".", "debug", "(", "'Connection opened'", ")", "connection", ".", "add_on_connection_blocked_callback", "(", "self", ".", "on_connection_blocked", ")", "connection", ".", "add_on_connecti...
This method is called by pika once the connection to RabbitMQ has been established. :type connection: pika.TornadoConnection
[ "This", "method", "is", "called", "by", "pika", "once", "the", "connection", "to", "RabbitMQ", "has", "been", "established", "." ]
de22b85aec1315bc01e47774637098c34525692b
https://github.com/sprockets/sprockets.mixins.amqp/blob/de22b85aec1315bc01e47774637098c34525692b/sprockets/mixins/amqp/__init__.py#L428-L441
train
34,068
sprockets/sprockets.mixins.amqp
sprockets/mixins/amqp/__init__.py
Client.on_connection_open_error
def on_connection_open_error(self, connection, error): """Invoked if the connection to RabbitMQ can not be made. :type connection: pika.TornadoConnection :param Exception error: The exception indicating failure """ LOGGER.critical('Could not connect to RabbitMQ (%s): %r', connection, error) self.state = self.STATE_CLOSED self._reconnect()
python
def on_connection_open_error(self, connection, error): """Invoked if the connection to RabbitMQ can not be made. :type connection: pika.TornadoConnection :param Exception error: The exception indicating failure """ LOGGER.critical('Could not connect to RabbitMQ (%s): %r', connection, error) self.state = self.STATE_CLOSED self._reconnect()
[ "def", "on_connection_open_error", "(", "self", ",", "connection", ",", "error", ")", ":", "LOGGER", ".", "critical", "(", "'Could not connect to RabbitMQ (%s): %r'", ",", "connection", ",", "error", ")", "self", ".", "state", "=", "self", ".", "STATE_CLOSED", "...
Invoked if the connection to RabbitMQ can not be made. :type connection: pika.TornadoConnection :param Exception error: The exception indicating failure
[ "Invoked", "if", "the", "connection", "to", "RabbitMQ", "can", "not", "be", "made", "." ]
de22b85aec1315bc01e47774637098c34525692b
https://github.com/sprockets/sprockets.mixins.amqp/blob/de22b85aec1315bc01e47774637098c34525692b/sprockets/mixins/amqp/__init__.py#L443-L453
train
34,069
sprockets/sprockets.mixins.amqp
sprockets/mixins/amqp/__init__.py
Client.on_connection_blocked
def on_connection_blocked(self, method_frame): """This method is called by pika if RabbitMQ sends a connection blocked method, to let us know we need to throttle our publishing. :param pika.amqp_object.Method method_frame: The blocked method frame """ LOGGER.warning('Connection blocked: %s', method_frame) self.state = self.STATE_BLOCKED if self.on_unavailable: self.on_unavailable(self)
python
def on_connection_blocked(self, method_frame): """This method is called by pika if RabbitMQ sends a connection blocked method, to let us know we need to throttle our publishing. :param pika.amqp_object.Method method_frame: The blocked method frame """ LOGGER.warning('Connection blocked: %s', method_frame) self.state = self.STATE_BLOCKED if self.on_unavailable: self.on_unavailable(self)
[ "def", "on_connection_blocked", "(", "self", ",", "method_frame", ")", ":", "LOGGER", ".", "warning", "(", "'Connection blocked: %s'", ",", "method_frame", ")", "self", ".", "state", "=", "self", ".", "STATE_BLOCKED", "if", "self", ".", "on_unavailable", ":", ...
This method is called by pika if RabbitMQ sends a connection blocked method, to let us know we need to throttle our publishing. :param pika.amqp_object.Method method_frame: The blocked method frame
[ "This", "method", "is", "called", "by", "pika", "if", "RabbitMQ", "sends", "a", "connection", "blocked", "method", "to", "let", "us", "know", "we", "need", "to", "throttle", "our", "publishing", "." ]
de22b85aec1315bc01e47774637098c34525692b
https://github.com/sprockets/sprockets.mixins.amqp/blob/de22b85aec1315bc01e47774637098c34525692b/sprockets/mixins/amqp/__init__.py#L466-L476
train
34,070
sprockets/sprockets.mixins.amqp
sprockets/mixins/amqp/__init__.py
Client.on_connection_closed
def on_connection_closed(self, connection, reply_code, reply_text): """This method is invoked by pika when the connection to RabbitMQ is closed unexpectedly. Since it is unexpected, we will reconnect to RabbitMQ if it disconnects. :param pika.TornadoConnection connection: Closed connection :param int reply_code: The server provided reply_code if given :param str reply_text: The server provided reply_text if given """ start_state = self.state self.state = self.STATE_CLOSED if self.on_unavailable: self.on_unavailable(self) self.connection = None self.channel = None if start_state != self.STATE_CLOSING: LOGGER.warning('%s closed while %s: (%s) %s', connection, self.state_description, reply_code, reply_text) self._reconnect()
python
def on_connection_closed(self, connection, reply_code, reply_text): """This method is invoked by pika when the connection to RabbitMQ is closed unexpectedly. Since it is unexpected, we will reconnect to RabbitMQ if it disconnects. :param pika.TornadoConnection connection: Closed connection :param int reply_code: The server provided reply_code if given :param str reply_text: The server provided reply_text if given """ start_state = self.state self.state = self.STATE_CLOSED if self.on_unavailable: self.on_unavailable(self) self.connection = None self.channel = None if start_state != self.STATE_CLOSING: LOGGER.warning('%s closed while %s: (%s) %s', connection, self.state_description, reply_code, reply_text) self._reconnect()
[ "def", "on_connection_closed", "(", "self", ",", "connection", ",", "reply_code", ",", "reply_text", ")", ":", "start_state", "=", "self", ".", "state", "self", ".", "state", "=", "self", ".", "STATE_CLOSED", "if", "self", ".", "on_unavailable", ":", "self",...
This method is invoked by pika when the connection to RabbitMQ is closed unexpectedly. Since it is unexpected, we will reconnect to RabbitMQ if it disconnects. :param pika.TornadoConnection connection: Closed connection :param int reply_code: The server provided reply_code if given :param str reply_text: The server provided reply_text if given
[ "This", "method", "is", "invoked", "by", "pika", "when", "the", "connection", "to", "RabbitMQ", "is", "closed", "unexpectedly", ".", "Since", "it", "is", "unexpected", "we", "will", "reconnect", "to", "RabbitMQ", "if", "it", "disconnects", "." ]
de22b85aec1315bc01e47774637098c34525692b
https://github.com/sprockets/sprockets.mixins.amqp/blob/de22b85aec1315bc01e47774637098c34525692b/sprockets/mixins/amqp/__init__.py#L490-L512
train
34,071
sprockets/sprockets.mixins.amqp
sprockets/mixins/amqp/__init__.py
Client.on_basic_return
def on_basic_return(self, _channel, method, properties, body): """Invoke a registered callback or log the returned message. :param _channel: The channel the message was sent on :type _channel: pika.channel.Channel :param pika.spec.Basic.Return method: The method object :param pika.spec.BasicProperties properties: The message properties :param str, unicode, bytes body: The message body """ if self.on_return: self.on_return(method, properties, body) else: LOGGER.critical( '%s message %s published to %s (CID %s) returned: %s', method.exchange, properties.message_id, method.routing_key, properties.correlation_id, method.reply_text)
python
def on_basic_return(self, _channel, method, properties, body): """Invoke a registered callback or log the returned message. :param _channel: The channel the message was sent on :type _channel: pika.channel.Channel :param pika.spec.Basic.Return method: The method object :param pika.spec.BasicProperties properties: The message properties :param str, unicode, bytes body: The message body """ if self.on_return: self.on_return(method, properties, body) else: LOGGER.critical( '%s message %s published to %s (CID %s) returned: %s', method.exchange, properties.message_id, method.routing_key, properties.correlation_id, method.reply_text)
[ "def", "on_basic_return", "(", "self", ",", "_channel", ",", "method", ",", "properties", ",", "body", ")", ":", "if", "self", ".", "on_return", ":", "self", ".", "on_return", "(", "method", ",", "properties", ",", "body", ")", "else", ":", "LOGGER", "...
Invoke a registered callback or log the returned message. :param _channel: The channel the message was sent on :type _channel: pika.channel.Channel :param pika.spec.Basic.Return method: The method object :param pika.spec.BasicProperties properties: The message properties :param str, unicode, bytes body: The message body
[ "Invoke", "a", "registered", "callback", "or", "log", "the", "returned", "message", "." ]
de22b85aec1315bc01e47774637098c34525692b
https://github.com/sprockets/sprockets.mixins.amqp/blob/de22b85aec1315bc01e47774637098c34525692b/sprockets/mixins/amqp/__init__.py#L518-L535
train
34,072
sprockets/sprockets.mixins.amqp
sprockets/mixins/amqp/__init__.py
Client.on_channel_closed
def on_channel_closed(self, channel, reply_code, reply_text): """Invoked by pika when RabbitMQ unexpectedly closes the channel. Channels are usually closed if you attempt to do something that violates the protocol, such as re-declare an exchange or queue with different parameters. In this case, we just want to log the error and create a new channel after setting the state back to connecting. :param pika.channel.Channel channel: The closed channel :param int reply_code: The numeric reason the channel was closed :param str reply_text: The text reason the channel was closed """ for future in self.messages.values(): future.set_exception(AMQPException(reply_code, reply_text)) self.messages = {} if self.closing: LOGGER.debug('Channel %s was intentionally closed (%s) %s', channel, reply_code, reply_text) else: LOGGER.warning('Channel %s was closed: (%s) %s', channel, reply_code, reply_text) self.state = self.STATE_BLOCKED if self.on_unavailable: self.on_unavailable(self) self.channel = self._open_channel()
python
def on_channel_closed(self, channel, reply_code, reply_text): """Invoked by pika when RabbitMQ unexpectedly closes the channel. Channels are usually closed if you attempt to do something that violates the protocol, such as re-declare an exchange or queue with different parameters. In this case, we just want to log the error and create a new channel after setting the state back to connecting. :param pika.channel.Channel channel: The closed channel :param int reply_code: The numeric reason the channel was closed :param str reply_text: The text reason the channel was closed """ for future in self.messages.values(): future.set_exception(AMQPException(reply_code, reply_text)) self.messages = {} if self.closing: LOGGER.debug('Channel %s was intentionally closed (%s) %s', channel, reply_code, reply_text) else: LOGGER.warning('Channel %s was closed: (%s) %s', channel, reply_code, reply_text) self.state = self.STATE_BLOCKED if self.on_unavailable: self.on_unavailable(self) self.channel = self._open_channel()
[ "def", "on_channel_closed", "(", "self", ",", "channel", ",", "reply_code", ",", "reply_text", ")", ":", "for", "future", "in", "self", ".", "messages", ".", "values", "(", ")", ":", "future", ".", "set_exception", "(", "AMQPException", "(", "reply_code", ...
Invoked by pika when RabbitMQ unexpectedly closes the channel. Channels are usually closed if you attempt to do something that violates the protocol, such as re-declare an exchange or queue with different parameters. In this case, we just want to log the error and create a new channel after setting the state back to connecting. :param pika.channel.Channel channel: The closed channel :param int reply_code: The numeric reason the channel was closed :param str reply_text: The text reason the channel was closed
[ "Invoked", "by", "pika", "when", "RabbitMQ", "unexpectedly", "closes", "the", "channel", "." ]
de22b85aec1315bc01e47774637098c34525692b
https://github.com/sprockets/sprockets.mixins.amqp/blob/de22b85aec1315bc01e47774637098c34525692b/sprockets/mixins/amqp/__init__.py#L559-L586
train
34,073
keeprocking/pygelf
pygelf/gelf.py
object_to_json
def object_to_json(obj): """Convert object that cannot be natively serialized by python to JSON representation.""" if isinstance(obj, (datetime.datetime, datetime.date, datetime.time)): return obj.isoformat() return str(obj)
python
def object_to_json(obj): """Convert object that cannot be natively serialized by python to JSON representation.""" if isinstance(obj, (datetime.datetime, datetime.date, datetime.time)): return obj.isoformat() return str(obj)
[ "def", "object_to_json", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "(", "datetime", ".", "datetime", ",", "datetime", ".", "date", ",", "datetime", ".", "time", ")", ")", ":", "return", "obj", ".", "isoformat", "(", ")", "return", "s...
Convert object that cannot be natively serialized by python to JSON representation.
[ "Convert", "object", "that", "cannot", "be", "natively", "serialized", "by", "python", "to", "JSON", "representation", "." ]
c851a277f86a239a6632683fd56dfb2300b353eb
https://github.com/keeprocking/pygelf/blob/c851a277f86a239a6632683fd56dfb2300b353eb/pygelf/gelf.py#L70-L74
train
34,074
ncjones/python-guerrillamail
guerrillamail.py
Mail.from_response
def from_response(cls, response_data): """ Factory method to create a Mail instance from a Guerrillamail response dict. """ identity = lambda x: x return Mail(**_transform_dict(response_data, { 'guid': ('mail_id', identity), 'subject': ('mail_subject', identity), 'sender': ('mail_from', identity), 'datetime': ('mail_timestamp', lambda x: datetime.utcfromtimestamp(int(x)).replace(tzinfo=utc)), 'read': ('mail_read', int), 'excerpt': ('mail_excerpt', identity), 'body': ('mail_body', identity), }))
python
def from_response(cls, response_data): """ Factory method to create a Mail instance from a Guerrillamail response dict. """ identity = lambda x: x return Mail(**_transform_dict(response_data, { 'guid': ('mail_id', identity), 'subject': ('mail_subject', identity), 'sender': ('mail_from', identity), 'datetime': ('mail_timestamp', lambda x: datetime.utcfromtimestamp(int(x)).replace(tzinfo=utc)), 'read': ('mail_read', int), 'excerpt': ('mail_excerpt', identity), 'body': ('mail_body', identity), }))
[ "def", "from_response", "(", "cls", ",", "response_data", ")", ":", "identity", "=", "lambda", "x", ":", "x", "return", "Mail", "(", "*", "*", "_transform_dict", "(", "response_data", ",", "{", "'guid'", ":", "(", "'mail_id'", ",", "identity", ")", ",", ...
Factory method to create a Mail instance from a Guerrillamail response dict.
[ "Factory", "method", "to", "create", "a", "Mail", "instance", "from", "a", "Guerrillamail", "response", "dict", "." ]
b4830b023d626d1e485d74602319d4fecea3d73d
https://github.com/ncjones/python-guerrillamail/blob/b4830b023d626d1e485d74602319d4fecea3d73d/guerrillamail.py#L70-L84
train
34,075
pmelchior/proxmin
examples/parabola.py
grad_f
def grad_f(xy): """Gradient of f""" return np.array([grad_fx(xy[0],xy[1]),grad_fy(xy[0],xy[1])])
python
def grad_f(xy): """Gradient of f""" return np.array([grad_fx(xy[0],xy[1]),grad_fy(xy[0],xy[1])])
[ "def", "grad_f", "(", "xy", ")", ":", "return", "np", ".", "array", "(", "[", "grad_fx", "(", "xy", "[", "0", "]", ",", "xy", "[", "1", "]", ")", ",", "grad_fy", "(", "xy", "[", "0", "]", ",", "xy", "[", "1", "]", ")", "]", ")" ]
Gradient of f
[ "Gradient", "of", "f" ]
60e49d90c67c46329cc1d3b5c484951dc8bd2c3f
https://github.com/pmelchior/proxmin/blob/60e49d90c67c46329cc1d3b5c484951dc8bd2c3f/examples/parabola.py#L26-L28
train
34,076
pmelchior/proxmin
examples/parabola.py
prox_circle
def prox_circle(xy, step): """Projection onto circle""" center = np.array([0,0]) dxy = xy - center radius = 0.5 # exclude interior of circle #if (dxy**2).sum() < radius**2: # exclude everything other than perimeter of circle if 1: phi = np.arctan2(dxy[1], dxy[0]) return center + radius*np.array([np.cos(phi), np.sin(phi)]) else: return xy
python
def prox_circle(xy, step): """Projection onto circle""" center = np.array([0,0]) dxy = xy - center radius = 0.5 # exclude interior of circle #if (dxy**2).sum() < radius**2: # exclude everything other than perimeter of circle if 1: phi = np.arctan2(dxy[1], dxy[0]) return center + radius*np.array([np.cos(phi), np.sin(phi)]) else: return xy
[ "def", "prox_circle", "(", "xy", ",", "step", ")", ":", "center", "=", "np", ".", "array", "(", "[", "0", ",", "0", "]", ")", "dxy", "=", "xy", "-", "center", "radius", "=", "0.5", "# exclude interior of circle", "#if (dxy**2).sum() < radius**2:", "# exclu...
Projection onto circle
[ "Projection", "onto", "circle" ]
60e49d90c67c46329cc1d3b5c484951dc8bd2c3f
https://github.com/pmelchior/proxmin/blob/60e49d90c67c46329cc1d3b5c484951dc8bd2c3f/examples/parabola.py#L30-L42
train
34,077
pmelchior/proxmin
examples/parabola.py
prox_xline
def prox_xline(x, step): """Projection onto line in x""" if not np.isscalar(x): x= x[0] if x > 0.5: return np.array([0.5]) else: return np.array([x])
python
def prox_xline(x, step): """Projection onto line in x""" if not np.isscalar(x): x= x[0] if x > 0.5: return np.array([0.5]) else: return np.array([x])
[ "def", "prox_xline", "(", "x", ",", "step", ")", ":", "if", "not", "np", ".", "isscalar", "(", "x", ")", ":", "x", "=", "x", "[", "0", "]", "if", "x", ">", "0.5", ":", "return", "np", ".", "array", "(", "[", "0.5", "]", ")", "else", ":", ...
Projection onto line in x
[ "Projection", "onto", "line", "in", "x" ]
60e49d90c67c46329cc1d3b5c484951dc8bd2c3f
https://github.com/pmelchior/proxmin/blob/60e49d90c67c46329cc1d3b5c484951dc8bd2c3f/examples/parabola.py#L44-L51
train
34,078
pmelchior/proxmin
examples/parabola.py
prox_yline
def prox_yline(y, step): """Projection onto line in y""" if not np.isscalar(y): y= y[0] if y > -0.75: return np.array([-0.75]) else: return np.array([y])
python
def prox_yline(y, step): """Projection onto line in y""" if not np.isscalar(y): y= y[0] if y > -0.75: return np.array([-0.75]) else: return np.array([y])
[ "def", "prox_yline", "(", "y", ",", "step", ")", ":", "if", "not", "np", ".", "isscalar", "(", "y", ")", ":", "y", "=", "y", "[", "0", "]", "if", "y", ">", "-", "0.75", ":", "return", "np", ".", "array", "(", "[", "-", "0.75", "]", ")", "...
Projection onto line in y
[ "Projection", "onto", "line", "in", "y" ]
60e49d90c67c46329cc1d3b5c484951dc8bd2c3f
https://github.com/pmelchior/proxmin/blob/60e49d90c67c46329cc1d3b5c484951dc8bd2c3f/examples/parabola.py#L53-L60
train
34,079
pmelchior/proxmin
examples/parabola.py
prox_line
def prox_line(xy, step): """2D projection onto 2 lines""" return np.concatenate((prox_xline(xy[0], step), prox_yline(xy[1], step)))
python
def prox_line(xy, step): """2D projection onto 2 lines""" return np.concatenate((prox_xline(xy[0], step), prox_yline(xy[1], step)))
[ "def", "prox_line", "(", "xy", ",", "step", ")", ":", "return", "np", ".", "concatenate", "(", "(", "prox_xline", "(", "xy", "[", "0", "]", ",", "step", ")", ",", "prox_yline", "(", "xy", "[", "1", "]", ",", "step", ")", ")", ")" ]
2D projection onto 2 lines
[ "2D", "projection", "onto", "2", "lines" ]
60e49d90c67c46329cc1d3b5c484951dc8bd2c3f
https://github.com/pmelchior/proxmin/blob/60e49d90c67c46329cc1d3b5c484951dc8bd2c3f/examples/parabola.py#L62-L64
train
34,080
pmelchior/proxmin
examples/parabola.py
prox_lim
def prox_lim(xy, step, boundary=None): """Proximal projection operator""" if boundary == "circle": return prox_circle(xy, step) if boundary == "line": return prox_line(xy, step) # default: do nothing return xy
python
def prox_lim(xy, step, boundary=None): """Proximal projection operator""" if boundary == "circle": return prox_circle(xy, step) if boundary == "line": return prox_line(xy, step) # default: do nothing return xy
[ "def", "prox_lim", "(", "xy", ",", "step", ",", "boundary", "=", "None", ")", ":", "if", "boundary", "==", "\"circle\"", ":", "return", "prox_circle", "(", "xy", ",", "step", ")", "if", "boundary", "==", "\"line\"", ":", "return", "prox_line", "(", "xy...
Proximal projection operator
[ "Proximal", "projection", "operator" ]
60e49d90c67c46329cc1d3b5c484951dc8bd2c3f
https://github.com/pmelchior/proxmin/blob/60e49d90c67c46329cc1d3b5c484951dc8bd2c3f/examples/parabola.py#L66-L73
train
34,081
pmelchior/proxmin
examples/parabola.py
prox_gradf12
def prox_gradf12(x, step, j=None, Xs=None): """1D gradient operator for x or y""" if j == 0: return x - step*grad_fx(Xs[0][0], Xs[1][0]) if j == 1: y = x return y - step*grad_fy(Xs[0][0], Xs[1][0]) raise NotImplementedError
python
def prox_gradf12(x, step, j=None, Xs=None): """1D gradient operator for x or y""" if j == 0: return x - step*grad_fx(Xs[0][0], Xs[1][0]) if j == 1: y = x return y - step*grad_fy(Xs[0][0], Xs[1][0]) raise NotImplementedError
[ "def", "prox_gradf12", "(", "x", ",", "step", ",", "j", "=", "None", ",", "Xs", "=", "None", ")", ":", "if", "j", "==", "0", ":", "return", "x", "-", "step", "*", "grad_fx", "(", "Xs", "[", "0", "]", "[", "0", "]", ",", "Xs", "[", "1", "]...
1D gradient operator for x or y
[ "1D", "gradient", "operator", "for", "x", "or", "y" ]
60e49d90c67c46329cc1d3b5c484951dc8bd2c3f
https://github.com/pmelchior/proxmin/blob/60e49d90c67c46329cc1d3b5c484951dc8bd2c3f/examples/parabola.py#L84-L91
train
34,082
pmelchior/proxmin
examples/parabola.py
prox_gradf_lim12
def prox_gradf_lim12(x, step, j=None, Xs=None, boundary=None): """1D projection operator""" # TODO: split boundary in x1 and x2 and use appropriate operator if j == 0: x -= step*grad_fx(Xs[0][0], Xs[1][0]) if j == 1: y = x y -= step*grad_fy(Xs[0][0], Xs[1][0]) return prox_lim12(x, step, j=j, Xs=Xs, boundary=boundary)
python
def prox_gradf_lim12(x, step, j=None, Xs=None, boundary=None): """1D projection operator""" # TODO: split boundary in x1 and x2 and use appropriate operator if j == 0: x -= step*grad_fx(Xs[0][0], Xs[1][0]) if j == 1: y = x y -= step*grad_fy(Xs[0][0], Xs[1][0]) return prox_lim12(x, step, j=j, Xs=Xs, boundary=boundary)
[ "def", "prox_gradf_lim12", "(", "x", ",", "step", ",", "j", "=", "None", ",", "Xs", "=", "None", ",", "boundary", "=", "None", ")", ":", "# TODO: split boundary in x1 and x2 and use appropriate operator", "if", "j", "==", "0", ":", "x", "-=", "step", "*", ...
1D projection operator
[ "1D", "projection", "operator" ]
60e49d90c67c46329cc1d3b5c484951dc8bd2c3f
https://github.com/pmelchior/proxmin/blob/60e49d90c67c46329cc1d3b5c484951dc8bd2c3f/examples/parabola.py#L121-L129
train
34,083
pmelchior/proxmin
proxmin/algorithms.py
pgm
def pgm(X, prox_f, step_f, accelerated=False, relax=None, e_rel=1e-6, max_iter=1000, traceback=None): """Proximal Gradient Method Adapted from Combettes 2009, Algorithm 3.4. The accelerated version is Algorithm 3.6 with modifications from Xu & Yin (2015). Args: X: initial X, will be updated prox_f: proxed function f (the forward-backward step) step_f: step size, < 1/L with L being the Lipschitz constant of grad f accelerated: If Nesterov acceleration should be used relax: (over)relaxation parameter, 0 < relax < 1.5 e_rel: relative error of X max_iter: maximum iteration, irrespective of residual error traceback: utils.Traceback to hold variable histories Returns: converged: whether the optimizer has converged within e_rel error: X^it - X^it-1 """ # init stepper = utils.NesterovStepper(accelerated=accelerated) if relax is not None: assert relax > 0 and relax < 1.5 if traceback is not None: traceback.update_history(0, X=X, step_f=step_f) if accelerated: traceback.update_history(0, omega=0) if relax is not None: traceback.update_history(0, relax=relax) for it in range(max_iter): # use Nesterov acceleration (if omega > 0), automatically incremented omega = stepper.omega if omega > 0: _X = X + omega*(X - X_) else: _X = X # make copy for convergence test and acceleration X_ = X.copy() # PGM step X[:] = prox_f(_X, step_f) if relax is not None: X += (relax-1)*(X - X_) if traceback is not None: traceback.update_history(it+1, X=X, step_f=step_f) if accelerated: traceback.update_history(it+1, omega=omega) if relax is not None: traceback.update_history(it+1, relax=relax) # test for fixed point convergence converged = utils.l2sq(X - X_) <= e_rel**2*utils.l2sq(X) if converged: break logger.info("Completed {0} iterations".format(it+1)) if not converged: logger.warning("Solution did not converge") return converged, X-X_
python
def pgm(X, prox_f, step_f, accelerated=False, relax=None, e_rel=1e-6, max_iter=1000, traceback=None): """Proximal Gradient Method Adapted from Combettes 2009, Algorithm 3.4. The accelerated version is Algorithm 3.6 with modifications from Xu & Yin (2015). Args: X: initial X, will be updated prox_f: proxed function f (the forward-backward step) step_f: step size, < 1/L with L being the Lipschitz constant of grad f accelerated: If Nesterov acceleration should be used relax: (over)relaxation parameter, 0 < relax < 1.5 e_rel: relative error of X max_iter: maximum iteration, irrespective of residual error traceback: utils.Traceback to hold variable histories Returns: converged: whether the optimizer has converged within e_rel error: X^it - X^it-1 """ # init stepper = utils.NesterovStepper(accelerated=accelerated) if relax is not None: assert relax > 0 and relax < 1.5 if traceback is not None: traceback.update_history(0, X=X, step_f=step_f) if accelerated: traceback.update_history(0, omega=0) if relax is not None: traceback.update_history(0, relax=relax) for it in range(max_iter): # use Nesterov acceleration (if omega > 0), automatically incremented omega = stepper.omega if omega > 0: _X = X + omega*(X - X_) else: _X = X # make copy for convergence test and acceleration X_ = X.copy() # PGM step X[:] = prox_f(_X, step_f) if relax is not None: X += (relax-1)*(X - X_) if traceback is not None: traceback.update_history(it+1, X=X, step_f=step_f) if accelerated: traceback.update_history(it+1, omega=omega) if relax is not None: traceback.update_history(it+1, relax=relax) # test for fixed point convergence converged = utils.l2sq(X - X_) <= e_rel**2*utils.l2sq(X) if converged: break logger.info("Completed {0} iterations".format(it+1)) if not converged: logger.warning("Solution did not converge") return converged, X-X_
[ "def", "pgm", "(", "X", ",", "prox_f", ",", "step_f", ",", "accelerated", "=", "False", ",", "relax", "=", "None", ",", "e_rel", "=", "1e-6", ",", "max_iter", "=", "1000", ",", "traceback", "=", "None", ")", ":", "# init", "stepper", "=", "utils", ...
Proximal Gradient Method Adapted from Combettes 2009, Algorithm 3.4. The accelerated version is Algorithm 3.6 with modifications from Xu & Yin (2015). Args: X: initial X, will be updated prox_f: proxed function f (the forward-backward step) step_f: step size, < 1/L with L being the Lipschitz constant of grad f accelerated: If Nesterov acceleration should be used relax: (over)relaxation parameter, 0 < relax < 1.5 e_rel: relative error of X max_iter: maximum iteration, irrespective of residual error traceback: utils.Traceback to hold variable histories Returns: converged: whether the optimizer has converged within e_rel error: X^it - X^it-1
[ "Proximal", "Gradient", "Method" ]
60e49d90c67c46329cc1d3b5c484951dc8bd2c3f
https://github.com/pmelchior/proxmin/blob/60e49d90c67c46329cc1d3b5c484951dc8bd2c3f/proxmin/algorithms.py#L10-L78
train
34,084
pmelchior/proxmin
proxmin/algorithms.py
admm
def admm(X, prox_f, step_f, prox_g=None, step_g=None, L=None, e_rel=1e-6, e_abs=0, max_iter=1000, traceback=None): """Alternating Direction Method of Multipliers This method implements the linearized ADMM from Parikh & Boyd (2014). Args: X: initial X will be updated prox_f: proxed function f step_f: step size for prox_f prox_g: proxed function g step_g: specific value of step size for prox_g (experts only!) By default, set to the maximum value of step_f * ||L||_s^2. L: linear operator of the argument of g. Matrix can be numpy.array, scipy.sparse, or None (for identity). e_rel: relative error threshold for primal and dual residuals e_abs: absolute error threshold for primal and dual residuals max_iter: maximum iteration number, irrespective of current residuals traceback: utils.Traceback to hold variable histories Returns: converged: whether the optimizer has converged within e_rel error: X^it - X^it-1 Reference: Moolekamp & Melchior, Algorithm 1 (arXiv:1708.09066) """ # use matrix adapter for convenient & fast notation _L = utils.MatrixAdapter(L) # get/check compatible step size for g if prox_g is not None and step_g is None: step_g = utils.get_step_g(step_f, _L.spectral_norm) # init Z,U = utils.initZU(X, _L) it = 0 if traceback is not None: traceback.update_history(it, X=X, step_f=step_f, Z=Z, U=U, R=np.zeros(Z.shape, dtype=Z.dtype), S=np.zeros(X.shape, dtype=X.dtype), step_g=step_g) while it < max_iter: # Update the variables, return LX and primal/dual residual LX, R, S = utils.update_variables(X, Z, U, prox_f, step_f, prox_g, step_g, _L) # Optionally store the variables in the history if traceback is not None: traceback.update_history(it+1, X=X, step_f=step_f, Z=Z, U=U, R=R, S=S, step_g=step_g) # convergence criteria, adapted from Boyd 2011, Sec 3.3.1 converged, error = utils.check_constraint_convergence(X, _L, LX, Z, U, R, S, step_f, step_g, e_rel, e_abs) if converged: break it += 1 # if X and primal residual does not change: decrease step_f and step_g, and restart if prox_g is not None: if it > 1: if (X == X_).all() and (R == R_).all(): step_f /= 2 step_g /= 2 # re-init it = 0 Z,U = utils.initZU(X, _L) logger.info("Restarting with step_f = %.3f" % step_f) if traceback is not None: traceback.reset() traceback.update_history(it, X=X, Z=Z, U=U, R=np.zeros(Z.shape, dtype=Z.dtype), S=np.zeros(X.shape, dtype=X.dtype), step_f=step_f, step_g=step_g) X_ = X.copy() R_ = R logger.info("Completed {0} iterations".format(it+1)) if not converged: logger.warning("Solution did not converge") return converged, error
python
def admm(X, prox_f, step_f, prox_g=None, step_g=None, L=None, e_rel=1e-6, e_abs=0, max_iter=1000, traceback=None): """Alternating Direction Method of Multipliers This method implements the linearized ADMM from Parikh & Boyd (2014). Args: X: initial X will be updated prox_f: proxed function f step_f: step size for prox_f prox_g: proxed function g step_g: specific value of step size for prox_g (experts only!) By default, set to the maximum value of step_f * ||L||_s^2. L: linear operator of the argument of g. Matrix can be numpy.array, scipy.sparse, or None (for identity). e_rel: relative error threshold for primal and dual residuals e_abs: absolute error threshold for primal and dual residuals max_iter: maximum iteration number, irrespective of current residuals traceback: utils.Traceback to hold variable histories Returns: converged: whether the optimizer has converged within e_rel error: X^it - X^it-1 Reference: Moolekamp & Melchior, Algorithm 1 (arXiv:1708.09066) """ # use matrix adapter for convenient & fast notation _L = utils.MatrixAdapter(L) # get/check compatible step size for g if prox_g is not None and step_g is None: step_g = utils.get_step_g(step_f, _L.spectral_norm) # init Z,U = utils.initZU(X, _L) it = 0 if traceback is not None: traceback.update_history(it, X=X, step_f=step_f, Z=Z, U=U, R=np.zeros(Z.shape, dtype=Z.dtype), S=np.zeros(X.shape, dtype=X.dtype), step_g=step_g) while it < max_iter: # Update the variables, return LX and primal/dual residual LX, R, S = utils.update_variables(X, Z, U, prox_f, step_f, prox_g, step_g, _L) # Optionally store the variables in the history if traceback is not None: traceback.update_history(it+1, X=X, step_f=step_f, Z=Z, U=U, R=R, S=S, step_g=step_g) # convergence criteria, adapted from Boyd 2011, Sec 3.3.1 converged, error = utils.check_constraint_convergence(X, _L, LX, Z, U, R, S, step_f, step_g, e_rel, e_abs) if converged: break it += 1 # if X and primal residual does not change: decrease step_f and step_g, and restart if prox_g is not None: if it > 1: if (X == X_).all() and (R == R_).all(): step_f /= 2 step_g /= 2 # re-init it = 0 Z,U = utils.initZU(X, _L) logger.info("Restarting with step_f = %.3f" % step_f) if traceback is not None: traceback.reset() traceback.update_history(it, X=X, Z=Z, U=U, R=np.zeros(Z.shape, dtype=Z.dtype), S=np.zeros(X.shape, dtype=X.dtype), step_f=step_f, step_g=step_g) X_ = X.copy() R_ = R logger.info("Completed {0} iterations".format(it+1)) if not converged: logger.warning("Solution did not converge") return converged, error
[ "def", "admm", "(", "X", ",", "prox_f", ",", "step_f", ",", "prox_g", "=", "None", ",", "step_g", "=", "None", ",", "L", "=", "None", ",", "e_rel", "=", "1e-6", ",", "e_abs", "=", "0", ",", "max_iter", "=", "1000", ",", "traceback", "=", "None", ...
Alternating Direction Method of Multipliers This method implements the linearized ADMM from Parikh & Boyd (2014). Args: X: initial X will be updated prox_f: proxed function f step_f: step size for prox_f prox_g: proxed function g step_g: specific value of step size for prox_g (experts only!) By default, set to the maximum value of step_f * ||L||_s^2. L: linear operator of the argument of g. Matrix can be numpy.array, scipy.sparse, or None (for identity). e_rel: relative error threshold for primal and dual residuals e_abs: absolute error threshold for primal and dual residuals max_iter: maximum iteration number, irrespective of current residuals traceback: utils.Traceback to hold variable histories Returns: converged: whether the optimizer has converged within e_rel error: X^it - X^it-1 Reference: Moolekamp & Melchior, Algorithm 1 (arXiv:1708.09066)
[ "Alternating", "Direction", "Method", "of", "Multipliers" ]
60e49d90c67c46329cc1d3b5c484951dc8bd2c3f
https://github.com/pmelchior/proxmin/blob/60e49d90c67c46329cc1d3b5c484951dc8bd2c3f/proxmin/algorithms.py#L81-L160
train
34,085
pmelchior/proxmin
proxmin/algorithms.py
bpgm
def bpgm(X, proxs_f, steps_f_cb, update_order=None, accelerated=False, relax=None, max_iter=1000, e_rel=1e-6, traceback=None): """Block Proximal Gradient Method. Also know as Alternating Proximal Gradient Method, it performs Proximal gradient (forward-backward) updates on each block in alternating fashion. Args: X: list of initial Xs, will be updated proxs_f: proxed function f Signature prox(X,step, j=None, Xs=None) -> X' step_f: step size, < 1/L with L being the Lipschitz constant of grad f steps_f_cb: callback function to compute step size for proxs_f[j] Signature: steps_f_cb(j, Xs) -> Reals update_order: list of components to update in desired order. accelerated: If Nesterov acceleration should be used for all variables relax: (over)relaxation parameter for each variable, < 1.5 e_rel: relative error of X max_iter: maximum iteration, irrespective of residual error traceback: utils.Traceback to hold variable histories Returns: converged: whether the optimizer has converged within e_rel error: X^it - X^it-1 """ # Set up N = len(X) if np.isscalar(e_rel): e_rel = [e_rel] * N if relax is not None: assert relax > 0 and relax < 1.5 if update_order is None: update_order = range(N) else: # we could check that every component is in the list # but one can think of cases when a component is *not* to be updated. #assert len(update_order) == N pass # init X_ = [None] * N stepper = utils.NesterovStepper(accelerated=accelerated) if traceback is not None: for j in update_order: traceback.update_history(0, j=j, X=X[j], steps_f=None) if accelerated: traceback.update_history(0, j=j, omega=0) if relax is not None: traceback.update_history(0, j=j, relax=relax) for it in range(max_iter): # use Nesterov acceleration (if omega > 0), automatically incremented omega = stepper.omega # iterate over blocks X_j for j in update_order: # tell prox the state of other variables proxs_f_j = partial(proxs_f, j=j, Xs=X) steps_f_j = steps_f_cb(j, X) # acceleration? # check for resizing: if resize ocurred, temporily skip acceleration if omega > 0 and X[j].shape == X_[j].shape: _X = X[j] + omega*(X[j] - X_[j]) else: _X = X[j] # keep copy for convergence test (and acceleration) X_[j] = X[j].copy() # PGM step, force inline update X[j][:] = proxs_f_j(_X, steps_f_j) if relax is not None: X[j] += (relax-1)*(X[j] - X_[j]) if traceback is not None: traceback.update_history(it+1, j=j, X=X[j], steps_f=steps_f_j) if accelerated: traceback.update_history(it+1, j=j, omega=omega) if relax is not None: traceback.update_history(it+1, j=j, relax=relax) # test for fixed point convergence # allowing for transparent resizing of X: need to check shape of X_ errors = [X[j] - X_[j] if X[j].shape == X_[j].shape else X[j] for j in range(N)] converged = [utils.l2sq(errors[j]) <= e_rel[j]**2*utils.l2sq(X[j]) for j in range(N)] if all(converged): break logger.info("Completed {0} iterations".format(it+1)) if not all(converged): logger.warning("Solution did not converge") return converged, errors
python
def bpgm(X, proxs_f, steps_f_cb, update_order=None, accelerated=False, relax=None, max_iter=1000, e_rel=1e-6, traceback=None): """Block Proximal Gradient Method. Also know as Alternating Proximal Gradient Method, it performs Proximal gradient (forward-backward) updates on each block in alternating fashion. Args: X: list of initial Xs, will be updated proxs_f: proxed function f Signature prox(X,step, j=None, Xs=None) -> X' step_f: step size, < 1/L with L being the Lipschitz constant of grad f steps_f_cb: callback function to compute step size for proxs_f[j] Signature: steps_f_cb(j, Xs) -> Reals update_order: list of components to update in desired order. accelerated: If Nesterov acceleration should be used for all variables relax: (over)relaxation parameter for each variable, < 1.5 e_rel: relative error of X max_iter: maximum iteration, irrespective of residual error traceback: utils.Traceback to hold variable histories Returns: converged: whether the optimizer has converged within e_rel error: X^it - X^it-1 """ # Set up N = len(X) if np.isscalar(e_rel): e_rel = [e_rel] * N if relax is not None: assert relax > 0 and relax < 1.5 if update_order is None: update_order = range(N) else: # we could check that every component is in the list # but one can think of cases when a component is *not* to be updated. #assert len(update_order) == N pass # init X_ = [None] * N stepper = utils.NesterovStepper(accelerated=accelerated) if traceback is not None: for j in update_order: traceback.update_history(0, j=j, X=X[j], steps_f=None) if accelerated: traceback.update_history(0, j=j, omega=0) if relax is not None: traceback.update_history(0, j=j, relax=relax) for it in range(max_iter): # use Nesterov acceleration (if omega > 0), automatically incremented omega = stepper.omega # iterate over blocks X_j for j in update_order: # tell prox the state of other variables proxs_f_j = partial(proxs_f, j=j, Xs=X) steps_f_j = steps_f_cb(j, X) # acceleration? # check for resizing: if resize ocurred, temporily skip acceleration if omega > 0 and X[j].shape == X_[j].shape: _X = X[j] + omega*(X[j] - X_[j]) else: _X = X[j] # keep copy for convergence test (and acceleration) X_[j] = X[j].copy() # PGM step, force inline update X[j][:] = proxs_f_j(_X, steps_f_j) if relax is not None: X[j] += (relax-1)*(X[j] - X_[j]) if traceback is not None: traceback.update_history(it+1, j=j, X=X[j], steps_f=steps_f_j) if accelerated: traceback.update_history(it+1, j=j, omega=omega) if relax is not None: traceback.update_history(it+1, j=j, relax=relax) # test for fixed point convergence # allowing for transparent resizing of X: need to check shape of X_ errors = [X[j] - X_[j] if X[j].shape == X_[j].shape else X[j] for j in range(N)] converged = [utils.l2sq(errors[j]) <= e_rel[j]**2*utils.l2sq(X[j]) for j in range(N)] if all(converged): break logger.info("Completed {0} iterations".format(it+1)) if not all(converged): logger.warning("Solution did not converge") return converged, errors
[ "def", "bpgm", "(", "X", ",", "proxs_f", ",", "steps_f_cb", ",", "update_order", "=", "None", ",", "accelerated", "=", "False", ",", "relax", "=", "None", ",", "max_iter", "=", "1000", ",", "e_rel", "=", "1e-6", ",", "traceback", "=", "None", ")", ":...
Block Proximal Gradient Method. Also know as Alternating Proximal Gradient Method, it performs Proximal gradient (forward-backward) updates on each block in alternating fashion. Args: X: list of initial Xs, will be updated proxs_f: proxed function f Signature prox(X,step, j=None, Xs=None) -> X' step_f: step size, < 1/L with L being the Lipschitz constant of grad f steps_f_cb: callback function to compute step size for proxs_f[j] Signature: steps_f_cb(j, Xs) -> Reals update_order: list of components to update in desired order. accelerated: If Nesterov acceleration should be used for all variables relax: (over)relaxation parameter for each variable, < 1.5 e_rel: relative error of X max_iter: maximum iteration, irrespective of residual error traceback: utils.Traceback to hold variable histories Returns: converged: whether the optimizer has converged within e_rel error: X^it - X^it-1
[ "Block", "Proximal", "Gradient", "Method", "." ]
60e49d90c67c46329cc1d3b5c484951dc8bd2c3f
https://github.com/pmelchior/proxmin/blob/60e49d90c67c46329cc1d3b5c484951dc8bd2c3f/proxmin/algorithms.py#L274-L371
train
34,086
pmelchior/proxmin
proxmin/utils.py
get_step_f
def get_step_f(step_f, lR2, lS2): """Update the stepsize of given the primal and dual errors. See Boyd (2011), section 3.4.1 """ mu, tau = 10, 2 if lR2 > mu*lS2: return step_f * tau elif lS2 > mu*lR2: return step_f / tau return step_f
python
def get_step_f(step_f, lR2, lS2): """Update the stepsize of given the primal and dual errors. See Boyd (2011), section 3.4.1 """ mu, tau = 10, 2 if lR2 > mu*lS2: return step_f * tau elif lS2 > mu*lR2: return step_f / tau return step_f
[ "def", "get_step_f", "(", "step_f", ",", "lR2", ",", "lS2", ")", ":", "mu", ",", "tau", "=", "10", ",", "2", "if", "lR2", ">", "mu", "*", "lS2", ":", "return", "step_f", "*", "tau", "elif", "lS2", ">", "mu", "*", "lR2", ":", "return", "step_f",...
Update the stepsize of given the primal and dual errors. See Boyd (2011), section 3.4.1
[ "Update", "the", "stepsize", "of", "given", "the", "primal", "and", "dual", "errors", "." ]
60e49d90c67c46329cc1d3b5c484951dc8bd2c3f
https://github.com/pmelchior/proxmin/blob/60e49d90c67c46329cc1d3b5c484951dc8bd2c3f/proxmin/utils.py#L300-L310
train
34,087
pmelchior/proxmin
proxmin/utils.py
update_variables
def update_variables(X, Z, U, prox_f, step_f, prox_g, step_g, L): """Update the primal and dual variables Note: X, Z, U are updated inline Returns: LX, R, S """ if not hasattr(prox_g, '__iter__'): if prox_g is not None: dX = step_f/step_g * L.T.dot(L.dot(X) - Z + U) X[:] = prox_f(X - dX, step_f) LX, R, S = do_the_mm(X, step_f, Z, U, prox_g, step_g, L) else: # fall back to simple fixed-point method for f # see do_the_mm for normal definitions of LX,Z,R,S S = -X.copy() X[:] = prox_f(X, step_f) LX = X Z[:] = X[:] R = np.zeros(X.shape, dtype=X.dtype) S += X else: M = len(prox_g) dX = np.sum([step_f/step_g[i] * L[i].T.dot(L[i].dot(X) - Z[i] + U[i]) for i in range(M)], axis=0) X[:] = prox_f(X - dX, step_f) LX = [None] * M R = [None] * M S = [None] * M for i in range(M): LX[i], R[i], S[i] = do_the_mm(X, step_f, Z[i], U[i], prox_g[i], step_g[i], L[i]) return LX, R, S
python
def update_variables(X, Z, U, prox_f, step_f, prox_g, step_g, L): """Update the primal and dual variables Note: X, Z, U are updated inline Returns: LX, R, S """ if not hasattr(prox_g, '__iter__'): if prox_g is not None: dX = step_f/step_g * L.T.dot(L.dot(X) - Z + U) X[:] = prox_f(X - dX, step_f) LX, R, S = do_the_mm(X, step_f, Z, U, prox_g, step_g, L) else: # fall back to simple fixed-point method for f # see do_the_mm for normal definitions of LX,Z,R,S S = -X.copy() X[:] = prox_f(X, step_f) LX = X Z[:] = X[:] R = np.zeros(X.shape, dtype=X.dtype) S += X else: M = len(prox_g) dX = np.sum([step_f/step_g[i] * L[i].T.dot(L[i].dot(X) - Z[i] + U[i]) for i in range(M)], axis=0) X[:] = prox_f(X - dX, step_f) LX = [None] * M R = [None] * M S = [None] * M for i in range(M): LX[i], R[i], S[i] = do_the_mm(X, step_f, Z[i], U[i], prox_g[i], step_g[i], L[i]) return LX, R, S
[ "def", "update_variables", "(", "X", ",", "Z", ",", "U", ",", "prox_f", ",", "step_f", ",", "prox_g", ",", "step_g", ",", "L", ")", ":", "if", "not", "hasattr", "(", "prox_g", ",", "'__iter__'", ")", ":", "if", "prox_g", "is", "not", "None", ":", ...
Update the primal and dual variables Note: X, Z, U are updated inline Returns: LX, R, S
[ "Update", "the", "primal", "and", "dual", "variables" ]
60e49d90c67c46329cc1d3b5c484951dc8bd2c3f
https://github.com/pmelchior/proxmin/blob/60e49d90c67c46329cc1d3b5c484951dc8bd2c3f/proxmin/utils.py#L323-L354
train
34,088
pmelchior/proxmin
proxmin/utils.py
get_variable_errors
def get_variable_errors(X, L, LX, Z, U, step_g, e_rel, e_abs=0): """Get the errors in a single multiplier method step For a given linear operator A, (and its dot product with X to save time), calculate the errors in the prime and dual variables, used by the Boyd 2011 Section 3 stopping criteria. """ n = X.size p = Z.size e_pri2 = np.sqrt(p)*e_abs/L.spectral_norm + e_rel*np.max([l2(LX), l2(Z)]) if step_g is not None: e_dual2 = np.sqrt(n)*e_abs/L.spectral_norm + e_rel*l2(L.T.dot(U)/step_g) else: e_dual2 = np.sqrt(n)*e_abs/L.spectral_norm + e_rel*l2(L.T.dot(U)) return e_pri2, e_dual2
python
def get_variable_errors(X, L, LX, Z, U, step_g, e_rel, e_abs=0): """Get the errors in a single multiplier method step For a given linear operator A, (and its dot product with X to save time), calculate the errors in the prime and dual variables, used by the Boyd 2011 Section 3 stopping criteria. """ n = X.size p = Z.size e_pri2 = np.sqrt(p)*e_abs/L.spectral_norm + e_rel*np.max([l2(LX), l2(Z)]) if step_g is not None: e_dual2 = np.sqrt(n)*e_abs/L.spectral_norm + e_rel*l2(L.T.dot(U)/step_g) else: e_dual2 = np.sqrt(n)*e_abs/L.spectral_norm + e_rel*l2(L.T.dot(U)) return e_pri2, e_dual2
[ "def", "get_variable_errors", "(", "X", ",", "L", ",", "LX", ",", "Z", ",", "U", ",", "step_g", ",", "e_rel", ",", "e_abs", "=", "0", ")", ":", "n", "=", "X", ".", "size", "p", "=", "Z", ".", "size", "e_pri2", "=", "np", ".", "sqrt", "(", "...
Get the errors in a single multiplier method step For a given linear operator A, (and its dot product with X to save time), calculate the errors in the prime and dual variables, used by the Boyd 2011 Section 3 stopping criteria.
[ "Get", "the", "errors", "in", "a", "single", "multiplier", "method", "step" ]
60e49d90c67c46329cc1d3b5c484951dc8bd2c3f
https://github.com/pmelchior/proxmin/blob/60e49d90c67c46329cc1d3b5c484951dc8bd2c3f/proxmin/utils.py#L356-L370
train
34,089
pmelchior/proxmin
proxmin/utils.py
check_constraint_convergence
def check_constraint_convergence(X, L, LX, Z, U, R, S, step_f, step_g, e_rel, e_abs): """Calculate if all constraints have converged. Using the stopping criteria from Boyd 2011, Sec 3.3.1, calculate whether the variables for each constraint have converged. """ if isinstance(L, list): M = len(L) convergence = True errors = [] # recursive call for i in range(M): c, e = check_constraint_convergence(X, L[i], LX[i], Z[i], U[i], R[i], S[i], step_f, step_g[i], e_rel, e_abs) convergence &= c errors.append(e) return convergence, errors else: # check convergence of prime residual R and dual residual S e_pri, e_dual = get_variable_errors(X, L, LX, Z, U, step_g, e_rel, e_abs) lR = l2(R) lS = l2(S) convergence = (lR <= e_pri) and (lS <= e_dual) return convergence, (e_pri, e_dual, lR, lS)
python
def check_constraint_convergence(X, L, LX, Z, U, R, S, step_f, step_g, e_rel, e_abs): """Calculate if all constraints have converged. Using the stopping criteria from Boyd 2011, Sec 3.3.1, calculate whether the variables for each constraint have converged. """ if isinstance(L, list): M = len(L) convergence = True errors = [] # recursive call for i in range(M): c, e = check_constraint_convergence(X, L[i], LX[i], Z[i], U[i], R[i], S[i], step_f, step_g[i], e_rel, e_abs) convergence &= c errors.append(e) return convergence, errors else: # check convergence of prime residual R and dual residual S e_pri, e_dual = get_variable_errors(X, L, LX, Z, U, step_g, e_rel, e_abs) lR = l2(R) lS = l2(S) convergence = (lR <= e_pri) and (lS <= e_dual) return convergence, (e_pri, e_dual, lR, lS)
[ "def", "check_constraint_convergence", "(", "X", ",", "L", ",", "LX", ",", "Z", ",", "U", ",", "R", ",", "S", ",", "step_f", ",", "step_g", ",", "e_rel", ",", "e_abs", ")", ":", "if", "isinstance", "(", "L", ",", "list", ")", ":", "M", "=", "le...
Calculate if all constraints have converged. Using the stopping criteria from Boyd 2011, Sec 3.3.1, calculate whether the variables for each constraint have converged.
[ "Calculate", "if", "all", "constraints", "have", "converged", "." ]
60e49d90c67c46329cc1d3b5c484951dc8bd2c3f
https://github.com/pmelchior/proxmin/blob/60e49d90c67c46329cc1d3b5c484951dc8bd2c3f/proxmin/utils.py#L372-L396
train
34,090
pmelchior/proxmin
proxmin/utils.py
check_convergence
def check_convergence(newX, oldX, e_rel): """Check that the algorithm converges using Langville 2014 criteria Uses the check from Langville 2014, Section 5, to check if the NMF algorithm has converged. """ # Calculate the norm for columns and rows, which can be used for debugging # Otherwise skip, since it takes extra processing time new_old = newX*oldX old2 = oldX**2 norms = [np.sum(new_old), np.sum(old2)] convergent = norms[0] >= (1-e_rel**2)*norms[1] return convergent, norms
python
def check_convergence(newX, oldX, e_rel): """Check that the algorithm converges using Langville 2014 criteria Uses the check from Langville 2014, Section 5, to check if the NMF algorithm has converged. """ # Calculate the norm for columns and rows, which can be used for debugging # Otherwise skip, since it takes extra processing time new_old = newX*oldX old2 = oldX**2 norms = [np.sum(new_old), np.sum(old2)] convergent = norms[0] >= (1-e_rel**2)*norms[1] return convergent, norms
[ "def", "check_convergence", "(", "newX", ",", "oldX", ",", "e_rel", ")", ":", "# Calculate the norm for columns and rows, which can be used for debugging", "# Otherwise skip, since it takes extra processing time", "new_old", "=", "newX", "*", "oldX", "old2", "=", "oldX", "**"...
Check that the algorithm converges using Langville 2014 criteria Uses the check from Langville 2014, Section 5, to check if the NMF algorithm has converged.
[ "Check", "that", "the", "algorithm", "converges", "using", "Langville", "2014", "criteria" ]
60e49d90c67c46329cc1d3b5c484951dc8bd2c3f
https://github.com/pmelchior/proxmin/blob/60e49d90c67c46329cc1d3b5c484951dc8bd2c3f/proxmin/utils.py#L398-L410
train
34,091
pmelchior/proxmin
proxmin/utils.py
Traceback._store_variable
def _store_variable(self, j, key, m, value): """Store a copy of the variable in the history """ if hasattr(value, 'copy'): v = value.copy() else: v = value self.history[j][key][m].append(v)
python
def _store_variable(self, j, key, m, value): """Store a copy of the variable in the history """ if hasattr(value, 'copy'): v = value.copy() else: v = value self.history[j][key][m].append(v)
[ "def", "_store_variable", "(", "self", ",", "j", ",", "key", ",", "m", ",", "value", ")", ":", "if", "hasattr", "(", "value", ",", "'copy'", ")", ":", "v", "=", "value", ".", "copy", "(", ")", "else", ":", "v", "=", "value", "self", ".", "histo...
Store a copy of the variable in the history
[ "Store", "a", "copy", "of", "the", "variable", "in", "the", "history" ]
60e49d90c67c46329cc1d3b5c484951dc8bd2c3f
https://github.com/pmelchior/proxmin/blob/60e49d90c67c46329cc1d3b5c484951dc8bd2c3f/proxmin/utils.py#L147-L155
train
34,092
pmelchior/proxmin
proxmin/utils.py
Traceback.update_history
def update_history(self, it, j=0, M=None, **kwargs): """Add the current state for all kwargs to the history """ # Create a new entry in the history for new variables (if they don't exist) if not np.any([k in self.history[j] for k in kwargs]): for k in kwargs: if M is None or M == 0: self.history[j][k] = [[]] else: self.history[j][k] = [[] for m in range(M)] """ # Check that the variables have been updated once per iteration elif np.any([[len(h)!=it+self.offset for h in self.history[j][k]] for k in kwargs.keys()]): for k in kwargs.keys(): for n,h in enumerate(self.history[j][k]): if len(h) != it+self.offset: err_str = "At iteration {0}, {1}[{2}] already has {3} entries" raise Exception(err_str.format(it, k, n, len(h)-self.offset)) """ # Add the variables to the history for k,v in kwargs.items(): if M is None or M == 0: self._store_variable(j, k, 0, v) else: for m in range(M): self._store_variable(j, k, m, v[m])
python
def update_history(self, it, j=0, M=None, **kwargs): """Add the current state for all kwargs to the history """ # Create a new entry in the history for new variables (if they don't exist) if not np.any([k in self.history[j] for k in kwargs]): for k in kwargs: if M is None or M == 0: self.history[j][k] = [[]] else: self.history[j][k] = [[] for m in range(M)] """ # Check that the variables have been updated once per iteration elif np.any([[len(h)!=it+self.offset for h in self.history[j][k]] for k in kwargs.keys()]): for k in kwargs.keys(): for n,h in enumerate(self.history[j][k]): if len(h) != it+self.offset: err_str = "At iteration {0}, {1}[{2}] already has {3} entries" raise Exception(err_str.format(it, k, n, len(h)-self.offset)) """ # Add the variables to the history for k,v in kwargs.items(): if M is None or M == 0: self._store_variable(j, k, 0, v) else: for m in range(M): self._store_variable(j, k, m, v[m])
[ "def", "update_history", "(", "self", ",", "it", ",", "j", "=", "0", ",", "M", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# Create a new entry in the history for new variables (if they don't exist)", "if", "not", "np", ".", "any", "(", "[", "k", "in", ...
Add the current state for all kwargs to the history
[ "Add", "the", "current", "state", "for", "all", "kwargs", "to", "the", "history" ]
60e49d90c67c46329cc1d3b5c484951dc8bd2c3f
https://github.com/pmelchior/proxmin/blob/60e49d90c67c46329cc1d3b5c484951dc8bd2c3f/proxmin/utils.py#L157-L182
train
34,093
pmelchior/proxmin
examples/unmixing.py
generateComponent
def generateComponent(m): """Creates oscillating components to be mixed""" freq = 25*np.random.random() phase = 2*np.pi*np.random.random() x = np.arange(m) return np.cos(x/freq-phase)**2
python
def generateComponent(m): """Creates oscillating components to be mixed""" freq = 25*np.random.random() phase = 2*np.pi*np.random.random() x = np.arange(m) return np.cos(x/freq-phase)**2
[ "def", "generateComponent", "(", "m", ")", ":", "freq", "=", "25", "*", "np", ".", "random", ".", "random", "(", ")", "phase", "=", "2", "*", "np", ".", "pi", "*", "np", ".", "random", ".", "random", "(", ")", "x", "=", "np", ".", "arange", "...
Creates oscillating components to be mixed
[ "Creates", "oscillating", "components", "to", "be", "mixed" ]
60e49d90c67c46329cc1d3b5c484951dc8bd2c3f
https://github.com/pmelchior/proxmin/blob/60e49d90c67c46329cc1d3b5c484951dc8bd2c3f/examples/unmixing.py#L16-L21
train
34,094
pmelchior/proxmin
examples/unmixing.py
generateAmplitudes
def generateAmplitudes(k): """Makes mixing coefficients""" res = np.array([np.random.random() for i in range(k)]) return res/res.sum()
python
def generateAmplitudes(k): """Makes mixing coefficients""" res = np.array([np.random.random() for i in range(k)]) return res/res.sum()
[ "def", "generateAmplitudes", "(", "k", ")", ":", "res", "=", "np", ".", "array", "(", "[", "np", ".", "random", ".", "random", "(", ")", "for", "i", "in", "range", "(", "k", ")", "]", ")", "return", "res", "/", "res", ".", "sum", "(", ")" ]
Makes mixing coefficients
[ "Makes", "mixing", "coefficients" ]
60e49d90c67c46329cc1d3b5c484951dc8bd2c3f
https://github.com/pmelchior/proxmin/blob/60e49d90c67c46329cc1d3b5c484951dc8bd2c3f/examples/unmixing.py#L23-L26
train
34,095
pmelchior/proxmin
examples/unmixing.py
add_noise
def add_noise(Y, sigma): """Adds noise to Y""" return Y + np.random.normal(0, sigma, Y.shape)
python
def add_noise(Y, sigma): """Adds noise to Y""" return Y + np.random.normal(0, sigma, Y.shape)
[ "def", "add_noise", "(", "Y", ",", "sigma", ")", ":", "return", "Y", "+", "np", ".", "random", ".", "normal", "(", "0", ",", "sigma", ",", "Y", ".", "shape", ")" ]
Adds noise to Y
[ "Adds", "noise", "to", "Y" ]
60e49d90c67c46329cc1d3b5c484951dc8bd2c3f
https://github.com/pmelchior/proxmin/blob/60e49d90c67c46329cc1d3b5c484951dc8bd2c3f/examples/unmixing.py#L28-L30
train
34,096
pmelchior/proxmin
proxmin/nmf.py
nmf
def nmf(Y, A, S, W=None, prox_A=operators.prox_plus, prox_S=operators.prox_plus, proxs_g=None, steps_g=None, Ls=None, slack=0.9, update_order=None, steps_g_update='steps_f', max_iter=1000, e_rel=1e-3, e_abs=0, traceback=None): """Non-negative matrix factorization. This method solves the NMF problem minimize || Y - AS ||_2^2 under an arbitrary number of constraints on A and/or S. Args: Y: target matrix MxN A: initial amplitude matrix MxK, will be updated S: initial source matrix KxN, will be updated W: (optional weight matrix MxN) prox_A: direct projection contraint of A prox_S: direct projection constraint of S proxs_g: list of constraints for A or S for ADMM-type optimization [[prox_A_0, prox_A_1...],[prox_S_0, prox_S_1,...]] steps_g: specific value of step size for proxs_g (experts only!) Ls: list of linear operators for the constraint functions proxs_g If set, needs to have same format as proxs_g. Matrices can be numpy.array, scipy.sparse, or None (for identity). slack: tolerance for (re)evaluation of Lipschitz constants See Steps_AS() for details. update_order: list of factor indices in update order j=0 -> A, j=1 -> S max_iter: maximum iteration number, irrespective of current residuals e_rel: relative error threshold for primal and dual residuals e_abs: absolute error threshold for primal and dual residuals traceback: utils.Traceback to hold variable histories Returns: converged: convence test for A,S errors: difference between latest and previous iterations for A,S See also: algorithms.bsdmm for update_order and steps_g_update utils.AcceleratedProxF for Nesterov acceleration Reference: Moolekamp & Melchior, 2017 (arXiv:1708.09066) """ # create stepsize callback, needs max of W if W is not None: # normalize in pixel and band directions to have similar update speeds WA = normalizeMatrix(W, 1) WS = normalizeMatrix(W, 0) else: WA = WS = 1 steps_f = Steps_AS(WA=WA, WS=WS, slack=slack) # gradient step, followed by direct application of prox_S or prox_A from functools import partial f = partial(prox_likelihood, Y=Y, WA=WA, WS=WS, prox_S=prox_S, prox_A=prox_A) X = [A, S] # use accelerated block-PGM if there's no proxs_g if proxs_g is None or not utils.hasNotNone(proxs_g): return algorithms.bpgm(X, f, steps_f, accelerated=True, update_order=update_order, max_iter=max_iter, e_rel=e_rel, traceback=traceback) else: return algorithms.bsdmm(X, f, steps_f, proxs_g, steps_g=steps_g, Ls=Ls, update_order=update_order, steps_g_update=steps_g_update, max_iter=max_iter, e_rel=e_rel, e_abs=e_abs, traceback=traceback)
python
def nmf(Y, A, S, W=None, prox_A=operators.prox_plus, prox_S=operators.prox_plus, proxs_g=None, steps_g=None, Ls=None, slack=0.9, update_order=None, steps_g_update='steps_f', max_iter=1000, e_rel=1e-3, e_abs=0, traceback=None): """Non-negative matrix factorization. This method solves the NMF problem minimize || Y - AS ||_2^2 under an arbitrary number of constraints on A and/or S. Args: Y: target matrix MxN A: initial amplitude matrix MxK, will be updated S: initial source matrix KxN, will be updated W: (optional weight matrix MxN) prox_A: direct projection contraint of A prox_S: direct projection constraint of S proxs_g: list of constraints for A or S for ADMM-type optimization [[prox_A_0, prox_A_1...],[prox_S_0, prox_S_1,...]] steps_g: specific value of step size for proxs_g (experts only!) Ls: list of linear operators for the constraint functions proxs_g If set, needs to have same format as proxs_g. Matrices can be numpy.array, scipy.sparse, or None (for identity). slack: tolerance for (re)evaluation of Lipschitz constants See Steps_AS() for details. update_order: list of factor indices in update order j=0 -> A, j=1 -> S max_iter: maximum iteration number, irrespective of current residuals e_rel: relative error threshold for primal and dual residuals e_abs: absolute error threshold for primal and dual residuals traceback: utils.Traceback to hold variable histories Returns: converged: convence test for A,S errors: difference between latest and previous iterations for A,S See also: algorithms.bsdmm for update_order and steps_g_update utils.AcceleratedProxF for Nesterov acceleration Reference: Moolekamp & Melchior, 2017 (arXiv:1708.09066) """ # create stepsize callback, needs max of W if W is not None: # normalize in pixel and band directions to have similar update speeds WA = normalizeMatrix(W, 1) WS = normalizeMatrix(W, 0) else: WA = WS = 1 steps_f = Steps_AS(WA=WA, WS=WS, slack=slack) # gradient step, followed by direct application of prox_S or prox_A from functools import partial f = partial(prox_likelihood, Y=Y, WA=WA, WS=WS, prox_S=prox_S, prox_A=prox_A) X = [A, S] # use accelerated block-PGM if there's no proxs_g if proxs_g is None or not utils.hasNotNone(proxs_g): return algorithms.bpgm(X, f, steps_f, accelerated=True, update_order=update_order, max_iter=max_iter, e_rel=e_rel, traceback=traceback) else: return algorithms.bsdmm(X, f, steps_f, proxs_g, steps_g=steps_g, Ls=Ls, update_order=update_order, steps_g_update=steps_g_update, max_iter=max_iter, e_rel=e_rel, e_abs=e_abs, traceback=traceback)
[ "def", "nmf", "(", "Y", ",", "A", ",", "S", ",", "W", "=", "None", ",", "prox_A", "=", "operators", ".", "prox_plus", ",", "prox_S", "=", "operators", ".", "prox_plus", ",", "proxs_g", "=", "None", ",", "steps_g", "=", "None", ",", "Ls", "=", "No...
Non-negative matrix factorization. This method solves the NMF problem minimize || Y - AS ||_2^2 under an arbitrary number of constraints on A and/or S. Args: Y: target matrix MxN A: initial amplitude matrix MxK, will be updated S: initial source matrix KxN, will be updated W: (optional weight matrix MxN) prox_A: direct projection contraint of A prox_S: direct projection constraint of S proxs_g: list of constraints for A or S for ADMM-type optimization [[prox_A_0, prox_A_1...],[prox_S_0, prox_S_1,...]] steps_g: specific value of step size for proxs_g (experts only!) Ls: list of linear operators for the constraint functions proxs_g If set, needs to have same format as proxs_g. Matrices can be numpy.array, scipy.sparse, or None (for identity). slack: tolerance for (re)evaluation of Lipschitz constants See Steps_AS() for details. update_order: list of factor indices in update order j=0 -> A, j=1 -> S max_iter: maximum iteration number, irrespective of current residuals e_rel: relative error threshold for primal and dual residuals e_abs: absolute error threshold for primal and dual residuals traceback: utils.Traceback to hold variable histories Returns: converged: convence test for A,S errors: difference between latest and previous iterations for A,S See also: algorithms.bsdmm for update_order and steps_g_update utils.AcceleratedProxF for Nesterov acceleration Reference: Moolekamp & Melchior, 2017 (arXiv:1708.09066)
[ "Non", "-", "negative", "matrix", "factorization", "." ]
60e49d90c67c46329cc1d3b5c484951dc8bd2c3f
https://github.com/pmelchior/proxmin/blob/60e49d90c67c46329cc1d3b5c484951dc8bd2c3f/proxmin/nmf.py#L107-L167
train
34,097
pmelchior/proxmin
proxmin/operators.py
prox_zero
def prox_zero(X, step): """Proximal operator to project onto zero """ return np.zeros(X.shape, dtype=X.dtype)
python
def prox_zero(X, step): """Proximal operator to project onto zero """ return np.zeros(X.shape, dtype=X.dtype)
[ "def", "prox_zero", "(", "X", ",", "step", ")", ":", "return", "np", ".", "zeros", "(", "X", ".", "shape", ",", "dtype", "=", "X", ".", "dtype", ")" ]
Proximal operator to project onto zero
[ "Proximal", "operator", "to", "project", "onto", "zero" ]
60e49d90c67c46329cc1d3b5c484951dc8bd2c3f
https://github.com/pmelchior/proxmin/blob/60e49d90c67c46329cc1d3b5c484951dc8bd2c3f/proxmin/operators.py#L22-L25
train
34,098
pmelchior/proxmin
proxmin/operators.py
prox_unity
def prox_unity(X, step, axis=0): """Projection onto sum=1 along an axis """ return X / np.sum(X, axis=axis, keepdims=True)
python
def prox_unity(X, step, axis=0): """Projection onto sum=1 along an axis """ return X / np.sum(X, axis=axis, keepdims=True)
[ "def", "prox_unity", "(", "X", ",", "step", ",", "axis", "=", "0", ")", ":", "return", "X", "/", "np", ".", "sum", "(", "X", ",", "axis", "=", "axis", ",", "keepdims", "=", "True", ")" ]
Projection onto sum=1 along an axis
[ "Projection", "onto", "sum", "=", "1", "along", "an", "axis" ]
60e49d90c67c46329cc1d3b5c484951dc8bd2c3f
https://github.com/pmelchior/proxmin/blob/60e49d90c67c46329cc1d3b5c484951dc8bd2c3f/proxmin/operators.py#L34-L37
train
34,099