id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
227,000 | google/openhtf | openhtf/plugs/usb/__init__.py | _open_usb_handle | def _open_usb_handle(serial_number=None, **kwargs):
"""Open a UsbHandle subclass, based on configuration.
If configuration 'remote_usb' is set, use it to connect to remote usb,
otherwise attempt to connect locally.'remote_usb' is set to usb type,
EtherSync or other.
Example of Cambrionix unit in config:
remote_usb: ethersync
ethersync:
mac_addr: 78:a5:04:ca:91:66
plug_port: 5
Args:
serial_number: Optional serial number to connect to.
**kwargs: Arguments to pass to respective handle's Open() method.
Returns:
Instance of UsbHandle.
"""
init_dependent_flags()
remote_usb = conf.remote_usb
if remote_usb:
if remote_usb.strip() == 'ethersync':
device = conf.ethersync
try:
mac_addr = device['mac_addr']
port = device['plug_port']
except (KeyError, TypeError):
raise ValueError('Ethersync needs mac_addr and plug_port to be set')
else:
ethersync = cambrionix.EtherSync(mac_addr)
serial_number = ethersync.get_usb_serial(port)
return local_usb.LibUsbHandle.open(serial_number=serial_number, **kwargs) | python | def _open_usb_handle(serial_number=None, **kwargs):
"""Open a UsbHandle subclass, based on configuration.
If configuration 'remote_usb' is set, use it to connect to remote usb,
otherwise attempt to connect locally.'remote_usb' is set to usb type,
EtherSync or other.
Example of Cambrionix unit in config:
remote_usb: ethersync
ethersync:
mac_addr: 78:a5:04:ca:91:66
plug_port: 5
Args:
serial_number: Optional serial number to connect to.
**kwargs: Arguments to pass to respective handle's Open() method.
Returns:
Instance of UsbHandle.
"""
init_dependent_flags()
remote_usb = conf.remote_usb
if remote_usb:
if remote_usb.strip() == 'ethersync':
device = conf.ethersync
try:
mac_addr = device['mac_addr']
port = device['plug_port']
except (KeyError, TypeError):
raise ValueError('Ethersync needs mac_addr and plug_port to be set')
else:
ethersync = cambrionix.EtherSync(mac_addr)
serial_number = ethersync.get_usb_serial(port)
return local_usb.LibUsbHandle.open(serial_number=serial_number, **kwargs) | [
"def",
"_open_usb_handle",
"(",
"serial_number",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"init_dependent_flags",
"(",
")",
"remote_usb",
"=",
"conf",
".",
"remote_usb",
"if",
"remote_usb",
":",
"if",
"remote_usb",
".",
"strip",
"(",
")",
"==",
"'ethersync'",
":",
"device",
"=",
"conf",
".",
"ethersync",
"try",
":",
"mac_addr",
"=",
"device",
"[",
"'mac_addr'",
"]",
"port",
"=",
"device",
"[",
"'plug_port'",
"]",
"except",
"(",
"KeyError",
",",
"TypeError",
")",
":",
"raise",
"ValueError",
"(",
"'Ethersync needs mac_addr and plug_port to be set'",
")",
"else",
":",
"ethersync",
"=",
"cambrionix",
".",
"EtherSync",
"(",
"mac_addr",
")",
"serial_number",
"=",
"ethersync",
".",
"get_usb_serial",
"(",
"port",
")",
"return",
"local_usb",
".",
"LibUsbHandle",
".",
"open",
"(",
"serial_number",
"=",
"serial_number",
",",
"*",
"*",
"kwargs",
")"
] | Open a UsbHandle subclass, based on configuration.
If configuration 'remote_usb' is set, use it to connect to remote usb,
otherwise attempt to connect locally.'remote_usb' is set to usb type,
EtherSync or other.
Example of Cambrionix unit in config:
remote_usb: ethersync
ethersync:
mac_addr: 78:a5:04:ca:91:66
plug_port: 5
Args:
serial_number: Optional serial number to connect to.
**kwargs: Arguments to pass to respective handle's Open() method.
Returns:
Instance of UsbHandle. | [
"Open",
"a",
"UsbHandle",
"subclass",
"based",
"on",
"configuration",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/__init__.py#L62-L96 |
227,001 | google/openhtf | openhtf/plugs/usb/__init__.py | AndroidTriggers._try_open | def _try_open(cls):
"""Try to open a USB handle."""
handle = None
for usb_cls, subcls, protocol in [(adb_device.CLASS,
adb_device.SUBCLASS,
adb_device.PROTOCOL),
(fastboot_device.CLASS,
fastboot_device.SUBCLASS,
fastboot_device.PROTOCOL)]:
try:
handle = local_usb.LibUsbHandle.open(
serial_number=cls.serial_number,
interface_class=usb_cls,
interface_subclass=subcls,
interface_protocol=protocol)
cls.serial_number = handle.serial_number
return True
except usb_exceptions.DeviceNotFoundError:
pass
except usb_exceptions.MultipleInterfacesFoundError:
_LOG.warning('Multiple Android devices found, ignoring!')
finally:
if handle:
handle.close()
return False | python | def _try_open(cls):
"""Try to open a USB handle."""
handle = None
for usb_cls, subcls, protocol in [(adb_device.CLASS,
adb_device.SUBCLASS,
adb_device.PROTOCOL),
(fastboot_device.CLASS,
fastboot_device.SUBCLASS,
fastboot_device.PROTOCOL)]:
try:
handle = local_usb.LibUsbHandle.open(
serial_number=cls.serial_number,
interface_class=usb_cls,
interface_subclass=subcls,
interface_protocol=protocol)
cls.serial_number = handle.serial_number
return True
except usb_exceptions.DeviceNotFoundError:
pass
except usb_exceptions.MultipleInterfacesFoundError:
_LOG.warning('Multiple Android devices found, ignoring!')
finally:
if handle:
handle.close()
return False | [
"def",
"_try_open",
"(",
"cls",
")",
":",
"handle",
"=",
"None",
"for",
"usb_cls",
",",
"subcls",
",",
"protocol",
"in",
"[",
"(",
"adb_device",
".",
"CLASS",
",",
"adb_device",
".",
"SUBCLASS",
",",
"adb_device",
".",
"PROTOCOL",
")",
",",
"(",
"fastboot_device",
".",
"CLASS",
",",
"fastboot_device",
".",
"SUBCLASS",
",",
"fastboot_device",
".",
"PROTOCOL",
")",
"]",
":",
"try",
":",
"handle",
"=",
"local_usb",
".",
"LibUsbHandle",
".",
"open",
"(",
"serial_number",
"=",
"cls",
".",
"serial_number",
",",
"interface_class",
"=",
"usb_cls",
",",
"interface_subclass",
"=",
"subcls",
",",
"interface_protocol",
"=",
"protocol",
")",
"cls",
".",
"serial_number",
"=",
"handle",
".",
"serial_number",
"return",
"True",
"except",
"usb_exceptions",
".",
"DeviceNotFoundError",
":",
"pass",
"except",
"usb_exceptions",
".",
"MultipleInterfacesFoundError",
":",
"_LOG",
".",
"warning",
"(",
"'Multiple Android devices found, ignoring!'",
")",
"finally",
":",
"if",
"handle",
":",
"handle",
".",
"close",
"(",
")",
"return",
"False"
] | Try to open a USB handle. | [
"Try",
"to",
"open",
"a",
"USB",
"handle",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/__init__.py#L164-L188 |
227,002 | google/openhtf | openhtf/plugs/usb/fastboot_device.py | _retry_usb_function | def _retry_usb_function(count, func, *args, **kwargs):
"""Helper function to retry USB."""
helper = timeouts.RetryHelper(count)
while True:
try:
return func(*args, **kwargs)
except usb_exceptions.CommonUsbError:
if not helper.retry_if_possible():
raise
time.sleep(0.1)
else:
break | python | def _retry_usb_function(count, func, *args, **kwargs):
"""Helper function to retry USB."""
helper = timeouts.RetryHelper(count)
while True:
try:
return func(*args, **kwargs)
except usb_exceptions.CommonUsbError:
if not helper.retry_if_possible():
raise
time.sleep(0.1)
else:
break | [
"def",
"_retry_usb_function",
"(",
"count",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"helper",
"=",
"timeouts",
".",
"RetryHelper",
"(",
"count",
")",
"while",
"True",
":",
"try",
":",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"usb_exceptions",
".",
"CommonUsbError",
":",
"if",
"not",
"helper",
".",
"retry_if_possible",
"(",
")",
":",
"raise",
"time",
".",
"sleep",
"(",
"0.1",
")",
"else",
":",
"break"
] | Helper function to retry USB. | [
"Helper",
"function",
"to",
"retry",
"USB",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/fastboot_device.py#L112-L123 |
227,003 | google/openhtf | openhtf/plugs/usb/fastboot_device.py | FastbootDevice.get_boot_config | def get_boot_config(self, name, info_cb=None):
"""Get bootconfig, either as full dict or specific value for key."""
result = {}
def default_info_cb(msg):
"""Default Info CB."""
if not msg.message:
return
key, value = msg.message.split(':', 1)
result[key.strip()] = value.strip()
info_cb = info_cb or default_info_cb
final_result = self.oem('bootconfig %s' % name, info_cb=info_cb)
# Return INFO messages before the final OKAY message.
if name in result:
return result[name]
return final_result | python | def get_boot_config(self, name, info_cb=None):
"""Get bootconfig, either as full dict or specific value for key."""
result = {}
def default_info_cb(msg):
"""Default Info CB."""
if not msg.message:
return
key, value = msg.message.split(':', 1)
result[key.strip()] = value.strip()
info_cb = info_cb or default_info_cb
final_result = self.oem('bootconfig %s' % name, info_cb=info_cb)
# Return INFO messages before the final OKAY message.
if name in result:
return result[name]
return final_result | [
"def",
"get_boot_config",
"(",
"self",
",",
"name",
",",
"info_cb",
"=",
"None",
")",
":",
"result",
"=",
"{",
"}",
"def",
"default_info_cb",
"(",
"msg",
")",
":",
"\"\"\"Default Info CB.\"\"\"",
"if",
"not",
"msg",
".",
"message",
":",
"return",
"key",
",",
"value",
"=",
"msg",
".",
"message",
".",
"split",
"(",
"':'",
",",
"1",
")",
"result",
"[",
"key",
".",
"strip",
"(",
")",
"]",
"=",
"value",
".",
"strip",
"(",
")",
"info_cb",
"=",
"info_cb",
"or",
"default_info_cb",
"final_result",
"=",
"self",
".",
"oem",
"(",
"'bootconfig %s'",
"%",
"name",
",",
"info_cb",
"=",
"info_cb",
")",
"# Return INFO messages before the final OKAY message.",
"if",
"name",
"in",
"result",
":",
"return",
"result",
"[",
"name",
"]",
"return",
"final_result"
] | Get bootconfig, either as full dict or specific value for key. | [
"Get",
"bootconfig",
"either",
"as",
"full",
"dict",
"or",
"specific",
"value",
"for",
"key",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/fastboot_device.py#L49-L63 |
227,004 | google/openhtf | openhtf/plugs/usb/local_usb.py | LibUsbHandle._device_to_sysfs_path | def _device_to_sysfs_path(device):
"""Convert device to corresponding sysfs path."""
return '%s-%s' % (
device.getBusNumber(),
'.'.join([str(item) for item in device.GetPortNumberList()])) | python | def _device_to_sysfs_path(device):
"""Convert device to corresponding sysfs path."""
return '%s-%s' % (
device.getBusNumber(),
'.'.join([str(item) for item in device.GetPortNumberList()])) | [
"def",
"_device_to_sysfs_path",
"(",
"device",
")",
":",
"return",
"'%s-%s'",
"%",
"(",
"device",
".",
"getBusNumber",
"(",
")",
",",
"'.'",
".",
"join",
"(",
"[",
"str",
"(",
"item",
")",
"for",
"item",
"in",
"device",
".",
"GetPortNumberList",
"(",
")",
"]",
")",
")"
] | Convert device to corresponding sysfs path. | [
"Convert",
"device",
"to",
"corresponding",
"sysfs",
"path",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/local_usb.py#L112-L116 |
227,005 | google/openhtf | openhtf/plugs/usb/local_usb.py | LibUsbHandle.open | def open(cls, **kwargs):
"""See iter_open, but raises if multiple or no matches found."""
handle_iter = cls.iter_open(**kwargs)
try:
handle = six.next(handle_iter)
except StopIteration:
# No matching interface, raise.
raise usb_exceptions.DeviceNotFoundError(
'Open failed with args: %s', kwargs)
try:
multiple_handle = six.next(handle_iter)
except StopIteration:
# Exactly one matching device, return it.
return handle
# We have more than one device, close the ones we opened and bail.
handle.close()
multiple_handle.close()
raise usb_exceptions.MultipleInterfacesFoundError(kwargs) | python | def open(cls, **kwargs):
"""See iter_open, but raises if multiple or no matches found."""
handle_iter = cls.iter_open(**kwargs)
try:
handle = six.next(handle_iter)
except StopIteration:
# No matching interface, raise.
raise usb_exceptions.DeviceNotFoundError(
'Open failed with args: %s', kwargs)
try:
multiple_handle = six.next(handle_iter)
except StopIteration:
# Exactly one matching device, return it.
return handle
# We have more than one device, close the ones we opened and bail.
handle.close()
multiple_handle.close()
raise usb_exceptions.MultipleInterfacesFoundError(kwargs) | [
"def",
"open",
"(",
"cls",
",",
"*",
"*",
"kwargs",
")",
":",
"handle_iter",
"=",
"cls",
".",
"iter_open",
"(",
"*",
"*",
"kwargs",
")",
"try",
":",
"handle",
"=",
"six",
".",
"next",
"(",
"handle_iter",
")",
"except",
"StopIteration",
":",
"# No matching interface, raise.",
"raise",
"usb_exceptions",
".",
"DeviceNotFoundError",
"(",
"'Open failed with args: %s'",
",",
"kwargs",
")",
"try",
":",
"multiple_handle",
"=",
"six",
".",
"next",
"(",
"handle_iter",
")",
"except",
"StopIteration",
":",
"# Exactly one matching device, return it.",
"return",
"handle",
"# We have more than one device, close the ones we opened and bail.",
"handle",
".",
"close",
"(",
")",
"multiple_handle",
".",
"close",
"(",
")",
"raise",
"usb_exceptions",
".",
"MultipleInterfacesFoundError",
"(",
"kwargs",
")"
] | See iter_open, but raises if multiple or no matches found. | [
"See",
"iter_open",
"but",
"raises",
"if",
"multiple",
"or",
"no",
"matches",
"found",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/local_usb.py#L158-L178 |
227,006 | google/openhtf | openhtf/plugs/usb/local_usb.py | LibUsbHandle.iter_open | def iter_open(cls, name=None, interface_class=None, interface_subclass=None,
interface_protocol=None, serial_number=None, port_path=None,
default_timeout_ms=None):
"""Find and yield locally connected devices that match.
Note that devices are opened (and interfaces claimd) as they are yielded.
Any devices yielded must be Close()'d.
Args:
name: Name to give *all* returned handles, used for logging only.
interface_class: USB interface_class to match.
interface_subclass: USB interface_subclass to match.
interface_protocol: USB interface_protocol to match.
serial_number: USB serial_number to match.
port_path: USB Port path to match, like X-X.X.X
default_timeout_ms: Default timeout in milliseconds of reads/writes on
the handles yielded.
Yields:
UsbHandle instances that match any non-None args given.
Raises:
LibusbWrappingError: When a libusb call errors during open.
"""
ctx = usb1.USBContext()
try:
devices = ctx.getDeviceList(skip_on_error=True)
except libusb1.USBError as exception:
raise usb_exceptions.LibusbWrappingError(
exception, 'Open(name=%s, class=%s, subclass=%s, protocol=%s, '
'serial=%s, port=%s) failed', name, interface_class,
interface_subclass, interface_protocol, serial_number, port_path)
for device in devices:
try:
if (serial_number is not None and
device.getSerialNumber() != serial_number):
continue
if (port_path is not None and
cls._device_to_sysfs_path(device) != port_path):
continue
for setting in device.iterSettings():
if (interface_class is not None and
setting.getClass() != interface_class):
continue
if (interface_subclass is not None and
setting.getSubClass() != interface_subclass):
continue
if (interface_protocol is not None and
setting.getProtocol() != interface_protocol):
continue
yield cls(device, setting, name=name,
default_timeout_ms=default_timeout_ms)
except libusb1.USBError as exception:
if (exception.value !=
libusb1.libusb_error.forward_dict['LIBUSB_ERROR_ACCESS']):
raise | python | def iter_open(cls, name=None, interface_class=None, interface_subclass=None,
interface_protocol=None, serial_number=None, port_path=None,
default_timeout_ms=None):
"""Find and yield locally connected devices that match.
Note that devices are opened (and interfaces claimd) as they are yielded.
Any devices yielded must be Close()'d.
Args:
name: Name to give *all* returned handles, used for logging only.
interface_class: USB interface_class to match.
interface_subclass: USB interface_subclass to match.
interface_protocol: USB interface_protocol to match.
serial_number: USB serial_number to match.
port_path: USB Port path to match, like X-X.X.X
default_timeout_ms: Default timeout in milliseconds of reads/writes on
the handles yielded.
Yields:
UsbHandle instances that match any non-None args given.
Raises:
LibusbWrappingError: When a libusb call errors during open.
"""
ctx = usb1.USBContext()
try:
devices = ctx.getDeviceList(skip_on_error=True)
except libusb1.USBError as exception:
raise usb_exceptions.LibusbWrappingError(
exception, 'Open(name=%s, class=%s, subclass=%s, protocol=%s, '
'serial=%s, port=%s) failed', name, interface_class,
interface_subclass, interface_protocol, serial_number, port_path)
for device in devices:
try:
if (serial_number is not None and
device.getSerialNumber() != serial_number):
continue
if (port_path is not None and
cls._device_to_sysfs_path(device) != port_path):
continue
for setting in device.iterSettings():
if (interface_class is not None and
setting.getClass() != interface_class):
continue
if (interface_subclass is not None and
setting.getSubClass() != interface_subclass):
continue
if (interface_protocol is not None and
setting.getProtocol() != interface_protocol):
continue
yield cls(device, setting, name=name,
default_timeout_ms=default_timeout_ms)
except libusb1.USBError as exception:
if (exception.value !=
libusb1.libusb_error.forward_dict['LIBUSB_ERROR_ACCESS']):
raise | [
"def",
"iter_open",
"(",
"cls",
",",
"name",
"=",
"None",
",",
"interface_class",
"=",
"None",
",",
"interface_subclass",
"=",
"None",
",",
"interface_protocol",
"=",
"None",
",",
"serial_number",
"=",
"None",
",",
"port_path",
"=",
"None",
",",
"default_timeout_ms",
"=",
"None",
")",
":",
"ctx",
"=",
"usb1",
".",
"USBContext",
"(",
")",
"try",
":",
"devices",
"=",
"ctx",
".",
"getDeviceList",
"(",
"skip_on_error",
"=",
"True",
")",
"except",
"libusb1",
".",
"USBError",
"as",
"exception",
":",
"raise",
"usb_exceptions",
".",
"LibusbWrappingError",
"(",
"exception",
",",
"'Open(name=%s, class=%s, subclass=%s, protocol=%s, '",
"'serial=%s, port=%s) failed'",
",",
"name",
",",
"interface_class",
",",
"interface_subclass",
",",
"interface_protocol",
",",
"serial_number",
",",
"port_path",
")",
"for",
"device",
"in",
"devices",
":",
"try",
":",
"if",
"(",
"serial_number",
"is",
"not",
"None",
"and",
"device",
".",
"getSerialNumber",
"(",
")",
"!=",
"serial_number",
")",
":",
"continue",
"if",
"(",
"port_path",
"is",
"not",
"None",
"and",
"cls",
".",
"_device_to_sysfs_path",
"(",
"device",
")",
"!=",
"port_path",
")",
":",
"continue",
"for",
"setting",
"in",
"device",
".",
"iterSettings",
"(",
")",
":",
"if",
"(",
"interface_class",
"is",
"not",
"None",
"and",
"setting",
".",
"getClass",
"(",
")",
"!=",
"interface_class",
")",
":",
"continue",
"if",
"(",
"interface_subclass",
"is",
"not",
"None",
"and",
"setting",
".",
"getSubClass",
"(",
")",
"!=",
"interface_subclass",
")",
":",
"continue",
"if",
"(",
"interface_protocol",
"is",
"not",
"None",
"and",
"setting",
".",
"getProtocol",
"(",
")",
"!=",
"interface_protocol",
")",
":",
"continue",
"yield",
"cls",
"(",
"device",
",",
"setting",
",",
"name",
"=",
"name",
",",
"default_timeout_ms",
"=",
"default_timeout_ms",
")",
"except",
"libusb1",
".",
"USBError",
"as",
"exception",
":",
"if",
"(",
"exception",
".",
"value",
"!=",
"libusb1",
".",
"libusb_error",
".",
"forward_dict",
"[",
"'LIBUSB_ERROR_ACCESS'",
"]",
")",
":",
"raise"
] | Find and yield locally connected devices that match.
Note that devices are opened (and interfaces claimd) as they are yielded.
Any devices yielded must be Close()'d.
Args:
name: Name to give *all* returned handles, used for logging only.
interface_class: USB interface_class to match.
interface_subclass: USB interface_subclass to match.
interface_protocol: USB interface_protocol to match.
serial_number: USB serial_number to match.
port_path: USB Port path to match, like X-X.X.X
default_timeout_ms: Default timeout in milliseconds of reads/writes on
the handles yielded.
Yields:
UsbHandle instances that match any non-None args given.
Raises:
LibusbWrappingError: When a libusb call errors during open. | [
"Find",
"and",
"yield",
"locally",
"connected",
"devices",
"that",
"match",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/local_usb.py#L182-L241 |
227,007 | google/openhtf | examples/all_the_things.py | hello_world | def hello_world(test, example, prompts):
"""A hello world test phase."""
test.logger.info('Hello World!')
test.measurements.widget_type = prompts.prompt(
'What\'s the widget type? (Hint: try `MyWidget` to PASS)',
text_input=True)
if test.measurements.widget_type == 'raise':
raise Exception()
test.measurements.widget_color = 'Black'
test.measurements.widget_size = 3
test.measurements.specified_as_args = 'Measurement args specified directly'
test.logger.info('Plug value: %s', example.increment()) | python | def hello_world(test, example, prompts):
"""A hello world test phase."""
test.logger.info('Hello World!')
test.measurements.widget_type = prompts.prompt(
'What\'s the widget type? (Hint: try `MyWidget` to PASS)',
text_input=True)
if test.measurements.widget_type == 'raise':
raise Exception()
test.measurements.widget_color = 'Black'
test.measurements.widget_size = 3
test.measurements.specified_as_args = 'Measurement args specified directly'
test.logger.info('Plug value: %s', example.increment()) | [
"def",
"hello_world",
"(",
"test",
",",
"example",
",",
"prompts",
")",
":",
"test",
".",
"logger",
".",
"info",
"(",
"'Hello World!'",
")",
"test",
".",
"measurements",
".",
"widget_type",
"=",
"prompts",
".",
"prompt",
"(",
"'What\\'s the widget type? (Hint: try `MyWidget` to PASS)'",
",",
"text_input",
"=",
"True",
")",
"if",
"test",
".",
"measurements",
".",
"widget_type",
"==",
"'raise'",
":",
"raise",
"Exception",
"(",
")",
"test",
".",
"measurements",
".",
"widget_color",
"=",
"'Black'",
"test",
".",
"measurements",
".",
"widget_size",
"=",
"3",
"test",
".",
"measurements",
".",
"specified_as_args",
"=",
"'Measurement args specified directly'",
"test",
".",
"logger",
".",
"info",
"(",
"'Plug value: %s'",
",",
"example",
".",
"increment",
"(",
")",
")"
] | A hello world test phase. | [
"A",
"hello",
"world",
"test",
"phase",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/examples/all_the_things.py#L55-L66 |
227,008 | google/openhtf | examples/all_the_things.py | set_measurements | def set_measurements(test):
"""Test phase that sets a measurement."""
test.measurements.level_none = 0
time.sleep(1)
test.measurements.level_some = 8
time.sleep(1)
test.measurements.level_all = 9
time.sleep(1)
level_all = test.get_measurement('level_all')
assert level_all.value == 9 | python | def set_measurements(test):
"""Test phase that sets a measurement."""
test.measurements.level_none = 0
time.sleep(1)
test.measurements.level_some = 8
time.sleep(1)
test.measurements.level_all = 9
time.sleep(1)
level_all = test.get_measurement('level_all')
assert level_all.value == 9 | [
"def",
"set_measurements",
"(",
"test",
")",
":",
"test",
".",
"measurements",
".",
"level_none",
"=",
"0",
"time",
".",
"sleep",
"(",
"1",
")",
"test",
".",
"measurements",
".",
"level_some",
"=",
"8",
"time",
".",
"sleep",
"(",
"1",
")",
"test",
".",
"measurements",
".",
"level_all",
"=",
"9",
"time",
".",
"sleep",
"(",
"1",
")",
"level_all",
"=",
"test",
".",
"get_measurement",
"(",
"'level_all'",
")",
"assert",
"level_all",
".",
"value",
"==",
"9"
] | Test phase that sets a measurement. | [
"Test",
"phase",
"that",
"sets",
"a",
"measurement",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/examples/all_the_things.py#L75-L84 |
227,009 | google/openhtf | openhtf/util/data.py | pprint_diff | def pprint_diff(first, second, first_name='first', second_name='second'):
"""Compare the pprint representation of two objects and yield diff lines."""
return difflib.unified_diff(
pprint.pformat(first).splitlines(),
pprint.pformat(second).splitlines(),
fromfile=first_name, tofile=second_name, lineterm='') | python | def pprint_diff(first, second, first_name='first', second_name='second'):
"""Compare the pprint representation of two objects and yield diff lines."""
return difflib.unified_diff(
pprint.pformat(first).splitlines(),
pprint.pformat(second).splitlines(),
fromfile=first_name, tofile=second_name, lineterm='') | [
"def",
"pprint_diff",
"(",
"first",
",",
"second",
",",
"first_name",
"=",
"'first'",
",",
"second_name",
"=",
"'second'",
")",
":",
"return",
"difflib",
".",
"unified_diff",
"(",
"pprint",
".",
"pformat",
"(",
"first",
")",
".",
"splitlines",
"(",
")",
",",
"pprint",
".",
"pformat",
"(",
"second",
")",
".",
"splitlines",
"(",
")",
",",
"fromfile",
"=",
"first_name",
",",
"tofile",
"=",
"second_name",
",",
"lineterm",
"=",
"''",
")"
] | Compare the pprint representation of two objects and yield diff lines. | [
"Compare",
"the",
"pprint",
"representation",
"of",
"two",
"objects",
"and",
"yield",
"diff",
"lines",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/data.py#L42-L47 |
227,010 | google/openhtf | openhtf/util/data.py | equals_log_diff | def equals_log_diff(expected, actual, level=logging.ERROR):
"""Compare two string blobs, error log diff if they don't match."""
if expected == actual:
return True
# Output the diff first.
logging.log(level, '***** Data mismatch: *****')
for line in difflib.unified_diff(
expected.splitlines(), actual.splitlines(),
fromfile='expected', tofile='actual', lineterm=''):
logging.log(level, line)
logging.log(level, '^^^^^ Data diff ^^^^^') | python | def equals_log_diff(expected, actual, level=logging.ERROR):
"""Compare two string blobs, error log diff if they don't match."""
if expected == actual:
return True
# Output the diff first.
logging.log(level, '***** Data mismatch: *****')
for line in difflib.unified_diff(
expected.splitlines(), actual.splitlines(),
fromfile='expected', tofile='actual', lineterm=''):
logging.log(level, line)
logging.log(level, '^^^^^ Data diff ^^^^^') | [
"def",
"equals_log_diff",
"(",
"expected",
",",
"actual",
",",
"level",
"=",
"logging",
".",
"ERROR",
")",
":",
"if",
"expected",
"==",
"actual",
":",
"return",
"True",
"# Output the diff first.",
"logging",
".",
"log",
"(",
"level",
",",
"'***** Data mismatch: *****'",
")",
"for",
"line",
"in",
"difflib",
".",
"unified_diff",
"(",
"expected",
".",
"splitlines",
"(",
")",
",",
"actual",
".",
"splitlines",
"(",
")",
",",
"fromfile",
"=",
"'expected'",
",",
"tofile",
"=",
"'actual'",
",",
"lineterm",
"=",
"''",
")",
":",
"logging",
".",
"log",
"(",
"level",
",",
"line",
")",
"logging",
".",
"log",
"(",
"level",
",",
"'^^^^^ Data diff ^^^^^'",
")"
] | Compare two string blobs, error log diff if they don't match. | [
"Compare",
"two",
"string",
"blobs",
"error",
"log",
"diff",
"if",
"they",
"don",
"t",
"match",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/data.py#L50-L61 |
227,011 | google/openhtf | openhtf/util/data.py | assert_records_equal_nonvolatile | def assert_records_equal_nonvolatile(first, second, volatile_fields, indent=0):
"""Compare two test_record tuples, ignoring any volatile fields.
'Volatile' fields include any fields that are expected to differ between
successive runs of the same test, mainly timestamps. All other fields
are recursively compared.
"""
if isinstance(first, dict) and isinstance(second, dict):
if set(first) != set(second):
logging.error('%sMismatching keys:', ' ' * indent)
logging.error('%s %s', ' ' * indent, list(first.keys()))
logging.error('%s %s', ' ' * indent, list(second.keys()))
assert set(first) == set(second)
for key in first:
if key in volatile_fields:
continue
try:
assert_records_equal_nonvolatile(first[key], second[key],
volatile_fields, indent + 2)
except AssertionError:
logging.error('%sKey: %s ^', ' ' * indent, key)
raise
elif hasattr(first, '_asdict') and hasattr(second, '_asdict'):
# Compare namedtuples as dicts so we get more useful output.
assert_records_equal_nonvolatile(first._asdict(), second._asdict(),
volatile_fields, indent)
elif hasattr(first, '__iter__') and hasattr(second, '__iter__'):
for idx, (fir, sec) in enumerate(itertools.izip(first, second)):
try:
assert_records_equal_nonvolatile(fir, sec, volatile_fields, indent + 2)
except AssertionError:
logging.error('%sIndex: %s ^', ' ' * indent, idx)
raise
elif (isinstance(first, records.RecordClass) and
isinstance(second, records.RecordClass)):
assert_records_equal_nonvolatile(
{slot: getattr(first, slot) for slot in first.__slots__},
{slot: getattr(second, slot) for slot in second.__slots__},
volatile_fields, indent)
elif first != second:
logging.error('%sRaw: "%s" != "%s"', ' ' * indent, first, second)
assert first == second | python | def assert_records_equal_nonvolatile(first, second, volatile_fields, indent=0):
"""Compare two test_record tuples, ignoring any volatile fields.
'Volatile' fields include any fields that are expected to differ between
successive runs of the same test, mainly timestamps. All other fields
are recursively compared.
"""
if isinstance(first, dict) and isinstance(second, dict):
if set(first) != set(second):
logging.error('%sMismatching keys:', ' ' * indent)
logging.error('%s %s', ' ' * indent, list(first.keys()))
logging.error('%s %s', ' ' * indent, list(second.keys()))
assert set(first) == set(second)
for key in first:
if key in volatile_fields:
continue
try:
assert_records_equal_nonvolatile(first[key], second[key],
volatile_fields, indent + 2)
except AssertionError:
logging.error('%sKey: %s ^', ' ' * indent, key)
raise
elif hasattr(first, '_asdict') and hasattr(second, '_asdict'):
# Compare namedtuples as dicts so we get more useful output.
assert_records_equal_nonvolatile(first._asdict(), second._asdict(),
volatile_fields, indent)
elif hasattr(first, '__iter__') and hasattr(second, '__iter__'):
for idx, (fir, sec) in enumerate(itertools.izip(first, second)):
try:
assert_records_equal_nonvolatile(fir, sec, volatile_fields, indent + 2)
except AssertionError:
logging.error('%sIndex: %s ^', ' ' * indent, idx)
raise
elif (isinstance(first, records.RecordClass) and
isinstance(second, records.RecordClass)):
assert_records_equal_nonvolatile(
{slot: getattr(first, slot) for slot in first.__slots__},
{slot: getattr(second, slot) for slot in second.__slots__},
volatile_fields, indent)
elif first != second:
logging.error('%sRaw: "%s" != "%s"', ' ' * indent, first, second)
assert first == second | [
"def",
"assert_records_equal_nonvolatile",
"(",
"first",
",",
"second",
",",
"volatile_fields",
",",
"indent",
"=",
"0",
")",
":",
"if",
"isinstance",
"(",
"first",
",",
"dict",
")",
"and",
"isinstance",
"(",
"second",
",",
"dict",
")",
":",
"if",
"set",
"(",
"first",
")",
"!=",
"set",
"(",
"second",
")",
":",
"logging",
".",
"error",
"(",
"'%sMismatching keys:'",
",",
"' '",
"*",
"indent",
")",
"logging",
".",
"error",
"(",
"'%s %s'",
",",
"' '",
"*",
"indent",
",",
"list",
"(",
"first",
".",
"keys",
"(",
")",
")",
")",
"logging",
".",
"error",
"(",
"'%s %s'",
",",
"' '",
"*",
"indent",
",",
"list",
"(",
"second",
".",
"keys",
"(",
")",
")",
")",
"assert",
"set",
"(",
"first",
")",
"==",
"set",
"(",
"second",
")",
"for",
"key",
"in",
"first",
":",
"if",
"key",
"in",
"volatile_fields",
":",
"continue",
"try",
":",
"assert_records_equal_nonvolatile",
"(",
"first",
"[",
"key",
"]",
",",
"second",
"[",
"key",
"]",
",",
"volatile_fields",
",",
"indent",
"+",
"2",
")",
"except",
"AssertionError",
":",
"logging",
".",
"error",
"(",
"'%sKey: %s ^'",
",",
"' '",
"*",
"indent",
",",
"key",
")",
"raise",
"elif",
"hasattr",
"(",
"first",
",",
"'_asdict'",
")",
"and",
"hasattr",
"(",
"second",
",",
"'_asdict'",
")",
":",
"# Compare namedtuples as dicts so we get more useful output.",
"assert_records_equal_nonvolatile",
"(",
"first",
".",
"_asdict",
"(",
")",
",",
"second",
".",
"_asdict",
"(",
")",
",",
"volatile_fields",
",",
"indent",
")",
"elif",
"hasattr",
"(",
"first",
",",
"'__iter__'",
")",
"and",
"hasattr",
"(",
"second",
",",
"'__iter__'",
")",
":",
"for",
"idx",
",",
"(",
"fir",
",",
"sec",
")",
"in",
"enumerate",
"(",
"itertools",
".",
"izip",
"(",
"first",
",",
"second",
")",
")",
":",
"try",
":",
"assert_records_equal_nonvolatile",
"(",
"fir",
",",
"sec",
",",
"volatile_fields",
",",
"indent",
"+",
"2",
")",
"except",
"AssertionError",
":",
"logging",
".",
"error",
"(",
"'%sIndex: %s ^'",
",",
"' '",
"*",
"indent",
",",
"idx",
")",
"raise",
"elif",
"(",
"isinstance",
"(",
"first",
",",
"records",
".",
"RecordClass",
")",
"and",
"isinstance",
"(",
"second",
",",
"records",
".",
"RecordClass",
")",
")",
":",
"assert_records_equal_nonvolatile",
"(",
"{",
"slot",
":",
"getattr",
"(",
"first",
",",
"slot",
")",
"for",
"slot",
"in",
"first",
".",
"__slots__",
"}",
",",
"{",
"slot",
":",
"getattr",
"(",
"second",
",",
"slot",
")",
"for",
"slot",
"in",
"second",
".",
"__slots__",
"}",
",",
"volatile_fields",
",",
"indent",
")",
"elif",
"first",
"!=",
"second",
":",
"logging",
".",
"error",
"(",
"'%sRaw: \"%s\" != \"%s\"'",
",",
"' '",
"*",
"indent",
",",
"first",
",",
"second",
")",
"assert",
"first",
"==",
"second"
] | Compare two test_record tuples, ignoring any volatile fields.
'Volatile' fields include any fields that are expected to differ between
successive runs of the same test, mainly timestamps. All other fields
are recursively compared. | [
"Compare",
"two",
"test_record",
"tuples",
"ignoring",
"any",
"volatile",
"fields",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/data.py#L64-L105 |
227,012 | google/openhtf | openhtf/util/data.py | convert_to_base_types | def convert_to_base_types(obj, ignore_keys=tuple(), tuple_type=tuple,
json_safe=True):
"""Recursively convert objects into base types.
This is used to convert some special types of objects used internally into
base types for more friendly output via mechanisms such as JSON. It is used
for sending internal objects via the network and outputting test records.
Specifically, the conversions that are performed:
- If an object has an as_base_types() method, immediately return the result
without any recursion; this can be used with caching in the object to
prevent unnecessary conversions.
- If an object has an _asdict() method, use that to convert it to a dict and
recursively converting its contents.
- mutablerecords Record instances are converted to dicts that map
attribute name to value. Optional attributes with a value of None are
skipped.
- Enum instances are converted to strings via their .name attribute.
- Real and integral numbers are converted to built-in types.
- Byte and unicode strings are left alone (instances of six.string_types).
- Other non-None values are converted to strings via str().
The return value contains only the Python built-in types: dict, list, tuple,
str, unicode, int, float, long, bool, and NoneType (unless tuple_type is set
to something else). If tuples should be converted to lists (e.g. for an
encoding that does not differentiate between the two), pass 'tuple_type=list'
as an argument.
If `json_safe` is True, then the float 'inf', '-inf', and 'nan' values will be
converted to strings. This ensures that the returned dictionary can be passed
to json.dumps to create valid JSON. Otherwise, json.dumps may return values
such as NaN which are not valid JSON.
"""
# Because it's *really* annoying to pass a single string accidentally.
assert not isinstance(ignore_keys, six.string_types), 'Pass a real iterable!'
if hasattr(obj, 'as_base_types'):
return obj.as_base_types()
if hasattr(obj, '_asdict'):
obj = obj._asdict()
elif isinstance(obj, records.RecordClass):
obj = {attr: getattr(obj, attr)
for attr in type(obj).all_attribute_names
if (getattr(obj, attr, None) is not None or
attr in type(obj).required_attributes)}
elif isinstance(obj, Enum):
obj = obj.name
if type(obj) in PASSTHROUGH_TYPES:
return obj
# Recursively convert values in dicts, lists, and tuples.
if isinstance(obj, dict):
return {convert_to_base_types(k, ignore_keys, tuple_type):
convert_to_base_types(v, ignore_keys, tuple_type)
for k, v in six.iteritems(obj) if k not in ignore_keys}
elif isinstance(obj, list):
return [convert_to_base_types(val, ignore_keys, tuple_type, json_safe)
for val in obj]
elif isinstance(obj, tuple):
return tuple_type(
convert_to_base_types(value, ignore_keys, tuple_type, json_safe)
for value in obj)
# Convert numeric types (e.g. numpy ints and floats) into built-in types.
elif isinstance(obj, numbers.Integral):
return long(obj)
elif isinstance(obj, numbers.Real):
as_float = float(obj)
if json_safe and (math.isinf(as_float) or math.isnan(as_float)):
return str(as_float)
return as_float
# Convert all other types to strings.
try:
return str(obj)
except:
logging.warning('Problem casting object of type %s to str.', type(obj))
raise | python | def convert_to_base_types(obj, ignore_keys=tuple(), tuple_type=tuple,
json_safe=True):
"""Recursively convert objects into base types.
This is used to convert some special types of objects used internally into
base types for more friendly output via mechanisms such as JSON. It is used
for sending internal objects via the network and outputting test records.
Specifically, the conversions that are performed:
- If an object has an as_base_types() method, immediately return the result
without any recursion; this can be used with caching in the object to
prevent unnecessary conversions.
- If an object has an _asdict() method, use that to convert it to a dict and
recursively converting its contents.
- mutablerecords Record instances are converted to dicts that map
attribute name to value. Optional attributes with a value of None are
skipped.
- Enum instances are converted to strings via their .name attribute.
- Real and integral numbers are converted to built-in types.
- Byte and unicode strings are left alone (instances of six.string_types).
- Other non-None values are converted to strings via str().
The return value contains only the Python built-in types: dict, list, tuple,
str, unicode, int, float, long, bool, and NoneType (unless tuple_type is set
to something else). If tuples should be converted to lists (e.g. for an
encoding that does not differentiate between the two), pass 'tuple_type=list'
as an argument.
If `json_safe` is True, then the float 'inf', '-inf', and 'nan' values will be
converted to strings. This ensures that the returned dictionary can be passed
to json.dumps to create valid JSON. Otherwise, json.dumps may return values
such as NaN which are not valid JSON.
"""
# Because it's *really* annoying to pass a single string accidentally.
assert not isinstance(ignore_keys, six.string_types), 'Pass a real iterable!'
if hasattr(obj, 'as_base_types'):
return obj.as_base_types()
if hasattr(obj, '_asdict'):
obj = obj._asdict()
elif isinstance(obj, records.RecordClass):
obj = {attr: getattr(obj, attr)
for attr in type(obj).all_attribute_names
if (getattr(obj, attr, None) is not None or
attr in type(obj).required_attributes)}
elif isinstance(obj, Enum):
obj = obj.name
if type(obj) in PASSTHROUGH_TYPES:
return obj
# Recursively convert values in dicts, lists, and tuples.
if isinstance(obj, dict):
return {convert_to_base_types(k, ignore_keys, tuple_type):
convert_to_base_types(v, ignore_keys, tuple_type)
for k, v in six.iteritems(obj) if k not in ignore_keys}
elif isinstance(obj, list):
return [convert_to_base_types(val, ignore_keys, tuple_type, json_safe)
for val in obj]
elif isinstance(obj, tuple):
return tuple_type(
convert_to_base_types(value, ignore_keys, tuple_type, json_safe)
for value in obj)
# Convert numeric types (e.g. numpy ints and floats) into built-in types.
elif isinstance(obj, numbers.Integral):
return long(obj)
elif isinstance(obj, numbers.Real):
as_float = float(obj)
if json_safe and (math.isinf(as_float) or math.isnan(as_float)):
return str(as_float)
return as_float
# Convert all other types to strings.
try:
return str(obj)
except:
logging.warning('Problem casting object of type %s to str.', type(obj))
raise | [
"def",
"convert_to_base_types",
"(",
"obj",
",",
"ignore_keys",
"=",
"tuple",
"(",
")",
",",
"tuple_type",
"=",
"tuple",
",",
"json_safe",
"=",
"True",
")",
":",
"# Because it's *really* annoying to pass a single string accidentally.",
"assert",
"not",
"isinstance",
"(",
"ignore_keys",
",",
"six",
".",
"string_types",
")",
",",
"'Pass a real iterable!'",
"if",
"hasattr",
"(",
"obj",
",",
"'as_base_types'",
")",
":",
"return",
"obj",
".",
"as_base_types",
"(",
")",
"if",
"hasattr",
"(",
"obj",
",",
"'_asdict'",
")",
":",
"obj",
"=",
"obj",
".",
"_asdict",
"(",
")",
"elif",
"isinstance",
"(",
"obj",
",",
"records",
".",
"RecordClass",
")",
":",
"obj",
"=",
"{",
"attr",
":",
"getattr",
"(",
"obj",
",",
"attr",
")",
"for",
"attr",
"in",
"type",
"(",
"obj",
")",
".",
"all_attribute_names",
"if",
"(",
"getattr",
"(",
"obj",
",",
"attr",
",",
"None",
")",
"is",
"not",
"None",
"or",
"attr",
"in",
"type",
"(",
"obj",
")",
".",
"required_attributes",
")",
"}",
"elif",
"isinstance",
"(",
"obj",
",",
"Enum",
")",
":",
"obj",
"=",
"obj",
".",
"name",
"if",
"type",
"(",
"obj",
")",
"in",
"PASSTHROUGH_TYPES",
":",
"return",
"obj",
"# Recursively convert values in dicts, lists, and tuples.",
"if",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"return",
"{",
"convert_to_base_types",
"(",
"k",
",",
"ignore_keys",
",",
"tuple_type",
")",
":",
"convert_to_base_types",
"(",
"v",
",",
"ignore_keys",
",",
"tuple_type",
")",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"obj",
")",
"if",
"k",
"not",
"in",
"ignore_keys",
"}",
"elif",
"isinstance",
"(",
"obj",
",",
"list",
")",
":",
"return",
"[",
"convert_to_base_types",
"(",
"val",
",",
"ignore_keys",
",",
"tuple_type",
",",
"json_safe",
")",
"for",
"val",
"in",
"obj",
"]",
"elif",
"isinstance",
"(",
"obj",
",",
"tuple",
")",
":",
"return",
"tuple_type",
"(",
"convert_to_base_types",
"(",
"value",
",",
"ignore_keys",
",",
"tuple_type",
",",
"json_safe",
")",
"for",
"value",
"in",
"obj",
")",
"# Convert numeric types (e.g. numpy ints and floats) into built-in types.",
"elif",
"isinstance",
"(",
"obj",
",",
"numbers",
".",
"Integral",
")",
":",
"return",
"long",
"(",
"obj",
")",
"elif",
"isinstance",
"(",
"obj",
",",
"numbers",
".",
"Real",
")",
":",
"as_float",
"=",
"float",
"(",
"obj",
")",
"if",
"json_safe",
"and",
"(",
"math",
".",
"isinf",
"(",
"as_float",
")",
"or",
"math",
".",
"isnan",
"(",
"as_float",
")",
")",
":",
"return",
"str",
"(",
"as_float",
")",
"return",
"as_float",
"# Convert all other types to strings.",
"try",
":",
"return",
"str",
"(",
"obj",
")",
"except",
":",
"logging",
".",
"warning",
"(",
"'Problem casting object of type %s to str.'",
",",
"type",
"(",
"obj",
")",
")",
"raise"
] | Recursively convert objects into base types.
This is used to convert some special types of objects used internally into
base types for more friendly output via mechanisms such as JSON. It is used
for sending internal objects via the network and outputting test records.
Specifically, the conversions that are performed:
- If an object has an as_base_types() method, immediately return the result
without any recursion; this can be used with caching in the object to
prevent unnecessary conversions.
- If an object has an _asdict() method, use that to convert it to a dict and
recursively converting its contents.
- mutablerecords Record instances are converted to dicts that map
attribute name to value. Optional attributes with a value of None are
skipped.
- Enum instances are converted to strings via their .name attribute.
- Real and integral numbers are converted to built-in types.
- Byte and unicode strings are left alone (instances of six.string_types).
- Other non-None values are converted to strings via str().
The return value contains only the Python built-in types: dict, list, tuple,
str, unicode, int, float, long, bool, and NoneType (unless tuple_type is set
to something else). If tuples should be converted to lists (e.g. for an
encoding that does not differentiate between the two), pass 'tuple_type=list'
as an argument.
If `json_safe` is True, then the float 'inf', '-inf', and 'nan' values will be
converted to strings. This ensures that the returned dictionary can be passed
to json.dumps to create valid JSON. Otherwise, json.dumps may return values
such as NaN which are not valid JSON. | [
"Recursively",
"convert",
"objects",
"into",
"base",
"types",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/data.py#L108-L186 |
227,013 | google/openhtf | openhtf/util/data.py | total_size | def total_size(obj):
"""Returns the approximate total memory footprint an object."""
seen = set()
def sizeof(current_obj):
try:
return _sizeof(current_obj)
except Exception: # pylint: disable=broad-except
# Not sure what just happened, but let's assume it's a reference.
return struct.calcsize('P')
def _sizeof(current_obj):
"""Do a depth-first acyclic traversal of all reachable objects."""
if id(current_obj) in seen:
# A rough approximation of the size cost of an additional reference.
return struct.calcsize('P')
seen.add(id(current_obj))
size = sys.getsizeof(current_obj)
if isinstance(current_obj, dict):
size += sum(map(sizeof, itertools.chain.from_iterable(
six.iteritems(current_obj))))
elif (isinstance(current_obj, collections.Iterable) and
not isinstance(current_obj, six.string_types)):
size += sum(sizeof(item) for item in current_obj)
elif isinstance(current_obj, records.RecordClass):
size += sum(sizeof(getattr(current_obj, attr))
for attr in current_obj.__slots__)
return size
return sizeof(obj) | python | def total_size(obj):
"""Returns the approximate total memory footprint an object."""
seen = set()
def sizeof(current_obj):
try:
return _sizeof(current_obj)
except Exception: # pylint: disable=broad-except
# Not sure what just happened, but let's assume it's a reference.
return struct.calcsize('P')
def _sizeof(current_obj):
"""Do a depth-first acyclic traversal of all reachable objects."""
if id(current_obj) in seen:
# A rough approximation of the size cost of an additional reference.
return struct.calcsize('P')
seen.add(id(current_obj))
size = sys.getsizeof(current_obj)
if isinstance(current_obj, dict):
size += sum(map(sizeof, itertools.chain.from_iterable(
six.iteritems(current_obj))))
elif (isinstance(current_obj, collections.Iterable) and
not isinstance(current_obj, six.string_types)):
size += sum(sizeof(item) for item in current_obj)
elif isinstance(current_obj, records.RecordClass):
size += sum(sizeof(getattr(current_obj, attr))
for attr in current_obj.__slots__)
return size
return sizeof(obj) | [
"def",
"total_size",
"(",
"obj",
")",
":",
"seen",
"=",
"set",
"(",
")",
"def",
"sizeof",
"(",
"current_obj",
")",
":",
"try",
":",
"return",
"_sizeof",
"(",
"current_obj",
")",
"except",
"Exception",
":",
"# pylint: disable=broad-except",
"# Not sure what just happened, but let's assume it's a reference.",
"return",
"struct",
".",
"calcsize",
"(",
"'P'",
")",
"def",
"_sizeof",
"(",
"current_obj",
")",
":",
"\"\"\"Do a depth-first acyclic traversal of all reachable objects.\"\"\"",
"if",
"id",
"(",
"current_obj",
")",
"in",
"seen",
":",
"# A rough approximation of the size cost of an additional reference.",
"return",
"struct",
".",
"calcsize",
"(",
"'P'",
")",
"seen",
".",
"add",
"(",
"id",
"(",
"current_obj",
")",
")",
"size",
"=",
"sys",
".",
"getsizeof",
"(",
"current_obj",
")",
"if",
"isinstance",
"(",
"current_obj",
",",
"dict",
")",
":",
"size",
"+=",
"sum",
"(",
"map",
"(",
"sizeof",
",",
"itertools",
".",
"chain",
".",
"from_iterable",
"(",
"six",
".",
"iteritems",
"(",
"current_obj",
")",
")",
")",
")",
"elif",
"(",
"isinstance",
"(",
"current_obj",
",",
"collections",
".",
"Iterable",
")",
"and",
"not",
"isinstance",
"(",
"current_obj",
",",
"six",
".",
"string_types",
")",
")",
":",
"size",
"+=",
"sum",
"(",
"sizeof",
"(",
"item",
")",
"for",
"item",
"in",
"current_obj",
")",
"elif",
"isinstance",
"(",
"current_obj",
",",
"records",
".",
"RecordClass",
")",
":",
"size",
"+=",
"sum",
"(",
"sizeof",
"(",
"getattr",
"(",
"current_obj",
",",
"attr",
")",
")",
"for",
"attr",
"in",
"current_obj",
".",
"__slots__",
")",
"return",
"size",
"return",
"sizeof",
"(",
"obj",
")"
] | Returns the approximate total memory footprint an object. | [
"Returns",
"the",
"approximate",
"total",
"memory",
"footprint",
"an",
"object",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/data.py#L189-L218 |
227,014 | google/openhtf | openhtf/output/callbacks/__init__.py | OutputToFile.open_output_file | def open_output_file(self, test_record):
"""Open file based on pattern."""
# Ignore keys for the log filename to not convert larger data structures.
record_dict = data.convert_to_base_types(
test_record, ignore_keys=('code_info', 'phases', 'log_records'))
pattern = self.filename_pattern
if isinstance(pattern, six.string_types) or callable(pattern):
output_file = self.open_file(util.format_string(pattern, record_dict))
try:
yield output_file
finally:
output_file.close()
elif hasattr(self.filename_pattern, 'write'):
yield self.filename_pattern
else:
raise ValueError(
'filename_pattern must be string, callable, or File-like object') | python | def open_output_file(self, test_record):
"""Open file based on pattern."""
# Ignore keys for the log filename to not convert larger data structures.
record_dict = data.convert_to_base_types(
test_record, ignore_keys=('code_info', 'phases', 'log_records'))
pattern = self.filename_pattern
if isinstance(pattern, six.string_types) or callable(pattern):
output_file = self.open_file(util.format_string(pattern, record_dict))
try:
yield output_file
finally:
output_file.close()
elif hasattr(self.filename_pattern, 'write'):
yield self.filename_pattern
else:
raise ValueError(
'filename_pattern must be string, callable, or File-like object') | [
"def",
"open_output_file",
"(",
"self",
",",
"test_record",
")",
":",
"# Ignore keys for the log filename to not convert larger data structures.",
"record_dict",
"=",
"data",
".",
"convert_to_base_types",
"(",
"test_record",
",",
"ignore_keys",
"=",
"(",
"'code_info'",
",",
"'phases'",
",",
"'log_records'",
")",
")",
"pattern",
"=",
"self",
".",
"filename_pattern",
"if",
"isinstance",
"(",
"pattern",
",",
"six",
".",
"string_types",
")",
"or",
"callable",
"(",
"pattern",
")",
":",
"output_file",
"=",
"self",
".",
"open_file",
"(",
"util",
".",
"format_string",
"(",
"pattern",
",",
"record_dict",
")",
")",
"try",
":",
"yield",
"output_file",
"finally",
":",
"output_file",
".",
"close",
"(",
")",
"elif",
"hasattr",
"(",
"self",
".",
"filename_pattern",
",",
"'write'",
")",
":",
"yield",
"self",
".",
"filename_pattern",
"else",
":",
"raise",
"ValueError",
"(",
"'filename_pattern must be string, callable, or File-like object'",
")"
] | Open file based on pattern. | [
"Open",
"file",
"based",
"on",
"pattern",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/output/callbacks/__init__.py#L82-L98 |
227,015 | google/openhtf | pylint_plugins/mutablerecords_plugin.py | mutable_record_transform | def mutable_record_transform(cls):
"""Transform mutable records usage by updating locals."""
if not (len(cls.bases) > 0
and isinstance(cls.bases[0], astroid.Call)
and cls.bases[0].func.as_string() == 'mutablerecords.Record'):
return
try:
# Add required attributes.
if len(cls.bases[0].args) >= 2:
for a in cls.bases[0].args[1].elts:
cls.locals[a] = [None]
# Add optional attributes.
if len(cls.bases[0].args) >= 3:
for a,b in cls.bases[0].args[2].items:
cls.locals[a.value] = [None]
except:
raise SyntaxError('Invalid mutablerecords syntax') | python | def mutable_record_transform(cls):
"""Transform mutable records usage by updating locals."""
if not (len(cls.bases) > 0
and isinstance(cls.bases[0], astroid.Call)
and cls.bases[0].func.as_string() == 'mutablerecords.Record'):
return
try:
# Add required attributes.
if len(cls.bases[0].args) >= 2:
for a in cls.bases[0].args[1].elts:
cls.locals[a] = [None]
# Add optional attributes.
if len(cls.bases[0].args) >= 3:
for a,b in cls.bases[0].args[2].items:
cls.locals[a.value] = [None]
except:
raise SyntaxError('Invalid mutablerecords syntax') | [
"def",
"mutable_record_transform",
"(",
"cls",
")",
":",
"if",
"not",
"(",
"len",
"(",
"cls",
".",
"bases",
")",
">",
"0",
"and",
"isinstance",
"(",
"cls",
".",
"bases",
"[",
"0",
"]",
",",
"astroid",
".",
"Call",
")",
"and",
"cls",
".",
"bases",
"[",
"0",
"]",
".",
"func",
".",
"as_string",
"(",
")",
"==",
"'mutablerecords.Record'",
")",
":",
"return",
"try",
":",
"# Add required attributes.",
"if",
"len",
"(",
"cls",
".",
"bases",
"[",
"0",
"]",
".",
"args",
")",
">=",
"2",
":",
"for",
"a",
"in",
"cls",
".",
"bases",
"[",
"0",
"]",
".",
"args",
"[",
"1",
"]",
".",
"elts",
":",
"cls",
".",
"locals",
"[",
"a",
"]",
"=",
"[",
"None",
"]",
"# Add optional attributes.",
"if",
"len",
"(",
"cls",
".",
"bases",
"[",
"0",
"]",
".",
"args",
")",
">=",
"3",
":",
"for",
"a",
",",
"b",
"in",
"cls",
".",
"bases",
"[",
"0",
"]",
".",
"args",
"[",
"2",
"]",
".",
"items",
":",
"cls",
".",
"locals",
"[",
"a",
".",
"value",
"]",
"=",
"[",
"None",
"]",
"except",
":",
"raise",
"SyntaxError",
"(",
"'Invalid mutablerecords syntax'",
")"
] | Transform mutable records usage by updating locals. | [
"Transform",
"mutable",
"records",
"usage",
"by",
"updating",
"locals",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/pylint_plugins/mutablerecords_plugin.py#L25-L44 |
227,016 | google/openhtf | openhtf/util/__init__.py | _log_every_n_to_logger | def _log_every_n_to_logger(n, logger, level, message, *args): # pylint: disable=invalid-name
"""Logs the given message every n calls to a logger.
Args:
n: Number of calls before logging.
logger: The logger to which to log.
level: The logging level (e.g. logging.INFO).
message: A message to log
*args: Any format args for the message.
Returns:
A method that logs and returns True every n calls.
"""
logger = logger or logging.getLogger()
def _gen(): # pylint: disable=missing-docstring
while True:
for _ in range(n):
yield False
logger.log(level, message, *args)
yield True
gen = _gen()
return lambda: six.next(gen) | python | def _log_every_n_to_logger(n, logger, level, message, *args): # pylint: disable=invalid-name
"""Logs the given message every n calls to a logger.
Args:
n: Number of calls before logging.
logger: The logger to which to log.
level: The logging level (e.g. logging.INFO).
message: A message to log
*args: Any format args for the message.
Returns:
A method that logs and returns True every n calls.
"""
logger = logger or logging.getLogger()
def _gen(): # pylint: disable=missing-docstring
while True:
for _ in range(n):
yield False
logger.log(level, message, *args)
yield True
gen = _gen()
return lambda: six.next(gen) | [
"def",
"_log_every_n_to_logger",
"(",
"n",
",",
"logger",
",",
"level",
",",
"message",
",",
"*",
"args",
")",
":",
"# pylint: disable=invalid-name",
"logger",
"=",
"logger",
"or",
"logging",
".",
"getLogger",
"(",
")",
"def",
"_gen",
"(",
")",
":",
"# pylint: disable=missing-docstring",
"while",
"True",
":",
"for",
"_",
"in",
"range",
"(",
"n",
")",
":",
"yield",
"False",
"logger",
".",
"log",
"(",
"level",
",",
"message",
",",
"*",
"args",
")",
"yield",
"True",
"gen",
"=",
"_gen",
"(",
")",
"return",
"lambda",
":",
"six",
".",
"next",
"(",
"gen",
")"
] | Logs the given message every n calls to a logger.
Args:
n: Number of calls before logging.
logger: The logger to which to log.
level: The logging level (e.g. logging.INFO).
message: A message to log
*args: Any format args for the message.
Returns:
A method that logs and returns True every n calls. | [
"Logs",
"the",
"given",
"message",
"every",
"n",
"calls",
"to",
"a",
"logger",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/__init__.py#L29-L49 |
227,017 | google/openhtf | openhtf/util/__init__.py | log_every_n | def log_every_n(n, level, message, *args): # pylint: disable=invalid-name
"""Logs a message every n calls. See _log_every_n_to_logger."""
return _log_every_n_to_logger(n, None, level, message, *args) | python | def log_every_n(n, level, message, *args): # pylint: disable=invalid-name
"""Logs a message every n calls. See _log_every_n_to_logger."""
return _log_every_n_to_logger(n, None, level, message, *args) | [
"def",
"log_every_n",
"(",
"n",
",",
"level",
",",
"message",
",",
"*",
"args",
")",
":",
"# pylint: disable=invalid-name",
"return",
"_log_every_n_to_logger",
"(",
"n",
",",
"None",
",",
"level",
",",
"message",
",",
"*",
"args",
")"
] | Logs a message every n calls. See _log_every_n_to_logger. | [
"Logs",
"a",
"message",
"every",
"n",
"calls",
".",
"See",
"_log_every_n_to_logger",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/__init__.py#L52-L54 |
227,018 | google/openhtf | openhtf/util/__init__.py | partial_format | def partial_format(target, **kwargs):
"""Formats a string without requiring all values to be present.
This function allows substitutions to be gradually made in several steps
rather than all at once. Similar to string.Template.safe_substitute.
"""
output = target[:]
for tag, var in re.findall(r'(\{(.*?)\})', output):
root = var.split('.')[0] # dot notation
root = root.split('[')[0] # dict notation
if root in kwargs:
output = output.replace(tag, tag.format(**{root: kwargs[root]}))
return output | python | def partial_format(target, **kwargs):
"""Formats a string without requiring all values to be present.
This function allows substitutions to be gradually made in several steps
rather than all at once. Similar to string.Template.safe_substitute.
"""
output = target[:]
for tag, var in re.findall(r'(\{(.*?)\})', output):
root = var.split('.')[0] # dot notation
root = root.split('[')[0] # dict notation
if root in kwargs:
output = output.replace(tag, tag.format(**{root: kwargs[root]}))
return output | [
"def",
"partial_format",
"(",
"target",
",",
"*",
"*",
"kwargs",
")",
":",
"output",
"=",
"target",
"[",
":",
"]",
"for",
"tag",
",",
"var",
"in",
"re",
".",
"findall",
"(",
"r'(\\{(.*?)\\})'",
",",
"output",
")",
":",
"root",
"=",
"var",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
"# dot notation",
"root",
"=",
"root",
".",
"split",
"(",
"'['",
")",
"[",
"0",
"]",
"# dict notation",
"if",
"root",
"in",
"kwargs",
":",
"output",
"=",
"output",
".",
"replace",
"(",
"tag",
",",
"tag",
".",
"format",
"(",
"*",
"*",
"{",
"root",
":",
"kwargs",
"[",
"root",
"]",
"}",
")",
")",
"return",
"output"
] | Formats a string without requiring all values to be present.
This function allows substitutions to be gradually made in several steps
rather than all at once. Similar to string.Template.safe_substitute. | [
"Formats",
"a",
"string",
"without",
"requiring",
"all",
"values",
"to",
"be",
"present",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/__init__.py#L96-L110 |
227,019 | google/openhtf | openhtf/util/__init__.py | SubscribableStateMixin.asdict_with_event | def asdict_with_event(self):
"""Get a dict representation of this object and an update event.
Returns:
state: Dict representation of this object.
update_event: An event that is guaranteed to be set if an update has been
triggered since the returned dict was generated.
"""
event = threading.Event()
with self._lock:
self._update_events.add(event)
return self._asdict(), event | python | def asdict_with_event(self):
"""Get a dict representation of this object and an update event.
Returns:
state: Dict representation of this object.
update_event: An event that is guaranteed to be set if an update has been
triggered since the returned dict was generated.
"""
event = threading.Event()
with self._lock:
self._update_events.add(event)
return self._asdict(), event | [
"def",
"asdict_with_event",
"(",
"self",
")",
":",
"event",
"=",
"threading",
".",
"Event",
"(",
")",
"with",
"self",
".",
"_lock",
":",
"self",
".",
"_update_events",
".",
"add",
"(",
"event",
")",
"return",
"self",
".",
"_asdict",
"(",
")",
",",
"event"
] | Get a dict representation of this object and an update event.
Returns:
state: Dict representation of this object.
update_event: An event that is guaranteed to be set if an update has been
triggered since the returned dict was generated. | [
"Get",
"a",
"dict",
"representation",
"of",
"this",
"object",
"and",
"an",
"update",
"event",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/__init__.py#L158-L169 |
227,020 | google/openhtf | openhtf/util/__init__.py | SubscribableStateMixin.notify_update | def notify_update(self):
"""Notify any update events that there was an update."""
with self._lock:
for event in self._update_events:
event.set()
self._update_events.clear() | python | def notify_update(self):
"""Notify any update events that there was an update."""
with self._lock:
for event in self._update_events:
event.set()
self._update_events.clear() | [
"def",
"notify_update",
"(",
"self",
")",
":",
"with",
"self",
".",
"_lock",
":",
"for",
"event",
"in",
"self",
".",
"_update_events",
":",
"event",
".",
"set",
"(",
")",
"self",
".",
"_update_events",
".",
"clear",
"(",
")"
] | Notify any update events that there was an update. | [
"Notify",
"any",
"update",
"events",
"that",
"there",
"was",
"an",
"update",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/__init__.py#L171-L176 |
227,021 | google/openhtf | openhtf/output/servers/web_gui_server.py | bind_port | def bind_port(requested_port):
"""Bind sockets to an available port, returning sockets and the bound port."""
sockets = tornado.netutil.bind_sockets(requested_port)
if requested_port != 0:
return sockets, requested_port
# Get the actual port number.
for s in sockets:
host, port = s.getsockname()[:2]
if host == '0.0.0.0':
return sockets, port
raise RuntimeError('Could not determine the bound port.') | python | def bind_port(requested_port):
"""Bind sockets to an available port, returning sockets and the bound port."""
sockets = tornado.netutil.bind_sockets(requested_port)
if requested_port != 0:
return sockets, requested_port
# Get the actual port number.
for s in sockets:
host, port = s.getsockname()[:2]
if host == '0.0.0.0':
return sockets, port
raise RuntimeError('Could not determine the bound port.') | [
"def",
"bind_port",
"(",
"requested_port",
")",
":",
"sockets",
"=",
"tornado",
".",
"netutil",
".",
"bind_sockets",
"(",
"requested_port",
")",
"if",
"requested_port",
"!=",
"0",
":",
"return",
"sockets",
",",
"requested_port",
"# Get the actual port number.",
"for",
"s",
"in",
"sockets",
":",
"host",
",",
"port",
"=",
"s",
".",
"getsockname",
"(",
")",
"[",
":",
"2",
"]",
"if",
"host",
"==",
"'0.0.0.0'",
":",
"return",
"sockets",
",",
"port",
"raise",
"RuntimeError",
"(",
"'Could not determine the bound port.'",
")"
] | Bind sockets to an available port, returning sockets and the bound port. | [
"Bind",
"sockets",
"to",
"an",
"available",
"port",
"returning",
"sockets",
"and",
"the",
"bound",
"port",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/output/servers/web_gui_server.py#L47-L60 |
227,022 | google/openhtf | openhtf/util/timeouts.py | loop_until_timeout_or_valid | def loop_until_timeout_or_valid(timeout_s, function, validation_fn, sleep_s=1): # pylint: disable=invalid-name
"""Loops until the specified function returns valid or a timeout is reached.
Note: The function may return anything which, when passed to validation_fn,
evaluates to implicit True. This function will loop calling the function as
long as the result of validation_fn(function_result) returns something which
evaluates to False. We ensure function is called at least once regardless
of timeout.
Args:
timeout_s: The number of seconds to wait until a timeout condition is
reached. As a convenience, this accepts None to mean never timeout. Can
also be passed a PolledTimeout object instead of an integer.
function: The function to call each iteration.
validation_fn: The validation function called on the function result to
determine whether to keep looping.
sleep_s: The number of seconds to wait after calling the function.
Returns:
Whatever the function returned last.
"""
if timeout_s is None or not hasattr(timeout_s, 'has_expired'):
timeout_s = PolledTimeout(timeout_s)
while True:
# Calls the function at least once
result = function()
if validation_fn(result) or timeout_s.has_expired():
return result
time.sleep(sleep_s) | python | def loop_until_timeout_or_valid(timeout_s, function, validation_fn, sleep_s=1): # pylint: disable=invalid-name
"""Loops until the specified function returns valid or a timeout is reached.
Note: The function may return anything which, when passed to validation_fn,
evaluates to implicit True. This function will loop calling the function as
long as the result of validation_fn(function_result) returns something which
evaluates to False. We ensure function is called at least once regardless
of timeout.
Args:
timeout_s: The number of seconds to wait until a timeout condition is
reached. As a convenience, this accepts None to mean never timeout. Can
also be passed a PolledTimeout object instead of an integer.
function: The function to call each iteration.
validation_fn: The validation function called on the function result to
determine whether to keep looping.
sleep_s: The number of seconds to wait after calling the function.
Returns:
Whatever the function returned last.
"""
if timeout_s is None or not hasattr(timeout_s, 'has_expired'):
timeout_s = PolledTimeout(timeout_s)
while True:
# Calls the function at least once
result = function()
if validation_fn(result) or timeout_s.has_expired():
return result
time.sleep(sleep_s) | [
"def",
"loop_until_timeout_or_valid",
"(",
"timeout_s",
",",
"function",
",",
"validation_fn",
",",
"sleep_s",
"=",
"1",
")",
":",
"# pylint: disable=invalid-name",
"if",
"timeout_s",
"is",
"None",
"or",
"not",
"hasattr",
"(",
"timeout_s",
",",
"'has_expired'",
")",
":",
"timeout_s",
"=",
"PolledTimeout",
"(",
"timeout_s",
")",
"while",
"True",
":",
"# Calls the function at least once",
"result",
"=",
"function",
"(",
")",
"if",
"validation_fn",
"(",
"result",
")",
"or",
"timeout_s",
".",
"has_expired",
"(",
")",
":",
"return",
"result",
"time",
".",
"sleep",
"(",
"sleep_s",
")"
] | Loops until the specified function returns valid or a timeout is reached.
Note: The function may return anything which, when passed to validation_fn,
evaluates to implicit True. This function will loop calling the function as
long as the result of validation_fn(function_result) returns something which
evaluates to False. We ensure function is called at least once regardless
of timeout.
Args:
timeout_s: The number of seconds to wait until a timeout condition is
reached. As a convenience, this accepts None to mean never timeout. Can
also be passed a PolledTimeout object instead of an integer.
function: The function to call each iteration.
validation_fn: The validation function called on the function result to
determine whether to keep looping.
sleep_s: The number of seconds to wait after calling the function.
Returns:
Whatever the function returned last. | [
"Loops",
"until",
"the",
"specified",
"function",
"returns",
"valid",
"or",
"a",
"timeout",
"is",
"reached",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/timeouts.py#L122-L151 |
227,023 | google/openhtf | openhtf/util/timeouts.py | loop_until_timeout_or_true | def loop_until_timeout_or_true(timeout_s, function, sleep_s=1): # pylint: disable=invalid-name
"""Loops until the specified function returns True or a timeout is reached.
Note: The function may return anything which evaluates to implicit True. This
function will loop calling it as long as it continues to return something
which evaluates to False. We ensure this method is called at least once
regardless of timeout.
Args:
timeout_s: The number of seconds to wait until a timeout condition is
reached. As a convenience, this accepts None to mean never timeout. Can
also be passed a PolledTimeout object instead of an integer.
function: The function to call each iteration.
sleep_s: The number of seconds to wait after calling the function.
Returns:
Whatever the function returned last.
"""
return loop_until_timeout_or_valid(timeout_s, function, lambda x: x, sleep_s) | python | def loop_until_timeout_or_true(timeout_s, function, sleep_s=1): # pylint: disable=invalid-name
"""Loops until the specified function returns True or a timeout is reached.
Note: The function may return anything which evaluates to implicit True. This
function will loop calling it as long as it continues to return something
which evaluates to False. We ensure this method is called at least once
regardless of timeout.
Args:
timeout_s: The number of seconds to wait until a timeout condition is
reached. As a convenience, this accepts None to mean never timeout. Can
also be passed a PolledTimeout object instead of an integer.
function: The function to call each iteration.
sleep_s: The number of seconds to wait after calling the function.
Returns:
Whatever the function returned last.
"""
return loop_until_timeout_or_valid(timeout_s, function, lambda x: x, sleep_s) | [
"def",
"loop_until_timeout_or_true",
"(",
"timeout_s",
",",
"function",
",",
"sleep_s",
"=",
"1",
")",
":",
"# pylint: disable=invalid-name",
"return",
"loop_until_timeout_or_valid",
"(",
"timeout_s",
",",
"function",
",",
"lambda",
"x",
":",
"x",
",",
"sleep_s",
")"
] | Loops until the specified function returns True or a timeout is reached.
Note: The function may return anything which evaluates to implicit True. This
function will loop calling it as long as it continues to return something
which evaluates to False. We ensure this method is called at least once
regardless of timeout.
Args:
timeout_s: The number of seconds to wait until a timeout condition is
reached. As a convenience, this accepts None to mean never timeout. Can
also be passed a PolledTimeout object instead of an integer.
function: The function to call each iteration.
sleep_s: The number of seconds to wait after calling the function.
Returns:
Whatever the function returned last. | [
"Loops",
"until",
"the",
"specified",
"function",
"returns",
"True",
"or",
"a",
"timeout",
"is",
"reached",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/timeouts.py#L154-L172 |
227,024 | google/openhtf | openhtf/util/timeouts.py | loop_until_timeout_or_not_none | def loop_until_timeout_or_not_none(timeout_s, function, sleep_s=1): # pylint: disable=invalid-name
"""Loops until the specified function returns non-None or until a timeout.
Args:
timeout_s: The number of seconds to wait until a timeout condition is
reached. As a convenience, this accepts None to mean never timeout. Can
also be passed a PolledTimeout object instead of an integer.
function: The function to call each iteration.
sleep_s: The number of seconds to wait after calling the function.
Returns:
Whatever the function returned last.
"""
return loop_until_timeout_or_valid(
timeout_s, function, lambda x: x is not None, sleep_s) | python | def loop_until_timeout_or_not_none(timeout_s, function, sleep_s=1): # pylint: disable=invalid-name
"""Loops until the specified function returns non-None or until a timeout.
Args:
timeout_s: The number of seconds to wait until a timeout condition is
reached. As a convenience, this accepts None to mean never timeout. Can
also be passed a PolledTimeout object instead of an integer.
function: The function to call each iteration.
sleep_s: The number of seconds to wait after calling the function.
Returns:
Whatever the function returned last.
"""
return loop_until_timeout_or_valid(
timeout_s, function, lambda x: x is not None, sleep_s) | [
"def",
"loop_until_timeout_or_not_none",
"(",
"timeout_s",
",",
"function",
",",
"sleep_s",
"=",
"1",
")",
":",
"# pylint: disable=invalid-name",
"return",
"loop_until_timeout_or_valid",
"(",
"timeout_s",
",",
"function",
",",
"lambda",
"x",
":",
"x",
"is",
"not",
"None",
",",
"sleep_s",
")"
] | Loops until the specified function returns non-None or until a timeout.
Args:
timeout_s: The number of seconds to wait until a timeout condition is
reached. As a convenience, this accepts None to mean never timeout. Can
also be passed a PolledTimeout object instead of an integer.
function: The function to call each iteration.
sleep_s: The number of seconds to wait after calling the function.
Returns:
Whatever the function returned last. | [
"Loops",
"until",
"the",
"specified",
"function",
"returns",
"non",
"-",
"None",
"or",
"until",
"a",
"timeout",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/timeouts.py#L175-L189 |
227,025 | google/openhtf | openhtf/util/timeouts.py | loop_until_true_else_raise | def loop_until_true_else_raise(timeout_s,
function,
invert=False,
message=None,
sleep_s=1):
"""Repeatedly call the given function until truthy, or raise on a timeout.
Args:
timeout_s: The number of seconds to wait until a timeout condition is
reached. As a convenience, this accepts None to mean never timeout. Can
also be passed a PolledTimeout object instead of an integer.
function: The function to call each iteration.
invert: If True, wait for the callable to return falsey instead of truthy.
message: Optional custom error message to use on a timeout.
sleep_s: Seconds to sleep between call attempts.
Returns:
The final return value of the function.
Raises:
RuntimeError if the timeout is reached before the function returns truthy.
"""
def validate(x):
return bool(x) != invert
result = loop_until_timeout_or_valid(timeout_s, function, validate, sleep_s=1)
if validate(result):
return result
if message is not None:
raise RuntimeError(message)
name = '(unknown)'
if hasattr(function, '__name__'):
name = function.__name__
elif (isinstance(function, functools.partial)
and hasattr(function.func, '__name__')):
name = function.func.__name__
raise RuntimeError(
'Function %s failed to return %s within %d seconds.'
% (name, 'falsey' if invert else 'truthy', timeout_s)) | python | def loop_until_true_else_raise(timeout_s,
function,
invert=False,
message=None,
sleep_s=1):
"""Repeatedly call the given function until truthy, or raise on a timeout.
Args:
timeout_s: The number of seconds to wait until a timeout condition is
reached. As a convenience, this accepts None to mean never timeout. Can
also be passed a PolledTimeout object instead of an integer.
function: The function to call each iteration.
invert: If True, wait for the callable to return falsey instead of truthy.
message: Optional custom error message to use on a timeout.
sleep_s: Seconds to sleep between call attempts.
Returns:
The final return value of the function.
Raises:
RuntimeError if the timeout is reached before the function returns truthy.
"""
def validate(x):
return bool(x) != invert
result = loop_until_timeout_or_valid(timeout_s, function, validate, sleep_s=1)
if validate(result):
return result
if message is not None:
raise RuntimeError(message)
name = '(unknown)'
if hasattr(function, '__name__'):
name = function.__name__
elif (isinstance(function, functools.partial)
and hasattr(function.func, '__name__')):
name = function.func.__name__
raise RuntimeError(
'Function %s failed to return %s within %d seconds.'
% (name, 'falsey' if invert else 'truthy', timeout_s)) | [
"def",
"loop_until_true_else_raise",
"(",
"timeout_s",
",",
"function",
",",
"invert",
"=",
"False",
",",
"message",
"=",
"None",
",",
"sleep_s",
"=",
"1",
")",
":",
"def",
"validate",
"(",
"x",
")",
":",
"return",
"bool",
"(",
"x",
")",
"!=",
"invert",
"result",
"=",
"loop_until_timeout_or_valid",
"(",
"timeout_s",
",",
"function",
",",
"validate",
",",
"sleep_s",
"=",
"1",
")",
"if",
"validate",
"(",
"result",
")",
":",
"return",
"result",
"if",
"message",
"is",
"not",
"None",
":",
"raise",
"RuntimeError",
"(",
"message",
")",
"name",
"=",
"'(unknown)'",
"if",
"hasattr",
"(",
"function",
",",
"'__name__'",
")",
":",
"name",
"=",
"function",
".",
"__name__",
"elif",
"(",
"isinstance",
"(",
"function",
",",
"functools",
".",
"partial",
")",
"and",
"hasattr",
"(",
"function",
".",
"func",
",",
"'__name__'",
")",
")",
":",
"name",
"=",
"function",
".",
"func",
".",
"__name__",
"raise",
"RuntimeError",
"(",
"'Function %s failed to return %s within %d seconds.'",
"%",
"(",
"name",
",",
"'falsey'",
"if",
"invert",
"else",
"'truthy'",
",",
"timeout_s",
")",
")"
] | Repeatedly call the given function until truthy, or raise on a timeout.
Args:
timeout_s: The number of seconds to wait until a timeout condition is
reached. As a convenience, this accepts None to mean never timeout. Can
also be passed a PolledTimeout object instead of an integer.
function: The function to call each iteration.
invert: If True, wait for the callable to return falsey instead of truthy.
message: Optional custom error message to use on a timeout.
sleep_s: Seconds to sleep between call attempts.
Returns:
The final return value of the function.
Raises:
RuntimeError if the timeout is reached before the function returns truthy. | [
"Repeatedly",
"call",
"the",
"given",
"function",
"until",
"truthy",
"or",
"raise",
"on",
"a",
"timeout",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/timeouts.py#L192-L232 |
227,026 | google/openhtf | openhtf/util/timeouts.py | execute_forever | def execute_forever(method, interval_s): # pylint: disable=invalid-name
"""Executes a method forever at the specified interval.
Args:
method: The callable to execute.
interval_s: The number of seconds to start the execution after each method
finishes.
Returns:
An Interval object.
"""
interval = Interval(method)
interval.start(interval_s)
return interval | python | def execute_forever(method, interval_s): # pylint: disable=invalid-name
"""Executes a method forever at the specified interval.
Args:
method: The callable to execute.
interval_s: The number of seconds to start the execution after each method
finishes.
Returns:
An Interval object.
"""
interval = Interval(method)
interval.start(interval_s)
return interval | [
"def",
"execute_forever",
"(",
"method",
",",
"interval_s",
")",
":",
"# pylint: disable=invalid-name",
"interval",
"=",
"Interval",
"(",
"method",
")",
"interval",
".",
"start",
"(",
"interval_s",
")",
"return",
"interval"
] | Executes a method forever at the specified interval.
Args:
method: The callable to execute.
interval_s: The number of seconds to start the execution after each method
finishes.
Returns:
An Interval object. | [
"Executes",
"a",
"method",
"forever",
"at",
"the",
"specified",
"interval",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/timeouts.py#L316-L328 |
227,027 | google/openhtf | openhtf/util/timeouts.py | execute_until_false | def execute_until_false(method, interval_s): # pylint: disable=invalid-name
"""Executes a method forever until the method returns a false value.
Args:
method: The callable to execute.
interval_s: The number of seconds to start the execution after each method
finishes.
Returns:
An Interval object.
"""
interval = Interval(method, stop_if_false=True)
interval.start(interval_s)
return interval | python | def execute_until_false(method, interval_s): # pylint: disable=invalid-name
"""Executes a method forever until the method returns a false value.
Args:
method: The callable to execute.
interval_s: The number of seconds to start the execution after each method
finishes.
Returns:
An Interval object.
"""
interval = Interval(method, stop_if_false=True)
interval.start(interval_s)
return interval | [
"def",
"execute_until_false",
"(",
"method",
",",
"interval_s",
")",
":",
"# pylint: disable=invalid-name",
"interval",
"=",
"Interval",
"(",
"method",
",",
"stop_if_false",
"=",
"True",
")",
"interval",
".",
"start",
"(",
"interval_s",
")",
"return",
"interval"
] | Executes a method forever until the method returns a false value.
Args:
method: The callable to execute.
interval_s: The number of seconds to start the execution after each method
finishes.
Returns:
An Interval object. | [
"Executes",
"a",
"method",
"forever",
"until",
"the",
"method",
"returns",
"a",
"false",
"value",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/timeouts.py#L331-L343 |
227,028 | google/openhtf | openhtf/util/timeouts.py | retry_until_true_or_limit_reached | def retry_until_true_or_limit_reached(method, limit, sleep_s=1,
catch_exceptions=()):
"""Executes a method until the retry limit is hit or True is returned."""
return retry_until_valid_or_limit_reached(
method, limit, lambda x: x, sleep_s, catch_exceptions) | python | def retry_until_true_or_limit_reached(method, limit, sleep_s=1,
catch_exceptions=()):
"""Executes a method until the retry limit is hit or True is returned."""
return retry_until_valid_or_limit_reached(
method, limit, lambda x: x, sleep_s, catch_exceptions) | [
"def",
"retry_until_true_or_limit_reached",
"(",
"method",
",",
"limit",
",",
"sleep_s",
"=",
"1",
",",
"catch_exceptions",
"=",
"(",
")",
")",
":",
"return",
"retry_until_valid_or_limit_reached",
"(",
"method",
",",
"limit",
",",
"lambda",
"x",
":",
"x",
",",
"sleep_s",
",",
"catch_exceptions",
")"
] | Executes a method until the retry limit is hit or True is returned. | [
"Executes",
"a",
"method",
"until",
"the",
"retry",
"limit",
"is",
"hit",
"or",
"True",
"is",
"returned",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/timeouts.py#L347-L351 |
227,029 | google/openhtf | openhtf/util/timeouts.py | retry_until_not_none_or_limit_reached | def retry_until_not_none_or_limit_reached(method, limit, sleep_s=1,
catch_exceptions=()):
"""Executes a method until the retry limit is hit or not None is returned."""
return retry_until_valid_or_limit_reached(
method, limit, lambda x: x is not None, sleep_s, catch_exceptions) | python | def retry_until_not_none_or_limit_reached(method, limit, sleep_s=1,
catch_exceptions=()):
"""Executes a method until the retry limit is hit or not None is returned."""
return retry_until_valid_or_limit_reached(
method, limit, lambda x: x is not None, sleep_s, catch_exceptions) | [
"def",
"retry_until_not_none_or_limit_reached",
"(",
"method",
",",
"limit",
",",
"sleep_s",
"=",
"1",
",",
"catch_exceptions",
"=",
"(",
")",
")",
":",
"return",
"retry_until_valid_or_limit_reached",
"(",
"method",
",",
"limit",
",",
"lambda",
"x",
":",
"x",
"is",
"not",
"None",
",",
"sleep_s",
",",
"catch_exceptions",
")"
] | Executes a method until the retry limit is hit or not None is returned. | [
"Executes",
"a",
"method",
"until",
"the",
"retry",
"limit",
"is",
"hit",
"or",
"not",
"None",
"is",
"returned",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/timeouts.py#L354-L358 |
227,030 | google/openhtf | openhtf/util/timeouts.py | retry_until_valid_or_limit_reached | def retry_until_valid_or_limit_reached(method, limit, validation_fn, sleep_s=1,
catch_exceptions=()):
"""Executes a method until the retry limit or validation_fn returns True.
The method is always called once so the effective lower limit for 'limit' is
1. Passing in a number less than 1 will still result it the method being
called once.
Args:
method: The method to execute should take no arguments.
limit: The number of times to try this method. Must be >0.
validation_fn: The validation function called on the function result to
determine whether to keep looping.
sleep_s: The time to sleep in between invocations.
catch_exceptions: Tuple of exception types to catch and count as failures.
Returns:
Whatever the method last returned, implicit False would indicate the
method never succeeded.
"""
assert limit > 0, 'Limit must be greater than 0'
def _execute_method(helper):
try:
return method()
except catch_exceptions:
if not helper.remaining:
raise
return None
helper = RetryHelper(limit - 1)
result = _execute_method(helper)
while not validation_fn(result) and helper.retry_if_possible():
time.sleep(sleep_s)
result = _execute_method(helper)
return result | python | def retry_until_valid_or_limit_reached(method, limit, validation_fn, sleep_s=1,
catch_exceptions=()):
"""Executes a method until the retry limit or validation_fn returns True.
The method is always called once so the effective lower limit for 'limit' is
1. Passing in a number less than 1 will still result it the method being
called once.
Args:
method: The method to execute should take no arguments.
limit: The number of times to try this method. Must be >0.
validation_fn: The validation function called on the function result to
determine whether to keep looping.
sleep_s: The time to sleep in between invocations.
catch_exceptions: Tuple of exception types to catch and count as failures.
Returns:
Whatever the method last returned, implicit False would indicate the
method never succeeded.
"""
assert limit > 0, 'Limit must be greater than 0'
def _execute_method(helper):
try:
return method()
except catch_exceptions:
if not helper.remaining:
raise
return None
helper = RetryHelper(limit - 1)
result = _execute_method(helper)
while not validation_fn(result) and helper.retry_if_possible():
time.sleep(sleep_s)
result = _execute_method(helper)
return result | [
"def",
"retry_until_valid_or_limit_reached",
"(",
"method",
",",
"limit",
",",
"validation_fn",
",",
"sleep_s",
"=",
"1",
",",
"catch_exceptions",
"=",
"(",
")",
")",
":",
"assert",
"limit",
">",
"0",
",",
"'Limit must be greater than 0'",
"def",
"_execute_method",
"(",
"helper",
")",
":",
"try",
":",
"return",
"method",
"(",
")",
"except",
"catch_exceptions",
":",
"if",
"not",
"helper",
".",
"remaining",
":",
"raise",
"return",
"None",
"helper",
"=",
"RetryHelper",
"(",
"limit",
"-",
"1",
")",
"result",
"=",
"_execute_method",
"(",
"helper",
")",
"while",
"not",
"validation_fn",
"(",
"result",
")",
"and",
"helper",
".",
"retry_if_possible",
"(",
")",
":",
"time",
".",
"sleep",
"(",
"sleep_s",
")",
"result",
"=",
"_execute_method",
"(",
"helper",
")",
"return",
"result"
] | Executes a method until the retry limit or validation_fn returns True.
The method is always called once so the effective lower limit for 'limit' is
1. Passing in a number less than 1 will still result it the method being
called once.
Args:
method: The method to execute should take no arguments.
limit: The number of times to try this method. Must be >0.
validation_fn: The validation function called on the function result to
determine whether to keep looping.
sleep_s: The time to sleep in between invocations.
catch_exceptions: Tuple of exception types to catch and count as failures.
Returns:
Whatever the method last returned, implicit False would indicate the
method never succeeded. | [
"Executes",
"a",
"method",
"until",
"the",
"retry",
"limit",
"or",
"validation_fn",
"returns",
"True",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/timeouts.py#L361-L395 |
227,031 | google/openhtf | openhtf/util/timeouts.py | take_at_least_n_seconds | def take_at_least_n_seconds(time_s):
"""A context manager which ensures it takes at least time_s to execute.
Example:
with take_at_least_n_seconds(5):
do.Something()
do.SomethingElse()
# if Something and SomethingElse took 3 seconds, the with block with sleep
# for 2 seconds before exiting.
Args:
time_s: The number of seconds this block should take. If it doesn't take at
least this time, then this method blocks during __exit__.
Yields:
To do some actions then on completion waits the remaining time.
"""
timeout = PolledTimeout(time_s)
yield
while not timeout.has_expired():
time.sleep(timeout.remaining) | python | def take_at_least_n_seconds(time_s):
"""A context manager which ensures it takes at least time_s to execute.
Example:
with take_at_least_n_seconds(5):
do.Something()
do.SomethingElse()
# if Something and SomethingElse took 3 seconds, the with block with sleep
# for 2 seconds before exiting.
Args:
time_s: The number of seconds this block should take. If it doesn't take at
least this time, then this method blocks during __exit__.
Yields:
To do some actions then on completion waits the remaining time.
"""
timeout = PolledTimeout(time_s)
yield
while not timeout.has_expired():
time.sleep(timeout.remaining) | [
"def",
"take_at_least_n_seconds",
"(",
"time_s",
")",
":",
"timeout",
"=",
"PolledTimeout",
"(",
"time_s",
")",
"yield",
"while",
"not",
"timeout",
".",
"has_expired",
"(",
")",
":",
"time",
".",
"sleep",
"(",
"timeout",
".",
"remaining",
")"
] | A context manager which ensures it takes at least time_s to execute.
Example:
with take_at_least_n_seconds(5):
do.Something()
do.SomethingElse()
# if Something and SomethingElse took 3 seconds, the with block with sleep
# for 2 seconds before exiting.
Args:
time_s: The number of seconds this block should take. If it doesn't take at
least this time, then this method blocks during __exit__.
Yields:
To do some actions then on completion waits the remaining time. | [
"A",
"context",
"manager",
"which",
"ensures",
"it",
"takes",
"at",
"least",
"time_s",
"to",
"execute",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/timeouts.py#L401-L419 |
227,032 | google/openhtf | openhtf/util/timeouts.py | take_at_most_n_seconds | def take_at_most_n_seconds(time_s, func, *args, **kwargs):
"""A function that returns whether a function call took less than time_s.
NOTE: The function call is not killed and will run indefinitely if hung.
Args:
time_s: Maximum amount of time to take.
func: Function to call.
*args: Arguments to call the function with.
**kwargs: Keyword arguments to call the function with.
Returns:
True if the function finished in less than time_s seconds.
"""
thread = threading.Thread(target=func, args=args, kwargs=kwargs)
thread.start()
thread.join(time_s)
if thread.is_alive():
return False
return True | python | def take_at_most_n_seconds(time_s, func, *args, **kwargs):
"""A function that returns whether a function call took less than time_s.
NOTE: The function call is not killed and will run indefinitely if hung.
Args:
time_s: Maximum amount of time to take.
func: Function to call.
*args: Arguments to call the function with.
**kwargs: Keyword arguments to call the function with.
Returns:
True if the function finished in less than time_s seconds.
"""
thread = threading.Thread(target=func, args=args, kwargs=kwargs)
thread.start()
thread.join(time_s)
if thread.is_alive():
return False
return True | [
"def",
"take_at_most_n_seconds",
"(",
"time_s",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"thread",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"func",
",",
"args",
"=",
"args",
",",
"kwargs",
"=",
"kwargs",
")",
"thread",
".",
"start",
"(",
")",
"thread",
".",
"join",
"(",
"time_s",
")",
"if",
"thread",
".",
"is_alive",
"(",
")",
":",
"return",
"False",
"return",
"True"
] | A function that returns whether a function call took less than time_s.
NOTE: The function call is not killed and will run indefinitely if hung.
Args:
time_s: Maximum amount of time to take.
func: Function to call.
*args: Arguments to call the function with.
**kwargs: Keyword arguments to call the function with.
Returns:
True if the function finished in less than time_s seconds. | [
"A",
"function",
"that",
"returns",
"whether",
"a",
"function",
"call",
"took",
"less",
"than",
"time_s",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/timeouts.py#L422-L440 |
227,033 | google/openhtf | openhtf/util/timeouts.py | execute_after_delay | def execute_after_delay(time_s, func, *args, **kwargs):
"""A function that executes the given function after a delay.
Executes func in a separate thread after a delay, so that this function
returns immediately. Note that any exceptions raised by func will be
ignored (but logged). Also, if time_s is a PolledTimeout with no expiration,
then this method simply returns immediately and does nothing.
Args:
time_s: Delay in seconds to wait before executing func, may be a
PolledTimeout object.
func: Function to call.
*args: Arguments to call the function with.
**kwargs: Keyword arguments to call the function with.
"""
timeout = PolledTimeout.from_seconds(time_s)
def target():
time.sleep(timeout.remaining)
try:
func(*args, **kwargs)
except Exception: # pylint: disable=broad-except
_LOG.exception('Error executing %s after %s expires.', func, timeout)
if timeout.remaining is not None:
thread = threading.Thread(target=target)
thread.start() | python | def execute_after_delay(time_s, func, *args, **kwargs):
"""A function that executes the given function after a delay.
Executes func in a separate thread after a delay, so that this function
returns immediately. Note that any exceptions raised by func will be
ignored (but logged). Also, if time_s is a PolledTimeout with no expiration,
then this method simply returns immediately and does nothing.
Args:
time_s: Delay in seconds to wait before executing func, may be a
PolledTimeout object.
func: Function to call.
*args: Arguments to call the function with.
**kwargs: Keyword arguments to call the function with.
"""
timeout = PolledTimeout.from_seconds(time_s)
def target():
time.sleep(timeout.remaining)
try:
func(*args, **kwargs)
except Exception: # pylint: disable=broad-except
_LOG.exception('Error executing %s after %s expires.', func, timeout)
if timeout.remaining is not None:
thread = threading.Thread(target=target)
thread.start() | [
"def",
"execute_after_delay",
"(",
"time_s",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"timeout",
"=",
"PolledTimeout",
".",
"from_seconds",
"(",
"time_s",
")",
"def",
"target",
"(",
")",
":",
"time",
".",
"sleep",
"(",
"timeout",
".",
"remaining",
")",
"try",
":",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"Exception",
":",
"# pylint: disable=broad-except",
"_LOG",
".",
"exception",
"(",
"'Error executing %s after %s expires.'",
",",
"func",
",",
"timeout",
")",
"if",
"timeout",
".",
"remaining",
"is",
"not",
"None",
":",
"thread",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"target",
")",
"thread",
".",
"start",
"(",
")"
] | A function that executes the given function after a delay.
Executes func in a separate thread after a delay, so that this function
returns immediately. Note that any exceptions raised by func will be
ignored (but logged). Also, if time_s is a PolledTimeout with no expiration,
then this method simply returns immediately and does nothing.
Args:
time_s: Delay in seconds to wait before executing func, may be a
PolledTimeout object.
func: Function to call.
*args: Arguments to call the function with.
**kwargs: Keyword arguments to call the function with. | [
"A",
"function",
"that",
"executes",
"the",
"given",
"function",
"after",
"a",
"delay",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/timeouts.py#L443-L468 |
227,034 | google/openhtf | openhtf/util/timeouts.py | PolledTimeout.from_millis | def from_millis(cls, timeout_ms):
"""Create a new PolledTimeout if needed.
If timeout_ms is already a PolledTimeout, just return it, otherwise create a
new PolledTimeout with the given timeout in milliseconds.
Args:
timeout_ms: PolledTimeout object, or number of milliseconds to use for
creating a new one.
Returns:
A PolledTimeout object that will expire in timeout_ms milliseconds, which
may be timeout_ms itself, or a newly allocated PolledTimeout.
"""
if hasattr(timeout_ms, 'has_expired'):
return timeout_ms
if timeout_ms is None:
return cls(None)
return cls(timeout_ms / 1000.0) | python | def from_millis(cls, timeout_ms):
"""Create a new PolledTimeout if needed.
If timeout_ms is already a PolledTimeout, just return it, otherwise create a
new PolledTimeout with the given timeout in milliseconds.
Args:
timeout_ms: PolledTimeout object, or number of milliseconds to use for
creating a new one.
Returns:
A PolledTimeout object that will expire in timeout_ms milliseconds, which
may be timeout_ms itself, or a newly allocated PolledTimeout.
"""
if hasattr(timeout_ms, 'has_expired'):
return timeout_ms
if timeout_ms is None:
return cls(None)
return cls(timeout_ms / 1000.0) | [
"def",
"from_millis",
"(",
"cls",
",",
"timeout_ms",
")",
":",
"if",
"hasattr",
"(",
"timeout_ms",
",",
"'has_expired'",
")",
":",
"return",
"timeout_ms",
"if",
"timeout_ms",
"is",
"None",
":",
"return",
"cls",
"(",
"None",
")",
"return",
"cls",
"(",
"timeout_ms",
"/",
"1000.0",
")"
] | Create a new PolledTimeout if needed.
If timeout_ms is already a PolledTimeout, just return it, otherwise create a
new PolledTimeout with the given timeout in milliseconds.
Args:
timeout_ms: PolledTimeout object, or number of milliseconds to use for
creating a new one.
Returns:
A PolledTimeout object that will expire in timeout_ms milliseconds, which
may be timeout_ms itself, or a newly allocated PolledTimeout. | [
"Create",
"a",
"new",
"PolledTimeout",
"if",
"needed",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/timeouts.py#L41-L59 |
227,035 | google/openhtf | openhtf/util/timeouts.py | Interval.start | def start(self, interval_s):
"""Starts executing the method at the specified interval.
Args:
interval_s: The amount of time between executions of the method.
Returns:
False if the interval was already running.
"""
if self.running:
return False
self.stopped.clear()
def _execute():
# Always execute immediately once
if not self.method() and self.stop_if_false:
return
while not self.stopped.wait(interval_s):
if not self.method() and self.stop_if_false:
return
self.thread = threading.Thread(target=_execute)
self.thread.daemon = True
self.thread.start()
return True | python | def start(self, interval_s):
"""Starts executing the method at the specified interval.
Args:
interval_s: The amount of time between executions of the method.
Returns:
False if the interval was already running.
"""
if self.running:
return False
self.stopped.clear()
def _execute():
# Always execute immediately once
if not self.method() and self.stop_if_false:
return
while not self.stopped.wait(interval_s):
if not self.method() and self.stop_if_false:
return
self.thread = threading.Thread(target=_execute)
self.thread.daemon = True
self.thread.start()
return True | [
"def",
"start",
"(",
"self",
",",
"interval_s",
")",
":",
"if",
"self",
".",
"running",
":",
"return",
"False",
"self",
".",
"stopped",
".",
"clear",
"(",
")",
"def",
"_execute",
"(",
")",
":",
"# Always execute immediately once",
"if",
"not",
"self",
".",
"method",
"(",
")",
"and",
"self",
".",
"stop_if_false",
":",
"return",
"while",
"not",
"self",
".",
"stopped",
".",
"wait",
"(",
"interval_s",
")",
":",
"if",
"not",
"self",
".",
"method",
"(",
")",
"and",
"self",
".",
"stop_if_false",
":",
"return",
"self",
".",
"thread",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"_execute",
")",
"self",
".",
"thread",
".",
"daemon",
"=",
"True",
"self",
".",
"thread",
".",
"start",
"(",
")",
"return",
"True"
] | Starts executing the method at the specified interval.
Args:
interval_s: The amount of time between executions of the method.
Returns:
False if the interval was already running. | [
"Starts",
"executing",
"the",
"method",
"at",
"the",
"specified",
"interval",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/timeouts.py#L257-L281 |
227,036 | google/openhtf | openhtf/util/timeouts.py | Interval.stop | def stop(self, timeout_s=None):
"""Stops the interval.
If a timeout is provided and stop returns False then the thread is
effectively abandoned in whatever state it was in (presumably dead-locked).
Args:
timeout_s: The time in seconds to wait on the thread to finish. By
default it's forever.
Returns:
False if a timeout was provided and we timed out.
"""
self.stopped.set()
if self.thread:
self.thread.join(timeout_s)
return not self.thread.isAlive()
else:
return True | python | def stop(self, timeout_s=None):
"""Stops the interval.
If a timeout is provided and stop returns False then the thread is
effectively abandoned in whatever state it was in (presumably dead-locked).
Args:
timeout_s: The time in seconds to wait on the thread to finish. By
default it's forever.
Returns:
False if a timeout was provided and we timed out.
"""
self.stopped.set()
if self.thread:
self.thread.join(timeout_s)
return not self.thread.isAlive()
else:
return True | [
"def",
"stop",
"(",
"self",
",",
"timeout_s",
"=",
"None",
")",
":",
"self",
".",
"stopped",
".",
"set",
"(",
")",
"if",
"self",
".",
"thread",
":",
"self",
".",
"thread",
".",
"join",
"(",
"timeout_s",
")",
"return",
"not",
"self",
".",
"thread",
".",
"isAlive",
"(",
")",
"else",
":",
"return",
"True"
] | Stops the interval.
If a timeout is provided and stop returns False then the thread is
effectively abandoned in whatever state it was in (presumably dead-locked).
Args:
timeout_s: The time in seconds to wait on the thread to finish. By
default it's forever.
Returns:
False if a timeout was provided and we timed out. | [
"Stops",
"the",
"interval",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/timeouts.py#L283-L300 |
227,037 | google/openhtf | openhtf/util/timeouts.py | Interval.join | def join(self, timeout_s=None):
"""Joins blocking until the interval ends or until timeout is reached.
Args:
timeout_s: The time in seconds to wait, defaults to forever.
Returns:
True if the interval is still running and we reached the timeout.
"""
if not self.thread:
return False
self.thread.join(timeout_s)
return self.running | python | def join(self, timeout_s=None):
"""Joins blocking until the interval ends or until timeout is reached.
Args:
timeout_s: The time in seconds to wait, defaults to forever.
Returns:
True if the interval is still running and we reached the timeout.
"""
if not self.thread:
return False
self.thread.join(timeout_s)
return self.running | [
"def",
"join",
"(",
"self",
",",
"timeout_s",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"thread",
":",
"return",
"False",
"self",
".",
"thread",
".",
"join",
"(",
"timeout_s",
")",
"return",
"self",
".",
"running"
] | Joins blocking until the interval ends or until timeout is reached.
Args:
timeout_s: The time in seconds to wait, defaults to forever.
Returns:
True if the interval is still running and we reached the timeout. | [
"Joins",
"blocking",
"until",
"the",
"interval",
"ends",
"or",
"until",
"timeout",
"is",
"reached",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/timeouts.py#L302-L313 |
227,038 | google/openhtf | pylint_plugins/conf_plugin.py | transform_declare | def transform_declare(node):
"""Transform conf.declare calls by stashing the declared names."""
global CURRENT_ROOT
if not (isinstance(node.func, astroid.Attribute)
and isinstance(node.func.expr, astroid.Name)
and node.func.expr.name == 'conf'
and node.func.attrname == 'declare'):
return
conf_key_name = None
if node.args:
conf_key_name = node.args[0].value
else:
for keyword in node.keywords:
if keyword.arg == 'name':
# Assume the name is an astroid.Const(str), so it has a str value.
conf_key_name = keyword.value.value
break
assert conf_key_name != None, "Invalid conf.declare() syntax"
if CONF_NODE:
# Keep track of the current root, refreshing the locals if it changes.
if not CURRENT_ROOT or CURRENT_ROOT != node.root():
CURRENT_ROOT = node.root()
CONF_NODE.locals = CONF_LOCALS
CONF_NODE.locals[conf_key_name] = [None]
else:
CONF_LOCALS[conf_key_name] = [None] | python | def transform_declare(node):
"""Transform conf.declare calls by stashing the declared names."""
global CURRENT_ROOT
if not (isinstance(node.func, astroid.Attribute)
and isinstance(node.func.expr, astroid.Name)
and node.func.expr.name == 'conf'
and node.func.attrname == 'declare'):
return
conf_key_name = None
if node.args:
conf_key_name = node.args[0].value
else:
for keyword in node.keywords:
if keyword.arg == 'name':
# Assume the name is an astroid.Const(str), so it has a str value.
conf_key_name = keyword.value.value
break
assert conf_key_name != None, "Invalid conf.declare() syntax"
if CONF_NODE:
# Keep track of the current root, refreshing the locals if it changes.
if not CURRENT_ROOT or CURRENT_ROOT != node.root():
CURRENT_ROOT = node.root()
CONF_NODE.locals = CONF_LOCALS
CONF_NODE.locals[conf_key_name] = [None]
else:
CONF_LOCALS[conf_key_name] = [None] | [
"def",
"transform_declare",
"(",
"node",
")",
":",
"global",
"CURRENT_ROOT",
"if",
"not",
"(",
"isinstance",
"(",
"node",
".",
"func",
",",
"astroid",
".",
"Attribute",
")",
"and",
"isinstance",
"(",
"node",
".",
"func",
".",
"expr",
",",
"astroid",
".",
"Name",
")",
"and",
"node",
".",
"func",
".",
"expr",
".",
"name",
"==",
"'conf'",
"and",
"node",
".",
"func",
".",
"attrname",
"==",
"'declare'",
")",
":",
"return",
"conf_key_name",
"=",
"None",
"if",
"node",
".",
"args",
":",
"conf_key_name",
"=",
"node",
".",
"args",
"[",
"0",
"]",
".",
"value",
"else",
":",
"for",
"keyword",
"in",
"node",
".",
"keywords",
":",
"if",
"keyword",
".",
"arg",
"==",
"'name'",
":",
"# Assume the name is an astroid.Const(str), so it has a str value.",
"conf_key_name",
"=",
"keyword",
".",
"value",
".",
"value",
"break",
"assert",
"conf_key_name",
"!=",
"None",
",",
"\"Invalid conf.declare() syntax\"",
"if",
"CONF_NODE",
":",
"# Keep track of the current root, refreshing the locals if it changes.",
"if",
"not",
"CURRENT_ROOT",
"or",
"CURRENT_ROOT",
"!=",
"node",
".",
"root",
"(",
")",
":",
"CURRENT_ROOT",
"=",
"node",
".",
"root",
"(",
")",
"CONF_NODE",
".",
"locals",
"=",
"CONF_LOCALS",
"CONF_NODE",
".",
"locals",
"[",
"conf_key_name",
"]",
"=",
"[",
"None",
"]",
"else",
":",
"CONF_LOCALS",
"[",
"conf_key_name",
"]",
"=",
"[",
"None",
"]"
] | Transform conf.declare calls by stashing the declared names. | [
"Transform",
"conf",
".",
"declare",
"calls",
"by",
"stashing",
"the",
"declared",
"names",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/pylint_plugins/conf_plugin.py#L30-L59 |
227,039 | google/openhtf | pylint_plugins/conf_plugin.py | transform_conf_module | def transform_conf_module(cls):
"""Transform usages of the conf module by updating locals."""
global CONF_NODE
if cls.name == 'openhtf.conf':
# Put all the attributes in Configuration into the openhtf.conf node.
cls._locals.update(cls.locals['Configuration'][0].locals)
# Store reference to this node for future use.
CONF_NODE = cls
CONF_LOCALS.update(cls.locals) | python | def transform_conf_module(cls):
"""Transform usages of the conf module by updating locals."""
global CONF_NODE
if cls.name == 'openhtf.conf':
# Put all the attributes in Configuration into the openhtf.conf node.
cls._locals.update(cls.locals['Configuration'][0].locals)
# Store reference to this node for future use.
CONF_NODE = cls
CONF_LOCALS.update(cls.locals) | [
"def",
"transform_conf_module",
"(",
"cls",
")",
":",
"global",
"CONF_NODE",
"if",
"cls",
".",
"name",
"==",
"'openhtf.conf'",
":",
"# Put all the attributes in Configuration into the openhtf.conf node.",
"cls",
".",
"_locals",
".",
"update",
"(",
"cls",
".",
"locals",
"[",
"'Configuration'",
"]",
"[",
"0",
"]",
".",
"locals",
")",
"# Store reference to this node for future use.",
"CONF_NODE",
"=",
"cls",
"CONF_LOCALS",
".",
"update",
"(",
"cls",
".",
"locals",
")"
] | Transform usages of the conf module by updating locals. | [
"Transform",
"usages",
"of",
"the",
"conf",
"module",
"by",
"updating",
"locals",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/pylint_plugins/conf_plugin.py#L62-L72 |
227,040 | google/openhtf | pylint_plugins/conf_plugin.py | register | def register(linter):
"""Register all transforms with the linter."""
MANAGER.register_transform(astroid.Call, transform_declare)
MANAGER.register_transform(astroid.Module, transform_conf_module) | python | def register(linter):
"""Register all transforms with the linter."""
MANAGER.register_transform(astroid.Call, transform_declare)
MANAGER.register_transform(astroid.Module, transform_conf_module) | [
"def",
"register",
"(",
"linter",
")",
":",
"MANAGER",
".",
"register_transform",
"(",
"astroid",
".",
"Call",
",",
"transform_declare",
")",
"MANAGER",
".",
"register_transform",
"(",
"astroid",
".",
"Module",
",",
"transform_conf_module",
")"
] | Register all transforms with the linter. | [
"Register",
"all",
"transforms",
"with",
"the",
"linter",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/pylint_plugins/conf_plugin.py#L75-L78 |
227,041 | google/openhtf | openhtf/plugs/user_input.py | ConsolePrompt.run | def run(self):
"""Main logic for this thread to execute."""
if platform.system() == 'Windows':
# Windows doesn't support file-like objects for select(), so fall back
# to raw_input().
response = input(''.join((self._message,
os.linesep,
PROMPT)))
self._answered = True
self._callback(response)
return
# First, display the prompt to the console.
console_output.cli_print(self._message, color=self._color,
end=os.linesep, logger=None)
console_output.cli_print(PROMPT, color=self._color, end='', logger=None)
sys.stdout.flush()
# Before reading, clear any lingering buffered terminal input.
termios.tcflush(sys.stdin, termios.TCIFLUSH)
line = ''
while not self._stop_event.is_set():
inputs, _, _ = select.select([sys.stdin], [], [], 0.001)
if sys.stdin in inputs:
new = os.read(sys.stdin.fileno(), 1024)
if not new:
# Hit EOF!
# They hit ^D (to insert EOF). Tell them to hit ^C if they
# want to actually quit.
print('Hit ^C (Ctrl+c) to exit.')
break
line += new.decode('utf-8')
if '\n' in line:
response = line[:line.find('\n')]
self._answered = True
self._callback(response)
return | python | def run(self):
"""Main logic for this thread to execute."""
if platform.system() == 'Windows':
# Windows doesn't support file-like objects for select(), so fall back
# to raw_input().
response = input(''.join((self._message,
os.linesep,
PROMPT)))
self._answered = True
self._callback(response)
return
# First, display the prompt to the console.
console_output.cli_print(self._message, color=self._color,
end=os.linesep, logger=None)
console_output.cli_print(PROMPT, color=self._color, end='', logger=None)
sys.stdout.flush()
# Before reading, clear any lingering buffered terminal input.
termios.tcflush(sys.stdin, termios.TCIFLUSH)
line = ''
while not self._stop_event.is_set():
inputs, _, _ = select.select([sys.stdin], [], [], 0.001)
if sys.stdin in inputs:
new = os.read(sys.stdin.fileno(), 1024)
if not new:
# Hit EOF!
# They hit ^D (to insert EOF). Tell them to hit ^C if they
# want to actually quit.
print('Hit ^C (Ctrl+c) to exit.')
break
line += new.decode('utf-8')
if '\n' in line:
response = line[:line.find('\n')]
self._answered = True
self._callback(response)
return | [
"def",
"run",
"(",
"self",
")",
":",
"if",
"platform",
".",
"system",
"(",
")",
"==",
"'Windows'",
":",
"# Windows doesn't support file-like objects for select(), so fall back",
"# to raw_input().",
"response",
"=",
"input",
"(",
"''",
".",
"join",
"(",
"(",
"self",
".",
"_message",
",",
"os",
".",
"linesep",
",",
"PROMPT",
")",
")",
")",
"self",
".",
"_answered",
"=",
"True",
"self",
".",
"_callback",
"(",
"response",
")",
"return",
"# First, display the prompt to the console.",
"console_output",
".",
"cli_print",
"(",
"self",
".",
"_message",
",",
"color",
"=",
"self",
".",
"_color",
",",
"end",
"=",
"os",
".",
"linesep",
",",
"logger",
"=",
"None",
")",
"console_output",
".",
"cli_print",
"(",
"PROMPT",
",",
"color",
"=",
"self",
".",
"_color",
",",
"end",
"=",
"''",
",",
"logger",
"=",
"None",
")",
"sys",
".",
"stdout",
".",
"flush",
"(",
")",
"# Before reading, clear any lingering buffered terminal input.",
"termios",
".",
"tcflush",
"(",
"sys",
".",
"stdin",
",",
"termios",
".",
"TCIFLUSH",
")",
"line",
"=",
"''",
"while",
"not",
"self",
".",
"_stop_event",
".",
"is_set",
"(",
")",
":",
"inputs",
",",
"_",
",",
"_",
"=",
"select",
".",
"select",
"(",
"[",
"sys",
".",
"stdin",
"]",
",",
"[",
"]",
",",
"[",
"]",
",",
"0.001",
")",
"if",
"sys",
".",
"stdin",
"in",
"inputs",
":",
"new",
"=",
"os",
".",
"read",
"(",
"sys",
".",
"stdin",
".",
"fileno",
"(",
")",
",",
"1024",
")",
"if",
"not",
"new",
":",
"# Hit EOF!",
"# They hit ^D (to insert EOF). Tell them to hit ^C if they",
"# want to actually quit.",
"print",
"(",
"'Hit ^C (Ctrl+c) to exit.'",
")",
"break",
"line",
"+=",
"new",
".",
"decode",
"(",
"'utf-8'",
")",
"if",
"'\\n'",
"in",
"line",
":",
"response",
"=",
"line",
"[",
":",
"line",
".",
"find",
"(",
"'\\n'",
")",
"]",
"self",
".",
"_answered",
"=",
"True",
"self",
".",
"_callback",
"(",
"response",
")",
"return"
] | Main logic for this thread to execute. | [
"Main",
"logic",
"for",
"this",
"thread",
"to",
"execute",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/user_input.py#L90-L127 |
227,042 | google/openhtf | openhtf/plugs/user_input.py | UserInput._asdict | def _asdict(self):
"""Return a dictionary representation of the current prompt."""
with self._cond:
if self._prompt is None:
return
return {'id': self._prompt.id,
'message': self._prompt.message,
'text-input': self._prompt.text_input} | python | def _asdict(self):
"""Return a dictionary representation of the current prompt."""
with self._cond:
if self._prompt is None:
return
return {'id': self._prompt.id,
'message': self._prompt.message,
'text-input': self._prompt.text_input} | [
"def",
"_asdict",
"(",
"self",
")",
":",
"with",
"self",
".",
"_cond",
":",
"if",
"self",
".",
"_prompt",
"is",
"None",
":",
"return",
"return",
"{",
"'id'",
":",
"self",
".",
"_prompt",
".",
"id",
",",
"'message'",
":",
"self",
".",
"_prompt",
".",
"message",
",",
"'text-input'",
":",
"self",
".",
"_prompt",
".",
"text_input",
"}"
] | Return a dictionary representation of the current prompt. | [
"Return",
"a",
"dictionary",
"representation",
"of",
"the",
"current",
"prompt",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/user_input.py#L146-L153 |
227,043 | google/openhtf | openhtf/plugs/user_input.py | UserInput.remove_prompt | def remove_prompt(self):
"""Remove the prompt."""
with self._cond:
self._prompt = None
if self._console_prompt:
self._console_prompt.Stop()
self._console_prompt = None
self.notify_update() | python | def remove_prompt(self):
"""Remove the prompt."""
with self._cond:
self._prompt = None
if self._console_prompt:
self._console_prompt.Stop()
self._console_prompt = None
self.notify_update() | [
"def",
"remove_prompt",
"(",
"self",
")",
":",
"with",
"self",
".",
"_cond",
":",
"self",
".",
"_prompt",
"=",
"None",
"if",
"self",
".",
"_console_prompt",
":",
"self",
".",
"_console_prompt",
".",
"Stop",
"(",
")",
"self",
".",
"_console_prompt",
"=",
"None",
"self",
".",
"notify_update",
"(",
")"
] | Remove the prompt. | [
"Remove",
"the",
"prompt",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/user_input.py#L158-L165 |
227,044 | google/openhtf | openhtf/plugs/user_input.py | UserInput.prompt | def prompt(self, message, text_input=False, timeout_s=None, cli_color=''):
"""Display a prompt and wait for a response.
Args:
message: A string to be presented to the user.
text_input: A boolean indicating whether the user must respond with text.
timeout_s: Seconds to wait before raising a PromptUnansweredError.
cli_color: An ANSI color code, or the empty string.
Returns:
A string response, or the empty string if text_input was False.
Raises:
MultiplePromptsError: There was already an existing prompt.
PromptUnansweredError: Timed out waiting for the user to respond.
"""
self.start_prompt(message, text_input, cli_color)
return self.wait_for_prompt(timeout_s) | python | def prompt(self, message, text_input=False, timeout_s=None, cli_color=''):
"""Display a prompt and wait for a response.
Args:
message: A string to be presented to the user.
text_input: A boolean indicating whether the user must respond with text.
timeout_s: Seconds to wait before raising a PromptUnansweredError.
cli_color: An ANSI color code, or the empty string.
Returns:
A string response, or the empty string if text_input was False.
Raises:
MultiplePromptsError: There was already an existing prompt.
PromptUnansweredError: Timed out waiting for the user to respond.
"""
self.start_prompt(message, text_input, cli_color)
return self.wait_for_prompt(timeout_s) | [
"def",
"prompt",
"(",
"self",
",",
"message",
",",
"text_input",
"=",
"False",
",",
"timeout_s",
"=",
"None",
",",
"cli_color",
"=",
"''",
")",
":",
"self",
".",
"start_prompt",
"(",
"message",
",",
"text_input",
",",
"cli_color",
")",
"return",
"self",
".",
"wait_for_prompt",
"(",
"timeout_s",
")"
] | Display a prompt and wait for a response.
Args:
message: A string to be presented to the user.
text_input: A boolean indicating whether the user must respond with text.
timeout_s: Seconds to wait before raising a PromptUnansweredError.
cli_color: An ANSI color code, or the empty string.
Returns:
A string response, or the empty string if text_input was False.
Raises:
MultiplePromptsError: There was already an existing prompt.
PromptUnansweredError: Timed out waiting for the user to respond. | [
"Display",
"a",
"prompt",
"and",
"wait",
"for",
"a",
"response",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/user_input.py#L167-L184 |
227,045 | google/openhtf | openhtf/plugs/user_input.py | UserInput.start_prompt | def start_prompt(self, message, text_input=False, cli_color=''):
"""Display a prompt.
Args:
message: A string to be presented to the user.
text_input: A boolean indicating whether the user must respond with text.
cli_color: An ANSI color code, or the empty string.
Raises:
MultiplePromptsError: There was already an existing prompt.
Returns:
A string uniquely identifying the prompt.
"""
with self._cond:
if self._prompt:
raise MultiplePromptsError
prompt_id = uuid.uuid4().hex
_LOG.debug('Displaying prompt (%s): "%s"%s', prompt_id, message,
', Expects text input.' if text_input else '')
self._response = None
self._prompt = Prompt(
id=prompt_id, message=message, text_input=text_input)
if sys.stdin.isatty():
self._console_prompt = ConsolePrompt(
message, functools.partial(self.respond, prompt_id), cli_color)
self._console_prompt.start()
self.notify_update()
return prompt_id | python | def start_prompt(self, message, text_input=False, cli_color=''):
"""Display a prompt.
Args:
message: A string to be presented to the user.
text_input: A boolean indicating whether the user must respond with text.
cli_color: An ANSI color code, or the empty string.
Raises:
MultiplePromptsError: There was already an existing prompt.
Returns:
A string uniquely identifying the prompt.
"""
with self._cond:
if self._prompt:
raise MultiplePromptsError
prompt_id = uuid.uuid4().hex
_LOG.debug('Displaying prompt (%s): "%s"%s', prompt_id, message,
', Expects text input.' if text_input else '')
self._response = None
self._prompt = Prompt(
id=prompt_id, message=message, text_input=text_input)
if sys.stdin.isatty():
self._console_prompt = ConsolePrompt(
message, functools.partial(self.respond, prompt_id), cli_color)
self._console_prompt.start()
self.notify_update()
return prompt_id | [
"def",
"start_prompt",
"(",
"self",
",",
"message",
",",
"text_input",
"=",
"False",
",",
"cli_color",
"=",
"''",
")",
":",
"with",
"self",
".",
"_cond",
":",
"if",
"self",
".",
"_prompt",
":",
"raise",
"MultiplePromptsError",
"prompt_id",
"=",
"uuid",
".",
"uuid4",
"(",
")",
".",
"hex",
"_LOG",
".",
"debug",
"(",
"'Displaying prompt (%s): \"%s\"%s'",
",",
"prompt_id",
",",
"message",
",",
"', Expects text input.'",
"if",
"text_input",
"else",
"''",
")",
"self",
".",
"_response",
"=",
"None",
"self",
".",
"_prompt",
"=",
"Prompt",
"(",
"id",
"=",
"prompt_id",
",",
"message",
"=",
"message",
",",
"text_input",
"=",
"text_input",
")",
"if",
"sys",
".",
"stdin",
".",
"isatty",
"(",
")",
":",
"self",
".",
"_console_prompt",
"=",
"ConsolePrompt",
"(",
"message",
",",
"functools",
".",
"partial",
"(",
"self",
".",
"respond",
",",
"prompt_id",
")",
",",
"cli_color",
")",
"self",
".",
"_console_prompt",
".",
"start",
"(",
")",
"self",
".",
"notify_update",
"(",
")",
"return",
"prompt_id"
] | Display a prompt.
Args:
message: A string to be presented to the user.
text_input: A boolean indicating whether the user must respond with text.
cli_color: An ANSI color code, or the empty string.
Raises:
MultiplePromptsError: There was already an existing prompt.
Returns:
A string uniquely identifying the prompt. | [
"Display",
"a",
"prompt",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/user_input.py#L186-L216 |
227,046 | google/openhtf | openhtf/plugs/user_input.py | UserInput.wait_for_prompt | def wait_for_prompt(self, timeout_s=None):
"""Wait for the user to respond to the current prompt.
Args:
timeout_s: Seconds to wait before raising a PromptUnansweredError.
Returns:
A string response, or the empty string if text_input was False.
Raises:
PromptUnansweredError: Timed out waiting for the user to respond.
"""
with self._cond:
if self._prompt:
if timeout_s is None:
self._cond.wait(3600 * 24 * 365)
else:
self._cond.wait(timeout_s)
if self._response is None:
raise PromptUnansweredError
return self._response | python | def wait_for_prompt(self, timeout_s=None):
"""Wait for the user to respond to the current prompt.
Args:
timeout_s: Seconds to wait before raising a PromptUnansweredError.
Returns:
A string response, or the empty string if text_input was False.
Raises:
PromptUnansweredError: Timed out waiting for the user to respond.
"""
with self._cond:
if self._prompt:
if timeout_s is None:
self._cond.wait(3600 * 24 * 365)
else:
self._cond.wait(timeout_s)
if self._response is None:
raise PromptUnansweredError
return self._response | [
"def",
"wait_for_prompt",
"(",
"self",
",",
"timeout_s",
"=",
"None",
")",
":",
"with",
"self",
".",
"_cond",
":",
"if",
"self",
".",
"_prompt",
":",
"if",
"timeout_s",
"is",
"None",
":",
"self",
".",
"_cond",
".",
"wait",
"(",
"3600",
"*",
"24",
"*",
"365",
")",
"else",
":",
"self",
".",
"_cond",
".",
"wait",
"(",
"timeout_s",
")",
"if",
"self",
".",
"_response",
"is",
"None",
":",
"raise",
"PromptUnansweredError",
"return",
"self",
".",
"_response"
] | Wait for the user to respond to the current prompt.
Args:
timeout_s: Seconds to wait before raising a PromptUnansweredError.
Returns:
A string response, or the empty string if text_input was False.
Raises:
PromptUnansweredError: Timed out waiting for the user to respond. | [
"Wait",
"for",
"the",
"user",
"to",
"respond",
"to",
"the",
"current",
"prompt",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/user_input.py#L218-L238 |
227,047 | google/openhtf | openhtf/plugs/user_input.py | UserInput.respond | def respond(self, prompt_id, response):
"""Respond to the prompt with the given ID.
If there is no active prompt or the given ID doesn't match the active
prompt, do nothing.
Args:
prompt_id: A string uniquely identifying the prompt.
response: A string response to the given prompt.
Returns:
True if the prompt with the given ID was active, otherwise False.
"""
_LOG.debug('Responding to prompt (%s): "%s"', prompt_id, response)
with self._cond:
if not (self._prompt and self._prompt.id == prompt_id):
return False
self._response = response
self.last_response = (prompt_id, response)
self.remove_prompt()
self._cond.notifyAll()
return True | python | def respond(self, prompt_id, response):
"""Respond to the prompt with the given ID.
If there is no active prompt or the given ID doesn't match the active
prompt, do nothing.
Args:
prompt_id: A string uniquely identifying the prompt.
response: A string response to the given prompt.
Returns:
True if the prompt with the given ID was active, otherwise False.
"""
_LOG.debug('Responding to prompt (%s): "%s"', prompt_id, response)
with self._cond:
if not (self._prompt and self._prompt.id == prompt_id):
return False
self._response = response
self.last_response = (prompt_id, response)
self.remove_prompt()
self._cond.notifyAll()
return True | [
"def",
"respond",
"(",
"self",
",",
"prompt_id",
",",
"response",
")",
":",
"_LOG",
".",
"debug",
"(",
"'Responding to prompt (%s): \"%s\"'",
",",
"prompt_id",
",",
"response",
")",
"with",
"self",
".",
"_cond",
":",
"if",
"not",
"(",
"self",
".",
"_prompt",
"and",
"self",
".",
"_prompt",
".",
"id",
"==",
"prompt_id",
")",
":",
"return",
"False",
"self",
".",
"_response",
"=",
"response",
"self",
".",
"last_response",
"=",
"(",
"prompt_id",
",",
"response",
")",
"self",
".",
"remove_prompt",
"(",
")",
"self",
".",
"_cond",
".",
"notifyAll",
"(",
")",
"return",
"True"
] | Respond to the prompt with the given ID.
If there is no active prompt or the given ID doesn't match the active
prompt, do nothing.
Args:
prompt_id: A string uniquely identifying the prompt.
response: A string response to the given prompt.
Returns:
True if the prompt with the given ID was active, otherwise False. | [
"Respond",
"to",
"the",
"prompt",
"with",
"the",
"given",
"ID",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/user_input.py#L240-L261 |
227,048 | google/openhtf | openhtf/core/phase_executor.py | PhaseExecutionOutcome.is_terminal | def is_terminal(self):
"""True if this result will stop the test."""
return (self.raised_exception or self.is_timeout or
self.phase_result == openhtf.PhaseResult.STOP) | python | def is_terminal(self):
"""True if this result will stop the test."""
return (self.raised_exception or self.is_timeout or
self.phase_result == openhtf.PhaseResult.STOP) | [
"def",
"is_terminal",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"raised_exception",
"or",
"self",
".",
"is_timeout",
"or",
"self",
".",
"phase_result",
"==",
"openhtf",
".",
"PhaseResult",
".",
"STOP",
")"
] | True if this result will stop the test. | [
"True",
"if",
"this",
"result",
"will",
"stop",
"the",
"test",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_executor.py#L119-L122 |
227,049 | google/openhtf | openhtf/core/phase_executor.py | PhaseExecutorThread._thread_proc | def _thread_proc(self):
"""Execute the encompassed phase and save the result."""
# Call the phase, save the return value, or default it to CONTINUE.
phase_return = self._phase_desc(self._test_state)
if phase_return is None:
phase_return = openhtf.PhaseResult.CONTINUE
# If phase_return is invalid, this will raise, and _phase_execution_outcome
# will get set to the InvalidPhaseResultError in _thread_exception instead.
self._phase_execution_outcome = PhaseExecutionOutcome(phase_return) | python | def _thread_proc(self):
"""Execute the encompassed phase and save the result."""
# Call the phase, save the return value, or default it to CONTINUE.
phase_return = self._phase_desc(self._test_state)
if phase_return is None:
phase_return = openhtf.PhaseResult.CONTINUE
# If phase_return is invalid, this will raise, and _phase_execution_outcome
# will get set to the InvalidPhaseResultError in _thread_exception instead.
self._phase_execution_outcome = PhaseExecutionOutcome(phase_return) | [
"def",
"_thread_proc",
"(",
"self",
")",
":",
"# Call the phase, save the return value, or default it to CONTINUE.",
"phase_return",
"=",
"self",
".",
"_phase_desc",
"(",
"self",
".",
"_test_state",
")",
"if",
"phase_return",
"is",
"None",
":",
"phase_return",
"=",
"openhtf",
".",
"PhaseResult",
".",
"CONTINUE",
"# If phase_return is invalid, this will raise, and _phase_execution_outcome",
"# will get set to the InvalidPhaseResultError in _thread_exception instead.",
"self",
".",
"_phase_execution_outcome",
"=",
"PhaseExecutionOutcome",
"(",
"phase_return",
")"
] | Execute the encompassed phase and save the result. | [
"Execute",
"the",
"encompassed",
"phase",
"and",
"save",
"the",
"result",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_executor.py#L152-L161 |
227,050 | google/openhtf | openhtf/core/phase_executor.py | PhaseExecutorThread.join_or_die | def join_or_die(self):
"""Wait for thread to finish, returning a PhaseExecutionOutcome instance."""
if self._phase_desc.options.timeout_s is not None:
self.join(self._phase_desc.options.timeout_s)
else:
self.join(DEFAULT_PHASE_TIMEOUT_S)
# We got a return value or an exception and handled it.
if isinstance(self._phase_execution_outcome, PhaseExecutionOutcome):
return self._phase_execution_outcome
# Check for timeout, indicated by None for
# PhaseExecutionOutcome.phase_result.
if self.is_alive():
self.kill()
return PhaseExecutionOutcome(None)
# Phase was killed.
return PhaseExecutionOutcome(threads.ThreadTerminationError()) | python | def join_or_die(self):
"""Wait for thread to finish, returning a PhaseExecutionOutcome instance."""
if self._phase_desc.options.timeout_s is not None:
self.join(self._phase_desc.options.timeout_s)
else:
self.join(DEFAULT_PHASE_TIMEOUT_S)
# We got a return value or an exception and handled it.
if isinstance(self._phase_execution_outcome, PhaseExecutionOutcome):
return self._phase_execution_outcome
# Check for timeout, indicated by None for
# PhaseExecutionOutcome.phase_result.
if self.is_alive():
self.kill()
return PhaseExecutionOutcome(None)
# Phase was killed.
return PhaseExecutionOutcome(threads.ThreadTerminationError()) | [
"def",
"join_or_die",
"(",
"self",
")",
":",
"if",
"self",
".",
"_phase_desc",
".",
"options",
".",
"timeout_s",
"is",
"not",
"None",
":",
"self",
".",
"join",
"(",
"self",
".",
"_phase_desc",
".",
"options",
".",
"timeout_s",
")",
"else",
":",
"self",
".",
"join",
"(",
"DEFAULT_PHASE_TIMEOUT_S",
")",
"# We got a return value or an exception and handled it.",
"if",
"isinstance",
"(",
"self",
".",
"_phase_execution_outcome",
",",
"PhaseExecutionOutcome",
")",
":",
"return",
"self",
".",
"_phase_execution_outcome",
"# Check for timeout, indicated by None for",
"# PhaseExecutionOutcome.phase_result.",
"if",
"self",
".",
"is_alive",
"(",
")",
":",
"self",
".",
"kill",
"(",
")",
"return",
"PhaseExecutionOutcome",
"(",
"None",
")",
"# Phase was killed.",
"return",
"PhaseExecutionOutcome",
"(",
"threads",
".",
"ThreadTerminationError",
"(",
")",
")"
] | Wait for thread to finish, returning a PhaseExecutionOutcome instance. | [
"Wait",
"for",
"thread",
"to",
"finish",
"returning",
"a",
"PhaseExecutionOutcome",
"instance",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_executor.py#L172-L190 |
227,051 | google/openhtf | openhtf/core/phase_executor.py | PhaseExecutor.execute_phase | def execute_phase(self, phase):
"""Executes a phase or skips it, yielding PhaseExecutionOutcome instances.
Args:
phase: Phase to execute.
Returns:
The final PhaseExecutionOutcome that wraps the phase return value
(or exception) of the final phase run. All intermediary results, if any,
are REPEAT and handled internally. Returning REPEAT here means the phase
hit its limit for repetitions.
"""
repeat_count = 1
repeat_limit = phase.options.repeat_limit or sys.maxsize
while not self._stopping.is_set():
is_last_repeat = repeat_count >= repeat_limit
phase_execution_outcome = self._execute_phase_once(phase, is_last_repeat)
if phase_execution_outcome.is_repeat and not is_last_repeat:
repeat_count += 1
continue
return phase_execution_outcome
# We've been cancelled, so just 'timeout' the phase.
return PhaseExecutionOutcome(None) | python | def execute_phase(self, phase):
"""Executes a phase or skips it, yielding PhaseExecutionOutcome instances.
Args:
phase: Phase to execute.
Returns:
The final PhaseExecutionOutcome that wraps the phase return value
(or exception) of the final phase run. All intermediary results, if any,
are REPEAT and handled internally. Returning REPEAT here means the phase
hit its limit for repetitions.
"""
repeat_count = 1
repeat_limit = phase.options.repeat_limit or sys.maxsize
while not self._stopping.is_set():
is_last_repeat = repeat_count >= repeat_limit
phase_execution_outcome = self._execute_phase_once(phase, is_last_repeat)
if phase_execution_outcome.is_repeat and not is_last_repeat:
repeat_count += 1
continue
return phase_execution_outcome
# We've been cancelled, so just 'timeout' the phase.
return PhaseExecutionOutcome(None) | [
"def",
"execute_phase",
"(",
"self",
",",
"phase",
")",
":",
"repeat_count",
"=",
"1",
"repeat_limit",
"=",
"phase",
".",
"options",
".",
"repeat_limit",
"or",
"sys",
".",
"maxsize",
"while",
"not",
"self",
".",
"_stopping",
".",
"is_set",
"(",
")",
":",
"is_last_repeat",
"=",
"repeat_count",
">=",
"repeat_limit",
"phase_execution_outcome",
"=",
"self",
".",
"_execute_phase_once",
"(",
"phase",
",",
"is_last_repeat",
")",
"if",
"phase_execution_outcome",
".",
"is_repeat",
"and",
"not",
"is_last_repeat",
":",
"repeat_count",
"+=",
"1",
"continue",
"return",
"phase_execution_outcome",
"# We've been cancelled, so just 'timeout' the phase.",
"return",
"PhaseExecutionOutcome",
"(",
"None",
")"
] | Executes a phase or skips it, yielding PhaseExecutionOutcome instances.
Args:
phase: Phase to execute.
Returns:
The final PhaseExecutionOutcome that wraps the phase return value
(or exception) of the final phase run. All intermediary results, if any,
are REPEAT and handled internally. Returning REPEAT here means the phase
hit its limit for repetitions. | [
"Executes",
"a",
"phase",
"or",
"skips",
"it",
"yielding",
"PhaseExecutionOutcome",
"instances",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_executor.py#L211-L235 |
227,052 | google/openhtf | openhtf/core/phase_executor.py | PhaseExecutor._execute_phase_once | def _execute_phase_once(self, phase_desc, is_last_repeat):
"""Executes the given phase, returning a PhaseExecutionOutcome."""
# Check this before we create a PhaseState and PhaseRecord.
if phase_desc.options.run_if and not phase_desc.options.run_if():
_LOG.debug('Phase %s skipped due to run_if returning falsey.',
phase_desc.name)
return PhaseExecutionOutcome(openhtf.PhaseResult.SKIP)
override_result = None
with self.test_state.running_phase_context(phase_desc) as phase_state:
_LOG.debug('Executing phase %s', phase_desc.name)
with self._current_phase_thread_lock:
# Checking _stopping must be in the lock context, otherwise there is a
# race condition: this thread checks _stopping and then switches to
# another thread where stop() sets _stopping and checks
# _current_phase_thread (which would not be set yet). In that case, the
# new phase thread will be still be started.
if self._stopping.is_set():
# PhaseRecord will be written at this point, so ensure that it has a
# Killed result.
result = PhaseExecutionOutcome(threads.ThreadTerminationError())
phase_state.result = result
return result
phase_thread = PhaseExecutorThread(phase_desc, self.test_state)
phase_thread.start()
self._current_phase_thread = phase_thread
phase_state.result = phase_thread.join_or_die()
if phase_state.result.is_repeat and is_last_repeat:
_LOG.error('Phase returned REPEAT, exceeding repeat_limit.')
phase_state.hit_repeat_limit = True
override_result = PhaseExecutionOutcome(openhtf.PhaseResult.STOP)
self._current_phase_thread = None
# Refresh the result in case a validation for a partially set measurement
# raised an exception.
result = override_result or phase_state.result
_LOG.debug('Phase %s finished with result %s', phase_desc.name,
result.phase_result)
return result | python | def _execute_phase_once(self, phase_desc, is_last_repeat):
"""Executes the given phase, returning a PhaseExecutionOutcome."""
# Check this before we create a PhaseState and PhaseRecord.
if phase_desc.options.run_if and not phase_desc.options.run_if():
_LOG.debug('Phase %s skipped due to run_if returning falsey.',
phase_desc.name)
return PhaseExecutionOutcome(openhtf.PhaseResult.SKIP)
override_result = None
with self.test_state.running_phase_context(phase_desc) as phase_state:
_LOG.debug('Executing phase %s', phase_desc.name)
with self._current_phase_thread_lock:
# Checking _stopping must be in the lock context, otherwise there is a
# race condition: this thread checks _stopping and then switches to
# another thread where stop() sets _stopping and checks
# _current_phase_thread (which would not be set yet). In that case, the
# new phase thread will be still be started.
if self._stopping.is_set():
# PhaseRecord will be written at this point, so ensure that it has a
# Killed result.
result = PhaseExecutionOutcome(threads.ThreadTerminationError())
phase_state.result = result
return result
phase_thread = PhaseExecutorThread(phase_desc, self.test_state)
phase_thread.start()
self._current_phase_thread = phase_thread
phase_state.result = phase_thread.join_or_die()
if phase_state.result.is_repeat and is_last_repeat:
_LOG.error('Phase returned REPEAT, exceeding repeat_limit.')
phase_state.hit_repeat_limit = True
override_result = PhaseExecutionOutcome(openhtf.PhaseResult.STOP)
self._current_phase_thread = None
# Refresh the result in case a validation for a partially set measurement
# raised an exception.
result = override_result or phase_state.result
_LOG.debug('Phase %s finished with result %s', phase_desc.name,
result.phase_result)
return result | [
"def",
"_execute_phase_once",
"(",
"self",
",",
"phase_desc",
",",
"is_last_repeat",
")",
":",
"# Check this before we create a PhaseState and PhaseRecord.",
"if",
"phase_desc",
".",
"options",
".",
"run_if",
"and",
"not",
"phase_desc",
".",
"options",
".",
"run_if",
"(",
")",
":",
"_LOG",
".",
"debug",
"(",
"'Phase %s skipped due to run_if returning falsey.'",
",",
"phase_desc",
".",
"name",
")",
"return",
"PhaseExecutionOutcome",
"(",
"openhtf",
".",
"PhaseResult",
".",
"SKIP",
")",
"override_result",
"=",
"None",
"with",
"self",
".",
"test_state",
".",
"running_phase_context",
"(",
"phase_desc",
")",
"as",
"phase_state",
":",
"_LOG",
".",
"debug",
"(",
"'Executing phase %s'",
",",
"phase_desc",
".",
"name",
")",
"with",
"self",
".",
"_current_phase_thread_lock",
":",
"# Checking _stopping must be in the lock context, otherwise there is a",
"# race condition: this thread checks _stopping and then switches to",
"# another thread where stop() sets _stopping and checks",
"# _current_phase_thread (which would not be set yet). In that case, the",
"# new phase thread will be still be started.",
"if",
"self",
".",
"_stopping",
".",
"is_set",
"(",
")",
":",
"# PhaseRecord will be written at this point, so ensure that it has a",
"# Killed result.",
"result",
"=",
"PhaseExecutionOutcome",
"(",
"threads",
".",
"ThreadTerminationError",
"(",
")",
")",
"phase_state",
".",
"result",
"=",
"result",
"return",
"result",
"phase_thread",
"=",
"PhaseExecutorThread",
"(",
"phase_desc",
",",
"self",
".",
"test_state",
")",
"phase_thread",
".",
"start",
"(",
")",
"self",
".",
"_current_phase_thread",
"=",
"phase_thread",
"phase_state",
".",
"result",
"=",
"phase_thread",
".",
"join_or_die",
"(",
")",
"if",
"phase_state",
".",
"result",
".",
"is_repeat",
"and",
"is_last_repeat",
":",
"_LOG",
".",
"error",
"(",
"'Phase returned REPEAT, exceeding repeat_limit.'",
")",
"phase_state",
".",
"hit_repeat_limit",
"=",
"True",
"override_result",
"=",
"PhaseExecutionOutcome",
"(",
"openhtf",
".",
"PhaseResult",
".",
"STOP",
")",
"self",
".",
"_current_phase_thread",
"=",
"None",
"# Refresh the result in case a validation for a partially set measurement",
"# raised an exception.",
"result",
"=",
"override_result",
"or",
"phase_state",
".",
"result",
"_LOG",
".",
"debug",
"(",
"'Phase %s finished with result %s'",
",",
"phase_desc",
".",
"name",
",",
"result",
".",
"phase_result",
")",
"return",
"result"
] | Executes the given phase, returning a PhaseExecutionOutcome. | [
"Executes",
"the",
"given",
"phase",
"returning",
"a",
"PhaseExecutionOutcome",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_executor.py#L237-L276 |
227,053 | google/openhtf | openhtf/core/phase_executor.py | PhaseExecutor.stop | def stop(self, timeout_s=None):
"""Stops execution of the current phase, if any.
It will raise a ThreadTerminationError, which will cause the test to stop
executing and terminate with an ERROR state.
Args:
timeout_s: int or None, timeout in seconds to wait for the phase to stop.
"""
self._stopping.set()
with self._current_phase_thread_lock:
phase_thread = self._current_phase_thread
if not phase_thread:
return
if phase_thread.is_alive():
phase_thread.kill()
_LOG.debug('Waiting for cancelled phase to exit: %s', phase_thread)
timeout = timeouts.PolledTimeout.from_seconds(timeout_s)
while phase_thread.is_alive() and not timeout.has_expired():
time.sleep(0.1)
_LOG.debug('Cancelled phase %s exit',
"didn't" if phase_thread.is_alive() else 'did')
# Clear the currently running phase, whether it finished or timed out.
self.test_state.stop_running_phase() | python | def stop(self, timeout_s=None):
"""Stops execution of the current phase, if any.
It will raise a ThreadTerminationError, which will cause the test to stop
executing and terminate with an ERROR state.
Args:
timeout_s: int or None, timeout in seconds to wait for the phase to stop.
"""
self._stopping.set()
with self._current_phase_thread_lock:
phase_thread = self._current_phase_thread
if not phase_thread:
return
if phase_thread.is_alive():
phase_thread.kill()
_LOG.debug('Waiting for cancelled phase to exit: %s', phase_thread)
timeout = timeouts.PolledTimeout.from_seconds(timeout_s)
while phase_thread.is_alive() and not timeout.has_expired():
time.sleep(0.1)
_LOG.debug('Cancelled phase %s exit',
"didn't" if phase_thread.is_alive() else 'did')
# Clear the currently running phase, whether it finished or timed out.
self.test_state.stop_running_phase() | [
"def",
"stop",
"(",
"self",
",",
"timeout_s",
"=",
"None",
")",
":",
"self",
".",
"_stopping",
".",
"set",
"(",
")",
"with",
"self",
".",
"_current_phase_thread_lock",
":",
"phase_thread",
"=",
"self",
".",
"_current_phase_thread",
"if",
"not",
"phase_thread",
":",
"return",
"if",
"phase_thread",
".",
"is_alive",
"(",
")",
":",
"phase_thread",
".",
"kill",
"(",
")",
"_LOG",
".",
"debug",
"(",
"'Waiting for cancelled phase to exit: %s'",
",",
"phase_thread",
")",
"timeout",
"=",
"timeouts",
".",
"PolledTimeout",
".",
"from_seconds",
"(",
"timeout_s",
")",
"while",
"phase_thread",
".",
"is_alive",
"(",
")",
"and",
"not",
"timeout",
".",
"has_expired",
"(",
")",
":",
"time",
".",
"sleep",
"(",
"0.1",
")",
"_LOG",
".",
"debug",
"(",
"'Cancelled phase %s exit'",
",",
"\"didn't\"",
"if",
"phase_thread",
".",
"is_alive",
"(",
")",
"else",
"'did'",
")",
"# Clear the currently running phase, whether it finished or timed out.",
"self",
".",
"test_state",
".",
"stop_running_phase",
"(",
")"
] | Stops execution of the current phase, if any.
It will raise a ThreadTerminationError, which will cause the test to stop
executing and terminate with an ERROR state.
Args:
timeout_s: int or None, timeout in seconds to wait for the phase to stop. | [
"Stops",
"execution",
"of",
"the",
"current",
"phase",
"if",
"any",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_executor.py#L281-L306 |
227,054 | google/openhtf | openhtf/core/phase_group.py | load_code_info | def load_code_info(phases_or_groups):
"""Recursively load code info for a PhaseGroup or list of phases or groups."""
if isinstance(phases_or_groups, PhaseGroup):
return phases_or_groups.load_code_info()
ret = []
for phase in phases_or_groups:
if isinstance(phase, PhaseGroup):
ret.append(phase.load_code_info())
else:
ret.append(
mutablerecords.CopyRecord(
phase, code_info=test_record.CodeInfo.for_function(phase.func)))
return ret | python | def load_code_info(phases_or_groups):
"""Recursively load code info for a PhaseGroup or list of phases or groups."""
if isinstance(phases_or_groups, PhaseGroup):
return phases_or_groups.load_code_info()
ret = []
for phase in phases_or_groups:
if isinstance(phase, PhaseGroup):
ret.append(phase.load_code_info())
else:
ret.append(
mutablerecords.CopyRecord(
phase, code_info=test_record.CodeInfo.for_function(phase.func)))
return ret | [
"def",
"load_code_info",
"(",
"phases_or_groups",
")",
":",
"if",
"isinstance",
"(",
"phases_or_groups",
",",
"PhaseGroup",
")",
":",
"return",
"phases_or_groups",
".",
"load_code_info",
"(",
")",
"ret",
"=",
"[",
"]",
"for",
"phase",
"in",
"phases_or_groups",
":",
"if",
"isinstance",
"(",
"phase",
",",
"PhaseGroup",
")",
":",
"ret",
".",
"append",
"(",
"phase",
".",
"load_code_info",
"(",
")",
")",
"else",
":",
"ret",
".",
"append",
"(",
"mutablerecords",
".",
"CopyRecord",
"(",
"phase",
",",
"code_info",
"=",
"test_record",
".",
"CodeInfo",
".",
"for_function",
"(",
"phase",
".",
"func",
")",
")",
")",
"return",
"ret"
] | Recursively load code info for a PhaseGroup or list of phases or groups. | [
"Recursively",
"load",
"code",
"info",
"for",
"a",
"PhaseGroup",
"or",
"list",
"of",
"phases",
"or",
"groups",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_group.py#L192-L204 |
227,055 | google/openhtf | openhtf/core/phase_group.py | flatten_phases_and_groups | def flatten_phases_and_groups(phases_or_groups):
"""Recursively flatten nested lists for the list of phases or groups."""
if isinstance(phases_or_groups, PhaseGroup):
phases_or_groups = [phases_or_groups]
ret = []
for phase in phases_or_groups:
if isinstance(phase, PhaseGroup):
ret.append(phase.flatten())
elif isinstance(phase, collections.Iterable):
ret.extend(flatten_phases_and_groups(phase))
else:
ret.append(phase_descriptor.PhaseDescriptor.wrap_or_copy(phase))
return ret | python | def flatten_phases_and_groups(phases_or_groups):
"""Recursively flatten nested lists for the list of phases or groups."""
if isinstance(phases_or_groups, PhaseGroup):
phases_or_groups = [phases_or_groups]
ret = []
for phase in phases_or_groups:
if isinstance(phase, PhaseGroup):
ret.append(phase.flatten())
elif isinstance(phase, collections.Iterable):
ret.extend(flatten_phases_and_groups(phase))
else:
ret.append(phase_descriptor.PhaseDescriptor.wrap_or_copy(phase))
return ret | [
"def",
"flatten_phases_and_groups",
"(",
"phases_or_groups",
")",
":",
"if",
"isinstance",
"(",
"phases_or_groups",
",",
"PhaseGroup",
")",
":",
"phases_or_groups",
"=",
"[",
"phases_or_groups",
"]",
"ret",
"=",
"[",
"]",
"for",
"phase",
"in",
"phases_or_groups",
":",
"if",
"isinstance",
"(",
"phase",
",",
"PhaseGroup",
")",
":",
"ret",
".",
"append",
"(",
"phase",
".",
"flatten",
"(",
")",
")",
"elif",
"isinstance",
"(",
"phase",
",",
"collections",
".",
"Iterable",
")",
":",
"ret",
".",
"extend",
"(",
"flatten_phases_and_groups",
"(",
"phase",
")",
")",
"else",
":",
"ret",
".",
"append",
"(",
"phase_descriptor",
".",
"PhaseDescriptor",
".",
"wrap_or_copy",
"(",
"phase",
")",
")",
"return",
"ret"
] | Recursively flatten nested lists for the list of phases or groups. | [
"Recursively",
"flatten",
"nested",
"lists",
"for",
"the",
"list",
"of",
"phases",
"or",
"groups",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_group.py#L207-L219 |
227,056 | google/openhtf | openhtf/core/phase_group.py | optionally_with_args | def optionally_with_args(phase, **kwargs):
"""Apply only the args that the phase knows.
If the phase has a **kwargs-style argument, it counts as knowing all args.
Args:
phase: phase_descriptor.PhaseDescriptor or PhaseGroup or callable, or
iterable of those, the phase or phase group (or iterable) to apply
with_args to.
**kwargs: arguments to apply to the phase.
Returns:
phase_descriptor.PhaseDescriptor or PhaseGroup or iterable with the updated
args.
"""
if isinstance(phase, PhaseGroup):
return phase.with_args(**kwargs)
if isinstance(phase, collections.Iterable):
return [optionally_with_args(p, **kwargs) for p in phase]
if not isinstance(phase, phase_descriptor.PhaseDescriptor):
phase = phase_descriptor.PhaseDescriptor.wrap_or_copy(phase)
return phase.with_known_args(**kwargs) | python | def optionally_with_args(phase, **kwargs):
"""Apply only the args that the phase knows.
If the phase has a **kwargs-style argument, it counts as knowing all args.
Args:
phase: phase_descriptor.PhaseDescriptor or PhaseGroup or callable, or
iterable of those, the phase or phase group (or iterable) to apply
with_args to.
**kwargs: arguments to apply to the phase.
Returns:
phase_descriptor.PhaseDescriptor or PhaseGroup or iterable with the updated
args.
"""
if isinstance(phase, PhaseGroup):
return phase.with_args(**kwargs)
if isinstance(phase, collections.Iterable):
return [optionally_with_args(p, **kwargs) for p in phase]
if not isinstance(phase, phase_descriptor.PhaseDescriptor):
phase = phase_descriptor.PhaseDescriptor.wrap_or_copy(phase)
return phase.with_known_args(**kwargs) | [
"def",
"optionally_with_args",
"(",
"phase",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"phase",
",",
"PhaseGroup",
")",
":",
"return",
"phase",
".",
"with_args",
"(",
"*",
"*",
"kwargs",
")",
"if",
"isinstance",
"(",
"phase",
",",
"collections",
".",
"Iterable",
")",
":",
"return",
"[",
"optionally_with_args",
"(",
"p",
",",
"*",
"*",
"kwargs",
")",
"for",
"p",
"in",
"phase",
"]",
"if",
"not",
"isinstance",
"(",
"phase",
",",
"phase_descriptor",
".",
"PhaseDescriptor",
")",
":",
"phase",
"=",
"phase_descriptor",
".",
"PhaseDescriptor",
".",
"wrap_or_copy",
"(",
"phase",
")",
"return",
"phase",
".",
"with_known_args",
"(",
"*",
"*",
"kwargs",
")"
] | Apply only the args that the phase knows.
If the phase has a **kwargs-style argument, it counts as knowing all args.
Args:
phase: phase_descriptor.PhaseDescriptor or PhaseGroup or callable, or
iterable of those, the phase or phase group (or iterable) to apply
with_args to.
**kwargs: arguments to apply to the phase.
Returns:
phase_descriptor.PhaseDescriptor or PhaseGroup or iterable with the updated
args. | [
"Apply",
"only",
"the",
"args",
"that",
"the",
"phase",
"knows",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_group.py#L222-L244 |
227,057 | google/openhtf | openhtf/core/phase_group.py | optionally_with_plugs | def optionally_with_plugs(phase, **subplugs):
"""Apply only the with_plugs that the phase knows.
This will determine the subset of plug overrides for only plugs the phase
actually has.
Args:
phase: phase_descriptor.PhaseDescriptor or PhaseGroup or callable, or
iterable of those, the phase or phase group (or iterable) to apply the
plug changes to.
**subplugs: mapping from plug name to derived plug class, the subplugs to
apply.
Raises:
openhtf.plugs.InvalidPlugError: if a specified subplug class is not a valid
replacement for the specified plug name.
Returns:
phase_descriptor.PhaseDescriptor or PhaseGroup or iterable with the updated
plugs.
"""
if isinstance(phase, PhaseGroup):
return phase.with_plugs(**subplugs)
if isinstance(phase, collections.Iterable):
return [optionally_with_plugs(p, **subplugs) for p in phase]
if not isinstance(phase, phase_descriptor.PhaseDescriptor):
phase = phase_descriptor.PhaseDescriptor.wrap_or_copy(phase)
return phase.with_known_plugs(**subplugs) | python | def optionally_with_plugs(phase, **subplugs):
"""Apply only the with_plugs that the phase knows.
This will determine the subset of plug overrides for only plugs the phase
actually has.
Args:
phase: phase_descriptor.PhaseDescriptor or PhaseGroup or callable, or
iterable of those, the phase or phase group (or iterable) to apply the
plug changes to.
**subplugs: mapping from plug name to derived plug class, the subplugs to
apply.
Raises:
openhtf.plugs.InvalidPlugError: if a specified subplug class is not a valid
replacement for the specified plug name.
Returns:
phase_descriptor.PhaseDescriptor or PhaseGroup or iterable with the updated
plugs.
"""
if isinstance(phase, PhaseGroup):
return phase.with_plugs(**subplugs)
if isinstance(phase, collections.Iterable):
return [optionally_with_plugs(p, **subplugs) for p in phase]
if not isinstance(phase, phase_descriptor.PhaseDescriptor):
phase = phase_descriptor.PhaseDescriptor.wrap_or_copy(phase)
return phase.with_known_plugs(**subplugs) | [
"def",
"optionally_with_plugs",
"(",
"phase",
",",
"*",
"*",
"subplugs",
")",
":",
"if",
"isinstance",
"(",
"phase",
",",
"PhaseGroup",
")",
":",
"return",
"phase",
".",
"with_plugs",
"(",
"*",
"*",
"subplugs",
")",
"if",
"isinstance",
"(",
"phase",
",",
"collections",
".",
"Iterable",
")",
":",
"return",
"[",
"optionally_with_plugs",
"(",
"p",
",",
"*",
"*",
"subplugs",
")",
"for",
"p",
"in",
"phase",
"]",
"if",
"not",
"isinstance",
"(",
"phase",
",",
"phase_descriptor",
".",
"PhaseDescriptor",
")",
":",
"phase",
"=",
"phase_descriptor",
".",
"PhaseDescriptor",
".",
"wrap_or_copy",
"(",
"phase",
")",
"return",
"phase",
".",
"with_known_plugs",
"(",
"*",
"*",
"subplugs",
")"
] | Apply only the with_plugs that the phase knows.
This will determine the subset of plug overrides for only plugs the phase
actually has.
Args:
phase: phase_descriptor.PhaseDescriptor or PhaseGroup or callable, or
iterable of those, the phase or phase group (or iterable) to apply the
plug changes to.
**subplugs: mapping from plug name to derived plug class, the subplugs to
apply.
Raises:
openhtf.plugs.InvalidPlugError: if a specified subplug class is not a valid
replacement for the specified plug name.
Returns:
phase_descriptor.PhaseDescriptor or PhaseGroup or iterable with the updated
plugs. | [
"Apply",
"only",
"the",
"with_plugs",
"that",
"the",
"phase",
"knows",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_group.py#L247-L275 |
227,058 | google/openhtf | openhtf/core/phase_group.py | PhaseGroup.convert_if_not | def convert_if_not(cls, phases_or_groups):
"""Convert list of phases or groups into a new PhaseGroup if not already."""
if isinstance(phases_or_groups, PhaseGroup):
return mutablerecords.CopyRecord(phases_or_groups)
flattened = flatten_phases_and_groups(phases_or_groups)
return cls(main=flattened) | python | def convert_if_not(cls, phases_or_groups):
"""Convert list of phases or groups into a new PhaseGroup if not already."""
if isinstance(phases_or_groups, PhaseGroup):
return mutablerecords.CopyRecord(phases_or_groups)
flattened = flatten_phases_and_groups(phases_or_groups)
return cls(main=flattened) | [
"def",
"convert_if_not",
"(",
"cls",
",",
"phases_or_groups",
")",
":",
"if",
"isinstance",
"(",
"phases_or_groups",
",",
"PhaseGroup",
")",
":",
"return",
"mutablerecords",
".",
"CopyRecord",
"(",
"phases_or_groups",
")",
"flattened",
"=",
"flatten_phases_and_groups",
"(",
"phases_or_groups",
")",
"return",
"cls",
"(",
"main",
"=",
"flattened",
")"
] | Convert list of phases or groups into a new PhaseGroup if not already. | [
"Convert",
"list",
"of",
"phases",
"or",
"groups",
"into",
"a",
"new",
"PhaseGroup",
"if",
"not",
"already",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_group.py#L79-L85 |
227,059 | google/openhtf | openhtf/core/phase_group.py | PhaseGroup.with_context | def with_context(cls, setup_phases, teardown_phases):
"""Create PhaseGroup creator function with setup and teardown phases.
Args:
setup_phases: list of phase_descriptor.PhaseDescriptors/PhaseGroups/
callables/iterables, phases to run during the setup for the PhaseGroup
returned from the created function.
teardown_phases: list of phase_descriptor.PhaseDescriptors/PhaseGroups/
callables/iterables, phases to run during the teardown for the
PhaseGroup returned from the created function.
Returns:
Function that takes *phases and returns a PhaseGroup with the predefined
setup and teardown phases, with *phases as the main phases.
"""
setup = flatten_phases_and_groups(setup_phases)
teardown = flatten_phases_and_groups(teardown_phases)
def _context_wrapper(*phases):
return cls(setup=setup,
main=flatten_phases_and_groups(phases),
teardown=teardown)
return _context_wrapper | python | def with_context(cls, setup_phases, teardown_phases):
"""Create PhaseGroup creator function with setup and teardown phases.
Args:
setup_phases: list of phase_descriptor.PhaseDescriptors/PhaseGroups/
callables/iterables, phases to run during the setup for the PhaseGroup
returned from the created function.
teardown_phases: list of phase_descriptor.PhaseDescriptors/PhaseGroups/
callables/iterables, phases to run during the teardown for the
PhaseGroup returned from the created function.
Returns:
Function that takes *phases and returns a PhaseGroup with the predefined
setup and teardown phases, with *phases as the main phases.
"""
setup = flatten_phases_and_groups(setup_phases)
teardown = flatten_phases_and_groups(teardown_phases)
def _context_wrapper(*phases):
return cls(setup=setup,
main=flatten_phases_and_groups(phases),
teardown=teardown)
return _context_wrapper | [
"def",
"with_context",
"(",
"cls",
",",
"setup_phases",
",",
"teardown_phases",
")",
":",
"setup",
"=",
"flatten_phases_and_groups",
"(",
"setup_phases",
")",
"teardown",
"=",
"flatten_phases_and_groups",
"(",
"teardown_phases",
")",
"def",
"_context_wrapper",
"(",
"*",
"phases",
")",
":",
"return",
"cls",
"(",
"setup",
"=",
"setup",
",",
"main",
"=",
"flatten_phases_and_groups",
"(",
"phases",
")",
",",
"teardown",
"=",
"teardown",
")",
"return",
"_context_wrapper"
] | Create PhaseGroup creator function with setup and teardown phases.
Args:
setup_phases: list of phase_descriptor.PhaseDescriptors/PhaseGroups/
callables/iterables, phases to run during the setup for the PhaseGroup
returned from the created function.
teardown_phases: list of phase_descriptor.PhaseDescriptors/PhaseGroups/
callables/iterables, phases to run during the teardown for the
PhaseGroup returned from the created function.
Returns:
Function that takes *phases and returns a PhaseGroup with the predefined
setup and teardown phases, with *phases as the main phases. | [
"Create",
"PhaseGroup",
"creator",
"function",
"with",
"setup",
"and",
"teardown",
"phases",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_group.py#L88-L110 |
227,060 | google/openhtf | openhtf/core/phase_group.py | PhaseGroup.combine | def combine(self, other, name=None):
"""Combine with another PhaseGroup and return the result."""
return PhaseGroup(
setup=self.setup + other.setup,
main=self.main + other.main,
teardown=self.teardown + other.teardown,
name=name) | python | def combine(self, other, name=None):
"""Combine with another PhaseGroup and return the result."""
return PhaseGroup(
setup=self.setup + other.setup,
main=self.main + other.main,
teardown=self.teardown + other.teardown,
name=name) | [
"def",
"combine",
"(",
"self",
",",
"other",
",",
"name",
"=",
"None",
")",
":",
"return",
"PhaseGroup",
"(",
"setup",
"=",
"self",
".",
"setup",
"+",
"other",
".",
"setup",
",",
"main",
"=",
"self",
".",
"main",
"+",
"other",
".",
"main",
",",
"teardown",
"=",
"self",
".",
"teardown",
"+",
"other",
".",
"teardown",
",",
"name",
"=",
"name",
")"
] | Combine with another PhaseGroup and return the result. | [
"Combine",
"with",
"another",
"PhaseGroup",
"and",
"return",
"the",
"result",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_group.py#L122-L128 |
227,061 | google/openhtf | openhtf/core/phase_group.py | PhaseGroup.wrap | def wrap(self, main_phases, name=None):
"""Returns PhaseGroup with additional main phases."""
new_main = list(self.main)
if isinstance(main_phases, collections.Iterable):
new_main.extend(main_phases)
else:
new_main.append(main_phases)
return PhaseGroup(
setup=self.setup,
main=new_main,
teardown=self.teardown,
name=name) | python | def wrap(self, main_phases, name=None):
"""Returns PhaseGroup with additional main phases."""
new_main = list(self.main)
if isinstance(main_phases, collections.Iterable):
new_main.extend(main_phases)
else:
new_main.append(main_phases)
return PhaseGroup(
setup=self.setup,
main=new_main,
teardown=self.teardown,
name=name) | [
"def",
"wrap",
"(",
"self",
",",
"main_phases",
",",
"name",
"=",
"None",
")",
":",
"new_main",
"=",
"list",
"(",
"self",
".",
"main",
")",
"if",
"isinstance",
"(",
"main_phases",
",",
"collections",
".",
"Iterable",
")",
":",
"new_main",
".",
"extend",
"(",
"main_phases",
")",
"else",
":",
"new_main",
".",
"append",
"(",
"main_phases",
")",
"return",
"PhaseGroup",
"(",
"setup",
"=",
"self",
".",
"setup",
",",
"main",
"=",
"new_main",
",",
"teardown",
"=",
"self",
".",
"teardown",
",",
"name",
"=",
"name",
")"
] | Returns PhaseGroup with additional main phases. | [
"Returns",
"PhaseGroup",
"with",
"additional",
"main",
"phases",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_group.py#L130-L141 |
227,062 | google/openhtf | openhtf/core/phase_group.py | PhaseGroup.flatten | def flatten(self):
"""Internally flatten out nested iterables."""
return PhaseGroup(
setup=flatten_phases_and_groups(self.setup),
main=flatten_phases_and_groups(self.main),
teardown=flatten_phases_and_groups(self.teardown),
name=self.name) | python | def flatten(self):
"""Internally flatten out nested iterables."""
return PhaseGroup(
setup=flatten_phases_and_groups(self.setup),
main=flatten_phases_and_groups(self.main),
teardown=flatten_phases_and_groups(self.teardown),
name=self.name) | [
"def",
"flatten",
"(",
"self",
")",
":",
"return",
"PhaseGroup",
"(",
"setup",
"=",
"flatten_phases_and_groups",
"(",
"self",
".",
"setup",
")",
",",
"main",
"=",
"flatten_phases_and_groups",
"(",
"self",
".",
"main",
")",
",",
"teardown",
"=",
"flatten_phases_and_groups",
"(",
"self",
".",
"teardown",
")",
",",
"name",
"=",
"self",
".",
"name",
")"
] | Internally flatten out nested iterables. | [
"Internally",
"flatten",
"out",
"nested",
"iterables",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_group.py#L175-L181 |
227,063 | google/openhtf | openhtf/core/phase_group.py | PhaseGroup.load_code_info | def load_code_info(self):
"""Load coded info for all contained phases."""
return PhaseGroup(
setup=load_code_info(self.setup),
main=load_code_info(self.main),
teardown=load_code_info(self.teardown),
name=self.name) | python | def load_code_info(self):
"""Load coded info for all contained phases."""
return PhaseGroup(
setup=load_code_info(self.setup),
main=load_code_info(self.main),
teardown=load_code_info(self.teardown),
name=self.name) | [
"def",
"load_code_info",
"(",
"self",
")",
":",
"return",
"PhaseGroup",
"(",
"setup",
"=",
"load_code_info",
"(",
"self",
".",
"setup",
")",
",",
"main",
"=",
"load_code_info",
"(",
"self",
".",
"main",
")",
",",
"teardown",
"=",
"load_code_info",
"(",
"self",
".",
"teardown",
")",
",",
"name",
"=",
"self",
".",
"name",
")"
] | Load coded info for all contained phases. | [
"Load",
"coded",
"info",
"for",
"all",
"contained",
"phases",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_group.py#L183-L189 |
227,064 | google/openhtf | openhtf/output/servers/pub_sub.py | PubSub.publish | def publish(cls, message, client_filter=None):
"""Publish messages to subscribers.
Args:
message: The message to publish.
client_filter: A filter function to call passing in each client. Only
clients for whom the function returns True will have the
message sent to them.
"""
with cls._lock:
for client in cls.subscribers:
if (not client_filter) or client_filter(client):
client.send(message) | python | def publish(cls, message, client_filter=None):
"""Publish messages to subscribers.
Args:
message: The message to publish.
client_filter: A filter function to call passing in each client. Only
clients for whom the function returns True will have the
message sent to them.
"""
with cls._lock:
for client in cls.subscribers:
if (not client_filter) or client_filter(client):
client.send(message) | [
"def",
"publish",
"(",
"cls",
",",
"message",
",",
"client_filter",
"=",
"None",
")",
":",
"with",
"cls",
".",
"_lock",
":",
"for",
"client",
"in",
"cls",
".",
"subscribers",
":",
"if",
"(",
"not",
"client_filter",
")",
"or",
"client_filter",
"(",
"client",
")",
":",
"client",
".",
"send",
"(",
"message",
")"
] | Publish messages to subscribers.
Args:
message: The message to publish.
client_filter: A filter function to call passing in each client. Only
clients for whom the function returns True will have the
message sent to them. | [
"Publish",
"messages",
"to",
"subscribers",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/output/servers/pub_sub.py#L43-L55 |
227,065 | google/openhtf | examples/repeat.py | FailTwicePlug.run | def run(self):
"""Increments counter and raises an exception for first two runs."""
self.count += 1
print('FailTwicePlug: Run number %s' % (self.count))
if self.count < 3:
raise RuntimeError('Fails a couple times')
return True | python | def run(self):
"""Increments counter and raises an exception for first two runs."""
self.count += 1
print('FailTwicePlug: Run number %s' % (self.count))
if self.count < 3:
raise RuntimeError('Fails a couple times')
return True | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"count",
"+=",
"1",
"print",
"(",
"'FailTwicePlug: Run number %s'",
"%",
"(",
"self",
".",
"count",
")",
")",
"if",
"self",
".",
"count",
"<",
"3",
":",
"raise",
"RuntimeError",
"(",
"'Fails a couple times'",
")",
"return",
"True"
] | Increments counter and raises an exception for first two runs. | [
"Increments",
"counter",
"and",
"raises",
"an",
"exception",
"for",
"first",
"two",
"runs",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/examples/repeat.py#L41-L48 |
227,066 | google/openhtf | openhtf/core/phase_descriptor.py | PhaseOptions.format_strings | def format_strings(self, **kwargs):
"""String substitution of name."""
return mutablerecords.CopyRecord(
self, name=util.format_string(self.name, kwargs)) | python | def format_strings(self, **kwargs):
"""String substitution of name."""
return mutablerecords.CopyRecord(
self, name=util.format_string(self.name, kwargs)) | [
"def",
"format_strings",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"mutablerecords",
".",
"CopyRecord",
"(",
"self",
",",
"name",
"=",
"util",
".",
"format_string",
"(",
"self",
".",
"name",
",",
"kwargs",
")",
")"
] | String substitution of name. | [
"String",
"substitution",
"of",
"name",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_descriptor.py#L96-L99 |
227,067 | google/openhtf | openhtf/core/phase_descriptor.py | PhaseDescriptor.wrap_or_copy | def wrap_or_copy(cls, func, **options):
"""Return a new PhaseDescriptor from the given function or instance.
We want to return a new copy so that you can reuse a phase with different
options, plugs, measurements, etc.
Args:
func: A phase function or PhaseDescriptor instance.
**options: Options to update on the result.
Raises:
PhaseWrapError: if func is a openhtf.PhaseGroup.
Returns:
A new PhaseDescriptor object.
"""
if isinstance(func, openhtf.PhaseGroup):
raise PhaseWrapError('Cannot wrap PhaseGroup <%s> as a phase.' % (
func.name or 'Unnamed'))
if isinstance(func, cls):
# We want to copy so that a phase can be reused with different options
# or kwargs. See with_args() below for more details.
retval = mutablerecords.CopyRecord(func)
else:
retval = cls(func)
retval.options.update(**options)
return retval | python | def wrap_or_copy(cls, func, **options):
"""Return a new PhaseDescriptor from the given function or instance.
We want to return a new copy so that you can reuse a phase with different
options, plugs, measurements, etc.
Args:
func: A phase function or PhaseDescriptor instance.
**options: Options to update on the result.
Raises:
PhaseWrapError: if func is a openhtf.PhaseGroup.
Returns:
A new PhaseDescriptor object.
"""
if isinstance(func, openhtf.PhaseGroup):
raise PhaseWrapError('Cannot wrap PhaseGroup <%s> as a phase.' % (
func.name or 'Unnamed'))
if isinstance(func, cls):
# We want to copy so that a phase can be reused with different options
# or kwargs. See with_args() below for more details.
retval = mutablerecords.CopyRecord(func)
else:
retval = cls(func)
retval.options.update(**options)
return retval | [
"def",
"wrap_or_copy",
"(",
"cls",
",",
"func",
",",
"*",
"*",
"options",
")",
":",
"if",
"isinstance",
"(",
"func",
",",
"openhtf",
".",
"PhaseGroup",
")",
":",
"raise",
"PhaseWrapError",
"(",
"'Cannot wrap PhaseGroup <%s> as a phase.'",
"%",
"(",
"func",
".",
"name",
"or",
"'Unnamed'",
")",
")",
"if",
"isinstance",
"(",
"func",
",",
"cls",
")",
":",
"# We want to copy so that a phase can be reused with different options",
"# or kwargs. See with_args() below for more details.",
"retval",
"=",
"mutablerecords",
".",
"CopyRecord",
"(",
"func",
")",
"else",
":",
"retval",
"=",
"cls",
"(",
"func",
")",
"retval",
".",
"options",
".",
"update",
"(",
"*",
"*",
"options",
")",
"return",
"retval"
] | Return a new PhaseDescriptor from the given function or instance.
We want to return a new copy so that you can reuse a phase with different
options, plugs, measurements, etc.
Args:
func: A phase function or PhaseDescriptor instance.
**options: Options to update on the result.
Raises:
PhaseWrapError: if func is a openhtf.PhaseGroup.
Returns:
A new PhaseDescriptor object. | [
"Return",
"a",
"new",
"PhaseDescriptor",
"from",
"the",
"given",
"function",
"or",
"instance",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_descriptor.py#L135-L161 |
227,068 | google/openhtf | openhtf/core/phase_descriptor.py | PhaseDescriptor.with_known_args | def with_known_args(self, **kwargs):
"""Send only known keyword-arguments to the phase when called."""
argspec = inspect.getargspec(self.func)
stored = {}
for key, arg in six.iteritems(kwargs):
if key in argspec.args or argspec.keywords:
stored[key] = arg
if stored:
return self.with_args(**stored)
return self | python | def with_known_args(self, **kwargs):
"""Send only known keyword-arguments to the phase when called."""
argspec = inspect.getargspec(self.func)
stored = {}
for key, arg in six.iteritems(kwargs):
if key in argspec.args or argspec.keywords:
stored[key] = arg
if stored:
return self.with_args(**stored)
return self | [
"def",
"with_known_args",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"argspec",
"=",
"inspect",
".",
"getargspec",
"(",
"self",
".",
"func",
")",
"stored",
"=",
"{",
"}",
"for",
"key",
",",
"arg",
"in",
"six",
".",
"iteritems",
"(",
"kwargs",
")",
":",
"if",
"key",
"in",
"argspec",
".",
"args",
"or",
"argspec",
".",
"keywords",
":",
"stored",
"[",
"key",
"]",
"=",
"arg",
"if",
"stored",
":",
"return",
"self",
".",
"with_args",
"(",
"*",
"*",
"stored",
")",
"return",
"self"
] | Send only known keyword-arguments to the phase when called. | [
"Send",
"only",
"known",
"keyword",
"-",
"arguments",
"to",
"the",
"phase",
"when",
"called",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_descriptor.py#L179-L188 |
227,069 | google/openhtf | openhtf/core/phase_descriptor.py | PhaseDescriptor.with_args | def with_args(self, **kwargs):
"""Send these keyword-arguments to the phase when called."""
# Make a copy so we can have multiple of the same phase with different args
# in the same test.
new_info = mutablerecords.CopyRecord(self)
new_info.options = new_info.options.format_strings(**kwargs)
new_info.extra_kwargs.update(kwargs)
new_info.measurements = [m.with_args(**kwargs) for m in self.measurements]
return new_info | python | def with_args(self, **kwargs):
"""Send these keyword-arguments to the phase when called."""
# Make a copy so we can have multiple of the same phase with different args
# in the same test.
new_info = mutablerecords.CopyRecord(self)
new_info.options = new_info.options.format_strings(**kwargs)
new_info.extra_kwargs.update(kwargs)
new_info.measurements = [m.with_args(**kwargs) for m in self.measurements]
return new_info | [
"def",
"with_args",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# Make a copy so we can have multiple of the same phase with different args",
"# in the same test.",
"new_info",
"=",
"mutablerecords",
".",
"CopyRecord",
"(",
"self",
")",
"new_info",
".",
"options",
"=",
"new_info",
".",
"options",
".",
"format_strings",
"(",
"*",
"*",
"kwargs",
")",
"new_info",
".",
"extra_kwargs",
".",
"update",
"(",
"kwargs",
")",
"new_info",
".",
"measurements",
"=",
"[",
"m",
".",
"with_args",
"(",
"*",
"*",
"kwargs",
")",
"for",
"m",
"in",
"self",
".",
"measurements",
"]",
"return",
"new_info"
] | Send these keyword-arguments to the phase when called. | [
"Send",
"these",
"keyword",
"-",
"arguments",
"to",
"the",
"phase",
"when",
"called",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_descriptor.py#L190-L198 |
227,070 | google/openhtf | openhtf/core/phase_descriptor.py | PhaseDescriptor._apply_with_plugs | def _apply_with_plugs(self, subplugs, error_on_unknown):
"""Substitute plugs for placeholders for this phase.
Args:
subplugs: dict of plug name to plug class, plug classes to replace.
error_on_unknown: bool, if True, then error when an unknown plug name is
provided.
Raises:
openhtf.plugs.InvalidPlugError if for one of the plug names one of the
following is true:
- error_on_unknown is True and the plug name is not registered.
- The new plug subclass is not a subclass of the original.
- The original plug class is not a placeholder or automatic placeholder.
Returns:
PhaseDescriptor with updated plugs.
"""
plugs_by_name = {plug.name: plug for plug in self.plugs}
new_plugs = dict(plugs_by_name)
for name, sub_class in six.iteritems(subplugs):
original_plug = plugs_by_name.get(name)
accept_substitute = True
if original_plug is None:
if not error_on_unknown:
continue
accept_substitute = False
elif isinstance(original_plug.cls, openhtf.plugs.PlugPlaceholder):
accept_substitute = issubclass(sub_class, original_plug.cls.base_class)
else:
# Check __dict__ to see if the attribute is explicitly defined in the
# class, rather than being defined in a parent class.
accept_substitute = ('auto_placeholder' in original_plug.cls.__dict__
and original_plug.cls.auto_placeholder
and issubclass(sub_class, original_plug.cls))
if not accept_substitute:
raise openhtf.plugs.InvalidPlugError(
'Could not find valid placeholder for substitute plug %s '
'required for phase %s' % (name, self.name))
new_plugs[name] = mutablerecords.CopyRecord(original_plug, cls=sub_class)
return mutablerecords.CopyRecord(
self,
plugs=list(new_plugs.values()),
options=self.options.format_strings(**subplugs),
measurements=[m.with_args(**subplugs) for m in self.measurements]) | python | def _apply_with_plugs(self, subplugs, error_on_unknown):
"""Substitute plugs for placeholders for this phase.
Args:
subplugs: dict of plug name to plug class, plug classes to replace.
error_on_unknown: bool, if True, then error when an unknown plug name is
provided.
Raises:
openhtf.plugs.InvalidPlugError if for one of the plug names one of the
following is true:
- error_on_unknown is True and the plug name is not registered.
- The new plug subclass is not a subclass of the original.
- The original plug class is not a placeholder or automatic placeholder.
Returns:
PhaseDescriptor with updated plugs.
"""
plugs_by_name = {plug.name: plug for plug in self.plugs}
new_plugs = dict(plugs_by_name)
for name, sub_class in six.iteritems(subplugs):
original_plug = plugs_by_name.get(name)
accept_substitute = True
if original_plug is None:
if not error_on_unknown:
continue
accept_substitute = False
elif isinstance(original_plug.cls, openhtf.plugs.PlugPlaceholder):
accept_substitute = issubclass(sub_class, original_plug.cls.base_class)
else:
# Check __dict__ to see if the attribute is explicitly defined in the
# class, rather than being defined in a parent class.
accept_substitute = ('auto_placeholder' in original_plug.cls.__dict__
and original_plug.cls.auto_placeholder
and issubclass(sub_class, original_plug.cls))
if not accept_substitute:
raise openhtf.plugs.InvalidPlugError(
'Could not find valid placeholder for substitute plug %s '
'required for phase %s' % (name, self.name))
new_plugs[name] = mutablerecords.CopyRecord(original_plug, cls=sub_class)
return mutablerecords.CopyRecord(
self,
plugs=list(new_plugs.values()),
options=self.options.format_strings(**subplugs),
measurements=[m.with_args(**subplugs) for m in self.measurements]) | [
"def",
"_apply_with_plugs",
"(",
"self",
",",
"subplugs",
",",
"error_on_unknown",
")",
":",
"plugs_by_name",
"=",
"{",
"plug",
".",
"name",
":",
"plug",
"for",
"plug",
"in",
"self",
".",
"plugs",
"}",
"new_plugs",
"=",
"dict",
"(",
"plugs_by_name",
")",
"for",
"name",
",",
"sub_class",
"in",
"six",
".",
"iteritems",
"(",
"subplugs",
")",
":",
"original_plug",
"=",
"plugs_by_name",
".",
"get",
"(",
"name",
")",
"accept_substitute",
"=",
"True",
"if",
"original_plug",
"is",
"None",
":",
"if",
"not",
"error_on_unknown",
":",
"continue",
"accept_substitute",
"=",
"False",
"elif",
"isinstance",
"(",
"original_plug",
".",
"cls",
",",
"openhtf",
".",
"plugs",
".",
"PlugPlaceholder",
")",
":",
"accept_substitute",
"=",
"issubclass",
"(",
"sub_class",
",",
"original_plug",
".",
"cls",
".",
"base_class",
")",
"else",
":",
"# Check __dict__ to see if the attribute is explicitly defined in the",
"# class, rather than being defined in a parent class.",
"accept_substitute",
"=",
"(",
"'auto_placeholder'",
"in",
"original_plug",
".",
"cls",
".",
"__dict__",
"and",
"original_plug",
".",
"cls",
".",
"auto_placeholder",
"and",
"issubclass",
"(",
"sub_class",
",",
"original_plug",
".",
"cls",
")",
")",
"if",
"not",
"accept_substitute",
":",
"raise",
"openhtf",
".",
"plugs",
".",
"InvalidPlugError",
"(",
"'Could not find valid placeholder for substitute plug %s '",
"'required for phase %s'",
"%",
"(",
"name",
",",
"self",
".",
"name",
")",
")",
"new_plugs",
"[",
"name",
"]",
"=",
"mutablerecords",
".",
"CopyRecord",
"(",
"original_plug",
",",
"cls",
"=",
"sub_class",
")",
"return",
"mutablerecords",
".",
"CopyRecord",
"(",
"self",
",",
"plugs",
"=",
"list",
"(",
"new_plugs",
".",
"values",
"(",
")",
")",
",",
"options",
"=",
"self",
".",
"options",
".",
"format_strings",
"(",
"*",
"*",
"subplugs",
")",
",",
"measurements",
"=",
"[",
"m",
".",
"with_args",
"(",
"*",
"*",
"subplugs",
")",
"for",
"m",
"in",
"self",
".",
"measurements",
"]",
")"
] | Substitute plugs for placeholders for this phase.
Args:
subplugs: dict of plug name to plug class, plug classes to replace.
error_on_unknown: bool, if True, then error when an unknown plug name is
provided.
Raises:
openhtf.plugs.InvalidPlugError if for one of the plug names one of the
following is true:
- error_on_unknown is True and the plug name is not registered.
- The new plug subclass is not a subclass of the original.
- The original plug class is not a placeholder or automatic placeholder.
Returns:
PhaseDescriptor with updated plugs. | [
"Substitute",
"plugs",
"for",
"placeholders",
"for",
"this",
"phase",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_descriptor.py#L208-L255 |
227,071 | google/openhtf | openhtf/plugs/usb/usb_handle.py | requires_open_handle | def requires_open_handle(method): # pylint: disable=invalid-name
"""Decorator to ensure a handle is open for certain methods.
Subclasses should decorate their Read() and Write() with this rather than
checking their own internal state, keeping all "is this handle open" logic
in is_closed().
Args:
method: A class method on a subclass of UsbHandle
Raises:
HandleClosedError: If this handle has been closed.
Returns:
A wrapper around method that ensures the handle is open before calling through
to the wrapped method.
"""
@functools.wraps(method)
def wrapper_requiring_open_handle(self, *args, **kwargs):
"""The wrapper to be returned."""
if self.is_closed():
raise usb_exceptions.HandleClosedError()
return method(self, *args, **kwargs)
return wrapper_requiring_open_handle | python | def requires_open_handle(method): # pylint: disable=invalid-name
"""Decorator to ensure a handle is open for certain methods.
Subclasses should decorate their Read() and Write() with this rather than
checking their own internal state, keeping all "is this handle open" logic
in is_closed().
Args:
method: A class method on a subclass of UsbHandle
Raises:
HandleClosedError: If this handle has been closed.
Returns:
A wrapper around method that ensures the handle is open before calling through
to the wrapped method.
"""
@functools.wraps(method)
def wrapper_requiring_open_handle(self, *args, **kwargs):
"""The wrapper to be returned."""
if self.is_closed():
raise usb_exceptions.HandleClosedError()
return method(self, *args, **kwargs)
return wrapper_requiring_open_handle | [
"def",
"requires_open_handle",
"(",
"method",
")",
":",
"# pylint: disable=invalid-name",
"@",
"functools",
".",
"wraps",
"(",
"method",
")",
"def",
"wrapper_requiring_open_handle",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"The wrapper to be returned.\"\"\"",
"if",
"self",
".",
"is_closed",
"(",
")",
":",
"raise",
"usb_exceptions",
".",
"HandleClosedError",
"(",
")",
"return",
"method",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"wrapper_requiring_open_handle"
] | Decorator to ensure a handle is open for certain methods.
Subclasses should decorate their Read() and Write() with this rather than
checking their own internal state, keeping all "is this handle open" logic
in is_closed().
Args:
method: A class method on a subclass of UsbHandle
Raises:
HandleClosedError: If this handle has been closed.
Returns:
A wrapper around method that ensures the handle is open before calling through
to the wrapped method. | [
"Decorator",
"to",
"ensure",
"a",
"handle",
"is",
"open",
"for",
"certain",
"methods",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/usb_handle.py#L36-L59 |
227,072 | google/openhtf | openhtf/plugs/usb/usb_handle_stub.py | StubUsbHandle._dotify | def _dotify(cls, data):
"""Add dots."""
return ''.join(char if char in cls.PRINTABLE_DATA else '.' for char in data) | python | def _dotify(cls, data):
"""Add dots."""
return ''.join(char if char in cls.PRINTABLE_DATA else '.' for char in data) | [
"def",
"_dotify",
"(",
"cls",
",",
"data",
")",
":",
"return",
"''",
".",
"join",
"(",
"char",
"if",
"char",
"in",
"cls",
".",
"PRINTABLE_DATA",
"else",
"'.'",
"for",
"char",
"in",
"data",
")"
] | Add dots. | [
"Add",
"dots",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/usb_handle_stub.py#L36-L38 |
227,073 | google/openhtf | openhtf/plugs/usb/usb_handle_stub.py | StubUsbHandle.write | def write(self, data, dummy=None):
"""Stub Write method."""
assert not self.closed
if self.expected_write_data is None:
return
expected_data = self.expected_write_data.pop(0)
if expected_data != data:
raise ValueError('Expected %s, got %s (%s)' % (
self._dotify(expected_data), binascii.hexlify(data),
self._dotify(data))) | python | def write(self, data, dummy=None):
"""Stub Write method."""
assert not self.closed
if self.expected_write_data is None:
return
expected_data = self.expected_write_data.pop(0)
if expected_data != data:
raise ValueError('Expected %s, got %s (%s)' % (
self._dotify(expected_data), binascii.hexlify(data),
self._dotify(data))) | [
"def",
"write",
"(",
"self",
",",
"data",
",",
"dummy",
"=",
"None",
")",
":",
"assert",
"not",
"self",
".",
"closed",
"if",
"self",
".",
"expected_write_data",
"is",
"None",
":",
"return",
"expected_data",
"=",
"self",
".",
"expected_write_data",
".",
"pop",
"(",
"0",
")",
"if",
"expected_data",
"!=",
"data",
":",
"raise",
"ValueError",
"(",
"'Expected %s, got %s (%s)'",
"%",
"(",
"self",
".",
"_dotify",
"(",
"expected_data",
")",
",",
"binascii",
".",
"hexlify",
"(",
"data",
")",
",",
"self",
".",
"_dotify",
"(",
"data",
")",
")",
")"
] | Stub Write method. | [
"Stub",
"Write",
"method",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/usb_handle_stub.py#L40-L50 |
227,074 | google/openhtf | openhtf/plugs/usb/usb_handle_stub.py | StubUsbHandle.read | def read(self, length, dummy=None):
"""Stub Read method."""
assert not self.closed
data = self.expected_read_data.pop(0)
if length < len(data):
raise ValueError(
'Overflow packet length. Read %d bytes, got %d bytes: %s',
length, len(data), self._dotify(data))
return data | python | def read(self, length, dummy=None):
"""Stub Read method."""
assert not self.closed
data = self.expected_read_data.pop(0)
if length < len(data):
raise ValueError(
'Overflow packet length. Read %d bytes, got %d bytes: %s',
length, len(data), self._dotify(data))
return data | [
"def",
"read",
"(",
"self",
",",
"length",
",",
"dummy",
"=",
"None",
")",
":",
"assert",
"not",
"self",
".",
"closed",
"data",
"=",
"self",
".",
"expected_read_data",
".",
"pop",
"(",
"0",
")",
"if",
"length",
"<",
"len",
"(",
"data",
")",
":",
"raise",
"ValueError",
"(",
"'Overflow packet length. Read %d bytes, got %d bytes: %s'",
",",
"length",
",",
"len",
"(",
"data",
")",
",",
"self",
".",
"_dotify",
"(",
"data",
")",
")",
"return",
"data"
] | Stub Read method. | [
"Stub",
"Read",
"method",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/usb_handle_stub.py#L52-L60 |
227,075 | google/openhtf | openhtf/plugs/cambrionix/__init__.py | EtherSync.get_usb_serial | def get_usb_serial(self, port_num):
"""Get the device serial number
Args:
port_num: port number on the Cambrionix unit
Return:
usb device serial number
"""
port = self.port_map[str(port_num)]
arg = ''.join(['DEVICE INFO,', self._addr, '.', port])
cmd = (['esuit64', '-t', arg])
info = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
serial = None
if "SERIAL" in info:
serial_info = info.split('SERIAL:')[1]
serial = serial_info.split('\n')[0].strip()
use_info = info.split('BY')[1].split(' ')[1]
if use_info == 'NO':
cmd = (['esuit64', '-t', 'AUTO USE ALL'])
subprocess.check_output(cmd, stderr=subprocess.STDOUT)
time.sleep(50.0/1000.0)
else:
raise ValueError('No USB device detected')
return serial | python | def get_usb_serial(self, port_num):
"""Get the device serial number
Args:
port_num: port number on the Cambrionix unit
Return:
usb device serial number
"""
port = self.port_map[str(port_num)]
arg = ''.join(['DEVICE INFO,', self._addr, '.', port])
cmd = (['esuit64', '-t', arg])
info = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
serial = None
if "SERIAL" in info:
serial_info = info.split('SERIAL:')[1]
serial = serial_info.split('\n')[0].strip()
use_info = info.split('BY')[1].split(' ')[1]
if use_info == 'NO':
cmd = (['esuit64', '-t', 'AUTO USE ALL'])
subprocess.check_output(cmd, stderr=subprocess.STDOUT)
time.sleep(50.0/1000.0)
else:
raise ValueError('No USB device detected')
return serial | [
"def",
"get_usb_serial",
"(",
"self",
",",
"port_num",
")",
":",
"port",
"=",
"self",
".",
"port_map",
"[",
"str",
"(",
"port_num",
")",
"]",
"arg",
"=",
"''",
".",
"join",
"(",
"[",
"'DEVICE INFO,'",
",",
"self",
".",
"_addr",
",",
"'.'",
",",
"port",
"]",
")",
"cmd",
"=",
"(",
"[",
"'esuit64'",
",",
"'-t'",
",",
"arg",
"]",
")",
"info",
"=",
"subprocess",
".",
"check_output",
"(",
"cmd",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
")",
"serial",
"=",
"None",
"if",
"\"SERIAL\"",
"in",
"info",
":",
"serial_info",
"=",
"info",
".",
"split",
"(",
"'SERIAL:'",
")",
"[",
"1",
"]",
"serial",
"=",
"serial_info",
".",
"split",
"(",
"'\\n'",
")",
"[",
"0",
"]",
".",
"strip",
"(",
")",
"use_info",
"=",
"info",
".",
"split",
"(",
"'BY'",
")",
"[",
"1",
"]",
".",
"split",
"(",
"' '",
")",
"[",
"1",
"]",
"if",
"use_info",
"==",
"'NO'",
":",
"cmd",
"=",
"(",
"[",
"'esuit64'",
",",
"'-t'",
",",
"'AUTO USE ALL'",
"]",
")",
"subprocess",
".",
"check_output",
"(",
"cmd",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
")",
"time",
".",
"sleep",
"(",
"50.0",
"/",
"1000.0",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'No USB device detected'",
")",
"return",
"serial"
] | Get the device serial number
Args:
port_num: port number on the Cambrionix unit
Return:
usb device serial number | [
"Get",
"the",
"device",
"serial",
"number"
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/cambrionix/__init__.py#L47-L72 |
227,076 | google/openhtf | openhtf/plugs/cambrionix/__init__.py | EtherSync.open_usb_handle | def open_usb_handle(self, port_num):
"""open usb port
Args:
port_num: port number on the Cambrionix unit
Return:
usb handle
"""
serial = self.get_usb_serial(port_num)
return local_usb.LibUsbHandle.open(serial_number=serial) | python | def open_usb_handle(self, port_num):
"""open usb port
Args:
port_num: port number on the Cambrionix unit
Return:
usb handle
"""
serial = self.get_usb_serial(port_num)
return local_usb.LibUsbHandle.open(serial_number=serial) | [
"def",
"open_usb_handle",
"(",
"self",
",",
"port_num",
")",
":",
"serial",
"=",
"self",
".",
"get_usb_serial",
"(",
"port_num",
")",
"return",
"local_usb",
".",
"LibUsbHandle",
".",
"open",
"(",
"serial_number",
"=",
"serial",
")"
] | open usb port
Args:
port_num: port number on the Cambrionix unit
Return:
usb handle | [
"open",
"usb",
"port"
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/cambrionix/__init__.py#L74-L84 |
227,077 | google/openhtf | openhtf/util/console_output.py | _printed_len | def _printed_len(some_string):
"""Compute the visible length of the string when printed."""
return len([x for x in ANSI_ESC_RE.sub('', some_string)
if x in string.printable]) | python | def _printed_len(some_string):
"""Compute the visible length of the string when printed."""
return len([x for x in ANSI_ESC_RE.sub('', some_string)
if x in string.printable]) | [
"def",
"_printed_len",
"(",
"some_string",
")",
":",
"return",
"len",
"(",
"[",
"x",
"for",
"x",
"in",
"ANSI_ESC_RE",
".",
"sub",
"(",
"''",
",",
"some_string",
")",
"if",
"x",
"in",
"string",
".",
"printable",
"]",
")"
] | Compute the visible length of the string when printed. | [
"Compute",
"the",
"visible",
"length",
"of",
"the",
"string",
"when",
"printed",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/console_output.py#L65-L68 |
227,078 | google/openhtf | openhtf/util/console_output.py | banner_print | def banner_print(msg, color='', width=60, file=sys.stdout, logger=_LOG):
"""Print the message as a banner with a fixed width.
Also logs the message (un-bannered) to the given logger at the debug level.
Args:
msg: The message to print.
color: Optional colorama color string to be applied to the message. You can
concatenate colorama color strings together in order to get any set of
effects you want.
width: Total width for the resulting banner.
file: A file object to which the banner text will be written. Intended for
use with CLI output file objects like sys.stdout.
logger: A logger to use, or None to disable logging.
Example:
>>> banner_print('Foo Bar Baz')
======================== Foo Bar Baz =======================
"""
if logger:
logger.debug(ANSI_ESC_RE.sub('', msg))
if CLI_QUIET:
return
lpad = int(math.ceil((width - _printed_len(msg) - 2) / 2.0)) * '='
rpad = int(math.floor((width - _printed_len(msg) - 2) / 2.0)) * '='
file.write('{sep}{color}{lpad} {msg} {rpad}{reset}{sep}{sep}'.format(
sep=_linesep_for_file(file), color=color, lpad=lpad, msg=msg, rpad=rpad,
reset=colorama.Style.RESET_ALL))
file.flush() | python | def banner_print(msg, color='', width=60, file=sys.stdout, logger=_LOG):
"""Print the message as a banner with a fixed width.
Also logs the message (un-bannered) to the given logger at the debug level.
Args:
msg: The message to print.
color: Optional colorama color string to be applied to the message. You can
concatenate colorama color strings together in order to get any set of
effects you want.
width: Total width for the resulting banner.
file: A file object to which the banner text will be written. Intended for
use with CLI output file objects like sys.stdout.
logger: A logger to use, or None to disable logging.
Example:
>>> banner_print('Foo Bar Baz')
======================== Foo Bar Baz =======================
"""
if logger:
logger.debug(ANSI_ESC_RE.sub('', msg))
if CLI_QUIET:
return
lpad = int(math.ceil((width - _printed_len(msg) - 2) / 2.0)) * '='
rpad = int(math.floor((width - _printed_len(msg) - 2) / 2.0)) * '='
file.write('{sep}{color}{lpad} {msg} {rpad}{reset}{sep}{sep}'.format(
sep=_linesep_for_file(file), color=color, lpad=lpad, msg=msg, rpad=rpad,
reset=colorama.Style.RESET_ALL))
file.flush() | [
"def",
"banner_print",
"(",
"msg",
",",
"color",
"=",
"''",
",",
"width",
"=",
"60",
",",
"file",
"=",
"sys",
".",
"stdout",
",",
"logger",
"=",
"_LOG",
")",
":",
"if",
"logger",
":",
"logger",
".",
"debug",
"(",
"ANSI_ESC_RE",
".",
"sub",
"(",
"''",
",",
"msg",
")",
")",
"if",
"CLI_QUIET",
":",
"return",
"lpad",
"=",
"int",
"(",
"math",
".",
"ceil",
"(",
"(",
"width",
"-",
"_printed_len",
"(",
"msg",
")",
"-",
"2",
")",
"/",
"2.0",
")",
")",
"*",
"'='",
"rpad",
"=",
"int",
"(",
"math",
".",
"floor",
"(",
"(",
"width",
"-",
"_printed_len",
"(",
"msg",
")",
"-",
"2",
")",
"/",
"2.0",
")",
")",
"*",
"'='",
"file",
".",
"write",
"(",
"'{sep}{color}{lpad} {msg} {rpad}{reset}{sep}{sep}'",
".",
"format",
"(",
"sep",
"=",
"_linesep_for_file",
"(",
"file",
")",
",",
"color",
"=",
"color",
",",
"lpad",
"=",
"lpad",
",",
"msg",
"=",
"msg",
",",
"rpad",
"=",
"rpad",
",",
"reset",
"=",
"colorama",
".",
"Style",
".",
"RESET_ALL",
")",
")",
"file",
".",
"flush",
"(",
")"
] | Print the message as a banner with a fixed width.
Also logs the message (un-bannered) to the given logger at the debug level.
Args:
msg: The message to print.
color: Optional colorama color string to be applied to the message. You can
concatenate colorama color strings together in order to get any set of
effects you want.
width: Total width for the resulting banner.
file: A file object to which the banner text will be written. Intended for
use with CLI output file objects like sys.stdout.
logger: A logger to use, or None to disable logging.
Example:
>>> banner_print('Foo Bar Baz')
======================== Foo Bar Baz ======================= | [
"Print",
"the",
"message",
"as",
"a",
"banner",
"with",
"a",
"fixed",
"width",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/console_output.py#L78-L109 |
227,079 | google/openhtf | openhtf/util/console_output.py | bracket_print | def bracket_print(msg, color='', width=8, file=sys.stdout):
"""Prints the message in brackets in the specified color and end the line.
Args:
msg: The message to put inside the brackets (a brief status message).
color: Optional colorama color string to be applied to the message. You can
concatenate colorama color strings together in order to get any set of
effects you want.
width: Total desired width of the bracketed message.
file: A file object to which the bracketed text will be written. Intended
for use with CLI output file objects like sys.stdout.
"""
if CLI_QUIET:
return
lpad = int(math.ceil((width - 2 - _printed_len(msg)) / 2.0)) * ' '
rpad = int(math.floor((width - 2 - _printed_len(msg)) / 2.0)) * ' '
file.write('[{lpad}{bright}{color}{msg}{reset}{rpad}]'.format(
lpad=lpad, bright=colorama.Style.BRIGHT, color=color, msg=msg,
reset=colorama.Style.RESET_ALL, rpad=rpad))
file.write(colorama.Style.RESET_ALL)
file.write(_linesep_for_file(file))
file.flush() | python | def bracket_print(msg, color='', width=8, file=sys.stdout):
"""Prints the message in brackets in the specified color and end the line.
Args:
msg: The message to put inside the brackets (a brief status message).
color: Optional colorama color string to be applied to the message. You can
concatenate colorama color strings together in order to get any set of
effects you want.
width: Total desired width of the bracketed message.
file: A file object to which the bracketed text will be written. Intended
for use with CLI output file objects like sys.stdout.
"""
if CLI_QUIET:
return
lpad = int(math.ceil((width - 2 - _printed_len(msg)) / 2.0)) * ' '
rpad = int(math.floor((width - 2 - _printed_len(msg)) / 2.0)) * ' '
file.write('[{lpad}{bright}{color}{msg}{reset}{rpad}]'.format(
lpad=lpad, bright=colorama.Style.BRIGHT, color=color, msg=msg,
reset=colorama.Style.RESET_ALL, rpad=rpad))
file.write(colorama.Style.RESET_ALL)
file.write(_linesep_for_file(file))
file.flush() | [
"def",
"bracket_print",
"(",
"msg",
",",
"color",
"=",
"''",
",",
"width",
"=",
"8",
",",
"file",
"=",
"sys",
".",
"stdout",
")",
":",
"if",
"CLI_QUIET",
":",
"return",
"lpad",
"=",
"int",
"(",
"math",
".",
"ceil",
"(",
"(",
"width",
"-",
"2",
"-",
"_printed_len",
"(",
"msg",
")",
")",
"/",
"2.0",
")",
")",
"*",
"' '",
"rpad",
"=",
"int",
"(",
"math",
".",
"floor",
"(",
"(",
"width",
"-",
"2",
"-",
"_printed_len",
"(",
"msg",
")",
")",
"/",
"2.0",
")",
")",
"*",
"' '",
"file",
".",
"write",
"(",
"'[{lpad}{bright}{color}{msg}{reset}{rpad}]'",
".",
"format",
"(",
"lpad",
"=",
"lpad",
",",
"bright",
"=",
"colorama",
".",
"Style",
".",
"BRIGHT",
",",
"color",
"=",
"color",
",",
"msg",
"=",
"msg",
",",
"reset",
"=",
"colorama",
".",
"Style",
".",
"RESET_ALL",
",",
"rpad",
"=",
"rpad",
")",
")",
"file",
".",
"write",
"(",
"colorama",
".",
"Style",
".",
"RESET_ALL",
")",
"file",
".",
"write",
"(",
"_linesep_for_file",
"(",
"file",
")",
")",
"file",
".",
"flush",
"(",
")"
] | Prints the message in brackets in the specified color and end the line.
Args:
msg: The message to put inside the brackets (a brief status message).
color: Optional colorama color string to be applied to the message. You can
concatenate colorama color strings together in order to get any set of
effects you want.
width: Total desired width of the bracketed message.
file: A file object to which the bracketed text will be written. Intended
for use with CLI output file objects like sys.stdout. | [
"Prints",
"the",
"message",
"in",
"brackets",
"in",
"the",
"specified",
"color",
"and",
"end",
"the",
"line",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/console_output.py#L112-L133 |
227,080 | google/openhtf | openhtf/util/console_output.py | cli_print | def cli_print(msg, color='', end=None, file=sys.stdout, logger=_LOG):
"""Print the message to file and also log it.
This function is intended as a 'tee' mechanism to enable the CLI interface as
a first-class citizen, while ensuring that everything the operator sees also
has an analogous logging entry in the test record for later inspection.
Args:
msg: The message to print/log.
color: Optional colorama color string to be applied to the message. You can
concatenate colorama color strings together in order to get any set of
effects you want.
end: A custom line-ending string to print instead of newline.
file: A file object to which the baracketed text will be written. Intended
for use with CLI output file objects like sys.stdout.
logger: A logger to use, or None to disable logging.
"""
if logger:
logger.debug('-> {}'.format(msg))
if CLI_QUIET:
return
if end is None:
end = _linesep_for_file(file)
file.write('{color}{msg}{reset}{end}'.format(
color=color, msg=msg, reset=colorama.Style.RESET_ALL, end=end)) | python | def cli_print(msg, color='', end=None, file=sys.stdout, logger=_LOG):
"""Print the message to file and also log it.
This function is intended as a 'tee' mechanism to enable the CLI interface as
a first-class citizen, while ensuring that everything the operator sees also
has an analogous logging entry in the test record for later inspection.
Args:
msg: The message to print/log.
color: Optional colorama color string to be applied to the message. You can
concatenate colorama color strings together in order to get any set of
effects you want.
end: A custom line-ending string to print instead of newline.
file: A file object to which the baracketed text will be written. Intended
for use with CLI output file objects like sys.stdout.
logger: A logger to use, or None to disable logging.
"""
if logger:
logger.debug('-> {}'.format(msg))
if CLI_QUIET:
return
if end is None:
end = _linesep_for_file(file)
file.write('{color}{msg}{reset}{end}'.format(
color=color, msg=msg, reset=colorama.Style.RESET_ALL, end=end)) | [
"def",
"cli_print",
"(",
"msg",
",",
"color",
"=",
"''",
",",
"end",
"=",
"None",
",",
"file",
"=",
"sys",
".",
"stdout",
",",
"logger",
"=",
"_LOG",
")",
":",
"if",
"logger",
":",
"logger",
".",
"debug",
"(",
"'-> {}'",
".",
"format",
"(",
"msg",
")",
")",
"if",
"CLI_QUIET",
":",
"return",
"if",
"end",
"is",
"None",
":",
"end",
"=",
"_linesep_for_file",
"(",
"file",
")",
"file",
".",
"write",
"(",
"'{color}{msg}{reset}{end}'",
".",
"format",
"(",
"color",
"=",
"color",
",",
"msg",
"=",
"msg",
",",
"reset",
"=",
"colorama",
".",
"Style",
".",
"RESET_ALL",
",",
"end",
"=",
"end",
")",
")"
] | Print the message to file and also log it.
This function is intended as a 'tee' mechanism to enable the CLI interface as
a first-class citizen, while ensuring that everything the operator sees also
has an analogous logging entry in the test record for later inspection.
Args:
msg: The message to print/log.
color: Optional colorama color string to be applied to the message. You can
concatenate colorama color strings together in order to get any set of
effects you want.
end: A custom line-ending string to print instead of newline.
file: A file object to which the baracketed text will be written. Intended
for use with CLI output file objects like sys.stdout.
logger: A logger to use, or None to disable logging. | [
"Print",
"the",
"message",
"to",
"file",
"and",
"also",
"log",
"it",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/console_output.py#L136-L160 |
227,081 | google/openhtf | openhtf/util/console_output.py | error_print | def error_print(msg, color=colorama.Fore.RED, file=sys.stderr):
"""Print the error message to the file in the specified color.
Args:
msg: The error message to be printed.
color: Optional colorama color string to be applied to the message. You can
concatenate colorama color strings together here, but note that style
strings will not be applied.
file: A file object to which the baracketed text will be written. Intended
for use with CLI output file objects, specifically sys.stderr.
"""
if CLI_QUIET:
return
file.write('{sep}{bright}{color}Error: {normal}{msg}{sep}{reset}'.format(
sep=_linesep_for_file(file), bright=colorama.Style.BRIGHT, color=color,
normal=colorama.Style.NORMAL, msg=msg, reset=colorama.Style.RESET_ALL))
file.flush() | python | def error_print(msg, color=colorama.Fore.RED, file=sys.stderr):
"""Print the error message to the file in the specified color.
Args:
msg: The error message to be printed.
color: Optional colorama color string to be applied to the message. You can
concatenate colorama color strings together here, but note that style
strings will not be applied.
file: A file object to which the baracketed text will be written. Intended
for use with CLI output file objects, specifically sys.stderr.
"""
if CLI_QUIET:
return
file.write('{sep}{bright}{color}Error: {normal}{msg}{sep}{reset}'.format(
sep=_linesep_for_file(file), bright=colorama.Style.BRIGHT, color=color,
normal=colorama.Style.NORMAL, msg=msg, reset=colorama.Style.RESET_ALL))
file.flush() | [
"def",
"error_print",
"(",
"msg",
",",
"color",
"=",
"colorama",
".",
"Fore",
".",
"RED",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
":",
"if",
"CLI_QUIET",
":",
"return",
"file",
".",
"write",
"(",
"'{sep}{bright}{color}Error: {normal}{msg}{sep}{reset}'",
".",
"format",
"(",
"sep",
"=",
"_linesep_for_file",
"(",
"file",
")",
",",
"bright",
"=",
"colorama",
".",
"Style",
".",
"BRIGHT",
",",
"color",
"=",
"color",
",",
"normal",
"=",
"colorama",
".",
"Style",
".",
"NORMAL",
",",
"msg",
"=",
"msg",
",",
"reset",
"=",
"colorama",
".",
"Style",
".",
"RESET_ALL",
")",
")",
"file",
".",
"flush",
"(",
")"
] | Print the error message to the file in the specified color.
Args:
msg: The error message to be printed.
color: Optional colorama color string to be applied to the message. You can
concatenate colorama color strings together here, but note that style
strings will not be applied.
file: A file object to which the baracketed text will be written. Intended
for use with CLI output file objects, specifically sys.stderr. | [
"Print",
"the",
"error",
"message",
"to",
"the",
"file",
"in",
"the",
"specified",
"color",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/console_output.py#L163-L179 |
227,082 | google/openhtf | openhtf/util/console_output.py | action_result_context | def action_result_context(action_text,
width=60,
status_width=8,
succeed_text='OK',
fail_text='FAIL',
unknown_text='????',
file=sys.stdout,
logger=_LOG):
"""A contextmanager that prints actions and results to the CLI.
When entering the context, the action will be printed, and when the context
is exited, the result will be printed. The object yielded by the context is
used to mark the action as a success or failure, and a raise from inside the
context will also result in the action being marked fail. If the result is
left unset, then indicative text ("????") will be printed as the result.
Args:
action_text: Text to be displayed that describes the action being taken.
width: Total width for each line of output.
status_width: Width of the just the status message portion of each line.
succeed_text: Status message displayed when the action succeeds.
fail_text: Status message displayed when the action fails.
unknown_text: Status message displayed when the result is left unset.
file: Specific file object to write to write CLI output to.
logger: A logger to use, or None to disable logging.
Example usage:
with action_result_context('Doing an action that will succeed...') as act:
time.sleep(2)
act.succeed()
with action_result_context('Doing an action with unset result...') as act:
time.sleep(2)
with action_result_context('Doing an action that will fail...') as act:
time.sleep(2)
act.fail()
with action_result_context('Doing an action that will raise...') as act:
time.sleep(2)
import textwrap
raise RuntimeError(textwrap.dedent('''\
Uh oh, looks like there was a raise in the mix.
If you see this message, it means you are running the console_output
module directly rather than using it as a library. Things to try:
* Not running it as a module.
* Running it as a module and enjoying the preview text.
* Getting another coffee.'''))
Example output:
Doing an action that will succeed... [ OK ]
Doing an action with unset result... [ ???? ]
Doing an action that will fail... [ FAIL ]
Doing an action that will raise... [ FAIL ]
...
"""
if logger:
logger.debug('Action - %s', action_text)
if not CLI_QUIET:
file.write(''.join((action_text, '\r')))
file.flush()
spacing = (width - status_width - _printed_len(action_text)) * ' '
result = ActionResult()
try:
yield result
except Exception as err:
if logger:
logger.debug('Result - %s [ %s ]', action_text, fail_text)
if not CLI_QUIET:
file.write(''.join((action_text, spacing)))
bracket_print(fail_text, width=status_width, color=colorama.Fore.RED,
file=file)
if not isinstance(err, ActionFailedError):
raise
return
result_text = succeed_text if result.success else unknown_text
result_color = colorama.Fore.GREEN if result.success else colorama.Fore.YELLOW
if logger:
logger.debug('Result - %s [ %s ]', action_text, result_text)
if not CLI_QUIET:
file.write(''.join((action_text, spacing)))
bracket_print(result_text, width=status_width, color=result_color,
file=file) | python | def action_result_context(action_text,
width=60,
status_width=8,
succeed_text='OK',
fail_text='FAIL',
unknown_text='????',
file=sys.stdout,
logger=_LOG):
"""A contextmanager that prints actions and results to the CLI.
When entering the context, the action will be printed, and when the context
is exited, the result will be printed. The object yielded by the context is
used to mark the action as a success or failure, and a raise from inside the
context will also result in the action being marked fail. If the result is
left unset, then indicative text ("????") will be printed as the result.
Args:
action_text: Text to be displayed that describes the action being taken.
width: Total width for each line of output.
status_width: Width of the just the status message portion of each line.
succeed_text: Status message displayed when the action succeeds.
fail_text: Status message displayed when the action fails.
unknown_text: Status message displayed when the result is left unset.
file: Specific file object to write to write CLI output to.
logger: A logger to use, or None to disable logging.
Example usage:
with action_result_context('Doing an action that will succeed...') as act:
time.sleep(2)
act.succeed()
with action_result_context('Doing an action with unset result...') as act:
time.sleep(2)
with action_result_context('Doing an action that will fail...') as act:
time.sleep(2)
act.fail()
with action_result_context('Doing an action that will raise...') as act:
time.sleep(2)
import textwrap
raise RuntimeError(textwrap.dedent('''\
Uh oh, looks like there was a raise in the mix.
If you see this message, it means you are running the console_output
module directly rather than using it as a library. Things to try:
* Not running it as a module.
* Running it as a module and enjoying the preview text.
* Getting another coffee.'''))
Example output:
Doing an action that will succeed... [ OK ]
Doing an action with unset result... [ ???? ]
Doing an action that will fail... [ FAIL ]
Doing an action that will raise... [ FAIL ]
...
"""
if logger:
logger.debug('Action - %s', action_text)
if not CLI_QUIET:
file.write(''.join((action_text, '\r')))
file.flush()
spacing = (width - status_width - _printed_len(action_text)) * ' '
result = ActionResult()
try:
yield result
except Exception as err:
if logger:
logger.debug('Result - %s [ %s ]', action_text, fail_text)
if not CLI_QUIET:
file.write(''.join((action_text, spacing)))
bracket_print(fail_text, width=status_width, color=colorama.Fore.RED,
file=file)
if not isinstance(err, ActionFailedError):
raise
return
result_text = succeed_text if result.success else unknown_text
result_color = colorama.Fore.GREEN if result.success else colorama.Fore.YELLOW
if logger:
logger.debug('Result - %s [ %s ]', action_text, result_text)
if not CLI_QUIET:
file.write(''.join((action_text, spacing)))
bracket_print(result_text, width=status_width, color=result_color,
file=file) | [
"def",
"action_result_context",
"(",
"action_text",
",",
"width",
"=",
"60",
",",
"status_width",
"=",
"8",
",",
"succeed_text",
"=",
"'OK'",
",",
"fail_text",
"=",
"'FAIL'",
",",
"unknown_text",
"=",
"'????'",
",",
"file",
"=",
"sys",
".",
"stdout",
",",
"logger",
"=",
"_LOG",
")",
":",
"if",
"logger",
":",
"logger",
".",
"debug",
"(",
"'Action - %s'",
",",
"action_text",
")",
"if",
"not",
"CLI_QUIET",
":",
"file",
".",
"write",
"(",
"''",
".",
"join",
"(",
"(",
"action_text",
",",
"'\\r'",
")",
")",
")",
"file",
".",
"flush",
"(",
")",
"spacing",
"=",
"(",
"width",
"-",
"status_width",
"-",
"_printed_len",
"(",
"action_text",
")",
")",
"*",
"' '",
"result",
"=",
"ActionResult",
"(",
")",
"try",
":",
"yield",
"result",
"except",
"Exception",
"as",
"err",
":",
"if",
"logger",
":",
"logger",
".",
"debug",
"(",
"'Result - %s [ %s ]'",
",",
"action_text",
",",
"fail_text",
")",
"if",
"not",
"CLI_QUIET",
":",
"file",
".",
"write",
"(",
"''",
".",
"join",
"(",
"(",
"action_text",
",",
"spacing",
")",
")",
")",
"bracket_print",
"(",
"fail_text",
",",
"width",
"=",
"status_width",
",",
"color",
"=",
"colorama",
".",
"Fore",
".",
"RED",
",",
"file",
"=",
"file",
")",
"if",
"not",
"isinstance",
"(",
"err",
",",
"ActionFailedError",
")",
":",
"raise",
"return",
"result_text",
"=",
"succeed_text",
"if",
"result",
".",
"success",
"else",
"unknown_text",
"result_color",
"=",
"colorama",
".",
"Fore",
".",
"GREEN",
"if",
"result",
".",
"success",
"else",
"colorama",
".",
"Fore",
".",
"YELLOW",
"if",
"logger",
":",
"logger",
".",
"debug",
"(",
"'Result - %s [ %s ]'",
",",
"action_text",
",",
"result_text",
")",
"if",
"not",
"CLI_QUIET",
":",
"file",
".",
"write",
"(",
"''",
".",
"join",
"(",
"(",
"action_text",
",",
"spacing",
")",
")",
")",
"bracket_print",
"(",
"result_text",
",",
"width",
"=",
"status_width",
",",
"color",
"=",
"result_color",
",",
"file",
"=",
"file",
")"
] | A contextmanager that prints actions and results to the CLI.
When entering the context, the action will be printed, and when the context
is exited, the result will be printed. The object yielded by the context is
used to mark the action as a success or failure, and a raise from inside the
context will also result in the action being marked fail. If the result is
left unset, then indicative text ("????") will be printed as the result.
Args:
action_text: Text to be displayed that describes the action being taken.
width: Total width for each line of output.
status_width: Width of the just the status message portion of each line.
succeed_text: Status message displayed when the action succeeds.
fail_text: Status message displayed when the action fails.
unknown_text: Status message displayed when the result is left unset.
file: Specific file object to write to write CLI output to.
logger: A logger to use, or None to disable logging.
Example usage:
with action_result_context('Doing an action that will succeed...') as act:
time.sleep(2)
act.succeed()
with action_result_context('Doing an action with unset result...') as act:
time.sleep(2)
with action_result_context('Doing an action that will fail...') as act:
time.sleep(2)
act.fail()
with action_result_context('Doing an action that will raise...') as act:
time.sleep(2)
import textwrap
raise RuntimeError(textwrap.dedent('''\
Uh oh, looks like there was a raise in the mix.
If you see this message, it means you are running the console_output
module directly rather than using it as a library. Things to try:
* Not running it as a module.
* Running it as a module and enjoying the preview text.
* Getting another coffee.'''))
Example output:
Doing an action that will succeed... [ OK ]
Doing an action with unset result... [ ???? ]
Doing an action that will fail... [ FAIL ]
Doing an action that will raise... [ FAIL ]
... | [
"A",
"contextmanager",
"that",
"prints",
"actions",
"and",
"results",
"to",
"the",
"CLI",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/console_output.py#L204-L290 |
227,083 | google/openhtf | openhtf/util/exceptions.py | reraise | def reraise(exc_type, message=None, *args, **kwargs): # pylint: disable=invalid-name
"""reraises an exception for exception translation.
This is primarily used for when you immediately reraise an exception that is
thrown in a library, so that your client will not have to depend on various
exceptions defined in the library implementation that is being abstracted. The
advantage of this helper function is somewhat preserve traceback information
although it is polluted by the reraise frame.
Example Code:
def A():
raise Exception('Whoops')
def main():
try:
A()
except Exception as e:
exceptions.reraise(ValueError)
main()
Traceback (most recent call last):
File "exception.py", line 53, in <module>
main()
File "exception.py", line 49, in main
reraise(ValueError)
File "exception.py", line 47, in main
A()
File "exception.py", line 42, in A
raise Exception('Whoops')
ValueError: line 49
When this code is run, the additional stack frames for calling A() and raising
within A() are printed out in exception, whereas a bare exception translation
would lose this information. As long as you ignore the reraise stack frame,
the stack trace is okay looking.
Generally this can be fixed by hacking on CPython to allow modification of
traceback objects ala
https://github.com/mitsuhiko/jinja2/blob/master/jinja2/debug.py, but this is
fixed in Python 3 anyways and that method is the definition of hackery.
Args:
exc_type: (Exception) Exception class to create.
message: (str) Optional message to place in exception instance. Usually not
needed as the original exception probably has a message that will be
printed out in the modified stacktrace.
*args: Args to pass to exception constructor.
**kwargs: Kwargs to pass to exception constructor.
"""
last_lineno = inspect.currentframe().f_back.f_lineno
line_msg = 'line %s: ' % last_lineno
if message:
line_msg += str(message)
raise exc_type(line_msg, *args, **kwargs).raise_with_traceback(sys.exc_info()[2]) | python | def reraise(exc_type, message=None, *args, **kwargs): # pylint: disable=invalid-name
"""reraises an exception for exception translation.
This is primarily used for when you immediately reraise an exception that is
thrown in a library, so that your client will not have to depend on various
exceptions defined in the library implementation that is being abstracted. The
advantage of this helper function is somewhat preserve traceback information
although it is polluted by the reraise frame.
Example Code:
def A():
raise Exception('Whoops')
def main():
try:
A()
except Exception as e:
exceptions.reraise(ValueError)
main()
Traceback (most recent call last):
File "exception.py", line 53, in <module>
main()
File "exception.py", line 49, in main
reraise(ValueError)
File "exception.py", line 47, in main
A()
File "exception.py", line 42, in A
raise Exception('Whoops')
ValueError: line 49
When this code is run, the additional stack frames for calling A() and raising
within A() are printed out in exception, whereas a bare exception translation
would lose this information. As long as you ignore the reraise stack frame,
the stack trace is okay looking.
Generally this can be fixed by hacking on CPython to allow modification of
traceback objects ala
https://github.com/mitsuhiko/jinja2/blob/master/jinja2/debug.py, but this is
fixed in Python 3 anyways and that method is the definition of hackery.
Args:
exc_type: (Exception) Exception class to create.
message: (str) Optional message to place in exception instance. Usually not
needed as the original exception probably has a message that will be
printed out in the modified stacktrace.
*args: Args to pass to exception constructor.
**kwargs: Kwargs to pass to exception constructor.
"""
last_lineno = inspect.currentframe().f_back.f_lineno
line_msg = 'line %s: ' % last_lineno
if message:
line_msg += str(message)
raise exc_type(line_msg, *args, **kwargs).raise_with_traceback(sys.exc_info()[2]) | [
"def",
"reraise",
"(",
"exc_type",
",",
"message",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=invalid-name",
"last_lineno",
"=",
"inspect",
".",
"currentframe",
"(",
")",
".",
"f_back",
".",
"f_lineno",
"line_msg",
"=",
"'line %s: '",
"%",
"last_lineno",
"if",
"message",
":",
"line_msg",
"+=",
"str",
"(",
"message",
")",
"raise",
"exc_type",
"(",
"line_msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
".",
"raise_with_traceback",
"(",
"sys",
".",
"exc_info",
"(",
")",
"[",
"2",
"]",
")"
] | reraises an exception for exception translation.
This is primarily used for when you immediately reraise an exception that is
thrown in a library, so that your client will not have to depend on various
exceptions defined in the library implementation that is being abstracted. The
advantage of this helper function is somewhat preserve traceback information
although it is polluted by the reraise frame.
Example Code:
def A():
raise Exception('Whoops')
def main():
try:
A()
except Exception as e:
exceptions.reraise(ValueError)
main()
Traceback (most recent call last):
File "exception.py", line 53, in <module>
main()
File "exception.py", line 49, in main
reraise(ValueError)
File "exception.py", line 47, in main
A()
File "exception.py", line 42, in A
raise Exception('Whoops')
ValueError: line 49
When this code is run, the additional stack frames for calling A() and raising
within A() are printed out in exception, whereas a bare exception translation
would lose this information. As long as you ignore the reraise stack frame,
the stack trace is okay looking.
Generally this can be fixed by hacking on CPython to allow modification of
traceback objects ala
https://github.com/mitsuhiko/jinja2/blob/master/jinja2/debug.py, but this is
fixed in Python 3 anyways and that method is the definition of hackery.
Args:
exc_type: (Exception) Exception class to create.
message: (str) Optional message to place in exception instance. Usually not
needed as the original exception probably has a message that will be
printed out in the modified stacktrace.
*args: Args to pass to exception constructor.
**kwargs: Kwargs to pass to exception constructor. | [
"reraises",
"an",
"exception",
"for",
"exception",
"translation",
"."
] | 655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09 | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/exceptions.py#L22-L74 |
227,084 | rflamary/POT | ot/plot.py | plot1D_mat | def plot1D_mat(a, b, M, title=''):
""" Plot matrix M with the source and target 1D distribution
Creates a subplot with the source distribution a on the left and
target distribution b on the tot. The matrix M is shown in between.
Parameters
----------
a : np.array, shape (na,)
Source distribution
b : np.array, shape (nb,)
Target distribution
M : np.array, shape (na,nb)
Matrix to plot
"""
na, nb = M.shape
gs = gridspec.GridSpec(3, 3)
xa = np.arange(na)
xb = np.arange(nb)
ax1 = pl.subplot(gs[0, 1:])
pl.plot(xb, b, 'r', label='Target distribution')
pl.yticks(())
pl.title(title)
ax2 = pl.subplot(gs[1:, 0])
pl.plot(a, xa, 'b', label='Source distribution')
pl.gca().invert_xaxis()
pl.gca().invert_yaxis()
pl.xticks(())
pl.subplot(gs[1:, 1:], sharex=ax1, sharey=ax2)
pl.imshow(M, interpolation='nearest')
pl.axis('off')
pl.xlim((0, nb))
pl.tight_layout()
pl.subplots_adjust(wspace=0., hspace=0.2) | python | def plot1D_mat(a, b, M, title=''):
""" Plot matrix M with the source and target 1D distribution
Creates a subplot with the source distribution a on the left and
target distribution b on the tot. The matrix M is shown in between.
Parameters
----------
a : np.array, shape (na,)
Source distribution
b : np.array, shape (nb,)
Target distribution
M : np.array, shape (na,nb)
Matrix to plot
"""
na, nb = M.shape
gs = gridspec.GridSpec(3, 3)
xa = np.arange(na)
xb = np.arange(nb)
ax1 = pl.subplot(gs[0, 1:])
pl.plot(xb, b, 'r', label='Target distribution')
pl.yticks(())
pl.title(title)
ax2 = pl.subplot(gs[1:, 0])
pl.plot(a, xa, 'b', label='Source distribution')
pl.gca().invert_xaxis()
pl.gca().invert_yaxis()
pl.xticks(())
pl.subplot(gs[1:, 1:], sharex=ax1, sharey=ax2)
pl.imshow(M, interpolation='nearest')
pl.axis('off')
pl.xlim((0, nb))
pl.tight_layout()
pl.subplots_adjust(wspace=0., hspace=0.2) | [
"def",
"plot1D_mat",
"(",
"a",
",",
"b",
",",
"M",
",",
"title",
"=",
"''",
")",
":",
"na",
",",
"nb",
"=",
"M",
".",
"shape",
"gs",
"=",
"gridspec",
".",
"GridSpec",
"(",
"3",
",",
"3",
")",
"xa",
"=",
"np",
".",
"arange",
"(",
"na",
")",
"xb",
"=",
"np",
".",
"arange",
"(",
"nb",
")",
"ax1",
"=",
"pl",
".",
"subplot",
"(",
"gs",
"[",
"0",
",",
"1",
":",
"]",
")",
"pl",
".",
"plot",
"(",
"xb",
",",
"b",
",",
"'r'",
",",
"label",
"=",
"'Target distribution'",
")",
"pl",
".",
"yticks",
"(",
"(",
")",
")",
"pl",
".",
"title",
"(",
"title",
")",
"ax2",
"=",
"pl",
".",
"subplot",
"(",
"gs",
"[",
"1",
":",
",",
"0",
"]",
")",
"pl",
".",
"plot",
"(",
"a",
",",
"xa",
",",
"'b'",
",",
"label",
"=",
"'Source distribution'",
")",
"pl",
".",
"gca",
"(",
")",
".",
"invert_xaxis",
"(",
")",
"pl",
".",
"gca",
"(",
")",
".",
"invert_yaxis",
"(",
")",
"pl",
".",
"xticks",
"(",
"(",
")",
")",
"pl",
".",
"subplot",
"(",
"gs",
"[",
"1",
":",
",",
"1",
":",
"]",
",",
"sharex",
"=",
"ax1",
",",
"sharey",
"=",
"ax2",
")",
"pl",
".",
"imshow",
"(",
"M",
",",
"interpolation",
"=",
"'nearest'",
")",
"pl",
".",
"axis",
"(",
"'off'",
")",
"pl",
".",
"xlim",
"(",
"(",
"0",
",",
"nb",
")",
")",
"pl",
".",
"tight_layout",
"(",
")",
"pl",
".",
"subplots_adjust",
"(",
"wspace",
"=",
"0.",
",",
"hspace",
"=",
"0.2",
")"
] | Plot matrix M with the source and target 1D distribution
Creates a subplot with the source distribution a on the left and
target distribution b on the tot. The matrix M is shown in between.
Parameters
----------
a : np.array, shape (na,)
Source distribution
b : np.array, shape (nb,)
Target distribution
M : np.array, shape (na,nb)
Matrix to plot | [
"Plot",
"matrix",
"M",
"with",
"the",
"source",
"and",
"target",
"1D",
"distribution"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/plot.py#L14-L54 |
227,085 | rflamary/POT | ot/plot.py | plot2D_samples_mat | def plot2D_samples_mat(xs, xt, G, thr=1e-8, **kwargs):
""" Plot matrix M in 2D with lines using alpha values
Plot lines between source and target 2D samples with a color
proportional to the value of the matrix G between samples.
Parameters
----------
xs : ndarray, shape (ns,2)
Source samples positions
b : ndarray, shape (nt,2)
Target samples positions
G : ndarray, shape (na,nb)
OT matrix
thr : float, optional
threshold above which the line is drawn
**kwargs : dict
paameters given to the plot functions (default color is black if
nothing given)
"""
if ('color' not in kwargs) and ('c' not in kwargs):
kwargs['color'] = 'k'
mx = G.max()
for i in range(xs.shape[0]):
for j in range(xt.shape[0]):
if G[i, j] / mx > thr:
pl.plot([xs[i, 0], xt[j, 0]], [xs[i, 1], xt[j, 1]],
alpha=G[i, j] / mx, **kwargs) | python | def plot2D_samples_mat(xs, xt, G, thr=1e-8, **kwargs):
""" Plot matrix M in 2D with lines using alpha values
Plot lines between source and target 2D samples with a color
proportional to the value of the matrix G between samples.
Parameters
----------
xs : ndarray, shape (ns,2)
Source samples positions
b : ndarray, shape (nt,2)
Target samples positions
G : ndarray, shape (na,nb)
OT matrix
thr : float, optional
threshold above which the line is drawn
**kwargs : dict
paameters given to the plot functions (default color is black if
nothing given)
"""
if ('color' not in kwargs) and ('c' not in kwargs):
kwargs['color'] = 'k'
mx = G.max()
for i in range(xs.shape[0]):
for j in range(xt.shape[0]):
if G[i, j] / mx > thr:
pl.plot([xs[i, 0], xt[j, 0]], [xs[i, 1], xt[j, 1]],
alpha=G[i, j] / mx, **kwargs) | [
"def",
"plot2D_samples_mat",
"(",
"xs",
",",
"xt",
",",
"G",
",",
"thr",
"=",
"1e-8",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"(",
"'color'",
"not",
"in",
"kwargs",
")",
"and",
"(",
"'c'",
"not",
"in",
"kwargs",
")",
":",
"kwargs",
"[",
"'color'",
"]",
"=",
"'k'",
"mx",
"=",
"G",
".",
"max",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"xs",
".",
"shape",
"[",
"0",
"]",
")",
":",
"for",
"j",
"in",
"range",
"(",
"xt",
".",
"shape",
"[",
"0",
"]",
")",
":",
"if",
"G",
"[",
"i",
",",
"j",
"]",
"/",
"mx",
">",
"thr",
":",
"pl",
".",
"plot",
"(",
"[",
"xs",
"[",
"i",
",",
"0",
"]",
",",
"xt",
"[",
"j",
",",
"0",
"]",
"]",
",",
"[",
"xs",
"[",
"i",
",",
"1",
"]",
",",
"xt",
"[",
"j",
",",
"1",
"]",
"]",
",",
"alpha",
"=",
"G",
"[",
"i",
",",
"j",
"]",
"/",
"mx",
",",
"*",
"*",
"kwargs",
")"
] | Plot matrix M in 2D with lines using alpha values
Plot lines between source and target 2D samples with a color
proportional to the value of the matrix G between samples.
Parameters
----------
xs : ndarray, shape (ns,2)
Source samples positions
b : ndarray, shape (nt,2)
Target samples positions
G : ndarray, shape (na,nb)
OT matrix
thr : float, optional
threshold above which the line is drawn
**kwargs : dict
paameters given to the plot functions (default color is black if
nothing given) | [
"Plot",
"matrix",
"M",
"in",
"2D",
"with",
"lines",
"using",
"alpha",
"values"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/plot.py#L57-L85 |
227,086 | rflamary/POT | ot/gpu/da.py | sinkhorn_lpl1_mm | def sinkhorn_lpl1_mm(a, labels_a, b, M, reg, eta=0.1, numItermax=10,
numInnerItermax=200, stopInnerThr=1e-9, verbose=False,
log=False, to_numpy=True):
"""
Solve the entropic regularization optimal transport problem with nonconvex
group lasso regularization on GPU
If the input matrix are in numpy format, they will be uploaded to the
GPU first which can incur significant time overhead.
The function solves the following optimization problem:
.. math::
\gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega_e(\gamma)
+ \eta \Omega_g(\gamma)
s.t. \gamma 1 = a
\gamma^T 1= b
\gamma\geq 0
where :
- M is the (ns,nt) metric cost matrix
- :math:`\Omega_e` is the entropic regularization term
:math:`\Omega_e(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
- :math:`\Omega_g` is the group lasso regulaization term
:math:`\Omega_g(\gamma)=\sum_{i,c} \|\gamma_{i,\mathcal{I}_c}\|^{1/2}_1`
where :math:`\mathcal{I}_c` are the index of samples from class c
in the source domain.
- a and b are source and target weights (sum to 1)
The algorithm used for solving the problem is the generalised conditional
gradient as proposed in [5]_ [7]_
Parameters
----------
a : np.ndarray (ns,)
samples weights in the source domain
labels_a : np.ndarray (ns,)
labels of samples in the source domain
b : np.ndarray (nt,)
samples weights in the target domain
M : np.ndarray (ns,nt)
loss matrix
reg : float
Regularization term for entropic regularization >0
eta : float, optional
Regularization term for group lasso regularization >0
numItermax : int, optional
Max number of iterations
numInnerItermax : int, optional
Max number of iterations (inner sinkhorn solver)
stopInnerThr : float, optional
Stop threshold on error (inner sinkhorn solver) (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
to_numpy : boolean, optional (default True)
If true convert back the GPU array result to numpy format.
Returns
-------
gamma : (ns x nt) ndarray
Optimal transportation matrix for the given parameters
log : dict
log dictionary return only if log==True in parameters
References
----------
.. [5] N. Courty; R. Flamary; D. Tuia; A. Rakotomamonjy,
"Optimal Transport for Domain Adaptation," in IEEE
Transactions on Pattern Analysis and Machine Intelligence ,
vol.PP, no.99, pp.1-1
.. [7] Rakotomamonjy, A., Flamary, R., & Courty, N. (2015).
Generalized conditional gradient: analysis of convergence
and applications. arXiv preprint arXiv:1510.06567.
See Also
--------
ot.lp.emd : Unregularized OT
ot.bregman.sinkhorn : Entropic regularized OT
ot.optim.cg : General regularized OT
"""
a, labels_a, b, M = utils.to_gpu(a, labels_a, b, M)
p = 0.5
epsilon = 1e-3
indices_labels = []
labels_a2 = cp.asnumpy(labels_a)
classes = npp.unique(labels_a2)
for c in classes:
idxc, = utils.to_gpu(npp.where(labels_a2 == c))
indices_labels.append(idxc)
W = np.zeros(M.shape)
for cpt in range(numItermax):
Mreg = M + eta * W
transp = sinkhorn(a, b, Mreg, reg, numItermax=numInnerItermax,
stopThr=stopInnerThr, to_numpy=False)
# the transport has been computed. Check if classes are really
# separated
W = np.ones(M.shape)
for (i, c) in enumerate(classes):
majs = np.sum(transp[indices_labels[i]], axis=0)
majs = p * ((majs + epsilon)**(p - 1))
W[indices_labels[i]] = majs
if to_numpy:
return utils.to_np(transp)
else:
return transp | python | def sinkhorn_lpl1_mm(a, labels_a, b, M, reg, eta=0.1, numItermax=10,
numInnerItermax=200, stopInnerThr=1e-9, verbose=False,
log=False, to_numpy=True):
"""
Solve the entropic regularization optimal transport problem with nonconvex
group lasso regularization on GPU
If the input matrix are in numpy format, they will be uploaded to the
GPU first which can incur significant time overhead.
The function solves the following optimization problem:
.. math::
\gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega_e(\gamma)
+ \eta \Omega_g(\gamma)
s.t. \gamma 1 = a
\gamma^T 1= b
\gamma\geq 0
where :
- M is the (ns,nt) metric cost matrix
- :math:`\Omega_e` is the entropic regularization term
:math:`\Omega_e(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
- :math:`\Omega_g` is the group lasso regulaization term
:math:`\Omega_g(\gamma)=\sum_{i,c} \|\gamma_{i,\mathcal{I}_c}\|^{1/2}_1`
where :math:`\mathcal{I}_c` are the index of samples from class c
in the source domain.
- a and b are source and target weights (sum to 1)
The algorithm used for solving the problem is the generalised conditional
gradient as proposed in [5]_ [7]_
Parameters
----------
a : np.ndarray (ns,)
samples weights in the source domain
labels_a : np.ndarray (ns,)
labels of samples in the source domain
b : np.ndarray (nt,)
samples weights in the target domain
M : np.ndarray (ns,nt)
loss matrix
reg : float
Regularization term for entropic regularization >0
eta : float, optional
Regularization term for group lasso regularization >0
numItermax : int, optional
Max number of iterations
numInnerItermax : int, optional
Max number of iterations (inner sinkhorn solver)
stopInnerThr : float, optional
Stop threshold on error (inner sinkhorn solver) (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
to_numpy : boolean, optional (default True)
If true convert back the GPU array result to numpy format.
Returns
-------
gamma : (ns x nt) ndarray
Optimal transportation matrix for the given parameters
log : dict
log dictionary return only if log==True in parameters
References
----------
.. [5] N. Courty; R. Flamary; D. Tuia; A. Rakotomamonjy,
"Optimal Transport for Domain Adaptation," in IEEE
Transactions on Pattern Analysis and Machine Intelligence ,
vol.PP, no.99, pp.1-1
.. [7] Rakotomamonjy, A., Flamary, R., & Courty, N. (2015).
Generalized conditional gradient: analysis of convergence
and applications. arXiv preprint arXiv:1510.06567.
See Also
--------
ot.lp.emd : Unregularized OT
ot.bregman.sinkhorn : Entropic regularized OT
ot.optim.cg : General regularized OT
"""
a, labels_a, b, M = utils.to_gpu(a, labels_a, b, M)
p = 0.5
epsilon = 1e-3
indices_labels = []
labels_a2 = cp.asnumpy(labels_a)
classes = npp.unique(labels_a2)
for c in classes:
idxc, = utils.to_gpu(npp.where(labels_a2 == c))
indices_labels.append(idxc)
W = np.zeros(M.shape)
for cpt in range(numItermax):
Mreg = M + eta * W
transp = sinkhorn(a, b, Mreg, reg, numItermax=numInnerItermax,
stopThr=stopInnerThr, to_numpy=False)
# the transport has been computed. Check if classes are really
# separated
W = np.ones(M.shape)
for (i, c) in enumerate(classes):
majs = np.sum(transp[indices_labels[i]], axis=0)
majs = p * ((majs + epsilon)**(p - 1))
W[indices_labels[i]] = majs
if to_numpy:
return utils.to_np(transp)
else:
return transp | [
"def",
"sinkhorn_lpl1_mm",
"(",
"a",
",",
"labels_a",
",",
"b",
",",
"M",
",",
"reg",
",",
"eta",
"=",
"0.1",
",",
"numItermax",
"=",
"10",
",",
"numInnerItermax",
"=",
"200",
",",
"stopInnerThr",
"=",
"1e-9",
",",
"verbose",
"=",
"False",
",",
"log",
"=",
"False",
",",
"to_numpy",
"=",
"True",
")",
":",
"a",
",",
"labels_a",
",",
"b",
",",
"M",
"=",
"utils",
".",
"to_gpu",
"(",
"a",
",",
"labels_a",
",",
"b",
",",
"M",
")",
"p",
"=",
"0.5",
"epsilon",
"=",
"1e-3",
"indices_labels",
"=",
"[",
"]",
"labels_a2",
"=",
"cp",
".",
"asnumpy",
"(",
"labels_a",
")",
"classes",
"=",
"npp",
".",
"unique",
"(",
"labels_a2",
")",
"for",
"c",
"in",
"classes",
":",
"idxc",
",",
"=",
"utils",
".",
"to_gpu",
"(",
"npp",
".",
"where",
"(",
"labels_a2",
"==",
"c",
")",
")",
"indices_labels",
".",
"append",
"(",
"idxc",
")",
"W",
"=",
"np",
".",
"zeros",
"(",
"M",
".",
"shape",
")",
"for",
"cpt",
"in",
"range",
"(",
"numItermax",
")",
":",
"Mreg",
"=",
"M",
"+",
"eta",
"*",
"W",
"transp",
"=",
"sinkhorn",
"(",
"a",
",",
"b",
",",
"Mreg",
",",
"reg",
",",
"numItermax",
"=",
"numInnerItermax",
",",
"stopThr",
"=",
"stopInnerThr",
",",
"to_numpy",
"=",
"False",
")",
"# the transport has been computed. Check if classes are really",
"# separated",
"W",
"=",
"np",
".",
"ones",
"(",
"M",
".",
"shape",
")",
"for",
"(",
"i",
",",
"c",
")",
"in",
"enumerate",
"(",
"classes",
")",
":",
"majs",
"=",
"np",
".",
"sum",
"(",
"transp",
"[",
"indices_labels",
"[",
"i",
"]",
"]",
",",
"axis",
"=",
"0",
")",
"majs",
"=",
"p",
"*",
"(",
"(",
"majs",
"+",
"epsilon",
")",
"**",
"(",
"p",
"-",
"1",
")",
")",
"W",
"[",
"indices_labels",
"[",
"i",
"]",
"]",
"=",
"majs",
"if",
"to_numpy",
":",
"return",
"utils",
".",
"to_np",
"(",
"transp",
")",
"else",
":",
"return",
"transp"
] | Solve the entropic regularization optimal transport problem with nonconvex
group lasso regularization on GPU
If the input matrix are in numpy format, they will be uploaded to the
GPU first which can incur significant time overhead.
The function solves the following optimization problem:
.. math::
\gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega_e(\gamma)
+ \eta \Omega_g(\gamma)
s.t. \gamma 1 = a
\gamma^T 1= b
\gamma\geq 0
where :
- M is the (ns,nt) metric cost matrix
- :math:`\Omega_e` is the entropic regularization term
:math:`\Omega_e(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
- :math:`\Omega_g` is the group lasso regulaization term
:math:`\Omega_g(\gamma)=\sum_{i,c} \|\gamma_{i,\mathcal{I}_c}\|^{1/2}_1`
where :math:`\mathcal{I}_c` are the index of samples from class c
in the source domain.
- a and b are source and target weights (sum to 1)
The algorithm used for solving the problem is the generalised conditional
gradient as proposed in [5]_ [7]_
Parameters
----------
a : np.ndarray (ns,)
samples weights in the source domain
labels_a : np.ndarray (ns,)
labels of samples in the source domain
b : np.ndarray (nt,)
samples weights in the target domain
M : np.ndarray (ns,nt)
loss matrix
reg : float
Regularization term for entropic regularization >0
eta : float, optional
Regularization term for group lasso regularization >0
numItermax : int, optional
Max number of iterations
numInnerItermax : int, optional
Max number of iterations (inner sinkhorn solver)
stopInnerThr : float, optional
Stop threshold on error (inner sinkhorn solver) (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
to_numpy : boolean, optional (default True)
If true convert back the GPU array result to numpy format.
Returns
-------
gamma : (ns x nt) ndarray
Optimal transportation matrix for the given parameters
log : dict
log dictionary return only if log==True in parameters
References
----------
.. [5] N. Courty; R. Flamary; D. Tuia; A. Rakotomamonjy,
"Optimal Transport for Domain Adaptation," in IEEE
Transactions on Pattern Analysis and Machine Intelligence ,
vol.PP, no.99, pp.1-1
.. [7] Rakotomamonjy, A., Flamary, R., & Courty, N. (2015).
Generalized conditional gradient: analysis of convergence
and applications. arXiv preprint arXiv:1510.06567.
See Also
--------
ot.lp.emd : Unregularized OT
ot.bregman.sinkhorn : Entropic regularized OT
ot.optim.cg : General regularized OT | [
"Solve",
"the",
"entropic",
"regularization",
"optimal",
"transport",
"problem",
"with",
"nonconvex",
"group",
"lasso",
"regularization",
"on",
"GPU"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/gpu/da.py#L22-L144 |
227,087 | rflamary/POT | ot/datasets.py | get_2D_samples_gauss | def get_2D_samples_gauss(n, m, sigma, random_state=None):
""" Deprecated see make_2D_samples_gauss """
return make_2D_samples_gauss(n, m, sigma, random_state=None) | python | def get_2D_samples_gauss(n, m, sigma, random_state=None):
""" Deprecated see make_2D_samples_gauss """
return make_2D_samples_gauss(n, m, sigma, random_state=None) | [
"def",
"get_2D_samples_gauss",
"(",
"n",
",",
"m",
",",
"sigma",
",",
"random_state",
"=",
"None",
")",
":",
"return",
"make_2D_samples_gauss",
"(",
"n",
",",
"m",
",",
"sigma",
",",
"random_state",
"=",
"None",
")"
] | Deprecated see make_2D_samples_gauss | [
"Deprecated",
"see",
"make_2D_samples_gauss"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/datasets.py#L83-L85 |
227,088 | rflamary/POT | ot/datasets.py | get_data_classif | def get_data_classif(dataset, n, nz=.5, theta=0, random_state=None, **kwargs):
""" Deprecated see make_data_classif """
return make_data_classif(dataset, n, nz=.5, theta=0, random_state=None, **kwargs) | python | def get_data_classif(dataset, n, nz=.5, theta=0, random_state=None, **kwargs):
""" Deprecated see make_data_classif """
return make_data_classif(dataset, n, nz=.5, theta=0, random_state=None, **kwargs) | [
"def",
"get_data_classif",
"(",
"dataset",
",",
"n",
",",
"nz",
"=",
".5",
",",
"theta",
"=",
"0",
",",
"random_state",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"make_data_classif",
"(",
"dataset",
",",
"n",
",",
"nz",
"=",
".5",
",",
"theta",
"=",
"0",
",",
"random_state",
"=",
"None",
",",
"*",
"*",
"kwargs",
")"
] | Deprecated see make_data_classif | [
"Deprecated",
"see",
"make_data_classif"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/datasets.py#L170-L172 |
227,089 | rflamary/POT | ot/bregman.py | sinkhorn | def sinkhorn(a, b, M, reg, method='sinkhorn', numItermax=1000,
stopThr=1e-9, verbose=False, log=False, **kwargs):
u"""
Solve the entropic regularization optimal transport problem and return the OT matrix
The function solves the following optimization problem:
.. math::
\gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma)
s.t. \gamma 1 = a
\gamma^T 1= b
\gamma\geq 0
where :
- M is the (ns,nt) metric cost matrix
- :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
- a and b are source and target weights (sum to 1)
The algorithm used for solving the problem is the Sinkhorn-Knopp matrix scaling algorithm as proposed in [2]_
Parameters
----------
a : np.ndarray (ns,)
samples weights in the source domain
b : np.ndarray (nt,) or np.ndarray (nt,nbb)
samples in the target domain, compute sinkhorn with multiple targets
and fixed M if b is a matrix (return OT loss + dual variables in log)
M : np.ndarray (ns,nt)
loss matrix
reg : float
Regularization term >0
method : str
method used for the solver either 'sinkhorn', 'greenkhorn', 'sinkhorn_stabilized' or
'sinkhorn_epsilon_scaling', see those function for specific parameters
numItermax : int, optional
Max number of iterations
stopThr : float, optional
Stop threshol on error (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
gamma : (ns x nt) ndarray
Optimal transportation matrix for the given parameters
log : dict
log dictionary return only if log==True in parameters
Examples
--------
>>> import ot
>>> a=[.5,.5]
>>> b=[.5,.5]
>>> M=[[0.,1.],[1.,0.]]
>>> ot.sinkhorn(a,b,M,1)
array([[ 0.36552929, 0.13447071],
[ 0.13447071, 0.36552929]])
References
----------
.. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013
.. [9] Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms for Entropy Regularized Transport Problems. arXiv preprint arXiv:1610.06519.
.. [10] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). Scaling algorithms for unbalanced transport problems. arXiv preprint arXiv:1607.05816.
See Also
--------
ot.lp.emd : Unregularized OT
ot.optim.cg : General regularized OT
ot.bregman.sinkhorn_knopp : Classic Sinkhorn [2]
ot.bregman.sinkhorn_stabilized: Stabilized sinkhorn [9][10]
ot.bregman.sinkhorn_epsilon_scaling: Sinkhorn with epslilon scaling [9][10]
"""
if method.lower() == 'sinkhorn':
def sink():
return sinkhorn_knopp(a, b, M, reg, numItermax=numItermax,
stopThr=stopThr, verbose=verbose, log=log, **kwargs)
elif method.lower() == 'greenkhorn':
def sink():
return greenkhorn(a, b, M, reg, numItermax=numItermax,
stopThr=stopThr, verbose=verbose, log=log)
elif method.lower() == 'sinkhorn_stabilized':
def sink():
return sinkhorn_stabilized(a, b, M, reg, numItermax=numItermax,
stopThr=stopThr, verbose=verbose, log=log, **kwargs)
elif method.lower() == 'sinkhorn_epsilon_scaling':
def sink():
return sinkhorn_epsilon_scaling(
a, b, M, reg, numItermax=numItermax,
stopThr=stopThr, verbose=verbose, log=log, **kwargs)
else:
print('Warning : unknown method using classic Sinkhorn Knopp')
def sink():
return sinkhorn_knopp(a, b, M, reg, numItermax=numItermax,
stopThr=stopThr, verbose=verbose, log=log, **kwargs)
return sink() | python | def sinkhorn(a, b, M, reg, method='sinkhorn', numItermax=1000,
stopThr=1e-9, verbose=False, log=False, **kwargs):
u"""
Solve the entropic regularization optimal transport problem and return the OT matrix
The function solves the following optimization problem:
.. math::
\gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma)
s.t. \gamma 1 = a
\gamma^T 1= b
\gamma\geq 0
where :
- M is the (ns,nt) metric cost matrix
- :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
- a and b are source and target weights (sum to 1)
The algorithm used for solving the problem is the Sinkhorn-Knopp matrix scaling algorithm as proposed in [2]_
Parameters
----------
a : np.ndarray (ns,)
samples weights in the source domain
b : np.ndarray (nt,) or np.ndarray (nt,nbb)
samples in the target domain, compute sinkhorn with multiple targets
and fixed M if b is a matrix (return OT loss + dual variables in log)
M : np.ndarray (ns,nt)
loss matrix
reg : float
Regularization term >0
method : str
method used for the solver either 'sinkhorn', 'greenkhorn', 'sinkhorn_stabilized' or
'sinkhorn_epsilon_scaling', see those function for specific parameters
numItermax : int, optional
Max number of iterations
stopThr : float, optional
Stop threshol on error (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
gamma : (ns x nt) ndarray
Optimal transportation matrix for the given parameters
log : dict
log dictionary return only if log==True in parameters
Examples
--------
>>> import ot
>>> a=[.5,.5]
>>> b=[.5,.5]
>>> M=[[0.,1.],[1.,0.]]
>>> ot.sinkhorn(a,b,M,1)
array([[ 0.36552929, 0.13447071],
[ 0.13447071, 0.36552929]])
References
----------
.. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013
.. [9] Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms for Entropy Regularized Transport Problems. arXiv preprint arXiv:1610.06519.
.. [10] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). Scaling algorithms for unbalanced transport problems. arXiv preprint arXiv:1607.05816.
See Also
--------
ot.lp.emd : Unregularized OT
ot.optim.cg : General regularized OT
ot.bregman.sinkhorn_knopp : Classic Sinkhorn [2]
ot.bregman.sinkhorn_stabilized: Stabilized sinkhorn [9][10]
ot.bregman.sinkhorn_epsilon_scaling: Sinkhorn with epslilon scaling [9][10]
"""
if method.lower() == 'sinkhorn':
def sink():
return sinkhorn_knopp(a, b, M, reg, numItermax=numItermax,
stopThr=stopThr, verbose=verbose, log=log, **kwargs)
elif method.lower() == 'greenkhorn':
def sink():
return greenkhorn(a, b, M, reg, numItermax=numItermax,
stopThr=stopThr, verbose=verbose, log=log)
elif method.lower() == 'sinkhorn_stabilized':
def sink():
return sinkhorn_stabilized(a, b, M, reg, numItermax=numItermax,
stopThr=stopThr, verbose=verbose, log=log, **kwargs)
elif method.lower() == 'sinkhorn_epsilon_scaling':
def sink():
return sinkhorn_epsilon_scaling(
a, b, M, reg, numItermax=numItermax,
stopThr=stopThr, verbose=verbose, log=log, **kwargs)
else:
print('Warning : unknown method using classic Sinkhorn Knopp')
def sink():
return sinkhorn_knopp(a, b, M, reg, numItermax=numItermax,
stopThr=stopThr, verbose=verbose, log=log, **kwargs)
return sink() | [
"def",
"sinkhorn",
"(",
"a",
",",
"b",
",",
"M",
",",
"reg",
",",
"method",
"=",
"'sinkhorn'",
",",
"numItermax",
"=",
"1000",
",",
"stopThr",
"=",
"1e-9",
",",
"verbose",
"=",
"False",
",",
"log",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"method",
".",
"lower",
"(",
")",
"==",
"'sinkhorn'",
":",
"def",
"sink",
"(",
")",
":",
"return",
"sinkhorn_knopp",
"(",
"a",
",",
"b",
",",
"M",
",",
"reg",
",",
"numItermax",
"=",
"numItermax",
",",
"stopThr",
"=",
"stopThr",
",",
"verbose",
"=",
"verbose",
",",
"log",
"=",
"log",
",",
"*",
"*",
"kwargs",
")",
"elif",
"method",
".",
"lower",
"(",
")",
"==",
"'greenkhorn'",
":",
"def",
"sink",
"(",
")",
":",
"return",
"greenkhorn",
"(",
"a",
",",
"b",
",",
"M",
",",
"reg",
",",
"numItermax",
"=",
"numItermax",
",",
"stopThr",
"=",
"stopThr",
",",
"verbose",
"=",
"verbose",
",",
"log",
"=",
"log",
")",
"elif",
"method",
".",
"lower",
"(",
")",
"==",
"'sinkhorn_stabilized'",
":",
"def",
"sink",
"(",
")",
":",
"return",
"sinkhorn_stabilized",
"(",
"a",
",",
"b",
",",
"M",
",",
"reg",
",",
"numItermax",
"=",
"numItermax",
",",
"stopThr",
"=",
"stopThr",
",",
"verbose",
"=",
"verbose",
",",
"log",
"=",
"log",
",",
"*",
"*",
"kwargs",
")",
"elif",
"method",
".",
"lower",
"(",
")",
"==",
"'sinkhorn_epsilon_scaling'",
":",
"def",
"sink",
"(",
")",
":",
"return",
"sinkhorn_epsilon_scaling",
"(",
"a",
",",
"b",
",",
"M",
",",
"reg",
",",
"numItermax",
"=",
"numItermax",
",",
"stopThr",
"=",
"stopThr",
",",
"verbose",
"=",
"verbose",
",",
"log",
"=",
"log",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"print",
"(",
"'Warning : unknown method using classic Sinkhorn Knopp'",
")",
"def",
"sink",
"(",
")",
":",
"return",
"sinkhorn_knopp",
"(",
"a",
",",
"b",
",",
"M",
",",
"reg",
",",
"numItermax",
"=",
"numItermax",
",",
"stopThr",
"=",
"stopThr",
",",
"verbose",
"=",
"verbose",
",",
"log",
"=",
"log",
",",
"*",
"*",
"kwargs",
")",
"return",
"sink",
"(",
")"
] | u"""
Solve the entropic regularization optimal transport problem and return the OT matrix
The function solves the following optimization problem:
.. math::
\gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma)
s.t. \gamma 1 = a
\gamma^T 1= b
\gamma\geq 0
where :
- M is the (ns,nt) metric cost matrix
- :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
- a and b are source and target weights (sum to 1)
The algorithm used for solving the problem is the Sinkhorn-Knopp matrix scaling algorithm as proposed in [2]_
Parameters
----------
a : np.ndarray (ns,)
samples weights in the source domain
b : np.ndarray (nt,) or np.ndarray (nt,nbb)
samples in the target domain, compute sinkhorn with multiple targets
and fixed M if b is a matrix (return OT loss + dual variables in log)
M : np.ndarray (ns,nt)
loss matrix
reg : float
Regularization term >0
method : str
method used for the solver either 'sinkhorn', 'greenkhorn', 'sinkhorn_stabilized' or
'sinkhorn_epsilon_scaling', see those function for specific parameters
numItermax : int, optional
Max number of iterations
stopThr : float, optional
Stop threshol on error (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
gamma : (ns x nt) ndarray
Optimal transportation matrix for the given parameters
log : dict
log dictionary return only if log==True in parameters
Examples
--------
>>> import ot
>>> a=[.5,.5]
>>> b=[.5,.5]
>>> M=[[0.,1.],[1.,0.]]
>>> ot.sinkhorn(a,b,M,1)
array([[ 0.36552929, 0.13447071],
[ 0.13447071, 0.36552929]])
References
----------
.. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013
.. [9] Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms for Entropy Regularized Transport Problems. arXiv preprint arXiv:1610.06519.
.. [10] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). Scaling algorithms for unbalanced transport problems. arXiv preprint arXiv:1607.05816.
See Also
--------
ot.lp.emd : Unregularized OT
ot.optim.cg : General regularized OT
ot.bregman.sinkhorn_knopp : Classic Sinkhorn [2]
ot.bregman.sinkhorn_stabilized: Stabilized sinkhorn [9][10]
ot.bregman.sinkhorn_epsilon_scaling: Sinkhorn with epslilon scaling [9][10] | [
"u",
"Solve",
"the",
"entropic",
"regularization",
"optimal",
"transport",
"problem",
"and",
"return",
"the",
"OT",
"matrix"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/bregman.py#L16-L128 |
227,090 | rflamary/POT | ot/bregman.py | sinkhorn2 | def sinkhorn2(a, b, M, reg, method='sinkhorn', numItermax=1000,
stopThr=1e-9, verbose=False, log=False, **kwargs):
u"""
Solve the entropic regularization optimal transport problem and return the loss
The function solves the following optimization problem:
.. math::
W = \min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma)
s.t. \gamma 1 = a
\gamma^T 1= b
\gamma\geq 0
where :
- M is the (ns,nt) metric cost matrix
- :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
- a and b are source and target weights (sum to 1)
The algorithm used for solving the problem is the Sinkhorn-Knopp matrix scaling algorithm as proposed in [2]_
Parameters
----------
a : np.ndarray (ns,)
samples weights in the source domain
b : np.ndarray (nt,) or np.ndarray (nt,nbb)
samples in the target domain, compute sinkhorn with multiple targets
and fixed M if b is a matrix (return OT loss + dual variables in log)
M : np.ndarray (ns,nt)
loss matrix
reg : float
Regularization term >0
method : str
method used for the solver either 'sinkhorn', 'sinkhorn_stabilized' or
'sinkhorn_epsilon_scaling', see those function for specific parameters
numItermax : int, optional
Max number of iterations
stopThr : float, optional
Stop threshol on error (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
W : (nt) ndarray or float
Optimal transportation matrix for the given parameters
log : dict
log dictionary return only if log==True in parameters
Examples
--------
>>> import ot
>>> a=[.5,.5]
>>> b=[.5,.5]
>>> M=[[0.,1.],[1.,0.]]
>>> ot.sinkhorn2(a,b,M,1)
array([ 0.26894142])
References
----------
.. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013
.. [9] Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms for Entropy Regularized Transport Problems. arXiv preprint arXiv:1610.06519.
.. [10] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). Scaling algorithms for unbalanced transport problems. arXiv preprint arXiv:1607.05816.
[21] Altschuler J., Weed J., Rigollet P. : Near-linear time approximation algorithms for optimal transport via Sinkhorn iteration, Advances in Neural Information Processing Systems (NIPS) 31, 2017
See Also
--------
ot.lp.emd : Unregularized OT
ot.optim.cg : General regularized OT
ot.bregman.sinkhorn_knopp : Classic Sinkhorn [2]
ot.bregman.greenkhorn : Greenkhorn [21]
ot.bregman.sinkhorn_stabilized: Stabilized sinkhorn [9][10]
ot.bregman.sinkhorn_epsilon_scaling: Sinkhorn with epslilon scaling [9][10]
"""
if method.lower() == 'sinkhorn':
def sink():
return sinkhorn_knopp(a, b, M, reg, numItermax=numItermax,
stopThr=stopThr, verbose=verbose, log=log, **kwargs)
elif method.lower() == 'sinkhorn_stabilized':
def sink():
return sinkhorn_stabilized(a, b, M, reg, numItermax=numItermax,
stopThr=stopThr, verbose=verbose, log=log, **kwargs)
elif method.lower() == 'sinkhorn_epsilon_scaling':
def sink():
return sinkhorn_epsilon_scaling(
a, b, M, reg, numItermax=numItermax,
stopThr=stopThr, verbose=verbose, log=log, **kwargs)
else:
print('Warning : unknown method using classic Sinkhorn Knopp')
def sink():
return sinkhorn_knopp(a, b, M, reg, **kwargs)
b = np.asarray(b, dtype=np.float64)
if len(b.shape) < 2:
b = b.reshape((-1, 1))
return sink() | python | def sinkhorn2(a, b, M, reg, method='sinkhorn', numItermax=1000,
stopThr=1e-9, verbose=False, log=False, **kwargs):
u"""
Solve the entropic regularization optimal transport problem and return the loss
The function solves the following optimization problem:
.. math::
W = \min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma)
s.t. \gamma 1 = a
\gamma^T 1= b
\gamma\geq 0
where :
- M is the (ns,nt) metric cost matrix
- :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
- a and b are source and target weights (sum to 1)
The algorithm used for solving the problem is the Sinkhorn-Knopp matrix scaling algorithm as proposed in [2]_
Parameters
----------
a : np.ndarray (ns,)
samples weights in the source domain
b : np.ndarray (nt,) or np.ndarray (nt,nbb)
samples in the target domain, compute sinkhorn with multiple targets
and fixed M if b is a matrix (return OT loss + dual variables in log)
M : np.ndarray (ns,nt)
loss matrix
reg : float
Regularization term >0
method : str
method used for the solver either 'sinkhorn', 'sinkhorn_stabilized' or
'sinkhorn_epsilon_scaling', see those function for specific parameters
numItermax : int, optional
Max number of iterations
stopThr : float, optional
Stop threshol on error (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
W : (nt) ndarray or float
Optimal transportation matrix for the given parameters
log : dict
log dictionary return only if log==True in parameters
Examples
--------
>>> import ot
>>> a=[.5,.5]
>>> b=[.5,.5]
>>> M=[[0.,1.],[1.,0.]]
>>> ot.sinkhorn2(a,b,M,1)
array([ 0.26894142])
References
----------
.. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013
.. [9] Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms for Entropy Regularized Transport Problems. arXiv preprint arXiv:1610.06519.
.. [10] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). Scaling algorithms for unbalanced transport problems. arXiv preprint arXiv:1607.05816.
[21] Altschuler J., Weed J., Rigollet P. : Near-linear time approximation algorithms for optimal transport via Sinkhorn iteration, Advances in Neural Information Processing Systems (NIPS) 31, 2017
See Also
--------
ot.lp.emd : Unregularized OT
ot.optim.cg : General regularized OT
ot.bregman.sinkhorn_knopp : Classic Sinkhorn [2]
ot.bregman.greenkhorn : Greenkhorn [21]
ot.bregman.sinkhorn_stabilized: Stabilized sinkhorn [9][10]
ot.bregman.sinkhorn_epsilon_scaling: Sinkhorn with epslilon scaling [9][10]
"""
if method.lower() == 'sinkhorn':
def sink():
return sinkhorn_knopp(a, b, M, reg, numItermax=numItermax,
stopThr=stopThr, verbose=verbose, log=log, **kwargs)
elif method.lower() == 'sinkhorn_stabilized':
def sink():
return sinkhorn_stabilized(a, b, M, reg, numItermax=numItermax,
stopThr=stopThr, verbose=verbose, log=log, **kwargs)
elif method.lower() == 'sinkhorn_epsilon_scaling':
def sink():
return sinkhorn_epsilon_scaling(
a, b, M, reg, numItermax=numItermax,
stopThr=stopThr, verbose=verbose, log=log, **kwargs)
else:
print('Warning : unknown method using classic Sinkhorn Knopp')
def sink():
return sinkhorn_knopp(a, b, M, reg, **kwargs)
b = np.asarray(b, dtype=np.float64)
if len(b.shape) < 2:
b = b.reshape((-1, 1))
return sink() | [
"def",
"sinkhorn2",
"(",
"a",
",",
"b",
",",
"M",
",",
"reg",
",",
"method",
"=",
"'sinkhorn'",
",",
"numItermax",
"=",
"1000",
",",
"stopThr",
"=",
"1e-9",
",",
"verbose",
"=",
"False",
",",
"log",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"method",
".",
"lower",
"(",
")",
"==",
"'sinkhorn'",
":",
"def",
"sink",
"(",
")",
":",
"return",
"sinkhorn_knopp",
"(",
"a",
",",
"b",
",",
"M",
",",
"reg",
",",
"numItermax",
"=",
"numItermax",
",",
"stopThr",
"=",
"stopThr",
",",
"verbose",
"=",
"verbose",
",",
"log",
"=",
"log",
",",
"*",
"*",
"kwargs",
")",
"elif",
"method",
".",
"lower",
"(",
")",
"==",
"'sinkhorn_stabilized'",
":",
"def",
"sink",
"(",
")",
":",
"return",
"sinkhorn_stabilized",
"(",
"a",
",",
"b",
",",
"M",
",",
"reg",
",",
"numItermax",
"=",
"numItermax",
",",
"stopThr",
"=",
"stopThr",
",",
"verbose",
"=",
"verbose",
",",
"log",
"=",
"log",
",",
"*",
"*",
"kwargs",
")",
"elif",
"method",
".",
"lower",
"(",
")",
"==",
"'sinkhorn_epsilon_scaling'",
":",
"def",
"sink",
"(",
")",
":",
"return",
"sinkhorn_epsilon_scaling",
"(",
"a",
",",
"b",
",",
"M",
",",
"reg",
",",
"numItermax",
"=",
"numItermax",
",",
"stopThr",
"=",
"stopThr",
",",
"verbose",
"=",
"verbose",
",",
"log",
"=",
"log",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"print",
"(",
"'Warning : unknown method using classic Sinkhorn Knopp'",
")",
"def",
"sink",
"(",
")",
":",
"return",
"sinkhorn_knopp",
"(",
"a",
",",
"b",
",",
"M",
",",
"reg",
",",
"*",
"*",
"kwargs",
")",
"b",
"=",
"np",
".",
"asarray",
"(",
"b",
",",
"dtype",
"=",
"np",
".",
"float64",
")",
"if",
"len",
"(",
"b",
".",
"shape",
")",
"<",
"2",
":",
"b",
"=",
"b",
".",
"reshape",
"(",
"(",
"-",
"1",
",",
"1",
")",
")",
"return",
"sink",
"(",
")"
] | u"""
Solve the entropic regularization optimal transport problem and return the loss
The function solves the following optimization problem:
.. math::
W = \min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma)
s.t. \gamma 1 = a
\gamma^T 1= b
\gamma\geq 0
where :
- M is the (ns,nt) metric cost matrix
- :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
- a and b are source and target weights (sum to 1)
The algorithm used for solving the problem is the Sinkhorn-Knopp matrix scaling algorithm as proposed in [2]_
Parameters
----------
a : np.ndarray (ns,)
samples weights in the source domain
b : np.ndarray (nt,) or np.ndarray (nt,nbb)
samples in the target domain, compute sinkhorn with multiple targets
and fixed M if b is a matrix (return OT loss + dual variables in log)
M : np.ndarray (ns,nt)
loss matrix
reg : float
Regularization term >0
method : str
method used for the solver either 'sinkhorn', 'sinkhorn_stabilized' or
'sinkhorn_epsilon_scaling', see those function for specific parameters
numItermax : int, optional
Max number of iterations
stopThr : float, optional
Stop threshol on error (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
W : (nt) ndarray or float
Optimal transportation matrix for the given parameters
log : dict
log dictionary return only if log==True in parameters
Examples
--------
>>> import ot
>>> a=[.5,.5]
>>> b=[.5,.5]
>>> M=[[0.,1.],[1.,0.]]
>>> ot.sinkhorn2(a,b,M,1)
array([ 0.26894142])
References
----------
.. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013
.. [9] Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms for Entropy Regularized Transport Problems. arXiv preprint arXiv:1610.06519.
.. [10] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). Scaling algorithms for unbalanced transport problems. arXiv preprint arXiv:1607.05816.
[21] Altschuler J., Weed J., Rigollet P. : Near-linear time approximation algorithms for optimal transport via Sinkhorn iteration, Advances in Neural Information Processing Systems (NIPS) 31, 2017
See Also
--------
ot.lp.emd : Unregularized OT
ot.optim.cg : General regularized OT
ot.bregman.sinkhorn_knopp : Classic Sinkhorn [2]
ot.bregman.greenkhorn : Greenkhorn [21]
ot.bregman.sinkhorn_stabilized: Stabilized sinkhorn [9][10]
ot.bregman.sinkhorn_epsilon_scaling: Sinkhorn with epslilon scaling [9][10] | [
"u",
"Solve",
"the",
"entropic",
"regularization",
"optimal",
"transport",
"problem",
"and",
"return",
"the",
"loss"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/bregman.py#L131-L245 |
227,091 | rflamary/POT | ot/bregman.py | geometricBar | def geometricBar(weights, alldistribT):
"""return the weighted geometric mean of distributions"""
assert(len(weights) == alldistribT.shape[1])
return np.exp(np.dot(np.log(alldistribT), weights.T)) | python | def geometricBar(weights, alldistribT):
"""return the weighted geometric mean of distributions"""
assert(len(weights) == alldistribT.shape[1])
return np.exp(np.dot(np.log(alldistribT), weights.T)) | [
"def",
"geometricBar",
"(",
"weights",
",",
"alldistribT",
")",
":",
"assert",
"(",
"len",
"(",
"weights",
")",
"==",
"alldistribT",
".",
"shape",
"[",
"1",
"]",
")",
"return",
"np",
".",
"exp",
"(",
"np",
".",
"dot",
"(",
"np",
".",
"log",
"(",
"alldistribT",
")",
",",
"weights",
".",
"T",
")",
")"
] | return the weighted geometric mean of distributions | [
"return",
"the",
"weighted",
"geometric",
"mean",
"of",
"distributions"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/bregman.py#L968-L971 |
227,092 | rflamary/POT | ot/bregman.py | geometricMean | def geometricMean(alldistribT):
"""return the geometric mean of distributions"""
return np.exp(np.mean(np.log(alldistribT), axis=1)) | python | def geometricMean(alldistribT):
"""return the geometric mean of distributions"""
return np.exp(np.mean(np.log(alldistribT), axis=1)) | [
"def",
"geometricMean",
"(",
"alldistribT",
")",
":",
"return",
"np",
".",
"exp",
"(",
"np",
".",
"mean",
"(",
"np",
".",
"log",
"(",
"alldistribT",
")",
",",
"axis",
"=",
"1",
")",
")"
] | return the geometric mean of distributions | [
"return",
"the",
"geometric",
"mean",
"of",
"distributions"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/bregman.py#L974-L976 |
227,093 | rflamary/POT | ot/bregman.py | projR | def projR(gamma, p):
"""return the KL projection on the row constrints """
return np.multiply(gamma.T, p / np.maximum(np.sum(gamma, axis=1), 1e-10)).T | python | def projR(gamma, p):
"""return the KL projection on the row constrints """
return np.multiply(gamma.T, p / np.maximum(np.sum(gamma, axis=1), 1e-10)).T | [
"def",
"projR",
"(",
"gamma",
",",
"p",
")",
":",
"return",
"np",
".",
"multiply",
"(",
"gamma",
".",
"T",
",",
"p",
"/",
"np",
".",
"maximum",
"(",
"np",
".",
"sum",
"(",
"gamma",
",",
"axis",
"=",
"1",
")",
",",
"1e-10",
")",
")",
".",
"T"
] | return the KL projection on the row constrints | [
"return",
"the",
"KL",
"projection",
"on",
"the",
"row",
"constrints"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/bregman.py#L979-L981 |
227,094 | rflamary/POT | ot/bregman.py | projC | def projC(gamma, q):
"""return the KL projection on the column constrints """
return np.multiply(gamma, q / np.maximum(np.sum(gamma, axis=0), 1e-10)) | python | def projC(gamma, q):
"""return the KL projection on the column constrints """
return np.multiply(gamma, q / np.maximum(np.sum(gamma, axis=0), 1e-10)) | [
"def",
"projC",
"(",
"gamma",
",",
"q",
")",
":",
"return",
"np",
".",
"multiply",
"(",
"gamma",
",",
"q",
"/",
"np",
".",
"maximum",
"(",
"np",
".",
"sum",
"(",
"gamma",
",",
"axis",
"=",
"0",
")",
",",
"1e-10",
")",
")"
] | return the KL projection on the column constrints | [
"return",
"the",
"KL",
"projection",
"on",
"the",
"column",
"constrints"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/bregman.py#L984-L986 |
227,095 | rflamary/POT | ot/bregman.py | barycenter | def barycenter(A, M, reg, weights=None, numItermax=1000,
stopThr=1e-4, verbose=False, log=False):
"""Compute the entropic regularized wasserstein barycenter of distributions A
The function solves the following optimization problem:
.. math::
\mathbf{a} = arg\min_\mathbf{a} \sum_i W_{reg}(\mathbf{a},\mathbf{a}_i)
where :
- :math:`W_{reg}(\cdot,\cdot)` is the entropic regularized Wasserstein distance (see ot.bregman.sinkhorn)
- :math:`\mathbf{a}_i` are training distributions in the columns of matrix :math:`\mathbf{A}`
- reg and :math:`\mathbf{M}` are respectively the regularization term and the cost matrix for OT
The algorithm used for solving the problem is the Sinkhorn-Knopp matrix scaling algorithm as proposed in [3]_
Parameters
----------
A : np.ndarray (d,n)
n training distributions a_i of size d
M : np.ndarray (d,d)
loss matrix for OT
reg : float
Regularization term >0
weights : np.ndarray (n,)
Weights of each histogram a_i on the simplex (barycentric coodinates)
numItermax : int, optional
Max number of iterations
stopThr : float, optional
Stop threshol on error (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
a : (d,) ndarray
Wasserstein barycenter
log : dict
log dictionary return only if log==True in parameters
References
----------
.. [3] Benamou, J. D., Carlier, G., Cuturi, M., Nenna, L., & Peyré, G. (2015). Iterative Bregman projections for regularized transportation problems. SIAM Journal on Scientific Computing, 37(2), A1111-A1138.
"""
if weights is None:
weights = np.ones(A.shape[1]) / A.shape[1]
else:
assert(len(weights) == A.shape[1])
if log:
log = {'err': []}
# M = M/np.median(M) # suggested by G. Peyre
K = np.exp(-M / reg)
cpt = 0
err = 1
UKv = np.dot(K, np.divide(A.T, np.sum(K, axis=0)).T)
u = (geometricMean(UKv) / UKv.T).T
while (err > stopThr and cpt < numItermax):
cpt = cpt + 1
UKv = u * np.dot(K, np.divide(A, np.dot(K, u)))
u = (u.T * geometricBar(weights, UKv)).T / UKv
if cpt % 10 == 1:
err = np.sum(np.std(UKv, axis=1))
# log and verbose print
if log:
log['err'].append(err)
if verbose:
if cpt % 200 == 0:
print(
'{:5s}|{:12s}'.format('It.', 'Err') + '\n' + '-' * 19)
print('{:5d}|{:8e}|'.format(cpt, err))
if log:
log['niter'] = cpt
return geometricBar(weights, UKv), log
else:
return geometricBar(weights, UKv) | python | def barycenter(A, M, reg, weights=None, numItermax=1000,
stopThr=1e-4, verbose=False, log=False):
"""Compute the entropic regularized wasserstein barycenter of distributions A
The function solves the following optimization problem:
.. math::
\mathbf{a} = arg\min_\mathbf{a} \sum_i W_{reg}(\mathbf{a},\mathbf{a}_i)
where :
- :math:`W_{reg}(\cdot,\cdot)` is the entropic regularized Wasserstein distance (see ot.bregman.sinkhorn)
- :math:`\mathbf{a}_i` are training distributions in the columns of matrix :math:`\mathbf{A}`
- reg and :math:`\mathbf{M}` are respectively the regularization term and the cost matrix for OT
The algorithm used for solving the problem is the Sinkhorn-Knopp matrix scaling algorithm as proposed in [3]_
Parameters
----------
A : np.ndarray (d,n)
n training distributions a_i of size d
M : np.ndarray (d,d)
loss matrix for OT
reg : float
Regularization term >0
weights : np.ndarray (n,)
Weights of each histogram a_i on the simplex (barycentric coodinates)
numItermax : int, optional
Max number of iterations
stopThr : float, optional
Stop threshol on error (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
a : (d,) ndarray
Wasserstein barycenter
log : dict
log dictionary return only if log==True in parameters
References
----------
.. [3] Benamou, J. D., Carlier, G., Cuturi, M., Nenna, L., & Peyré, G. (2015). Iterative Bregman projections for regularized transportation problems. SIAM Journal on Scientific Computing, 37(2), A1111-A1138.
"""
if weights is None:
weights = np.ones(A.shape[1]) / A.shape[1]
else:
assert(len(weights) == A.shape[1])
if log:
log = {'err': []}
# M = M/np.median(M) # suggested by G. Peyre
K = np.exp(-M / reg)
cpt = 0
err = 1
UKv = np.dot(K, np.divide(A.T, np.sum(K, axis=0)).T)
u = (geometricMean(UKv) / UKv.T).T
while (err > stopThr and cpt < numItermax):
cpt = cpt + 1
UKv = u * np.dot(K, np.divide(A, np.dot(K, u)))
u = (u.T * geometricBar(weights, UKv)).T / UKv
if cpt % 10 == 1:
err = np.sum(np.std(UKv, axis=1))
# log and verbose print
if log:
log['err'].append(err)
if verbose:
if cpt % 200 == 0:
print(
'{:5s}|{:12s}'.format('It.', 'Err') + '\n' + '-' * 19)
print('{:5d}|{:8e}|'.format(cpt, err))
if log:
log['niter'] = cpt
return geometricBar(weights, UKv), log
else:
return geometricBar(weights, UKv) | [
"def",
"barycenter",
"(",
"A",
",",
"M",
",",
"reg",
",",
"weights",
"=",
"None",
",",
"numItermax",
"=",
"1000",
",",
"stopThr",
"=",
"1e-4",
",",
"verbose",
"=",
"False",
",",
"log",
"=",
"False",
")",
":",
"if",
"weights",
"is",
"None",
":",
"weights",
"=",
"np",
".",
"ones",
"(",
"A",
".",
"shape",
"[",
"1",
"]",
")",
"/",
"A",
".",
"shape",
"[",
"1",
"]",
"else",
":",
"assert",
"(",
"len",
"(",
"weights",
")",
"==",
"A",
".",
"shape",
"[",
"1",
"]",
")",
"if",
"log",
":",
"log",
"=",
"{",
"'err'",
":",
"[",
"]",
"}",
"# M = M/np.median(M) # suggested by G. Peyre",
"K",
"=",
"np",
".",
"exp",
"(",
"-",
"M",
"/",
"reg",
")",
"cpt",
"=",
"0",
"err",
"=",
"1",
"UKv",
"=",
"np",
".",
"dot",
"(",
"K",
",",
"np",
".",
"divide",
"(",
"A",
".",
"T",
",",
"np",
".",
"sum",
"(",
"K",
",",
"axis",
"=",
"0",
")",
")",
".",
"T",
")",
"u",
"=",
"(",
"geometricMean",
"(",
"UKv",
")",
"/",
"UKv",
".",
"T",
")",
".",
"T",
"while",
"(",
"err",
">",
"stopThr",
"and",
"cpt",
"<",
"numItermax",
")",
":",
"cpt",
"=",
"cpt",
"+",
"1",
"UKv",
"=",
"u",
"*",
"np",
".",
"dot",
"(",
"K",
",",
"np",
".",
"divide",
"(",
"A",
",",
"np",
".",
"dot",
"(",
"K",
",",
"u",
")",
")",
")",
"u",
"=",
"(",
"u",
".",
"T",
"*",
"geometricBar",
"(",
"weights",
",",
"UKv",
")",
")",
".",
"T",
"/",
"UKv",
"if",
"cpt",
"%",
"10",
"==",
"1",
":",
"err",
"=",
"np",
".",
"sum",
"(",
"np",
".",
"std",
"(",
"UKv",
",",
"axis",
"=",
"1",
")",
")",
"# log and verbose print",
"if",
"log",
":",
"log",
"[",
"'err'",
"]",
".",
"append",
"(",
"err",
")",
"if",
"verbose",
":",
"if",
"cpt",
"%",
"200",
"==",
"0",
":",
"print",
"(",
"'{:5s}|{:12s}'",
".",
"format",
"(",
"'It.'",
",",
"'Err'",
")",
"+",
"'\\n'",
"+",
"'-'",
"*",
"19",
")",
"print",
"(",
"'{:5d}|{:8e}|'",
".",
"format",
"(",
"cpt",
",",
"err",
")",
")",
"if",
"log",
":",
"log",
"[",
"'niter'",
"]",
"=",
"cpt",
"return",
"geometricBar",
"(",
"weights",
",",
"UKv",
")",
",",
"log",
"else",
":",
"return",
"geometricBar",
"(",
"weights",
",",
"UKv",
")"
] | Compute the entropic regularized wasserstein barycenter of distributions A
The function solves the following optimization problem:
.. math::
\mathbf{a} = arg\min_\mathbf{a} \sum_i W_{reg}(\mathbf{a},\mathbf{a}_i)
where :
- :math:`W_{reg}(\cdot,\cdot)` is the entropic regularized Wasserstein distance (see ot.bregman.sinkhorn)
- :math:`\mathbf{a}_i` are training distributions in the columns of matrix :math:`\mathbf{A}`
- reg and :math:`\mathbf{M}` are respectively the regularization term and the cost matrix for OT
The algorithm used for solving the problem is the Sinkhorn-Knopp matrix scaling algorithm as proposed in [3]_
Parameters
----------
A : np.ndarray (d,n)
n training distributions a_i of size d
M : np.ndarray (d,d)
loss matrix for OT
reg : float
Regularization term >0
weights : np.ndarray (n,)
Weights of each histogram a_i on the simplex (barycentric coodinates)
numItermax : int, optional
Max number of iterations
stopThr : float, optional
Stop threshol on error (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
a : (d,) ndarray
Wasserstein barycenter
log : dict
log dictionary return only if log==True in parameters
References
----------
.. [3] Benamou, J. D., Carlier, G., Cuturi, M., Nenna, L., & Peyré, G. (2015). Iterative Bregman projections for regularized transportation problems. SIAM Journal on Scientific Computing, 37(2), A1111-A1138. | [
"Compute",
"the",
"entropic",
"regularized",
"wasserstein",
"barycenter",
"of",
"distributions",
"A"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/bregman.py#L989-L1082 |
227,096 | rflamary/POT | ot/bregman.py | convolutional_barycenter2d | def convolutional_barycenter2d(A, reg, weights=None, numItermax=10000, stopThr=1e-9, stabThr=1e-30, verbose=False, log=False):
"""Compute the entropic regularized wasserstein barycenter of distributions A
where A is a collection of 2D images.
The function solves the following optimization problem:
.. math::
\mathbf{a} = arg\min_\mathbf{a} \sum_i W_{reg}(\mathbf{a},\mathbf{a}_i)
where :
- :math:`W_{reg}(\cdot,\cdot)` is the entropic regularized Wasserstein distance (see ot.bregman.sinkhorn)
- :math:`\mathbf{a}_i` are training distributions (2D images) in the mast two dimensions of matrix :math:`\mathbf{A}`
- reg is the regularization strength scalar value
The algorithm used for solving the problem is the Sinkhorn-Knopp matrix scaling algorithm as proposed in [21]_
Parameters
----------
A : np.ndarray (n,w,h)
n distributions (2D images) of size w x h
reg : float
Regularization term >0
weights : np.ndarray (n,)
Weights of each image on the simplex (barycentric coodinates)
numItermax : int, optional
Max number of iterations
stopThr : float, optional
Stop threshol on error (>0)
stabThr : float, optional
Stabilization threshold to avoid numerical precision issue
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
a : (w,h) ndarray
2D Wasserstein barycenter
log : dict
log dictionary return only if log==True in parameters
References
----------
.. [21] Solomon, J., De Goes, F., Peyré, G., Cuturi, M., Butscher, A., Nguyen, A. & Guibas, L. (2015).
Convolutional wasserstein distances: Efficient optimal transportation on geometric domains
ACM Transactions on Graphics (TOG), 34(4), 66
"""
if weights is None:
weights = np.ones(A.shape[0]) / A.shape[0]
else:
assert(len(weights) == A.shape[0])
if log:
log = {'err': []}
b = np.zeros_like(A[0, :, :])
U = np.ones_like(A)
KV = np.ones_like(A)
cpt = 0
err = 1
# build the convolution operator
t = np.linspace(0, 1, A.shape[1])
[Y, X] = np.meshgrid(t, t)
xi1 = np.exp(-(X - Y)**2 / reg)
def K(x):
return np.dot(np.dot(xi1, x), xi1)
while (err > stopThr and cpt < numItermax):
bold = b
cpt = cpt + 1
b = np.zeros_like(A[0, :, :])
for r in range(A.shape[0]):
KV[r, :, :] = K(A[r, :, :] / np.maximum(stabThr, K(U[r, :, :])))
b += weights[r] * np.log(np.maximum(stabThr, U[r, :, :] * KV[r, :, :]))
b = np.exp(b)
for r in range(A.shape[0]):
U[r, :, :] = b / np.maximum(stabThr, KV[r, :, :])
if cpt % 10 == 1:
err = np.sum(np.abs(bold - b))
# log and verbose print
if log:
log['err'].append(err)
if verbose:
if cpt % 200 == 0:
print('{:5s}|{:12s}'.format('It.', 'Err') + '\n' + '-' * 19)
print('{:5d}|{:8e}|'.format(cpt, err))
if log:
log['niter'] = cpt
log['U'] = U
return b, log
else:
return b | python | def convolutional_barycenter2d(A, reg, weights=None, numItermax=10000, stopThr=1e-9, stabThr=1e-30, verbose=False, log=False):
"""Compute the entropic regularized wasserstein barycenter of distributions A
where A is a collection of 2D images.
The function solves the following optimization problem:
.. math::
\mathbf{a} = arg\min_\mathbf{a} \sum_i W_{reg}(\mathbf{a},\mathbf{a}_i)
where :
- :math:`W_{reg}(\cdot,\cdot)` is the entropic regularized Wasserstein distance (see ot.bregman.sinkhorn)
- :math:`\mathbf{a}_i` are training distributions (2D images) in the mast two dimensions of matrix :math:`\mathbf{A}`
- reg is the regularization strength scalar value
The algorithm used for solving the problem is the Sinkhorn-Knopp matrix scaling algorithm as proposed in [21]_
Parameters
----------
A : np.ndarray (n,w,h)
n distributions (2D images) of size w x h
reg : float
Regularization term >0
weights : np.ndarray (n,)
Weights of each image on the simplex (barycentric coodinates)
numItermax : int, optional
Max number of iterations
stopThr : float, optional
Stop threshol on error (>0)
stabThr : float, optional
Stabilization threshold to avoid numerical precision issue
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
a : (w,h) ndarray
2D Wasserstein barycenter
log : dict
log dictionary return only if log==True in parameters
References
----------
.. [21] Solomon, J., De Goes, F., Peyré, G., Cuturi, M., Butscher, A., Nguyen, A. & Guibas, L. (2015).
Convolutional wasserstein distances: Efficient optimal transportation on geometric domains
ACM Transactions on Graphics (TOG), 34(4), 66
"""
if weights is None:
weights = np.ones(A.shape[0]) / A.shape[0]
else:
assert(len(weights) == A.shape[0])
if log:
log = {'err': []}
b = np.zeros_like(A[0, :, :])
U = np.ones_like(A)
KV = np.ones_like(A)
cpt = 0
err = 1
# build the convolution operator
t = np.linspace(0, 1, A.shape[1])
[Y, X] = np.meshgrid(t, t)
xi1 = np.exp(-(X - Y)**2 / reg)
def K(x):
return np.dot(np.dot(xi1, x), xi1)
while (err > stopThr and cpt < numItermax):
bold = b
cpt = cpt + 1
b = np.zeros_like(A[0, :, :])
for r in range(A.shape[0]):
KV[r, :, :] = K(A[r, :, :] / np.maximum(stabThr, K(U[r, :, :])))
b += weights[r] * np.log(np.maximum(stabThr, U[r, :, :] * KV[r, :, :]))
b = np.exp(b)
for r in range(A.shape[0]):
U[r, :, :] = b / np.maximum(stabThr, KV[r, :, :])
if cpt % 10 == 1:
err = np.sum(np.abs(bold - b))
# log and verbose print
if log:
log['err'].append(err)
if verbose:
if cpt % 200 == 0:
print('{:5s}|{:12s}'.format('It.', 'Err') + '\n' + '-' * 19)
print('{:5d}|{:8e}|'.format(cpt, err))
if log:
log['niter'] = cpt
log['U'] = U
return b, log
else:
return b | [
"def",
"convolutional_barycenter2d",
"(",
"A",
",",
"reg",
",",
"weights",
"=",
"None",
",",
"numItermax",
"=",
"10000",
",",
"stopThr",
"=",
"1e-9",
",",
"stabThr",
"=",
"1e-30",
",",
"verbose",
"=",
"False",
",",
"log",
"=",
"False",
")",
":",
"if",
"weights",
"is",
"None",
":",
"weights",
"=",
"np",
".",
"ones",
"(",
"A",
".",
"shape",
"[",
"0",
"]",
")",
"/",
"A",
".",
"shape",
"[",
"0",
"]",
"else",
":",
"assert",
"(",
"len",
"(",
"weights",
")",
"==",
"A",
".",
"shape",
"[",
"0",
"]",
")",
"if",
"log",
":",
"log",
"=",
"{",
"'err'",
":",
"[",
"]",
"}",
"b",
"=",
"np",
".",
"zeros_like",
"(",
"A",
"[",
"0",
",",
":",
",",
":",
"]",
")",
"U",
"=",
"np",
".",
"ones_like",
"(",
"A",
")",
"KV",
"=",
"np",
".",
"ones_like",
"(",
"A",
")",
"cpt",
"=",
"0",
"err",
"=",
"1",
"# build the convolution operator",
"t",
"=",
"np",
".",
"linspace",
"(",
"0",
",",
"1",
",",
"A",
".",
"shape",
"[",
"1",
"]",
")",
"[",
"Y",
",",
"X",
"]",
"=",
"np",
".",
"meshgrid",
"(",
"t",
",",
"t",
")",
"xi1",
"=",
"np",
".",
"exp",
"(",
"-",
"(",
"X",
"-",
"Y",
")",
"**",
"2",
"/",
"reg",
")",
"def",
"K",
"(",
"x",
")",
":",
"return",
"np",
".",
"dot",
"(",
"np",
".",
"dot",
"(",
"xi1",
",",
"x",
")",
",",
"xi1",
")",
"while",
"(",
"err",
">",
"stopThr",
"and",
"cpt",
"<",
"numItermax",
")",
":",
"bold",
"=",
"b",
"cpt",
"=",
"cpt",
"+",
"1",
"b",
"=",
"np",
".",
"zeros_like",
"(",
"A",
"[",
"0",
",",
":",
",",
":",
"]",
")",
"for",
"r",
"in",
"range",
"(",
"A",
".",
"shape",
"[",
"0",
"]",
")",
":",
"KV",
"[",
"r",
",",
":",
",",
":",
"]",
"=",
"K",
"(",
"A",
"[",
"r",
",",
":",
",",
":",
"]",
"/",
"np",
".",
"maximum",
"(",
"stabThr",
",",
"K",
"(",
"U",
"[",
"r",
",",
":",
",",
":",
"]",
")",
")",
")",
"b",
"+=",
"weights",
"[",
"r",
"]",
"*",
"np",
".",
"log",
"(",
"np",
".",
"maximum",
"(",
"stabThr",
",",
"U",
"[",
"r",
",",
":",
",",
":",
"]",
"*",
"KV",
"[",
"r",
",",
":",
",",
":",
"]",
")",
")",
"b",
"=",
"np",
".",
"exp",
"(",
"b",
")",
"for",
"r",
"in",
"range",
"(",
"A",
".",
"shape",
"[",
"0",
"]",
")",
":",
"U",
"[",
"r",
",",
":",
",",
":",
"]",
"=",
"b",
"/",
"np",
".",
"maximum",
"(",
"stabThr",
",",
"KV",
"[",
"r",
",",
":",
",",
":",
"]",
")",
"if",
"cpt",
"%",
"10",
"==",
"1",
":",
"err",
"=",
"np",
".",
"sum",
"(",
"np",
".",
"abs",
"(",
"bold",
"-",
"b",
")",
")",
"# log and verbose print",
"if",
"log",
":",
"log",
"[",
"'err'",
"]",
".",
"append",
"(",
"err",
")",
"if",
"verbose",
":",
"if",
"cpt",
"%",
"200",
"==",
"0",
":",
"print",
"(",
"'{:5s}|{:12s}'",
".",
"format",
"(",
"'It.'",
",",
"'Err'",
")",
"+",
"'\\n'",
"+",
"'-'",
"*",
"19",
")",
"print",
"(",
"'{:5d}|{:8e}|'",
".",
"format",
"(",
"cpt",
",",
"err",
")",
")",
"if",
"log",
":",
"log",
"[",
"'niter'",
"]",
"=",
"cpt",
"log",
"[",
"'U'",
"]",
"=",
"U",
"return",
"b",
",",
"log",
"else",
":",
"return",
"b"
] | Compute the entropic regularized wasserstein barycenter of distributions A
where A is a collection of 2D images.
The function solves the following optimization problem:
.. math::
\mathbf{a} = arg\min_\mathbf{a} \sum_i W_{reg}(\mathbf{a},\mathbf{a}_i)
where :
- :math:`W_{reg}(\cdot,\cdot)` is the entropic regularized Wasserstein distance (see ot.bregman.sinkhorn)
- :math:`\mathbf{a}_i` are training distributions (2D images) in the mast two dimensions of matrix :math:`\mathbf{A}`
- reg is the regularization strength scalar value
The algorithm used for solving the problem is the Sinkhorn-Knopp matrix scaling algorithm as proposed in [21]_
Parameters
----------
A : np.ndarray (n,w,h)
n distributions (2D images) of size w x h
reg : float
Regularization term >0
weights : np.ndarray (n,)
Weights of each image on the simplex (barycentric coodinates)
numItermax : int, optional
Max number of iterations
stopThr : float, optional
Stop threshol on error (>0)
stabThr : float, optional
Stabilization threshold to avoid numerical precision issue
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
a : (w,h) ndarray
2D Wasserstein barycenter
log : dict
log dictionary return only if log==True in parameters
References
----------
.. [21] Solomon, J., De Goes, F., Peyré, G., Cuturi, M., Butscher, A., Nguyen, A. & Guibas, L. (2015).
Convolutional wasserstein distances: Efficient optimal transportation on geometric domains
ACM Transactions on Graphics (TOG), 34(4), 66 | [
"Compute",
"the",
"entropic",
"regularized",
"wasserstein",
"barycenter",
"of",
"distributions",
"A",
"where",
"A",
"is",
"a",
"collection",
"of",
"2D",
"images",
"."
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/bregman.py#L1085-L1192 |
227,097 | rflamary/POT | ot/bregman.py | unmix | def unmix(a, D, M, M0, h0, reg, reg0, alpha, numItermax=1000,
stopThr=1e-3, verbose=False, log=False):
"""
Compute the unmixing of an observation with a given dictionary using Wasserstein distance
The function solve the following optimization problem:
.. math::
\mathbf{h} = arg\min_\mathbf{h} (1- \\alpha) W_{M,reg}(\mathbf{a},\mathbf{Dh})+\\alpha W_{M0,reg0}(\mathbf{h}_0,\mathbf{h})
where :
- :math:`W_{M,reg}(\cdot,\cdot)` is the entropic regularized Wasserstein distance with M loss matrix (see ot.bregman.sinkhorn)
- :math:`\mathbf{a}` is an observed distribution, :math:`\mathbf{h}_0` is aprior on unmixing
- reg and :math:`\mathbf{M}` are respectively the regularization term and the cost matrix for OT data fitting
- reg0 and :math:`\mathbf{M0}` are respectively the regularization term and the cost matrix for regularization
- :math:`\\alpha`weight data fitting and regularization
The optimization problem is solved suing the algorithm described in [4]
Parameters
----------
a : np.ndarray (d)
observed distribution
D : np.ndarray (d,n)
dictionary matrix
M : np.ndarray (d,d)
loss matrix
M0 : np.ndarray (n,n)
loss matrix
h0 : np.ndarray (n,)
prior on h
reg : float
Regularization term >0 (Wasserstein data fitting)
reg0 : float
Regularization term >0 (Wasserstein reg with h0)
alpha : float
How much should we trust the prior ([0,1])
numItermax : int, optional
Max number of iterations
stopThr : float, optional
Stop threshol on error (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
a : (d,) ndarray
Wasserstein barycenter
log : dict
log dictionary return only if log==True in parameters
References
----------
.. [4] S. Nakhostin, N. Courty, R. Flamary, D. Tuia, T. Corpetti, Supervised planetary unmixing with optimal transport, Whorkshop on Hyperspectral Image and Signal Processing : Evolution in Remote Sensing (WHISPERS), 2016.
"""
# M = M/np.median(M)
K = np.exp(-M / reg)
# M0 = M0/np.median(M0)
K0 = np.exp(-M0 / reg0)
old = h0
err = 1
cpt = 0
# log = {'niter':0, 'all_err':[]}
if log:
log = {'err': []}
while (err > stopThr and cpt < numItermax):
K = projC(K, a)
K0 = projC(K0, h0)
new = np.sum(K0, axis=1)
# we recombine the current selection from dictionnary
inv_new = np.dot(D, new)
other = np.sum(K, axis=1)
# geometric interpolation
delta = np.exp(alpha * np.log(other) + (1 - alpha) * np.log(inv_new))
K = projR(K, delta)
K0 = np.dot(np.diag(np.dot(D.T, delta / inv_new)), K0)
err = np.linalg.norm(np.sum(K0, axis=1) - old)
old = new
if log:
log['err'].append(err)
if verbose:
if cpt % 200 == 0:
print('{:5s}|{:12s}'.format('It.', 'Err') + '\n' + '-' * 19)
print('{:5d}|{:8e}|'.format(cpt, err))
cpt = cpt + 1
if log:
log['niter'] = cpt
return np.sum(K0, axis=1), log
else:
return np.sum(K0, axis=1) | python | def unmix(a, D, M, M0, h0, reg, reg0, alpha, numItermax=1000,
stopThr=1e-3, verbose=False, log=False):
"""
Compute the unmixing of an observation with a given dictionary using Wasserstein distance
The function solve the following optimization problem:
.. math::
\mathbf{h} = arg\min_\mathbf{h} (1- \\alpha) W_{M,reg}(\mathbf{a},\mathbf{Dh})+\\alpha W_{M0,reg0}(\mathbf{h}_0,\mathbf{h})
where :
- :math:`W_{M,reg}(\cdot,\cdot)` is the entropic regularized Wasserstein distance with M loss matrix (see ot.bregman.sinkhorn)
- :math:`\mathbf{a}` is an observed distribution, :math:`\mathbf{h}_0` is aprior on unmixing
- reg and :math:`\mathbf{M}` are respectively the regularization term and the cost matrix for OT data fitting
- reg0 and :math:`\mathbf{M0}` are respectively the regularization term and the cost matrix for regularization
- :math:`\\alpha`weight data fitting and regularization
The optimization problem is solved suing the algorithm described in [4]
Parameters
----------
a : np.ndarray (d)
observed distribution
D : np.ndarray (d,n)
dictionary matrix
M : np.ndarray (d,d)
loss matrix
M0 : np.ndarray (n,n)
loss matrix
h0 : np.ndarray (n,)
prior on h
reg : float
Regularization term >0 (Wasserstein data fitting)
reg0 : float
Regularization term >0 (Wasserstein reg with h0)
alpha : float
How much should we trust the prior ([0,1])
numItermax : int, optional
Max number of iterations
stopThr : float, optional
Stop threshol on error (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
a : (d,) ndarray
Wasserstein barycenter
log : dict
log dictionary return only if log==True in parameters
References
----------
.. [4] S. Nakhostin, N. Courty, R. Flamary, D. Tuia, T. Corpetti, Supervised planetary unmixing with optimal transport, Whorkshop on Hyperspectral Image and Signal Processing : Evolution in Remote Sensing (WHISPERS), 2016.
"""
# M = M/np.median(M)
K = np.exp(-M / reg)
# M0 = M0/np.median(M0)
K0 = np.exp(-M0 / reg0)
old = h0
err = 1
cpt = 0
# log = {'niter':0, 'all_err':[]}
if log:
log = {'err': []}
while (err > stopThr and cpt < numItermax):
K = projC(K, a)
K0 = projC(K0, h0)
new = np.sum(K0, axis=1)
# we recombine the current selection from dictionnary
inv_new = np.dot(D, new)
other = np.sum(K, axis=1)
# geometric interpolation
delta = np.exp(alpha * np.log(other) + (1 - alpha) * np.log(inv_new))
K = projR(K, delta)
K0 = np.dot(np.diag(np.dot(D.T, delta / inv_new)), K0)
err = np.linalg.norm(np.sum(K0, axis=1) - old)
old = new
if log:
log['err'].append(err)
if verbose:
if cpt % 200 == 0:
print('{:5s}|{:12s}'.format('It.', 'Err') + '\n' + '-' * 19)
print('{:5d}|{:8e}|'.format(cpt, err))
cpt = cpt + 1
if log:
log['niter'] = cpt
return np.sum(K0, axis=1), log
else:
return np.sum(K0, axis=1) | [
"def",
"unmix",
"(",
"a",
",",
"D",
",",
"M",
",",
"M0",
",",
"h0",
",",
"reg",
",",
"reg0",
",",
"alpha",
",",
"numItermax",
"=",
"1000",
",",
"stopThr",
"=",
"1e-3",
",",
"verbose",
"=",
"False",
",",
"log",
"=",
"False",
")",
":",
"# M = M/np.median(M)",
"K",
"=",
"np",
".",
"exp",
"(",
"-",
"M",
"/",
"reg",
")",
"# M0 = M0/np.median(M0)",
"K0",
"=",
"np",
".",
"exp",
"(",
"-",
"M0",
"/",
"reg0",
")",
"old",
"=",
"h0",
"err",
"=",
"1",
"cpt",
"=",
"0",
"# log = {'niter':0, 'all_err':[]}",
"if",
"log",
":",
"log",
"=",
"{",
"'err'",
":",
"[",
"]",
"}",
"while",
"(",
"err",
">",
"stopThr",
"and",
"cpt",
"<",
"numItermax",
")",
":",
"K",
"=",
"projC",
"(",
"K",
",",
"a",
")",
"K0",
"=",
"projC",
"(",
"K0",
",",
"h0",
")",
"new",
"=",
"np",
".",
"sum",
"(",
"K0",
",",
"axis",
"=",
"1",
")",
"# we recombine the current selection from dictionnary",
"inv_new",
"=",
"np",
".",
"dot",
"(",
"D",
",",
"new",
")",
"other",
"=",
"np",
".",
"sum",
"(",
"K",
",",
"axis",
"=",
"1",
")",
"# geometric interpolation",
"delta",
"=",
"np",
".",
"exp",
"(",
"alpha",
"*",
"np",
".",
"log",
"(",
"other",
")",
"+",
"(",
"1",
"-",
"alpha",
")",
"*",
"np",
".",
"log",
"(",
"inv_new",
")",
")",
"K",
"=",
"projR",
"(",
"K",
",",
"delta",
")",
"K0",
"=",
"np",
".",
"dot",
"(",
"np",
".",
"diag",
"(",
"np",
".",
"dot",
"(",
"D",
".",
"T",
",",
"delta",
"/",
"inv_new",
")",
")",
",",
"K0",
")",
"err",
"=",
"np",
".",
"linalg",
".",
"norm",
"(",
"np",
".",
"sum",
"(",
"K0",
",",
"axis",
"=",
"1",
")",
"-",
"old",
")",
"old",
"=",
"new",
"if",
"log",
":",
"log",
"[",
"'err'",
"]",
".",
"append",
"(",
"err",
")",
"if",
"verbose",
":",
"if",
"cpt",
"%",
"200",
"==",
"0",
":",
"print",
"(",
"'{:5s}|{:12s}'",
".",
"format",
"(",
"'It.'",
",",
"'Err'",
")",
"+",
"'\\n'",
"+",
"'-'",
"*",
"19",
")",
"print",
"(",
"'{:5d}|{:8e}|'",
".",
"format",
"(",
"cpt",
",",
"err",
")",
")",
"cpt",
"=",
"cpt",
"+",
"1",
"if",
"log",
":",
"log",
"[",
"'niter'",
"]",
"=",
"cpt",
"return",
"np",
".",
"sum",
"(",
"K0",
",",
"axis",
"=",
"1",
")",
",",
"log",
"else",
":",
"return",
"np",
".",
"sum",
"(",
"K0",
",",
"axis",
"=",
"1",
")"
] | Compute the unmixing of an observation with a given dictionary using Wasserstein distance
The function solve the following optimization problem:
.. math::
\mathbf{h} = arg\min_\mathbf{h} (1- \\alpha) W_{M,reg}(\mathbf{a},\mathbf{Dh})+\\alpha W_{M0,reg0}(\mathbf{h}_0,\mathbf{h})
where :
- :math:`W_{M,reg}(\cdot,\cdot)` is the entropic regularized Wasserstein distance with M loss matrix (see ot.bregman.sinkhorn)
- :math:`\mathbf{a}` is an observed distribution, :math:`\mathbf{h}_0` is aprior on unmixing
- reg and :math:`\mathbf{M}` are respectively the regularization term and the cost matrix for OT data fitting
- reg0 and :math:`\mathbf{M0}` are respectively the regularization term and the cost matrix for regularization
- :math:`\\alpha`weight data fitting and regularization
The optimization problem is solved suing the algorithm described in [4]
Parameters
----------
a : np.ndarray (d)
observed distribution
D : np.ndarray (d,n)
dictionary matrix
M : np.ndarray (d,d)
loss matrix
M0 : np.ndarray (n,n)
loss matrix
h0 : np.ndarray (n,)
prior on h
reg : float
Regularization term >0 (Wasserstein data fitting)
reg0 : float
Regularization term >0 (Wasserstein reg with h0)
alpha : float
How much should we trust the prior ([0,1])
numItermax : int, optional
Max number of iterations
stopThr : float, optional
Stop threshol on error (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
a : (d,) ndarray
Wasserstein barycenter
log : dict
log dictionary return only if log==True in parameters
References
----------
.. [4] S. Nakhostin, N. Courty, R. Flamary, D. Tuia, T. Corpetti, Supervised planetary unmixing with optimal transport, Whorkshop on Hyperspectral Image and Signal Processing : Evolution in Remote Sensing (WHISPERS), 2016. | [
"Compute",
"the",
"unmixing",
"of",
"an",
"observation",
"with",
"a",
"given",
"dictionary",
"using",
"Wasserstein",
"distance"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/bregman.py#L1195-L1300 |
227,098 | rflamary/POT | ot/bregman.py | empirical_sinkhorn | def empirical_sinkhorn(X_s, X_t, reg, a=None, b=None, metric='sqeuclidean', numIterMax=10000, stopThr=1e-9, verbose=False, log=False, **kwargs):
'''
Solve the entropic regularization optimal transport problem and return the
OT matrix from empirical data
The function solves the following optimization problem:
.. math::
\gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma)
s.t. \gamma 1 = a
\gamma^T 1= b
\gamma\geq 0
where :
- :math:`M` is the (ns,nt) metric cost matrix
- :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
- :math:`a` and :math:`b` are source and target weights (sum to 1)
Parameters
----------
X_s : np.ndarray (ns, d)
samples in the source domain
X_t : np.ndarray (nt, d)
samples in the target domain
reg : float
Regularization term >0
a : np.ndarray (ns,)
samples weights in the source domain
b : np.ndarray (nt,)
samples weights in the target domain
numItermax : int, optional
Max number of iterations
stopThr : float, optional
Stop threshol on error (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
gamma : (ns x nt) ndarray
Regularized optimal transportation matrix for the given parameters
log : dict
log dictionary return only if log==True in parameters
Examples
--------
>>> n_s = 2
>>> n_t = 2
>>> reg = 0.1
>>> X_s = np.reshape(np.arange(n_s), (n_s, 1))
>>> X_t = np.reshape(np.arange(0, n_t), (n_t, 1))
>>> emp_sinkhorn = empirical_sinkhorn(X_s, X_t, reg, verbose=False)
>>> print(emp_sinkhorn)
>>> [[4.99977301e-01 2.26989344e-05]
[2.26989344e-05 4.99977301e-01]]
References
----------
.. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013
.. [9] Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms for Entropy Regularized Transport Problems. arXiv preprint arXiv:1610.06519.
.. [10] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). Scaling algorithms for unbalanced transport problems. arXiv preprint arXiv:1607.05816.
'''
if a is None:
a = unif(np.shape(X_s)[0])
if b is None:
b = unif(np.shape(X_t)[0])
M = dist(X_s, X_t, metric=metric)
if log:
pi, log = sinkhorn(a, b, M, reg, numItermax=numIterMax, stopThr=stopThr, verbose=verbose, log=True, **kwargs)
return pi, log
else:
pi = sinkhorn(a, b, M, reg, numItermax=numIterMax, stopThr=stopThr, verbose=verbose, log=False, **kwargs)
return pi | python | def empirical_sinkhorn(X_s, X_t, reg, a=None, b=None, metric='sqeuclidean', numIterMax=10000, stopThr=1e-9, verbose=False, log=False, **kwargs):
'''
Solve the entropic regularization optimal transport problem and return the
OT matrix from empirical data
The function solves the following optimization problem:
.. math::
\gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma)
s.t. \gamma 1 = a
\gamma^T 1= b
\gamma\geq 0
where :
- :math:`M` is the (ns,nt) metric cost matrix
- :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
- :math:`a` and :math:`b` are source and target weights (sum to 1)
Parameters
----------
X_s : np.ndarray (ns, d)
samples in the source domain
X_t : np.ndarray (nt, d)
samples in the target domain
reg : float
Regularization term >0
a : np.ndarray (ns,)
samples weights in the source domain
b : np.ndarray (nt,)
samples weights in the target domain
numItermax : int, optional
Max number of iterations
stopThr : float, optional
Stop threshol on error (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
gamma : (ns x nt) ndarray
Regularized optimal transportation matrix for the given parameters
log : dict
log dictionary return only if log==True in parameters
Examples
--------
>>> n_s = 2
>>> n_t = 2
>>> reg = 0.1
>>> X_s = np.reshape(np.arange(n_s), (n_s, 1))
>>> X_t = np.reshape(np.arange(0, n_t), (n_t, 1))
>>> emp_sinkhorn = empirical_sinkhorn(X_s, X_t, reg, verbose=False)
>>> print(emp_sinkhorn)
>>> [[4.99977301e-01 2.26989344e-05]
[2.26989344e-05 4.99977301e-01]]
References
----------
.. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013
.. [9] Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms for Entropy Regularized Transport Problems. arXiv preprint arXiv:1610.06519.
.. [10] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). Scaling algorithms for unbalanced transport problems. arXiv preprint arXiv:1607.05816.
'''
if a is None:
a = unif(np.shape(X_s)[0])
if b is None:
b = unif(np.shape(X_t)[0])
M = dist(X_s, X_t, metric=metric)
if log:
pi, log = sinkhorn(a, b, M, reg, numItermax=numIterMax, stopThr=stopThr, verbose=verbose, log=True, **kwargs)
return pi, log
else:
pi = sinkhorn(a, b, M, reg, numItermax=numIterMax, stopThr=stopThr, verbose=verbose, log=False, **kwargs)
return pi | [
"def",
"empirical_sinkhorn",
"(",
"X_s",
",",
"X_t",
",",
"reg",
",",
"a",
"=",
"None",
",",
"b",
"=",
"None",
",",
"metric",
"=",
"'sqeuclidean'",
",",
"numIterMax",
"=",
"10000",
",",
"stopThr",
"=",
"1e-9",
",",
"verbose",
"=",
"False",
",",
"log",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"a",
"is",
"None",
":",
"a",
"=",
"unif",
"(",
"np",
".",
"shape",
"(",
"X_s",
")",
"[",
"0",
"]",
")",
"if",
"b",
"is",
"None",
":",
"b",
"=",
"unif",
"(",
"np",
".",
"shape",
"(",
"X_t",
")",
"[",
"0",
"]",
")",
"M",
"=",
"dist",
"(",
"X_s",
",",
"X_t",
",",
"metric",
"=",
"metric",
")",
"if",
"log",
":",
"pi",
",",
"log",
"=",
"sinkhorn",
"(",
"a",
",",
"b",
",",
"M",
",",
"reg",
",",
"numItermax",
"=",
"numIterMax",
",",
"stopThr",
"=",
"stopThr",
",",
"verbose",
"=",
"verbose",
",",
"log",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
"return",
"pi",
",",
"log",
"else",
":",
"pi",
"=",
"sinkhorn",
"(",
"a",
",",
"b",
",",
"M",
",",
"reg",
",",
"numItermax",
"=",
"numIterMax",
",",
"stopThr",
"=",
"stopThr",
",",
"verbose",
"=",
"verbose",
",",
"log",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
"return",
"pi"
] | Solve the entropic regularization optimal transport problem and return the
OT matrix from empirical data
The function solves the following optimization problem:
.. math::
\gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma)
s.t. \gamma 1 = a
\gamma^T 1= b
\gamma\geq 0
where :
- :math:`M` is the (ns,nt) metric cost matrix
- :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
- :math:`a` and :math:`b` are source and target weights (sum to 1)
Parameters
----------
X_s : np.ndarray (ns, d)
samples in the source domain
X_t : np.ndarray (nt, d)
samples in the target domain
reg : float
Regularization term >0
a : np.ndarray (ns,)
samples weights in the source domain
b : np.ndarray (nt,)
samples weights in the target domain
numItermax : int, optional
Max number of iterations
stopThr : float, optional
Stop threshol on error (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
gamma : (ns x nt) ndarray
Regularized optimal transportation matrix for the given parameters
log : dict
log dictionary return only if log==True in parameters
Examples
--------
>>> n_s = 2
>>> n_t = 2
>>> reg = 0.1
>>> X_s = np.reshape(np.arange(n_s), (n_s, 1))
>>> X_t = np.reshape(np.arange(0, n_t), (n_t, 1))
>>> emp_sinkhorn = empirical_sinkhorn(X_s, X_t, reg, verbose=False)
>>> print(emp_sinkhorn)
>>> [[4.99977301e-01 2.26989344e-05]
[2.26989344e-05 4.99977301e-01]]
References
----------
.. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013
.. [9] Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms for Entropy Regularized Transport Problems. arXiv preprint arXiv:1610.06519.
.. [10] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). Scaling algorithms for unbalanced transport problems. arXiv preprint arXiv:1607.05816. | [
"Solve",
"the",
"entropic",
"regularization",
"optimal",
"transport",
"problem",
"and",
"return",
"the",
"OT",
"matrix",
"from",
"empirical",
"data"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/bregman.py#L1303-L1390 |
227,099 | rflamary/POT | ot/bregman.py | empirical_sinkhorn2 | def empirical_sinkhorn2(X_s, X_t, reg, a=None, b=None, metric='sqeuclidean', numIterMax=10000, stopThr=1e-9, verbose=False, log=False, **kwargs):
'''
Solve the entropic regularization optimal transport problem from empirical
data and return the OT loss
The function solves the following optimization problem:
.. math::
W = \min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma)
s.t. \gamma 1 = a
\gamma^T 1= b
\gamma\geq 0
where :
- :math:`M` is the (ns,nt) metric cost matrix
- :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
- :math:`a` and :math:`b` are source and target weights (sum to 1)
Parameters
----------
X_s : np.ndarray (ns, d)
samples in the source domain
X_t : np.ndarray (nt, d)
samples in the target domain
reg : float
Regularization term >0
a : np.ndarray (ns,)
samples weights in the source domain
b : np.ndarray (nt,)
samples weights in the target domain
numItermax : int, optional
Max number of iterations
stopThr : float, optional
Stop threshol on error (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
gamma : (ns x nt) ndarray
Regularized optimal transportation matrix for the given parameters
log : dict
log dictionary return only if log==True in parameters
Examples
--------
>>> n_s = 2
>>> n_t = 2
>>> reg = 0.1
>>> X_s = np.reshape(np.arange(n_s), (n_s, 1))
>>> X_t = np.reshape(np.arange(0, n_t), (n_t, 1))
>>> loss_sinkhorn = empirical_sinkhorn2(X_s, X_t, reg, verbose=False)
>>> print(loss_sinkhorn)
>>> [4.53978687e-05]
References
----------
.. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013
.. [9] Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms for Entropy Regularized Transport Problems. arXiv preprint arXiv:1610.06519.
.. [10] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). Scaling algorithms for unbalanced transport problems. arXiv preprint arXiv:1607.05816.
'''
if a is None:
a = unif(np.shape(X_s)[0])
if b is None:
b = unif(np.shape(X_t)[0])
M = dist(X_s, X_t, metric=metric)
if log:
sinkhorn_loss, log = sinkhorn2(a, b, M, reg, numItermax=numIterMax, stopThr=stopThr, verbose=verbose, log=log, **kwargs)
return sinkhorn_loss, log
else:
sinkhorn_loss = sinkhorn2(a, b, M, reg, numItermax=numIterMax, stopThr=stopThr, verbose=verbose, log=log, **kwargs)
return sinkhorn_loss | python | def empirical_sinkhorn2(X_s, X_t, reg, a=None, b=None, metric='sqeuclidean', numIterMax=10000, stopThr=1e-9, verbose=False, log=False, **kwargs):
'''
Solve the entropic regularization optimal transport problem from empirical
data and return the OT loss
The function solves the following optimization problem:
.. math::
W = \min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma)
s.t. \gamma 1 = a
\gamma^T 1= b
\gamma\geq 0
where :
- :math:`M` is the (ns,nt) metric cost matrix
- :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
- :math:`a` and :math:`b` are source and target weights (sum to 1)
Parameters
----------
X_s : np.ndarray (ns, d)
samples in the source domain
X_t : np.ndarray (nt, d)
samples in the target domain
reg : float
Regularization term >0
a : np.ndarray (ns,)
samples weights in the source domain
b : np.ndarray (nt,)
samples weights in the target domain
numItermax : int, optional
Max number of iterations
stopThr : float, optional
Stop threshol on error (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
gamma : (ns x nt) ndarray
Regularized optimal transportation matrix for the given parameters
log : dict
log dictionary return only if log==True in parameters
Examples
--------
>>> n_s = 2
>>> n_t = 2
>>> reg = 0.1
>>> X_s = np.reshape(np.arange(n_s), (n_s, 1))
>>> X_t = np.reshape(np.arange(0, n_t), (n_t, 1))
>>> loss_sinkhorn = empirical_sinkhorn2(X_s, X_t, reg, verbose=False)
>>> print(loss_sinkhorn)
>>> [4.53978687e-05]
References
----------
.. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013
.. [9] Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms for Entropy Regularized Transport Problems. arXiv preprint arXiv:1610.06519.
.. [10] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). Scaling algorithms for unbalanced transport problems. arXiv preprint arXiv:1607.05816.
'''
if a is None:
a = unif(np.shape(X_s)[0])
if b is None:
b = unif(np.shape(X_t)[0])
M = dist(X_s, X_t, metric=metric)
if log:
sinkhorn_loss, log = sinkhorn2(a, b, M, reg, numItermax=numIterMax, stopThr=stopThr, verbose=verbose, log=log, **kwargs)
return sinkhorn_loss, log
else:
sinkhorn_loss = sinkhorn2(a, b, M, reg, numItermax=numIterMax, stopThr=stopThr, verbose=verbose, log=log, **kwargs)
return sinkhorn_loss | [
"def",
"empirical_sinkhorn2",
"(",
"X_s",
",",
"X_t",
",",
"reg",
",",
"a",
"=",
"None",
",",
"b",
"=",
"None",
",",
"metric",
"=",
"'sqeuclidean'",
",",
"numIterMax",
"=",
"10000",
",",
"stopThr",
"=",
"1e-9",
",",
"verbose",
"=",
"False",
",",
"log",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"a",
"is",
"None",
":",
"a",
"=",
"unif",
"(",
"np",
".",
"shape",
"(",
"X_s",
")",
"[",
"0",
"]",
")",
"if",
"b",
"is",
"None",
":",
"b",
"=",
"unif",
"(",
"np",
".",
"shape",
"(",
"X_t",
")",
"[",
"0",
"]",
")",
"M",
"=",
"dist",
"(",
"X_s",
",",
"X_t",
",",
"metric",
"=",
"metric",
")",
"if",
"log",
":",
"sinkhorn_loss",
",",
"log",
"=",
"sinkhorn2",
"(",
"a",
",",
"b",
",",
"M",
",",
"reg",
",",
"numItermax",
"=",
"numIterMax",
",",
"stopThr",
"=",
"stopThr",
",",
"verbose",
"=",
"verbose",
",",
"log",
"=",
"log",
",",
"*",
"*",
"kwargs",
")",
"return",
"sinkhorn_loss",
",",
"log",
"else",
":",
"sinkhorn_loss",
"=",
"sinkhorn2",
"(",
"a",
",",
"b",
",",
"M",
",",
"reg",
",",
"numItermax",
"=",
"numIterMax",
",",
"stopThr",
"=",
"stopThr",
",",
"verbose",
"=",
"verbose",
",",
"log",
"=",
"log",
",",
"*",
"*",
"kwargs",
")",
"return",
"sinkhorn_loss"
] | Solve the entropic regularization optimal transport problem from empirical
data and return the OT loss
The function solves the following optimization problem:
.. math::
W = \min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma)
s.t. \gamma 1 = a
\gamma^T 1= b
\gamma\geq 0
where :
- :math:`M` is the (ns,nt) metric cost matrix
- :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
- :math:`a` and :math:`b` are source and target weights (sum to 1)
Parameters
----------
X_s : np.ndarray (ns, d)
samples in the source domain
X_t : np.ndarray (nt, d)
samples in the target domain
reg : float
Regularization term >0
a : np.ndarray (ns,)
samples weights in the source domain
b : np.ndarray (nt,)
samples weights in the target domain
numItermax : int, optional
Max number of iterations
stopThr : float, optional
Stop threshol on error (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
gamma : (ns x nt) ndarray
Regularized optimal transportation matrix for the given parameters
log : dict
log dictionary return only if log==True in parameters
Examples
--------
>>> n_s = 2
>>> n_t = 2
>>> reg = 0.1
>>> X_s = np.reshape(np.arange(n_s), (n_s, 1))
>>> X_t = np.reshape(np.arange(0, n_t), (n_t, 1))
>>> loss_sinkhorn = empirical_sinkhorn2(X_s, X_t, reg, verbose=False)
>>> print(loss_sinkhorn)
>>> [4.53978687e-05]
References
----------
.. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013
.. [9] Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms for Entropy Regularized Transport Problems. arXiv preprint arXiv:1610.06519.
.. [10] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). Scaling algorithms for unbalanced transport problems. arXiv preprint arXiv:1607.05816. | [
"Solve",
"the",
"entropic",
"regularization",
"optimal",
"transport",
"problem",
"from",
"empirical",
"data",
"and",
"return",
"the",
"OT",
"loss"
] | c5108efc7b6702e1af3928bef1032e6b37734d1c | https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/bregman.py#L1393-L1480 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.