etho-python 1.0__py3-none-any.whl → 1.2__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.
@@ -0,0 +1,476 @@
1
+ import logging
2
+ import threading
3
+ import time
4
+
5
+ import numpy as np
6
+
7
+ from . import camera
8
+ from .callbacks import callbacks
9
+
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+
14
+ class ResumableZeroService:
15
+ def __init__(self):
16
+ self.state = "new"
17
+ self.log = logger
18
+
19
+ def setup_hardware(self):
20
+ raise NotImplementedError
21
+
22
+ def prepare_run(self, *args, **kwargs):
23
+ raise NotImplementedError
24
+
25
+ def start(self):
26
+ raise NotImplementedError
27
+
28
+ def stop_run(self):
29
+ raise NotImplementedError
30
+
31
+ def close(self):
32
+ raise NotImplementedError
33
+
34
+ def information(self):
35
+ return getattr(self, "info", {})
36
+
37
+
38
+ def array_generator(data):
39
+ yield data
40
+
41
+
42
+ def close_callback(callback, sleep_time=0.05):
43
+ try:
44
+ callback.close(sleep_time=sleep_time)
45
+ except TypeError:
46
+ callback.close()
47
+
48
+
49
+ class ResumableDAQ(ResumableZeroService):
50
+ def __init__(self, params):
51
+ super().__init__()
52
+ self.params = params
53
+ self.callbacks = []
54
+ self.info = {}
55
+
56
+ def setup_hardware(self):
57
+ import etho.services.DAQZeroService as daq_service
58
+
59
+ self.log.info("Setting up DAQ hardware.")
60
+ daqmx_import_error = getattr(daq_service, "daqmx_import_error", None)
61
+ if daqmx_import_error is not None:
62
+ raise ImportError(daqmx_import_error)
63
+ if not hasattr(daq_service, "IOTask"):
64
+ raise ImportError("DAQ IOTask is unavailable. Check PyDAQmx installation.")
65
+
66
+ self.fs = self.params["samplingrate"]
67
+ self.dev_name = self.params.get("device") or "Dev1"
68
+ self.clock_source = self.params["clock_source"]
69
+ self.nb_inputsamples_per_cycle = self.params["nb_inputsamples_per_cycle"]
70
+ self.analog_chans_in = self.params["analog_chans_in"]
71
+ self.analog_chans_out = self.params["analog_chans_out"]
72
+ self.digital_chans_out = self.params["digital_chans_out"]
73
+ IOTask = daq_service.IOTask
74
+
75
+ if self.analog_chans_in:
76
+ self.taskAI = IOTask(
77
+ dev_name=self.dev_name,
78
+ cha_name=self.analog_chans_in,
79
+ rate=self.fs,
80
+ nb_inputsamples_per_cycle=self.nb_inputsamples_per_cycle,
81
+ clock_source=self.clock_source,
82
+ logger=self.log,
83
+ )
84
+ self.taskAI.data_rec = []
85
+ if self.analog_chans_out:
86
+ self.taskAO = IOTask(
87
+ dev_name=self.dev_name,
88
+ cha_name=self.analog_chans_out,
89
+ rate=self.fs,
90
+ clock_source=self.clock_source,
91
+ logger=self.log,
92
+ )
93
+ if self.digital_chans_out:
94
+ self.taskDO = IOTask(
95
+ dev_name=self.dev_name,
96
+ cha_name=self.digital_chans_out,
97
+ rate=self.fs,
98
+ clock_source=self.clock_source,
99
+ logger=self.log,
100
+ )
101
+ self.info = {
102
+ "job": {
103
+ "sample rate": f"{self.fs}Hz",
104
+ "analog output": self.analog_chans_out,
105
+ "digital output": self.digital_chans_out,
106
+ "analog input": self.analog_chans_in,
107
+ }
108
+ }
109
+ self.state = "ready"
110
+ self.log.info("DAQ hardware ready.")
111
+ return self
112
+
113
+ def prepare_run(self, savefilename, analog_data_out=None, digital_data_out=None, duration=None, metadata=None):
114
+ self.stop_run()
115
+ self.savefilename = savefilename
116
+ self.metadata = metadata or {}
117
+ self._time_started = None
118
+ self.prev_elapsed = 0
119
+ self.log.info(f"Preparing DAQ run: {savefilename}.")
120
+
121
+ if analog_data_out is not None:
122
+ analog_data_out = np.asarray(analog_data_out, dtype=np.float64)
123
+ if analog_data_out.ndim == 1:
124
+ analog_data_out = analog_data_out.reshape(-1, 1)
125
+ if digital_data_out is not None:
126
+ digital_data_out = np.asarray(digital_data_out, dtype=np.uint8)
127
+ if digital_data_out.ndim == 1:
128
+ digital_data_out = digital_data_out.reshape(-1, 1)
129
+
130
+ if duration is None:
131
+ n_samples = 0
132
+ if analog_data_out is not None:
133
+ n_samples = analog_data_out.shape[0]
134
+ if digital_data_out is not None:
135
+ n_samples = max(n_samples, digital_data_out.shape[0])
136
+ duration = n_samples / self.fs if n_samples else self.params.get("duration", -1)
137
+ self.duration = duration
138
+
139
+ if self.analog_chans_out:
140
+ if analog_data_out is None:
141
+ analog_data_out = np.zeros((int(duration * self.fs), len(self.analog_chans_out)), dtype=np.float64)
142
+ if analog_data_out.shape[1] != len(self.analog_chans_out):
143
+ raise ValueError("analog_data_out channel count does not match analog_chans_out")
144
+ self.taskAO.data_gen = array_generator(analog_data_out)
145
+ if self.digital_chans_out:
146
+ if digital_data_out is None:
147
+ digital_data_out = np.zeros((int(duration * self.fs), len(self.digital_chans_out)), dtype=np.uint8)
148
+ if digital_data_out.shape[1] != len(self.digital_chans_out):
149
+ raise ValueError("digital_data_out channel count does not match digital_chans_out")
150
+ self.taskDO.data_gen = array_generator(digital_data_out)
151
+ for task_name in ("taskAI", "taskDO", "taskAO"):
152
+ task = getattr(self, task_name, None)
153
+ if task is not None:
154
+ if hasattr(task, "samples_read"):
155
+ try:
156
+ task.samples_read.value = 0
157
+ except Exception:
158
+ pass
159
+ if hasattr(task, "_newdata_event"):
160
+ task._newdata_event.clear()
161
+
162
+ if self.analog_chans_in:
163
+ attrs = {
164
+ "rate": self.fs,
165
+ "analog_chans_in": self.analog_chans_in,
166
+ "analog_chans_out": self.analog_chans_out,
167
+ "digital_chans_out": self.digital_chans_out,
168
+ **self.metadata,
169
+ }
170
+ common = {
171
+ "file_name": self.savefilename,
172
+ "nb_inputsamples_per_cycle": self.nb_inputsamples_per_cycle,
173
+ "nb_analog_chans_in": len(self.analog_chans_in),
174
+ "attrs": attrs,
175
+ }
176
+ self.callbacks = []
177
+ self.taskAI.data_rec = []
178
+ for cb_name, cb_params in (self.params.get("callbacks") or {}).items():
179
+ task_kwargs = common if cb_params is None else {**common, **cb_params}
180
+ callback = callbacks[cb_name].make_concurrent(task_kwargs=task_kwargs)
181
+ self.callbacks.append(callback)
182
+ self.taskAI.data_rec.append(callback)
183
+ self.log.info(f" callback {cb_name}.")
184
+
185
+ if duration and duration > 0:
186
+ self._thread_timer = threading.Timer(duration, self.stop_run)
187
+ self.info = {
188
+ "job": {
189
+ "sample rate": f"{self.fs}Hz",
190
+ "analog output": self.analog_chans_out,
191
+ "digital output": self.digital_chans_out,
192
+ "analog input": self.analog_chans_in,
193
+ "duration": f"{self.duration}s",
194
+ "savefilename": self.savefilename,
195
+ "metadata": self.metadata,
196
+ }
197
+ }
198
+ self.state = "prepared"
199
+ self.log.info(f"DAQ run prepared for {self.duration}s.")
200
+ return self
201
+
202
+ def start(self):
203
+ self.log.info("Starting DAQ run.")
204
+ for callback in self.callbacks:
205
+ callback.start()
206
+ if self.analog_chans_out:
207
+ self.taskAO.StartTask()
208
+ if self.digital_chans_out:
209
+ self.taskDO.StartTask()
210
+ if self.analog_chans_in:
211
+ self.taskAI.StartTask()
212
+ self._time_started = time.time()
213
+ self.prev_elapsed = 0
214
+ if hasattr(self, "_thread_timer"):
215
+ self._thread_timer.start()
216
+ self.state = "running"
217
+ self.log.info("DAQ run started.")
218
+
219
+ def stop_run(self):
220
+ was_active = self.state in {"prepared", "running"}
221
+ if self.state == "running":
222
+ self.log.info("Stopping DAQ run.")
223
+ if hasattr(self, "_thread_timer"):
224
+ self._thread_timer.cancel()
225
+ del self._thread_timer
226
+ for task_name in ("taskAI", "taskDO", "taskAO"):
227
+ task = getattr(self, task_name, None)
228
+ if task is not None:
229
+ try:
230
+ task.StopTask()
231
+ except Exception as e:
232
+ self.log.debug(e)
233
+ for callback in self.callbacks:
234
+ try:
235
+ callback.finish()
236
+ close_callback(callback)
237
+ except Exception as e:
238
+ self.log.debug(e)
239
+ self.callbacks = []
240
+ if hasattr(self, "taskAI"):
241
+ self.taskAI.data_rec = []
242
+ if hasattr(self, "taskAO"):
243
+ self.taskAO.data_gen = None
244
+ if hasattr(self, "taskDO"):
245
+ self.taskDO.data_gen = None
246
+ if self.state != "new":
247
+ self.state = "stopped"
248
+ if was_active:
249
+ self.log.info("DAQ run stopped.")
250
+
251
+ def close(self):
252
+ self.stop_run()
253
+ self.log.info("Closing DAQ hardware.")
254
+ for task_name in ("taskAI", "taskDO", "taskAO"):
255
+ task = getattr(self, task_name, None)
256
+ if task is not None:
257
+ try:
258
+ task.ClearTask()
259
+ except Exception as e:
260
+ self.log.debug(e)
261
+ self.state = "closed"
262
+ self.log.info("DAQ hardware closed.")
263
+
264
+ def progress(self):
265
+ elapsed = time.time() - self._time_started if getattr(self, "_time_started", None) else 0
266
+ elapsed_delta = elapsed - getattr(self, "prev_elapsed", 0)
267
+ self.prev_elapsed = elapsed
268
+ return {
269
+ "total": self.duration if getattr(self, "duration", None) else 0,
270
+ "elapsed": elapsed,
271
+ "elapsed_delta": elapsed_delta,
272
+ "elapsed_units": "seconds",
273
+ }
274
+
275
+
276
+ class ResumableGCM(ResumableZeroService):
277
+ def __init__(self, params):
278
+ super().__init__()
279
+ self.params = params
280
+ self.callbacks = []
281
+ self.callback_names = []
282
+ self.frameNumber = 0
283
+ self.prev_framenumber = 0
284
+ self.prev_elapsed = 0
285
+ self.info = {}
286
+
287
+ def setup_hardware(self):
288
+ self.log.info("Setting up camera hardware.")
289
+ params = {
290
+ "binning": 1,
291
+ "gamma": 1,
292
+ "gain": 0,
293
+ "brightness": 0,
294
+ "optimize_auto_exposure": False,
295
+ "external_trigger": False,
296
+ "frame_offx": 0,
297
+ "frame_offy": 0,
298
+ **self.params,
299
+ }
300
+ self.params = params
301
+ self.c = camera.make[params["cam_type"]](str(params["cam_serialnumber"]))
302
+ try:
303
+ self.c.init()
304
+ except Exception:
305
+ self.c.reset()
306
+ self.c.init()
307
+
308
+ self.c.roi = [params["frame_offx"], params["frame_offy"], params["frame_width"], params["frame_height"]]
309
+ self.c.exposure = params["shutter_speed"]
310
+ self.c.brightness = params["brightness"]
311
+ self.c.gamma = params["gamma"]
312
+ self.c.gain = params["gain"]
313
+ self.c.framerate = params["frame_rate"]
314
+ self.c.binning = params["binning"]
315
+ if params["optimize_auto_exposure"]:
316
+ self.c.optimize_auto_exposure()
317
+
318
+ self.c.disable_gpio_strobe()
319
+ self.c.external_trigger = False
320
+ self.c.start()
321
+ self.test_image, _, _ = self.c.get()
322
+ self.c.stop()
323
+ self.c.external_trigger = params["external_trigger"]
324
+
325
+ self.frame_width, self.frame_height, self.frame_channels = self.test_image.shape
326
+ self.framerate = self.c.framerate
327
+ self.info = self._information(savefilename=None, duration=None, callbacks={})
328
+ self.state = "ready"
329
+ self.log.info("Camera hardware ready.")
330
+ return self
331
+
332
+ def _information(self, savefilename, duration, callbacks):
333
+ iii = self.c.info_imaging() if hasattr(self.c, "info_imaging") else {}
334
+ if "exposure" in iii:
335
+ iii["exposure"] = f"{iii['exposure']:1.2f}ms"
336
+ params = dict(self.params)
337
+ params["exposure"] = f"{params['shutter_speed'] / 1_000:1.2f}ms"
338
+ params["framerate"] = params["frame_rate"]
339
+ params["offsetX"], params["offsetY"], params["width"], params["height"] = (
340
+ params["frame_offx"],
341
+ params["frame_offy"],
342
+ params["frame_width"],
343
+ params["frame_height"],
344
+ )
345
+ hii = self.c.info_hardware() if hasattr(self.c, "info_hardware") else {}
346
+ try:
347
+ hii.update({k: v if v is not None else "defaults" for k, v in callbacks.items()})
348
+ except AttributeError:
349
+ pass
350
+ if savefilename is not None:
351
+ hii["savefilename"] = savefilename
352
+ if duration is not None:
353
+ hii["duration"] = duration
354
+ return {"hardware": hii, "image": (iii, params)}
355
+
356
+ def prepare_run(self, savefilename, duration, preview=False):
357
+ self.stop_run()
358
+ self.savefilename = savefilename
359
+ self.duration = duration
360
+ self.nFrames = int(self.framerate * duration + 100)
361
+ self.frameNumber = 0
362
+ self.prev_framenumber = 0
363
+ self.prev_elapsed = 0
364
+ if hasattr(self.c, "_t0"):
365
+ self.c._t0 = time.time()
366
+ self.callbacks = []
367
+ self.callback_names = []
368
+ self.log.info(f"Preparing camera run: {savefilename}.")
369
+ common = {
370
+ "file_name": self.savefilename,
371
+ "frame_rate": self.framerate,
372
+ "frame_height": self.frame_height,
373
+ "frame_width": self.frame_width,
374
+ }
375
+ run_callbacks = {"disp_fast": None} if preview else (self.params.get("callbacks") or {})
376
+ for cb_name, cb_params in run_callbacks.items():
377
+ task_kwargs = common if cb_params is None else {**common, **cb_params}
378
+ self.callbacks.append(callbacks[cb_name].make_concurrent(task_kwargs=task_kwargs))
379
+ self.callback_names.append(cb_name)
380
+ self.log.info(f" callback {cb_name}.")
381
+ self._thread_stopper = threading.Event()
382
+ self._worker_thread = threading.Thread(target=self._worker, args=(self._thread_stopper,))
383
+ if duration and duration > 0:
384
+ self._thread_timer = threading.Timer(duration, self.stop_run)
385
+ self.info = self._information(self.savefilename, self.duration, run_callbacks)
386
+ self.state = "prepared"
387
+ self.log.info(f"Camera run prepared for {self.duration}s.")
388
+ return self
389
+
390
+ def start(self):
391
+ self.log.info("Starting camera run.")
392
+ for callback in self.callbacks:
393
+ callback.start()
394
+ self._time_started = time.time()
395
+ self.prev_elapsed = 0
396
+ self._prev_elapsed = 0
397
+ self._worker_thread.start()
398
+ if hasattr(self, "_thread_timer"):
399
+ self._thread_timer.start()
400
+ self.state = "running"
401
+ self.log.info("Camera run started.")
402
+
403
+ def _worker(self, stop_event):
404
+ self.log.info("Camera worker started.")
405
+ self.c.enable_gpio_strobe()
406
+ self.c.start()
407
+ while not stop_event.is_set() and self.frameNumber < self.nFrames:
408
+ try:
409
+ image, image_ts, system_ts = self.c.get()
410
+ except Exception as e:
411
+ self.log.exception("Camera get failed", exc_info=e)
412
+ break
413
+ for callback_name, callback in zip(self.callback_names, self.callbacks):
414
+ package = (0, (system_ts, image_ts)) if "timestamps" in callback_name else (image, (system_ts, image_ts))
415
+ callback.send(package)
416
+ self.frameNumber += 1
417
+ try:
418
+ self.c.stop()
419
+ except Exception:
420
+ pass
421
+ self.log.info("Camera worker stopped.")
422
+
423
+ def stop_run(self):
424
+ was_active = self.state in {"prepared", "running"}
425
+ if self.state == "running":
426
+ self.log.info("Stopping camera run.")
427
+ if hasattr(self, "_thread_timer"):
428
+ self._thread_timer.cancel()
429
+ del self._thread_timer
430
+ if hasattr(self, "_thread_stopper"):
431
+ self._thread_stopper.set()
432
+ try:
433
+ self.c.disable_gpio_strobe()
434
+ self.c.stop()
435
+ except Exception:
436
+ pass
437
+ if hasattr(self, "_worker_thread") and self._worker_thread.is_alive():
438
+ self._worker_thread.join(timeout=0.5)
439
+ for callback in self.callbacks:
440
+ try:
441
+ callback.finish()
442
+ close_callback(callback)
443
+ except Exception as e:
444
+ self.log.debug(e)
445
+ self.callbacks = []
446
+ self.callback_names = []
447
+ if self.state != "new":
448
+ self.state = "stopped"
449
+ if was_active:
450
+ self.log.info("Camera run stopped.")
451
+
452
+ def close(self):
453
+ self.stop_run()
454
+ self.log.info("Closing camera hardware.")
455
+ try:
456
+ self.c.close()
457
+ except Exception:
458
+ pass
459
+ self.state = "closed"
460
+ self.log.info("Camera hardware closed.")
461
+
462
+ def progress(self):
463
+ elapsed = time.time() - self._time_started if getattr(self, "_time_started", None) else 0
464
+ elapsed_delta = elapsed - getattr(self, "prev_elapsed", 0)
465
+ frame_delta = self.frameNumber - self.prev_framenumber
466
+ self.prev_framenumber = self.frameNumber
467
+ self.prev_elapsed = elapsed
468
+ return {
469
+ "total": self.duration if getattr(self, "duration", None) else 0,
470
+ "elapsed": elapsed,
471
+ "elapsed_delta": elapsed_delta,
472
+ "elapsed_units": "seconds",
473
+ "framenumber": self.frameNumber,
474
+ "framenumber_delta": frame_delta,
475
+ "framenumber_units": "frames",
476
+ }