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,240 @@
1
+ #!/usr/bin/env python
2
+ from .ZeroService import BaseZeroService # import super class
3
+ import time # for timer
4
+ import threading
5
+ from .utils.log_exceptions import for_all_methods, log_exceptions
6
+ from .dlp import dlp_runners
7
+ import logging
8
+ import defopt
9
+ from typing import Optional
10
+
11
+ try:
12
+ import pycrafter4500
13
+ from pybmt.callback.threshold_callback import ThresholdCallback
14
+ from pybmt.callback.broadcast_callback import BroadcastCallback
15
+ from pybmt.fictrac.service import FicTracDriver
16
+ from pybmt.fictrac.state import FicTracState
17
+
18
+ dlp_import_error = None
19
+ except ImportError as dlp_import_error:
20
+ pass
21
+
22
+
23
+ # decorate all methods in the class so that exceptions are properly logged
24
+ @for_all_methods(log_exceptions(logging.getLogger(__name__)))
25
+ class DLP(BaseZeroService):
26
+
27
+ LOGGING_PORT = 1453 # set this to range 1420-1460
28
+ SERVICE_PORT = 4253 # last two digits match logging port - but start with "42" instead of "14"
29
+ SERVICE_NAME = "DLP" # short, uppercase, 3-letter ID of the service (must equal class name)
30
+
31
+ def setup(self, duration, logfilename, params=None):
32
+ if dlp_import_error is not None:
33
+ raise dlp_import_error
34
+
35
+ self._time_started = None
36
+ self.duration = float(duration)
37
+ fps = 180
38
+ nb_frames = int(self.duration * fps)
39
+ self.tracDrv = FicTracDriver.as_client(remote_endpoint_url="localhost:5556")
40
+ if self.tracDrv.fictrac_process is None: # ensure fictrac is running
41
+ self.tracDrv = None
42
+
43
+ # 180 hz, 7 bit depth, white
44
+ try:
45
+ pycrafter4500.pattern_mode(
46
+ num_pats=3,
47
+ fps=180,
48
+ bit_depth=7,
49
+ led_color=0b111, # BGR flags
50
+ )
51
+ except AttributeError:
52
+ raise ValueError("Failed setting DLP pattern mode. Maybe DLP is off.")
53
+
54
+ # background jobs should be run and controlled via a thread
55
+
56
+ # signals that the works is initialized and ready to receive the start_run signal
57
+ self._thread_is_ready = threading.Event()
58
+ # start running the worker after init
59
+ self._thread_start_run = threading.Event()
60
+ # threads can be stopped by setting an event: `_thread_stopper.set()`
61
+ self._thread_stopper = threading.Event()
62
+
63
+ # via a timer
64
+ if self.duration > 0:
65
+ self._thread_timer = threading.Timer(self.duration, self.finish, kwargs={"stop_service": True})
66
+ #
67
+ self._worker_thread = threading.Thread(
68
+ target=self._worker,
69
+ args=(
70
+ self._thread_stopper,
71
+ self._thread_start_run,
72
+ self._thread_is_ready,
73
+ logfilename,
74
+ nb_frames,
75
+ self.log,
76
+ self.tracDrv,
77
+ params,
78
+ ),
79
+ )
80
+
81
+ # start thread here so everything is initialized before
82
+ # we start for more deterministic delays
83
+ self.log.info("Initialzing PsychoPy stuff.")
84
+
85
+ # start the thread - this will halt after initialization
86
+ self._worker_thread.start()
87
+
88
+ # block until thread is initialized
89
+ self._thread_is_ready.wait()
90
+
91
+ def start(self):
92
+ self._time_started = time.time()
93
+ # background jobs should be run and controlled via a thread
94
+ self._thread_start_run.set() # this will start playing the DLP stimulis
95
+ self.log.info("started")
96
+ if hasattr(self, "_thread_timer"):
97
+ self.log.info("duration {0} seconds".format(self.duration))
98
+ self._thread_timer.start()
99
+ self.log.info("finish timer started")
100
+
101
+ def _worker(self, stop_event, start_run_event, is_ready_event, savefilename, nb_frames, logger, tracDrv, params):
102
+ # need to import psychopy here since psychopy only works in the thread where it's imported
103
+ from psychopy.visual.windowframepack import ProjectorFramePacker
104
+ import psychopy.visual, psychopy.event, psychopy.core, psychopy.visual.windowwarp
105
+ from tqdm import tqdm
106
+ from .callbacks import callbacks
107
+
108
+ # # INIT WINDOW
109
+ screen_id = 1
110
+
111
+ # main window
112
+ win = psychopy.visual.Window(
113
+ monitor="projector", screen=screen_id, units="norm", fullscr=False, useFBO=True, size=(912, 1140), allowGUI=False
114
+ )
115
+ framePacker = ProjectorFramePacker(win)
116
+
117
+ # INIT WARPER (skip for prototyping)
118
+ if params["use_warping"]:
119
+ logger.info(f"Loading warp data from {params['warpfile']}")
120
+ # create a warper and change projection using warpfile
121
+ warper = psychopy.visual.windowwarp.Warper(win, warp=None, warpfile=None)
122
+ warper.changeProjection(
123
+ warp="warpfile", warpfile=params["warpfile"], eyepoint=[0.5, 0.5], flipHorizontal=False, flipVertical=False
124
+ )
125
+ logger.info("Warp file loaded.")
126
+
127
+ # INIT RUNNERS
128
+ logger.info("Initializing runners:")
129
+ runners = {}
130
+ for runner_name, runner_args in params["runners"].items():
131
+ if "object" in runner_args: # get class handle from object name
132
+ runner_args["object"] = psychopy.visual.__dict__[runner_args["object"]]
133
+ logger.info(f" {runner_name}: {runner_args}")
134
+ runners[runner_name] = dlp_runners.runners[runner_name](win, **runner_args)
135
+
136
+ # INIT CALLBACKS
137
+ tasks = []
138
+ attrs = {}
139
+ common_task_kwargs = {"file_name": savefilename, "attrs": attrs}
140
+ for cb_name, cb_params in params["callbacks"].items():
141
+ if cb_params is not None:
142
+ task_kwargs = {**common_task_kwargs, **cb_params}
143
+ else:
144
+ task_kwargs = common_task_kwargs
145
+ tasks.append(callbacks[cb_name].make_concurrent(task_kwargs=task_kwargs))
146
+
147
+ for task in tasks:
148
+ task.start()
149
+
150
+ logger.info("Finished initializing worker.")
151
+ is_ready_event.set()
152
+ logger.info("Waiting for `start_run` event.")
153
+ self._thread_start_run.wait()
154
+
155
+ # re-activate windows
156
+ win.winHandle.activate() # re-activate window
157
+ win.flip() # redraw the newly activated window
158
+
159
+ # RUN THE RUNNERS
160
+ logger.info("Running the runners")
161
+ ball_info = None
162
+ log_msg = dict()
163
+ for frame_number in tqdm(range(nb_frames), total=nb_frames, mininterval=1):
164
+ if stop_event.is_set():
165
+ logger.info("received stop event")
166
+ break
167
+
168
+ if tracDrv is not None: # get ball info
169
+ ball_info = tracDrv._read_message()
170
+
171
+ for runner_name, runner in runners.items():
172
+ log_data = runner.update(frame_number, ball_info)
173
+ log_msg[runner_name] = log_data
174
+ win.flip()
175
+
176
+ systemtime = time.time()
177
+ for task in tasks:
178
+ task.send((log_msg, systemtime))
179
+
180
+ # CLEAN UP RUNNERS
181
+ for runner in runners.values():
182
+ runner.destroy()
183
+
184
+ win.close()
185
+ # win2.close()
186
+ for task in tasks:
187
+ try:
188
+ task.close()
189
+ except Exception as e:
190
+ pass # print(e)
191
+ psychopy.core.quit()
192
+
193
+ def finish(self, stop_service=False):
194
+ self.log.warning("stopping")
195
+ # stop thread if necessary
196
+ if hasattr(self, "_thread_stopper"):
197
+ self._thread_stopper.set()
198
+ if hasattr(self, "_thread_timer"):
199
+ self._thread_timer.cancel()
200
+ # clean up code here
201
+
202
+ self.log.warning(" stopped ")
203
+ # mode log file and savefilename
204
+ if stop_service:
205
+ time.sleep(2)
206
+ self.service_stop()
207
+
208
+ def disp(self):
209
+ pass
210
+
211
+ def is_busy(self):
212
+ return True # should return True/False
213
+
214
+ def test(self):
215
+ return True
216
+
217
+ def cleanup(self):
218
+ self.finish()
219
+ # your code here
220
+ return True
221
+
222
+ def info(self):
223
+ if self.is_busy():
224
+ pass # your code here
225
+ else:
226
+ return None
227
+
228
+
229
+ def cli(serializer: str = "default", port: Optional[str] = None):
230
+ if port == None:
231
+ port = DLP.SERVICE_PORT
232
+ s = DLP(serializer=serializer)
233
+ s.bind("tcp://0.0.0.0:{0}".format(port)) # broadcast on all IPs
234
+ print("running DLPZeroService")
235
+ s.run()
236
+ print("done")
237
+
238
+
239
+ if __name__ == "__main__":
240
+ defopt.run(cli)
@@ -0,0 +1,271 @@
1
+ from .ZeroService import BaseZeroService
2
+ import time
3
+ import threading
4
+ import sys
5
+ from .utils.log_exceptions import for_all_methods, log_exceptions
6
+ import logging
7
+ from ..services import camera
8
+ from .callbacks import callbacks
9
+
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+
14
+ @for_all_methods(log_exceptions(logger))
15
+ class GCM(BaseZeroService):
16
+ LOGGING_PORT = 1446 # set this to range 1420-1460
17
+ SERVICE_PORT = 4246 # last to digits match logging port - but start with "42" instead of "14"
18
+ SERVICE_NAME = "GCM" # short, uppercase, 3-letter ID of the service (equals class name)
19
+
20
+ def setup(self, savefilename, duration, params):
21
+ self._time_started = None
22
+ self.duration = duration
23
+ self.savefilename = savefilename
24
+ self.c = None
25
+
26
+ # set up CAMERA
27
+ self.cam_serialnumber = str(params["cam_serialnumber"])
28
+ self.cam_type = params["cam_type"]
29
+ assert self.cam_type in camera.make.keys()
30
+ self.c = camera.make[self.cam_type](self.cam_serialnumber)
31
+ try:
32
+ self.c.init()
33
+ except Exception as e:
34
+ self.log.exception(
35
+ f"Failed to init {self.cam_type} (sn {self.cam_serialnumber}). Reset and re-try.",
36
+ exc_info=e,
37
+ )
38
+ self.c.reset()
39
+ self.c.init()
40
+
41
+ defaults = {
42
+ "binning": 1,
43
+ "gamma": 1,
44
+ "gain": 0,
45
+ "brightness": 0,
46
+ "optimize_auto_exposure": False,
47
+ "external_trigger": False,
48
+ "frame_offx": 0,
49
+ "frame_offy": 0,
50
+ }
51
+ params = defaults | params # merge directory - keep existing values in params, only add non-existing from defaults
52
+
53
+ self.c.roi = [
54
+ params["frame_offx"],
55
+ params["frame_offy"],
56
+ params["frame_width"],
57
+ params["frame_height"],
58
+ ]
59
+ self.c.exposure = params["shutter_speed"]
60
+ self.c.brightness = params["brightness"]
61
+ self.c.gamma = params["gamma"]
62
+ self.c.gain = params["gain"]
63
+ self.c.framerate = params["frame_rate"]
64
+ self.c.binning = params["binning"]
65
+
66
+ if "optimize_auto_exposure" in params and params["optimize_auto_exposure"]:
67
+ self.c.optimize_auto_exposure()
68
+
69
+ # acquire test image
70
+ self.c.disable_gpio_strobe() # to prevent the test image producing strobes
71
+ self.c.external_trigger = False # disable here so test image acq works w/o ext trigger
72
+ self.c.start()
73
+ self.test_image, image_ts, system_ts = self.c.get()
74
+ self.c.stop()
75
+
76
+ self.c.external_trigger = params["external_trigger"]
77
+
78
+ self.frame_width, self.frame_height, self.frame_channels = self.test_image.shape
79
+ self.framerate = self.c.framerate
80
+ self.nFrames = int(self.framerate * self.duration + 100)
81
+ self.frameNumber = 0
82
+ self.prev_framenumber = 0
83
+
84
+ self.callbacks = []
85
+ self.callback_names = []
86
+ common_task_kwargs = {
87
+ "file_name": self.savefilename,
88
+ "frame_rate": self.framerate,
89
+ "frame_height": self.frame_height,
90
+ "frame_width": self.frame_width,
91
+ }
92
+
93
+ if "callbacks" in params and params["callbacks"]:
94
+ for cb_name, cb_params in params["callbacks"].items():
95
+ if cb_params is not None:
96
+ task_kwargs = {**common_task_kwargs, **cb_params}
97
+ else:
98
+ task_kwargs = common_task_kwargs
99
+
100
+ self.callbacks.append(callbacks[cb_name].make_concurrent(task_kwargs=task_kwargs))
101
+ self.callback_names.append(cb_name)
102
+
103
+ # background jobs should be run and controlled via a thread
104
+ # threads can be stopped by setting an event: `_thread_stopper.set()`
105
+ self._thread_stopper = threading.Event()
106
+ # and/or via a timer
107
+
108
+ if self.duration > 0:
109
+ self._thread_timer = threading.Timer(self.duration, self.finish, kwargs={"stop_service": True})
110
+
111
+ # set up the worker thread
112
+ self._worker_thread = threading.Thread(target=self._worker, args=(self._thread_stopper,))
113
+
114
+ iii = self.c.info_imaging()
115
+ iii["exposure"] = f"{iii['exposure']:1.2f}ms"
116
+ params["exposure"] = f"{params['shutter_speed']/1_000:1.2f}ms"
117
+ params["framerate"] = params["frame_rate"]
118
+ params["offsetX"], params["offsetY"], params["width"], params["height"] = (
119
+ params["frame_offx"],
120
+ params["frame_offy"],
121
+ params["frame_width"],
122
+ params["frame_height"],
123
+ )
124
+
125
+ hii = self.c.info_hardware()
126
+ self.log.info(params.__str__())
127
+ try:
128
+ hii.update({k: v if v is not None else "defaults" for k, v in params["callbacks"].items()})
129
+ except AttributeError:
130
+ pass
131
+ hii["savefilename"] = self.savefilename
132
+ hii["duration"] = self.duration
133
+ self.info = {"hardware": hii, "image": (iii, params)}
134
+
135
+ self.finished = False
136
+
137
+ def start(self):
138
+ for callback in self.callbacks:
139
+ callback.start()
140
+ self._time_started = time.time()
141
+
142
+ # background jobs should be run and controlled via a thread
143
+ self._worker_thread.start()
144
+ self.log.debug("started")
145
+ if hasattr(self, "_thread_timer"):
146
+ self.log.debug("duration {0} seconds".format(self.duration))
147
+ self._thread_timer.start()
148
+ self.log.debug("finish timer started")
149
+
150
+ def _worker(self, stop_event):
151
+ RUN = True
152
+ self.frameNumber = 0
153
+ self.prev_framenumber = 0
154
+ self.log.info("started worker")
155
+ self.c.enable_gpio_strobe()
156
+ self.c.start()
157
+
158
+ while RUN:
159
+ try:
160
+ out = self.c.get()
161
+ if out is None:
162
+ raise ValueError("Image is None")
163
+ else:
164
+ image, image_ts, system_ts = out
165
+
166
+ for callback_name, callback in zip(self.callback_names, self.callbacks):
167
+ if "timestamps" in callback_name:
168
+ package = (0, (system_ts, image_ts))
169
+ else:
170
+ package = (image, (system_ts, image_ts))
171
+ callback.send(package)
172
+
173
+ self.frameNumber += 1
174
+ if self.frameNumber == self.nFrames:
175
+ self.log.info("Max number of frames reached - stopping.")
176
+ RUN = False
177
+
178
+ except ValueError as e:
179
+ RUN = False
180
+ self.c.stop()
181
+ self.log.debug(e, exc_info=True)
182
+ except Exception as e:
183
+ self.log.exception("Error", exc_info=e)
184
+
185
+ def finish(self, stop_service=False):
186
+ self.log.warning("stopping")
187
+ try:
188
+ self.c.disable_gpio_strobe()
189
+ except Exception as e:
190
+ pass # self.log.warning(e)
191
+
192
+ # stop thread if necessary
193
+ if hasattr(self, "_thread_stopper"):
194
+ self._thread_stopper.set()
195
+ if hasattr(self, "_thread_timer"):
196
+ self._thread_timer.cancel()
197
+
198
+ # clean up code here
199
+ try:
200
+ self.c.close() # not sure this works if BeginAcquistion has not been called
201
+ except:
202
+ pass
203
+
204
+ for callback in self.callbacks:
205
+ callback.finish()
206
+
207
+ # callbacks clean up after themselves now so probably no need for this:
208
+ for callback in self.callbacks:
209
+ try:
210
+ callback.close()
211
+ except Exception as e:
212
+ pass
213
+
214
+ self.finished = True
215
+ self.log.warning(" stopped ")
216
+ if stop_service:
217
+ time.sleep(0.5)
218
+ self.service_stop()
219
+ # self.kill_children()
220
+ # self.kill()
221
+
222
+ def progress(self):
223
+ try:
224
+ p = super().progress()
225
+ fn = self.frameNumber
226
+ p.update(
227
+ {
228
+ "framenumber": fn,
229
+ "framenumber_delta": fn - self.prev_framenumber,
230
+ "framenumber_units": "frames",
231
+ }
232
+ )
233
+ self.prev_framenumber = fn
234
+ return p
235
+ except:
236
+ pass
237
+
238
+ def disp(self):
239
+ pass
240
+
241
+ def is_busy(self):
242
+ return True # should return True/False
243
+
244
+ def test(self):
245
+ return True
246
+
247
+ def cleanup(self):
248
+ self.finish()
249
+ # your code here
250
+ return True
251
+
252
+ def info(self):
253
+ if self.is_busy():
254
+ pass # your code here
255
+ else:
256
+ return None
257
+
258
+
259
+ if __name__ == "__main__":
260
+ if len(sys.argv) > 1:
261
+ ser = sys.argv[1]
262
+ else:
263
+ ser = "default"
264
+ if len(sys.argv) > 2:
265
+ port = sys.argv[2]
266
+ else:
267
+ port = GCM.SERVICE_PORT
268
+ logger.info(f'Starting service GCM at {port} with serializer "{ser}".')
269
+ s = GCM(serializer=ser)
270
+ s.bind("tcp://0.0.0.0:{0}".format(port)) # broadcast on all IPs
271
+ s.run()