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
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
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. >>> >>> :p...
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. >>> >>> :p...
[ "def", "cmd", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "wrapper", "(", "*", "args", ",", "**", "kwargs", ")", ":", "return", "f", "(", "*", "args", ",", "**", "kwargs", ")", "setattr", "(", "wrapper", ",", "executors", ".", "EXEC...
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...
[ "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
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: ...
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: ...
[ "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 {...
[ "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
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 = ...
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 = ...
[ "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
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
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 worke...
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 worke...
[ "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
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...
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...
[ "def", "get_inline_func", "(", "inline_str", ",", "modules", "=", "None", ",", "**", "stream_kwargs", ")", ":", "if", "not", "_is_compilable", "(", "inline_str", ")", ":", "raise", "ValueError", "(", "'cannot compile the inline expression - \"%s\"'", "%", "inline_st...
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 fu...
[ "returns", "a", "function", "decorated", "by", "cbox", ".", "stream", "decorator", "." ]
2d0cda5b3f61a55e530251430bf3d460dcd3732e
https://github.com/shmuelamar/cbox/blob/2d0cda5b3f61a55e530251430bf3d460dcd3732e/cbox/__main__.py#L77-L95
train
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__'): s...
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__'): s...
[ "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
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...
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...
[ "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 ...
[ "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
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:`Fals...
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:`Fals...
[ "def", "input", "(", "channel", ")", ":", "_check_configured", "(", "channel", ")", "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:`G...
[ "Read", "the", "value", "of", "a", "GPIO", "pin", "." ]
d151885eb0f0fc25d4a86266eefebc105700f3fd
https://github.com/rm-hull/OPi.GPIO/blob/d151885eb0f0fc25d4a86266eefebc105700f3fd/OPi/GPIO.py#L373-L384
train
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` ...
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` ...
[ "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.HIG...
[ "Set", "the", "output", "state", "of", "a", "GPIO", "pin", "." ]
d151885eb0f0fc25d4a86266eefebc105700f3fd
https://github.com/rm-hull/OPi.GPIO/blob/d151885eb0f0fc25d4a86266eefebc105700f3fd/OPi/GPIO.py#L387-L411
train
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`). :p...
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`). :p...
[ "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.RIS...
[ "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
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:...
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:...
[ "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
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
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...
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...
[ "def", "update", "(", "self", ",", "entries", "=", "{", "}", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "isinstance", "(", "entries", ",", "dict", ")", ":", "entries", "=", "self", ".", "_reject_reserved_keys", "(", "entries", ")", "for",...
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
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...
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...
[ "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. Defau...
[ "Parse", "data", "files", "from", "the", "data", "directory" ]
21a8a7f5eebea40f270beef9ede4d9a57e3c81c3
https://github.com/elyase/geotext/blob/21a8a7f5eebea40f270beef9ede4d9a57e3c81c3/geotext/geotext.py#L15-L60
train
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 co...
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 co...
[ "def", "build_index", "(", ")", ":", "nationalities", "=", "read_table", "(", "get_data_path", "(", "'nationalities.txt'", ")", ",", "sep", "=", "':'", ")", "countries", "=", "read_table", "(", "get_data_path", "(", "'countryInfo.txt'", ")", ",", "usecols", "=...
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
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 ...
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 ...
[ "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
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('...
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('...
[ "def", "get_elastix_exes", "(", ")", ":", "if", "EXES", ":", "if", "EXES", "[", "0", "]", ":", "return", "EXES", "else", ":", "raise", "RuntimeError", "(", "'No Elastix executable.'", ")", "elastix", ",", "ver", "=", "_find_executables", "(", "'elastix'", ...
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
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) e...
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) e...
[ "def", "_clear_dir", "(", "dirName", ")", ":", "for", "fname", "in", "os", ".", "listdir", "(", "dirName", ")", ":", "try", ":", "os", ".", "remove", "(", "os", ".", "path", ".", "join", "(", "dirName", ",", "fname", ")", ")", "except", "Exception"...
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
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. ...
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. ...
[ "def", "get_tempdir", "(", ")", ":", "tempdir", "=", "os", ".", "path", ".", "join", "(", "tempfile", ".", "gettempdir", "(", ")", ",", "'pyelastix'", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "tempdir", ")", ":", "os", ".", "makedirs...
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
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
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: # Gr...
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: # Gr...
[ "def", "_get_image_paths", "(", "im1", ",", "im2", ")", ":", "paths", "=", "[", "]", "for", "im", "in", "[", "im1", ",", "im2", "]", ":", "if", "im", "is", "None", ":", "paths", ".", "append", "(", "paths", "[", "0", "]", ")", "continue", "if",...
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
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() ...
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() ...
[ "def", "_system3", "(", "cmd", ",", "verbose", "=", "False", ")", ":", "interrupted", "=", "False", "if", "verbose", ">", "0", ":", "progress", "=", "Progress", "(", ")", "stdout", "=", "[", "]", "def", "poll_process", "(", "p", ")", ":", "while", ...
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
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'), (...
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'), (...
[ "def", "_get_dtype_maps", "(", ")", ":", "tmp", "=", "[", "(", "np", ".", "float32", ",", "'MET_FLOAT'", ")", ",", "(", "np", ".", "float64", ",", "'MET_DOUBLE'", ")", ",", "(", "np", ".", "uint8", ",", "'MET_UCHAR'", ")", ",", "(", "np", ".", "i...
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
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.findal...
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.findal...
[ "def", "_read_image_data", "(", "mhd_file", ")", ":", "tempdir", "=", "get_tempdir", "(", ")", "fname", "=", "tempdir", "+", "'/'", "+", "mhd_file", "des", "=", "open", "(", "fname", ",", "'r'", ")", ".", "read", "(", ")", "match", "=", "re", ".", ...
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
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 =...
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 =...
[ "def", "_get_fixed_params", "(", "im", ")", ":", "p", "=", "Parameters", "(", ")", "if", "not", "isinstance", "(", "im", ",", "np", ".", "ndarray", ")", ":", "return", "p", "p", ".", "FixedImageDimension", "=", "im", ".", "ndim", "p", ".", "MovingIma...
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
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" #...
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" #...
[ "def", "get_advanced_params", "(", ")", ":", "p", "=", "Parameters", "(", ")", "p", ".", "FixedInternalImagePixelType", "=", "\"float\"", "p", ".", "MovingInternalImagePixelType", "=", "\"float\"", "p", ".", "UseDirectionCosines", "=", "True", "p", ".", "Registr...
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
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() ...
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() ...
[ "def", "_write_parameter_file", "(", "params", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "get_tempdir", "(", ")", ",", "'params.txt'", ")", "def", "valToStr", "(", "val", ")", ":", "if", "val", "in", "[", "True", ",", "False", "]", ...
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
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 s...
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 s...
[ "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...
[ "Syntax", "-", "highlights", "HTML", "-", "rendered", "Markdown", "." ]
7bf7529296acfa7db0edf7914cb4571d691b63ee
https://github.com/pypa/readme_renderer/blob/7bf7529296acfa7db0edf7914cb4571d691b63ee/readme_renderer/markdown.py#L68-L110
train
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 deprec...
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 deprec...
[ "def", "check_restructuredtext", "(", "self", ")", ":", "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\"", ")"...
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
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.highlig...
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.highlig...
[ "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
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 ...
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 ...
[ "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
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: ...
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: ...
[ "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
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 ...
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 ...
[ "def", "parse_optimization_expression", "(", "obj", ",", "linear", "=", "True", ",", "quadratic", "=", "False", ",", "expression", "=", "None", ",", "**", "kwargs", ")", ":", "if", "expression", "is", "None", ":", "expression", "=", "obj", ".", "expression...
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 expressi...
[ "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
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 e...
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 e...
[ "def", "_parse_quadratic_expression", "(", "expression", ",", "expanded", "=", "False", ")", ":", "linear_coefficients", "=", "{", "}", "quadratic_coefficients", "=", "{", "}", "offset", "=", "0", "if", "expression", ".", "is_Number", ":", "return", "float", "...
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
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, l...
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, l...
[ "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
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) ) ...
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) ) ...
[ "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
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) """ j...
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) """ j...
[ "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
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 co...
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 co...
[ "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 variable...
[ "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
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) """ ...
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) """ ...
[ "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
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) """ retur...
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) """ retur...
[ "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
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) """ ...
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) """ ...
[ "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
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 var...
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 var...
[ "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
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...
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...
[ "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
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...
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...
[ "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 y...
[ "Add", "variables", "and", "constraints", "." ]
13673ac26f6b3ba37a2ef392489722c52e3c5ff1
https://github.com/biosustain/optlang/blob/13673ac26f6b3ba37a2ef392489722c52e3c5ff1/optlang/interface.py#L1340-L1375
train
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). ...
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). ...
[ "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 ------- Non...
[ "Remove", "variables", "and", "constraints", "." ]
13673ac26f6b3ba37a2ef392489722c52e3c5ff1
https://github.com/biosustain/optlang/blob/13673ac26f6b3ba37a2ef392489722c52e3c5ff1/optlang/interface.py#L1377-L1415
train
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 = [] cal...
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 = [] cal...
[ "def", "update", "(", "self", ",", "callback", "=", "int", ")", ":", "add_var", "=", "self", ".", "_pending_modifications", ".", "add_var", "if", "len", "(", "add_var", ")", ">", "0", ":", "self", ".", "_add_variables", "(", "add_var", ")", "self", "."...
Process all pending model modifications.
[ "Process", "all", "pending", "model", "modifications", "." ]
13673ac26f6b3ba37a2ef392489722c52e3c5ff1
https://github.com/biosustain/optlang/blob/13673ac26f6b3ba37a2ef392489722c52e3c5ff1/optlang/interface.py#L1417-L1452
train
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. ...
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. ...
[ "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 access...
[ "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
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 >...
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 >...
[ "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") ...
[ "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
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 'as...
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 'as...
[ "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 solutio...
[ "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
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) ret...
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) ret...
[ "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
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_...
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_...
[ "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
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: ...
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: ...
[ "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
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
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 coe...
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 coe...
[ "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
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[na...
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[na...
[ "def", "remove_variable", "(", "self", ",", "name", ")", ":", "index", "=", "self", ".", "_get_var_index", "(", "name", ")", "self", ".", "_A", "=", "np", ".", "delete", "(", "self", ".", "A", ",", "index", ",", "1", ")", "del", "self", ".", "bou...
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
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) # R...
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) # R...
[ "def", "remove_constraint", "(", "self", ",", "name", ")", ":", "index", "=", "self", ".", "_get_constraint_index", "(", "name", ")", "self", ".", "_A", "=", "np", ".", "delete", "(", "self", ".", "A", ",", "index", ",", "0", ")", "self", ".", "upp...
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
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
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
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
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.iterval...
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.iterval...
[ "def", "optimize", "(", "self", ",", "method", "=", "\"simplex\"", ",", "verbosity", "=", "False", ",", "tolerance", "=", "1e-9", ",", "**", "kwargs", ")", ":", "c", "=", "np", ".", "array", "(", "[", "self", ".", "objective", ".", "get", "(", "nam...
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
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
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...
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...
[ "def", "install", "(", "application", ",", "io_loop", "=", "None", ",", "**", "kwargs", ")", ":", "if", "getattr", "(", "application", ",", "'amqp'", ",", "None", ")", "is", "not", "None", ":", "LOGGER", ".", "warning", "(", "'AMQP is already installed'", ...
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
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 :par...
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 :par...
[ "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.c...
[ "Publish", "a", "message", "to", "RabbitMQ" ]
de22b85aec1315bc01e47774637098c34525692b
https://github.com/sprockets/sprockets.mixins.amqp/blob/de22b85aec1315bc01e47774637098c34525692b/sprockets/mixins/amqp/__init__.py#L108-L126
train
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:...
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:...
[ "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...
[ "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
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 mes...
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 mes...
[ "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.Pu...
[ "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
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) ...
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) ...
[ "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
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_late...
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_late...
[ "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
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( sel...
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( sel...
[ "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
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', ...
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', ...
[ "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
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...
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...
[ "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
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 connect...
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 connect...
[ "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 ...
[ "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
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 pi...
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 pi...
[ "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 ...
[ "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
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. ...
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. ...
[ "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 ...
[ "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
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
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_subje...
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_subje...
[ "def", "from_response", "(", "cls", ",", "response_data", ")", ":", "identity", "=", "lambda", "x", ":", "x", "return", "Mail", "(", "**", "_transform_dict", "(", "response_data", ",", "{", "'guid'", ":", "(", "'mail_id'", ",", "identity", ")", ",", "'su...
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
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
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 c...
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 c...
[ "def", "prox_circle", "(", "xy", ",", "step", ")", ":", "center", "=", "np", ".", "array", "(", "[", "0", ",", "0", "]", ")", "dxy", "=", "xy", "-", "center", "radius", "=", "0.5", "if", "1", ":", "phi", "=", "np", ".", "arctan2", "(", "dxy",...
Projection onto circle
[ "Projection", "onto", "circle" ]
60e49d90c67c46329cc1d3b5c484951dc8bd2c3f
https://github.com/pmelchior/proxmin/blob/60e49d90c67c46329cc1d3b5c484951dc8bd2c3f/examples/parabola.py#L30-L42
train
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
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
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
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
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
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_lim...
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_lim...
[ "def", "prox_gradf_lim12", "(", "x", ",", "step", ",", "j", "=", "None", ",", "Xs", "=", "None", ",", "boundary", "=", "None", ")", ":", "if", "j", "==", "0", ":", "x", "-=", "step", "*", "grad_fx", "(", "Xs", "[", "0", "]", "[", "0", "]", ...
1D projection operator
[ "1D", "projection", "operator" ]
60e49d90c67c46329cc1d3b5c484951dc8bd2c3f
https://github.com/pmelchior/proxmin/blob/60e49d90c67c46329cc1d3b5c484951dc8bd2c3f/examples/parabola.py#L121-L129
train
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 update...
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 update...
[ "def", "pgm", "(", "X", ",", "prox_f", ",", "step_f", ",", "accelerated", "=", "False", ",", "relax", "=", "None", ",", "e_rel", "=", "1e-6", ",", "max_iter", "=", "1000", ",", "traceback", "=", "None", ")", ":", "stepper", "=", "utils", ".", "Nest...
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...
[ "Proximal", "Gradient", "Method" ]
60e49d90c67c46329cc1d3b5c484951dc8bd2c3f
https://github.com/pmelchior/proxmin/blob/60e49d90c67c46329cc1d3b5c484951dc8bd2c3f/proxmin/algorithms.py#L10-L78
train
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...
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...
[ "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 ...
[ "Alternating", "Direction", "Method", "of", "Multipliers" ]
60e49d90c67c46329cc1d3b5c484951dc8bd2c3f
https://github.com/pmelchior/proxmin/blob/60e49d90c67c46329cc1d3b5c484951dc8bd2c3f/proxmin/algorithms.py#L81-L160
train
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....
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....
[ "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=Non...
[ "Block", "Proximal", "Gradient", "Method", "." ]
60e49d90c67c46329cc1d3b5c484951dc8bd2c3f
https://github.com/pmelchior/proxmin/blob/60e49d90c67c46329cc1d3b5c484951dc8bd2c3f/proxmin/algorithms.py#L274-L371
train
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
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) ...
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) ...
[ "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
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. ""...
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. ""...
[ "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
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 = l...
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 = l...
[ "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
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 sk...
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 sk...
[ "def", "check_convergence", "(", "newX", ",", "oldX", ",", "e_rel", ")", ":", "new_old", "=", "newX", "*", "oldX", "old2", "=", "oldX", "**", "2", "norms", "=", "[", "np", ".", "sum", "(", "new_old", ")", ",", "np", ".", "sum", "(", "old2", ")", ...
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
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
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: ...
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: ...
[ "def", "update_history", "(", "self", ",", "it", ",", "j", "=", "0", ",", "M", "=", "None", ",", "**", "kwargs", ")", ":", "if", "not", "np", ".", "any", "(", "[", "k", "in", "self", ".", "history", "[", "j", "]", "for", "k", "in", "kwargs", ...
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
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
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
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
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 min...
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 min...
[ "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...
[ "Non", "-", "negative", "matrix", "factorization", "." ]
60e49d90c67c46329cc1d3b5c484951dc8bd2c3f
https://github.com/pmelchior/proxmin/blob/60e49d90c67c46329cc1d3b5c484951dc8bd2c3f/proxmin/nmf.py#L107-L167
train
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
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