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,123 @@
1
+ from .ZeroService import BaseZeroService # import super class
2
+ import time # for timer
3
+ import sys
4
+ import numpy as np
5
+ from .utils.log_exceptions import for_all_methods, log_exceptions
6
+ import logging
7
+
8
+ try:
9
+ import PyDAQmx as daq
10
+ from PyDAQmx.DAQmxCallBack import *
11
+ from PyDAQmx.DAQmxConstants import *
12
+ from PyDAQmx.DAQmxFunctions import *
13
+ pydaqmx_import_error = None
14
+ except ImportError as pydaqmx_import_error:
15
+ pass
16
+
17
+
18
+ @for_all_methods(log_exceptions(logging.getLogger(__name__)))
19
+ class ANA(BaseZeroService):
20
+ """[summary]"""
21
+
22
+ LOGGING_PORT = 1451 # set this to range 1420-1460
23
+ SERVICE_PORT = 4251 # last to digits match logging output_channels - but start with "42" instead of "14"
24
+ SERVICE_NAME = "ANA" # short, uppercase, 3-letter ID of the service (equals class name)
25
+
26
+ def setup(self, duration, output_channels):
27
+ """Setup the trigger service (intiates the digital output channels).
28
+
29
+ Args:
30
+ duration (float): Unused - kept to keep the interface same across services [description]
31
+ output_channels (str): , e.g. "/dev1/port0/line0:1"
32
+ """
33
+ if pydaqmx_import_error is not None:
34
+ raise pydaqmx_import_error
35
+
36
+ self._time_started = None
37
+ self.duration = float(duration)
38
+
39
+ self.samples_read = daq.int32()
40
+ dev_name = "/Dev1"
41
+ cha_name = ["ao2", "ao3"]
42
+ self.cha_name = [dev_name + "/" + ch for ch in cha_name] # append device name
43
+ self.cha_string = ", ".join(self.cha_name)
44
+ self.num_channels = len(cha_name)
45
+ self.num_samples_per_chan = 10_000
46
+ self._data = np.ones((self.num_samples_per_chan, self.num_channels), dtype=np.float64) # init empty data array
47
+
48
+ limits = 10
49
+ self.task = daq.Task()
50
+ self.task.CreateAOVoltageChan(self.cha_string, "", -limits, limits, DAQmx_Val_Volts, None)
51
+ self.task.StartTask()
52
+
53
+ def set_value(self, state, duration=0.0001):
54
+ """Set the digital output channels to specified state.
55
+
56
+ Args:
57
+ state ([type]): [description]
58
+ duration (float, optional): How long the trigger state should last (in seconds).
59
+ Will reset to all 0 after the duration.
60
+ If None will return immediatelly and keep the trigger state permanent.
61
+ Defaults to 0.0001.
62
+ """
63
+ # if len(state) != self.nb_channels:
64
+ # raise ValueError(f"State vector should have same length as the number of digital output channels. Is {len(state)}, should be {'x'}.")
65
+ self.log.info("sending {state} on {output_channels}")
66
+ self.task.WriteAnalogF64(
67
+ self._data.shape[0],
68
+ 0,
69
+ DAQmx_Val_WaitInfinitely,
70
+ DAQmx_Val_GroupByScanNumber,
71
+ self._data * state,
72
+ daq.byref(self.samples_read),
73
+ None,
74
+ )
75
+
76
+ # This is currently blocking - not so great
77
+ if duration is not None:
78
+ time.sleep(duration) # alternatively could return immediately using a threaded timer
79
+ self.task.WriteAnalogF64(
80
+ self._data.shape[0],
81
+ 0,
82
+ DAQmx_Val_WaitInfinitely,
83
+ DAQmx_Val_GroupByScanNumber,
84
+ self._data * 0,
85
+ daq.byref(self.samples_read),
86
+ None,
87
+ )
88
+ self.log.info(" success.")
89
+
90
+ def start(self):
91
+ pass
92
+
93
+ def finish(self, stop_service=False):
94
+ self.log.warning("stopping")
95
+ self.task.StopTask()
96
+
97
+ # clean up code here
98
+ self.log.warning(" stopped ")
99
+ # mode log file and savefilename
100
+ if stop_service:
101
+ time.sleep(2)
102
+ self.service_stop()
103
+
104
+ def is_busy(self):
105
+ return True # should return True/False
106
+
107
+ def test(self):
108
+ return True
109
+
110
+ def cleanup(self):
111
+ self.finish()
112
+ # your code here
113
+ return True
114
+
115
+
116
+ if __name__ == "__main__":
117
+ if len(sys.argv) > 1:
118
+ ser = sys.argv[1]
119
+ else:
120
+ ser = "default"
121
+ s = ANA(serializer=ser)
122
+ s.bind("tcp://0.0.0.0:{0}".format(ANA.SERVICE_PORT)) # broadcast on all IPs
123
+ s.run()
@@ -0,0 +1,108 @@
1
+ from .ZeroService import BaseZeroService # import super class
2
+ import time
3
+ import threading
4
+ import logging
5
+ import defopt
6
+ from typing import Optional
7
+
8
+ from .utils.log_exceptions import for_all_methods, log_exceptions
9
+ from .utils.concurrent_task import Pipe
10
+
11
+ try:
12
+ from pybmt.callback.threshold_callback import ThresholdCallback
13
+ from pybmt.callback.broadcast_callback import BroadcastCallback
14
+ from pybmt.fictrac.service import FicTracDriver
15
+
16
+ pybmt_error = None
17
+ except ImportError as pybmt_error:
18
+ pass
19
+
20
+ # decorate all methods in the class so that exceptions are properly logged
21
+ @for_all_methods(log_exceptions(logging.getLogger(__name__)))
22
+ class BLT(BaseZeroService):
23
+
24
+ LOGGING_PORT = 1452 # set this to range 1420-1460
25
+ SERVICE_PORT = 4252 # last two digits match logging port - but start with "42" instead of "14"
26
+ SERVICE_NAME = "BLT" # short, uppercase, 3-letter ID of the service (must equal class name)
27
+
28
+ def setup(self, savefilename, duration, params):
29
+ if pybmt_error is not None:
30
+ raise pybmt_error
31
+ self.log.info("setup")
32
+ self._time_started = None
33
+ self.duration = float(duration)
34
+
35
+ # APPLICATION SPECIFIC SETUP CODE HERE
36
+
37
+ # Instantiate a FicTracDriver object to handle running of FicTrac in the background
38
+ # and communication of program state.
39
+ self.tracDrv = FicTracDriver.as_server(config_file=params["config_file"], savefilename=savefilename)
40
+
41
+ # self._thread_stopper = threading.Event()
42
+ if self.duration > 0:
43
+ self._thread_timer = threading.Timer(self.duration, self.finish, kwargs={"stop_service": True})
44
+ # self._worker_thread = threading.Thread(target=self._worker, args=(self._thread_stopper,))
45
+
46
+ def start(self):
47
+ self._time_started = time.time()
48
+ # self._worker_thread.start()
49
+ # background jobs should be run and controlled via a thread
50
+ self.log.info("started")
51
+ if hasattr(self, "_thread_timer"):
52
+ self.log.info("duration {0} seconds".format(self.duration))
53
+ self._thread_timer.start()
54
+ self.log.info("finish timer started")
55
+
56
+ # def _worker(self, stop_event):
57
+ # pass
58
+
59
+ def finish(self, stop_service=False):
60
+ self.log.warning("stopping")
61
+ # stop thread if necessary
62
+ if hasattr(self, "_thread_stopper"):
63
+ self._thread_stopper.set()
64
+ if hasattr(self, "_thread_timer"):
65
+ self._thread_timer.cancel()
66
+ # clean up code here
67
+ self.tracDrv.fictrac_process.terminate()
68
+ del self.tracDrv # free resource
69
+
70
+ self.log.warning(" stopped ")
71
+ # mode log file and savefilename
72
+ if stop_service:
73
+ time.sleep(2)
74
+ self.service_stop()
75
+
76
+ def disp(self):
77
+ pass
78
+
79
+ def is_busy(self):
80
+ return True # should return True/False
81
+
82
+ def test(self):
83
+ return True
84
+
85
+ def cleanup(self):
86
+ self.finish()
87
+ # your code here
88
+ return True
89
+
90
+ def info(self):
91
+ if self.is_busy():
92
+ pass # your code here
93
+ else:
94
+ return None
95
+
96
+
97
+ def cli(serializer: str = "default", port: Optional[str] = None):
98
+ if port == None:
99
+ port = BLT.SERVICE_PORT
100
+ s = BLT(serializer=serializer)
101
+ s.bind("tcp://0.0.0.0:{0}".format(port)) # broadcast on all IPs
102
+ print("running BLTZeroService")
103
+ s.run()
104
+ print("done")
105
+
106
+
107
+ if __name__ == "__main__":
108
+ defopt.run(cli)
@@ -0,0 +1,326 @@
1
+ from .ZeroService import BaseZeroService
2
+ import time
3
+ import threading
4
+ import sys
5
+ import copy
6
+ from typing import Iterable, Sequence, Optional, Dict, Any
7
+ from .utils.log_exceptions import for_all_methods, log_exceptions
8
+ from .callbacks import callbacks
9
+ import logging
10
+ import numpy as np
11
+
12
+ daqmx_import_error = None
13
+ try:
14
+ from .daq.IOTask import *
15
+
16
+ daqmx_import_error = None
17
+ except (ImportError, NameError, NotImplementedError) as daqmx_import_error:
18
+ pass
19
+
20
+
21
+ @for_all_methods(log_exceptions(logging.getLogger(__name__)))
22
+ class DAQ(BaseZeroService):
23
+ """Bundles and synchronizes analog/digital input and output tasks."""
24
+
25
+ LOGGING_PORT = 1449 # set this to range 1420-1460
26
+ SERVICE_PORT = 4249 # last to digits match logging port - but start with "42" instead of "14"
27
+ SERVICE_NAME = "DAQ" # short, uppercase, 3-letter ID of the service (equals class name)
28
+
29
+ def setup(
30
+ self,
31
+ savefilename: str = None,
32
+ play_order: Iterable = None,
33
+ playlist_info=None,
34
+ duration: float = -1,
35
+ fs: int = 10000,
36
+ dev_name="Dev1",
37
+ nb_inputsamples_per_cycle=None,
38
+ clock_source=None,
39
+ analog_chans_out: Optional[Sequence[str]] = None,
40
+ analog_chans_out_limits=None,
41
+ analog_chans_in: Sequence[str] = ["ai0"],
42
+ analog_chans_in_limits=None,
43
+ analog_chans_in_terminals=None,
44
+ digital_chans_out: Optional[Sequence[str]] = None,
45
+ analog_data_out: Optional[Sequence[np.ndarray]] = None,
46
+ digital_data_out: Optional[Sequence] = None,
47
+ metadata: Optional[Dict] = None,
48
+ params=None,
49
+ ):
50
+ """[summary]
51
+
52
+ Args:
53
+ savefilename (str, optional): [description]. Defaults to None.
54
+ play_order (Iterable, optional): [description]. Defaults to None.
55
+ playlist_info ([type], optional): [description]. Defaults to None.
56
+ duration (float, optional): [description]. Defaults to -1.
57
+ fs (int, optional): [description]. Defaults to 10000.
58
+ nb_inputsamples_per_cycle ([type], optional): [description]. Defaults to None.
59
+ clock_source (str, optional): None for AI-synced clock.
60
+ Use 'OnboardClock' for boards that don't support this (USB-DAQ).
61
+ Defaults to None.
62
+ analog_chans_out (Sequence, optional): [description]. Defaults to None.
63
+ analog_chans_in (Sequence, optional): [description]. Defaults to ['ai0'].
64
+ digital_chans_out (Sequence, optional): [description]. Defaults to None.
65
+ analog_data_out (Sequence, optional): [description]. Defaults to None.
66
+ digital_data_out (Sequence, optional): [description]. Defaults to None.
67
+ metadata (dict, optional): [description]. Defaults to {}.
68
+ params: part of prot dict (prot['DAQ'])
69
+
70
+ Raises:
71
+ ValueError: [description]
72
+ """
73
+ self.status = "initializing"
74
+
75
+ if daqmx_import_error is not None:
76
+ raise ImportError(daqmx_import_error)
77
+
78
+ self._time_started = None
79
+ self.duration = duration
80
+ self.fs = fs
81
+ self.savefilename = savefilename
82
+ self.metadata = metadata
83
+ self.playlist_info = playlist_info
84
+
85
+ self.analog_chans_out = analog_chans_out
86
+ self.analog_chans_out_limits = analog_chans_out_limits
87
+
88
+ self.analog_chans_in = analog_chans_in
89
+ self.analog_chans_in_limits = analog_chans_in_limits
90
+ self.analog_chans_in_terminals= analog_chans_in_terminals
91
+
92
+ self.digital_chans_out = digital_chans_out
93
+
94
+ # ANALOG OUTPUT
95
+ if self.analog_chans_out:
96
+ self.taskAO = IOTask(
97
+ dev_name=dev_name,
98
+ cha_name=self.analog_chans_out,
99
+ rate=fs,
100
+ clock_source=clock_source,
101
+ logger=self.log,
102
+ )
103
+ if analog_data_out[0].shape[-1] is not len(self.analog_chans_out):
104
+ raise ValueError(f"Number of analog output channels ({len(self.analog_chans_out)}) does not match the number of channels in the sound files ({analog_data_out[0].shape[-1]}).")
105
+ play_order_new = copy.deepcopy(play_order)
106
+ self.taskAO.data_gen = data_playlist(analog_data_out, play_order_new, playlist_info, self.log, name="AO")
107
+ if clock_source is None:
108
+ self.taskAO.CfgDigEdgeStartTrig("ai/StartTrigger", DAQmx_Val_Rising)
109
+ else:
110
+ self.taskAO.DisableStartTrig()
111
+ # DIGITAL OUTPUT
112
+ if self.digital_chans_out:
113
+ self.taskDO = IOTask(
114
+ dev_name=dev_name,
115
+ cha_name=self.digital_chans_out,
116
+ rate=fs,
117
+ clock_source=clock_source,
118
+ logger=self.log,
119
+ )
120
+ play_order_new = copy.deepcopy(play_order)
121
+ self.taskDO.data_gen = data_playlist(digital_data_out, play_order_new, name="DO")
122
+ if clock_source is None:
123
+ self.taskDO.CfgDigEdgeStartTrig("ai/StartTrigger", DAQmx_Val_Rising)
124
+ else:
125
+ self.taskDO.DisableStartTrig()
126
+ # ANALOG INPUT
127
+ if self.analog_chans_in:
128
+ self.taskAI = IOTask(
129
+ dev_name=dev_name,
130
+ cha_name=self.analog_chans_in,
131
+ rate=fs,
132
+ nb_inputsamples_per_cycle=nb_inputsamples_per_cycle,
133
+ clock_source=clock_source,
134
+ duration=self.duration,
135
+ logger=self.log,
136
+ )
137
+ self.taskAI.data_rec = []
138
+
139
+ self.callbacks = []
140
+ if metadata is None:
141
+ metadata = {}
142
+ attrs = {
143
+ "rate": fs,
144
+ "analog_chans_in": analog_chans_in,
145
+ "analog_chans_out": analog_chans_out,
146
+ "digital_chans_out": digital_chans_out,
147
+ **metadata,
148
+ }
149
+ common_task_kwargs = {
150
+ "file_name": self.savefilename,
151
+ "nb_inputsamples_per_cycle": nb_inputsamples_per_cycle,
152
+ "nb_analog_chans_in": len(analog_chans_in),
153
+ "attrs": attrs,
154
+ }
155
+
156
+ self.callbacks = []
157
+ if "callbacks" in params and params["callbacks"]:
158
+ for cb_name, cb_params in params["callbacks"].items():
159
+ if cb_params is not None:
160
+ task_kwargs = {**common_task_kwargs, **cb_params}
161
+ else:
162
+ task_kwargs = common_task_kwargs
163
+ callback = callbacks[cb_name].make_concurrent(task_kwargs=task_kwargs)
164
+ self.callbacks.append(callback)
165
+ self.taskAI.data_rec.append(callback)
166
+
167
+ if self.duration > 0: # if zero, will stop when nothing is to be outputted
168
+ self._thread_timer = threading.Timer(self.duration, self.finish, kwargs={"stop_service": True})
169
+ self.status = "initialized"
170
+
171
+ self.info: Dict[str, Dict[str, Any]] = dict()
172
+ self.info["job"]: Dict[str, Any] = {
173
+ "sample rate": f"{self.fs}Hz",
174
+ "analog output": self.analog_chans_out,
175
+ "digital output": self.digital_chans_out,
176
+ "analog input": self.analog_chans_in,
177
+ "duration": f"{self.duration}s",
178
+ "savefilename": self.savefilename,
179
+ "metadata": self.metadata,
180
+ }
181
+ self.info["playlist"] = self.playlist_info
182
+
183
+ def start(self):
184
+ self.status = "running"
185
+
186
+ self._time_started = time.time()
187
+
188
+ for task in self.taskAI.data_rec:
189
+ task.start()
190
+
191
+ # Arm the output tasks - won't start until the AI start is triggered
192
+ if self.analog_chans_out:
193
+ self.taskAO.StartTask()
194
+
195
+ if self.digital_chans_out:
196
+ self.taskDO.StartTask()
197
+
198
+ # Start the AI task - generates AI start trigger and triggers the output tasks
199
+ self.taskAI.StartTask()
200
+
201
+ self.log.debug("started")
202
+ if hasattr(self, "_thread_timer"):
203
+ self.log.debug("duration {0} seconds".format(self.duration))
204
+ self._thread_timer.start()
205
+ self.log.debug("finish timer started")
206
+
207
+ def finish(self, stop_service=False):
208
+ self.status = "finishing"
209
+ self.log.warning("stopping")
210
+ if hasattr(self, "_thread_stopper"):
211
+ self._thread_stopper.set()
212
+ if hasattr(self, "_thread_timer"):
213
+ self._thread_timer.cancel()
214
+
215
+ for callback in self.callbacks:
216
+ try:
217
+ callback.finish()
218
+ except Exception as e:
219
+ self.log.warning(e)
220
+
221
+ try:
222
+ self.taskAI.StopTask()
223
+ self.log.warning(" stoppedAI")
224
+ except InvalidTaskError as e:
225
+ self.log.warning(e)
226
+
227
+ # close any files in the callbacks
228
+ for callback in self.callbacks:
229
+ try:
230
+ callback.close()
231
+ except Exception as e:
232
+ self.log.warning(e)
233
+
234
+ self.taskAI.ClearTask()
235
+
236
+ # stop tasks and properly close callbacks (e.g. flush data to disk and close file)
237
+ if hasattr(self, "digital_chans_out") and self.digital_chans_out:
238
+ # try:
239
+
240
+ # self.taskDO.StopTask()
241
+ # except GenStoppedToPreventRegenOfOldSamplesError as e:
242
+ # pass
243
+ # print("\n stoppedDO")
244
+ self.taskDO.stop()
245
+
246
+ if hasattr(self, "analog_chans_out") and self.analog_chans_out:
247
+ # try:
248
+ # self.taskAO.StopTask()
249
+ # except GenStoppedToPreventRegenOfOldSamplesError as e:
250
+ # pass
251
+ # print("\n stoppedAO")
252
+ self.taskAO.stop()
253
+
254
+ if self.analog_chans_out:
255
+ self.taskAO.ClearTask()
256
+
257
+ if self.digital_chans_out:
258
+ self.taskDO.ClearTask()
259
+
260
+ self.log.warning(" stopped ")
261
+ if stop_service:
262
+ time.sleep(0.5)
263
+ self.service_stop()
264
+
265
+ def disp(self):
266
+ pass
267
+
268
+ def is_busy(self, ai=True, ao=True):
269
+ taskCheckFailed = False
270
+
271
+ taskIsDoneAI = daq.c_ulong()
272
+ if self.analog_chans_out:
273
+ taskIsDoneAO = daq.c_ulong()
274
+ if ai:
275
+ try:
276
+ self.taskAI.IsTaskDone(taskIsDoneAI)
277
+ except (
278
+ daq.InvalidTaskError,
279
+ GenStoppedToPreventRegenOfOldSamplesError,
280
+ ) as e:
281
+ taskCheckFailed = True
282
+ else:
283
+ taskIsDoneAI = 0
284
+ if ao and self.analog_chans_out:
285
+ try:
286
+ self.taskAO.IsTaskDone(taskIsDoneAO)
287
+ except (
288
+ daq.InvalidTaskError,
289
+ GenStoppedToPreventRegenOfOldSamplesError,
290
+ ) as e:
291
+ taskCheckFailed = True
292
+ else:
293
+ taskIsDoneAO = 0
294
+
295
+ return not bool(taskIsDoneAI) and not bool(taskIsDoneAO) and not taskCheckFailed
296
+
297
+ def test(self):
298
+ return True
299
+
300
+ def cleanup(self):
301
+ self.finish()
302
+ return True
303
+
304
+ def info(self):
305
+ if self.is_busy():
306
+ pass # your code here
307
+ else:
308
+ return None
309
+
310
+
311
+ if __name__ == "__main__":
312
+ daqmx_import_error = None
313
+ if len(sys.argv) > 1:
314
+ ser = sys.argv[1]
315
+ else:
316
+ ser = "default"
317
+
318
+ if len(sys.argv) > 2:
319
+ port = sys.argv[2]
320
+ else:
321
+ port = DAQ.SERVICE_PORT
322
+
323
+ logging.info("Starting DAQ service")
324
+ s = DAQ(serializer=ser) # expose class via zerorpc
325
+ s.bind("tcp://0.0.0.0:{0}".format(port)) # broadcast on all IPs
326
+ s.run()