etho-python 0.22.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. etho/__init__.py +9 -0
  2. etho/app.py +569 -0
  3. etho/assets/etho_icon1_pipeline_dark.svg +23 -0
  4. etho/assets/etho_icon1_pipeline_light.svg +30 -0
  5. etho/cli.py +215 -0
  6. etho/client.py +384 -0
  7. etho/services/ANAZeroService.py +123 -0
  8. etho/services/BLTZeroService.py +108 -0
  9. etho/services/DAQZeroService.py +326 -0
  10. etho/services/DLPZeroService.py +240 -0
  11. etho/services/GCMZeroService.py +271 -0
  12. etho/services/GOVZeroService.py +231 -0
  13. etho/services/NICounterZeroService.py +92 -0
  14. etho/services/NITriggerZeroService.py +120 -0
  15. etho/services/TemplateZeroService.py +98 -0
  16. etho/services/ZeroService.py +272 -0
  17. etho/services/__init__.py +0 -0
  18. etho/services/callbacks/__init__.py +19 -0
  19. etho/services/callbacks/_base.py +92 -0
  20. etho/services/callbacks/_image.py +798 -0
  21. etho/services/callbacks/_trace.py +456 -0
  22. etho/services/camera/__init__.py +13 -0
  23. etho/services/camera/base.py +164 -0
  24. etho/services/camera/basler.py +201 -0
  25. etho/services/camera/dummy.py +139 -0
  26. etho/services/camera/hamamatsu.py +133 -0
  27. etho/services/camera/spinnaker.py +317 -0
  28. etho/services/camera/ximea.py +167 -0
  29. etho/services/daq/IOTask.py +311 -0
  30. etho/services/daq/ai.py +174 -0
  31. etho/services/dlp/dlp_make_warpfiles.py +131 -0
  32. etho/services/dlp/dlp_runners.py +238 -0
  33. etho/services/utils/__init__.py +0 -0
  34. etho/services/utils/concurrent_task.py +236 -0
  35. etho/services/utils/log_exceptions.py +39 -0
  36. etho/utils/__init__.py +0 -0
  37. etho/utils/calibration.py +88 -0
  38. etho/utils/config.py +41 -0
  39. etho/utils/runner.py +121 -0
  40. etho/utils/shuffled_cycle.py +45 -0
  41. etho/utils/sound.py +336 -0
  42. etho/utils/tui.py +105 -0
  43. etho/utils/zeroclient.py +95 -0
  44. etho_python-0.22.0.dist-info/METADATA +49 -0
  45. etho_python-0.22.0.dist-info/RECORD +47 -0
  46. etho_python-0.22.0.dist-info/WHEEL +4 -0
  47. etho_python-0.22.0.dist-info/entry_points.txt +3 -0
@@ -0,0 +1,272 @@
1
+ import zerorpc
2
+ import abc
3
+ import zmq
4
+ import logging
5
+ from zmq.log.handlers import PUBHandler
6
+ import socket
7
+ import time
8
+ import os
9
+ from typing import Optional, Dict, Any
10
+ import psutil
11
+
12
+
13
+ class BaseZeroService(abc.ABC, zerorpc.Server):
14
+ """Define abstract base class for all 0services.
15
+
16
+ Derivations need to change/implement the following properties/methods:
17
+ LOGGING_PORT: network port for publishing log messages
18
+ SERVICE_PORT: network port for communication with the head
19
+ SERVICE_NAME: unique, three-letter identifier for the service
20
+ is_busy: indicates whether service is running (True/False)
21
+ cleanup: called when finishing/shutting down the service serviceease hardware, close files etc
22
+ test - test functionality of the class (?)
23
+
24
+ Optional:
25
+ setup
26
+ start
27
+
28
+ Global functionality:
29
+ server_start/server_stop
30
+ progress -
31
+ ping - check if server is alive (response with "pong")
32
+ init_local_logger(self, logfilename)
33
+
34
+ """
35
+
36
+ # TODO: make more robust - add exceptions/try-catch
37
+ LOGGING_PORT: Optional[int] = None # network port used for publishing log messages
38
+ SERVICE_PORT: Optional[int] = None # network port for communicating with the head
39
+ SERVICE_NAME: Optional[str] = None
40
+
41
+ def __init__(self, *args, serializer: str = "default", head_ip: str = "192.168.1.1", **kwargs):
42
+ """[summary]
43
+
44
+ Args:
45
+ serializer (str, optional): [description]. Defaults to 'default'.
46
+ head_ip (str, optional): [description]. Defaults to '192.168.1.1'.
47
+ logging_port (int, optional): [description]. Defaults to None.
48
+ service_port (int, optional): [description]. Defaults to None.
49
+ """
50
+ self._serializer = serializer
51
+ ctx = zerorpc.Context()
52
+ ctx.register_serializer(self._serializer)
53
+ super(BaseZeroService, self).__init__(*args, **kwargs, heartbeat=120, context=ctx)
54
+
55
+ self._init_network_logger(head_ip)
56
+
57
+ self._time_started = None
58
+ self.duration = None
59
+ self.prev_elapsed = 0
60
+ self.info: Dict[str, Any] = dict()
61
+
62
+ @classmethod
63
+ def make(
64
+ cls,
65
+ serializer: str,
66
+ host: str = "localhost",
67
+ python_exe: str = "python",
68
+ port: Optional[int] = None,
69
+ new_console: bool = False,
70
+ ):
71
+ from ..utils.zeroclient import ZeroClient # only works on the head node
72
+
73
+ if port is None:
74
+ port = cls.SERVICE_PORT # fall back to default port
75
+
76
+ server_name = f"{python_exe} -m {cls.__module__} {serializer} {port}"
77
+ logging.debug(f"initializing {cls.SERVICE_NAME} at port {port}.")
78
+ service = ZeroClient(
79
+ host,
80
+ service_name=cls.__module__,
81
+ serializer=serializer,
82
+ python_exe=python_exe,
83
+ )
84
+ logging.debug(" starting server:")
85
+ ret = service.start_server(server_name, warmup=1, new_console=new_console)
86
+ logging.debug(f'{"success" if ret else "FAILED"}.')
87
+ logging.debug(" connecting to server:")
88
+
89
+ ret = service.connect("tcp://{0}:{1}".format(host, port))
90
+ logging.debug(f'{"success" if ret else "FAILED"}.')
91
+ return service
92
+
93
+ def _init_network_logger(self, head_ip: str = "192.168.1.1", log_level: int = logging.INFO):
94
+ """Initialize logger that publishes messages over the network format.
95
+
96
+ For live display of messages on head node (see ethomaster.head.headlogger).
97
+ Args:
98
+ head_ip: IP address to publish to (defaults to '192.168.1.1')
99
+ lob_level: (defaults to logging.INFO)
100
+ """
101
+ # setup connection - publish to head_ip via LOGGING_PORT
102
+ ctx = zmq.Context()
103
+ ctx.LINGER = 0
104
+ pub = ctx.socket(zmq.PUB)
105
+ pub.connect("tcp://{0}:{1}".format(head_ip, self.LOGGING_PORT))
106
+
107
+ self.log = logging.getLogger((__name__))
108
+ self.log.setLevel(log_level)
109
+
110
+ # get host name or IP to append to message
111
+ self.hostname = socket.gethostname()
112
+
113
+ prefix = "%(asctime)s.%(msecs)03d {0}@{1}:".format(self.SERVICE_NAME, self.hostname)
114
+ body = "%(module)s:%(funcName)s:%(lineno)d - %(message)s"
115
+ df = "%Y-%m-%d,%H:%M:%S"
116
+ formatters = {
117
+ logging.DEBUG: logging.Formatter(prefix + body + "\n", datefmt=df),
118
+ logging.INFO: logging.Formatter(prefix + "%(message)s\n", datefmt=df),
119
+ logging.WARN: logging.Formatter(prefix + body + "\n", datefmt=df),
120
+ logging.ERROR: logging.Formatter(prefix + body + " - %(exc_info)s\n", datefmt=df),
121
+ logging.CRITICAL: logging.Formatter(prefix + body + "\n", datefmt=df),
122
+ }
123
+
124
+ # setup log handler which publishes all log messages to the network
125
+ handler = PUBHandler(pub)
126
+ handler.setLevel(log_level) # catch only important messages
127
+ handler.formatters = formatters
128
+ self.log.addHandler(handler)
129
+
130
+ # initialize attributes for log to local file (should be in __init__)
131
+ self.logfilename = None
132
+ self.filelogger = None
133
+
134
+ @abc.abstractmethod
135
+ def is_busy(self): # returns bool
136
+ """return state of the instance - IDLE, BUSY, FAILED, etc"""
137
+
138
+ @abc.abstractmethod
139
+ def test(self): # returns bool
140
+ """test whether the instance will be functional"""
141
+
142
+ @abc.abstractmethod
143
+ def cleanup(self): # returns bool
144
+ """free resources"""
145
+
146
+ def init_local_logger(self, logfilename):
147
+ """log locally to LOGFILENAME"""
148
+ self.logfilename = logfilename
149
+ if self.filelogger is not None:
150
+ # remove old handler
151
+ self.log.removeHandler(self.filelogger)
152
+
153
+ # create a file handler
154
+ os.makedirs(os.path.dirname(self.logfilename), exist_ok=True)
155
+ self.filelogger = logging.FileHandler(self.logfilename)
156
+ self.filelogger.setLevel(logging.INFO) # catch all messages
157
+
158
+ # create a logging format
159
+ formatter = logging.Formatter("%(asctime)s.%(msecs)03d {0}@{1}: %(message)s".format(self.SERVICE_NAME, self.hostname), datefmt="%Y-%m-%d,%H:%M:%S")
160
+ self.filelogger.setFormatter(formatter)
161
+ # add the handlers to the logger
162
+ self.log.addHandler(self.filelogger)
163
+
164
+ def _flush_loggers(self):
165
+ """Make sure all log messages are sent/saved."""
166
+ for handler in self.log.handlers:
167
+ handler.flush()
168
+
169
+ def _time_elapsed(self):
170
+ if self._time_started is None:
171
+ time_elapsed = None
172
+ else:
173
+ time_elapsed = time.time() - self._time_started
174
+ return time_elapsed
175
+
176
+ def attr(self, name: str):
177
+ # 0rpc only exposes functions - can't access attributes directly
178
+ # so we wrap attribute access in a function
179
+ return self.__getattribute__(name)
180
+
181
+ def information(self):
182
+ """Information to display about the
183
+
184
+ should be Dict[str, Dict[str, Any]]
185
+ should be Dict[str, Tuple[Dict[str, Any], Dict[str, Any]]]
186
+ should be Dict[str, pd.DataFrame]
187
+
188
+ Print to terminal with `ethoservice.utils.tui.rich_information`.
189
+ """
190
+ return self.info
191
+
192
+ def progress(self):
193
+ try:
194
+ elapsed = self._time_elapsed()
195
+ p = {
196
+ "total": self.duration,
197
+ "elapsed": elapsed,
198
+ "elapsed_delta": elapsed - self.prev_elapsed,
199
+ "elapsed_units": "seconds",
200
+ }
201
+ self.prev_elapsed = elapsed
202
+ return p
203
+ except:
204
+ pass
205
+
206
+ def ping(self):
207
+ self.log.info("pong")
208
+ return "pong"
209
+
210
+ def service_start(self, ip_address: str = "tcp://0.0.0.0"):
211
+ """Start service.
212
+
213
+ Args:
214
+ ip_address: "tcp://0.0.0.0"
215
+ """
216
+ self.log.warning("starting")
217
+ self.bind(f"{ip_address}:{self.SERVICE_PORT}")
218
+ self.run()
219
+ self.log.warning(" done")
220
+
221
+ def service_stop(self):
222
+ """Stop service."""
223
+ self.log.warning("stopping service")
224
+ try:
225
+ self.stop()
226
+ except Exception as e:
227
+ self.log.debug("Could not stop.", exc_info=e)
228
+ self.log.warning(" done")
229
+ self._flush_loggers()
230
+ self.service_kill()
231
+
232
+ def service_kill(self):
233
+ self.log.warning(" kill process {0}".format(self.pid))
234
+ self.kill_children()
235
+ self.kill()
236
+
237
+ def kill(self, include_children: bool = False):
238
+ if include_children:
239
+ self.kill_children()
240
+ self.log.warning(" kill process {0}".format(self.pid))
241
+ psutil.Process(self.pid).kill()
242
+
243
+ def kill_children(self):
244
+ try:
245
+ parent = psutil.Process(self.pid)
246
+ except psutil.NoSuchProcess:
247
+ return
248
+ children = parent.children(recursive=True)
249
+ for p in children:
250
+ p.kill()
251
+
252
+ def _getpid(self):
253
+ return os.getpid()[0]
254
+
255
+ def getpid(self):
256
+ return os.getpid()[0]
257
+
258
+ @property
259
+ def pid(self):
260
+ return os.getpid()
261
+
262
+ @property
263
+ def pgrp(self):
264
+ try:
265
+ return os.getpgrp() # not supported in windows
266
+ except:
267
+ return None
268
+
269
+ def __del__(self):
270
+ self.cleanup()
271
+ self.stop()
272
+ self._flush_loggers()
File without changes
@@ -0,0 +1,19 @@
1
+ # first define this and then import the submodules so callbacks are automatically
2
+ # registered by their name in the `callbacks` dict
3
+
4
+ callbacks = dict()
5
+
6
+
7
+ def _register_callback(func):
8
+ """Adds func to model_dict Dict[modelname: modelfunc]. For selecting models by string."""
9
+ if hasattr(func, "FRIENDLY_NAME"):
10
+ callbacks[func.FRIENDLY_NAME] = func
11
+ callbacks[func.__name__] = func
12
+ return func
13
+
14
+
15
+ register_callback = _register_callback
16
+
17
+ from ._base import BaseCallback
18
+ from . import _image
19
+ from . import _trace
@@ -0,0 +1,92 @@
1
+ import queue
2
+ import time
3
+ from ..utils.concurrent_task import ConcurrentTask
4
+ from . import register_callback
5
+ from typing import Optional
6
+
7
+
8
+ class BaseCallback:
9
+ def __init__(self, data_source, poll_timeout: Optional[float] = None, rate: float = 0, **kwargs):
10
+ """_summary_
11
+
12
+ Args:
13
+ data_source (_type_): Queue, pipe or ...
14
+ poll_timeout (Optional[float], optional): Timeout for polling data source. Defaults to None.
15
+ rate (float, optional): Rate (interval between calls in seconds) at which callback is called. Defaults to 0 (no rate limiting).
16
+ """
17
+ self.data_source = data_source
18
+ self.poll_timeout = poll_timeout
19
+ self.RUN: bool = True
20
+ self.CLEAN: bool = False
21
+ self.rate = rate
22
+
23
+ @classmethod
24
+ def make_run(cls, *class_args, **class_kwargs):
25
+ obj = cls(*class_args, **class_kwargs)
26
+ obj.RUN = True
27
+ obj._run()
28
+ return obj
29
+
30
+ @classmethod
31
+ def make_concurrent(cls, comms="queue", **kwargs):
32
+ # will run `cls.make_run(data_source="eval(comms)", **kwargs)
33
+ return ConcurrentTask(task=cls.make_run, comms=comms, **kwargs)
34
+
35
+ def start(self):
36
+ self.RUN = True
37
+ self._run()
38
+
39
+ def stop(self):
40
+ self.RUN = False
41
+
42
+ def _run(self):
43
+ t1 = 0
44
+ while self.RUN:
45
+ t0 = time.time()
46
+ try:
47
+ data = self.data_source.get(timeout=self.poll_timeout)
48
+ except AttributeError:
49
+ if self.data_source.poll(timeout=self.poll_timeout):
50
+ data = self.data_source.recv()
51
+ else:
52
+ continue
53
+ except queue.Empty:
54
+ continue
55
+
56
+ if data is not None:
57
+ if (t0 - t1) >= self.rate:
58
+ self._loop(data)
59
+ t1 = t0
60
+ else:
61
+ self.stop()
62
+
63
+ self._cleanup()
64
+
65
+ def _loop(self, data):
66
+ """Override this and do sth with `data`
67
+
68
+ Args:
69
+ data (_type_): _description_
70
+ """
71
+ pass
72
+
73
+ def _cleanup(self):
74
+ """Clean up before killing callback.
75
+
76
+ Override this and:
77
+ - flush all data_sources (e.g. process all items from the queue)
78
+ - close all files or hardware
79
+ - call `super()._cleanup()` at the end
80
+ """
81
+ self.CLEAN = True
82
+
83
+ def __del__(self):
84
+ self.stop()
85
+ if not self.CLEAN:
86
+ self._cleanup()
87
+
88
+
89
+ @register_callback
90
+ class BroadcastCallback:
91
+ """Broadcast data w/o acting on it."""
92
+ pass