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
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
|
---|---|---|---|---|---|---|---|---|---|---|---|
3,900 | pahaz/sshtunnel | sshtunnel.py | SSHTunnelForwarder._check_tunnel | def _check_tunnel(self, _srv):
""" Check if tunnel is already established """
if self.skip_tunnel_checkup:
self.tunnel_is_up[_srv.local_address] = True
return
self.logger.info('Checking tunnel to: {0}'.format(_srv.remote_address))
if isinstance(_srv.local_address, string_types): # UNIX stream
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
else:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(TUNNEL_TIMEOUT)
try:
# Windows raises WinError 10049 if trying to connect to 0.0.0.0
connect_to = ('127.0.0.1', _srv.local_port) \
if _srv.local_host == '0.0.0.0' else _srv.local_address
s.connect(connect_to)
self.tunnel_is_up[_srv.local_address] = _srv.tunnel_ok.get(
timeout=TUNNEL_TIMEOUT * 1.1
)
self.logger.debug(
'Tunnel to {0} is DOWN'.format(_srv.remote_address)
)
except socket.error:
self.logger.debug(
'Tunnel to {0} is DOWN'.format(_srv.remote_address)
)
self.tunnel_is_up[_srv.local_address] = False
except queue.Empty:
self.logger.debug(
'Tunnel to {0} is UP'.format(_srv.remote_address)
)
self.tunnel_is_up[_srv.local_address] = True
finally:
s.close() | python | def _check_tunnel(self, _srv):
""" Check if tunnel is already established """
if self.skip_tunnel_checkup:
self.tunnel_is_up[_srv.local_address] = True
return
self.logger.info('Checking tunnel to: {0}'.format(_srv.remote_address))
if isinstance(_srv.local_address, string_types): # UNIX stream
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
else:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(TUNNEL_TIMEOUT)
try:
# Windows raises WinError 10049 if trying to connect to 0.0.0.0
connect_to = ('127.0.0.1', _srv.local_port) \
if _srv.local_host == '0.0.0.0' else _srv.local_address
s.connect(connect_to)
self.tunnel_is_up[_srv.local_address] = _srv.tunnel_ok.get(
timeout=TUNNEL_TIMEOUT * 1.1
)
self.logger.debug(
'Tunnel to {0} is DOWN'.format(_srv.remote_address)
)
except socket.error:
self.logger.debug(
'Tunnel to {0} is DOWN'.format(_srv.remote_address)
)
self.tunnel_is_up[_srv.local_address] = False
except queue.Empty:
self.logger.debug(
'Tunnel to {0} is UP'.format(_srv.remote_address)
)
self.tunnel_is_up[_srv.local_address] = True
finally:
s.close() | [
"def",
"_check_tunnel",
"(",
"self",
",",
"_srv",
")",
":",
"if",
"self",
".",
"skip_tunnel_checkup",
":",
"self",
".",
"tunnel_is_up",
"[",
"_srv",
".",
"local_address",
"]",
"=",
"True",
"return",
"self",
".",
"logger",
".",
"info",
"(",
"'Checking tunnel to: {0}'",
".",
"format",
"(",
"_srv",
".",
"remote_address",
")",
")",
"if",
"isinstance",
"(",
"_srv",
".",
"local_address",
",",
"string_types",
")",
":",
"# UNIX stream",
"s",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_UNIX",
",",
"socket",
".",
"SOCK_STREAM",
")",
"else",
":",
"s",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_STREAM",
")",
"s",
".",
"settimeout",
"(",
"TUNNEL_TIMEOUT",
")",
"try",
":",
"# Windows raises WinError 10049 if trying to connect to 0.0.0.0",
"connect_to",
"=",
"(",
"'127.0.0.1'",
",",
"_srv",
".",
"local_port",
")",
"if",
"_srv",
".",
"local_host",
"==",
"'0.0.0.0'",
"else",
"_srv",
".",
"local_address",
"s",
".",
"connect",
"(",
"connect_to",
")",
"self",
".",
"tunnel_is_up",
"[",
"_srv",
".",
"local_address",
"]",
"=",
"_srv",
".",
"tunnel_ok",
".",
"get",
"(",
"timeout",
"=",
"TUNNEL_TIMEOUT",
"*",
"1.1",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"'Tunnel to {0} is DOWN'",
".",
"format",
"(",
"_srv",
".",
"remote_address",
")",
")",
"except",
"socket",
".",
"error",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'Tunnel to {0} is DOWN'",
".",
"format",
"(",
"_srv",
".",
"remote_address",
")",
")",
"self",
".",
"tunnel_is_up",
"[",
"_srv",
".",
"local_address",
"]",
"=",
"False",
"except",
"queue",
".",
"Empty",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'Tunnel to {0} is UP'",
".",
"format",
"(",
"_srv",
".",
"remote_address",
")",
")",
"self",
".",
"tunnel_is_up",
"[",
"_srv",
".",
"local_address",
"]",
"=",
"True",
"finally",
":",
"s",
".",
"close",
"(",
")"
] | Check if tunnel is already established | [
"Check",
"if",
"tunnel",
"is",
"already",
"established"
] | 66a923e4c6c8e41b8348420523fbf5ddfd53176c | https://github.com/pahaz/sshtunnel/blob/66a923e4c6c8e41b8348420523fbf5ddfd53176c/sshtunnel.py#L1243-L1277 |
3,901 | pahaz/sshtunnel | sshtunnel.py | SSHTunnelForwarder.start | def start(self):
""" Start the SSH tunnels """
if self.is_alive:
self.logger.warning('Already started!')
return
self._create_tunnels()
if not self.is_active:
self._raise(BaseSSHTunnelForwarderError,
reason='Could not establish session to SSH gateway')
for _srv in self._server_list:
thread = threading.Thread(
target=self._serve_forever_wrapper,
args=(_srv, ),
name='Srv-{0}'.format(address_to_str(_srv.local_port))
)
thread.daemon = self.daemon_forward_servers
thread.start()
self._check_tunnel(_srv)
self.is_alive = any(self.tunnel_is_up.values())
if not self.is_alive:
self._raise(HandlerSSHTunnelForwarderError,
'An error occurred while opening tunnels.') | python | def start(self):
""" Start the SSH tunnels """
if self.is_alive:
self.logger.warning('Already started!')
return
self._create_tunnels()
if not self.is_active:
self._raise(BaseSSHTunnelForwarderError,
reason='Could not establish session to SSH gateway')
for _srv in self._server_list:
thread = threading.Thread(
target=self._serve_forever_wrapper,
args=(_srv, ),
name='Srv-{0}'.format(address_to_str(_srv.local_port))
)
thread.daemon = self.daemon_forward_servers
thread.start()
self._check_tunnel(_srv)
self.is_alive = any(self.tunnel_is_up.values())
if not self.is_alive:
self._raise(HandlerSSHTunnelForwarderError,
'An error occurred while opening tunnels.') | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_alive",
":",
"self",
".",
"logger",
".",
"warning",
"(",
"'Already started!'",
")",
"return",
"self",
".",
"_create_tunnels",
"(",
")",
"if",
"not",
"self",
".",
"is_active",
":",
"self",
".",
"_raise",
"(",
"BaseSSHTunnelForwarderError",
",",
"reason",
"=",
"'Could not establish session to SSH gateway'",
")",
"for",
"_srv",
"in",
"self",
".",
"_server_list",
":",
"thread",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"self",
".",
"_serve_forever_wrapper",
",",
"args",
"=",
"(",
"_srv",
",",
")",
",",
"name",
"=",
"'Srv-{0}'",
".",
"format",
"(",
"address_to_str",
"(",
"_srv",
".",
"local_port",
")",
")",
")",
"thread",
".",
"daemon",
"=",
"self",
".",
"daemon_forward_servers",
"thread",
".",
"start",
"(",
")",
"self",
".",
"_check_tunnel",
"(",
"_srv",
")",
"self",
".",
"is_alive",
"=",
"any",
"(",
"self",
".",
"tunnel_is_up",
".",
"values",
"(",
")",
")",
"if",
"not",
"self",
".",
"is_alive",
":",
"self",
".",
"_raise",
"(",
"HandlerSSHTunnelForwarderError",
",",
"'An error occurred while opening tunnels.'",
")"
] | Start the SSH tunnels | [
"Start",
"the",
"SSH",
"tunnels"
] | 66a923e4c6c8e41b8348420523fbf5ddfd53176c | https://github.com/pahaz/sshtunnel/blob/66a923e4c6c8e41b8348420523fbf5ddfd53176c/sshtunnel.py#L1287-L1308 |
3,902 | pahaz/sshtunnel | sshtunnel.py | SSHTunnelForwarder.stop | def stop(self):
"""
Shut the tunnel down.
.. note:: This **had** to be handled with care before ``0.1.0``:
- if a port redirection is opened
- the destination is not reachable
- we attempt a connection to that tunnel (``SYN`` is sent and
acknowledged, then a ``FIN`` packet is sent and never
acknowledged... weird)
- we try to shutdown: it will not succeed until ``FIN_WAIT_2`` and
``CLOSE_WAIT`` time out.
.. note::
Handle these scenarios with :attr:`.tunnel_is_up`: if False, server
``shutdown()`` will be skipped on that tunnel
"""
self.logger.info('Closing all open connections...')
opened_address_text = ', '.join(
(address_to_str(k.local_address) for k in self._server_list)
) or 'None'
self.logger.debug('Listening tunnels: ' + opened_address_text)
self._stop_transport()
self._server_list = [] # reset server list
self.tunnel_is_up = {} | python | def stop(self):
"""
Shut the tunnel down.
.. note:: This **had** to be handled with care before ``0.1.0``:
- if a port redirection is opened
- the destination is not reachable
- we attempt a connection to that tunnel (``SYN`` is sent and
acknowledged, then a ``FIN`` packet is sent and never
acknowledged... weird)
- we try to shutdown: it will not succeed until ``FIN_WAIT_2`` and
``CLOSE_WAIT`` time out.
.. note::
Handle these scenarios with :attr:`.tunnel_is_up`: if False, server
``shutdown()`` will be skipped on that tunnel
"""
self.logger.info('Closing all open connections...')
opened_address_text = ', '.join(
(address_to_str(k.local_address) for k in self._server_list)
) or 'None'
self.logger.debug('Listening tunnels: ' + opened_address_text)
self._stop_transport()
self._server_list = [] # reset server list
self.tunnel_is_up = {} | [
"def",
"stop",
"(",
"self",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'Closing all open connections...'",
")",
"opened_address_text",
"=",
"', '",
".",
"join",
"(",
"(",
"address_to_str",
"(",
"k",
".",
"local_address",
")",
"for",
"k",
"in",
"self",
".",
"_server_list",
")",
")",
"or",
"'None'",
"self",
".",
"logger",
".",
"debug",
"(",
"'Listening tunnels: '",
"+",
"opened_address_text",
")",
"self",
".",
"_stop_transport",
"(",
")",
"self",
".",
"_server_list",
"=",
"[",
"]",
"# reset server list",
"self",
".",
"tunnel_is_up",
"=",
"{",
"}"
] | Shut the tunnel down.
.. note:: This **had** to be handled with care before ``0.1.0``:
- if a port redirection is opened
- the destination is not reachable
- we attempt a connection to that tunnel (``SYN`` is sent and
acknowledged, then a ``FIN`` packet is sent and never
acknowledged... weird)
- we try to shutdown: it will not succeed until ``FIN_WAIT_2`` and
``CLOSE_WAIT`` time out.
.. note::
Handle these scenarios with :attr:`.tunnel_is_up`: if False, server
``shutdown()`` will be skipped on that tunnel | [
"Shut",
"the",
"tunnel",
"down",
"."
] | 66a923e4c6c8e41b8348420523fbf5ddfd53176c | https://github.com/pahaz/sshtunnel/blob/66a923e4c6c8e41b8348420523fbf5ddfd53176c/sshtunnel.py#L1310-L1335 |
3,903 | pahaz/sshtunnel | sshtunnel.py | SSHTunnelForwarder._serve_forever_wrapper | def _serve_forever_wrapper(self, _srv, poll_interval=0.1):
"""
Wrapper for the server created for a SSH forward
"""
self.logger.info('Opening tunnel: {0} <> {1}'.format(
address_to_str(_srv.local_address),
address_to_str(_srv.remote_address))
)
_srv.serve_forever(poll_interval) # blocks until finished
self.logger.info('Tunnel: {0} <> {1} released'.format(
address_to_str(_srv.local_address),
address_to_str(_srv.remote_address))
) | python | def _serve_forever_wrapper(self, _srv, poll_interval=0.1):
"""
Wrapper for the server created for a SSH forward
"""
self.logger.info('Opening tunnel: {0} <> {1}'.format(
address_to_str(_srv.local_address),
address_to_str(_srv.remote_address))
)
_srv.serve_forever(poll_interval) # blocks until finished
self.logger.info('Tunnel: {0} <> {1} released'.format(
address_to_str(_srv.local_address),
address_to_str(_srv.remote_address))
) | [
"def",
"_serve_forever_wrapper",
"(",
"self",
",",
"_srv",
",",
"poll_interval",
"=",
"0.1",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'Opening tunnel: {0} <> {1}'",
".",
"format",
"(",
"address_to_str",
"(",
"_srv",
".",
"local_address",
")",
",",
"address_to_str",
"(",
"_srv",
".",
"remote_address",
")",
")",
")",
"_srv",
".",
"serve_forever",
"(",
"poll_interval",
")",
"# blocks until finished",
"self",
".",
"logger",
".",
"info",
"(",
"'Tunnel: {0} <> {1} released'",
".",
"format",
"(",
"address_to_str",
"(",
"_srv",
".",
"local_address",
")",
",",
"address_to_str",
"(",
"_srv",
".",
"remote_address",
")",
")",
")"
] | Wrapper for the server created for a SSH forward | [
"Wrapper",
"for",
"the",
"server",
"created",
"for",
"a",
"SSH",
"forward"
] | 66a923e4c6c8e41b8348420523fbf5ddfd53176c | https://github.com/pahaz/sshtunnel/blob/66a923e4c6c8e41b8348420523fbf5ddfd53176c/sshtunnel.py#L1383-L1396 |
3,904 | pahaz/sshtunnel | sshtunnel.py | SSHTunnelForwarder._stop_transport | def _stop_transport(self):
""" Close the underlying transport when nothing more is needed """
try:
self._check_is_started()
except (BaseSSHTunnelForwarderError,
HandlerSSHTunnelForwarderError) as e:
self.logger.warning(e)
for _srv in self._server_list:
tunnel = _srv.local_address
if self.tunnel_is_up[tunnel]:
self.logger.info('Shutting down tunnel {0}'.format(tunnel))
_srv.shutdown()
_srv.server_close()
# clean up the UNIX domain socket if we're using one
if isinstance(_srv, _UnixStreamForwardServer):
try:
os.unlink(_srv.local_address)
except Exception as e:
self.logger.error('Unable to unlink socket {0}: {1}'
.format(self.local_address, repr(e)))
self.is_alive = False
if self.is_active:
self._transport.close()
self._transport.stop_thread()
self.logger.debug('Transport is closed') | python | def _stop_transport(self):
""" Close the underlying transport when nothing more is needed """
try:
self._check_is_started()
except (BaseSSHTunnelForwarderError,
HandlerSSHTunnelForwarderError) as e:
self.logger.warning(e)
for _srv in self._server_list:
tunnel = _srv.local_address
if self.tunnel_is_up[tunnel]:
self.logger.info('Shutting down tunnel {0}'.format(tunnel))
_srv.shutdown()
_srv.server_close()
# clean up the UNIX domain socket if we're using one
if isinstance(_srv, _UnixStreamForwardServer):
try:
os.unlink(_srv.local_address)
except Exception as e:
self.logger.error('Unable to unlink socket {0}: {1}'
.format(self.local_address, repr(e)))
self.is_alive = False
if self.is_active:
self._transport.close()
self._transport.stop_thread()
self.logger.debug('Transport is closed') | [
"def",
"_stop_transport",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"_check_is_started",
"(",
")",
"except",
"(",
"BaseSSHTunnelForwarderError",
",",
"HandlerSSHTunnelForwarderError",
")",
"as",
"e",
":",
"self",
".",
"logger",
".",
"warning",
"(",
"e",
")",
"for",
"_srv",
"in",
"self",
".",
"_server_list",
":",
"tunnel",
"=",
"_srv",
".",
"local_address",
"if",
"self",
".",
"tunnel_is_up",
"[",
"tunnel",
"]",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'Shutting down tunnel {0}'",
".",
"format",
"(",
"tunnel",
")",
")",
"_srv",
".",
"shutdown",
"(",
")",
"_srv",
".",
"server_close",
"(",
")",
"# clean up the UNIX domain socket if we're using one",
"if",
"isinstance",
"(",
"_srv",
",",
"_UnixStreamForwardServer",
")",
":",
"try",
":",
"os",
".",
"unlink",
"(",
"_srv",
".",
"local_address",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"logger",
".",
"error",
"(",
"'Unable to unlink socket {0}: {1}'",
".",
"format",
"(",
"self",
".",
"local_address",
",",
"repr",
"(",
"e",
")",
")",
")",
"self",
".",
"is_alive",
"=",
"False",
"if",
"self",
".",
"is_active",
":",
"self",
".",
"_transport",
".",
"close",
"(",
")",
"self",
".",
"_transport",
".",
"stop_thread",
"(",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"'Transport is closed'",
")"
] | Close the underlying transport when nothing more is needed | [
"Close",
"the",
"underlying",
"transport",
"when",
"nothing",
"more",
"is",
"needed"
] | 66a923e4c6c8e41b8348420523fbf5ddfd53176c | https://github.com/pahaz/sshtunnel/blob/66a923e4c6c8e41b8348420523fbf5ddfd53176c/sshtunnel.py#L1398-L1422 |
3,905 | pahaz/sshtunnel | sshtunnel.py | SSHTunnelForwarder.local_bind_ports | def local_bind_ports(self):
"""
Return a list containing the ports of local side of the TCP tunnels
"""
self._check_is_started()
return [_server.local_port for _server in self._server_list if
_server.local_port is not None] | python | def local_bind_ports(self):
"""
Return a list containing the ports of local side of the TCP tunnels
"""
self._check_is_started()
return [_server.local_port for _server in self._server_list if
_server.local_port is not None] | [
"def",
"local_bind_ports",
"(",
"self",
")",
":",
"self",
".",
"_check_is_started",
"(",
")",
"return",
"[",
"_server",
".",
"local_port",
"for",
"_server",
"in",
"self",
".",
"_server_list",
"if",
"_server",
".",
"local_port",
"is",
"not",
"None",
"]"
] | Return a list containing the ports of local side of the TCP tunnels | [
"Return",
"a",
"list",
"containing",
"the",
"ports",
"of",
"local",
"side",
"of",
"the",
"TCP",
"tunnels"
] | 66a923e4c6c8e41b8348420523fbf5ddfd53176c | https://github.com/pahaz/sshtunnel/blob/66a923e4c6c8e41b8348420523fbf5ddfd53176c/sshtunnel.py#L1455-L1461 |
3,906 | pahaz/sshtunnel | sshtunnel.py | SSHTunnelForwarder.local_bind_hosts | def local_bind_hosts(self):
"""
Return a list containing the IP addresses listening for the tunnels
"""
self._check_is_started()
return [_server.local_host for _server in self._server_list if
_server.local_host is not None] | python | def local_bind_hosts(self):
"""
Return a list containing the IP addresses listening for the tunnels
"""
self._check_is_started()
return [_server.local_host for _server in self._server_list if
_server.local_host is not None] | [
"def",
"local_bind_hosts",
"(",
"self",
")",
":",
"self",
".",
"_check_is_started",
"(",
")",
"return",
"[",
"_server",
".",
"local_host",
"for",
"_server",
"in",
"self",
".",
"_server_list",
"if",
"_server",
".",
"local_host",
"is",
"not",
"None",
"]"
] | Return a list containing the IP addresses listening for the tunnels | [
"Return",
"a",
"list",
"containing",
"the",
"IP",
"addresses",
"listening",
"for",
"the",
"tunnels"
] | 66a923e4c6c8e41b8348420523fbf5ddfd53176c | https://github.com/pahaz/sshtunnel/blob/66a923e4c6c8e41b8348420523fbf5ddfd53176c/sshtunnel.py#L1464-L1470 |
3,907 | DMSC-Instrument-Data/lewis | src/lewis/core/utils.py | get_submodules | def get_submodules(module):
"""
This function imports all sub-modules of the supplied module and returns a dictionary
with module names as keys and the sub-module objects as values. If the supplied parameter
is not a module object, a RuntimeError is raised.
:param module: Module object from which to import sub-modules.
:return: Dict with name-module pairs.
"""
if not inspect.ismodule(module):
raise RuntimeError(
'Can only extract submodules from a module object, '
'for example imported via importlib.import_module')
submodules = get_members(module, inspect.ismodule)
module_path = list(getattr(module, '__path__', [None]))[0]
if module_path is not None:
for item in listdir(module_path):
module_name = extract_module_name(osp.join(module_path, item))
if module_name is not None:
try:
submodules[module_name] = importlib.import_module(
'.{}'.format(module_name), package=module.__name__)
except ImportError:
# This is necessary in case random directories are in the path or things can
# just not be imported due to other ImportErrors.
pass
return submodules | python | def get_submodules(module):
"""
This function imports all sub-modules of the supplied module and returns a dictionary
with module names as keys and the sub-module objects as values. If the supplied parameter
is not a module object, a RuntimeError is raised.
:param module: Module object from which to import sub-modules.
:return: Dict with name-module pairs.
"""
if not inspect.ismodule(module):
raise RuntimeError(
'Can only extract submodules from a module object, '
'for example imported via importlib.import_module')
submodules = get_members(module, inspect.ismodule)
module_path = list(getattr(module, '__path__', [None]))[0]
if module_path is not None:
for item in listdir(module_path):
module_name = extract_module_name(osp.join(module_path, item))
if module_name is not None:
try:
submodules[module_name] = importlib.import_module(
'.{}'.format(module_name), package=module.__name__)
except ImportError:
# This is necessary in case random directories are in the path or things can
# just not be imported due to other ImportErrors.
pass
return submodules | [
"def",
"get_submodules",
"(",
"module",
")",
":",
"if",
"not",
"inspect",
".",
"ismodule",
"(",
"module",
")",
":",
"raise",
"RuntimeError",
"(",
"'Can only extract submodules from a module object, '",
"'for example imported via importlib.import_module'",
")",
"submodules",
"=",
"get_members",
"(",
"module",
",",
"inspect",
".",
"ismodule",
")",
"module_path",
"=",
"list",
"(",
"getattr",
"(",
"module",
",",
"'__path__'",
",",
"[",
"None",
"]",
")",
")",
"[",
"0",
"]",
"if",
"module_path",
"is",
"not",
"None",
":",
"for",
"item",
"in",
"listdir",
"(",
"module_path",
")",
":",
"module_name",
"=",
"extract_module_name",
"(",
"osp",
".",
"join",
"(",
"module_path",
",",
"item",
")",
")",
"if",
"module_name",
"is",
"not",
"None",
":",
"try",
":",
"submodules",
"[",
"module_name",
"]",
"=",
"importlib",
".",
"import_module",
"(",
"'.{}'",
".",
"format",
"(",
"module_name",
")",
",",
"package",
"=",
"module",
".",
"__name__",
")",
"except",
"ImportError",
":",
"# This is necessary in case random directories are in the path or things can",
"# just not be imported due to other ImportErrors.",
"pass",
"return",
"submodules"
] | This function imports all sub-modules of the supplied module and returns a dictionary
with module names as keys and the sub-module objects as values. If the supplied parameter
is not a module object, a RuntimeError is raised.
:param module: Module object from which to import sub-modules.
:return: Dict with name-module pairs. | [
"This",
"function",
"imports",
"all",
"sub",
"-",
"modules",
"of",
"the",
"supplied",
"module",
"and",
"returns",
"a",
"dictionary",
"with",
"module",
"names",
"as",
"keys",
"and",
"the",
"sub",
"-",
"module",
"objects",
"as",
"values",
".",
"If",
"the",
"supplied",
"parameter",
"is",
"not",
"a",
"module",
"object",
"a",
"RuntimeError",
"is",
"raised",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/core/utils.py#L42-L73 |
3,908 | DMSC-Instrument-Data/lewis | src/lewis/core/utils.py | extract_module_name | def extract_module_name(absolute_path):
"""
This function tries to extract a valid module name from the basename of the supplied path.
If it's a directory, the directory name is returned, if it's a file, the file name
without extension is returned. If the basename starts with _ or . or it's a file with an
ending different from .py, the function returns None
:param absolute_path: Absolute path of something that might be a module.
:return: Module name or None.
"""
base_name = osp.basename(osp.normpath(absolute_path))
# If the basename starts with _ it's probably __init__.py or __pycache__ or something internal.
# At the moment there seems to be no use case for those
if base_name[0] in ('.', '_'):
return None
# If it's a directory, there's nothing else to check, so it can be returned directly
if osp.isdir(absolute_path):
return base_name
module_name, extension = osp.splitext(base_name)
# If it's a file, it must have a .py ending
if extension == '.py':
return module_name
return None | python | def extract_module_name(absolute_path):
"""
This function tries to extract a valid module name from the basename of the supplied path.
If it's a directory, the directory name is returned, if it's a file, the file name
without extension is returned. If the basename starts with _ or . or it's a file with an
ending different from .py, the function returns None
:param absolute_path: Absolute path of something that might be a module.
:return: Module name or None.
"""
base_name = osp.basename(osp.normpath(absolute_path))
# If the basename starts with _ it's probably __init__.py or __pycache__ or something internal.
# At the moment there seems to be no use case for those
if base_name[0] in ('.', '_'):
return None
# If it's a directory, there's nothing else to check, so it can be returned directly
if osp.isdir(absolute_path):
return base_name
module_name, extension = osp.splitext(base_name)
# If it's a file, it must have a .py ending
if extension == '.py':
return module_name
return None | [
"def",
"extract_module_name",
"(",
"absolute_path",
")",
":",
"base_name",
"=",
"osp",
".",
"basename",
"(",
"osp",
".",
"normpath",
"(",
"absolute_path",
")",
")",
"# If the basename starts with _ it's probably __init__.py or __pycache__ or something internal.",
"# At the moment there seems to be no use case for those",
"if",
"base_name",
"[",
"0",
"]",
"in",
"(",
"'.'",
",",
"'_'",
")",
":",
"return",
"None",
"# If it's a directory, there's nothing else to check, so it can be returned directly",
"if",
"osp",
".",
"isdir",
"(",
"absolute_path",
")",
":",
"return",
"base_name",
"module_name",
",",
"extension",
"=",
"osp",
".",
"splitext",
"(",
"base_name",
")",
"# If it's a file, it must have a .py ending",
"if",
"extension",
"==",
"'.py'",
":",
"return",
"module_name",
"return",
"None"
] | This function tries to extract a valid module name from the basename of the supplied path.
If it's a directory, the directory name is returned, if it's a file, the file name
without extension is returned. If the basename starts with _ or . or it's a file with an
ending different from .py, the function returns None
:param absolute_path: Absolute path of something that might be a module.
:return: Module name or None. | [
"This",
"function",
"tries",
"to",
"extract",
"a",
"valid",
"module",
"name",
"from",
"the",
"basename",
"of",
"the",
"supplied",
"path",
".",
"If",
"it",
"s",
"a",
"directory",
"the",
"directory",
"name",
"is",
"returned",
"if",
"it",
"s",
"a",
"file",
"the",
"file",
"name",
"without",
"extension",
"is",
"returned",
".",
"If",
"the",
"basename",
"starts",
"with",
"_",
"or",
".",
"or",
"it",
"s",
"a",
"file",
"with",
"an",
"ending",
"different",
"from",
".",
"py",
"the",
"function",
"returns",
"None"
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/core/utils.py#L97-L124 |
3,909 | DMSC-Instrument-Data/lewis | src/lewis/core/utils.py | dict_strict_update | def dict_strict_update(base_dict, update_dict):
"""
This function updates base_dict with update_dict if and only if update_dict does not contain
keys that are not already in base_dict. It is essentially a more strict interpretation of the
term "updating" the dict.
If update_dict contains keys that are not in base_dict, a RuntimeError is raised.
:param base_dict: The dict that is to be updated. This dict is modified.
:param update_dict: The dict containing the new values.
"""
additional_keys = set(update_dict.keys()) - set(base_dict.keys())
if len(additional_keys) > 0:
raise RuntimeError(
'The update dictionary contains keys that are not part of '
'the base dictionary: {}'.format(str(additional_keys)),
additional_keys)
base_dict.update(update_dict) | python | def dict_strict_update(base_dict, update_dict):
"""
This function updates base_dict with update_dict if and only if update_dict does not contain
keys that are not already in base_dict. It is essentially a more strict interpretation of the
term "updating" the dict.
If update_dict contains keys that are not in base_dict, a RuntimeError is raised.
:param base_dict: The dict that is to be updated. This dict is modified.
:param update_dict: The dict containing the new values.
"""
additional_keys = set(update_dict.keys()) - set(base_dict.keys())
if len(additional_keys) > 0:
raise RuntimeError(
'The update dictionary contains keys that are not part of '
'the base dictionary: {}'.format(str(additional_keys)),
additional_keys)
base_dict.update(update_dict) | [
"def",
"dict_strict_update",
"(",
"base_dict",
",",
"update_dict",
")",
":",
"additional_keys",
"=",
"set",
"(",
"update_dict",
".",
"keys",
"(",
")",
")",
"-",
"set",
"(",
"base_dict",
".",
"keys",
"(",
")",
")",
"if",
"len",
"(",
"additional_keys",
")",
">",
"0",
":",
"raise",
"RuntimeError",
"(",
"'The update dictionary contains keys that are not part of '",
"'the base dictionary: {}'",
".",
"format",
"(",
"str",
"(",
"additional_keys",
")",
")",
",",
"additional_keys",
")",
"base_dict",
".",
"update",
"(",
"update_dict",
")"
] | This function updates base_dict with update_dict if and only if update_dict does not contain
keys that are not already in base_dict. It is essentially a more strict interpretation of the
term "updating" the dict.
If update_dict contains keys that are not in base_dict, a RuntimeError is raised.
:param base_dict: The dict that is to be updated. This dict is modified.
:param update_dict: The dict containing the new values. | [
"This",
"function",
"updates",
"base_dict",
"with",
"update_dict",
"if",
"and",
"only",
"if",
"update_dict",
"does",
"not",
"contain",
"keys",
"that",
"are",
"not",
"already",
"in",
"base_dict",
".",
"It",
"is",
"essentially",
"a",
"more",
"strict",
"interpretation",
"of",
"the",
"term",
"updating",
"the",
"dict",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/core/utils.py#L127-L145 |
3,910 | DMSC-Instrument-Data/lewis | src/lewis/core/utils.py | format_doc_text | def format_doc_text(text):
"""
A very thin wrapper around textwrap.fill to consistently wrap documentation text
for display in a command line environment. The text is wrapped to 99 characters with an
indentation depth of 4 spaces. Each line is wrapped independently in order to preserve
manually added line breaks.
:param text: The text to format, it is cleaned by inspect.cleandoc.
:return: The formatted doc text.
"""
return '\n'.join(
textwrap.fill(line, width=99, initial_indent=' ', subsequent_indent=' ')
for line in inspect.cleandoc(text).splitlines()) | python | def format_doc_text(text):
"""
A very thin wrapper around textwrap.fill to consistently wrap documentation text
for display in a command line environment. The text is wrapped to 99 characters with an
indentation depth of 4 spaces. Each line is wrapped independently in order to preserve
manually added line breaks.
:param text: The text to format, it is cleaned by inspect.cleandoc.
:return: The formatted doc text.
"""
return '\n'.join(
textwrap.fill(line, width=99, initial_indent=' ', subsequent_indent=' ')
for line in inspect.cleandoc(text).splitlines()) | [
"def",
"format_doc_text",
"(",
"text",
")",
":",
"return",
"'\\n'",
".",
"join",
"(",
"textwrap",
".",
"fill",
"(",
"line",
",",
"width",
"=",
"99",
",",
"initial_indent",
"=",
"' '",
",",
"subsequent_indent",
"=",
"' '",
")",
"for",
"line",
"in",
"inspect",
".",
"cleandoc",
"(",
"text",
")",
".",
"splitlines",
"(",
")",
")"
] | A very thin wrapper around textwrap.fill to consistently wrap documentation text
for display in a command line environment. The text is wrapped to 99 characters with an
indentation depth of 4 spaces. Each line is wrapped independently in order to preserve
manually added line breaks.
:param text: The text to format, it is cleaned by inspect.cleandoc.
:return: The formatted doc text. | [
"A",
"very",
"thin",
"wrapper",
"around",
"textwrap",
".",
"fill",
"to",
"consistently",
"wrap",
"documentation",
"text",
"for",
"display",
"in",
"a",
"command",
"line",
"environment",
".",
"The",
"text",
"is",
"wrapped",
"to",
"99",
"characters",
"with",
"an",
"indentation",
"depth",
"of",
"4",
"spaces",
".",
"Each",
"line",
"is",
"wrapped",
"independently",
"in",
"order",
"to",
"preserve",
"manually",
"added",
"line",
"breaks",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/core/utils.py#L250-L263 |
3,911 | DMSC-Instrument-Data/lewis | src/lewis/core/utils.py | FromOptionalDependency.do_import | def do_import(self, *names):
"""
Tries to import names from the module specified on initialization
of the FromOptionalDependency-object. In case an ImportError occurs,
the requested names are replaced with stub objects.
:param names: List of strings that are used as type names.
:return: Tuple of actual symbols or stub types with provided names. If there is only one
element in the tuple, that element is returned.
"""
try:
module_object = importlib.import_module(self._module)
objects = tuple(getattr(module_object, name) for name in names)
except ImportError:
def failing_init(obj, *args, **kwargs):
raise self._exception
objects = tuple(type(name, (object,), {'__init__': failing_init})
for name in names)
return objects if len(objects) != 1 else objects[0] | python | def do_import(self, *names):
"""
Tries to import names from the module specified on initialization
of the FromOptionalDependency-object. In case an ImportError occurs,
the requested names are replaced with stub objects.
:param names: List of strings that are used as type names.
:return: Tuple of actual symbols or stub types with provided names. If there is only one
element in the tuple, that element is returned.
"""
try:
module_object = importlib.import_module(self._module)
objects = tuple(getattr(module_object, name) for name in names)
except ImportError:
def failing_init(obj, *args, **kwargs):
raise self._exception
objects = tuple(type(name, (object,), {'__init__': failing_init})
for name in names)
return objects if len(objects) != 1 else objects[0] | [
"def",
"do_import",
"(",
"self",
",",
"*",
"names",
")",
":",
"try",
":",
"module_object",
"=",
"importlib",
".",
"import_module",
"(",
"self",
".",
"_module",
")",
"objects",
"=",
"tuple",
"(",
"getattr",
"(",
"module_object",
",",
"name",
")",
"for",
"name",
"in",
"names",
")",
"except",
"ImportError",
":",
"def",
"failing_init",
"(",
"obj",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"raise",
"self",
".",
"_exception",
"objects",
"=",
"tuple",
"(",
"type",
"(",
"name",
",",
"(",
"object",
",",
")",
",",
"{",
"'__init__'",
":",
"failing_init",
"}",
")",
"for",
"name",
"in",
"names",
")",
"return",
"objects",
"if",
"len",
"(",
"objects",
")",
"!=",
"1",
"else",
"objects",
"[",
"0",
"]"
] | Tries to import names from the module specified on initialization
of the FromOptionalDependency-object. In case an ImportError occurs,
the requested names are replaced with stub objects.
:param names: List of strings that are used as type names.
:return: Tuple of actual symbols or stub types with provided names. If there is only one
element in the tuple, that element is returned. | [
"Tries",
"to",
"import",
"names",
"from",
"the",
"module",
"specified",
"on",
"initialization",
"of",
"the",
"FromOptionalDependency",
"-",
"object",
".",
"In",
"case",
"an",
"ImportError",
"occurs",
"the",
"requested",
"names",
"are",
"replaced",
"with",
"stub",
"objects",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/core/utils.py#L226-L247 |
3,912 | DMSC-Instrument-Data/lewis | src/lewis/core/control_server.py | ExposedObject.get_api | def get_api(self):
"""
This method returns the class name and a list of exposed methods.
It is exposed to RPC-clients by an instance of ExposedObjectCollection.
:return: A dictionary describing the exposed API (consisting of a class name and methods).
"""
return {'class': type(self._object).__name__, 'methods': list(self._function_map.keys())} | python | def get_api(self):
"""
This method returns the class name and a list of exposed methods.
It is exposed to RPC-clients by an instance of ExposedObjectCollection.
:return: A dictionary describing the exposed API (consisting of a class name and methods).
"""
return {'class': type(self._object).__name__, 'methods': list(self._function_map.keys())} | [
"def",
"get_api",
"(",
"self",
")",
":",
"return",
"{",
"'class'",
":",
"type",
"(",
"self",
".",
"_object",
")",
".",
"__name__",
",",
"'methods'",
":",
"list",
"(",
"self",
".",
"_function_map",
".",
"keys",
"(",
")",
")",
"}"
] | This method returns the class name and a list of exposed methods.
It is exposed to RPC-clients by an instance of ExposedObjectCollection.
:return: A dictionary describing the exposed API (consisting of a class name and methods). | [
"This",
"method",
"returns",
"the",
"class",
"name",
"and",
"a",
"list",
"of",
"exposed",
"methods",
".",
"It",
"is",
"exposed",
"to",
"RPC",
"-",
"clients",
"by",
"an",
"instance",
"of",
"ExposedObjectCollection",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/core/control_server.py#L121-L128 |
3,913 | DMSC-Instrument-Data/lewis | src/lewis/core/control_server.py | ExposedObjectCollection.remove_object | def remove_object(self, name):
"""
Remove the object exposed under that name. If no object is registered under the supplied
name, a RuntimeError is raised.
:param name: Name of object to be removed.
"""
if name not in self._object_map:
raise RuntimeError('No object with name {} is registered.'.format(name))
for fn_name in list(self._function_map.keys()):
if fn_name.startswith(name + '.') or fn_name.startswith(name + ':'):
self._remove_function(fn_name)
del self._object_map[name] | python | def remove_object(self, name):
"""
Remove the object exposed under that name. If no object is registered under the supplied
name, a RuntimeError is raised.
:param name: Name of object to be removed.
"""
if name not in self._object_map:
raise RuntimeError('No object with name {} is registered.'.format(name))
for fn_name in list(self._function_map.keys()):
if fn_name.startswith(name + '.') or fn_name.startswith(name + ':'):
self._remove_function(fn_name)
del self._object_map[name] | [
"def",
"remove_object",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"not",
"in",
"self",
".",
"_object_map",
":",
"raise",
"RuntimeError",
"(",
"'No object with name {} is registered.'",
".",
"format",
"(",
"name",
")",
")",
"for",
"fn_name",
"in",
"list",
"(",
"self",
".",
"_function_map",
".",
"keys",
"(",
")",
")",
":",
"if",
"fn_name",
".",
"startswith",
"(",
"name",
"+",
"'.'",
")",
"or",
"fn_name",
".",
"startswith",
"(",
"name",
"+",
"':'",
")",
":",
"self",
".",
"_remove_function",
"(",
"fn_name",
")",
"del",
"self",
".",
"_object_map",
"[",
"name",
"]"
] | Remove the object exposed under that name. If no object is registered under the supplied
name, a RuntimeError is raised.
:param name: Name of object to be removed. | [
"Remove",
"the",
"object",
"exposed",
"under",
"that",
"name",
".",
"If",
"no",
"object",
"is",
"registered",
"under",
"the",
"supplied",
"name",
"a",
"RuntimeError",
"is",
"raised",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/core/control_server.py#L219-L233 |
3,914 | DMSC-Instrument-Data/lewis | src/lewis/devices/julabo/devices/device.py | SimulatedJulabo.set_set_point | def set_set_point(self, param):
"""
Sets the target temperature.
:param param: The new temperature in C. Must be positive.
:return: Empty string.
"""
if self.temperature_low_limit <= param <= self.temperature_high_limit:
self.set_point_temperature = param
return "" | python | def set_set_point(self, param):
"""
Sets the target temperature.
:param param: The new temperature in C. Must be positive.
:return: Empty string.
"""
if self.temperature_low_limit <= param <= self.temperature_high_limit:
self.set_point_temperature = param
return "" | [
"def",
"set_set_point",
"(",
"self",
",",
"param",
")",
":",
"if",
"self",
".",
"temperature_low_limit",
"<=",
"param",
"<=",
"self",
".",
"temperature_high_limit",
":",
"self",
".",
"set_point_temperature",
"=",
"param",
"return",
"\"\""
] | Sets the target temperature.
:param param: The new temperature in C. Must be positive.
:return: Empty string. | [
"Sets",
"the",
"target",
"temperature",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/devices/julabo/devices/device.py#L73-L82 |
3,915 | DMSC-Instrument-Data/lewis | src/lewis/devices/julabo/devices/device.py | SimulatedJulabo.set_circulating | def set_circulating(self, param):
"""
Sets whether to circulate - in effect whether the heater is on.
:param param: The mode to set, must be 0 or 1.
:return: Empty string.
"""
if param == 0:
self.is_circulating = param
self.circulate_commanded = False
elif param == 1:
self.is_circulating = param
self.circulate_commanded = True
return "" | python | def set_circulating(self, param):
"""
Sets whether to circulate - in effect whether the heater is on.
:param param: The mode to set, must be 0 or 1.
:return: Empty string.
"""
if param == 0:
self.is_circulating = param
self.circulate_commanded = False
elif param == 1:
self.is_circulating = param
self.circulate_commanded = True
return "" | [
"def",
"set_circulating",
"(",
"self",
",",
"param",
")",
":",
"if",
"param",
"==",
"0",
":",
"self",
".",
"is_circulating",
"=",
"param",
"self",
".",
"circulate_commanded",
"=",
"False",
"elif",
"param",
"==",
"1",
":",
"self",
".",
"is_circulating",
"=",
"param",
"self",
".",
"circulate_commanded",
"=",
"True",
"return",
"\"\""
] | Sets whether to circulate - in effect whether the heater is on.
:param param: The mode to set, must be 0 or 1.
:return: Empty string. | [
"Sets",
"whether",
"to",
"circulate",
"-",
"in",
"effect",
"whether",
"the",
"heater",
"is",
"on",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/devices/julabo/devices/device.py#L84-L97 |
3,916 | DMSC-Instrument-Data/lewis | src/lewis/core/simulation.py | SimulationFactory.get_protocols | def get_protocols(self, device):
"""Returns a list of available protocols for the specified device."""
return self._reg.device_builder(device, self._rv).protocols | python | def get_protocols(self, device):
"""Returns a list of available protocols for the specified device."""
return self._reg.device_builder(device, self._rv).protocols | [
"def",
"get_protocols",
"(",
"self",
",",
"device",
")",
":",
"return",
"self",
".",
"_reg",
".",
"device_builder",
"(",
"device",
",",
"self",
".",
"_rv",
")",
".",
"protocols"
] | Returns a list of available protocols for the specified device. | [
"Returns",
"a",
"list",
"of",
"available",
"protocols",
"for",
"the",
"specified",
"device",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/core/simulation.py#L433-L435 |
3,917 | DMSC-Instrument-Data/lewis | src/lewis/core/approaches.py | linear | def linear(current, target, rate, dt):
"""
This function returns the new value after moving towards
target at the given speed constantly for the time dt.
If for example the current position is 10 and the target is -20,
the returned value will be less than 10 if rate and dt are greater
than 0:
.. sourcecode:: Python
new_pos = linear(10, -20, 10, 0.1) # new_pos = 9
The function makes sure that the returned value never overshoots:
.. sourcecode:: Python
new_pos = linear(10, -20, 10, 100) # new_pos = -20
:param current: The current value of the variable to be changed.
:param target: The target value to approach.
:param rate: The rate at which the parameter should move towards target.
:param dt: The time for which to calculate the change.
:return: The new variable value.
"""
sign = (target > current) - (target < current)
if not sign:
return current
new_value = current + sign * rate * dt
if sign * new_value > sign * target:
return target
return new_value | python | def linear(current, target, rate, dt):
"""
This function returns the new value after moving towards
target at the given speed constantly for the time dt.
If for example the current position is 10 and the target is -20,
the returned value will be less than 10 if rate and dt are greater
than 0:
.. sourcecode:: Python
new_pos = linear(10, -20, 10, 0.1) # new_pos = 9
The function makes sure that the returned value never overshoots:
.. sourcecode:: Python
new_pos = linear(10, -20, 10, 100) # new_pos = -20
:param current: The current value of the variable to be changed.
:param target: The target value to approach.
:param rate: The rate at which the parameter should move towards target.
:param dt: The time for which to calculate the change.
:return: The new variable value.
"""
sign = (target > current) - (target < current)
if not sign:
return current
new_value = current + sign * rate * dt
if sign * new_value > sign * target:
return target
return new_value | [
"def",
"linear",
"(",
"current",
",",
"target",
",",
"rate",
",",
"dt",
")",
":",
"sign",
"=",
"(",
"target",
">",
"current",
")",
"-",
"(",
"target",
"<",
"current",
")",
"if",
"not",
"sign",
":",
"return",
"current",
"new_value",
"=",
"current",
"+",
"sign",
"*",
"rate",
"*",
"dt",
"if",
"sign",
"*",
"new_value",
">",
"sign",
"*",
"target",
":",
"return",
"target",
"return",
"new_value"
] | This function returns the new value after moving towards
target at the given speed constantly for the time dt.
If for example the current position is 10 and the target is -20,
the returned value will be less than 10 if rate and dt are greater
than 0:
.. sourcecode:: Python
new_pos = linear(10, -20, 10, 0.1) # new_pos = 9
The function makes sure that the returned value never overshoots:
.. sourcecode:: Python
new_pos = linear(10, -20, 10, 100) # new_pos = -20
:param current: The current value of the variable to be changed.
:param target: The target value to approach.
:param rate: The rate at which the parameter should move towards target.
:param dt: The time for which to calculate the change.
:return: The new variable value. | [
"This",
"function",
"returns",
"the",
"new",
"value",
"after",
"moving",
"towards",
"target",
"at",
"the",
"given",
"speed",
"constantly",
"for",
"the",
"time",
"dt",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/core/approaches.py#L26-L61 |
3,918 | DMSC-Instrument-Data/lewis | src/lewis/adapters/epics.py | BoundPV.meta | def meta(self):
"""Value of the bound meta-property on the target."""
if not self._pv.meta_data_property or not self._meta_target:
return {}
return getattr(self._meta_target, self._pv.meta_data_property) | python | def meta(self):
"""Value of the bound meta-property on the target."""
if not self._pv.meta_data_property or not self._meta_target:
return {}
return getattr(self._meta_target, self._pv.meta_data_property) | [
"def",
"meta",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_pv",
".",
"meta_data_property",
"or",
"not",
"self",
".",
"_meta_target",
":",
"return",
"{",
"}",
"return",
"getattr",
"(",
"self",
".",
"_meta_target",
",",
"self",
".",
"_pv",
".",
"meta_data_property",
")"
] | Value of the bound meta-property on the target. | [
"Value",
"of",
"the",
"bound",
"meta",
"-",
"property",
"on",
"the",
"target",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/adapters/epics.py#L93-L98 |
3,919 | DMSC-Instrument-Data/lewis | src/lewis/adapters/epics.py | BoundPV.doc | def doc(self):
"""Docstring of property on target or override specified on PV-object."""
return self._pv.doc or inspect.getdoc(
getattr(type(self._target), self._pv.property, None)) or '' | python | def doc(self):
"""Docstring of property on target or override specified on PV-object."""
return self._pv.doc or inspect.getdoc(
getattr(type(self._target), self._pv.property, None)) or '' | [
"def",
"doc",
"(",
"self",
")",
":",
"return",
"self",
".",
"_pv",
".",
"doc",
"or",
"inspect",
".",
"getdoc",
"(",
"getattr",
"(",
"type",
"(",
"self",
".",
"_target",
")",
",",
"self",
".",
"_pv",
".",
"property",
",",
"None",
")",
")",
"or",
"''"
] | Docstring of property on target or override specified on PV-object. | [
"Docstring",
"of",
"property",
"on",
"target",
"or",
"override",
"specified",
"on",
"PV",
"-",
"object",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/adapters/epics.py#L116-L119 |
3,920 | DMSC-Instrument-Data/lewis | src/lewis/adapters/epics.py | PV.bind | def bind(self, *targets):
"""
Tries to bind the PV to one of the supplied targets. Targets are inspected according to
the order in which they are supplied.
:param targets: Objects to inspect from.
:return: BoundPV instance with the PV bound to the target property.
"""
self.property = 'value'
self.meta_data_property = 'meta'
return BoundPV(self,
self._get_target(self.property, *targets),
self._get_target(self.meta_data_property, *targets)) | python | def bind(self, *targets):
"""
Tries to bind the PV to one of the supplied targets. Targets are inspected according to
the order in which they are supplied.
:param targets: Objects to inspect from.
:return: BoundPV instance with the PV bound to the target property.
"""
self.property = 'value'
self.meta_data_property = 'meta'
return BoundPV(self,
self._get_target(self.property, *targets),
self._get_target(self.meta_data_property, *targets)) | [
"def",
"bind",
"(",
"self",
",",
"*",
"targets",
")",
":",
"self",
".",
"property",
"=",
"'value'",
"self",
".",
"meta_data_property",
"=",
"'meta'",
"return",
"BoundPV",
"(",
"self",
",",
"self",
".",
"_get_target",
"(",
"self",
".",
"property",
",",
"*",
"targets",
")",
",",
"self",
".",
"_get_target",
"(",
"self",
".",
"meta_data_property",
",",
"*",
"targets",
")",
")"
] | Tries to bind the PV to one of the supplied targets. Targets are inspected according to
the order in which they are supplied.
:param targets: Objects to inspect from.
:return: BoundPV instance with the PV bound to the target property. | [
"Tries",
"to",
"bind",
"the",
"PV",
"to",
"one",
"of",
"the",
"supplied",
"targets",
".",
"Targets",
"are",
"inspected",
"according",
"to",
"the",
"order",
"in",
"which",
"they",
"are",
"supplied",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/adapters/epics.py#L224-L237 |
3,921 | DMSC-Instrument-Data/lewis | src/lewis/adapters/epics.py | PV._get_callable | def _get_callable(self, func, *targets):
"""
If func is already a callable, it is returned directly. If it's a string, it is assumed
to be a method on one of the objects supplied in targets and that is returned. If no
method with the specified name is found, an AttributeError is raised.
:param func: Callable or name of method on one object in targets.
:param targets: List of targets with decreasing priority for finding func.
:return: Callable.
"""
if not callable(func):
func_name = func
func = next((getattr(obj, func, None) for obj in targets if func in dir(obj)),
None)
if not func:
raise AttributeError(
'No method with the name \'{}\' could be found on any of the target objects '
'(device, interface). Please check the spelling.'.format(func_name))
return func | python | def _get_callable(self, func, *targets):
"""
If func is already a callable, it is returned directly. If it's a string, it is assumed
to be a method on one of the objects supplied in targets and that is returned. If no
method with the specified name is found, an AttributeError is raised.
:param func: Callable or name of method on one object in targets.
:param targets: List of targets with decreasing priority for finding func.
:return: Callable.
"""
if not callable(func):
func_name = func
func = next((getattr(obj, func, None) for obj in targets if func in dir(obj)),
None)
if not func:
raise AttributeError(
'No method with the name \'{}\' could be found on any of the target objects '
'(device, interface). Please check the spelling.'.format(func_name))
return func | [
"def",
"_get_callable",
"(",
"self",
",",
"func",
",",
"*",
"targets",
")",
":",
"if",
"not",
"callable",
"(",
"func",
")",
":",
"func_name",
"=",
"func",
"func",
"=",
"next",
"(",
"(",
"getattr",
"(",
"obj",
",",
"func",
",",
"None",
")",
"for",
"obj",
"in",
"targets",
"if",
"func",
"in",
"dir",
"(",
"obj",
")",
")",
",",
"None",
")",
"if",
"not",
"func",
":",
"raise",
"AttributeError",
"(",
"'No method with the name \\'{}\\' could be found on any of the target objects '",
"'(device, interface). Please check the spelling.'",
".",
"format",
"(",
"func_name",
")",
")",
"return",
"func"
] | If func is already a callable, it is returned directly. If it's a string, it is assumed
to be a method on one of the objects supplied in targets and that is returned. If no
method with the specified name is found, an AttributeError is raised.
:param func: Callable or name of method on one object in targets.
:param targets: List of targets with decreasing priority for finding func.
:return: Callable. | [
"If",
"func",
"is",
"already",
"a",
"callable",
"it",
"is",
"returned",
"directly",
".",
"If",
"it",
"s",
"a",
"string",
"it",
"is",
"assumed",
"to",
"be",
"a",
"method",
"on",
"one",
"of",
"the",
"objects",
"supplied",
"in",
"targets",
"and",
"that",
"is",
"returned",
".",
"If",
"no",
"method",
"with",
"the",
"specified",
"name",
"is",
"found",
"an",
"AttributeError",
"is",
"raised",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/adapters/epics.py#L361-L381 |
3,922 | DMSC-Instrument-Data/lewis | src/lewis/adapters/epics.py | PV._function_has_n_args | def _function_has_n_args(self, func, n):
"""
Returns true if func has n arguments. Arguments with default and self for
methods are not considered.
"""
if inspect.ismethod(func):
n += 1
argspec = inspect.getargspec(func)
defaults = argspec.defaults or ()
return len(argspec.args) - len(defaults) == n | python | def _function_has_n_args(self, func, n):
"""
Returns true if func has n arguments. Arguments with default and self for
methods are not considered.
"""
if inspect.ismethod(func):
n += 1
argspec = inspect.getargspec(func)
defaults = argspec.defaults or ()
return len(argspec.args) - len(defaults) == n | [
"def",
"_function_has_n_args",
"(",
"self",
",",
"func",
",",
"n",
")",
":",
"if",
"inspect",
".",
"ismethod",
"(",
"func",
")",
":",
"n",
"+=",
"1",
"argspec",
"=",
"inspect",
".",
"getargspec",
"(",
"func",
")",
"defaults",
"=",
"argspec",
".",
"defaults",
"or",
"(",
")",
"return",
"len",
"(",
"argspec",
".",
"args",
")",
"-",
"len",
"(",
"defaults",
")",
"==",
"n"
] | Returns true if func has n arguments. Arguments with default and self for
methods are not considered. | [
"Returns",
"true",
"if",
"func",
"has",
"n",
"arguments",
".",
"Arguments",
"with",
"default",
"and",
"self",
"for",
"methods",
"are",
"not",
"considered",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/adapters/epics.py#L383-L394 |
3,923 | DMSC-Instrument-Data/lewis | src/lewis/adapters/epics.py | EpicsAdapter.start_server | def start_server(self):
"""
Creates a pcaspy-server.
.. note::
The server does not process requests unless :meth:`handle` is called regularly.
"""
if self._server is None:
self._server = SimpleServer()
self._server.createPV(prefix=self._options.prefix,
pvdb={k: v.config for k, v in self.interface.bound_pvs.items()})
self._driver = PropertyExposingDriver(interface=self.interface,
device_lock=self.device_lock)
self._driver.process_pv_updates(force=True)
self.log.info('Started serving PVs: %s',
', '.join((self._options.prefix + pv for pv in
self.interface.bound_pvs.keys()))) | python | def start_server(self):
"""
Creates a pcaspy-server.
.. note::
The server does not process requests unless :meth:`handle` is called regularly.
"""
if self._server is None:
self._server = SimpleServer()
self._server.createPV(prefix=self._options.prefix,
pvdb={k: v.config for k, v in self.interface.bound_pvs.items()})
self._driver = PropertyExposingDriver(interface=self.interface,
device_lock=self.device_lock)
self._driver.process_pv_updates(force=True)
self.log.info('Started serving PVs: %s',
', '.join((self._options.prefix + pv for pv in
self.interface.bound_pvs.keys()))) | [
"def",
"start_server",
"(",
"self",
")",
":",
"if",
"self",
".",
"_server",
"is",
"None",
":",
"self",
".",
"_server",
"=",
"SimpleServer",
"(",
")",
"self",
".",
"_server",
".",
"createPV",
"(",
"prefix",
"=",
"self",
".",
"_options",
".",
"prefix",
",",
"pvdb",
"=",
"{",
"k",
":",
"v",
".",
"config",
"for",
"k",
",",
"v",
"in",
"self",
".",
"interface",
".",
"bound_pvs",
".",
"items",
"(",
")",
"}",
")",
"self",
".",
"_driver",
"=",
"PropertyExposingDriver",
"(",
"interface",
"=",
"self",
".",
"interface",
",",
"device_lock",
"=",
"self",
".",
"device_lock",
")",
"self",
".",
"_driver",
".",
"process_pv_updates",
"(",
"force",
"=",
"True",
")",
"self",
".",
"log",
".",
"info",
"(",
"'Started serving PVs: %s'",
",",
"', '",
".",
"join",
"(",
"(",
"self",
".",
"_options",
".",
"prefix",
"+",
"pv",
"for",
"pv",
"in",
"self",
".",
"interface",
".",
"bound_pvs",
".",
"keys",
"(",
")",
")",
")",
")"
] | Creates a pcaspy-server.
.. note::
The server does not process requests unless :meth:`handle` is called regularly. | [
"Creates",
"a",
"pcaspy",
"-",
"server",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/adapters/epics.py#L550-L568 |
3,924 | DMSC-Instrument-Data/lewis | src/lewis/adapters/epics.py | EpicsAdapter.handle | def handle(self, cycle_delay=0.1):
"""
Call this method to spend about ``cycle_delay`` seconds processing
requests in the pcaspy server. Under load, for example when running ``caget`` at a
high frequency, the actual time spent in the method may be much shorter. This effect
is not corrected for.
:param cycle_delay: Approximate time to be spent processing requests in pcaspy server.
"""
if self._server is not None:
self._server.process(cycle_delay)
self._driver.process_pv_updates() | python | def handle(self, cycle_delay=0.1):
"""
Call this method to spend about ``cycle_delay`` seconds processing
requests in the pcaspy server. Under load, for example when running ``caget`` at a
high frequency, the actual time spent in the method may be much shorter. This effect
is not corrected for.
:param cycle_delay: Approximate time to be spent processing requests in pcaspy server.
"""
if self._server is not None:
self._server.process(cycle_delay)
self._driver.process_pv_updates() | [
"def",
"handle",
"(",
"self",
",",
"cycle_delay",
"=",
"0.1",
")",
":",
"if",
"self",
".",
"_server",
"is",
"not",
"None",
":",
"self",
".",
"_server",
".",
"process",
"(",
"cycle_delay",
")",
"self",
".",
"_driver",
".",
"process_pv_updates",
"(",
")"
] | Call this method to spend about ``cycle_delay`` seconds processing
requests in the pcaspy server. Under load, for example when running ``caget`` at a
high frequency, the actual time spent in the method may be much shorter. This effect
is not corrected for.
:param cycle_delay: Approximate time to be spent processing requests in pcaspy server. | [
"Call",
"this",
"method",
"to",
"spend",
"about",
"cycle_delay",
"seconds",
"processing",
"requests",
"in",
"the",
"pcaspy",
"server",
".",
"Under",
"load",
"for",
"example",
"when",
"running",
"caget",
"at",
"a",
"high",
"frequency",
"the",
"actual",
"time",
"spent",
"in",
"the",
"method",
"may",
"be",
"much",
"shorter",
".",
"This",
"effect",
"is",
"not",
"corrected",
"for",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/adapters/epics.py#L578-L589 |
3,925 | DMSC-Instrument-Data/lewis | src/lewis/core/control_client.py | ObjectProxy._make_request | def _make_request(self, method, *args):
"""
This method performs a JSON-RPC request via the object's ZMQ socket. If successful,
the result is returned, otherwise exceptions are raised. Server side exceptions are
raised using the same type as on the server if they are part of the exceptions-module.
Otherwise, a RemoteException is raised.
:param method: Method of the object to call on the remote.
:param args: Positional arguments to the method call.
:return: Result of the remote call if successful.
"""
response, request_id = self._connection.json_rpc(self._prefix + method, *args)
if 'id' not in response:
raise ProtocolException('JSON-RPC response does not contain ID field.')
if response['id'] != request_id:
raise ProtocolException(
'ID of JSON-RPC request ({}) did not match response ({}).'.format(
request_id, response['id']))
if 'result' in response:
return response['result']
if 'error' in response:
if 'data' in response['error']:
exception_type = response['error']['data']['type']
exception_message = response['error']['data']['message']
if not hasattr(exceptions, exception_type):
raise RemoteException(exception_type, exception_message)
else:
exception = getattr(exceptions, exception_type)
raise exception(exception_message)
else:
raise ProtocolException(response['error']['message']) | python | def _make_request(self, method, *args):
"""
This method performs a JSON-RPC request via the object's ZMQ socket. If successful,
the result is returned, otherwise exceptions are raised. Server side exceptions are
raised using the same type as on the server if they are part of the exceptions-module.
Otherwise, a RemoteException is raised.
:param method: Method of the object to call on the remote.
:param args: Positional arguments to the method call.
:return: Result of the remote call if successful.
"""
response, request_id = self._connection.json_rpc(self._prefix + method, *args)
if 'id' not in response:
raise ProtocolException('JSON-RPC response does not contain ID field.')
if response['id'] != request_id:
raise ProtocolException(
'ID of JSON-RPC request ({}) did not match response ({}).'.format(
request_id, response['id']))
if 'result' in response:
return response['result']
if 'error' in response:
if 'data' in response['error']:
exception_type = response['error']['data']['type']
exception_message = response['error']['data']['message']
if not hasattr(exceptions, exception_type):
raise RemoteException(exception_type, exception_message)
else:
exception = getattr(exceptions, exception_type)
raise exception(exception_message)
else:
raise ProtocolException(response['error']['message']) | [
"def",
"_make_request",
"(",
"self",
",",
"method",
",",
"*",
"args",
")",
":",
"response",
",",
"request_id",
"=",
"self",
".",
"_connection",
".",
"json_rpc",
"(",
"self",
".",
"_prefix",
"+",
"method",
",",
"*",
"args",
")",
"if",
"'id'",
"not",
"in",
"response",
":",
"raise",
"ProtocolException",
"(",
"'JSON-RPC response does not contain ID field.'",
")",
"if",
"response",
"[",
"'id'",
"]",
"!=",
"request_id",
":",
"raise",
"ProtocolException",
"(",
"'ID of JSON-RPC request ({}) did not match response ({}).'",
".",
"format",
"(",
"request_id",
",",
"response",
"[",
"'id'",
"]",
")",
")",
"if",
"'result'",
"in",
"response",
":",
"return",
"response",
"[",
"'result'",
"]",
"if",
"'error'",
"in",
"response",
":",
"if",
"'data'",
"in",
"response",
"[",
"'error'",
"]",
":",
"exception_type",
"=",
"response",
"[",
"'error'",
"]",
"[",
"'data'",
"]",
"[",
"'type'",
"]",
"exception_message",
"=",
"response",
"[",
"'error'",
"]",
"[",
"'data'",
"]",
"[",
"'message'",
"]",
"if",
"not",
"hasattr",
"(",
"exceptions",
",",
"exception_type",
")",
":",
"raise",
"RemoteException",
"(",
"exception_type",
",",
"exception_message",
")",
"else",
":",
"exception",
"=",
"getattr",
"(",
"exceptions",
",",
"exception_type",
")",
"raise",
"exception",
"(",
"exception_message",
")",
"else",
":",
"raise",
"ProtocolException",
"(",
"response",
"[",
"'error'",
"]",
"[",
"'message'",
"]",
")"
] | This method performs a JSON-RPC request via the object's ZMQ socket. If successful,
the result is returned, otherwise exceptions are raised. Server side exceptions are
raised using the same type as on the server if they are part of the exceptions-module.
Otherwise, a RemoteException is raised.
:param method: Method of the object to call on the remote.
:param args: Positional arguments to the method call.
:return: Result of the remote call if successful. | [
"This",
"method",
"performs",
"a",
"JSON",
"-",
"RPC",
"request",
"via",
"the",
"object",
"s",
"ZMQ",
"socket",
".",
"If",
"successful",
"the",
"result",
"is",
"returned",
"otherwise",
"exceptions",
"are",
"raised",
".",
"Server",
"side",
"exceptions",
"are",
"raised",
"using",
"the",
"same",
"type",
"as",
"on",
"the",
"server",
"if",
"they",
"are",
"part",
"of",
"the",
"exceptions",
"-",
"module",
".",
"Otherwise",
"a",
"RemoteException",
"is",
"raised",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/core/control_client.py#L194-L229 |
3,926 | DMSC-Instrument-Data/lewis | src/lewis/devices/linkam_t95/interfaces/stream_interface.py | LinkamT95StreamInterface.get_status | def get_status(self):
"""
Models "T Command" functionality of device.
Returns all available status information about the device as single byte array.
:return: Byte array consisting of 10 status bytes.
"""
# "The first command sent must be a 'T' command" from T95 manual
self.device.serial_command_mode = True
Tarray = [0x80] * 10
# Status byte (SB1)
Tarray[0] = {
'stopped': 0x01,
'heat': 0x10,
'cool': 0x20,
'hold': 0x30,
}.get(self.device._csm.state, 0x01)
if Tarray[0] == 0x30 and self.device.hold_commanded:
Tarray[0] = 0x50
# Error status byte (EB1)
if self.device.pump_overspeed:
Tarray[1] |= 0x01
# TODO: Add support for other error conditions?
# Pump status byte (PB1)
Tarray[2] = 0x80 + self.device.pump_speed
# Temperature
Tarray[6:10] = [ord(x) for x in "%04x" % (int(self.device.temperature * 10) & 0xFFFF)]
return ''.join(chr(c) for c in Tarray) | python | def get_status(self):
"""
Models "T Command" functionality of device.
Returns all available status information about the device as single byte array.
:return: Byte array consisting of 10 status bytes.
"""
# "The first command sent must be a 'T' command" from T95 manual
self.device.serial_command_mode = True
Tarray = [0x80] * 10
# Status byte (SB1)
Tarray[0] = {
'stopped': 0x01,
'heat': 0x10,
'cool': 0x20,
'hold': 0x30,
}.get(self.device._csm.state, 0x01)
if Tarray[0] == 0x30 and self.device.hold_commanded:
Tarray[0] = 0x50
# Error status byte (EB1)
if self.device.pump_overspeed:
Tarray[1] |= 0x01
# TODO: Add support for other error conditions?
# Pump status byte (PB1)
Tarray[2] = 0x80 + self.device.pump_speed
# Temperature
Tarray[6:10] = [ord(x) for x in "%04x" % (int(self.device.temperature * 10) & 0xFFFF)]
return ''.join(chr(c) for c in Tarray) | [
"def",
"get_status",
"(",
"self",
")",
":",
"# \"The first command sent must be a 'T' command\" from T95 manual",
"self",
".",
"device",
".",
"serial_command_mode",
"=",
"True",
"Tarray",
"=",
"[",
"0x80",
"]",
"*",
"10",
"# Status byte (SB1)",
"Tarray",
"[",
"0",
"]",
"=",
"{",
"'stopped'",
":",
"0x01",
",",
"'heat'",
":",
"0x10",
",",
"'cool'",
":",
"0x20",
",",
"'hold'",
":",
"0x30",
",",
"}",
".",
"get",
"(",
"self",
".",
"device",
".",
"_csm",
".",
"state",
",",
"0x01",
")",
"if",
"Tarray",
"[",
"0",
"]",
"==",
"0x30",
"and",
"self",
".",
"device",
".",
"hold_commanded",
":",
"Tarray",
"[",
"0",
"]",
"=",
"0x50",
"# Error status byte (EB1)",
"if",
"self",
".",
"device",
".",
"pump_overspeed",
":",
"Tarray",
"[",
"1",
"]",
"|=",
"0x01",
"# TODO: Add support for other error conditions?",
"# Pump status byte (PB1)",
"Tarray",
"[",
"2",
"]",
"=",
"0x80",
"+",
"self",
".",
"device",
".",
"pump_speed",
"# Temperature",
"Tarray",
"[",
"6",
":",
"10",
"]",
"=",
"[",
"ord",
"(",
"x",
")",
"for",
"x",
"in",
"\"%04x\"",
"%",
"(",
"int",
"(",
"self",
".",
"device",
".",
"temperature",
"*",
"10",
")",
"&",
"0xFFFF",
")",
"]",
"return",
"''",
".",
"join",
"(",
"chr",
"(",
"c",
")",
"for",
"c",
"in",
"Tarray",
")"
] | Models "T Command" functionality of device.
Returns all available status information about the device as single byte array.
:return: Byte array consisting of 10 status bytes. | [
"Models",
"T",
"Command",
"functionality",
"of",
"device",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/devices/linkam_t95/interfaces/stream_interface.py#L49-L85 |
3,927 | DMSC-Instrument-Data/lewis | src/lewis/devices/linkam_t95/interfaces/stream_interface.py | LinkamT95StreamInterface.set_rate | def set_rate(self, param):
"""
Models "Rate Command" functionality of device.
Sets the target rate of temperature change.
:param param: Rate of temperature change in C/min, multiplied by 100, as a string.
Must be positive.
:return: Empty string.
"""
# TODO: Is not having leading zeroes / 4 digits an error?
rate = int(param)
if 1 <= rate <= 15000:
self.device.temperature_rate = rate / 100.0
return "" | python | def set_rate(self, param):
"""
Models "Rate Command" functionality of device.
Sets the target rate of temperature change.
:param param: Rate of temperature change in C/min, multiplied by 100, as a string.
Must be positive.
:return: Empty string.
"""
# TODO: Is not having leading zeroes / 4 digits an error?
rate = int(param)
if 1 <= rate <= 15000:
self.device.temperature_rate = rate / 100.0
return "" | [
"def",
"set_rate",
"(",
"self",
",",
"param",
")",
":",
"# TODO: Is not having leading zeroes / 4 digits an error?",
"rate",
"=",
"int",
"(",
"param",
")",
"if",
"1",
"<=",
"rate",
"<=",
"15000",
":",
"self",
".",
"device",
".",
"temperature_rate",
"=",
"rate",
"/",
"100.0",
"return",
"\"\""
] | Models "Rate Command" functionality of device.
Sets the target rate of temperature change.
:param param: Rate of temperature change in C/min, multiplied by 100, as a string.
Must be positive.
:return: Empty string. | [
"Models",
"Rate",
"Command",
"functionality",
"of",
"device",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/devices/linkam_t95/interfaces/stream_interface.py#L87-L101 |
3,928 | DMSC-Instrument-Data/lewis | src/lewis/devices/linkam_t95/interfaces/stream_interface.py | LinkamT95StreamInterface.set_limit | def set_limit(self, param):
"""
Models "Limit Command" functionality of device.
Sets the target temperate to be reached.
:param param: Target temperature in C, multiplied by 10, as a string. Can be negative.
:return: Empty string.
"""
# TODO: Is not having leading zeroes / 4 digits an error?
limit = int(param)
if -2000 <= limit <= 6000:
self.device.temperature_limit = limit / 10.0
return "" | python | def set_limit(self, param):
"""
Models "Limit Command" functionality of device.
Sets the target temperate to be reached.
:param param: Target temperature in C, multiplied by 10, as a string. Can be negative.
:return: Empty string.
"""
# TODO: Is not having leading zeroes / 4 digits an error?
limit = int(param)
if -2000 <= limit <= 6000:
self.device.temperature_limit = limit / 10.0
return "" | [
"def",
"set_limit",
"(",
"self",
",",
"param",
")",
":",
"# TODO: Is not having leading zeroes / 4 digits an error?",
"limit",
"=",
"int",
"(",
"param",
")",
"if",
"-",
"2000",
"<=",
"limit",
"<=",
"6000",
":",
"self",
".",
"device",
".",
"temperature_limit",
"=",
"limit",
"/",
"10.0",
"return",
"\"\""
] | Models "Limit Command" functionality of device.
Sets the target temperate to be reached.
:param param: Target temperature in C, multiplied by 10, as a string. Can be negative.
:return: Empty string. | [
"Models",
"Limit",
"Command",
"functionality",
"of",
"device",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/devices/linkam_t95/interfaces/stream_interface.py#L103-L116 |
3,929 | DMSC-Instrument-Data/lewis | src/lewis/devices/linkam_t95/interfaces/stream_interface.py | LinkamT95StreamInterface.pump_command | def pump_command(self, param):
"""
Models "LNP Pump Commands" functionality of device.
Switches between automatic or manual pump mode, and adjusts speed when in manual mode.
:param param: 'a0' for auto, 'm0' for manual, [0-N] for speed.
:return:
"""
lookup = [c for c in "0123456789:;<=>?@ABCDEFGHIJKLMN"]
if param == "a0":
self.device.pump_manual_mode = False
elif param == "m0":
self.device.pump_manual_mode = True
elif param in lookup:
self.device.manual_target_speed = lookup.index(param)
return "" | python | def pump_command(self, param):
"""
Models "LNP Pump Commands" functionality of device.
Switches between automatic or manual pump mode, and adjusts speed when in manual mode.
:param param: 'a0' for auto, 'm0' for manual, [0-N] for speed.
:return:
"""
lookup = [c for c in "0123456789:;<=>?@ABCDEFGHIJKLMN"]
if param == "a0":
self.device.pump_manual_mode = False
elif param == "m0":
self.device.pump_manual_mode = True
elif param in lookup:
self.device.manual_target_speed = lookup.index(param)
return "" | [
"def",
"pump_command",
"(",
"self",
",",
"param",
")",
":",
"lookup",
"=",
"[",
"c",
"for",
"c",
"in",
"\"0123456789:;<=>?@ABCDEFGHIJKLMN\"",
"]",
"if",
"param",
"==",
"\"a0\"",
":",
"self",
".",
"device",
".",
"pump_manual_mode",
"=",
"False",
"elif",
"param",
"==",
"\"m0\"",
":",
"self",
".",
"device",
".",
"pump_manual_mode",
"=",
"True",
"elif",
"param",
"in",
"lookup",
":",
"self",
".",
"device",
".",
"manual_target_speed",
"=",
"lookup",
".",
"index",
"(",
"param",
")",
"return",
"\"\""
] | Models "LNP Pump Commands" functionality of device.
Switches between automatic or manual pump mode, and adjusts speed when in manual mode.
:param param: 'a0' for auto, 'm0' for manual, [0-N] for speed.
:return: | [
"Models",
"LNP",
"Pump",
"Commands",
"functionality",
"of",
"device",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/devices/linkam_t95/interfaces/stream_interface.py#L172-L190 |
3,930 | DMSC-Instrument-Data/lewis | src/lewis/core/statemachine.py | HasContext.set_context | def set_context(self, new_context):
"""Assigns the new context to the member variable ``_context``."""
self._context = new_context
if hasattr(self, '_set_logging_context'):
self._set_logging_context(self._context) | python | def set_context(self, new_context):
"""Assigns the new context to the member variable ``_context``."""
self._context = new_context
if hasattr(self, '_set_logging_context'):
self._set_logging_context(self._context) | [
"def",
"set_context",
"(",
"self",
",",
"new_context",
")",
":",
"self",
".",
"_context",
"=",
"new_context",
"if",
"hasattr",
"(",
"self",
",",
"'_set_logging_context'",
")",
":",
"self",
".",
"_set_logging_context",
"(",
"self",
".",
"_context",
")"
] | Assigns the new context to the member variable ``_context``. | [
"Assigns",
"the",
"new",
"context",
"to",
"the",
"member",
"variable",
"_context",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/core/statemachine.py#L56-L61 |
3,931 | DMSC-Instrument-Data/lewis | src/lewis/devices/linkam_t95/devices/device.py | SimulatedLinkamT95._initialize_data | def _initialize_data(self):
"""
This method is called once on construction. After that, it may be
manually called again to reset the device to its default state.
After the first call during construction, the class is frozen.
This means that attempting to define a new member variable will
raise an exception. This is to prevent typos from inadvertently
and silently adding new members instead of accessing existing ones.
"""
self.serial_command_mode = False
self.pump_overspeed = False
self.start_commanded = False
self.stop_commanded = False
self.hold_commanded = False
# Real device remembers values from last run, we use arbitrary defaults
self.temperature_rate = 5.0 # Rate of change of temperature in C/min
self.temperature_limit = 0.0 # Target temperature in C
self.pump_speed = 0 # Pump speed in arbitrary unit, ranging 0 to 30
self.temperature = 24.0 # Current temperature in C
self.pump_manual_mode = False
self.manual_target_speed = 0 | python | def _initialize_data(self):
"""
This method is called once on construction. After that, it may be
manually called again to reset the device to its default state.
After the first call during construction, the class is frozen.
This means that attempting to define a new member variable will
raise an exception. This is to prevent typos from inadvertently
and silently adding new members instead of accessing existing ones.
"""
self.serial_command_mode = False
self.pump_overspeed = False
self.start_commanded = False
self.stop_commanded = False
self.hold_commanded = False
# Real device remembers values from last run, we use arbitrary defaults
self.temperature_rate = 5.0 # Rate of change of temperature in C/min
self.temperature_limit = 0.0 # Target temperature in C
self.pump_speed = 0 # Pump speed in arbitrary unit, ranging 0 to 30
self.temperature = 24.0 # Current temperature in C
self.pump_manual_mode = False
self.manual_target_speed = 0 | [
"def",
"_initialize_data",
"(",
"self",
")",
":",
"self",
".",
"serial_command_mode",
"=",
"False",
"self",
".",
"pump_overspeed",
"=",
"False",
"self",
".",
"start_commanded",
"=",
"False",
"self",
".",
"stop_commanded",
"=",
"False",
"self",
".",
"hold_commanded",
"=",
"False",
"# Real device remembers values from last run, we use arbitrary defaults",
"self",
".",
"temperature_rate",
"=",
"5.0",
"# Rate of change of temperature in C/min",
"self",
".",
"temperature_limit",
"=",
"0.0",
"# Target temperature in C",
"self",
".",
"pump_speed",
"=",
"0",
"# Pump speed in arbitrary unit, ranging 0 to 30",
"self",
".",
"temperature",
"=",
"24.0",
"# Current temperature in C",
"self",
".",
"pump_manual_mode",
"=",
"False",
"self",
".",
"manual_target_speed",
"=",
"0"
] | This method is called once on construction. After that, it may be
manually called again to reset the device to its default state.
After the first call during construction, the class is frozen.
This means that attempting to define a new member variable will
raise an exception. This is to prevent typos from inadvertently
and silently adding new members instead of accessing existing ones. | [
"This",
"method",
"is",
"called",
"once",
"on",
"construction",
".",
"After",
"that",
"it",
"may",
"be",
"manually",
"called",
"again",
"to",
"reset",
"the",
"device",
"to",
"its",
"default",
"state",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/devices/linkam_t95/devices/device.py#L28-L54 |
3,932 | DMSC-Instrument-Data/lewis | src/lewis/core/logging.py | has_log | def has_log(target):
"""
This is a decorator to add logging functionality to a class or function.
Applying this decorator to a class or function will add two new members:
- ``log`` is an instance of ``logging.Logger``. The name of the logger is
set to ``lewis.Foo`` for a class named Foo.
- ``_set_logging_context`` is a method that modifies the name of the logger
when the class is used in a certain context.
If ``context`` is a string, that string is directly inserted between ``lewis``
and ``Foo``, so that the logger name would be ``lewis.bar.Foo`` if context
was ``'bar'``. The more common case is probably ``context`` being an object of
some class, in which case the class name is inserted. If ``context`` is an object
of type ``Bar``, the logger name of ``Foo`` would be ``lewis.Bar.Foo``.
To provide a more concrete example in terms of Lewis, this is used for the state
machine logger in a device. So the logs of the state machine belonging to a certain
device appear in the log as originating from ``lewis.DeviceName.StateMachine``, which
makes it possible to distinguish between messages from different state machines.
Example for how to use logging in a class:
.. sourcecode:: Python
from lewis.core.logging import has_log
@has_log
class Foo(Base):
def __init__(self):
super(Foo, self).__init__()
def bar(self, baz):
self.log.debug('Called bar with parameter baz=%s', baz)
return baz is not None
It works similarly for free functions, although the actual logging calls are a bit different:
.. sourcecode:: Python
from lewis.core.logging import has_log
@has_log
def foo(bar):
foo.log.info('Called with argument bar=%s', bar)
return bar
The name of the logger is ``lewis.foo``, the context could also be modified by calling
``foo._set_logging_context``.
:param target: Target to decorate with logging functionality.
"""
logger_name = target.__name__
def get_logger_name(context=None):
log_names = [root_logger_name, logger_name]
if context is not None:
log_names.insert(1,
context if isinstance(context,
string_types) else context.__class__.__name__)
return '.'.join(log_names)
def _set_logging_context(obj, context):
"""
Changes the logger name of this class using the supplied context
according to the rules described in the documentation of :func:`has_log`. To
clear the context of a class logger, supply ``None`` as the argument.
:param context: String or object, ``None`` to clear context.
"""
obj.log.name = get_logger_name(context)
target.log = logging.getLogger(get_logger_name())
target._set_logging_context = _set_logging_context
return target | python | def has_log(target):
"""
This is a decorator to add logging functionality to a class or function.
Applying this decorator to a class or function will add two new members:
- ``log`` is an instance of ``logging.Logger``. The name of the logger is
set to ``lewis.Foo`` for a class named Foo.
- ``_set_logging_context`` is a method that modifies the name of the logger
when the class is used in a certain context.
If ``context`` is a string, that string is directly inserted between ``lewis``
and ``Foo``, so that the logger name would be ``lewis.bar.Foo`` if context
was ``'bar'``. The more common case is probably ``context`` being an object of
some class, in which case the class name is inserted. If ``context`` is an object
of type ``Bar``, the logger name of ``Foo`` would be ``lewis.Bar.Foo``.
To provide a more concrete example in terms of Lewis, this is used for the state
machine logger in a device. So the logs of the state machine belonging to a certain
device appear in the log as originating from ``lewis.DeviceName.StateMachine``, which
makes it possible to distinguish between messages from different state machines.
Example for how to use logging in a class:
.. sourcecode:: Python
from lewis.core.logging import has_log
@has_log
class Foo(Base):
def __init__(self):
super(Foo, self).__init__()
def bar(self, baz):
self.log.debug('Called bar with parameter baz=%s', baz)
return baz is not None
It works similarly for free functions, although the actual logging calls are a bit different:
.. sourcecode:: Python
from lewis.core.logging import has_log
@has_log
def foo(bar):
foo.log.info('Called with argument bar=%s', bar)
return bar
The name of the logger is ``lewis.foo``, the context could also be modified by calling
``foo._set_logging_context``.
:param target: Target to decorate with logging functionality.
"""
logger_name = target.__name__
def get_logger_name(context=None):
log_names = [root_logger_name, logger_name]
if context is not None:
log_names.insert(1,
context if isinstance(context,
string_types) else context.__class__.__name__)
return '.'.join(log_names)
def _set_logging_context(obj, context):
"""
Changes the logger name of this class using the supplied context
according to the rules described in the documentation of :func:`has_log`. To
clear the context of a class logger, supply ``None`` as the argument.
:param context: String or object, ``None`` to clear context.
"""
obj.log.name = get_logger_name(context)
target.log = logging.getLogger(get_logger_name())
target._set_logging_context = _set_logging_context
return target | [
"def",
"has_log",
"(",
"target",
")",
":",
"logger_name",
"=",
"target",
".",
"__name__",
"def",
"get_logger_name",
"(",
"context",
"=",
"None",
")",
":",
"log_names",
"=",
"[",
"root_logger_name",
",",
"logger_name",
"]",
"if",
"context",
"is",
"not",
"None",
":",
"log_names",
".",
"insert",
"(",
"1",
",",
"context",
"if",
"isinstance",
"(",
"context",
",",
"string_types",
")",
"else",
"context",
".",
"__class__",
".",
"__name__",
")",
"return",
"'.'",
".",
"join",
"(",
"log_names",
")",
"def",
"_set_logging_context",
"(",
"obj",
",",
"context",
")",
":",
"\"\"\"\n Changes the logger name of this class using the supplied context\n according to the rules described in the documentation of :func:`has_log`. To\n clear the context of a class logger, supply ``None`` as the argument.\n\n :param context: String or object, ``None`` to clear context.\n \"\"\"",
"obj",
".",
"log",
".",
"name",
"=",
"get_logger_name",
"(",
"context",
")",
"target",
".",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"get_logger_name",
"(",
")",
")",
"target",
".",
"_set_logging_context",
"=",
"_set_logging_context",
"return",
"target"
] | This is a decorator to add logging functionality to a class or function.
Applying this decorator to a class or function will add two new members:
- ``log`` is an instance of ``logging.Logger``. The name of the logger is
set to ``lewis.Foo`` for a class named Foo.
- ``_set_logging_context`` is a method that modifies the name of the logger
when the class is used in a certain context.
If ``context`` is a string, that string is directly inserted between ``lewis``
and ``Foo``, so that the logger name would be ``lewis.bar.Foo`` if context
was ``'bar'``. The more common case is probably ``context`` being an object of
some class, in which case the class name is inserted. If ``context`` is an object
of type ``Bar``, the logger name of ``Foo`` would be ``lewis.Bar.Foo``.
To provide a more concrete example in terms of Lewis, this is used for the state
machine logger in a device. So the logs of the state machine belonging to a certain
device appear in the log as originating from ``lewis.DeviceName.StateMachine``, which
makes it possible to distinguish between messages from different state machines.
Example for how to use logging in a class:
.. sourcecode:: Python
from lewis.core.logging import has_log
@has_log
class Foo(Base):
def __init__(self):
super(Foo, self).__init__()
def bar(self, baz):
self.log.debug('Called bar with parameter baz=%s', baz)
return baz is not None
It works similarly for free functions, although the actual logging calls are a bit different:
.. sourcecode:: Python
from lewis.core.logging import has_log
@has_log
def foo(bar):
foo.log.info('Called with argument bar=%s', bar)
return bar
The name of the logger is ``lewis.foo``, the context could also be modified by calling
``foo._set_logging_context``.
:param target: Target to decorate with logging functionality. | [
"This",
"is",
"a",
"decorator",
"to",
"add",
"logging",
"functionality",
"to",
"a",
"class",
"or",
"function",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/core/logging.py#L44-L122 |
3,933 | DMSC-Instrument-Data/lewis | src/lewis/scripts/__init__.py | get_usage_text | def get_usage_text(parser, indent=None):
"""
This small helper function extracts the help information from an ArgumentParser instance
and indents the text by the number of spaces supplied in the indent-argument.
:param parser: ArgumentParser object.
:param indent: Number of spaces to put before each line or None.
:return: Formatted help string of the supplied parser.
"""
usage_text = StringIO()
parser.print_help(usage_text)
usage_string = usage_text.getvalue()
if indent is None:
return usage_string
return '\n'.join([' ' * indent + line for line in usage_string.split('\n')]) | python | def get_usage_text(parser, indent=None):
"""
This small helper function extracts the help information from an ArgumentParser instance
and indents the text by the number of spaces supplied in the indent-argument.
:param parser: ArgumentParser object.
:param indent: Number of spaces to put before each line or None.
:return: Formatted help string of the supplied parser.
"""
usage_text = StringIO()
parser.print_help(usage_text)
usage_string = usage_text.getvalue()
if indent is None:
return usage_string
return '\n'.join([' ' * indent + line for line in usage_string.split('\n')]) | [
"def",
"get_usage_text",
"(",
"parser",
",",
"indent",
"=",
"None",
")",
":",
"usage_text",
"=",
"StringIO",
"(",
")",
"parser",
".",
"print_help",
"(",
"usage_text",
")",
"usage_string",
"=",
"usage_text",
".",
"getvalue",
"(",
")",
"if",
"indent",
"is",
"None",
":",
"return",
"usage_string",
"return",
"'\\n'",
".",
"join",
"(",
"[",
"' '",
"*",
"indent",
"+",
"line",
"for",
"line",
"in",
"usage_string",
".",
"split",
"(",
"'\\n'",
")",
"]",
")"
] | This small helper function extracts the help information from an ArgumentParser instance
and indents the text by the number of spaces supplied in the indent-argument.
:param parser: ArgumentParser object.
:param indent: Number of spaces to put before each line or None.
:return: Formatted help string of the supplied parser. | [
"This",
"small",
"helper",
"function",
"extracts",
"the",
"help",
"information",
"from",
"an",
"ArgumentParser",
"instance",
"and",
"indents",
"the",
"text",
"by",
"the",
"number",
"of",
"spaces",
"supplied",
"in",
"the",
"indent",
"-",
"argument",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/scripts/__init__.py#L23-L40 |
3,934 | DMSC-Instrument-Data/lewis | src/lewis/examples/example_motor/__init__.py | SimulatedExampleMotor.stop | def stop(self):
"""Stops the motor and returns the new target and position, which are equal"""
self._target = self.position
self.log.info('Stopping movement after user request.')
return self.target, self.position | python | def stop(self):
"""Stops the motor and returns the new target and position, which are equal"""
self._target = self.position
self.log.info('Stopping movement after user request.')
return self.target, self.position | [
"def",
"stop",
"(",
"self",
")",
":",
"self",
".",
"_target",
"=",
"self",
".",
"position",
"self",
".",
"log",
".",
"info",
"(",
"'Stopping movement after user request.'",
")",
"return",
"self",
".",
"target",
",",
"self",
".",
"position"
] | Stops the motor and returns the new target and position, which are equal | [
"Stops",
"the",
"motor",
"and",
"returns",
"the",
"new",
"target",
"and",
"position",
"which",
"are",
"equal"
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/examples/example_motor/__init__.py#L75-L82 |
3,935 | DMSC-Instrument-Data/lewis | src/lewis/scripts/run.py | run_simulation | def run_simulation(argument_list=None): # noqa: C901
"""
This is effectively the main function of a typical simulation run. Arguments passed in are
parsed and used to construct and run the simulation.
This function only exits when the program has completed or is interrupted.
:param argument_list: Argument list to pass to the argument parser declared in this module.
"""
try:
arguments = parser.parse_args(argument_list or sys.argv[1:])
if arguments.version:
print(__version__)
return
if arguments.relaxed_versions:
print('Unknown option --relaxed-versions. Did you mean --ignore-versions?')
return
loglevel = 'debug' if arguments.verify else arguments.output_level
if loglevel != 'none':
logging.basicConfig(
level=getattr(logging, loglevel.upper()), format=default_log_format)
if arguments.add_path is not None:
additional_path = os.path.abspath(arguments.add_path)
logging.getLogger().debug('Extending path with: %s', additional_path)
sys.path.append(additional_path)
strict_versions = use_strict_versions(arguments.strict_versions, arguments.ignore_versions)
simulation_factory = SimulationFactory(arguments.device_package, strict_versions)
if not arguments.device:
devices = ['Please specify a device to simulate. The following devices are available:']
for dev in simulation_factory.devices:
devices.append(' ' + dev)
print('\n'.join(devices))
return
if arguments.list_protocols:
print('\n'.join(simulation_factory.get_protocols(arguments.device)))
return
protocols = parse_adapter_options(arguments.adapter_options) \
if not arguments.no_interface else {}
simulation = simulation_factory.create(
arguments.device, arguments.setup, protocols, arguments.rpc_host)
if arguments.show_interface:
print(simulation._adapters.documentation())
return
if arguments.list_adapter_options:
configurations = simulation._adapters.configuration()
for protocol, options in configurations.items():
print('{}:'.format(protocol))
for opt, val in options.items():
print(' {} = {}'.format(opt, val))
return
simulation.cycle_delay = arguments.cycle_delay
simulation.speed = arguments.speed
if not arguments.verify:
try:
simulation.start()
except KeyboardInterrupt:
print('\nInterrupt received; shutting down. Goodbye, cruel world!')
simulation.log.critical('Simulation aborted by user interaction')
finally:
simulation.stop()
except LewisException as e:
print('\n'.join(('An error occurred:', str(e)))) | python | def run_simulation(argument_list=None): # noqa: C901
"""
This is effectively the main function of a typical simulation run. Arguments passed in are
parsed and used to construct and run the simulation.
This function only exits when the program has completed or is interrupted.
:param argument_list: Argument list to pass to the argument parser declared in this module.
"""
try:
arguments = parser.parse_args(argument_list or sys.argv[1:])
if arguments.version:
print(__version__)
return
if arguments.relaxed_versions:
print('Unknown option --relaxed-versions. Did you mean --ignore-versions?')
return
loglevel = 'debug' if arguments.verify else arguments.output_level
if loglevel != 'none':
logging.basicConfig(
level=getattr(logging, loglevel.upper()), format=default_log_format)
if arguments.add_path is not None:
additional_path = os.path.abspath(arguments.add_path)
logging.getLogger().debug('Extending path with: %s', additional_path)
sys.path.append(additional_path)
strict_versions = use_strict_versions(arguments.strict_versions, arguments.ignore_versions)
simulation_factory = SimulationFactory(arguments.device_package, strict_versions)
if not arguments.device:
devices = ['Please specify a device to simulate. The following devices are available:']
for dev in simulation_factory.devices:
devices.append(' ' + dev)
print('\n'.join(devices))
return
if arguments.list_protocols:
print('\n'.join(simulation_factory.get_protocols(arguments.device)))
return
protocols = parse_adapter_options(arguments.adapter_options) \
if not arguments.no_interface else {}
simulation = simulation_factory.create(
arguments.device, arguments.setup, protocols, arguments.rpc_host)
if arguments.show_interface:
print(simulation._adapters.documentation())
return
if arguments.list_adapter_options:
configurations = simulation._adapters.configuration()
for protocol, options in configurations.items():
print('{}:'.format(protocol))
for opt, val in options.items():
print(' {} = {}'.format(opt, val))
return
simulation.cycle_delay = arguments.cycle_delay
simulation.speed = arguments.speed
if not arguments.verify:
try:
simulation.start()
except KeyboardInterrupt:
print('\nInterrupt received; shutting down. Goodbye, cruel world!')
simulation.log.critical('Simulation aborted by user interaction')
finally:
simulation.stop()
except LewisException as e:
print('\n'.join(('An error occurred:', str(e)))) | [
"def",
"run_simulation",
"(",
"argument_list",
"=",
"None",
")",
":",
"# noqa: C901",
"try",
":",
"arguments",
"=",
"parser",
".",
"parse_args",
"(",
"argument_list",
"or",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
")",
"if",
"arguments",
".",
"version",
":",
"print",
"(",
"__version__",
")",
"return",
"if",
"arguments",
".",
"relaxed_versions",
":",
"print",
"(",
"'Unknown option --relaxed-versions. Did you mean --ignore-versions?'",
")",
"return",
"loglevel",
"=",
"'debug'",
"if",
"arguments",
".",
"verify",
"else",
"arguments",
".",
"output_level",
"if",
"loglevel",
"!=",
"'none'",
":",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"getattr",
"(",
"logging",
",",
"loglevel",
".",
"upper",
"(",
")",
")",
",",
"format",
"=",
"default_log_format",
")",
"if",
"arguments",
".",
"add_path",
"is",
"not",
"None",
":",
"additional_path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"arguments",
".",
"add_path",
")",
"logging",
".",
"getLogger",
"(",
")",
".",
"debug",
"(",
"'Extending path with: %s'",
",",
"additional_path",
")",
"sys",
".",
"path",
".",
"append",
"(",
"additional_path",
")",
"strict_versions",
"=",
"use_strict_versions",
"(",
"arguments",
".",
"strict_versions",
",",
"arguments",
".",
"ignore_versions",
")",
"simulation_factory",
"=",
"SimulationFactory",
"(",
"arguments",
".",
"device_package",
",",
"strict_versions",
")",
"if",
"not",
"arguments",
".",
"device",
":",
"devices",
"=",
"[",
"'Please specify a device to simulate. The following devices are available:'",
"]",
"for",
"dev",
"in",
"simulation_factory",
".",
"devices",
":",
"devices",
".",
"append",
"(",
"' '",
"+",
"dev",
")",
"print",
"(",
"'\\n'",
".",
"join",
"(",
"devices",
")",
")",
"return",
"if",
"arguments",
".",
"list_protocols",
":",
"print",
"(",
"'\\n'",
".",
"join",
"(",
"simulation_factory",
".",
"get_protocols",
"(",
"arguments",
".",
"device",
")",
")",
")",
"return",
"protocols",
"=",
"parse_adapter_options",
"(",
"arguments",
".",
"adapter_options",
")",
"if",
"not",
"arguments",
".",
"no_interface",
"else",
"{",
"}",
"simulation",
"=",
"simulation_factory",
".",
"create",
"(",
"arguments",
".",
"device",
",",
"arguments",
".",
"setup",
",",
"protocols",
",",
"arguments",
".",
"rpc_host",
")",
"if",
"arguments",
".",
"show_interface",
":",
"print",
"(",
"simulation",
".",
"_adapters",
".",
"documentation",
"(",
")",
")",
"return",
"if",
"arguments",
".",
"list_adapter_options",
":",
"configurations",
"=",
"simulation",
".",
"_adapters",
".",
"configuration",
"(",
")",
"for",
"protocol",
",",
"options",
"in",
"configurations",
".",
"items",
"(",
")",
":",
"print",
"(",
"'{}:'",
".",
"format",
"(",
"protocol",
")",
")",
"for",
"opt",
",",
"val",
"in",
"options",
".",
"items",
"(",
")",
":",
"print",
"(",
"' {} = {}'",
".",
"format",
"(",
"opt",
",",
"val",
")",
")",
"return",
"simulation",
".",
"cycle_delay",
"=",
"arguments",
".",
"cycle_delay",
"simulation",
".",
"speed",
"=",
"arguments",
".",
"speed",
"if",
"not",
"arguments",
".",
"verify",
":",
"try",
":",
"simulation",
".",
"start",
"(",
")",
"except",
"KeyboardInterrupt",
":",
"print",
"(",
"'\\nInterrupt received; shutting down. Goodbye, cruel world!'",
")",
"simulation",
".",
"log",
".",
"critical",
"(",
"'Simulation aborted by user interaction'",
")",
"finally",
":",
"simulation",
".",
"stop",
"(",
")",
"except",
"LewisException",
"as",
"e",
":",
"print",
"(",
"'\\n'",
".",
"join",
"(",
"(",
"'An error occurred:'",
",",
"str",
"(",
"e",
")",
")",
")",
")"
] | This is effectively the main function of a typical simulation run. Arguments passed in are
parsed and used to construct and run the simulation.
This function only exits when the program has completed or is interrupted.
:param argument_list: Argument list to pass to the argument parser declared in this module. | [
"This",
"is",
"effectively",
"the",
"main",
"function",
"of",
"a",
"typical",
"simulation",
"run",
".",
"Arguments",
"passed",
"in",
"are",
"parsed",
"and",
"used",
"to",
"construct",
"and",
"run",
"the",
"simulation",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/scripts/run.py#L172-L253 |
3,936 | DMSC-Instrument-Data/lewis | src/lewis/adapters/stream.py | Func.map_arguments | def map_arguments(self, arguments):
"""
Returns the mapped function arguments. If no mapping functions are defined, the arguments
are returned as they were supplied.
:param arguments: List of arguments for bound function as strings.
:return: Mapped arguments.
"""
if self.argument_mappings is None:
return arguments
return [f(a) for f, a in zip(self.argument_mappings, arguments)] | python | def map_arguments(self, arguments):
"""
Returns the mapped function arguments. If no mapping functions are defined, the arguments
are returned as they were supplied.
:param arguments: List of arguments for bound function as strings.
:return: Mapped arguments.
"""
if self.argument_mappings is None:
return arguments
return [f(a) for f, a in zip(self.argument_mappings, arguments)] | [
"def",
"map_arguments",
"(",
"self",
",",
"arguments",
")",
":",
"if",
"self",
".",
"argument_mappings",
"is",
"None",
":",
"return",
"arguments",
"return",
"[",
"f",
"(",
"a",
")",
"for",
"f",
",",
"a",
"in",
"zip",
"(",
"self",
".",
"argument_mappings",
",",
"arguments",
")",
"]"
] | Returns the mapped function arguments. If no mapping functions are defined, the arguments
are returned as they were supplied.
:param arguments: List of arguments for bound function as strings.
:return: Mapped arguments. | [
"Returns",
"the",
"mapped",
"function",
"arguments",
".",
"If",
"no",
"mapping",
"functions",
"are",
"defined",
"the",
"arguments",
"are",
"returned",
"as",
"they",
"were",
"supplied",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/adapters/stream.py#L368-L379 |
3,937 | DMSC-Instrument-Data/lewis | src/lewis/adapters/stream.py | Func.map_return_value | def map_return_value(self, return_value):
"""
Returns the mapped return_value of a processed request. If no return_mapping has been
defined, the value is returned as is. If return_mapping is a static value, that value
is returned, ignoring return_value completely.
:param return_value: Value to map.
:return: Mapped return value.
"""
if callable(self.return_mapping):
return self.return_mapping(return_value)
if self.return_mapping is not None:
return self.return_mapping
return return_value | python | def map_return_value(self, return_value):
"""
Returns the mapped return_value of a processed request. If no return_mapping has been
defined, the value is returned as is. If return_mapping is a static value, that value
is returned, ignoring return_value completely.
:param return_value: Value to map.
:return: Mapped return value.
"""
if callable(self.return_mapping):
return self.return_mapping(return_value)
if self.return_mapping is not None:
return self.return_mapping
return return_value | [
"def",
"map_return_value",
"(",
"self",
",",
"return_value",
")",
":",
"if",
"callable",
"(",
"self",
".",
"return_mapping",
")",
":",
"return",
"self",
".",
"return_mapping",
"(",
"return_value",
")",
"if",
"self",
".",
"return_mapping",
"is",
"not",
"None",
":",
"return",
"self",
".",
"return_mapping",
"return",
"return_value"
] | Returns the mapped return_value of a processed request. If no return_mapping has been
defined, the value is returned as is. If return_mapping is a static value, that value
is returned, ignoring return_value completely.
:param return_value: Value to map.
:return: Mapped return value. | [
"Returns",
"the",
"mapped",
"return_value",
"of",
"a",
"processed",
"request",
".",
"If",
"no",
"return_mapping",
"has",
"been",
"defined",
"the",
"value",
"is",
"returned",
"as",
"is",
".",
"If",
"return_mapping",
"is",
"a",
"static",
"value",
"that",
"value",
"is",
"returned",
"ignoring",
"return_value",
"completely",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/adapters/stream.py#L381-L396 |
3,938 | DMSC-Instrument-Data/lewis | src/lewis/adapters/stream.py | StreamAdapter.start_server | def start_server(self):
"""
Starts the TCP stream server, binding to the configured host and port.
Host and port are configured via the command line arguments.
.. note:: The server does not process requests unless
:meth:`handle` is called in regular intervals.
"""
if self._server is None:
if self._options.telnet_mode:
self.interface.in_terminator = '\r\n'
self.interface.out_terminator = '\r\n'
self._server = StreamServer(self._options.bind_address, self._options.port,
self.interface, self.device_lock) | python | def start_server(self):
"""
Starts the TCP stream server, binding to the configured host and port.
Host and port are configured via the command line arguments.
.. note:: The server does not process requests unless
:meth:`handle` is called in regular intervals.
"""
if self._server is None:
if self._options.telnet_mode:
self.interface.in_terminator = '\r\n'
self.interface.out_terminator = '\r\n'
self._server = StreamServer(self._options.bind_address, self._options.port,
self.interface, self.device_lock) | [
"def",
"start_server",
"(",
"self",
")",
":",
"if",
"self",
".",
"_server",
"is",
"None",
":",
"if",
"self",
".",
"_options",
".",
"telnet_mode",
":",
"self",
".",
"interface",
".",
"in_terminator",
"=",
"'\\r\\n'",
"self",
".",
"interface",
".",
"out_terminator",
"=",
"'\\r\\n'",
"self",
".",
"_server",
"=",
"StreamServer",
"(",
"self",
".",
"_options",
".",
"bind_address",
",",
"self",
".",
"_options",
".",
"port",
",",
"self",
".",
"interface",
",",
"self",
".",
"device_lock",
")"
] | Starts the TCP stream server, binding to the configured host and port.
Host and port are configured via the command line arguments.
.. note:: The server does not process requests unless
:meth:`handle` is called in regular intervals. | [
"Starts",
"the",
"TCP",
"stream",
"server",
"binding",
"to",
"the",
"configured",
"host",
"and",
"port",
".",
"Host",
"and",
"port",
"are",
"configured",
"via",
"the",
"command",
"line",
"arguments",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/adapters/stream.py#L632-L647 |
3,939 | DMSC-Instrument-Data/lewis | src/lewis/adapters/stream.py | StreamAdapter.handle | def handle(self, cycle_delay=0.1):
"""
Spend approximately ``cycle_delay`` seconds to process requests to the server.
:param cycle_delay: S
"""
asyncore.loop(cycle_delay, count=1)
self._server.process(int(cycle_delay * 1000)) | python | def handle(self, cycle_delay=0.1):
"""
Spend approximately ``cycle_delay`` seconds to process requests to the server.
:param cycle_delay: S
"""
asyncore.loop(cycle_delay, count=1)
self._server.process(int(cycle_delay * 1000)) | [
"def",
"handle",
"(",
"self",
",",
"cycle_delay",
"=",
"0.1",
")",
":",
"asyncore",
".",
"loop",
"(",
"cycle_delay",
",",
"count",
"=",
"1",
")",
"self",
".",
"_server",
".",
"process",
"(",
"int",
"(",
"cycle_delay",
"*",
"1000",
")",
")"
] | Spend approximately ``cycle_delay`` seconds to process requests to the server.
:param cycle_delay: S | [
"Spend",
"approximately",
"cycle_delay",
"seconds",
"to",
"process",
"requests",
"to",
"the",
"server",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/adapters/stream.py#L658-L665 |
3,940 | DMSC-Instrument-Data/lewis | src/lewis/devices/__init__.py | StateMachineDevice._override_data | def _override_data(self, overrides):
"""
This method overrides data members of the class, but does not allow for adding new members.
:param overrides: Dict with data overrides.
"""
if overrides is not None:
for name, val in overrides.items():
self.log.debug('Trying to override initial data (%s=%s)', name, val)
if name not in dir(self):
raise AttributeError(
'Can not override non-existing attribute'
'\'{}\' of class \'{}\'.'.format(name, type(self).__name__))
setattr(self, name, val) | python | def _override_data(self, overrides):
"""
This method overrides data members of the class, but does not allow for adding new members.
:param overrides: Dict with data overrides.
"""
if overrides is not None:
for name, val in overrides.items():
self.log.debug('Trying to override initial data (%s=%s)', name, val)
if name not in dir(self):
raise AttributeError(
'Can not override non-existing attribute'
'\'{}\' of class \'{}\'.'.format(name, type(self).__name__))
setattr(self, name, val) | [
"def",
"_override_data",
"(",
"self",
",",
"overrides",
")",
":",
"if",
"overrides",
"is",
"not",
"None",
":",
"for",
"name",
",",
"val",
"in",
"overrides",
".",
"items",
"(",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'Trying to override initial data (%s=%s)'",
",",
"name",
",",
"val",
")",
"if",
"name",
"not",
"in",
"dir",
"(",
"self",
")",
":",
"raise",
"AttributeError",
"(",
"'Can not override non-existing attribute'",
"'\\'{}\\' of class \\'{}\\'.'",
".",
"format",
"(",
"name",
",",
"type",
"(",
"self",
")",
".",
"__name__",
")",
")",
"setattr",
"(",
"self",
",",
"name",
",",
"val",
")"
] | This method overrides data members of the class, but does not allow for adding new members.
:param overrides: Dict with data overrides. | [
"This",
"method",
"overrides",
"data",
"members",
"of",
"the",
"class",
"but",
"does",
"not",
"allow",
"for",
"adding",
"new",
"members",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/devices/__init__.py#L177-L191 |
3,941 | DMSC-Instrument-Data/lewis | src/lewis/adapters/modbus.py | ModbusDataBank.get | def get(self, addr, count):
"""
Read list of ``count`` values at ``addr`` memory location in DataBank.
:param addr: Address to read from
:param count: Number of entries to retrieve
:return: list of entry values
:except IndexError: Raised if address range falls outside valid range
"""
addr -= self._start_addr
data = self._data[addr:addr + count]
if len(data) != count:
addr += self._start_addr
raise IndexError("Invalid address range [{:#06x} - {:#06x}]"
.format(addr, addr + count))
return data | python | def get(self, addr, count):
"""
Read list of ``count`` values at ``addr`` memory location in DataBank.
:param addr: Address to read from
:param count: Number of entries to retrieve
:return: list of entry values
:except IndexError: Raised if address range falls outside valid range
"""
addr -= self._start_addr
data = self._data[addr:addr + count]
if len(data) != count:
addr += self._start_addr
raise IndexError("Invalid address range [{:#06x} - {:#06x}]"
.format(addr, addr + count))
return data | [
"def",
"get",
"(",
"self",
",",
"addr",
",",
"count",
")",
":",
"addr",
"-=",
"self",
".",
"_start_addr",
"data",
"=",
"self",
".",
"_data",
"[",
"addr",
":",
"addr",
"+",
"count",
"]",
"if",
"len",
"(",
"data",
")",
"!=",
"count",
":",
"addr",
"+=",
"self",
".",
"_start_addr",
"raise",
"IndexError",
"(",
"\"Invalid address range [{:#06x} - {:#06x}]\"",
".",
"format",
"(",
"addr",
",",
"addr",
"+",
"count",
")",
")",
"return",
"data"
] | Read list of ``count`` values at ``addr`` memory location in DataBank.
:param addr: Address to read from
:param count: Number of entries to retrieve
:return: list of entry values
:except IndexError: Raised if address range falls outside valid range | [
"Read",
"list",
"of",
"count",
"values",
"at",
"addr",
"memory",
"location",
"in",
"DataBank",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/adapters/modbus.py#L64-L79 |
3,942 | DMSC-Instrument-Data/lewis | src/lewis/adapters/modbus.py | ModbusDataBank.set | def set(self, addr, values):
"""
Write list ``values`` to ``addr`` memory location in DataBank.
:param addr: Address to write to
:param values: list of values to write
:except IndexError: Raised if address range falls outside valid range
"""
addr -= self._start_addr
end = addr + len(values)
if not 0 <= addr <= end <= len(self._data):
addr += self._start_addr
raise IndexError("Invalid address range [{:#06x} - {:#06x}]"
.format(addr, addr + len(values)))
self._data[addr:end] = values | python | def set(self, addr, values):
"""
Write list ``values`` to ``addr`` memory location in DataBank.
:param addr: Address to write to
:param values: list of values to write
:except IndexError: Raised if address range falls outside valid range
"""
addr -= self._start_addr
end = addr + len(values)
if not 0 <= addr <= end <= len(self._data):
addr += self._start_addr
raise IndexError("Invalid address range [{:#06x} - {:#06x}]"
.format(addr, addr + len(values)))
self._data[addr:end] = values | [
"def",
"set",
"(",
"self",
",",
"addr",
",",
"values",
")",
":",
"addr",
"-=",
"self",
".",
"_start_addr",
"end",
"=",
"addr",
"+",
"len",
"(",
"values",
")",
"if",
"not",
"0",
"<=",
"addr",
"<=",
"end",
"<=",
"len",
"(",
"self",
".",
"_data",
")",
":",
"addr",
"+=",
"self",
".",
"_start_addr",
"raise",
"IndexError",
"(",
"\"Invalid address range [{:#06x} - {:#06x}]\"",
".",
"format",
"(",
"addr",
",",
"addr",
"+",
"len",
"(",
"values",
")",
")",
")",
"self",
".",
"_data",
"[",
"addr",
":",
"end",
"]",
"=",
"values"
] | Write list ``values`` to ``addr`` memory location in DataBank.
:param addr: Address to write to
:param values: list of values to write
:except IndexError: Raised if address range falls outside valid range | [
"Write",
"list",
"values",
"to",
"addr",
"memory",
"location",
"in",
"DataBank",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/adapters/modbus.py#L81-L95 |
3,943 | DMSC-Instrument-Data/lewis | src/lewis/adapters/modbus.py | ModbusTCPFrame.from_bytearray | def from_bytearray(self, stream):
"""
Constructs this frame from input data stream, consuming as many bytes as necessary from
the beginning of the stream.
If stream does not contain enough data to construct a complete modbus frame, an EOFError
is raised and no data is consumed.
:param stream: bytearray to consume data from to construct this frame.
:except EOFError: Not enough data for complete frame; no data consumed.
"""
fmt = '>HHHBB'
size_header = struct.calcsize(fmt)
if len(stream) < size_header:
raise EOFError
(
self.transaction_id,
self.protocol_id,
self.length,
self.unit_id,
self.fcode
) = struct.unpack(fmt, bytes(stream[:size_header]))
size_total = size_header + self.length - 2
if len(stream) < size_total:
raise EOFError
self.data = stream[size_header:size_total]
del stream[:size_total] | python | def from_bytearray(self, stream):
"""
Constructs this frame from input data stream, consuming as many bytes as necessary from
the beginning of the stream.
If stream does not contain enough data to construct a complete modbus frame, an EOFError
is raised and no data is consumed.
:param stream: bytearray to consume data from to construct this frame.
:except EOFError: Not enough data for complete frame; no data consumed.
"""
fmt = '>HHHBB'
size_header = struct.calcsize(fmt)
if len(stream) < size_header:
raise EOFError
(
self.transaction_id,
self.protocol_id,
self.length,
self.unit_id,
self.fcode
) = struct.unpack(fmt, bytes(stream[:size_header]))
size_total = size_header + self.length - 2
if len(stream) < size_total:
raise EOFError
self.data = stream[size_header:size_total]
del stream[:size_total] | [
"def",
"from_bytearray",
"(",
"self",
",",
"stream",
")",
":",
"fmt",
"=",
"'>HHHBB'",
"size_header",
"=",
"struct",
".",
"calcsize",
"(",
"fmt",
")",
"if",
"len",
"(",
"stream",
")",
"<",
"size_header",
":",
"raise",
"EOFError",
"(",
"self",
".",
"transaction_id",
",",
"self",
".",
"protocol_id",
",",
"self",
".",
"length",
",",
"self",
".",
"unit_id",
",",
"self",
".",
"fcode",
")",
"=",
"struct",
".",
"unpack",
"(",
"fmt",
",",
"bytes",
"(",
"stream",
"[",
":",
"size_header",
"]",
")",
")",
"size_total",
"=",
"size_header",
"+",
"self",
".",
"length",
"-",
"2",
"if",
"len",
"(",
"stream",
")",
"<",
"size_total",
":",
"raise",
"EOFError",
"self",
".",
"data",
"=",
"stream",
"[",
"size_header",
":",
"size_total",
"]",
"del",
"stream",
"[",
":",
"size_total",
"]"
] | Constructs this frame from input data stream, consuming as many bytes as necessary from
the beginning of the stream.
If stream does not contain enough data to construct a complete modbus frame, an EOFError
is raised and no data is consumed.
:param stream: bytearray to consume data from to construct this frame.
:except EOFError: Not enough data for complete frame; no data consumed. | [
"Constructs",
"this",
"frame",
"from",
"input",
"data",
"stream",
"consuming",
"as",
"many",
"bytes",
"as",
"necessary",
"from",
"the",
"beginning",
"of",
"the",
"stream",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/adapters/modbus.py#L171-L200 |
3,944 | DMSC-Instrument-Data/lewis | src/lewis/adapters/modbus.py | ModbusTCPFrame.to_bytearray | def to_bytearray(self):
"""
Convert this frame into its bytearray representation.
:return: bytearray representation of this frame.
"""
header = bytearray(struct.pack(
'>HHHBB',
self.transaction_id,
self.protocol_id,
self.length,
self.unit_id,
self.fcode
))
return header + self.data | python | def to_bytearray(self):
"""
Convert this frame into its bytearray representation.
:return: bytearray representation of this frame.
"""
header = bytearray(struct.pack(
'>HHHBB',
self.transaction_id,
self.protocol_id,
self.length,
self.unit_id,
self.fcode
))
return header + self.data | [
"def",
"to_bytearray",
"(",
"self",
")",
":",
"header",
"=",
"bytearray",
"(",
"struct",
".",
"pack",
"(",
"'>HHHBB'",
",",
"self",
".",
"transaction_id",
",",
"self",
".",
"protocol_id",
",",
"self",
".",
"length",
",",
"self",
".",
"unit_id",
",",
"self",
".",
"fcode",
")",
")",
"return",
"header",
"+",
"self",
".",
"data"
] | Convert this frame into its bytearray representation.
:return: bytearray representation of this frame. | [
"Convert",
"this",
"frame",
"into",
"its",
"bytearray",
"representation",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/adapters/modbus.py#L202-L216 |
3,945 | DMSC-Instrument-Data/lewis | src/lewis/adapters/modbus.py | ModbusTCPFrame.is_valid | def is_valid(self):
"""
Check integrity and validity of this frame.
:return: bool True if this frame is structurally valid.
"""
conditions = [
self.protocol_id == 0, # Modbus always uses protocol 0
2 <= self.length <= 260, # Absolute length limits
len(self.data) == self.length - 2, # Total length matches data length
]
return all(conditions) | python | def is_valid(self):
"""
Check integrity and validity of this frame.
:return: bool True if this frame is structurally valid.
"""
conditions = [
self.protocol_id == 0, # Modbus always uses protocol 0
2 <= self.length <= 260, # Absolute length limits
len(self.data) == self.length - 2, # Total length matches data length
]
return all(conditions) | [
"def",
"is_valid",
"(",
"self",
")",
":",
"conditions",
"=",
"[",
"self",
".",
"protocol_id",
"==",
"0",
",",
"# Modbus always uses protocol 0",
"2",
"<=",
"self",
".",
"length",
"<=",
"260",
",",
"# Absolute length limits",
"len",
"(",
"self",
".",
"data",
")",
"==",
"self",
".",
"length",
"-",
"2",
",",
"# Total length matches data length",
"]",
"return",
"all",
"(",
"conditions",
")"
] | Check integrity and validity of this frame.
:return: bool True if this frame is structurally valid. | [
"Check",
"integrity",
"and",
"validity",
"of",
"this",
"frame",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/adapters/modbus.py#L218-L229 |
3,946 | DMSC-Instrument-Data/lewis | src/lewis/adapters/modbus.py | ModbusTCPFrame.create_exception | def create_exception(self, code):
"""
Create an exception frame based on this frame.
:param code: Modbus exception code to use for this exception
:return: ModbusTCPFrame instance that represents an exception
"""
frame = deepcopy(self)
frame.length = 3
frame.fcode += 0x80
frame.data = bytearray(chr(code))
return frame | python | def create_exception(self, code):
"""
Create an exception frame based on this frame.
:param code: Modbus exception code to use for this exception
:return: ModbusTCPFrame instance that represents an exception
"""
frame = deepcopy(self)
frame.length = 3
frame.fcode += 0x80
frame.data = bytearray(chr(code))
return frame | [
"def",
"create_exception",
"(",
"self",
",",
"code",
")",
":",
"frame",
"=",
"deepcopy",
"(",
"self",
")",
"frame",
".",
"length",
"=",
"3",
"frame",
".",
"fcode",
"+=",
"0x80",
"frame",
".",
"data",
"=",
"bytearray",
"(",
"chr",
"(",
"code",
")",
")",
"return",
"frame"
] | Create an exception frame based on this frame.
:param code: Modbus exception code to use for this exception
:return: ModbusTCPFrame instance that represents an exception | [
"Create",
"an",
"exception",
"frame",
"based",
"on",
"this",
"frame",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/adapters/modbus.py#L231-L242 |
3,947 | DMSC-Instrument-Data/lewis | src/lewis/adapters/modbus.py | ModbusTCPFrame.create_response | def create_response(self, data=None):
"""
Create a response frame based on this frame.
:param data: Data section of response as bytearray. If None, request data section is kept.
:return: ModbusTCPFrame instance that represents a response
"""
frame = deepcopy(self)
if data is not None:
frame.data = data
frame.length = 2 + len(frame.data)
return frame | python | def create_response(self, data=None):
"""
Create a response frame based on this frame.
:param data: Data section of response as bytearray. If None, request data section is kept.
:return: ModbusTCPFrame instance that represents a response
"""
frame = deepcopy(self)
if data is not None:
frame.data = data
frame.length = 2 + len(frame.data)
return frame | [
"def",
"create_response",
"(",
"self",
",",
"data",
"=",
"None",
")",
":",
"frame",
"=",
"deepcopy",
"(",
"self",
")",
"if",
"data",
"is",
"not",
"None",
":",
"frame",
".",
"data",
"=",
"data",
"frame",
".",
"length",
"=",
"2",
"+",
"len",
"(",
"frame",
".",
"data",
")",
"return",
"frame"
] | Create a response frame based on this frame.
:param data: Data section of response as bytearray. If None, request data section is kept.
:return: ModbusTCPFrame instance that represents a response | [
"Create",
"a",
"response",
"frame",
"based",
"on",
"this",
"frame",
"."
] | 931d96b8c761550a6a58f6e61e202690db04233a | https://github.com/DMSC-Instrument-Data/lewis/blob/931d96b8c761550a6a58f6e61e202690db04233a/src/lewis/adapters/modbus.py#L244-L255 |
3,948 | simpleai-team/simpleai | simpleai/search/local.py | _all_expander | def _all_expander(fringe, iteration, viewer):
'''
Expander that expands all nodes on the fringe.
'''
expanded_neighbors = [node.expand(local_search=True)
for node in fringe]
if viewer:
viewer.event('expanded', list(fringe), expanded_neighbors)
list(map(fringe.extend, expanded_neighbors)) | python | def _all_expander(fringe, iteration, viewer):
'''
Expander that expands all nodes on the fringe.
'''
expanded_neighbors = [node.expand(local_search=True)
for node in fringe]
if viewer:
viewer.event('expanded', list(fringe), expanded_neighbors)
list(map(fringe.extend, expanded_neighbors)) | [
"def",
"_all_expander",
"(",
"fringe",
",",
"iteration",
",",
"viewer",
")",
":",
"expanded_neighbors",
"=",
"[",
"node",
".",
"expand",
"(",
"local_search",
"=",
"True",
")",
"for",
"node",
"in",
"fringe",
"]",
"if",
"viewer",
":",
"viewer",
".",
"event",
"(",
"'expanded'",
",",
"list",
"(",
"fringe",
")",
",",
"expanded_neighbors",
")",
"list",
"(",
"map",
"(",
"fringe",
".",
"extend",
",",
"expanded_neighbors",
")",
")"
] | Expander that expands all nodes on the fringe. | [
"Expander",
"that",
"expands",
"all",
"nodes",
"on",
"the",
"fringe",
"."
] | 2836befa7e970013f62e0ee75562652aacac6f65 | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/local.py#L8-L18 |
3,949 | simpleai-team/simpleai | simpleai/search/local.py | beam | def beam(problem, beam_size=100, iterations_limit=0, viewer=None):
'''
Beam search.
beam_size is the size of the beam.
If iterations_limit is specified, the algorithm will end after that
number of iterations. Else, it will continue until it can't find a
better node than the current one.
Requires: SearchProblem.actions, SearchProblem.result, SearchProblem.value,
and SearchProblem.generate_random_state.
'''
return _local_search(problem,
_all_expander,
iterations_limit=iterations_limit,
fringe_size=beam_size,
random_initial_states=True,
stop_when_no_better=iterations_limit==0,
viewer=viewer) | python | def beam(problem, beam_size=100, iterations_limit=0, viewer=None):
'''
Beam search.
beam_size is the size of the beam.
If iterations_limit is specified, the algorithm will end after that
number of iterations. Else, it will continue until it can't find a
better node than the current one.
Requires: SearchProblem.actions, SearchProblem.result, SearchProblem.value,
and SearchProblem.generate_random_state.
'''
return _local_search(problem,
_all_expander,
iterations_limit=iterations_limit,
fringe_size=beam_size,
random_initial_states=True,
stop_when_no_better=iterations_limit==0,
viewer=viewer) | [
"def",
"beam",
"(",
"problem",
",",
"beam_size",
"=",
"100",
",",
"iterations_limit",
"=",
"0",
",",
"viewer",
"=",
"None",
")",
":",
"return",
"_local_search",
"(",
"problem",
",",
"_all_expander",
",",
"iterations_limit",
"=",
"iterations_limit",
",",
"fringe_size",
"=",
"beam_size",
",",
"random_initial_states",
"=",
"True",
",",
"stop_when_no_better",
"=",
"iterations_limit",
"==",
"0",
",",
"viewer",
"=",
"viewer",
")"
] | Beam search.
beam_size is the size of the beam.
If iterations_limit is specified, the algorithm will end after that
number of iterations. Else, it will continue until it can't find a
better node than the current one.
Requires: SearchProblem.actions, SearchProblem.result, SearchProblem.value,
and SearchProblem.generate_random_state. | [
"Beam",
"search",
"."
] | 2836befa7e970013f62e0ee75562652aacac6f65 | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/local.py#L21-L38 |
3,950 | simpleai-team/simpleai | simpleai/search/local.py | _first_expander | def _first_expander(fringe, iteration, viewer):
'''
Expander that expands only the first node on the fringe.
'''
current = fringe[0]
neighbors = current.expand(local_search=True)
if viewer:
viewer.event('expanded', [current], [neighbors])
fringe.extend(neighbors) | python | def _first_expander(fringe, iteration, viewer):
'''
Expander that expands only the first node on the fringe.
'''
current = fringe[0]
neighbors = current.expand(local_search=True)
if viewer:
viewer.event('expanded', [current], [neighbors])
fringe.extend(neighbors) | [
"def",
"_first_expander",
"(",
"fringe",
",",
"iteration",
",",
"viewer",
")",
":",
"current",
"=",
"fringe",
"[",
"0",
"]",
"neighbors",
"=",
"current",
".",
"expand",
"(",
"local_search",
"=",
"True",
")",
"if",
"viewer",
":",
"viewer",
".",
"event",
"(",
"'expanded'",
",",
"[",
"current",
"]",
",",
"[",
"neighbors",
"]",
")",
"fringe",
".",
"extend",
"(",
"neighbors",
")"
] | Expander that expands only the first node on the fringe. | [
"Expander",
"that",
"expands",
"only",
"the",
"first",
"node",
"on",
"the",
"fringe",
"."
] | 2836befa7e970013f62e0ee75562652aacac6f65 | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/local.py#L41-L51 |
3,951 | simpleai-team/simpleai | simpleai/search/local.py | beam_best_first | def beam_best_first(problem, beam_size=100, iterations_limit=0, viewer=None):
'''
Beam search best first.
beam_size is the size of the beam.
If iterations_limit is specified, the algorithm will end after that
number of iterations. Else, it will continue until it can't find a
better node than the current one.
Requires: SearchProblem.actions, SearchProblem.result, and
SearchProblem.value.
'''
return _local_search(problem,
_first_expander,
iterations_limit=iterations_limit,
fringe_size=beam_size,
random_initial_states=True,
stop_when_no_better=iterations_limit==0,
viewer=viewer) | python | def beam_best_first(problem, beam_size=100, iterations_limit=0, viewer=None):
'''
Beam search best first.
beam_size is the size of the beam.
If iterations_limit is specified, the algorithm will end after that
number of iterations. Else, it will continue until it can't find a
better node than the current one.
Requires: SearchProblem.actions, SearchProblem.result, and
SearchProblem.value.
'''
return _local_search(problem,
_first_expander,
iterations_limit=iterations_limit,
fringe_size=beam_size,
random_initial_states=True,
stop_when_no_better=iterations_limit==0,
viewer=viewer) | [
"def",
"beam_best_first",
"(",
"problem",
",",
"beam_size",
"=",
"100",
",",
"iterations_limit",
"=",
"0",
",",
"viewer",
"=",
"None",
")",
":",
"return",
"_local_search",
"(",
"problem",
",",
"_first_expander",
",",
"iterations_limit",
"=",
"iterations_limit",
",",
"fringe_size",
"=",
"beam_size",
",",
"random_initial_states",
"=",
"True",
",",
"stop_when_no_better",
"=",
"iterations_limit",
"==",
"0",
",",
"viewer",
"=",
"viewer",
")"
] | Beam search best first.
beam_size is the size of the beam.
If iterations_limit is specified, the algorithm will end after that
number of iterations. Else, it will continue until it can't find a
better node than the current one.
Requires: SearchProblem.actions, SearchProblem.result, and
SearchProblem.value. | [
"Beam",
"search",
"best",
"first",
"."
] | 2836befa7e970013f62e0ee75562652aacac6f65 | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/local.py#L55-L72 |
3,952 | simpleai-team/simpleai | simpleai/search/local.py | hill_climbing | def hill_climbing(problem, iterations_limit=0, viewer=None):
'''
Hill climbing search.
If iterations_limit is specified, the algorithm will end after that
number of iterations. Else, it will continue until it can't find a
better node than the current one.
Requires: SearchProblem.actions, SearchProblem.result, and
SearchProblem.value.
'''
return _local_search(problem,
_first_expander,
iterations_limit=iterations_limit,
fringe_size=1,
stop_when_no_better=True,
viewer=viewer) | python | def hill_climbing(problem, iterations_limit=0, viewer=None):
'''
Hill climbing search.
If iterations_limit is specified, the algorithm will end after that
number of iterations. Else, it will continue until it can't find a
better node than the current one.
Requires: SearchProblem.actions, SearchProblem.result, and
SearchProblem.value.
'''
return _local_search(problem,
_first_expander,
iterations_limit=iterations_limit,
fringe_size=1,
stop_when_no_better=True,
viewer=viewer) | [
"def",
"hill_climbing",
"(",
"problem",
",",
"iterations_limit",
"=",
"0",
",",
"viewer",
"=",
"None",
")",
":",
"return",
"_local_search",
"(",
"problem",
",",
"_first_expander",
",",
"iterations_limit",
"=",
"iterations_limit",
",",
"fringe_size",
"=",
"1",
",",
"stop_when_no_better",
"=",
"True",
",",
"viewer",
"=",
"viewer",
")"
] | Hill climbing search.
If iterations_limit is specified, the algorithm will end after that
number of iterations. Else, it will continue until it can't find a
better node than the current one.
Requires: SearchProblem.actions, SearchProblem.result, and
SearchProblem.value. | [
"Hill",
"climbing",
"search",
"."
] | 2836befa7e970013f62e0ee75562652aacac6f65 | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/local.py#L75-L90 |
3,953 | simpleai-team/simpleai | simpleai/search/local.py | hill_climbing_stochastic | def hill_climbing_stochastic(problem, iterations_limit=0, viewer=None):
'''
Stochastic hill climbing.
If iterations_limit is specified, the algorithm will end after that
number of iterations. Else, it will continue until it can't find a
better node than the current one.
Requires: SearchProblem.actions, SearchProblem.result, and
SearchProblem.value.
'''
return _local_search(problem,
_random_best_expander,
iterations_limit=iterations_limit,
fringe_size=1,
stop_when_no_better=iterations_limit==0,
viewer=viewer) | python | def hill_climbing_stochastic(problem, iterations_limit=0, viewer=None):
'''
Stochastic hill climbing.
If iterations_limit is specified, the algorithm will end after that
number of iterations. Else, it will continue until it can't find a
better node than the current one.
Requires: SearchProblem.actions, SearchProblem.result, and
SearchProblem.value.
'''
return _local_search(problem,
_random_best_expander,
iterations_limit=iterations_limit,
fringe_size=1,
stop_when_no_better=iterations_limit==0,
viewer=viewer) | [
"def",
"hill_climbing_stochastic",
"(",
"problem",
",",
"iterations_limit",
"=",
"0",
",",
"viewer",
"=",
"None",
")",
":",
"return",
"_local_search",
"(",
"problem",
",",
"_random_best_expander",
",",
"iterations_limit",
"=",
"iterations_limit",
",",
"fringe_size",
"=",
"1",
",",
"stop_when_no_better",
"=",
"iterations_limit",
"==",
"0",
",",
"viewer",
"=",
"viewer",
")"
] | Stochastic hill climbing.
If iterations_limit is specified, the algorithm will end after that
number of iterations. Else, it will continue until it can't find a
better node than the current one.
Requires: SearchProblem.actions, SearchProblem.result, and
SearchProblem.value. | [
"Stochastic",
"hill",
"climbing",
"."
] | 2836befa7e970013f62e0ee75562652aacac6f65 | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/local.py#L112-L127 |
3,954 | simpleai-team/simpleai | simpleai/search/local.py | hill_climbing_random_restarts | def hill_climbing_random_restarts(problem, restarts_limit, iterations_limit=0, viewer=None):
'''
Hill climbing with random restarts.
restarts_limit specifies the number of times hill_climbing will be runned.
If iterations_limit is specified, each hill_climbing will end after that
number of iterations. Else, it will continue until it can't find a
better node than the current one.
Requires: SearchProblem.actions, SearchProblem.result, SearchProblem.value,
and SearchProblem.generate_random_state.
'''
restarts = 0
best = None
while restarts < restarts_limit:
new = _local_search(problem,
_first_expander,
iterations_limit=iterations_limit,
fringe_size=1,
random_initial_states=True,
stop_when_no_better=True,
viewer=viewer)
if not best or best.value < new.value:
best = new
restarts += 1
if viewer:
viewer.event('no_more_runs', best, 'returned after %i runs' % restarts_limit)
return best | python | def hill_climbing_random_restarts(problem, restarts_limit, iterations_limit=0, viewer=None):
'''
Hill climbing with random restarts.
restarts_limit specifies the number of times hill_climbing will be runned.
If iterations_limit is specified, each hill_climbing will end after that
number of iterations. Else, it will continue until it can't find a
better node than the current one.
Requires: SearchProblem.actions, SearchProblem.result, SearchProblem.value,
and SearchProblem.generate_random_state.
'''
restarts = 0
best = None
while restarts < restarts_limit:
new = _local_search(problem,
_first_expander,
iterations_limit=iterations_limit,
fringe_size=1,
random_initial_states=True,
stop_when_no_better=True,
viewer=viewer)
if not best or best.value < new.value:
best = new
restarts += 1
if viewer:
viewer.event('no_more_runs', best, 'returned after %i runs' % restarts_limit)
return best | [
"def",
"hill_climbing_random_restarts",
"(",
"problem",
",",
"restarts_limit",
",",
"iterations_limit",
"=",
"0",
",",
"viewer",
"=",
"None",
")",
":",
"restarts",
"=",
"0",
"best",
"=",
"None",
"while",
"restarts",
"<",
"restarts_limit",
":",
"new",
"=",
"_local_search",
"(",
"problem",
",",
"_first_expander",
",",
"iterations_limit",
"=",
"iterations_limit",
",",
"fringe_size",
"=",
"1",
",",
"random_initial_states",
"=",
"True",
",",
"stop_when_no_better",
"=",
"True",
",",
"viewer",
"=",
"viewer",
")",
"if",
"not",
"best",
"or",
"best",
".",
"value",
"<",
"new",
".",
"value",
":",
"best",
"=",
"new",
"restarts",
"+=",
"1",
"if",
"viewer",
":",
"viewer",
".",
"event",
"(",
"'no_more_runs'",
",",
"best",
",",
"'returned after %i runs'",
"%",
"restarts_limit",
")",
"return",
"best"
] | Hill climbing with random restarts.
restarts_limit specifies the number of times hill_climbing will be runned.
If iterations_limit is specified, each hill_climbing will end after that
number of iterations. Else, it will continue until it can't find a
better node than the current one.
Requires: SearchProblem.actions, SearchProblem.result, SearchProblem.value,
and SearchProblem.generate_random_state. | [
"Hill",
"climbing",
"with",
"random",
"restarts",
"."
] | 2836befa7e970013f62e0ee75562652aacac6f65 | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/local.py#L130-L161 |
3,955 | simpleai-team/simpleai | simpleai/search/local.py | _exp_schedule | def _exp_schedule(iteration, k=20, lam=0.005, limit=100):
'''
Possible scheduler for simulated_annealing, based on the aima example.
'''
return k * math.exp(-lam * iteration) | python | def _exp_schedule(iteration, k=20, lam=0.005, limit=100):
'''
Possible scheduler for simulated_annealing, based on the aima example.
'''
return k * math.exp(-lam * iteration) | [
"def",
"_exp_schedule",
"(",
"iteration",
",",
"k",
"=",
"20",
",",
"lam",
"=",
"0.005",
",",
"limit",
"=",
"100",
")",
":",
"return",
"k",
"*",
"math",
".",
"exp",
"(",
"-",
"lam",
"*",
"iteration",
")"
] | Possible scheduler for simulated_annealing, based on the aima example. | [
"Possible",
"scheduler",
"for",
"simulated_annealing",
"based",
"on",
"the",
"aima",
"example",
"."
] | 2836befa7e970013f62e0ee75562652aacac6f65 | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/local.py#L165-L169 |
3,956 | simpleai-team/simpleai | simpleai/search/local.py | simulated_annealing | def simulated_annealing(problem, schedule=_exp_schedule, iterations_limit=0, viewer=None):
'''
Simulated annealing.
schedule is the scheduling function that decides the chance to choose worst
nodes depending on the time.
If iterations_limit is specified, the algorithm will end after that
number of iterations. Else, it will continue until it can't find a
better node than the current one.
Requires: SearchProblem.actions, SearchProblem.result, and
SearchProblem.value.
'''
return _local_search(problem,
_create_simulated_annealing_expander(schedule),
iterations_limit=iterations_limit,
fringe_size=1,
stop_when_no_better=iterations_limit==0,
viewer=viewer) | python | def simulated_annealing(problem, schedule=_exp_schedule, iterations_limit=0, viewer=None):
'''
Simulated annealing.
schedule is the scheduling function that decides the chance to choose worst
nodes depending on the time.
If iterations_limit is specified, the algorithm will end after that
number of iterations. Else, it will continue until it can't find a
better node than the current one.
Requires: SearchProblem.actions, SearchProblem.result, and
SearchProblem.value.
'''
return _local_search(problem,
_create_simulated_annealing_expander(schedule),
iterations_limit=iterations_limit,
fringe_size=1,
stop_when_no_better=iterations_limit==0,
viewer=viewer) | [
"def",
"simulated_annealing",
"(",
"problem",
",",
"schedule",
"=",
"_exp_schedule",
",",
"iterations_limit",
"=",
"0",
",",
"viewer",
"=",
"None",
")",
":",
"return",
"_local_search",
"(",
"problem",
",",
"_create_simulated_annealing_expander",
"(",
"schedule",
")",
",",
"iterations_limit",
"=",
"iterations_limit",
",",
"fringe_size",
"=",
"1",
",",
"stop_when_no_better",
"=",
"iterations_limit",
"==",
"0",
",",
"viewer",
"=",
"viewer",
")"
] | Simulated annealing.
schedule is the scheduling function that decides the chance to choose worst
nodes depending on the time.
If iterations_limit is specified, the algorithm will end after that
number of iterations. Else, it will continue until it can't find a
better node than the current one.
Requires: SearchProblem.actions, SearchProblem.result, and
SearchProblem.value. | [
"Simulated",
"annealing",
"."
] | 2836befa7e970013f62e0ee75562652aacac6f65 | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/local.py#L198-L215 |
3,957 | simpleai-team/simpleai | simpleai/search/local.py | _create_genetic_expander | def _create_genetic_expander(problem, mutation_chance):
'''
Creates an expander that expands the bests nodes of the population,
crossing over them.
'''
def _expander(fringe, iteration, viewer):
fitness = [x.value for x in fringe]
sampler = InverseTransformSampler(fitness, fringe)
new_generation = []
expanded_nodes = []
expanded_neighbors = []
for _ in fringe:
node1 = sampler.sample()
node2 = sampler.sample()
child = problem.crossover(node1.state, node2.state)
action = 'crossover'
if random.random() < mutation_chance:
# Noooouuu! she is... he is... *IT* is a mutant!
child = problem.mutate(child)
action += '+mutation'
child_node = SearchNodeValueOrdered(state=child, problem=problem, action=action)
new_generation.append(child_node)
expanded_nodes.append(node1)
expanded_neighbors.append([child_node])
expanded_nodes.append(node2)
expanded_neighbors.append([child_node])
if viewer:
viewer.event('expanded', expanded_nodes, expanded_neighbors)
fringe.clear()
for node in new_generation:
fringe.append(node)
return _expander | python | def _create_genetic_expander(problem, mutation_chance):
'''
Creates an expander that expands the bests nodes of the population,
crossing over them.
'''
def _expander(fringe, iteration, viewer):
fitness = [x.value for x in fringe]
sampler = InverseTransformSampler(fitness, fringe)
new_generation = []
expanded_nodes = []
expanded_neighbors = []
for _ in fringe:
node1 = sampler.sample()
node2 = sampler.sample()
child = problem.crossover(node1.state, node2.state)
action = 'crossover'
if random.random() < mutation_chance:
# Noooouuu! she is... he is... *IT* is a mutant!
child = problem.mutate(child)
action += '+mutation'
child_node = SearchNodeValueOrdered(state=child, problem=problem, action=action)
new_generation.append(child_node)
expanded_nodes.append(node1)
expanded_neighbors.append([child_node])
expanded_nodes.append(node2)
expanded_neighbors.append([child_node])
if viewer:
viewer.event('expanded', expanded_nodes, expanded_neighbors)
fringe.clear()
for node in new_generation:
fringe.append(node)
return _expander | [
"def",
"_create_genetic_expander",
"(",
"problem",
",",
"mutation_chance",
")",
":",
"def",
"_expander",
"(",
"fringe",
",",
"iteration",
",",
"viewer",
")",
":",
"fitness",
"=",
"[",
"x",
".",
"value",
"for",
"x",
"in",
"fringe",
"]",
"sampler",
"=",
"InverseTransformSampler",
"(",
"fitness",
",",
"fringe",
")",
"new_generation",
"=",
"[",
"]",
"expanded_nodes",
"=",
"[",
"]",
"expanded_neighbors",
"=",
"[",
"]",
"for",
"_",
"in",
"fringe",
":",
"node1",
"=",
"sampler",
".",
"sample",
"(",
")",
"node2",
"=",
"sampler",
".",
"sample",
"(",
")",
"child",
"=",
"problem",
".",
"crossover",
"(",
"node1",
".",
"state",
",",
"node2",
".",
"state",
")",
"action",
"=",
"'crossover'",
"if",
"random",
".",
"random",
"(",
")",
"<",
"mutation_chance",
":",
"# Noooouuu! she is... he is... *IT* is a mutant!",
"child",
"=",
"problem",
".",
"mutate",
"(",
"child",
")",
"action",
"+=",
"'+mutation'",
"child_node",
"=",
"SearchNodeValueOrdered",
"(",
"state",
"=",
"child",
",",
"problem",
"=",
"problem",
",",
"action",
"=",
"action",
")",
"new_generation",
".",
"append",
"(",
"child_node",
")",
"expanded_nodes",
".",
"append",
"(",
"node1",
")",
"expanded_neighbors",
".",
"append",
"(",
"[",
"child_node",
"]",
")",
"expanded_nodes",
".",
"append",
"(",
"node2",
")",
"expanded_neighbors",
".",
"append",
"(",
"[",
"child_node",
"]",
")",
"if",
"viewer",
":",
"viewer",
".",
"event",
"(",
"'expanded'",
",",
"expanded_nodes",
",",
"expanded_neighbors",
")",
"fringe",
".",
"clear",
"(",
")",
"for",
"node",
"in",
"new_generation",
":",
"fringe",
".",
"append",
"(",
"node",
")",
"return",
"_expander"
] | Creates an expander that expands the bests nodes of the population,
crossing over them. | [
"Creates",
"an",
"expander",
"that",
"expands",
"the",
"bests",
"nodes",
"of",
"the",
"population",
"crossing",
"over",
"them",
"."
] | 2836befa7e970013f62e0ee75562652aacac6f65 | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/local.py#L218-L256 |
3,958 | simpleai-team/simpleai | simpleai/search/local.py | genetic | def genetic(problem, population_size=100, mutation_chance=0.1,
iterations_limit=0, viewer=None):
'''
Genetic search.
population_size specifies the size of the population (ORLY).
mutation_chance specifies the probability of a mutation on a child,
varying from 0 to 1.
If iterations_limit is specified, the algorithm will end after that
number of iterations. Else, it will continue until it can't find a
better node than the current one.
Requires: SearchProblem.generate_random_state, SearchProblem.crossover,
SearchProblem.mutate and SearchProblem.value.
'''
return _local_search(problem,
_create_genetic_expander(problem, mutation_chance),
iterations_limit=iterations_limit,
fringe_size=population_size,
random_initial_states=True,
stop_when_no_better=iterations_limit==0,
viewer=viewer) | python | def genetic(problem, population_size=100, mutation_chance=0.1,
iterations_limit=0, viewer=None):
'''
Genetic search.
population_size specifies the size of the population (ORLY).
mutation_chance specifies the probability of a mutation on a child,
varying from 0 to 1.
If iterations_limit is specified, the algorithm will end after that
number of iterations. Else, it will continue until it can't find a
better node than the current one.
Requires: SearchProblem.generate_random_state, SearchProblem.crossover,
SearchProblem.mutate and SearchProblem.value.
'''
return _local_search(problem,
_create_genetic_expander(problem, mutation_chance),
iterations_limit=iterations_limit,
fringe_size=population_size,
random_initial_states=True,
stop_when_no_better=iterations_limit==0,
viewer=viewer) | [
"def",
"genetic",
"(",
"problem",
",",
"population_size",
"=",
"100",
",",
"mutation_chance",
"=",
"0.1",
",",
"iterations_limit",
"=",
"0",
",",
"viewer",
"=",
"None",
")",
":",
"return",
"_local_search",
"(",
"problem",
",",
"_create_genetic_expander",
"(",
"problem",
",",
"mutation_chance",
")",
",",
"iterations_limit",
"=",
"iterations_limit",
",",
"fringe_size",
"=",
"population_size",
",",
"random_initial_states",
"=",
"True",
",",
"stop_when_no_better",
"=",
"iterations_limit",
"==",
"0",
",",
"viewer",
"=",
"viewer",
")"
] | Genetic search.
population_size specifies the size of the population (ORLY).
mutation_chance specifies the probability of a mutation on a child,
varying from 0 to 1.
If iterations_limit is specified, the algorithm will end after that
number of iterations. Else, it will continue until it can't find a
better node than the current one.
Requires: SearchProblem.generate_random_state, SearchProblem.crossover,
SearchProblem.mutate and SearchProblem.value. | [
"Genetic",
"search",
"."
] | 2836befa7e970013f62e0ee75562652aacac6f65 | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/local.py#L259-L279 |
3,959 | simpleai-team/simpleai | simpleai/search/local.py | _local_search | def _local_search(problem, fringe_expander, iterations_limit=0, fringe_size=1,
random_initial_states=False, stop_when_no_better=True,
viewer=None):
'''
Basic algorithm for all local search algorithms.
'''
if viewer:
viewer.event('started')
fringe = BoundedPriorityQueue(fringe_size)
if random_initial_states:
for _ in range(fringe_size):
s = problem.generate_random_state()
fringe.append(SearchNodeValueOrdered(state=s, problem=problem))
else:
fringe.append(SearchNodeValueOrdered(state=problem.initial_state,
problem=problem))
finish_reason = ''
iteration = 0
run = True
best = None
while run:
if viewer:
viewer.event('new_iteration', list(fringe))
old_best = fringe[0]
fringe_expander(fringe, iteration, viewer)
best = fringe[0]
iteration += 1
if iterations_limit and iteration >= iterations_limit:
run = False
finish_reason = 'reaching iteration limit'
elif old_best.value >= best.value and stop_when_no_better:
run = False
finish_reason = 'not being able to improve solution'
if viewer:
viewer.event('finished', fringe, best, 'returned after %s' % finish_reason)
return best | python | def _local_search(problem, fringe_expander, iterations_limit=0, fringe_size=1,
random_initial_states=False, stop_when_no_better=True,
viewer=None):
'''
Basic algorithm for all local search algorithms.
'''
if viewer:
viewer.event('started')
fringe = BoundedPriorityQueue(fringe_size)
if random_initial_states:
for _ in range(fringe_size):
s = problem.generate_random_state()
fringe.append(SearchNodeValueOrdered(state=s, problem=problem))
else:
fringe.append(SearchNodeValueOrdered(state=problem.initial_state,
problem=problem))
finish_reason = ''
iteration = 0
run = True
best = None
while run:
if viewer:
viewer.event('new_iteration', list(fringe))
old_best = fringe[0]
fringe_expander(fringe, iteration, viewer)
best = fringe[0]
iteration += 1
if iterations_limit and iteration >= iterations_limit:
run = False
finish_reason = 'reaching iteration limit'
elif old_best.value >= best.value and stop_when_no_better:
run = False
finish_reason = 'not being able to improve solution'
if viewer:
viewer.event('finished', fringe, best, 'returned after %s' % finish_reason)
return best | [
"def",
"_local_search",
"(",
"problem",
",",
"fringe_expander",
",",
"iterations_limit",
"=",
"0",
",",
"fringe_size",
"=",
"1",
",",
"random_initial_states",
"=",
"False",
",",
"stop_when_no_better",
"=",
"True",
",",
"viewer",
"=",
"None",
")",
":",
"if",
"viewer",
":",
"viewer",
".",
"event",
"(",
"'started'",
")",
"fringe",
"=",
"BoundedPriorityQueue",
"(",
"fringe_size",
")",
"if",
"random_initial_states",
":",
"for",
"_",
"in",
"range",
"(",
"fringe_size",
")",
":",
"s",
"=",
"problem",
".",
"generate_random_state",
"(",
")",
"fringe",
".",
"append",
"(",
"SearchNodeValueOrdered",
"(",
"state",
"=",
"s",
",",
"problem",
"=",
"problem",
")",
")",
"else",
":",
"fringe",
".",
"append",
"(",
"SearchNodeValueOrdered",
"(",
"state",
"=",
"problem",
".",
"initial_state",
",",
"problem",
"=",
"problem",
")",
")",
"finish_reason",
"=",
"''",
"iteration",
"=",
"0",
"run",
"=",
"True",
"best",
"=",
"None",
"while",
"run",
":",
"if",
"viewer",
":",
"viewer",
".",
"event",
"(",
"'new_iteration'",
",",
"list",
"(",
"fringe",
")",
")",
"old_best",
"=",
"fringe",
"[",
"0",
"]",
"fringe_expander",
"(",
"fringe",
",",
"iteration",
",",
"viewer",
")",
"best",
"=",
"fringe",
"[",
"0",
"]",
"iteration",
"+=",
"1",
"if",
"iterations_limit",
"and",
"iteration",
">=",
"iterations_limit",
":",
"run",
"=",
"False",
"finish_reason",
"=",
"'reaching iteration limit'",
"elif",
"old_best",
".",
"value",
">=",
"best",
".",
"value",
"and",
"stop_when_no_better",
":",
"run",
"=",
"False",
"finish_reason",
"=",
"'not being able to improve solution'",
"if",
"viewer",
":",
"viewer",
".",
"event",
"(",
"'finished'",
",",
"fringe",
",",
"best",
",",
"'returned after %s'",
"%",
"finish_reason",
")",
"return",
"best"
] | Basic algorithm for all local search algorithms. | [
"Basic",
"algorithm",
"for",
"all",
"local",
"search",
"algorithms",
"."
] | 2836befa7e970013f62e0ee75562652aacac6f65 | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/local.py#L282-L325 |
3,960 | simpleai-team/simpleai | samples/search/eight_puzzle.py | EigthPuzzleProblem.actions | def actions(self, state):
'''Returns a list of the pieces we can move to the empty space.'''
rows = string_to_list(state)
row_e, col_e = find_location(rows, 'e')
actions = []
if row_e > 0:
actions.append(rows[row_e - 1][col_e])
if row_e < 2:
actions.append(rows[row_e + 1][col_e])
if col_e > 0:
actions.append(rows[row_e][col_e - 1])
if col_e < 2:
actions.append(rows[row_e][col_e + 1])
return actions | python | def actions(self, state):
'''Returns a list of the pieces we can move to the empty space.'''
rows = string_to_list(state)
row_e, col_e = find_location(rows, 'e')
actions = []
if row_e > 0:
actions.append(rows[row_e - 1][col_e])
if row_e < 2:
actions.append(rows[row_e + 1][col_e])
if col_e > 0:
actions.append(rows[row_e][col_e - 1])
if col_e < 2:
actions.append(rows[row_e][col_e + 1])
return actions | [
"def",
"actions",
"(",
"self",
",",
"state",
")",
":",
"rows",
"=",
"string_to_list",
"(",
"state",
")",
"row_e",
",",
"col_e",
"=",
"find_location",
"(",
"rows",
",",
"'e'",
")",
"actions",
"=",
"[",
"]",
"if",
"row_e",
">",
"0",
":",
"actions",
".",
"append",
"(",
"rows",
"[",
"row_e",
"-",
"1",
"]",
"[",
"col_e",
"]",
")",
"if",
"row_e",
"<",
"2",
":",
"actions",
".",
"append",
"(",
"rows",
"[",
"row_e",
"+",
"1",
"]",
"[",
"col_e",
"]",
")",
"if",
"col_e",
">",
"0",
":",
"actions",
".",
"append",
"(",
"rows",
"[",
"row_e",
"]",
"[",
"col_e",
"-",
"1",
"]",
")",
"if",
"col_e",
"<",
"2",
":",
"actions",
".",
"append",
"(",
"rows",
"[",
"row_e",
"]",
"[",
"col_e",
"+",
"1",
"]",
")",
"return",
"actions"
] | Returns a list of the pieces we can move to the empty space. | [
"Returns",
"a",
"list",
"of",
"the",
"pieces",
"we",
"can",
"move",
"to",
"the",
"empty",
"space",
"."
] | 2836befa7e970013f62e0ee75562652aacac6f65 | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/samples/search/eight_puzzle.py#L64-L79 |
3,961 | simpleai-team/simpleai | simpleai/machine_learning/models.py | is_attribute | def is_attribute(method, name=None):
"""
Decorator for methods that are attributes.
"""
if name is None:
name = method.__name__
method.is_attribute = True
method.name = name
return method | python | def is_attribute(method, name=None):
"""
Decorator for methods that are attributes.
"""
if name is None:
name = method.__name__
method.is_attribute = True
method.name = name
return method | [
"def",
"is_attribute",
"(",
"method",
",",
"name",
"=",
"None",
")",
":",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"method",
".",
"__name__",
"method",
".",
"is_attribute",
"=",
"True",
"method",
".",
"name",
"=",
"name",
"return",
"method"
] | Decorator for methods that are attributes. | [
"Decorator",
"for",
"methods",
"that",
"are",
"attributes",
"."
] | 2836befa7e970013f62e0ee75562652aacac6f65 | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/machine_learning/models.py#L230-L238 |
3,962 | simpleai-team/simpleai | simpleai/machine_learning/models.py | Classifier.load | def load(cls, filepath):
"""
Loads a pickled version of the classifier saved in `filepath`
"""
with open(filepath, "rb") as filehandler:
classifier = pickle.load(filehandler)
if not isinstance(classifier, Classifier):
raise ValueError("Pickled object is not a Classifier")
return classifier | python | def load(cls, filepath):
"""
Loads a pickled version of the classifier saved in `filepath`
"""
with open(filepath, "rb") as filehandler:
classifier = pickle.load(filehandler)
if not isinstance(classifier, Classifier):
raise ValueError("Pickled object is not a Classifier")
return classifier | [
"def",
"load",
"(",
"cls",
",",
"filepath",
")",
":",
"with",
"open",
"(",
"filepath",
",",
"\"rb\"",
")",
"as",
"filehandler",
":",
"classifier",
"=",
"pickle",
".",
"load",
"(",
"filehandler",
")",
"if",
"not",
"isinstance",
"(",
"classifier",
",",
"Classifier",
")",
":",
"raise",
"ValueError",
"(",
"\"Pickled object is not a Classifier\"",
")",
"return",
"classifier"
] | Loads a pickled version of the classifier saved in `filepath` | [
"Loads",
"a",
"pickled",
"version",
"of",
"the",
"classifier",
"saved",
"in",
"filepath"
] | 2836befa7e970013f62e0ee75562652aacac6f65 | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/machine_learning/models.py#L76-L86 |
3,963 | simpleai-team/simpleai | simpleai/machine_learning/classifiers.py | tree_to_str | def tree_to_str(root):
"""
Returns a string representation of a decision tree with
root node `root`.
"""
xs = []
for value, node, depth in iter_tree(root):
template = "{indent}"
if node is not root:
template += "case={value}\t"
if node.attribute is None:
template += "result={result} -- P={prob:.2}"
else:
template += "split by {split}:\t" +\
"(partial result={result} -- P={prob:.2})"
line = template.format(indent=" " * depth,
value=value,
result=node.result[0],
prob=node.result[1],
split=str(node.attribute))
xs.append(line)
return "\n".join(xs) | python | def tree_to_str(root):
"""
Returns a string representation of a decision tree with
root node `root`.
"""
xs = []
for value, node, depth in iter_tree(root):
template = "{indent}"
if node is not root:
template += "case={value}\t"
if node.attribute is None:
template += "result={result} -- P={prob:.2}"
else:
template += "split by {split}:\t" +\
"(partial result={result} -- P={prob:.2})"
line = template.format(indent=" " * depth,
value=value,
result=node.result[0],
prob=node.result[1],
split=str(node.attribute))
xs.append(line)
return "\n".join(xs) | [
"def",
"tree_to_str",
"(",
"root",
")",
":",
"xs",
"=",
"[",
"]",
"for",
"value",
",",
"node",
",",
"depth",
"in",
"iter_tree",
"(",
"root",
")",
":",
"template",
"=",
"\"{indent}\"",
"if",
"node",
"is",
"not",
"root",
":",
"template",
"+=",
"\"case={value}\\t\"",
"if",
"node",
".",
"attribute",
"is",
"None",
":",
"template",
"+=",
"\"result={result} -- P={prob:.2}\"",
"else",
":",
"template",
"+=",
"\"split by {split}:\\t\"",
"+",
"\"(partial result={result} -- P={prob:.2})\"",
"line",
"=",
"template",
".",
"format",
"(",
"indent",
"=",
"\" \"",
"*",
"depth",
",",
"value",
"=",
"value",
",",
"result",
"=",
"node",
".",
"result",
"[",
"0",
"]",
",",
"prob",
"=",
"node",
".",
"result",
"[",
"1",
"]",
",",
"split",
"=",
"str",
"(",
"node",
".",
"attribute",
")",
")",
"xs",
".",
"append",
"(",
"line",
")",
"return",
"\"\\n\"",
".",
"join",
"(",
"xs",
")"
] | Returns a string representation of a decision tree with
root node `root`. | [
"Returns",
"a",
"string",
"representation",
"of",
"a",
"decision",
"tree",
"with",
"root",
"node",
"root",
"."
] | 2836befa7e970013f62e0ee75562652aacac6f65 | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/machine_learning/classifiers.py#L216-L238 |
3,964 | simpleai-team/simpleai | simpleai/machine_learning/classifiers.py | KNearestNeighbors.save | def save(self, filepath):
"""
Saves the classifier to `filepath`.
Because this classifier needs to save the dataset, it must
be something that can be pickled and not something like an
iterator.
"""
if not filepath or not isinstance(filepath, str):
raise ValueError("Invalid filepath")
with open(filepath, "wb") as filehandler:
pickle.dump(self, filehandler) | python | def save(self, filepath):
"""
Saves the classifier to `filepath`.
Because this classifier needs to save the dataset, it must
be something that can be pickled and not something like an
iterator.
"""
if not filepath or not isinstance(filepath, str):
raise ValueError("Invalid filepath")
with open(filepath, "wb") as filehandler:
pickle.dump(self, filehandler) | [
"def",
"save",
"(",
"self",
",",
"filepath",
")",
":",
"if",
"not",
"filepath",
"or",
"not",
"isinstance",
"(",
"filepath",
",",
"str",
")",
":",
"raise",
"ValueError",
"(",
"\"Invalid filepath\"",
")",
"with",
"open",
"(",
"filepath",
",",
"\"wb\"",
")",
"as",
"filehandler",
":",
"pickle",
".",
"dump",
"(",
"self",
",",
"filehandler",
")"
] | Saves the classifier to `filepath`.
Because this classifier needs to save the dataset, it must
be something that can be pickled and not something like an
iterator. | [
"Saves",
"the",
"classifier",
"to",
"filepath",
".",
"Because",
"this",
"classifier",
"needs",
"to",
"save",
"the",
"dataset",
"it",
"must",
"be",
"something",
"that",
"can",
"be",
"pickled",
"and",
"not",
"something",
"like",
"an",
"iterator",
"."
] | 2836befa7e970013f62e0ee75562652aacac6f65 | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/machine_learning/classifiers.py#L180-L192 |
3,965 | simpleai-team/simpleai | simpleai/machine_learning/classifiers.py | DecisionTreeLearner_Queued._max_gain_split | def _max_gain_split(self, examples):
"""
Returns an OnlineInformationGain of the attribute with
max gain based on `examples`.
"""
gains = self._new_set_of_gain_counters()
for example in examples:
for gain in gains:
gain.add(example)
winner = max(gains, key=lambda gain: gain.get_gain())
if not winner.get_target_class_counts():
raise ValueError("Dataset is empty")
return winner | python | def _max_gain_split(self, examples):
"""
Returns an OnlineInformationGain of the attribute with
max gain based on `examples`.
"""
gains = self._new_set_of_gain_counters()
for example in examples:
for gain in gains:
gain.add(example)
winner = max(gains, key=lambda gain: gain.get_gain())
if not winner.get_target_class_counts():
raise ValueError("Dataset is empty")
return winner | [
"def",
"_max_gain_split",
"(",
"self",
",",
"examples",
")",
":",
"gains",
"=",
"self",
".",
"_new_set_of_gain_counters",
"(",
")",
"for",
"example",
"in",
"examples",
":",
"for",
"gain",
"in",
"gains",
":",
"gain",
".",
"add",
"(",
"example",
")",
"winner",
"=",
"max",
"(",
"gains",
",",
"key",
"=",
"lambda",
"gain",
":",
"gain",
".",
"get_gain",
"(",
")",
")",
"if",
"not",
"winner",
".",
"get_target_class_counts",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Dataset is empty\"",
")",
"return",
"winner"
] | Returns an OnlineInformationGain of the attribute with
max gain based on `examples`. | [
"Returns",
"an",
"OnlineInformationGain",
"of",
"the",
"attribute",
"with",
"max",
"gain",
"based",
"on",
"examples",
"."
] | 2836befa7e970013f62e0ee75562652aacac6f65 | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/machine_learning/classifiers.py#L322-L334 |
3,966 | simpleai-team/simpleai | simpleai/search/csp.py | backtrack | def backtrack(problem, variable_heuristic='', value_heuristic='', inference=True):
'''
Backtracking search.
variable_heuristic is the heuristic for variable choosing, can be
MOST_CONSTRAINED_VARIABLE, HIGHEST_DEGREE_VARIABLE, or blank for simple
ordered choosing.
value_heuristic is the heuristic for value choosing, can be
LEAST_CONSTRAINING_VALUE or blank for simple ordered choosing.
'''
assignment = {}
domains = deepcopy(problem.domains)
if variable_heuristic == MOST_CONSTRAINED_VARIABLE:
variable_chooser = _most_constrained_variable_chooser
elif variable_heuristic == HIGHEST_DEGREE_VARIABLE:
variable_chooser = _highest_degree_variable_chooser
else:
variable_chooser = _basic_variable_chooser
if value_heuristic == LEAST_CONSTRAINING_VALUE:
values_sorter = _least_constraining_values_sorter
else:
values_sorter = _basic_values_sorter
return _backtracking(problem,
assignment,
domains,
variable_chooser,
values_sorter,
inference=inference) | python | def backtrack(problem, variable_heuristic='', value_heuristic='', inference=True):
'''
Backtracking search.
variable_heuristic is the heuristic for variable choosing, can be
MOST_CONSTRAINED_VARIABLE, HIGHEST_DEGREE_VARIABLE, or blank for simple
ordered choosing.
value_heuristic is the heuristic for value choosing, can be
LEAST_CONSTRAINING_VALUE or blank for simple ordered choosing.
'''
assignment = {}
domains = deepcopy(problem.domains)
if variable_heuristic == MOST_CONSTRAINED_VARIABLE:
variable_chooser = _most_constrained_variable_chooser
elif variable_heuristic == HIGHEST_DEGREE_VARIABLE:
variable_chooser = _highest_degree_variable_chooser
else:
variable_chooser = _basic_variable_chooser
if value_heuristic == LEAST_CONSTRAINING_VALUE:
values_sorter = _least_constraining_values_sorter
else:
values_sorter = _basic_values_sorter
return _backtracking(problem,
assignment,
domains,
variable_chooser,
values_sorter,
inference=inference) | [
"def",
"backtrack",
"(",
"problem",
",",
"variable_heuristic",
"=",
"''",
",",
"value_heuristic",
"=",
"''",
",",
"inference",
"=",
"True",
")",
":",
"assignment",
"=",
"{",
"}",
"domains",
"=",
"deepcopy",
"(",
"problem",
".",
"domains",
")",
"if",
"variable_heuristic",
"==",
"MOST_CONSTRAINED_VARIABLE",
":",
"variable_chooser",
"=",
"_most_constrained_variable_chooser",
"elif",
"variable_heuristic",
"==",
"HIGHEST_DEGREE_VARIABLE",
":",
"variable_chooser",
"=",
"_highest_degree_variable_chooser",
"else",
":",
"variable_chooser",
"=",
"_basic_variable_chooser",
"if",
"value_heuristic",
"==",
"LEAST_CONSTRAINING_VALUE",
":",
"values_sorter",
"=",
"_least_constraining_values_sorter",
"else",
":",
"values_sorter",
"=",
"_basic_values_sorter",
"return",
"_backtracking",
"(",
"problem",
",",
"assignment",
",",
"domains",
",",
"variable_chooser",
",",
"values_sorter",
",",
"inference",
"=",
"inference",
")"
] | Backtracking search.
variable_heuristic is the heuristic for variable choosing, can be
MOST_CONSTRAINED_VARIABLE, HIGHEST_DEGREE_VARIABLE, or blank for simple
ordered choosing.
value_heuristic is the heuristic for value choosing, can be
LEAST_CONSTRAINING_VALUE or blank for simple ordered choosing. | [
"Backtracking",
"search",
"."
] | 2836befa7e970013f62e0ee75562652aacac6f65 | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/csp.py#L12-L41 |
3,967 | simpleai-team/simpleai | simpleai/search/csp.py | _most_constrained_variable_chooser | def _most_constrained_variable_chooser(problem, variables, domains):
'''
Choose the variable that has less available values.
'''
# the variable with fewer values available
return sorted(variables, key=lambda v: len(domains[v]))[0] | python | def _most_constrained_variable_chooser(problem, variables, domains):
'''
Choose the variable that has less available values.
'''
# the variable with fewer values available
return sorted(variables, key=lambda v: len(domains[v]))[0] | [
"def",
"_most_constrained_variable_chooser",
"(",
"problem",
",",
"variables",
",",
"domains",
")",
":",
"# the variable with fewer values available",
"return",
"sorted",
"(",
"variables",
",",
"key",
"=",
"lambda",
"v",
":",
"len",
"(",
"domains",
"[",
"v",
"]",
")",
")",
"[",
"0",
"]"
] | Choose the variable that has less available values. | [
"Choose",
"the",
"variable",
"that",
"has",
"less",
"available",
"values",
"."
] | 2836befa7e970013f62e0ee75562652aacac6f65 | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/csp.py#L51-L56 |
3,968 | simpleai-team/simpleai | simpleai/search/csp.py | _highest_degree_variable_chooser | def _highest_degree_variable_chooser(problem, variables, domains):
'''
Choose the variable that is involved on more constraints.
'''
# the variable involved in more constraints
return sorted(variables, key=lambda v: problem.var_degrees[v], reverse=True)[0] | python | def _highest_degree_variable_chooser(problem, variables, domains):
'''
Choose the variable that is involved on more constraints.
'''
# the variable involved in more constraints
return sorted(variables, key=lambda v: problem.var_degrees[v], reverse=True)[0] | [
"def",
"_highest_degree_variable_chooser",
"(",
"problem",
",",
"variables",
",",
"domains",
")",
":",
"# the variable involved in more constraints",
"return",
"sorted",
"(",
"variables",
",",
"key",
"=",
"lambda",
"v",
":",
"problem",
".",
"var_degrees",
"[",
"v",
"]",
",",
"reverse",
"=",
"True",
")",
"[",
"0",
"]"
] | Choose the variable that is involved on more constraints. | [
"Choose",
"the",
"variable",
"that",
"is",
"involved",
"on",
"more",
"constraints",
"."
] | 2836befa7e970013f62e0ee75562652aacac6f65 | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/csp.py#L59-L64 |
3,969 | simpleai-team/simpleai | simpleai/search/csp.py | _count_conflicts | def _count_conflicts(problem, assignment, variable=None, value=None):
'''
Count the number of violated constraints on a given assignment.
'''
return len(_find_conflicts(problem, assignment, variable, value)) | python | def _count_conflicts(problem, assignment, variable=None, value=None):
'''
Count the number of violated constraints on a given assignment.
'''
return len(_find_conflicts(problem, assignment, variable, value)) | [
"def",
"_count_conflicts",
"(",
"problem",
",",
"assignment",
",",
"variable",
"=",
"None",
",",
"value",
"=",
"None",
")",
":",
"return",
"len",
"(",
"_find_conflicts",
"(",
"problem",
",",
"assignment",
",",
"variable",
",",
"value",
")",
")"
] | Count the number of violated constraints on a given assignment. | [
"Count",
"the",
"number",
"of",
"violated",
"constraints",
"on",
"a",
"given",
"assignment",
"."
] | 2836befa7e970013f62e0ee75562652aacac6f65 | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/csp.py#L67-L71 |
3,970 | simpleai-team/simpleai | simpleai/search/csp.py | _find_conflicts | def _find_conflicts(problem, assignment, variable=None, value=None):
'''
Find violated constraints on a given assignment, with the possibility
of specifying a new variable and value to add to the assignment before
checking.
'''
if variable is not None and value is not None:
assignment = deepcopy(assignment)
assignment[variable] = value
conflicts = []
for neighbors, constraint in problem.constraints:
# if all the neighbors on the constraint have values, check if conflict
if all(n in assignment for n in neighbors):
if not _call_constraint(assignment, neighbors, constraint):
conflicts.append((neighbors, constraint))
return conflicts | python | def _find_conflicts(problem, assignment, variable=None, value=None):
'''
Find violated constraints on a given assignment, with the possibility
of specifying a new variable and value to add to the assignment before
checking.
'''
if variable is not None and value is not None:
assignment = deepcopy(assignment)
assignment[variable] = value
conflicts = []
for neighbors, constraint in problem.constraints:
# if all the neighbors on the constraint have values, check if conflict
if all(n in assignment for n in neighbors):
if not _call_constraint(assignment, neighbors, constraint):
conflicts.append((neighbors, constraint))
return conflicts | [
"def",
"_find_conflicts",
"(",
"problem",
",",
"assignment",
",",
"variable",
"=",
"None",
",",
"value",
"=",
"None",
")",
":",
"if",
"variable",
"is",
"not",
"None",
"and",
"value",
"is",
"not",
"None",
":",
"assignment",
"=",
"deepcopy",
"(",
"assignment",
")",
"assignment",
"[",
"variable",
"]",
"=",
"value",
"conflicts",
"=",
"[",
"]",
"for",
"neighbors",
",",
"constraint",
"in",
"problem",
".",
"constraints",
":",
"# if all the neighbors on the constraint have values, check if conflict",
"if",
"all",
"(",
"n",
"in",
"assignment",
"for",
"n",
"in",
"neighbors",
")",
":",
"if",
"not",
"_call_constraint",
"(",
"assignment",
",",
"neighbors",
",",
"constraint",
")",
":",
"conflicts",
".",
"append",
"(",
"(",
"neighbors",
",",
"constraint",
")",
")",
"return",
"conflicts"
] | Find violated constraints on a given assignment, with the possibility
of specifying a new variable and value to add to the assignment before
checking. | [
"Find",
"violated",
"constraints",
"on",
"a",
"given",
"assignment",
"with",
"the",
"possibility",
"of",
"specifying",
"a",
"new",
"variable",
"and",
"value",
"to",
"add",
"to",
"the",
"assignment",
"before",
"checking",
"."
] | 2836befa7e970013f62e0ee75562652aacac6f65 | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/csp.py#L80-L97 |
3,971 | simpleai-team/simpleai | simpleai/search/csp.py | _least_constraining_values_sorter | def _least_constraining_values_sorter(problem, assignment, variable, domains):
'''
Sort values based on how many conflicts they generate if assigned.
'''
# the value that generates less conflicts
def update_assignment(value):
new_assignment = deepcopy(assignment)
new_assignment[variable] = value
return new_assignment
values = sorted(domains[variable][:],
key=lambda v: _count_conflicts(problem, assignment,
variable, v))
return values | python | def _least_constraining_values_sorter(problem, assignment, variable, domains):
'''
Sort values based on how many conflicts they generate if assigned.
'''
# the value that generates less conflicts
def update_assignment(value):
new_assignment = deepcopy(assignment)
new_assignment[variable] = value
return new_assignment
values = sorted(domains[variable][:],
key=lambda v: _count_conflicts(problem, assignment,
variable, v))
return values | [
"def",
"_least_constraining_values_sorter",
"(",
"problem",
",",
"assignment",
",",
"variable",
",",
"domains",
")",
":",
"# the value that generates less conflicts",
"def",
"update_assignment",
"(",
"value",
")",
":",
"new_assignment",
"=",
"deepcopy",
"(",
"assignment",
")",
"new_assignment",
"[",
"variable",
"]",
"=",
"value",
"return",
"new_assignment",
"values",
"=",
"sorted",
"(",
"domains",
"[",
"variable",
"]",
"[",
":",
"]",
",",
"key",
"=",
"lambda",
"v",
":",
"_count_conflicts",
"(",
"problem",
",",
"assignment",
",",
"variable",
",",
"v",
")",
")",
"return",
"values"
] | Sort values based on how many conflicts they generate if assigned. | [
"Sort",
"values",
"based",
"on",
"how",
"many",
"conflicts",
"they",
"generate",
"if",
"assigned",
"."
] | 2836befa7e970013f62e0ee75562652aacac6f65 | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/csp.py#L107-L120 |
3,972 | simpleai-team/simpleai | simpleai/search/csp.py | _backtracking | def _backtracking(problem, assignment, domains, variable_chooser, values_sorter, inference=True):
'''
Internal recursive backtracking algorithm.
'''
from simpleai.search.arc import arc_consistency_3
if len(assignment) == len(problem.variables):
return assignment
pending = [v for v in problem.variables
if v not in assignment]
variable = variable_chooser(problem, pending, domains)
values = values_sorter(problem, assignment, variable, domains)
for value in values:
new_assignment = deepcopy(assignment)
new_assignment[variable] = value
if not _count_conflicts(problem, new_assignment): # TODO on aima also checks if using fc
new_domains = deepcopy(domains)
new_domains[variable] = [value]
if not inference or arc_consistency_3(new_domains, problem.constraints):
result = _backtracking(problem,
new_assignment,
new_domains,
variable_chooser,
values_sorter,
inference=inference)
if result:
return result
return None | python | def _backtracking(problem, assignment, domains, variable_chooser, values_sorter, inference=True):
'''
Internal recursive backtracking algorithm.
'''
from simpleai.search.arc import arc_consistency_3
if len(assignment) == len(problem.variables):
return assignment
pending = [v for v in problem.variables
if v not in assignment]
variable = variable_chooser(problem, pending, domains)
values = values_sorter(problem, assignment, variable, domains)
for value in values:
new_assignment = deepcopy(assignment)
new_assignment[variable] = value
if not _count_conflicts(problem, new_assignment): # TODO on aima also checks if using fc
new_domains = deepcopy(domains)
new_domains[variable] = [value]
if not inference or arc_consistency_3(new_domains, problem.constraints):
result = _backtracking(problem,
new_assignment,
new_domains,
variable_chooser,
values_sorter,
inference=inference)
if result:
return result
return None | [
"def",
"_backtracking",
"(",
"problem",
",",
"assignment",
",",
"domains",
",",
"variable_chooser",
",",
"values_sorter",
",",
"inference",
"=",
"True",
")",
":",
"from",
"simpleai",
".",
"search",
".",
"arc",
"import",
"arc_consistency_3",
"if",
"len",
"(",
"assignment",
")",
"==",
"len",
"(",
"problem",
".",
"variables",
")",
":",
"return",
"assignment",
"pending",
"=",
"[",
"v",
"for",
"v",
"in",
"problem",
".",
"variables",
"if",
"v",
"not",
"in",
"assignment",
"]",
"variable",
"=",
"variable_chooser",
"(",
"problem",
",",
"pending",
",",
"domains",
")",
"values",
"=",
"values_sorter",
"(",
"problem",
",",
"assignment",
",",
"variable",
",",
"domains",
")",
"for",
"value",
"in",
"values",
":",
"new_assignment",
"=",
"deepcopy",
"(",
"assignment",
")",
"new_assignment",
"[",
"variable",
"]",
"=",
"value",
"if",
"not",
"_count_conflicts",
"(",
"problem",
",",
"new_assignment",
")",
":",
"# TODO on aima also checks if using fc",
"new_domains",
"=",
"deepcopy",
"(",
"domains",
")",
"new_domains",
"[",
"variable",
"]",
"=",
"[",
"value",
"]",
"if",
"not",
"inference",
"or",
"arc_consistency_3",
"(",
"new_domains",
",",
"problem",
".",
"constraints",
")",
":",
"result",
"=",
"_backtracking",
"(",
"problem",
",",
"new_assignment",
",",
"new_domains",
",",
"variable_chooser",
",",
"values_sorter",
",",
"inference",
"=",
"inference",
")",
"if",
"result",
":",
"return",
"result",
"return",
"None"
] | Internal recursive backtracking algorithm. | [
"Internal",
"recursive",
"backtracking",
"algorithm",
"."
] | 2836befa7e970013f62e0ee75562652aacac6f65 | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/csp.py#L123-L155 |
3,973 | simpleai-team/simpleai | simpleai/search/csp.py | _min_conflicts_value | def _min_conflicts_value(problem, assignment, variable):
'''
Return the value generate the less number of conflicts.
In case of tie, a random value is selected among this values subset.
'''
return argmin(problem.domains[variable], lambda x: _count_conflicts(problem, assignment, variable, x)) | python | def _min_conflicts_value(problem, assignment, variable):
'''
Return the value generate the less number of conflicts.
In case of tie, a random value is selected among this values subset.
'''
return argmin(problem.domains[variable], lambda x: _count_conflicts(problem, assignment, variable, x)) | [
"def",
"_min_conflicts_value",
"(",
"problem",
",",
"assignment",
",",
"variable",
")",
":",
"return",
"argmin",
"(",
"problem",
".",
"domains",
"[",
"variable",
"]",
",",
"lambda",
"x",
":",
"_count_conflicts",
"(",
"problem",
",",
"assignment",
",",
"variable",
",",
"x",
")",
")"
] | Return the value generate the less number of conflicts.
In case of tie, a random value is selected among this values subset. | [
"Return",
"the",
"value",
"generate",
"the",
"less",
"number",
"of",
"conflicts",
".",
"In",
"case",
"of",
"tie",
"a",
"random",
"value",
"is",
"selected",
"among",
"this",
"values",
"subset",
"."
] | 2836befa7e970013f62e0ee75562652aacac6f65 | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/csp.py#L158-L163 |
3,974 | simpleai-team/simpleai | simpleai/search/csp.py | min_conflicts | def min_conflicts(problem, initial_assignment=None, iterations_limit=0):
"""
Min conflicts search.
initial_assignment the initial assignment, or None to generate a random
one.
If iterations_limit is specified, the algorithm will end after that
number of iterations. Else, it will continue until if finds an assignment
that doesn't generate conflicts (a solution).
"""
assignment = {}
if initial_assignment:
assignment.update(initial_assignment)
else:
for variable in problem.variables:
value = _min_conflicts_value(problem, assignment, variable)
assignment[variable] = value
iteration = 0
run = True
while run:
conflicts = _find_conflicts(problem, assignment)
conflict_variables = [v for v in problem.variables
if any(v in conflict[0] for conflict in conflicts)]
if conflict_variables:
variable = random.choice(conflict_variables)
value = _min_conflicts_value(problem, assignment, variable)
assignment[variable] = value
iteration += 1
if iterations_limit and iteration >= iterations_limit:
run = False
elif not _count_conflicts(problem, assignment):
run = False
return assignment | python | def min_conflicts(problem, initial_assignment=None, iterations_limit=0):
"""
Min conflicts search.
initial_assignment the initial assignment, or None to generate a random
one.
If iterations_limit is specified, the algorithm will end after that
number of iterations. Else, it will continue until if finds an assignment
that doesn't generate conflicts (a solution).
"""
assignment = {}
if initial_assignment:
assignment.update(initial_assignment)
else:
for variable in problem.variables:
value = _min_conflicts_value(problem, assignment, variable)
assignment[variable] = value
iteration = 0
run = True
while run:
conflicts = _find_conflicts(problem, assignment)
conflict_variables = [v for v in problem.variables
if any(v in conflict[0] for conflict in conflicts)]
if conflict_variables:
variable = random.choice(conflict_variables)
value = _min_conflicts_value(problem, assignment, variable)
assignment[variable] = value
iteration += 1
if iterations_limit and iteration >= iterations_limit:
run = False
elif not _count_conflicts(problem, assignment):
run = False
return assignment | [
"def",
"min_conflicts",
"(",
"problem",
",",
"initial_assignment",
"=",
"None",
",",
"iterations_limit",
"=",
"0",
")",
":",
"assignment",
"=",
"{",
"}",
"if",
"initial_assignment",
":",
"assignment",
".",
"update",
"(",
"initial_assignment",
")",
"else",
":",
"for",
"variable",
"in",
"problem",
".",
"variables",
":",
"value",
"=",
"_min_conflicts_value",
"(",
"problem",
",",
"assignment",
",",
"variable",
")",
"assignment",
"[",
"variable",
"]",
"=",
"value",
"iteration",
"=",
"0",
"run",
"=",
"True",
"while",
"run",
":",
"conflicts",
"=",
"_find_conflicts",
"(",
"problem",
",",
"assignment",
")",
"conflict_variables",
"=",
"[",
"v",
"for",
"v",
"in",
"problem",
".",
"variables",
"if",
"any",
"(",
"v",
"in",
"conflict",
"[",
"0",
"]",
"for",
"conflict",
"in",
"conflicts",
")",
"]",
"if",
"conflict_variables",
":",
"variable",
"=",
"random",
".",
"choice",
"(",
"conflict_variables",
")",
"value",
"=",
"_min_conflicts_value",
"(",
"problem",
",",
"assignment",
",",
"variable",
")",
"assignment",
"[",
"variable",
"]",
"=",
"value",
"iteration",
"+=",
"1",
"if",
"iterations_limit",
"and",
"iteration",
">=",
"iterations_limit",
":",
"run",
"=",
"False",
"elif",
"not",
"_count_conflicts",
"(",
"problem",
",",
"assignment",
")",
":",
"run",
"=",
"False",
"return",
"assignment"
] | Min conflicts search.
initial_assignment the initial assignment, or None to generate a random
one.
If iterations_limit is specified, the algorithm will end after that
number of iterations. Else, it will continue until if finds an assignment
that doesn't generate conflicts (a solution). | [
"Min",
"conflicts",
"search",
"."
] | 2836befa7e970013f62e0ee75562652aacac6f65 | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/csp.py#L166-L204 |
3,975 | simpleai-team/simpleai | simpleai/search/csp.py | convert_to_binary | def convert_to_binary(variables, domains, constraints):
"""
Returns new constraint list, all binary, using hidden variables.
You can use it as previous step when creating a problem.
"""
def wdiff(vars_):
def diff(variables, values):
hidden, other = variables
if hidden.startswith('hidden'):
idx = vars_.index(other)
return values[1] == values[0][idx]
else:
idx = vars_.index(hidden)
return values[0] == values[1][idx]
diff.no_wrap = True # so it's not wrapped to swap values
return diff
new_constraints = []
new_domains = copy(domains)
new_variables = list(variables)
last = 0
for vars_, const in constraints:
if len(vars_) == 2:
new_constraints.append((vars_, const))
continue
hidden = 'hidden%d' % last
new_variables.append(hidden)
last += 1
new_domains[hidden] = [t for t in product(*map(domains.get, vars_)) if const(vars_, t)]
for var in vars_:
new_constraints.append(((hidden, var), wdiff(vars_)))
return new_variables, new_domains, new_constraints | python | def convert_to_binary(variables, domains, constraints):
"""
Returns new constraint list, all binary, using hidden variables.
You can use it as previous step when creating a problem.
"""
def wdiff(vars_):
def diff(variables, values):
hidden, other = variables
if hidden.startswith('hidden'):
idx = vars_.index(other)
return values[1] == values[0][idx]
else:
idx = vars_.index(hidden)
return values[0] == values[1][idx]
diff.no_wrap = True # so it's not wrapped to swap values
return diff
new_constraints = []
new_domains = copy(domains)
new_variables = list(variables)
last = 0
for vars_, const in constraints:
if len(vars_) == 2:
new_constraints.append((vars_, const))
continue
hidden = 'hidden%d' % last
new_variables.append(hidden)
last += 1
new_domains[hidden] = [t for t in product(*map(domains.get, vars_)) if const(vars_, t)]
for var in vars_:
new_constraints.append(((hidden, var), wdiff(vars_)))
return new_variables, new_domains, new_constraints | [
"def",
"convert_to_binary",
"(",
"variables",
",",
"domains",
",",
"constraints",
")",
":",
"def",
"wdiff",
"(",
"vars_",
")",
":",
"def",
"diff",
"(",
"variables",
",",
"values",
")",
":",
"hidden",
",",
"other",
"=",
"variables",
"if",
"hidden",
".",
"startswith",
"(",
"'hidden'",
")",
":",
"idx",
"=",
"vars_",
".",
"index",
"(",
"other",
")",
"return",
"values",
"[",
"1",
"]",
"==",
"values",
"[",
"0",
"]",
"[",
"idx",
"]",
"else",
":",
"idx",
"=",
"vars_",
".",
"index",
"(",
"hidden",
")",
"return",
"values",
"[",
"0",
"]",
"==",
"values",
"[",
"1",
"]",
"[",
"idx",
"]",
"diff",
".",
"no_wrap",
"=",
"True",
"# so it's not wrapped to swap values",
"return",
"diff",
"new_constraints",
"=",
"[",
"]",
"new_domains",
"=",
"copy",
"(",
"domains",
")",
"new_variables",
"=",
"list",
"(",
"variables",
")",
"last",
"=",
"0",
"for",
"vars_",
",",
"const",
"in",
"constraints",
":",
"if",
"len",
"(",
"vars_",
")",
"==",
"2",
":",
"new_constraints",
".",
"append",
"(",
"(",
"vars_",
",",
"const",
")",
")",
"continue",
"hidden",
"=",
"'hidden%d'",
"%",
"last",
"new_variables",
".",
"append",
"(",
"hidden",
")",
"last",
"+=",
"1",
"new_domains",
"[",
"hidden",
"]",
"=",
"[",
"t",
"for",
"t",
"in",
"product",
"(",
"*",
"map",
"(",
"domains",
".",
"get",
",",
"vars_",
")",
")",
"if",
"const",
"(",
"vars_",
",",
"t",
")",
"]",
"for",
"var",
"in",
"vars_",
":",
"new_constraints",
".",
"append",
"(",
"(",
"(",
"hidden",
",",
"var",
")",
",",
"wdiff",
"(",
"vars_",
")",
")",
")",
"return",
"new_variables",
",",
"new_domains",
",",
"new_constraints"
] | Returns new constraint list, all binary, using hidden variables.
You can use it as previous step when creating a problem. | [
"Returns",
"new",
"constraint",
"list",
"all",
"binary",
"using",
"hidden",
"variables",
"."
] | 2836befa7e970013f62e0ee75562652aacac6f65 | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/csp.py#L207-L242 |
3,976 | simpleai-team/simpleai | simpleai/machine_learning/reinforcement_learning.py | boltzmann_exploration | def boltzmann_exploration(actions, utilities, temperature, action_counter):
'''returns an action with a probability depending on utilities and temperature'''
utilities = [utilities[x] for x in actions]
temperature = max(temperature, 0.01)
_max = max(utilities)
_min = min(utilities)
if _max == _min:
return random.choice(actions)
utilities = [math.exp(((u - _min) / (_max - _min)) / temperature) for u in utilities]
probs = [u / sum(utilities) for u in utilities]
i = 0
tot = probs[i]
r = random.random()
while i < len(actions) and r >= tot:
i += 1
tot += probs[i]
return actions[i] | python | def boltzmann_exploration(actions, utilities, temperature, action_counter):
'''returns an action with a probability depending on utilities and temperature'''
utilities = [utilities[x] for x in actions]
temperature = max(temperature, 0.01)
_max = max(utilities)
_min = min(utilities)
if _max == _min:
return random.choice(actions)
utilities = [math.exp(((u - _min) / (_max - _min)) / temperature) for u in utilities]
probs = [u / sum(utilities) for u in utilities]
i = 0
tot = probs[i]
r = random.random()
while i < len(actions) and r >= tot:
i += 1
tot += probs[i]
return actions[i] | [
"def",
"boltzmann_exploration",
"(",
"actions",
",",
"utilities",
",",
"temperature",
",",
"action_counter",
")",
":",
"utilities",
"=",
"[",
"utilities",
"[",
"x",
"]",
"for",
"x",
"in",
"actions",
"]",
"temperature",
"=",
"max",
"(",
"temperature",
",",
"0.01",
")",
"_max",
"=",
"max",
"(",
"utilities",
")",
"_min",
"=",
"min",
"(",
"utilities",
")",
"if",
"_max",
"==",
"_min",
":",
"return",
"random",
".",
"choice",
"(",
"actions",
")",
"utilities",
"=",
"[",
"math",
".",
"exp",
"(",
"(",
"(",
"u",
"-",
"_min",
")",
"/",
"(",
"_max",
"-",
"_min",
")",
")",
"/",
"temperature",
")",
"for",
"u",
"in",
"utilities",
"]",
"probs",
"=",
"[",
"u",
"/",
"sum",
"(",
"utilities",
")",
"for",
"u",
"in",
"utilities",
"]",
"i",
"=",
"0",
"tot",
"=",
"probs",
"[",
"i",
"]",
"r",
"=",
"random",
".",
"random",
"(",
")",
"while",
"i",
"<",
"len",
"(",
"actions",
")",
"and",
"r",
">=",
"tot",
":",
"i",
"+=",
"1",
"tot",
"+=",
"probs",
"[",
"i",
"]",
"return",
"actions",
"[",
"i",
"]"
] | returns an action with a probability depending on utilities and temperature | [
"returns",
"an",
"action",
"with",
"a",
"probability",
"depending",
"on",
"utilities",
"and",
"temperature"
] | 2836befa7e970013f62e0ee75562652aacac6f65 | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/machine_learning/reinforcement_learning.py#L28-L45 |
3,977 | simpleai-team/simpleai | samples/search/sudoku.py | mkconstraints | def mkconstraints():
"""
Make constraint list for binary constraint problem.
"""
constraints = []
for j in range(1, 10):
vars = ["%s%d" % (i, j) for i in uppercase[:9]]
constraints.extend((c, const_different) for c in combinations(vars, 2))
for i in uppercase[:9]:
vars = ["%s%d" % (i, j) for j in range(1, 10)]
constraints.extend((c, const_different) for c in combinations(vars, 2))
for b0 in ['ABC', 'DEF', 'GHI']:
for b1 in [[1, 2, 3], [4, 5, 6], [7, 8, 9]]:
vars = ["%s%d" % (i, j) for i in b0 for j in b1]
l = list((c, const_different) for c in combinations(vars, 2))
constraints.extend(l)
return constraints | python | def mkconstraints():
"""
Make constraint list for binary constraint problem.
"""
constraints = []
for j in range(1, 10):
vars = ["%s%d" % (i, j) for i in uppercase[:9]]
constraints.extend((c, const_different) for c in combinations(vars, 2))
for i in uppercase[:9]:
vars = ["%s%d" % (i, j) for j in range(1, 10)]
constraints.extend((c, const_different) for c in combinations(vars, 2))
for b0 in ['ABC', 'DEF', 'GHI']:
for b1 in [[1, 2, 3], [4, 5, 6], [7, 8, 9]]:
vars = ["%s%d" % (i, j) for i in b0 for j in b1]
l = list((c, const_different) for c in combinations(vars, 2))
constraints.extend(l)
return constraints | [
"def",
"mkconstraints",
"(",
")",
":",
"constraints",
"=",
"[",
"]",
"for",
"j",
"in",
"range",
"(",
"1",
",",
"10",
")",
":",
"vars",
"=",
"[",
"\"%s%d\"",
"%",
"(",
"i",
",",
"j",
")",
"for",
"i",
"in",
"uppercase",
"[",
":",
"9",
"]",
"]",
"constraints",
".",
"extend",
"(",
"(",
"c",
",",
"const_different",
")",
"for",
"c",
"in",
"combinations",
"(",
"vars",
",",
"2",
")",
")",
"for",
"i",
"in",
"uppercase",
"[",
":",
"9",
"]",
":",
"vars",
"=",
"[",
"\"%s%d\"",
"%",
"(",
"i",
",",
"j",
")",
"for",
"j",
"in",
"range",
"(",
"1",
",",
"10",
")",
"]",
"constraints",
".",
"extend",
"(",
"(",
"c",
",",
"const_different",
")",
"for",
"c",
"in",
"combinations",
"(",
"vars",
",",
"2",
")",
")",
"for",
"b0",
"in",
"[",
"'ABC'",
",",
"'DEF'",
",",
"'GHI'",
"]",
":",
"for",
"b1",
"in",
"[",
"[",
"1",
",",
"2",
",",
"3",
"]",
",",
"[",
"4",
",",
"5",
",",
"6",
"]",
",",
"[",
"7",
",",
"8",
",",
"9",
"]",
"]",
":",
"vars",
"=",
"[",
"\"%s%d\"",
"%",
"(",
"i",
",",
"j",
")",
"for",
"i",
"in",
"b0",
"for",
"j",
"in",
"b1",
"]",
"l",
"=",
"list",
"(",
"(",
"c",
",",
"const_different",
")",
"for",
"c",
"in",
"combinations",
"(",
"vars",
",",
"2",
")",
")",
"constraints",
".",
"extend",
"(",
"l",
")",
"return",
"constraints"
] | Make constraint list for binary constraint problem. | [
"Make",
"constraint",
"list",
"for",
"binary",
"constraint",
"problem",
"."
] | 2836befa7e970013f62e0ee75562652aacac6f65 | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/samples/search/sudoku.py#L57-L77 |
3,978 | simpleai-team/simpleai | simpleai/machine_learning/evaluation.py | precision | def precision(classifier, testset):
"""
Runs the classifier for each example in `testset`
and verifies that the classification is correct
using the `target`.
Returns a number between 0.0 and 1.0 with the
precision of classification for this test set.
"""
hit = 0
total = 0
for example in testset:
if classifier.classify(example)[0] == classifier.target(example):
hit += 1
total += 1
if total == 0:
raise ValueError("Empty testset!")
return hit / float(total) | python | def precision(classifier, testset):
"""
Runs the classifier for each example in `testset`
and verifies that the classification is correct
using the `target`.
Returns a number between 0.0 and 1.0 with the
precision of classification for this test set.
"""
hit = 0
total = 0
for example in testset:
if classifier.classify(example)[0] == classifier.target(example):
hit += 1
total += 1
if total == 0:
raise ValueError("Empty testset!")
return hit / float(total) | [
"def",
"precision",
"(",
"classifier",
",",
"testset",
")",
":",
"hit",
"=",
"0",
"total",
"=",
"0",
"for",
"example",
"in",
"testset",
":",
"if",
"classifier",
".",
"classify",
"(",
"example",
")",
"[",
"0",
"]",
"==",
"classifier",
".",
"target",
"(",
"example",
")",
":",
"hit",
"+=",
"1",
"total",
"+=",
"1",
"if",
"total",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"\"Empty testset!\"",
")",
"return",
"hit",
"/",
"float",
"(",
"total",
")"
] | Runs the classifier for each example in `testset`
and verifies that the classification is correct
using the `target`.
Returns a number between 0.0 and 1.0 with the
precision of classification for this test set. | [
"Runs",
"the",
"classifier",
"for",
"each",
"example",
"in",
"testset",
"and",
"verifies",
"that",
"the",
"classification",
"is",
"correct",
"using",
"the",
"target",
"."
] | 2836befa7e970013f62e0ee75562652aacac6f65 | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/machine_learning/evaluation.py#L12-L30 |
3,979 | simpleai-team/simpleai | simpleai/machine_learning/evaluation.py | kfold | def kfold(dataset, problem, method, k=10):
"""
Does a k-fold on `dataset` with `method`.
This is, it randomly creates k-partitions of the dataset, and k-times
trains the method with k-1 parts and runs it with the partition left.
After all this, returns the overall success ratio.
"""
if k <= 1:
raise ValueError("k argument must be at least 2")
dataset = list(dataset)
random.shuffle(dataset)
trials = 0
positive = 0
for i in range(k):
train = [x for j, x in enumerate(dataset) if j % k != i]
test = [x for j, x in enumerate(dataset) if j % k == i]
classifier = method(train, problem)
for data in test:
trials += 1
result = classifier.classify(data)
if result is not None and result[0] == problem.target(data):
positive += 1
return float(positive) / float(trials) | python | def kfold(dataset, problem, method, k=10):
"""
Does a k-fold on `dataset` with `method`.
This is, it randomly creates k-partitions of the dataset, and k-times
trains the method with k-1 parts and runs it with the partition left.
After all this, returns the overall success ratio.
"""
if k <= 1:
raise ValueError("k argument must be at least 2")
dataset = list(dataset)
random.shuffle(dataset)
trials = 0
positive = 0
for i in range(k):
train = [x for j, x in enumerate(dataset) if j % k != i]
test = [x for j, x in enumerate(dataset) if j % k == i]
classifier = method(train, problem)
for data in test:
trials += 1
result = classifier.classify(data)
if result is not None and result[0] == problem.target(data):
positive += 1
return float(positive) / float(trials) | [
"def",
"kfold",
"(",
"dataset",
",",
"problem",
",",
"method",
",",
"k",
"=",
"10",
")",
":",
"if",
"k",
"<=",
"1",
":",
"raise",
"ValueError",
"(",
"\"k argument must be at least 2\"",
")",
"dataset",
"=",
"list",
"(",
"dataset",
")",
"random",
".",
"shuffle",
"(",
"dataset",
")",
"trials",
"=",
"0",
"positive",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"k",
")",
":",
"train",
"=",
"[",
"x",
"for",
"j",
",",
"x",
"in",
"enumerate",
"(",
"dataset",
")",
"if",
"j",
"%",
"k",
"!=",
"i",
"]",
"test",
"=",
"[",
"x",
"for",
"j",
",",
"x",
"in",
"enumerate",
"(",
"dataset",
")",
"if",
"j",
"%",
"k",
"==",
"i",
"]",
"classifier",
"=",
"method",
"(",
"train",
",",
"problem",
")",
"for",
"data",
"in",
"test",
":",
"trials",
"+=",
"1",
"result",
"=",
"classifier",
".",
"classify",
"(",
"data",
")",
"if",
"result",
"is",
"not",
"None",
"and",
"result",
"[",
"0",
"]",
"==",
"problem",
".",
"target",
"(",
"data",
")",
":",
"positive",
"+=",
"1",
"return",
"float",
"(",
"positive",
")",
"/",
"float",
"(",
"trials",
")"
] | Does a k-fold on `dataset` with `method`.
This is, it randomly creates k-partitions of the dataset, and k-times
trains the method with k-1 parts and runs it with the partition left.
After all this, returns the overall success ratio. | [
"Does",
"a",
"k",
"-",
"fold",
"on",
"dataset",
"with",
"method",
".",
"This",
"is",
"it",
"randomly",
"creates",
"k",
"-",
"partitions",
"of",
"the",
"dataset",
"and",
"k",
"-",
"times",
"trains",
"the",
"method",
"with",
"k",
"-",
"1",
"parts",
"and",
"runs",
"it",
"with",
"the",
"partition",
"left",
".",
"After",
"all",
"this",
"returns",
"the",
"overall",
"success",
"ratio",
"."
] | 2836befa7e970013f62e0ee75562652aacac6f65 | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/machine_learning/evaluation.py#L33-L59 |
3,980 | simpleai-team/simpleai | samples/machine_learning/tic_tac_toe.py | TicTacToeProblem.actions | def actions(self, state):
'actions are index where we can make a move'
actions = []
for index, char in enumerate(state):
if char == '_':
actions.append(index)
return actions | python | def actions(self, state):
'actions are index where we can make a move'
actions = []
for index, char in enumerate(state):
if char == '_':
actions.append(index)
return actions | [
"def",
"actions",
"(",
"self",
",",
"state",
")",
":",
"actions",
"=",
"[",
"]",
"for",
"index",
",",
"char",
"in",
"enumerate",
"(",
"state",
")",
":",
"if",
"char",
"==",
"'_'",
":",
"actions",
".",
"append",
"(",
"index",
")",
"return",
"actions"
] | actions are index where we can make a move | [
"actions",
"are",
"index",
"where",
"we",
"can",
"make",
"a",
"move"
] | 2836befa7e970013f62e0ee75562652aacac6f65 | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/samples/machine_learning/tic_tac_toe.py#L14-L20 |
3,981 | simpleai-team/simpleai | samples/search/missioners.py | MissionersProblem.actions | def actions(self, s):
'''Possible actions from a state.'''
# we try to generate every possible state and then filter those
# states that are valid
return [a for a in self._actions if self._is_valid(self.result(s, a))] | python | def actions(self, s):
'''Possible actions from a state.'''
# we try to generate every possible state and then filter those
# states that are valid
return [a for a in self._actions if self._is_valid(self.result(s, a))] | [
"def",
"actions",
"(",
"self",
",",
"s",
")",
":",
"# we try to generate every possible state and then filter those",
"# states that are valid",
"return",
"[",
"a",
"for",
"a",
"in",
"self",
".",
"_actions",
"if",
"self",
".",
"_is_valid",
"(",
"self",
".",
"result",
"(",
"s",
",",
"a",
")",
")",
"]"
] | Possible actions from a state. | [
"Possible",
"actions",
"from",
"a",
"state",
"."
] | 2836befa7e970013f62e0ee75562652aacac6f65 | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/samples/search/missioners.py#L21-L25 |
3,982 | simpleai-team/simpleai | samples/search/missioners.py | MissionersProblem._is_valid | def _is_valid(self, s):
'''Check if a state is valid.'''
# valid states: no more cannibals than missioners on each side,
# and numbers between 0 and 3
return ((s[0] >= s[1] or s[0] == 0)) and \
((3 - s[0]) >= (3 - s[1]) or s[0] == 3) and \
(0 <= s[0] <= 3) and \
(0 <= s[1] <= 3) | python | def _is_valid(self, s):
'''Check if a state is valid.'''
# valid states: no more cannibals than missioners on each side,
# and numbers between 0 and 3
return ((s[0] >= s[1] or s[0] == 0)) and \
((3 - s[0]) >= (3 - s[1]) or s[0] == 3) and \
(0 <= s[0] <= 3) and \
(0 <= s[1] <= 3) | [
"def",
"_is_valid",
"(",
"self",
",",
"s",
")",
":",
"# valid states: no more cannibals than missioners on each side,",
"# and numbers between 0 and 3",
"return",
"(",
"(",
"s",
"[",
"0",
"]",
">=",
"s",
"[",
"1",
"]",
"or",
"s",
"[",
"0",
"]",
"==",
"0",
")",
")",
"and",
"(",
"(",
"3",
"-",
"s",
"[",
"0",
"]",
")",
">=",
"(",
"3",
"-",
"s",
"[",
"1",
"]",
")",
"or",
"s",
"[",
"0",
"]",
"==",
"3",
")",
"and",
"(",
"0",
"<=",
"s",
"[",
"0",
"]",
"<=",
"3",
")",
"and",
"(",
"0",
"<=",
"s",
"[",
"1",
"]",
"<=",
"3",
")"
] | Check if a state is valid. | [
"Check",
"if",
"a",
"state",
"is",
"valid",
"."
] | 2836befa7e970013f62e0ee75562652aacac6f65 | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/samples/search/missioners.py#L27-L34 |
3,983 | simpleai-team/simpleai | samples/search/missioners.py | MissionersProblem.result | def result(self, s, a):
'''Result of applying an action to a state.'''
# result: boat on opposite side, and numbers of missioners and
# cannibals updated according to the move
if s[2] == 0:
return (s[0] - a[1][0], s[1] - a[1][1], 1)
else:
return (s[0] + a[1][0], s[1] + a[1][1], 0) | python | def result(self, s, a):
'''Result of applying an action to a state.'''
# result: boat on opposite side, and numbers of missioners and
# cannibals updated according to the move
if s[2] == 0:
return (s[0] - a[1][0], s[1] - a[1][1], 1)
else:
return (s[0] + a[1][0], s[1] + a[1][1], 0) | [
"def",
"result",
"(",
"self",
",",
"s",
",",
"a",
")",
":",
"# result: boat on opposite side, and numbers of missioners and",
"# cannibals updated according to the move",
"if",
"s",
"[",
"2",
"]",
"==",
"0",
":",
"return",
"(",
"s",
"[",
"0",
"]",
"-",
"a",
"[",
"1",
"]",
"[",
"0",
"]",
",",
"s",
"[",
"1",
"]",
"-",
"a",
"[",
"1",
"]",
"[",
"1",
"]",
",",
"1",
")",
"else",
":",
"return",
"(",
"s",
"[",
"0",
"]",
"+",
"a",
"[",
"1",
"]",
"[",
"0",
"]",
",",
"s",
"[",
"1",
"]",
"+",
"a",
"[",
"1",
"]",
"[",
"1",
"]",
",",
"0",
")"
] | Result of applying an action to a state. | [
"Result",
"of",
"applying",
"an",
"action",
"to",
"a",
"state",
"."
] | 2836befa7e970013f62e0ee75562652aacac6f65 | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/samples/search/missioners.py#L36-L43 |
3,984 | simpleai-team/simpleai | simpleai/search/arc.py | arc_consistency_3 | def arc_consistency_3(domains, constraints):
"""
Makes a CSP problem arc consistent.
Ignores any constraint that is not binary.
"""
arcs = list(all_arcs(constraints))
pending_arcs = set(arcs)
while pending_arcs:
x, y = pending_arcs.pop()
if revise(domains, (x, y), constraints):
if len(domains[x]) == 0:
return False
pending_arcs = pending_arcs.union((x2, y2) for x2, y2 in arcs
if y2 == x)
return True | python | def arc_consistency_3(domains, constraints):
"""
Makes a CSP problem arc consistent.
Ignores any constraint that is not binary.
"""
arcs = list(all_arcs(constraints))
pending_arcs = set(arcs)
while pending_arcs:
x, y = pending_arcs.pop()
if revise(domains, (x, y), constraints):
if len(domains[x]) == 0:
return False
pending_arcs = pending_arcs.union((x2, y2) for x2, y2 in arcs
if y2 == x)
return True | [
"def",
"arc_consistency_3",
"(",
"domains",
",",
"constraints",
")",
":",
"arcs",
"=",
"list",
"(",
"all_arcs",
"(",
"constraints",
")",
")",
"pending_arcs",
"=",
"set",
"(",
"arcs",
")",
"while",
"pending_arcs",
":",
"x",
",",
"y",
"=",
"pending_arcs",
".",
"pop",
"(",
")",
"if",
"revise",
"(",
"domains",
",",
"(",
"x",
",",
"y",
")",
",",
"constraints",
")",
":",
"if",
"len",
"(",
"domains",
"[",
"x",
"]",
")",
"==",
"0",
":",
"return",
"False",
"pending_arcs",
"=",
"pending_arcs",
".",
"union",
"(",
"(",
"x2",
",",
"y2",
")",
"for",
"x2",
",",
"y2",
"in",
"arcs",
"if",
"y2",
"==",
"x",
")",
"return",
"True"
] | Makes a CSP problem arc consistent.
Ignores any constraint that is not binary. | [
"Makes",
"a",
"CSP",
"problem",
"arc",
"consistent",
"."
] | 2836befa7e970013f62e0ee75562652aacac6f65 | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/arc.py#L58-L74 |
3,985 | simpleai-team/simpleai | simpleai/search/models.py | SearchNode.expand | def expand(self, local_search=False):
'''Create successors.'''
new_nodes = []
for action in self.problem.actions(self.state):
new_state = self.problem.result(self.state, action)
cost = self.problem.cost(self.state,
action,
new_state)
nodefactory = self.__class__
new_nodes.append(nodefactory(state=new_state,
parent=None if local_search else self,
problem=self.problem,
action=action,
cost=self.cost + cost,
depth=self.depth + 1))
return new_nodes | python | def expand(self, local_search=False):
'''Create successors.'''
new_nodes = []
for action in self.problem.actions(self.state):
new_state = self.problem.result(self.state, action)
cost = self.problem.cost(self.state,
action,
new_state)
nodefactory = self.__class__
new_nodes.append(nodefactory(state=new_state,
parent=None if local_search else self,
problem=self.problem,
action=action,
cost=self.cost + cost,
depth=self.depth + 1))
return new_nodes | [
"def",
"expand",
"(",
"self",
",",
"local_search",
"=",
"False",
")",
":",
"new_nodes",
"=",
"[",
"]",
"for",
"action",
"in",
"self",
".",
"problem",
".",
"actions",
"(",
"self",
".",
"state",
")",
":",
"new_state",
"=",
"self",
".",
"problem",
".",
"result",
"(",
"self",
".",
"state",
",",
"action",
")",
"cost",
"=",
"self",
".",
"problem",
".",
"cost",
"(",
"self",
".",
"state",
",",
"action",
",",
"new_state",
")",
"nodefactory",
"=",
"self",
".",
"__class__",
"new_nodes",
".",
"append",
"(",
"nodefactory",
"(",
"state",
"=",
"new_state",
",",
"parent",
"=",
"None",
"if",
"local_search",
"else",
"self",
",",
"problem",
"=",
"self",
".",
"problem",
",",
"action",
"=",
"action",
",",
"cost",
"=",
"self",
".",
"cost",
"+",
"cost",
",",
"depth",
"=",
"self",
".",
"depth",
"+",
"1",
")",
")",
"return",
"new_nodes"
] | Create successors. | [
"Create",
"successors",
"."
] | 2836befa7e970013f62e0ee75562652aacac6f65 | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/models.py#L102-L117 |
3,986 | simpleai-team/simpleai | simpleai/environments.py | Environment.step | def step(self, viewer=None):
"This method evolves one step in time"
if not self.is_completed(self.state):
for agent in self.agents:
action = agent.program(self.percept(agent, self.state))
next_state = self.do_action(self.state, action, agent)
if viewer:
viewer.event(self.state, action, next_state, agent)
self.state = next_state
if self.is_completed(self.state):
return | python | def step(self, viewer=None):
"This method evolves one step in time"
if not self.is_completed(self.state):
for agent in self.agents:
action = agent.program(self.percept(agent, self.state))
next_state = self.do_action(self.state, action, agent)
if viewer:
viewer.event(self.state, action, next_state, agent)
self.state = next_state
if self.is_completed(self.state):
return | [
"def",
"step",
"(",
"self",
",",
"viewer",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"is_completed",
"(",
"self",
".",
"state",
")",
":",
"for",
"agent",
"in",
"self",
".",
"agents",
":",
"action",
"=",
"agent",
".",
"program",
"(",
"self",
".",
"percept",
"(",
"agent",
",",
"self",
".",
"state",
")",
")",
"next_state",
"=",
"self",
".",
"do_action",
"(",
"self",
".",
"state",
",",
"action",
",",
"agent",
")",
"if",
"viewer",
":",
"viewer",
".",
"event",
"(",
"self",
".",
"state",
",",
"action",
",",
"next_state",
",",
"agent",
")",
"self",
".",
"state",
"=",
"next_state",
"if",
"self",
".",
"is_completed",
"(",
"self",
".",
"state",
")",
":",
"return"
] | This method evolves one step in time | [
"This",
"method",
"evolves",
"one",
"step",
"in",
"time"
] | 2836befa7e970013f62e0ee75562652aacac6f65 | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/environments.py#L18-L28 |
3,987 | simpleai-team/simpleai | simpleai/search/traditional.py | breadth_first | def breadth_first(problem, graph_search=False, viewer=None):
'''
Breadth first search.
If graph_search=True, will avoid exploring repeated states.
Requires: SearchProblem.actions, SearchProblem.result, and
SearchProblem.is_goal.
'''
return _search(problem,
FifoList(),
graph_search=graph_search,
viewer=viewer) | python | def breadth_first(problem, graph_search=False, viewer=None):
'''
Breadth first search.
If graph_search=True, will avoid exploring repeated states.
Requires: SearchProblem.actions, SearchProblem.result, and
SearchProblem.is_goal.
'''
return _search(problem,
FifoList(),
graph_search=graph_search,
viewer=viewer) | [
"def",
"breadth_first",
"(",
"problem",
",",
"graph_search",
"=",
"False",
",",
"viewer",
"=",
"None",
")",
":",
"return",
"_search",
"(",
"problem",
",",
"FifoList",
"(",
")",
",",
"graph_search",
"=",
"graph_search",
",",
"viewer",
"=",
"viewer",
")"
] | Breadth first search.
If graph_search=True, will avoid exploring repeated states.
Requires: SearchProblem.actions, SearchProblem.result, and
SearchProblem.is_goal. | [
"Breadth",
"first",
"search",
"."
] | 2836befa7e970013f62e0ee75562652aacac6f65 | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/traditional.py#L8-L19 |
3,988 | simpleai-team/simpleai | simpleai/search/traditional.py | depth_first | def depth_first(problem, graph_search=False, viewer=None):
'''
Depth first search.
If graph_search=True, will avoid exploring repeated states.
Requires: SearchProblem.actions, SearchProblem.result, and
SearchProblem.is_goal.
'''
return _search(problem,
LifoList(),
graph_search=graph_search,
viewer=viewer) | python | def depth_first(problem, graph_search=False, viewer=None):
'''
Depth first search.
If graph_search=True, will avoid exploring repeated states.
Requires: SearchProblem.actions, SearchProblem.result, and
SearchProblem.is_goal.
'''
return _search(problem,
LifoList(),
graph_search=graph_search,
viewer=viewer) | [
"def",
"depth_first",
"(",
"problem",
",",
"graph_search",
"=",
"False",
",",
"viewer",
"=",
"None",
")",
":",
"return",
"_search",
"(",
"problem",
",",
"LifoList",
"(",
")",
",",
"graph_search",
"=",
"graph_search",
",",
"viewer",
"=",
"viewer",
")"
] | Depth first search.
If graph_search=True, will avoid exploring repeated states.
Requires: SearchProblem.actions, SearchProblem.result, and
SearchProblem.is_goal. | [
"Depth",
"first",
"search",
"."
] | 2836befa7e970013f62e0ee75562652aacac6f65 | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/traditional.py#L22-L33 |
3,989 | simpleai-team/simpleai | simpleai/search/traditional.py | limited_depth_first | def limited_depth_first(problem, depth_limit, graph_search=False, viewer=None):
'''
Limited depth first search.
Depth_limit is the maximum depth allowed, being depth 0 the initial state.
If graph_search=True, will avoid exploring repeated states.
Requires: SearchProblem.actions, SearchProblem.result, and
SearchProblem.is_goal.
'''
return _search(problem,
LifoList(),
graph_search=graph_search,
depth_limit=depth_limit,
viewer=viewer) | python | def limited_depth_first(problem, depth_limit, graph_search=False, viewer=None):
'''
Limited depth first search.
Depth_limit is the maximum depth allowed, being depth 0 the initial state.
If graph_search=True, will avoid exploring repeated states.
Requires: SearchProblem.actions, SearchProblem.result, and
SearchProblem.is_goal.
'''
return _search(problem,
LifoList(),
graph_search=graph_search,
depth_limit=depth_limit,
viewer=viewer) | [
"def",
"limited_depth_first",
"(",
"problem",
",",
"depth_limit",
",",
"graph_search",
"=",
"False",
",",
"viewer",
"=",
"None",
")",
":",
"return",
"_search",
"(",
"problem",
",",
"LifoList",
"(",
")",
",",
"graph_search",
"=",
"graph_search",
",",
"depth_limit",
"=",
"depth_limit",
",",
"viewer",
"=",
"viewer",
")"
] | Limited depth first search.
Depth_limit is the maximum depth allowed, being depth 0 the initial state.
If graph_search=True, will avoid exploring repeated states.
Requires: SearchProblem.actions, SearchProblem.result, and
SearchProblem.is_goal. | [
"Limited",
"depth",
"first",
"search",
"."
] | 2836befa7e970013f62e0ee75562652aacac6f65 | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/traditional.py#L36-L49 |
3,990 | simpleai-team/simpleai | simpleai/search/traditional.py | iterative_limited_depth_first | def iterative_limited_depth_first(problem, graph_search=False, viewer=None):
'''
Iterative limited depth first search.
If graph_search=True, will avoid exploring repeated states.
Requires: SearchProblem.actions, SearchProblem.result, and
SearchProblem.is_goal.
'''
solution = None
limit = 0
while not solution:
solution = limited_depth_first(problem,
depth_limit=limit,
graph_search=graph_search,
viewer=viewer)
limit += 1
if viewer:
viewer.event('no_more_runs', solution, 'returned after %i runs' % limit)
return solution | python | def iterative_limited_depth_first(problem, graph_search=False, viewer=None):
'''
Iterative limited depth first search.
If graph_search=True, will avoid exploring repeated states.
Requires: SearchProblem.actions, SearchProblem.result, and
SearchProblem.is_goal.
'''
solution = None
limit = 0
while not solution:
solution = limited_depth_first(problem,
depth_limit=limit,
graph_search=graph_search,
viewer=viewer)
limit += 1
if viewer:
viewer.event('no_more_runs', solution, 'returned after %i runs' % limit)
return solution | [
"def",
"iterative_limited_depth_first",
"(",
"problem",
",",
"graph_search",
"=",
"False",
",",
"viewer",
"=",
"None",
")",
":",
"solution",
"=",
"None",
"limit",
"=",
"0",
"while",
"not",
"solution",
":",
"solution",
"=",
"limited_depth_first",
"(",
"problem",
",",
"depth_limit",
"=",
"limit",
",",
"graph_search",
"=",
"graph_search",
",",
"viewer",
"=",
"viewer",
")",
"limit",
"+=",
"1",
"if",
"viewer",
":",
"viewer",
".",
"event",
"(",
"'no_more_runs'",
",",
"solution",
",",
"'returned after %i runs'",
"%",
"limit",
")",
"return",
"solution"
] | Iterative limited depth first search.
If graph_search=True, will avoid exploring repeated states.
Requires: SearchProblem.actions, SearchProblem.result, and
SearchProblem.is_goal. | [
"Iterative",
"limited",
"depth",
"first",
"search",
"."
] | 2836befa7e970013f62e0ee75562652aacac6f65 | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/traditional.py#L52-L73 |
3,991 | simpleai-team/simpleai | simpleai/search/traditional.py | uniform_cost | def uniform_cost(problem, graph_search=False, viewer=None):
'''
Uniform cost search.
If graph_search=True, will avoid exploring repeated states.
Requires: SearchProblem.actions, SearchProblem.result,
SearchProblem.is_goal, and SearchProblem.cost.
'''
return _search(problem,
BoundedPriorityQueue(),
graph_search=graph_search,
node_factory=SearchNodeCostOrdered,
graph_replace_when_better=True,
viewer=viewer) | python | def uniform_cost(problem, graph_search=False, viewer=None):
'''
Uniform cost search.
If graph_search=True, will avoid exploring repeated states.
Requires: SearchProblem.actions, SearchProblem.result,
SearchProblem.is_goal, and SearchProblem.cost.
'''
return _search(problem,
BoundedPriorityQueue(),
graph_search=graph_search,
node_factory=SearchNodeCostOrdered,
graph_replace_when_better=True,
viewer=viewer) | [
"def",
"uniform_cost",
"(",
"problem",
",",
"graph_search",
"=",
"False",
",",
"viewer",
"=",
"None",
")",
":",
"return",
"_search",
"(",
"problem",
",",
"BoundedPriorityQueue",
"(",
")",
",",
"graph_search",
"=",
"graph_search",
",",
"node_factory",
"=",
"SearchNodeCostOrdered",
",",
"graph_replace_when_better",
"=",
"True",
",",
"viewer",
"=",
"viewer",
")"
] | Uniform cost search.
If graph_search=True, will avoid exploring repeated states.
Requires: SearchProblem.actions, SearchProblem.result,
SearchProblem.is_goal, and SearchProblem.cost. | [
"Uniform",
"cost",
"search",
"."
] | 2836befa7e970013f62e0ee75562652aacac6f65 | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/traditional.py#L76-L89 |
3,992 | simpleai-team/simpleai | simpleai/search/traditional.py | greedy | def greedy(problem, graph_search=False, viewer=None):
'''
Greedy search.
If graph_search=True, will avoid exploring repeated states.
Requires: SearchProblem.actions, SearchProblem.result,
SearchProblem.is_goal, SearchProblem.cost, and SearchProblem.heuristic.
'''
return _search(problem,
BoundedPriorityQueue(),
graph_search=graph_search,
node_factory=SearchNodeHeuristicOrdered,
graph_replace_when_better=True,
viewer=viewer) | python | def greedy(problem, graph_search=False, viewer=None):
'''
Greedy search.
If graph_search=True, will avoid exploring repeated states.
Requires: SearchProblem.actions, SearchProblem.result,
SearchProblem.is_goal, SearchProblem.cost, and SearchProblem.heuristic.
'''
return _search(problem,
BoundedPriorityQueue(),
graph_search=graph_search,
node_factory=SearchNodeHeuristicOrdered,
graph_replace_when_better=True,
viewer=viewer) | [
"def",
"greedy",
"(",
"problem",
",",
"graph_search",
"=",
"False",
",",
"viewer",
"=",
"None",
")",
":",
"return",
"_search",
"(",
"problem",
",",
"BoundedPriorityQueue",
"(",
")",
",",
"graph_search",
"=",
"graph_search",
",",
"node_factory",
"=",
"SearchNodeHeuristicOrdered",
",",
"graph_replace_when_better",
"=",
"True",
",",
"viewer",
"=",
"viewer",
")"
] | Greedy search.
If graph_search=True, will avoid exploring repeated states.
Requires: SearchProblem.actions, SearchProblem.result,
SearchProblem.is_goal, SearchProblem.cost, and SearchProblem.heuristic. | [
"Greedy",
"search",
"."
] | 2836befa7e970013f62e0ee75562652aacac6f65 | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/traditional.py#L92-L105 |
3,993 | simpleai-team/simpleai | simpleai/search/traditional.py | _search | def _search(problem, fringe, graph_search=False, depth_limit=None,
node_factory=SearchNode, graph_replace_when_better=False,
viewer=None):
'''
Basic search algorithm, base of all the other search algorithms.
'''
if viewer:
viewer.event('started')
memory = set()
initial_node = node_factory(state=problem.initial_state,
problem=problem)
fringe.append(initial_node)
while fringe:
if viewer:
viewer.event('new_iteration', fringe.sorted())
node = fringe.pop()
if problem.is_goal(node.state):
if viewer:
viewer.event('chosen_node', node, True)
viewer.event('finished', fringe.sorted(), node, 'goal found')
return node
else:
if viewer:
viewer.event('chosen_node', node, False)
memory.add(node.state)
if depth_limit is None or node.depth < depth_limit:
expanded = node.expand()
if viewer:
viewer.event('expanded', [node], [expanded])
for n in expanded:
if graph_search:
others = [x for x in fringe if x.state == n.state]
assert len(others) in (0, 1)
if n.state not in memory and len(others) == 0:
fringe.append(n)
elif graph_replace_when_better and len(others) > 0 and n < others[0]:
fringe.remove(others[0])
fringe.append(n)
else:
fringe.append(n)
if viewer:
viewer.event('finished', fringe.sorted(), None, 'goal not found') | python | def _search(problem, fringe, graph_search=False, depth_limit=None,
node_factory=SearchNode, graph_replace_when_better=False,
viewer=None):
'''
Basic search algorithm, base of all the other search algorithms.
'''
if viewer:
viewer.event('started')
memory = set()
initial_node = node_factory(state=problem.initial_state,
problem=problem)
fringe.append(initial_node)
while fringe:
if viewer:
viewer.event('new_iteration', fringe.sorted())
node = fringe.pop()
if problem.is_goal(node.state):
if viewer:
viewer.event('chosen_node', node, True)
viewer.event('finished', fringe.sorted(), node, 'goal found')
return node
else:
if viewer:
viewer.event('chosen_node', node, False)
memory.add(node.state)
if depth_limit is None or node.depth < depth_limit:
expanded = node.expand()
if viewer:
viewer.event('expanded', [node], [expanded])
for n in expanded:
if graph_search:
others = [x for x in fringe if x.state == n.state]
assert len(others) in (0, 1)
if n.state not in memory and len(others) == 0:
fringe.append(n)
elif graph_replace_when_better and len(others) > 0 and n < others[0]:
fringe.remove(others[0])
fringe.append(n)
else:
fringe.append(n)
if viewer:
viewer.event('finished', fringe.sorted(), None, 'goal not found') | [
"def",
"_search",
"(",
"problem",
",",
"fringe",
",",
"graph_search",
"=",
"False",
",",
"depth_limit",
"=",
"None",
",",
"node_factory",
"=",
"SearchNode",
",",
"graph_replace_when_better",
"=",
"False",
",",
"viewer",
"=",
"None",
")",
":",
"if",
"viewer",
":",
"viewer",
".",
"event",
"(",
"'started'",
")",
"memory",
"=",
"set",
"(",
")",
"initial_node",
"=",
"node_factory",
"(",
"state",
"=",
"problem",
".",
"initial_state",
",",
"problem",
"=",
"problem",
")",
"fringe",
".",
"append",
"(",
"initial_node",
")",
"while",
"fringe",
":",
"if",
"viewer",
":",
"viewer",
".",
"event",
"(",
"'new_iteration'",
",",
"fringe",
".",
"sorted",
"(",
")",
")",
"node",
"=",
"fringe",
".",
"pop",
"(",
")",
"if",
"problem",
".",
"is_goal",
"(",
"node",
".",
"state",
")",
":",
"if",
"viewer",
":",
"viewer",
".",
"event",
"(",
"'chosen_node'",
",",
"node",
",",
"True",
")",
"viewer",
".",
"event",
"(",
"'finished'",
",",
"fringe",
".",
"sorted",
"(",
")",
",",
"node",
",",
"'goal found'",
")",
"return",
"node",
"else",
":",
"if",
"viewer",
":",
"viewer",
".",
"event",
"(",
"'chosen_node'",
",",
"node",
",",
"False",
")",
"memory",
".",
"add",
"(",
"node",
".",
"state",
")",
"if",
"depth_limit",
"is",
"None",
"or",
"node",
".",
"depth",
"<",
"depth_limit",
":",
"expanded",
"=",
"node",
".",
"expand",
"(",
")",
"if",
"viewer",
":",
"viewer",
".",
"event",
"(",
"'expanded'",
",",
"[",
"node",
"]",
",",
"[",
"expanded",
"]",
")",
"for",
"n",
"in",
"expanded",
":",
"if",
"graph_search",
":",
"others",
"=",
"[",
"x",
"for",
"x",
"in",
"fringe",
"if",
"x",
".",
"state",
"==",
"n",
".",
"state",
"]",
"assert",
"len",
"(",
"others",
")",
"in",
"(",
"0",
",",
"1",
")",
"if",
"n",
".",
"state",
"not",
"in",
"memory",
"and",
"len",
"(",
"others",
")",
"==",
"0",
":",
"fringe",
".",
"append",
"(",
"n",
")",
"elif",
"graph_replace_when_better",
"and",
"len",
"(",
"others",
")",
">",
"0",
"and",
"n",
"<",
"others",
"[",
"0",
"]",
":",
"fringe",
".",
"remove",
"(",
"others",
"[",
"0",
"]",
")",
"fringe",
".",
"append",
"(",
"n",
")",
"else",
":",
"fringe",
".",
"append",
"(",
"n",
")",
"if",
"viewer",
":",
"viewer",
".",
"event",
"(",
"'finished'",
",",
"fringe",
".",
"sorted",
"(",
")",
",",
"None",
",",
"'goal not found'",
")"
] | Basic search algorithm, base of all the other search algorithms. | [
"Basic",
"search",
"algorithm",
"base",
"of",
"all",
"the",
"other",
"search",
"algorithms",
"."
] | 2836befa7e970013f62e0ee75562652aacac6f65 | https://github.com/simpleai-team/simpleai/blob/2836befa7e970013f62e0ee75562652aacac6f65/simpleai/search/traditional.py#L124-L173 |
3,994 | andosa/treeinterpreter | treeinterpreter/treeinterpreter.py | _get_tree_paths | def _get_tree_paths(tree, node_id, depth=0):
"""
Returns all paths through the tree as list of node_ids
"""
if node_id == _tree.TREE_LEAF:
raise ValueError("Invalid node_id %s" % _tree.TREE_LEAF)
left_child = tree.children_left[node_id]
right_child = tree.children_right[node_id]
if left_child != _tree.TREE_LEAF:
left_paths = _get_tree_paths(tree, left_child, depth=depth + 1)
right_paths = _get_tree_paths(tree, right_child, depth=depth + 1)
for path in left_paths:
path.append(node_id)
for path in right_paths:
path.append(node_id)
paths = left_paths + right_paths
else:
paths = [[node_id]]
return paths | python | def _get_tree_paths(tree, node_id, depth=0):
"""
Returns all paths through the tree as list of node_ids
"""
if node_id == _tree.TREE_LEAF:
raise ValueError("Invalid node_id %s" % _tree.TREE_LEAF)
left_child = tree.children_left[node_id]
right_child = tree.children_right[node_id]
if left_child != _tree.TREE_LEAF:
left_paths = _get_tree_paths(tree, left_child, depth=depth + 1)
right_paths = _get_tree_paths(tree, right_child, depth=depth + 1)
for path in left_paths:
path.append(node_id)
for path in right_paths:
path.append(node_id)
paths = left_paths + right_paths
else:
paths = [[node_id]]
return paths | [
"def",
"_get_tree_paths",
"(",
"tree",
",",
"node_id",
",",
"depth",
"=",
"0",
")",
":",
"if",
"node_id",
"==",
"_tree",
".",
"TREE_LEAF",
":",
"raise",
"ValueError",
"(",
"\"Invalid node_id %s\"",
"%",
"_tree",
".",
"TREE_LEAF",
")",
"left_child",
"=",
"tree",
".",
"children_left",
"[",
"node_id",
"]",
"right_child",
"=",
"tree",
".",
"children_right",
"[",
"node_id",
"]",
"if",
"left_child",
"!=",
"_tree",
".",
"TREE_LEAF",
":",
"left_paths",
"=",
"_get_tree_paths",
"(",
"tree",
",",
"left_child",
",",
"depth",
"=",
"depth",
"+",
"1",
")",
"right_paths",
"=",
"_get_tree_paths",
"(",
"tree",
",",
"right_child",
",",
"depth",
"=",
"depth",
"+",
"1",
")",
"for",
"path",
"in",
"left_paths",
":",
"path",
".",
"append",
"(",
"node_id",
")",
"for",
"path",
"in",
"right_paths",
":",
"path",
".",
"append",
"(",
"node_id",
")",
"paths",
"=",
"left_paths",
"+",
"right_paths",
"else",
":",
"paths",
"=",
"[",
"[",
"node_id",
"]",
"]",
"return",
"paths"
] | Returns all paths through the tree as list of node_ids | [
"Returns",
"all",
"paths",
"through",
"the",
"tree",
"as",
"list",
"of",
"node_ids"
] | c4294ad6ad74ea574ca41aa81b6f7f1545da0186 | https://github.com/andosa/treeinterpreter/blob/c4294ad6ad74ea574ca41aa81b6f7f1545da0186/treeinterpreter/treeinterpreter.py#L12-L33 |
3,995 | csurfer/rake-nltk | rake_nltk/rake.py | Rake.extract_keywords_from_text | def extract_keywords_from_text(self, text):
"""Method to extract keywords from the text provided.
:param text: Text to extract keywords from, provided as a string.
"""
sentences = nltk.tokenize.sent_tokenize(text)
self.extract_keywords_from_sentences(sentences) | python | def extract_keywords_from_text(self, text):
"""Method to extract keywords from the text provided.
:param text: Text to extract keywords from, provided as a string.
"""
sentences = nltk.tokenize.sent_tokenize(text)
self.extract_keywords_from_sentences(sentences) | [
"def",
"extract_keywords_from_text",
"(",
"self",
",",
"text",
")",
":",
"sentences",
"=",
"nltk",
".",
"tokenize",
".",
"sent_tokenize",
"(",
"text",
")",
"self",
".",
"extract_keywords_from_sentences",
"(",
"sentences",
")"
] | Method to extract keywords from the text provided.
:param text: Text to extract keywords from, provided as a string. | [
"Method",
"to",
"extract",
"keywords",
"from",
"the",
"text",
"provided",
"."
] | e36116d6074c5ddfbc69bce4440f0342355ceb2e | https://github.com/csurfer/rake-nltk/blob/e36116d6074c5ddfbc69bce4440f0342355ceb2e/rake_nltk/rake.py#L76-L82 |
3,996 | csurfer/rake-nltk | rake_nltk/rake.py | Rake.extract_keywords_from_sentences | def extract_keywords_from_sentences(self, sentences):
"""Method to extract keywords from the list of sentences provided.
:param sentences: Text to extraxt keywords from, provided as a list
of strings, where each string is a sentence.
"""
phrase_list = self._generate_phrases(sentences)
self._build_frequency_dist(phrase_list)
self._build_word_co_occurance_graph(phrase_list)
self._build_ranklist(phrase_list) | python | def extract_keywords_from_sentences(self, sentences):
"""Method to extract keywords from the list of sentences provided.
:param sentences: Text to extraxt keywords from, provided as a list
of strings, where each string is a sentence.
"""
phrase_list = self._generate_phrases(sentences)
self._build_frequency_dist(phrase_list)
self._build_word_co_occurance_graph(phrase_list)
self._build_ranklist(phrase_list) | [
"def",
"extract_keywords_from_sentences",
"(",
"self",
",",
"sentences",
")",
":",
"phrase_list",
"=",
"self",
".",
"_generate_phrases",
"(",
"sentences",
")",
"self",
".",
"_build_frequency_dist",
"(",
"phrase_list",
")",
"self",
".",
"_build_word_co_occurance_graph",
"(",
"phrase_list",
")",
"self",
".",
"_build_ranklist",
"(",
"phrase_list",
")"
] | Method to extract keywords from the list of sentences provided.
:param sentences: Text to extraxt keywords from, provided as a list
of strings, where each string is a sentence. | [
"Method",
"to",
"extract",
"keywords",
"from",
"the",
"list",
"of",
"sentences",
"provided",
"."
] | e36116d6074c5ddfbc69bce4440f0342355ceb2e | https://github.com/csurfer/rake-nltk/blob/e36116d6074c5ddfbc69bce4440f0342355ceb2e/rake_nltk/rake.py#L84-L93 |
3,997 | csurfer/rake-nltk | rake_nltk/rake.py | Rake._build_word_co_occurance_graph | def _build_word_co_occurance_graph(self, phrase_list):
"""Builds the co-occurance graph of words in the given body of text to
compute degree of each word.
:param phrase_list: List of List of strings where each sublist is a
collection of words which form a contender phrase.
"""
co_occurance_graph = defaultdict(lambda: defaultdict(lambda: 0))
for phrase in phrase_list:
# For each phrase in the phrase list, count co-occurances of the
# word with other words in the phrase.
#
# Note: Keep the co-occurances graph as is, to help facilitate its
# use in other creative ways if required later.
for (word, coword) in product(phrase, phrase):
co_occurance_graph[word][coword] += 1
self.degree = defaultdict(lambda: 0)
for key in co_occurance_graph:
self.degree[key] = sum(co_occurance_graph[key].values()) | python | def _build_word_co_occurance_graph(self, phrase_list):
"""Builds the co-occurance graph of words in the given body of text to
compute degree of each word.
:param phrase_list: List of List of strings where each sublist is a
collection of words which form a contender phrase.
"""
co_occurance_graph = defaultdict(lambda: defaultdict(lambda: 0))
for phrase in phrase_list:
# For each phrase in the phrase list, count co-occurances of the
# word with other words in the phrase.
#
# Note: Keep the co-occurances graph as is, to help facilitate its
# use in other creative ways if required later.
for (word, coword) in product(phrase, phrase):
co_occurance_graph[word][coword] += 1
self.degree = defaultdict(lambda: 0)
for key in co_occurance_graph:
self.degree[key] = sum(co_occurance_graph[key].values()) | [
"def",
"_build_word_co_occurance_graph",
"(",
"self",
",",
"phrase_list",
")",
":",
"co_occurance_graph",
"=",
"defaultdict",
"(",
"lambda",
":",
"defaultdict",
"(",
"lambda",
":",
"0",
")",
")",
"for",
"phrase",
"in",
"phrase_list",
":",
"# For each phrase in the phrase list, count co-occurances of the",
"# word with other words in the phrase.",
"#",
"# Note: Keep the co-occurances graph as is, to help facilitate its",
"# use in other creative ways if required later.",
"for",
"(",
"word",
",",
"coword",
")",
"in",
"product",
"(",
"phrase",
",",
"phrase",
")",
":",
"co_occurance_graph",
"[",
"word",
"]",
"[",
"coword",
"]",
"+=",
"1",
"self",
".",
"degree",
"=",
"defaultdict",
"(",
"lambda",
":",
"0",
")",
"for",
"key",
"in",
"co_occurance_graph",
":",
"self",
".",
"degree",
"[",
"key",
"]",
"=",
"sum",
"(",
"co_occurance_graph",
"[",
"key",
"]",
".",
"values",
"(",
")",
")"
] | Builds the co-occurance graph of words in the given body of text to
compute degree of each word.
:param phrase_list: List of List of strings where each sublist is a
collection of words which form a contender phrase. | [
"Builds",
"the",
"co",
"-",
"occurance",
"graph",
"of",
"words",
"in",
"the",
"given",
"body",
"of",
"text",
"to",
"compute",
"degree",
"of",
"each",
"word",
"."
] | e36116d6074c5ddfbc69bce4440f0342355ceb2e | https://github.com/csurfer/rake-nltk/blob/e36116d6074c5ddfbc69bce4440f0342355ceb2e/rake_nltk/rake.py#L135-L153 |
3,998 | csurfer/rake-nltk | rake_nltk/rake.py | Rake._build_ranklist | def _build_ranklist(self, phrase_list):
"""Method to rank each contender phrase using the formula
phrase_score = sum of scores of words in the phrase.
word_score = d(w)/f(w) where d is degree and f is frequency.
:param phrase_list: List of List of strings where each sublist is a
collection of words which form a contender phrase.
"""
self.rank_list = []
for phrase in phrase_list:
rank = 0.0
for word in phrase:
if self.metric == Metric.DEGREE_TO_FREQUENCY_RATIO:
rank += 1.0 * self.degree[word] / self.frequency_dist[word]
elif self.metric == Metric.WORD_DEGREE:
rank += 1.0 * self.degree[word]
else:
rank += 1.0 * self.frequency_dist[word]
self.rank_list.append((rank, " ".join(phrase)))
self.rank_list.sort(reverse=True)
self.ranked_phrases = [ph[1] for ph in self.rank_list] | python | def _build_ranklist(self, phrase_list):
"""Method to rank each contender phrase using the formula
phrase_score = sum of scores of words in the phrase.
word_score = d(w)/f(w) where d is degree and f is frequency.
:param phrase_list: List of List of strings where each sublist is a
collection of words which form a contender phrase.
"""
self.rank_list = []
for phrase in phrase_list:
rank = 0.0
for word in phrase:
if self.metric == Metric.DEGREE_TO_FREQUENCY_RATIO:
rank += 1.0 * self.degree[word] / self.frequency_dist[word]
elif self.metric == Metric.WORD_DEGREE:
rank += 1.0 * self.degree[word]
else:
rank += 1.0 * self.frequency_dist[word]
self.rank_list.append((rank, " ".join(phrase)))
self.rank_list.sort(reverse=True)
self.ranked_phrases = [ph[1] for ph in self.rank_list] | [
"def",
"_build_ranklist",
"(",
"self",
",",
"phrase_list",
")",
":",
"self",
".",
"rank_list",
"=",
"[",
"]",
"for",
"phrase",
"in",
"phrase_list",
":",
"rank",
"=",
"0.0",
"for",
"word",
"in",
"phrase",
":",
"if",
"self",
".",
"metric",
"==",
"Metric",
".",
"DEGREE_TO_FREQUENCY_RATIO",
":",
"rank",
"+=",
"1.0",
"*",
"self",
".",
"degree",
"[",
"word",
"]",
"/",
"self",
".",
"frequency_dist",
"[",
"word",
"]",
"elif",
"self",
".",
"metric",
"==",
"Metric",
".",
"WORD_DEGREE",
":",
"rank",
"+=",
"1.0",
"*",
"self",
".",
"degree",
"[",
"word",
"]",
"else",
":",
"rank",
"+=",
"1.0",
"*",
"self",
".",
"frequency_dist",
"[",
"word",
"]",
"self",
".",
"rank_list",
".",
"append",
"(",
"(",
"rank",
",",
"\" \"",
".",
"join",
"(",
"phrase",
")",
")",
")",
"self",
".",
"rank_list",
".",
"sort",
"(",
"reverse",
"=",
"True",
")",
"self",
".",
"ranked_phrases",
"=",
"[",
"ph",
"[",
"1",
"]",
"for",
"ph",
"in",
"self",
".",
"rank_list",
"]"
] | Method to rank each contender phrase using the formula
phrase_score = sum of scores of words in the phrase.
word_score = d(w)/f(w) where d is degree and f is frequency.
:param phrase_list: List of List of strings where each sublist is a
collection of words which form a contender phrase. | [
"Method",
"to",
"rank",
"each",
"contender",
"phrase",
"using",
"the",
"formula"
] | e36116d6074c5ddfbc69bce4440f0342355ceb2e | https://github.com/csurfer/rake-nltk/blob/e36116d6074c5ddfbc69bce4440f0342355ceb2e/rake_nltk/rake.py#L155-L176 |
3,999 | csurfer/rake-nltk | rake_nltk/rake.py | Rake._generate_phrases | def _generate_phrases(self, sentences):
"""Method to generate contender phrases given the sentences of the text
document.
:param sentences: List of strings where each string represents a
sentence which forms the text.
:return: Set of string tuples where each tuple is a collection
of words forming a contender phrase.
"""
phrase_list = set()
# Create contender phrases from sentences.
for sentence in sentences:
word_list = [word.lower() for word in wordpunct_tokenize(sentence)]
phrase_list.update(self._get_phrase_list_from_words(word_list))
return phrase_list | python | def _generate_phrases(self, sentences):
"""Method to generate contender phrases given the sentences of the text
document.
:param sentences: List of strings where each string represents a
sentence which forms the text.
:return: Set of string tuples where each tuple is a collection
of words forming a contender phrase.
"""
phrase_list = set()
# Create contender phrases from sentences.
for sentence in sentences:
word_list = [word.lower() for word in wordpunct_tokenize(sentence)]
phrase_list.update(self._get_phrase_list_from_words(word_list))
return phrase_list | [
"def",
"_generate_phrases",
"(",
"self",
",",
"sentences",
")",
":",
"phrase_list",
"=",
"set",
"(",
")",
"# Create contender phrases from sentences.",
"for",
"sentence",
"in",
"sentences",
":",
"word_list",
"=",
"[",
"word",
".",
"lower",
"(",
")",
"for",
"word",
"in",
"wordpunct_tokenize",
"(",
"sentence",
")",
"]",
"phrase_list",
".",
"update",
"(",
"self",
".",
"_get_phrase_list_from_words",
"(",
"word_list",
")",
")",
"return",
"phrase_list"
] | Method to generate contender phrases given the sentences of the text
document.
:param sentences: List of strings where each string represents a
sentence which forms the text.
:return: Set of string tuples where each tuple is a collection
of words forming a contender phrase. | [
"Method",
"to",
"generate",
"contender",
"phrases",
"given",
"the",
"sentences",
"of",
"the",
"text",
"document",
"."
] | e36116d6074c5ddfbc69bce4440f0342355ceb2e | https://github.com/csurfer/rake-nltk/blob/e36116d6074c5ddfbc69bce4440f0342355ceb2e/rake_nltk/rake.py#L178-L192 |
Subsets and Splits