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,456 @@
1
+ """Callbacks for processing time series."""
2
+
3
+ import logging
4
+ import numpy as np
5
+ from numpy.core.numeric import False_
6
+ import scipy.signal as ss
7
+
8
+ from ..utils.concurrent_task import ConcurrentTask
9
+ from ..utils.log_exceptions import for_all_methods, log_exceptions
10
+ from . import register_callback
11
+ from typing import List
12
+ from ._base import BaseCallback
13
+
14
+ try:
15
+ import tables
16
+
17
+ tables_import_error = None
18
+ except ImportError as tables_import_error:
19
+ pass
20
+
21
+ try:
22
+ import peakutils
23
+ except ImportError:
24
+ pass
25
+
26
+ try:
27
+ from qtpy import QtWidgets
28
+ import pyqtgraph as pg
29
+
30
+ pyqtgraph_import_error = None
31
+ except Exception as pyqtgraph_import_error: # catch generic Exception to cover missing Qt error from pyqtgraph
32
+ pass
33
+
34
+ try:
35
+ import zarr
36
+ from numcodecs import Blosc
37
+
38
+ zarr_import_error = None
39
+ except Exception as zarr_import_error: # catch generic Exception to cover missing Qt error from pyqtgraph
40
+ pass
41
+
42
+ logger = logging.getLogger(__name__)
43
+
44
+
45
+ @for_all_methods(log_exceptions(logger))
46
+ @register_callback
47
+ class PlotMPL(BaseCallback):
48
+ FRIENDLY_NAME = "plot"
49
+
50
+ def __init__(self, data_source, *, poll_timeout=0.01, channels_to_plot: List, nb_samples: int = 10_000, **kwargs):
51
+ super().__init__(data_source=data_source, poll_timeout=poll_timeout, **kwargs)
52
+ self.channels_to_plot = channels_to_plot
53
+ self.nb_channels = len(self.channels_to_plot)
54
+ self.nb_samples = nb_samples
55
+
56
+ import matplotlib
57
+
58
+ matplotlib.use("tkagg")
59
+ import matplotlib.pyplot as plt
60
+
61
+ plt.ion()
62
+ self.fig = plt.figure()
63
+ self.fig.canvas.set_window_title("traces: daq")
64
+ self.ax = [self.fig.add_subplot(self.nb_channels, 1, channel + 1) for channel in range(self.nb_channels)]
65
+ plt.show(block=False)
66
+ plt.draw()
67
+ self.fig.canvas.start_event_loop(0.01) # otherwise plot freezes after 3-4 iterations
68
+ self.bgrd = [self.fig.canvas.copy_from_bbox(this_ax.bbox) for this_ax in self.ax]
69
+ self.points = [ax.plot(np.arange(self.nb_samples), np.zeros((self.nb_samples, 1)), linewidth=0.4)[0] for ax in self.ax] # init plot content
70
+ [ax.set_ylim(-5, 5) for ax in self.ax] # init plot content
71
+ [ax.set_xlim(0, self.nb_samples) for ax in self.ax] # init plot content
72
+ for cnt, ax in enumerate(self.fig.get_axes()[::-1]):
73
+ ax.label_outer()
74
+ ax.spines["top"].set_visible(False)
75
+ ax.spines["right"].set_visible(False)
76
+ plt.show(block=False)
77
+ plt.draw()
78
+
79
+ def _loop(self, data):
80
+ data_to_plot, timestamp = data
81
+ self.nb_samples = data_to_plot.shape[0]
82
+ x = np.arange(self.nb_samples)
83
+ for ax, bgrd, points, chn in zip(self.ax, self.bgrd, self.points, self.channels_to_plot):
84
+ self.fig.canvas.restore_region(bgrd) # restore background
85
+ points.set_data(x, data_to_plot[: self.nb_samples, chn])
86
+ ax.draw_artist(points) # redraw just the points
87
+ self.fig.canvas.blit(ax.bbox) # fill in the axes rectangle
88
+ self.fig.canvas.draw()
89
+ self.fig.canvas.flush_events()
90
+
91
+
92
+ @for_all_methods(log_exceptions(logger))
93
+ @register_callback
94
+ class PlotPQG(BaseCallback):
95
+ FRIENDLY_NAME = "plot_fast"
96
+
97
+ def __init__(self, data_source, *, poll_timeout=0.01, channels_to_plot: List, nb_samples: int = 10_000, **kwargs):
98
+ super().__init__(data_source=data_source, poll_timeout=poll_timeout, **kwargs)
99
+
100
+ if pyqtgraph_import_error is not None:
101
+ logger.exception("Could not import pyqtgraph. Aborting!", exc_info=pyqtgraph_import_error)
102
+ raise pyqtgraph_import_error
103
+
104
+ self.channels_to_plot = channels_to_plot
105
+ self.nb_channels = len(self.channels_to_plot)
106
+ self.nb_samples = nb_samples
107
+
108
+ pg.setConfigOption("background", "w")
109
+ pg.setConfigOption("leftButtonPan", False)
110
+
111
+ # set up window and subplots
112
+ self.app = QtWidgets.QApplication([])
113
+ self.win = pg.GraphicsLayoutWidget(title="DAQ")
114
+ self.win.resize(1000, min(100 * self.nb_channels, 1000))
115
+ self.p = []
116
+ for row in range(self.nb_channels):
117
+ w = self.win.addPlot(row=row, col=0, y=np.zeros((self.nb_samples,)))
118
+ w.setXRange(0, self.nb_samples, padding=0)
119
+ w.setYRange(-5, 5)
120
+ w.setMouseEnabled(x=False, y=False)
121
+ w.enableAutoRange("xy", False_)
122
+ self.p.append(w.plot(pen="k"))
123
+ print(self.p)
124
+ self.win.show()
125
+ self.app.processEvents()
126
+
127
+ def _loop(self, data):
128
+ data_to_plot, timestamp = data
129
+ for plot, chan in zip(self.p, self.channels_to_plot):
130
+ plot.setData(data_to_plot[:, chan])
131
+ self.app.processEvents()
132
+
133
+
134
+ @for_all_methods(log_exceptions(logger))
135
+ @register_callback
136
+ class SaveHDF(BaseCallback):
137
+ FRIENDLY_NAME = "save_h5"
138
+ SUFFIX = "_daq.h5"
139
+
140
+ def __init__(self, data_source, *, file_name, attrs=None, poll_timeout=0.01, **kwargs):
141
+ super().__init__(data_source=data_source, poll_timeout=poll_timeout, **kwargs)
142
+
143
+ if tables_import_error is not None:
144
+ logger.exception("Could not import tables. Aborting!", exc_info=tables_import_error)
145
+ raise tables_import_error
146
+ self.file_name = file_name
147
+ self.f = tables.open_file(self.file_name + self.SUFFIX, mode="w")
148
+ self.vanilla: bool = True
149
+ self.arrays = dict()
150
+ self.attrs = attrs
151
+
152
+ @classmethod
153
+ def make_concurrent(cls, task_kwargs, comms="queue"):
154
+ return ConcurrentTask(task=cls.make_run, task_kwargs=task_kwargs, comms=comms)
155
+
156
+ def _init_data(self, data, systemtime):
157
+ filters = tables.Filters(complevel=4, complib="zlib", fletcher32=True)
158
+
159
+ self.arrays["samples"] = self.f.create_earray(
160
+ self.f.root,
161
+ "samples",
162
+ tables.Atom.from_dtype(data.dtype),
163
+ shape=[0, *data.shape[1:]],
164
+ chunkshape=[*data.shape],
165
+ filters=filters,
166
+ )
167
+ if self.attrs is not None:
168
+ for key, val in self.attrs.items():
169
+ self.arrays["samples"].attrs[key] = val
170
+
171
+ self.arrays["systemtime"] = self.f.create_earray(
172
+ self.f.root,
173
+ "systemtime",
174
+ tables.Atom.from_dtype(np.array(systemtime).dtype),
175
+ shape=[0, 1],
176
+ chunkshape=[100, 1],
177
+ filters=filters,
178
+ )
179
+
180
+ samplenumber = self.f.root["samples"].shape[:1]
181
+ self.arrays["samplenumber"] = self.f.create_earray(
182
+ self.f.root,
183
+ "samplenumber",
184
+ tables.Atom.from_dtype(np.array([samplenumber])[:, np.newaxis].dtype),
185
+ shape=[0, 1],
186
+ chunkshape=[100, 1],
187
+ filters=filters,
188
+ )
189
+ # print([(k, v.shape) for k, v in self.arrays.items()])
190
+
191
+ def _append_data(self, data, systemtime):
192
+ # print(data.shape, self.arrays["samples"].shape, self.arrays["samplenumber"].shape)
193
+ self.arrays["samples"].append(data)
194
+
195
+ samplenumber = data.shape[:1] # self.f.root['samples'].shape[:1]
196
+ self.arrays["samplenumber"].append(np.array([samplenumber]))
197
+
198
+ self.arrays["systemtime"].append(systemtime)
199
+
200
+ def _loop(self, data):
201
+ data_to_save, systemtime = data # unpack
202
+ sn = np.array([systemtime])[:, np.newaxis]
203
+ if self.vanilla:
204
+ self._init_data(data_to_save, sn)
205
+ self.vanilla = False
206
+ self._append_data(data_to_save, sn)
207
+
208
+ def _cleanup(self):
209
+ logger.warning("cleaning")
210
+ if self.f.isopen:
211
+ self.f.flush()
212
+ self.f.close()
213
+ else:
214
+ logger.debug(f"{self.file_name} already closed.")
215
+
216
+
217
+ @for_all_methods(log_exceptions(logger))
218
+ @register_callback
219
+ class SaveZarr(BaseCallback):
220
+ FRIENDLY_NAME = "save_zarr"
221
+ SUFFIX = "_daq.zarr"
222
+
223
+ def __init__(self, data_source, *, file_name, attrs=None, poll_timeout=0.01, **kwargs):
224
+ super().__init__(data_source=data_source, poll_timeout=poll_timeout, **kwargs)
225
+
226
+ if zarr_import_error is not None:
227
+ logger.exception("Could not import zarr. Aborting!", exc_info=tables_import_error)
228
+ raise zarr_import_error
229
+ self.file_name = file_name
230
+ self.f = zarr.DirectoryStore(self.file_name + self.SUFFIX)
231
+ self.vanilla: bool = True
232
+ self.arrays = zarr.group(self.f, overwrite=True)
233
+
234
+ self.attrs = attrs
235
+
236
+ @classmethod
237
+ def make_concurrent(cls, task_kwargs, comms="queue"):
238
+ return ConcurrentTask(task=cls.make_run, task_kwargs=task_kwargs, comms=comms)
239
+
240
+ def _init_data(self, data, systemtime):
241
+ compressor = Blosc(cname="zstd", clevel=3, shuffle=Blosc.BITSHUFFLE)
242
+
243
+ self.arrays.create_dataset("samples", shape=(0, *data.shape[1:]), chunks=data.shape, dtype=data.dtype, compressor=compressor)
244
+
245
+ if self.attrs is not None:
246
+ for key, val in self.attrs.items():
247
+ self.arrays["samples"].attrs[key] = val
248
+
249
+ self.arrays.create_dataset("systemtime", shape=(0, 1), chunks=True, dtype=systemtime.dtype, compressor=compressor)
250
+
251
+ sn = np.array(data.shape[:1])[:, np.newaxis]
252
+ self.arrays.create_dataset("samplenumber", shape=(0, 1), chunks=True, dtype=sn.dtype, compressor=compressor)
253
+ # print([(k, v.shape) for k, v in self.arrays.items()])
254
+
255
+ def _append_data(self, data, systemtime):
256
+ # print(data.shape, self.arrays["samples"].shape, self.arrays["samplenumber"].shape)
257
+ self.arrays["samples"].append(data, axis=0)
258
+
259
+ samplenumber = np.array(data.shape[:1])[:, np.newaxis] # self.f.root['samples'].shape[:1]
260
+ self.arrays["samplenumber"].append(samplenumber, axis=0)
261
+
262
+ self.arrays["systemtime"].append(systemtime, axis=0)
263
+
264
+ def _loop(self, data):
265
+ data_to_save, systemtime = data # unpack
266
+ sn = np.array([systemtime])[:, np.newaxis]
267
+ if self.vanilla:
268
+ self._init_data(data_to_save, sn)
269
+ self.vanilla = False
270
+ self._append_data(data_to_save, sn)
271
+
272
+ def _cleanup(self):
273
+ logger.warning("cleaning")
274
+ try:
275
+ self.f.close()
276
+ except:
277
+ logger.debug(f"{self.file_name} already closed.")
278
+
279
+
280
+ @for_all_methods(log_exceptions(logger))
281
+ @register_callback
282
+ class SaveDLP_HDF(BaseCallback):
283
+ """
284
+ Save dict of dicts of single values to h5.
285
+ First dict's keys map to groups, second dict's keys to variables.
286
+ """
287
+
288
+ FRIENDLY_NAME = "savedlp_h5"
289
+ SUFFIX = "_dlp.h5"
290
+
291
+ def __init__(self, data_source, *, file_name, attrs=None, poll_timeout=0.01, **kwargs):
292
+ super().__init__(data_source=data_source, poll_timeout=poll_timeout, **kwargs)
293
+
294
+ if tables_import_error is not None:
295
+ logger.exception("Could not import tables. Aborting!", exc_info=tables_import_error)
296
+ raise tables_import_error
297
+
298
+ self.file_name = file_name
299
+ self.f = tables.open_file(self.file_name + self.SUFFIX, mode="w")
300
+ self.vanilla: bool = True # True if the data structure has not been initialized (via `_init_data`)
301
+ self.arrays = dict()
302
+
303
+ @classmethod
304
+ def make_concurrent(cls, task_kwargs, comms="queue"):
305
+ return ConcurrentTask(task=cls.make_run, task_kwargs=task_kwargs, comms=comms)
306
+
307
+ def _init_data(self, data, systemtime):
308
+ filters = tables.Filters(complevel=4, complib="zlib", fletcher32=True)
309
+ for grp_name, grp_data in data.items():
310
+ group = self.f.create_group("/", name=grp_name)
311
+ self.arrays[grp_name] = dict()
312
+ for key, val in grp_data.items():
313
+ self.arrays[grp_name][key] = self.f.create_earray(group, key, tables.Atom.from_dtype(np.array(val).dtype), shape=(0,), chunkshape=(1000,), filters=filters)
314
+
315
+ self.arrays["systemtime"] = self.f.create_earray(self.f.root, "systemtime", tables.Atom.from_dtype(systemtime.dtype), shape=(0,), chunkshape=(1000,), filters=filters)
316
+ self.vanilla = False
317
+
318
+ def _append_data(self, data, systemtime):
319
+ for grp_name, grp_data in data.items():
320
+ for key, val in grp_data.items():
321
+ self.arrays[grp_name][key].append(np.array([val]))
322
+ self.arrays["systemtime"].append(systemtime)
323
+
324
+ def _loop(self, data):
325
+ data_to_save, systemtime = data # unpack
326
+ if self.vanilla:
327
+ self._init_data(data_to_save, np.array([systemtime]))
328
+ self._append_data(data_to_save, np.array([systemtime]))
329
+
330
+ def _cleanup(self):
331
+ if self.f.isopen:
332
+ self.f.flush()
333
+ self.f.close()
334
+ else:
335
+ logging.debug(f"{self.file_name} already closed.")
336
+
337
+
338
+ @for_all_methods(log_exceptions(logger))
339
+ @register_callback
340
+ class RealtimeDSS(BaseCallback):
341
+ def __init__(self, data_source, *, poll_timeout=0.01, model_save_name: str = None, **kwargs):
342
+ super().__init__(data_source=data_source, poll_timeout=poll_timeout, **kwargs)
343
+ """Coroutine for rt processing of data."""
344
+ from utils.zeroclient import ZeroClient
345
+ from services.ANAZeroService import ANA
346
+ import subprocess
347
+ import tensorflow as tf
348
+ import das
349
+ import das.utils
350
+ import das.event_utils
351
+
352
+ print(" started RT processing")
353
+ ip_address = "localhost"
354
+ # init DAQ for output
355
+ self.nit = ZeroClient(ip_address, "nidaq")
356
+ self.sp = subprocess.Popen("python -m ethoservice.ANAZeroService")
357
+ self.nit.connect("tcp://{0}:{1}".format(ip_address, ANA.SERVICE_PORT))
358
+ self.nit.setup(-1, 0)
359
+ # nit.init_local_logger('{0}/{1}/{1}_nit.log'.format(daq_save_folder, filename))
360
+
361
+ self.samplerate = 10_000 # make sure audio data and the annotations are all on the same sampling rate
362
+ # bandpass to get rid of slow baseline fluctuations and high-freuqency ripples
363
+ self.sos_bp = ss.butter(5, [50, 1000], "bandpass", output="sos", fs=self.samplerate)
364
+
365
+ print("preparing network")
366
+ # model_save_name = 'C:/Users/ncb.UG-MGEN/dss/vibrations1024/20191109_074320'
367
+ # model_save_name = 'C:/Users/ncb.UG-MGEN/dss/vibrations4096/20191108_235948'
368
+ # model_save_name = 'C:/Users/ncb.UG-MGEN/dss/vibrations8192/20191109_080559'
369
+ self.model_save_name = model_save_name
370
+ self.model, self.params = das.utils.load_model_and_params(self.model_save_name)
371
+ self.input_shape = self.model.inputs[0].shape[1:]
372
+ self.model.predict(np.zeros((1, *self.input_shape))) # use model.input_shape
373
+
374
+ self.data_buffer = np.zeros(self.input_shape)
375
+ self.started = False
376
+
377
+ @classmethod
378
+ def make_concurrent(cls, task_kwargs, comms="array"):
379
+ return ConcurrentTask(task=cls.make_run, task_kwargs=task_kwargs, comms=comms)
380
+
381
+ def _append_to_buffer(self, buffer, x):
382
+ buffer = np.roll(buffer, shift=-x.shape[0], axis=0)
383
+ buffer[-len(x) :, ...] = x
384
+ return buffer
385
+
386
+ def _loop(self, data):
387
+ # TODO: save raw data, filtered data and prediction to file...
388
+ data = data[:, : self.input_shape[-1]]
389
+ data = ss.sosfiltfilt(self.sos_bp, data, axis=0).astype(np.float16)
390
+ self.data_buffer = self._append_to_buffer(self.data_buffer, data)
391
+ batch = self.data_buffer.reshape((1, *self.data_buffer.shape)) # model expects [nb_batches, nb_samples=1024, nb_channels=16]
392
+ # batch = data.reshape((1, *data.shape)) # model expects [nb_batches, nb_samples=1024, nb_channels=16]
393
+ prediction = self.model.predict(batch)
394
+
395
+ # detect vibration pulses:
396
+ # pulsetimes_pred, pulsetimes_pred_confidence = dss.event_utils.detect_events((prediction[0, ..., 1]>0.2).astype(np.float), thres=0.5, min_dist=500)
397
+ pulsetimes_pred = peakutils.indexes(prediction[0, ..., 1], thres=0.25, min_dist=500, thres_abs=True)
398
+
399
+ # filter vibrations by preceding IPI
400
+ min_ipi = 1000 # 100ms
401
+ max_ipi = 2000 # 200ms
402
+ good_pulses = np.logical_and(np.diff(pulsetimes_pred, append=0) > min_ipi, np.diff(pulsetimes_pred, append=0) < max_ipi)
403
+ print(pulsetimes_pred, pulsetimes_pred[good_pulses])
404
+ pulsetimes_pred = pulsetimes_pred[good_pulses]
405
+ vibrations_present = len(pulsetimes_pred) > 1
406
+
407
+ if not self.started and vibrations_present:
408
+ print(" sending START")
409
+ self.nit.send_trigger(1.5, duration=3)
410
+ self.started = True
411
+ elif self.started and not vibrations_present:
412
+ self.nit.send_trigger(0, duration=None)
413
+ self.started = False
414
+
415
+ def _cleanup(self):
416
+ print(" stopped RT processing")
417
+ self.nit.send_trigger(0, duration=None)
418
+ self.nit.finish()
419
+ self.nit.stop_server()
420
+ del self.nit
421
+ self.sp.terminate()
422
+ self.sp.kill()
423
+
424
+
425
+ if __name__ == "__main__":
426
+ import time
427
+
428
+ # ct = PlotPQG.make_concurrent(task_kwargs={'channels_to_plot': [0, 2], 'rate': .1}, comms='pipe')
429
+ # ct.start()
430
+ # for _ in range(100000):
431
+ # timestamp = time.time()
432
+ # ct.send((np.random.randn(10_000, 4), timestamp))
433
+ # ct.finish()
434
+ # ct.close()
435
+
436
+ # ct = SaveHDF.make_concurrent({"file_name": "test"})
437
+ # ct.start()
438
+ # for _ in range(10):
439
+ # timestamp = time.time()
440
+ # print(timestamp)
441
+ # # ct.send((np.random.randn(10_000, 4), timestamp))
442
+ # ct.send((np.zeros((10_000, 4)), timestamp))
443
+ # time.sleep(1)
444
+ # ct.finish()
445
+ # ct.close()
446
+
447
+ ct = SaveZarr.make_concurrent({"file_name": "test"})
448
+ ct.start()
449
+ for _ in range(10):
450
+ timestamp = time.time()
451
+ print(timestamp)
452
+ # ct.send((np.random.randn(10_000, 4), timestamp))
453
+ ct.send((np.zeros((10_000, 4)), timestamp))
454
+ time.sleep(1)
455
+ ct.finish()
456
+ ct.close()
@@ -0,0 +1,13 @@
1
+ from .spinnaker import Spinnaker
2
+ from .ximea import Ximea
3
+ from .basler import Basler
4
+ from .hamamatsu import Hamamatsu
5
+ from .dummy import Dummy
6
+
7
+ make = {
8
+ "Spinnaker": Spinnaker,
9
+ "Ximea": Ximea,
10
+ "Basler": Basler,
11
+ "Hamamatsu": Hamamatsu,
12
+ "Dummy": Dummy,
13
+ }
@@ -0,0 +1,164 @@
1
+ import numpy as np
2
+ from typing import Tuple, Optional, Dict, Any
3
+
4
+
5
+ def gray2rgb(image: np.ndarray) -> np.ndarray:
6
+ if image.shape[-1] != 3:
7
+ image = np.tile(image, (1, 1, 3))
8
+ return image
9
+
10
+
11
+ class BaseCam:
12
+ def __init__(self, serialnumber: int):
13
+ """[summary]
14
+
15
+ Should set:
16
+ - continuous acq
17
+ - anything that optimizes throughput
18
+ - pixel format
19
+ - time stamping
20
+ - init pointer to image
21
+
22
+ Args:
23
+ serialnumber ([type]): [description]
24
+ """
25
+ self.serialnumber: int = serialnumber
26
+
27
+ def init(self):
28
+ pass
29
+
30
+ def get(self, timeout: Optional[float] = None) -> Tuple[np.ndarray, float, float]:
31
+ """
32
+
33
+ pull image from cam, convert to np.ndarray, get time stamp
34
+
35
+ Args:
36
+ timeout (Optional[float], optional): [description]. Defaults to None.
37
+
38
+ Returns:
39
+ Tuple[np.ndarray, float, float]:
40
+ image as np.array (x,y,c)
41
+ image_timestamp (in seconds UTC)
42
+ system_timestamp (in seconds UTC)
43
+
44
+ Raises:
45
+ ValueError is sth goes wrong
46
+ """
47
+ pass
48
+
49
+ def _estimate_timestamp_offset(self) -> float:
50
+ """[summary]
51
+
52
+ Returns:
53
+ float: Timestamp offset rel to system time.
54
+ Return 0 if timestamps are already in system time.
55
+ """
56
+ pass
57
+
58
+ def optimize_auto_exposure(self):
59
+ pass
60
+
61
+ @property
62
+ def roi(self) -> Tuple[int, int, int, int]:
63
+ pass
64
+
65
+ @roi.setter
66
+ def roi(self, x0_y0_x_y: Tuple[int, int, int, int]):
67
+ pass
68
+
69
+ @property
70
+ def brightness(self) -> float:
71
+ pass
72
+
73
+ @brightness.setter
74
+ def brightness(self, value: float):
75
+ pass
76
+
77
+ @property
78
+ def exposure(self) -> float:
79
+ pass
80
+
81
+ @exposure.setter
82
+ def exposure(self, value: float):
83
+ pass
84
+
85
+ @property
86
+ def gain(self) -> float:
87
+ pass
88
+
89
+ @gain.setter
90
+ def gain(self, value: float):
91
+ pass
92
+
93
+ @property
94
+ def gamma(self) -> float:
95
+ pass
96
+
97
+ @gamma.setter
98
+ def gamma(self, value: float):
99
+ pass
100
+
101
+ @property
102
+ def framerate(self) -> float:
103
+ return self._framerate
104
+
105
+ @framerate.setter
106
+ def framerate(self, value: float):
107
+ self._framerate = value
108
+
109
+ @property
110
+ def external_trigger(self):
111
+ pass
112
+
113
+ @external_trigger.setter
114
+ def external_trigger(self, value: bool = False):
115
+ pass
116
+
117
+ @property
118
+ def binning(self):
119
+ pass
120
+
121
+ @binning.setter
122
+ def binning(self, value: int = 1):
123
+ pass
124
+
125
+ def enable_gpio_strobe(self):
126
+ pass
127
+
128
+ def disable_gpio_strobe(self):
129
+ pass
130
+
131
+ def start(self):
132
+ pass
133
+
134
+ def stop(self):
135
+ pass
136
+
137
+ def close(self):
138
+ pass
139
+
140
+ def reset(self):
141
+ """Reset the camera system to free all resources."""
142
+ pass
143
+
144
+ def info_hardware(self):
145
+ return {
146
+ "Serial number": self.serialnumber,
147
+ "Camera model": self.__class__,
148
+ }
149
+
150
+ def info_imaging(self):
151
+ x0, y0, x, y = self.roi
152
+ info = {
153
+ "width": x,
154
+ "height": y,
155
+ "offsetX": x0,
156
+ "offsetY": y0,
157
+ "exposure": self.exposure / 1_000,
158
+ "brightness": self.brightness,
159
+ "gamma": self.gamma,
160
+ "gain": self.gain,
161
+ "framerate": self.framerate,
162
+ "binning": self.binning,
163
+ }
164
+ return info