mosca 2.0.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.
Files changed (73) hide show
  1. mosca/__init__.py +11 -0
  2. mosca/common/__init__.py +9 -0
  3. mosca/common/enums.py +79 -0
  4. mosca/common/logger.py +139 -0
  5. mosca/common/threads.py +199 -0
  6. mosca/common/utils.py +70 -0
  7. mosca/control/__init__.py +4 -0
  8. mosca/control/buffer.py +526 -0
  9. mosca/control/controller.py +278 -0
  10. mosca/control/datahandler.py +261 -0
  11. mosca/control/detectors.py +116 -0
  12. mosca/control/mosca.py +693 -0
  13. mosca/control/spectra.py +36 -0
  14. mosca/control/stats.py +43 -0
  15. mosca/control/tasks/__init__.py +3 -0
  16. mosca/control/tasks/background.py +118 -0
  17. mosca/control/tasks/rois.py +466 -0
  18. mosca/control/tasks/saving.py +391 -0
  19. mosca/control/tasks/spectrasums.py +185 -0
  20. mosca/control/tasks/task.py +201 -0
  21. mosca/control/tasks/taskmanager.py +133 -0
  22. mosca/devices/__init__.py +28 -0
  23. mosca/devices/hamamatsu/__init__.py +0 -0
  24. mosca/devices/hamamatsu/hamamatsu.py +88 -0
  25. mosca/devices/hamamatsu/hamamatsuhw.py +1298 -0
  26. mosca/devices/oceanoptics/__init__.py +0 -0
  27. mosca/devices/oceanoptics/oceanoptics.py +59 -0
  28. mosca/devices/oceanoptics/oceanopticshw.py +379 -0
  29. mosca/devices/simulation/__init__.py +0 -0
  30. mosca/devices/simulation/dante/__init__.py +1 -0
  31. mosca/devices/simulation/dante/simdante.py +33 -0
  32. mosca/devices/simulation/dante/simdantehw.py +506 -0
  33. mosca/devices/simulation/dummy/__init__.py +1 -0
  34. mosca/devices/simulation/dummy/dummy.py +299 -0
  35. mosca/devices/simulation/generator.py +607 -0
  36. mosca/devices/simulation/xia/__init__.py +1 -0
  37. mosca/devices/simulation/xia/iniparser.py +99 -0
  38. mosca/devices/simulation/xia/simfalconx.py +26 -0
  39. mosca/devices/simulation/xia/simfalconxhw.py +599 -0
  40. mosca/devices/xglab/__init__.py +0 -0
  41. mosca/devices/xglab/dante.py +126 -0
  42. mosca/devices/xglab/dantehw.py +1178 -0
  43. mosca/devices/xia/__init__.py +0 -0
  44. mosca/devices/xia/falconx.py +232 -0
  45. mosca/devices/xia/handel/__init__.py +14 -0
  46. mosca/devices/xia/handel/_cffi.py +62 -0
  47. mosca/devices/xia/handel/error.py +272 -0
  48. mosca/devices/xia/handel/handel_inc/handel_constants.h +127 -0
  49. mosca/devices/xia/handel/handel_inc/handel_errors.h +254 -0
  50. mosca/devices/xia/handel/handel_inc/handel_generic.h +66 -0
  51. mosca/devices/xia/handel/interface.py +1025 -0
  52. mosca/devices/xia/handel/mapping.py +107 -0
  53. mosca/devices/xia/handel/parser.py +62 -0
  54. mosca/devices/xia/handel/stats.py +85 -0
  55. mosca/devices/xia/mercury.py +160 -0
  56. mosca/devices/xia/utils.py +47 -0
  57. mosca/devices/xia/xia.py +575 -0
  58. mosca/devices/xia/xiads.py +161 -0
  59. mosca/mosca.py +0 -0
  60. mosca/tango/__init__.py +2 -0
  61. mosca/tango/controller.py +80 -0
  62. mosca/tango/main.py +163 -0
  63. mosca/tango/mosca.py +513 -0
  64. mosca/tango/moscav1.py +408 -0
  65. mosca/tango/shared.py +23 -0
  66. mosca/tango/tasks/__init__.py +0 -0
  67. mosca/tango/tasks/background.py +55 -0
  68. mosca/tango/utils.py +109 -0
  69. mosca-2.0.2.dist-info/METADATA +32 -0
  70. mosca-2.0.2.dist-info/RECORD +73 -0
  71. mosca-2.0.2.dist-info/WHEEL +4 -0
  72. mosca-2.0.2.dist-info/entry_points.txt +2 -0
  73. mosca-2.0.2.dist-info/licenses/LICENSE +166 -0
@@ -0,0 +1,1298 @@
1
+ import logging
2
+ logger = logging.getLogger(__name__)
3
+ # logger.setLevel(logging.DEBUG)
4
+
5
+ import sys
6
+ import time
7
+ import math
8
+ import atexit
9
+ import inspect
10
+ from functools import partial
11
+ from dataclasses import dataclass
12
+ from typing import NamedTuple
13
+ from enum import Enum
14
+ import ctypes
15
+
16
+ import numpy as np
17
+
18
+
19
+ from ...common import GateMode, TriggerMode, to_enum
20
+ from ...control import Controller, PollResult, Status, setparam
21
+
22
+ # LIB_DIR = "C:/blissadm/hamamatsu/Minispectrometer_USB2.0_edition_ver1.1.0.0/DeveloperTools/DLL/x64"
23
+ # sys.path.append(LIB_DIR)
24
+ # print(sys.path)
25
+
26
+ # default_hama_dir = os.path.join(os.path.dirname(__file__), "hamadll")
27
+ # hama_dir = os.getenv("HAMAMATSU_LIB_PATH", default_hama_dir)
28
+ # sys.path.append(hama_dir)
29
+
30
+ # c.NET imports
31
+ import clr
32
+ from System import Array, UInt16, Int16, Int64, UInt64, Char, Double
33
+ from System.Runtime.InteropServices import GCHandle, GCHandleType
34
+ clr.AddReference("HSSUSB2A")
35
+
36
+ from HSSUSB2_DLL import HSSUSB2, Usb2Struct # noqa: E402
37
+ HAMA_ERRORS = Usb2Struct.Cusb2Err
38
+
39
+
40
+ def hama_cleanup():
41
+ logger.debug("Module cleanup.")
42
+ global _HAMAMATSU
43
+ if _HAMAMATSU is None:
44
+ logger.debug("Hama was not instanciated.")
45
+ return
46
+ _HAMAMATSU.teardown()
47
+
48
+
49
+ atexit.register(hama_cleanup)
50
+
51
+
52
+ class ModuleInformation(NamedTuple):
53
+ vender: str
54
+ product: str
55
+ serial: str
56
+ firmware: str
57
+ driver: str
58
+ library: str
59
+
60
+
61
+ class SpectroInformation(NamedTuple):
62
+ unit: str
63
+ sensor: str
64
+
65
+
66
+ class ModuleProperty(NamedTuple):
67
+ pixel: int
68
+ resolution: int
69
+ capturemode: int
70
+ binningmode: int
71
+ triggermode: int
72
+ triggerpolarity: int
73
+
74
+
75
+ class DataPositionProperty(NamedTuple):
76
+ lowerposition: int
77
+ upperposition: int
78
+
79
+
80
+ class ExposureProperty(NamedTuple):
81
+ lowertime: float
82
+ uppertime: float
83
+ timestep: float
84
+ lowercycle: float
85
+ uppercycle: float
86
+ cyclestep: float
87
+
88
+
89
+ class AdOffsetProperty(NamedTuple):
90
+ lower: int
91
+ upper: int
92
+
93
+
94
+ class WaveLengthProperty(NamedTuple):
95
+ lowerwavelength: int
96
+ upperwavelength: int
97
+
98
+
99
+ class DataTriggerOffsetProperty(NamedTuple):
100
+ lower: int
101
+ upper: int
102
+
103
+
104
+ class HamaGainMode(Enum):
105
+ SENSOR = 0x00
106
+ CIRCUIT = 0x01
107
+
108
+
109
+ class HamaCalibrationCoefficient(Enum):
110
+ WAVELENGTH = 0x00
111
+ SENSITIVITY = 0x01
112
+
113
+
114
+ class HamaCaptureMode(Enum):
115
+ COUNT = 0x00
116
+ CONTINUOUS = 0x01
117
+ TRIGGER = 0x02
118
+
119
+
120
+ class HamaTriggerMode(Enum):
121
+ INTERNAL = 0x00
122
+ SOFTWARE_ASYNC = 0x01
123
+ SOFTWARE_SYNC = 0x02
124
+ EXTERNAL_ASYNC_EDGE = 0x03
125
+ EXTERNAL_ASYNC_LEVEL = 0x04
126
+ EXTERNAL_SYNC_EDGE = 0x05
127
+ EXTERNAL_SYNC_LEVEL = 0x06
128
+ EXTERNAL_SYNC_PULSE = 0x07
129
+
130
+
131
+ class HamaTriggerPolarity(Enum):
132
+ FALLING = 0x01
133
+ RAISING = 0x03
134
+
135
+
136
+ class HamaTriggerOutput(Enum):
137
+ OFF = 0x01
138
+ ON = 0x03
139
+
140
+
141
+ class HamaError(Enum):
142
+ SUCCESS = HAMA_ERRORS.usb2Success.value__
143
+ UNSUCCESS = HAMA_ERRORS.usb2Err_unsuccess.value__
144
+ NOTLIST = HAMA_ERRORS.usb2Err_notList.value__
145
+ NOTACCESS = HAMA_ERRORS.usb2Err_notAccess.value__
146
+ NOTFRAME = HAMA_ERRORS.usb2Err_notFrame.value__
147
+ NOTACPOWER = HAMA_ERRORS.usb2Err_notAcPower.value__
148
+ NOTIMAGE = HAMA_ERRORS.usb2Err_notImage.value__
149
+ NOTBUFFER = HAMA_ERRORS.usb2Err_notBuffer.value__
150
+ NOTDATA = HAMA_ERRORS.usb2Err_notData.value__
151
+ NOTDOWNLOAD = HAMA_ERRORS.usb2Err_notDownload.value__
152
+ INVALIDDEVICEINDEX = HAMA_ERRORS.usb2Err_invalidDeviceIndex.value__
153
+ INVALIDMODE = HAMA_ERRORS.usb2Err_invalidMode.value__
154
+ INVALIDPARAMETER = HAMA_ERRORS.usb2Err_invalidParameter.value__
155
+ INVALIDTRIGGERMODE = HAMA_ERRORS.usb2Err_invalidTriggermode.value__
156
+ INVALIDTRIGGERPOLARITY = HAMA_ERRORS.usb2Err_invalidTriggerpolarity.value__
157
+ INVALIDTRIGGEROUTPUT = HAMA_ERRORS.usb2Err_invalidTriggeroutput.value__
158
+ INVALIDBINNING = HAMA_ERRORS.usb2Err_invalidBinning.value__
159
+ INVALIDPOSITION = HAMA_ERRORS.usb2Err_invalidPosition.value__
160
+ INVALIDSIZE = HAMA_ERRORS.usb2Err_invalidSize.value__
161
+ INVALIDGAIN = HAMA_ERRORS.usb2Err_invalidGain.value__
162
+ INVALIDOFFSET = HAMA_ERRORS.usb2Err_invalidOffset.value__
163
+ INVALIDCOOLINGSTATUS = HAMA_ERRORS.usb2Err_invalidCoolingstatus.value__
164
+ INVALIDFRAME = HAMA_ERRORS.usb2Err_invalidFrame.value__
165
+ INVALIDEVENTID = HAMA_ERRORS.usb2Err_invalidEventID.value__
166
+ INVALIDEVENTHANDLE = HAMA_ERRORS.usb2Err_invalidEventhandle.value__
167
+ INVALIDDATA = HAMA_ERRORS.usb2Err_invalidData.value__
168
+ INVALIDINDEX = HAMA_ERRORS.usb2Err_invalidIndex.value__
169
+ INVALIDNUMBER = HAMA_ERRORS.usb2Err_invalidNumber.value__
170
+ INVALIDADDRESS = HAMA_ERRORS.usb2Err_invalidAddress.value__
171
+ INVALIDLENGTH = HAMA_ERRORS.usb2Err_invalidLength.value__
172
+ OVERTIME = HAMA_ERRORS.usb2Err_overTime.value__
173
+ UNDERTIME = HAMA_ERRORS.usb2Err_underTime.value__
174
+ OVERTEMPERATURE = HAMA_ERRORS.usb2Err_overTemperature.value__
175
+ UNDERTEMPERATURE = HAMA_ERRORS.usb2Err_underTemperature.value__
176
+ OVERAREA = HAMA_ERRORS.usb2Err_overArea.value__
177
+ NOWCAPTURING = HAMA_ERRORS.usb2Err_nowCapturing.value__
178
+ NOWFIRMUPDATE = HAMA_ERRORS.usb2Err_nowFirmUpdate.value__
179
+ INITIALIZED = HAMA_ERRORS.usb2Err_initialized.value__
180
+ OPENED = HAMA_ERRORS.usb2Err_opened.value__
181
+ EXISTDEVICE = HAMA_ERRORS.usb2Err_existDevice.value__
182
+ FIRMCORRUPTED = HAMA_ERRORS.usb2Err_FirmCorrupted.value__
183
+ READIMAGESTATUS = HAMA_ERRORS.usb2Err_ReadImageStatus.value__
184
+ INVALIDEEPROMPARAMETER = HAMA_ERRORS.usb2Err_InvalidEepromParameter.value__
185
+ WAITINGSTOP = HAMA_ERRORS.usb2Err_WaitingStop.value__
186
+
187
+
188
+ _MAP_NET_NP = {
189
+ "Single": np.dtype("float32"),
190
+ "Double": np.dtype("float64"),
191
+ "SByte": np.dtype("int8"),
192
+ "Byte": np.dtype("uint8"),
193
+ "Char": np.dtype("uint16"),
194
+ "Int16": np.dtype("int16"),
195
+ "Int32": np.dtype("int32"),
196
+ "Int64": np.dtype("int64"),
197
+ "UInt16": np.dtype("uint16"),
198
+ "UInt32": np.dtype("uint32"),
199
+ "UInt64": np.dtype("uint64"),
200
+ "Boolean": np.dtype("bool"),
201
+ }
202
+
203
+
204
+ def asNumpyArray(netArray):
205
+ """
206
+ Given a CLR `System.Array` returns a `numpy.ndarray`. See _MAP_NET_NP for
207
+ the mapping of CLR types to Numpy dtypes.
208
+ """
209
+ dims = np.empty(netArray.Rank, dtype=int)
210
+ for idx in range(netArray.Rank):
211
+ dims[idx] = netArray.GetLength(idx)
212
+
213
+ netType = netArray.GetType().GetElementType().Name
214
+
215
+ try:
216
+ npArray = np.empty(dims, order="C", dtype=_MAP_NET_NP[netType])
217
+ except KeyError:
218
+ raise NotImplementedError(
219
+ "asNumpyArray does not yet support System type {}".format(netType)
220
+ )
221
+
222
+ sourceHandle = None
223
+ try: # Memmove
224
+ sourceHandle = GCHandle.Alloc(netArray, GCHandleType.Pinned)
225
+ sourcePtr = sourceHandle.AddrOfPinnedObject().ToInt64()
226
+ destPtr = npArray.__array_interface__["data"][0]
227
+ ctypes.memmove(destPtr, sourcePtr, npArray.nbytes)
228
+ finally:
229
+ if sourceHandle is not None and sourceHandle.IsAllocated:
230
+ sourceHandle.Free()
231
+
232
+ return npArray
233
+
234
+
235
+ _HAMAMATSU = None
236
+
237
+ def HamamatsuComm():
238
+ global _HAMAMATSU
239
+ if _HAMAMATSU is None:
240
+ _HAMAMATSU = _HamamatsuComm()
241
+ return _HAMAMATSU
242
+
243
+
244
+ def log_call(func):
245
+ def _inner(self, *args, **kwargs):
246
+ logger.debug("Call: %s(%s, %s)", func.__name__, args, kwargs)
247
+ return func(self, *args, **kwargs)
248
+ return _inner
249
+
250
+
251
+ class HamaCommandError(Exception):
252
+ def __init__(self, hama_err, hama_cmd, results=None):
253
+ msg = f"Command {hama_cmd} failed with error {hama_err.name}={hama_err.value} (caller: {hama_cmd}))."
254
+ super().__init__(msg)
255
+ self.hama_err = hama_err
256
+ self.hama_cmd = hama_cmd
257
+ self.results = results
258
+
259
+
260
+ class _HamamatsuComm:
261
+ MAX_MODULES = 8
262
+
263
+ usb = property(lambda self: self._usb)
264
+
265
+ def __init__(self):
266
+ self._usb = HSSUSB2()
267
+ self._modules = set()
268
+
269
+ def teardown(self):
270
+ logger.debug("Teardown")
271
+ # warning: copying because self._modules is updated
272
+ # in self.close
273
+ opened = list(self._modules)
274
+ for module_id in opened:
275
+ try:
276
+ self.captureStop(module_id)
277
+ except HamaCommandError as ex:
278
+ if ex.hama_err != HamaError.WAITINGSTOP:
279
+ logger.exception("Failed to stop capture for module %s during teardown.", module_id)
280
+ else:
281
+ logger.warning("Module %s did not confirm stop before timeout during teardown; "
282
+ "proceeding with releaseBuffer/close anyway.", module_id)
283
+ try:
284
+ self.releaseBuffer(module_id)
285
+ except HamaCommandError:
286
+ logger.exception("Failed to release buffer for module %s during teardown.", module_id)
287
+ try:
288
+ self.close(module_id)
289
+ except HamaCommandError:
290
+ logger.exception("Failed to close module %s during teardown.", module_id)
291
+ self.uninitialize()
292
+
293
+ def _check_ret(self, ret, *results, accept=None):
294
+ """ Checks the given return code.
295
+ Raises an exception if the code is not SUCCESS or
296
+ if it's different from one provided with the
297
+ accept keyword.
298
+ """
299
+ try:
300
+ value = HamaError(ret)
301
+ except ValueError:
302
+ caller = inspect.stack(context=2)[1]
303
+ raise ValueError(f"Unknown return value {ret} (caller: {caller.function}).")
304
+
305
+ logger.debug("Return code: [%s=%s].", value.name, value.value)
306
+
307
+ if value != HamaError.SUCCESS and accept != value:
308
+ caller = inspect.stack(context=2)[1]
309
+ raise HamaCommandError(value, caller.function, results)#f"Command failed with error {value.name}={value.value} (caller: {caller.function})).")
310
+
311
+ return value
312
+
313
+ @log_call
314
+ def initialize(self):
315
+ """ Initializes the library. """
316
+ rc = self._usb.USB2_initialize()
317
+ self._check_ret(rc, accept=HamaError.INITIALIZED)
318
+
319
+ @log_call
320
+ def getModuleConnectionList(self, max_modules=MAX_MODULES):
321
+ """ Returns the list of available modules. """
322
+ modules = Array[Int16](max_modules)
323
+ rc, nmods = self._usb.USB2_getModuleConnectionList(modules, max_modules)
324
+ self._check_ret(rc, nmods)
325
+ if nmods > 0:
326
+ return list(modules)[0:nmods]
327
+ else:
328
+ return []
329
+
330
+ @log_call
331
+ def close(self, module_id: int):
332
+ logger.debug("Closing module %s.", module_id)
333
+ rc = self._usb.USB2_close(module_id)
334
+ self._check_ret(rc, accept=HamaError.INVALIDDEVICEINDEX)
335
+ self._modules.discard(module_id)
336
+
337
+ @log_call
338
+ def open(self, module_id: int):
339
+ logger.debug("Opening module %s.", module_id)
340
+ rc = self._usb.USB2_open(module_id)
341
+ self._check_ret(rc, accept=HamaError.OPENED)
342
+ self._modules.add(module_id)
343
+
344
+ @log_call
345
+ def uninitialize(self):
346
+ rc = self._usb.USB2_uninitialize()
347
+ self._check_ret(rc)
348
+
349
+ @log_call
350
+ def getModuleInformation(self, module_id: int):
351
+ info = Usb2Struct.CModuleInformation()
352
+ rc, info = self._usb.USB2_getModuleInformation(module_id, info)
353
+ self._check_ret(rc, info)
354
+ kw = {field: getattr(info, field).split("\x00", 1)[0]
355
+ for field in ModuleInformation._fields}
356
+ return ModuleInformation(**kw)
357
+
358
+ @log_call
359
+ def getSpectroInformation(self, module_id: int):
360
+ info = Usb2Struct.CSpectroInformation()
361
+ rc, info = self._usb.USB2_getSpectroInformation(module_id, info)
362
+ self._check_ret(rc, info)
363
+ kw = {field: getattr(info, field).split("\x00", 1)[0]
364
+ for field in SpectroInformation._fields}
365
+ return SpectroInformation(**kw)
366
+
367
+ @log_call
368
+ def getModuleProperty(self, module_id: int):
369
+ prop = Usb2Struct.CModuleProperty()
370
+ rc, info = self._usb.USB2_getModuleProperty(module_id, prop)
371
+ self._check_ret(rc, info)
372
+ kw = {field: getattr(prop, field)
373
+ for field in ModuleProperty._fields}
374
+ return ModuleProperty(**kw)
375
+
376
+ @log_call
377
+ def getDataPositionProperty(self, module_id: int):
378
+ datapos = Usb2Struct.CDataPositionProperty()
379
+ rc, datapos = self._usb.USB2_getDataPositionProperty(module_id, datapos)
380
+ self._check_ret(rc, datapos)
381
+ kw = {field: getattr(datapos, field)
382
+ for field in DataPositionProperty._fields}
383
+ return DataPositionProperty(**kw)
384
+
385
+ @log_call
386
+ def getDataCountProperty(self, module_id: int):
387
+ rc, count = self._usb.USB2_getDataCountProperty(module_id, 0)
388
+ self._check_ret(rc, count)
389
+ return count
390
+
391
+ @log_call
392
+ def getImageSize(self, module_id: int):
393
+ rc, size_x, size_y = self._usb.USB2_getImageSize(module_id, 0, 0)
394
+ self._check_ret(rc, size_x, size_y)
395
+ return size_x, size_y
396
+
397
+ @log_call
398
+ def getStatusRequest(self, module_id: int) -> int:
399
+ rc, status = self._usb.USB2_GetStatusRequest(module_id, 0)
400
+ self._check_ret(rc, status)
401
+ return ord(status)
402
+
403
+ @log_call
404
+ def setCalibrationCoefficient(self, module_id: int, index: int, coefficient: list[float]):
405
+ rc = self._usb.USB2_SetCalibrationCoefficient(module_id, index, coefficient)
406
+ self._check_ret(rc)
407
+
408
+ @log_call
409
+ def allocateBuffer(self, module_id: int, n_frames):
410
+ rc = self._usb.USB2_allocateBuffer(module_id, n_frames)
411
+ self._check_ret(rc)
412
+
413
+ @log_call
414
+ def captureStart(self, module_id: int, count: int):
415
+ rc = self._usb.USB2_captureStart(module_id, count)
416
+ self._check_ret(rc)
417
+
418
+ @log_call
419
+ def captureStop(self, module_id: int, timeout_s=0.5):
420
+ logger.debug("Stopping capture [module %s]", module_id)
421
+ stop_t = time.monotonic()
422
+ while 1:
423
+ try:
424
+ rc = self._usb.USB2_captureStop(module_id)
425
+ self._check_ret(rc)
426
+ break
427
+ except HamaCommandError as ex:
428
+ if ex.hama_err == HamaError.WAITINGSTOP:
429
+ if time.monotonic() - stop_t < timeout_s:
430
+ time.sleep(0.1)
431
+ else:
432
+ raise
433
+ else:
434
+ raise
435
+
436
+ @log_call
437
+ def fireTrigger(self, module_id: int):
438
+ rc = self._usb.USB2_fireTrigger(module_id)
439
+ self._check_ret(rc)
440
+
441
+ def getAdOffset(self, module_id: int) -> int:
442
+ rc, offset = self._usb.USB2_getAdOffset(module_id, 0)
443
+ self._check_ret(rc, offset)
444
+ return offset
445
+
446
+ @log_call
447
+ def getAdOffsetProperty(self, module_id: int):
448
+ offset = Usb2Struct.CAdOffsetProperty()
449
+ rc, offset = self._usb.USB2_getAdOffsetProperty(module_id, offset)
450
+ self._check_ret(rc, offset)
451
+ kw = {field: getattr(offset, field)
452
+ for field in AdOffsetProperty._fields}
453
+ return AdOffsetProperty(**kw)
454
+
455
+ @log_call
456
+ def getCalibrationCoefficient(self, module_id: int, index: int) -> list[float]:
457
+ coefficient = Array[Double](6)
458
+ rc, coefficient = self._usb.USB2_getCalibrationCoefficient(module_id, index, coefficient)
459
+ self._check_ret(rc, coefficient)
460
+ return list(coefficient)
461
+
462
+ @log_call
463
+ def getCaptureMode(self, module_id: int):
464
+ rc, mode = self._usb.USB2_getCaptureMode(module_id, 0)
465
+ self._check_ret(rc, mode)
466
+ return mode
467
+
468
+ @log_call
469
+ def getCaptureStatus(self, module_id: int, ignore_err=None) -> tuple[int]:
470
+ rc, frame, index = self._usb.USB2_getCaptureStatus(module_id, 0, 0)
471
+ self._check_ret(rc, frame, index, accept=ignore_err)
472
+ return frame, index
473
+
474
+ @log_call
475
+ def getCoolingTemperature(self, module_id: int) -> float:
476
+ rc, temperature = self._usb.USB2_getCoolingTemperature(module_id, 0.0)
477
+ self._check_ret(rc, temperature)
478
+ return temperature
479
+
480
+ @log_call
481
+ def getDataCount(self, module_id: int):
482
+ rc, count = self._usb.USB2_getDataCount(module_id, 0)
483
+ self._check_ret(rc, count)
484
+ return count
485
+
486
+ @log_call
487
+ def getDataPosition(self, module_id: int):
488
+ rc, position = self._usb.USB2_getDataPosition(module_id, 0)
489
+ self._check_ret(rc)
490
+ return position
491
+
492
+ @log_call
493
+ def getDataTransmit(self, module_id: int):
494
+ rc, transmit = self._usb.USB2_getDataTransmit(module_id, 0)
495
+ self._check_ret(rc, transmit)
496
+ return transmit
497
+
498
+ @log_call
499
+ def getDataTransmitProperty(self, module_id: int):
500
+ rc, num = self._usb.USB2_getDataTransmitProperty(module_id, 0)
501
+ self._check_ret(rc, num)
502
+ return num
503
+
504
+ @log_call
505
+ def getDataTriggerOffset(self, module_id: int):
506
+ rc, offset = self._usb.USB2_getDataTriggerOffset(module_id, 0)
507
+ self._check_ret(rc, offset)
508
+ return offset
509
+
510
+ @log_call
511
+ def getDataTriggerOffsetProperty(self, module_id: int):
512
+ trigger_offset = Usb2Struct.CDataTriggerOffsetProperty()
513
+ rc, trigger_offset = self._usb.USB2_getDataTriggerOffsetProperty(module_id, trigger_offset)
514
+ self._check_ret(rc, trigger_offset)
515
+ kw = {field: getattr(trigger_offset, field)
516
+ for field in DataTriggerOffsetProperty._fields}
517
+ return DataTriggerOffsetProperty(**kw)
518
+
519
+ @log_call
520
+ def getExposureCycle(self, module_id: int):
521
+ rc, exposure = self._usb.USB2_getExposureCycle(module_id, 0.0)
522
+ self._check_ret(rc, exposure)
523
+ return exposure
524
+
525
+ @log_call
526
+ def getExposureProperty(self, module_id: int):
527
+ exposure = Usb2Struct.CExposureProperty()
528
+ rc, exposure = self._usb.USB2_getExposureProperty(module_id, exposure)
529
+ self._check_ret(rc, exposure)
530
+ kw = {field: getattr(exposure, field)
531
+ for field in ExposureProperty._fields}
532
+ return ExposureProperty(**kw)
533
+
534
+ @log_call
535
+ def getExposureTime(self, module_id: int):
536
+ rc, exposure = self._usb.USB2_getExposureTime(module_id, 0.0)
537
+ self._check_ret(rc, exposure)
538
+ return exposure
539
+
540
+ @log_call
541
+ def getGain(self, module_id: int, mode: int) -> int:
542
+ rc, gain = self._usb.USB2_getGain(module_id, mode, 0)
543
+ self._check_ret(rc, gain)
544
+ return gain
545
+
546
+ @log_call
547
+ def getGainProperty(self, module_id: int, mode):
548
+ rc, gain = self._usb.USB2_getGainProperty(module_id, mode, 0)
549
+ self._check_ret(rc, gain)
550
+ return gain
551
+
552
+ @log_call
553
+ def getImageData(self, module_id: int, index: int, frame: int, buffers=None):
554
+ if buffers is None:
555
+ size_x, size_y = self.getImageSize(module_id)
556
+ transmit = self.getDataTransmit(module_id)
557
+ buffer_size = size_x * size_y * frame * transmit
558
+ img_buffer = Array[UInt16](buffer_size)
559
+ time_buffer = Array[UInt64](buffer_size)
560
+ else:
561
+ img_buffer, time_buffer = buffers
562
+
563
+ # TODO make sure that image_buffer and time_buffer actually contains data
564
+ rc, img_buffer, time_buffer = self._usb.USB2_getImageData(module_id, img_buffer, index, frame, time_buffer)
565
+ self._check_ret(rc, img_buffer, time_buffer)
566
+ return img_buffer, time_buffer
567
+
568
+ @log_call
569
+ def getImageHeaderData(self, module_id: int):
570
+ raise NotImplementedError
571
+ # rc = self._usb.USB2_getImageHeaderData(module_id)
572
+ # self._check_ret(rc)
573
+
574
+ @log_call
575
+ def getModuleReadoutTime(self, module_id: int):
576
+ raise NotImplementedError
577
+ # rc = self._usb.USB2_getModuleReadoutTime(module_id)
578
+ # self._check_ret(rc)
579
+
580
+ @log_call
581
+ def getTriggerMode(self, module_id: int):
582
+ rc, mode = self._usb.USB2_getTriggerMode(module_id, 0)
583
+ self._check_ret(rc, mode)
584
+ return mode
585
+
586
+ @log_call
587
+ def getTriggerOutput(self, module_id: int) -> int:
588
+ rc, output = self._usb.USB2_getTriggerOutput(module_id, 0)
589
+ self._check_ret(rc, output)
590
+ return output
591
+
592
+ @log_call
593
+ def getTriggerPolarity(self, module_id: int) -> int:
594
+ rc, polarity = self._usb.USB2_getTriggerPolarity(module_id, 0)
595
+ self._check_ret(rc, polarity)
596
+ return polarity
597
+
598
+ @log_call
599
+ def getWaveLengthProperty(self, module_id: int):
600
+ wavelength = Usb2Struct.CWaveLengthProperty()
601
+ rc, wavelength = self._usb.USB2_getWaveLengthProperty(module_id, wavelength)
602
+ self._check_ret(rc, wavelength)
603
+ kw = {field: getattr(wavelength, field)
604
+ for field in WaveLengthProperty._fields}
605
+ return WaveLengthProperty(**kw)
606
+
607
+ @log_call
608
+ def readEepromUserArea(self, module_id: int, address: int, length: int):
609
+ data = Array[Char](length)
610
+ rc, data = self._usb.USB2_readEepromUserArea(module_id, address, data, length)
611
+ self._check_ret(rc, data)
612
+ return asNumpyArray(data)
613
+
614
+ @log_call
615
+ def releaseBuffer(self, module_id: int):
616
+ rc = self._usb.USB2_releaseBuffer(module_id)
617
+ self._check_ret(rc, accept=HamaError.NOTBUFFER)
618
+
619
+ @log_call
620
+ def setAdOffset(self, module_id: int, offset: int):
621
+ rc = self._usb.USB2_setAdOffset(module_id, offset)
622
+ self._check_ret(rc)
623
+
624
+ @log_call
625
+ def setCaptureMode(self, module_id: int, mode):
626
+ rc = self._usb.USB2_setCaptureMode(module_id, mode)
627
+ self._check_ret(rc)
628
+
629
+ @log_call
630
+ def setDataCount(self, module_id: int, count):
631
+ rc = self._usb.USB2_setDataCount(module_id, count)
632
+ self._check_ret(rc)
633
+
634
+ @log_call
635
+ def setDataPosition(self, module_id: int, position):
636
+ rc = self._usb.USB2_setDataPosition(module_id, position)
637
+ self._check_ret(rc)
638
+
639
+ @log_call
640
+ def setDataTransmit(self, module_id: int, transmit):
641
+ rc = self._usb.USB2_setDataTransmit(module_id, transmit)
642
+ self._check_ret(rc)
643
+
644
+ @log_call
645
+ def setDataTriggerOffset(self, module_id: int, offset):
646
+ rc = self._usb.USB2_setDataTriggerOffset(module_id, offset)
647
+ self._check_ret(rc)
648
+
649
+ @log_call
650
+ def setExposureCycle(self, module_id: int, exposure_us: float):
651
+ rc = self._usb.USB2_setExposureCycle(module_id, exposure_us)
652
+ self._check_ret(rc)
653
+
654
+ @log_call
655
+ def setExposureTime(self, module_id: int, exposure_us: float):
656
+ rc = self._usb.USB2_setExposureTime(module_id, exposure_us)
657
+ self._check_ret(rc)
658
+
659
+ @log_call
660
+ def setGain(self, module_id: int, mode: int, gain: int):
661
+ rc = self._usb.USB2_setGain(module_id, mode, gain)
662
+ self._check_ret(rc)
663
+
664
+ @log_call
665
+ def setTriggerMode(self, module_id: int, mode):
666
+ rc = self._usb.USB2_setTriggerMode(module_id, mode)
667
+ self._check_ret(rc)
668
+
669
+ @log_call
670
+ def setTriggerOutput(self, module_id: int, output: int):
671
+ rc = self._usb.USB2_setTriggerOutput(module_id, output)
672
+ self._check_ret(rc)
673
+
674
+ @log_call
675
+ def setTriggerPolarity(self, module_id: int, polarity: int):
676
+ rc = self._usb.USB2_setTriggerPolarity(module_id, polarity)
677
+ self._check_ret(rc)
678
+
679
+ # def getCurrentTemperature(self, module_id: int):
680
+ # # rc = self._usb.USB2_getCurrentTemperature(module_id)
681
+ # self._check_ret(rc)
682
+
683
+ # def getBootVersion(self):
684
+ # # rc, version = self._usb.USB2_GetBootVersion()
685
+ # self._check_ret(rc)
686
+
687
+ # def GetDefectivePixel(self, module_id: int):
688
+ # # rc = self._usb.USB2_GetDefectivePixel(module_id)
689
+ # self._check_ret(rc)
690
+
691
+ # def GetStatusData(self, module_id: int):
692
+ # # rc = self._usb.USB2_GetStatusData(module_id)
693
+ # self._check_ret(rc)
694
+
695
+ # def ShutDownPeltiter(self, module_id: int):
696
+ # # rc = self._usb.USB2_ShutDownPeltiter(module_id)
697
+ # self._check_ret(rc)
698
+
699
+ # def downloadFirmware(self, module_id: int):
700
+ # # rc = self._usb.USB2_downloadFirmware(module_id)
701
+ # self._check_ret(rc)
702
+
703
+ # def getBinningSubarray(self, module_id: int):
704
+ # # rc = self._usb.USB2_getBinningSubarray(module_id)
705
+ # self._check_ret(rc)
706
+
707
+ # def getCoolingProperty(self, module_id: int):
708
+ # # rc = self._usb.USB2_getCoolingProperty(module_id)
709
+ # self._check_ret(rc)
710
+
711
+ # def getCoolingStatus(self, module_id: int):
712
+ # # rc = self._usb.USB2_getCoolingStatus(module_id)
713
+ # self._check_ret(rc)
714
+
715
+ # def readEeprom(self, module_id: int):
716
+ # # rc = self._usb.USB2_readEeprom(module_id)
717
+ # self._check_ret(rc)
718
+
719
+ # def setBinningSubarray(self, module_id: int):
720
+ # # rc = self._usb.USB2_setBinningSubarray(module_id)
721
+ # self._check_ret(rc)
722
+
723
+ # def setCoolingStatus(self, module_id: int):
724
+ # # rc = self._usb.USB2_setCoolingStatus(module_id)
725
+ # self._check_ret(rc)
726
+
727
+ # def setCoolingTemperature(self, module_id: int):
728
+ # # rc = self._usb.USB2_setCoolingTemperature(module_id)
729
+ # self._check_ret(rc)
730
+
731
+ # def writeEeprom(self, module_id: int):
732
+ # # rc = self._usb.USB2_writeEeprom(module_id)
733
+ # self._check_ret(rc)
734
+
735
+ # def writeEepromUserArea(self, module_id: int):
736
+ # # rc = self._usb.USB2_writeEepromUserArea(module_id)
737
+ # self._check_ret(rc)
738
+
739
+ # def setEventHandle(self, module_id: int):
740
+ # # rc = self._usb.USB2_setEventHandle(module_id)
741
+ # self._check_ret(rc)
742
+
743
+
744
+ def mosca_to_hama(trigger_mode, gate_mode, nb_points):
745
+ hama_data_count = 1
746
+ hama_capture_mode = None
747
+ hama_trigger_mode = None
748
+ hama_trigger_polarity = None
749
+
750
+ if nb_points <= 0:
751
+ raise ValueError("Mosca hamamatsu only supports acq_nb_points > 0.")
752
+
753
+ if trigger_mode == TriggerMode.INT_TRIG_READOUT:
754
+ hama_trigger_mode = HamaTriggerMode.INTERNAL
755
+ hama_capture_mode = HamaCaptureMode.COUNT
756
+ hama_data_count = nb_points
757
+ elif trigger_mode == TriggerMode.EXT_TRIG_READOUT:
758
+ hama_capture_mode = HamaCaptureMode.TRIGGER
759
+ hama_trigger_mode = HamaTriggerMode.EXTERNAL_SYNC_EDGE
760
+ if gate_mode == GateMode.HIGH:
761
+ hama_trigger_polarity = HamaTriggerPolarity.RAISING
762
+ elif gate_mode == GateMode.LOW:
763
+ hama_trigger_polarity = HamaTriggerPolarity.FALLING
764
+ else:
765
+ raise ValueError("Can't have gate mode IGNORE with "
766
+ "trigger mode EXT TRIG READOUT.")
767
+ else:
768
+ raise ValueError(f"Invalid configuration: {trigger_mode.name}, {gate_mode.name}.")
769
+
770
+ return hama_capture_mode, hama_trigger_mode, hama_trigger_polarity, hama_data_count
771
+ # only supported run mode
772
+ # if run_mode == RunModes.FREERUN:
773
+ # if gate_mode == GateMode.IGNORE and start_trigger == ControlTriggers.NONE:
774
+ # trigger_mode = HamaTriggerMode.INTERNAL
775
+ # if nb_points <= 0:
776
+ # # continuous acquisition mode
777
+ # capture_mode = HamaCaptureMode.CONTINUOUS
778
+ # # data_count = nb_points
779
+ # else:
780
+ # # acquisition mode runs until the number of points
781
+ # # is reached
782
+ # capture_mode = HamaCaptureMode.COUNT
783
+ # data_count = nb_points
784
+ # else:
785
+ # # using triggers
786
+ # capture_mode = HamaCaptureMode.TRIGGER
787
+
788
+ # if start_trigger == ControlTriggers.SOFTWARE:
789
+ # # software trigger, gate_mode is ignored
790
+ # trigger_mode = HamaTriggerMode.SOFTWARE_SYNC
791
+ # elif gate_mode == GateMode.IGNORE:
792
+ # # not using gate -> triggers on edge
793
+ # if start_trigger == ControlTriggers.RISING:
794
+ # trigger_mode = HamaTriggerMode.EXTERNAL_SYNC_PULSE
795
+ # trigger_polarity = HamaTriggerPolarity.RAISING
796
+ # elif start_trigger == ControlTriggers.FALLING:
797
+ # trigger_mode = HamaTriggerMode.EXTERNAL_SYNC_PULSE
798
+ # trigger_polarity = HamaTriggerPolarity.FALLING
799
+ # elif gate_mode == GateMode.HIGH:
800
+ # # acquires while gate is high
801
+ # trigger_mode = HamaTriggerMode.EXTERNAL_SYNC_EDGE
802
+ # trigger_polarity = HamaTriggerPolarity.RAISING
803
+ # elif gate_mode == GateMode.LOW:
804
+ # # acquires while gate is low
805
+ # trigger_mode = HamaTriggerMode.EXTERNAL_SYNC_EDGE
806
+ # trigger_polarity = HamaTriggerPolarity.FALLING
807
+
808
+ # if capture_mode is None or trigger_mode is None:
809
+ # raise ValueError(f"Unsupported set of parameters:"
810
+ # f" {run_mode}, {gate_mode}, {start_trigger}, {nb_points}.")
811
+
812
+ # return capture_mode, trigger_mode, trigger_polarity, data_count
813
+
814
+
815
+ class Module:
816
+ """ Helper to avoid having to type the module ID. """
817
+ def __init__(self, comm, module_id):
818
+ self._comm = comm
819
+ self._module_id = module_id
820
+ # self._fn = {}
821
+
822
+ def __getattr__(self, name):
823
+ fn = partial(getattr(self._comm, name),
824
+ self._module_id)
825
+ setattr(self, name, fn)
826
+ return fn
827
+
828
+
829
+ def default_readout_time(product, readout_time=None):
830
+ if readout_time is None or readout_time <= 0:
831
+ try:
832
+ readout_time = HamamatsuHW.READOUT_TIMES[product]
833
+ except KeyError:
834
+ models = list(HamamatsuHW.READOUT_TIMES.keys())
835
+ ex = RuntimeError(f"No known readout_time for model {product}. "
836
+ f"Please provide one (known models: {models}).")
837
+ logger.exception(ex)
838
+ raise ex
839
+ logger.warning("No readout time provided, using documented "
840
+ f"one for model {product}: {readout_time} us.\n"
841
+ "(MINI-SPECTROMETERS DLL Function Specifications, Feb. 2024)")
842
+ return readout_time
843
+
844
+
845
+ class HamamatsuHW(Controller):
846
+ # * datacount(X): number of points acquired per trigger
847
+ # * datatransmit(Y): number of points per "download" (or frame = Y points)
848
+ # (aka pixels per buffer for XIA.)
849
+ # * value passed to captureStart(N): not sure... the counter is reset after that value
850
+ # but the acquisition continues...
851
+ # Attention: if acquiring more than N points, it seems that you have to make sure
852
+ # that you have read all N points before the next point is triggered... otherwise
853
+ # the program hangs!
854
+
855
+ module = property(lambda self: self._module)
856
+ module_id = property(lambda self: self._module_id)
857
+
858
+ READOUT_TIMES ={ "C11118GA": 1031,
859
+ "C11482GA": 1033,
860
+ "C11697MB": 1049,
861
+ "C13053MA": 113,
862
+ "C13054MA": 113,
863
+ "C13555MA": 113,
864
+ "C14214MA": 420,
865
+ "C14486GA": 136 }
866
+
867
+ def __init__(self, *args, module_id=0, readout_time=None, **kwargs):
868
+ super().__init__(*args, **kwargs)
869
+ self._module_id = module_id
870
+ self._comm = HamamatsuComm()
871
+ self._comm.initialize()
872
+ self._module = Module(self._comm, module_id)
873
+ self._module.open()
874
+
875
+ self._poller = None
876
+
877
+ self._module_info = self.module.getModuleInformation()
878
+ self._exposure_property = self.module.getExposureProperty()
879
+ self._spectro_info = self.module.getSpectroInformation()
880
+ self._module_property = self.module.getModuleProperty()
881
+ self._data_count_property = self.module.getDataCountProperty()
882
+ self._data_transmit_property = self.module.getDataTransmitProperty()
883
+
884
+ self._n_points = 1
885
+
886
+ # This is done to differentiate between "automatically computed"
887
+ # exposure_cycle (i.e: exposure cycle is changed implicitly by
888
+ # the server when setting the exposure time)
889
+ # and user set exposure_cycle (exposure cycle is not changed
890
+ # when applying exposure time)
891
+ # If user_exposure_cycle is set to a value <= 0 then the
892
+ # exposure_cycle will be automatically set using
893
+ # lowercycle value found in ExposureProperty .
894
+ self._user_exposure_cycle = None
895
+
896
+ # This is the delay between the end of an acquisition
897
+ # and the start of the next one.
898
+ # In hamamatsu terms: readout_time = exposure cycle - exposure time
899
+ product = self._module_info.product
900
+
901
+ self._readout_time = default_readout_time(product, readout_time=readout_time)
902
+
903
+ # resetting exposure time to set exposure cycle
904
+ # to default exposure time + readout time
905
+ expo_time = self.exposure_time()
906
+ self.set_exposure_time(expo_time)
907
+
908
+ @property
909
+ def module_info(self):
910
+ """ Returns the CModuleInfo struct. """
911
+ return self._module_info
912
+
913
+ @property
914
+ def exposure_property(self):
915
+ """ Returns the CModuleProperty struct. """
916
+ return self._exposure_property
917
+
918
+ @property
919
+ def spectro_information(self):
920
+ """ Returns the CSpectroInformation struct. """
921
+ return self._spectro_info
922
+
923
+ @property
924
+ def module_property(self):
925
+ """ Returns the CModuleProperty struct. """
926
+ return self._module_property
927
+
928
+ @property
929
+ def data_count_property(self):
930
+ return self._data_count_property
931
+
932
+ @property
933
+ def data_transmit_property(self):
934
+ return self._data_transmit_property
935
+
936
+ def capture_mode(self):
937
+ return to_enum(self.module.getCaptureMode(),
938
+ HamaCaptureMode)
939
+
940
+ def set_capture_mode(self, capture_mode):
941
+ capture_mode = to_enum(capture_mode,
942
+ HamaCaptureMode).value
943
+ return self.module.setCaptureMode(capture_mode)
944
+
945
+ def trigger_mode(self):
946
+ return to_enum(self.module.getTriggerMode(),
947
+ HamaTriggerMode)
948
+
949
+ def set_trigger_mode(self, trigger_mode):
950
+ trigger_mode = to_enum(trigger_mode,
951
+ HamaTriggerMode).value
952
+ return self.module.setTriggerMode(trigger_mode)
953
+
954
+ def trigger_polarity(self):
955
+ return to_enum(self.module.getTriggerPolarity(),
956
+ HamaTriggerPolarity)
957
+
958
+ def set_trigger_polarity(self, trigger_polarity):
959
+ trigger_polarity = to_enum(trigger_polarity,
960
+ HamaTriggerPolarity).value
961
+ return self.module.setTriggerPolarity(trigger_polarity)
962
+
963
+ def readout_time(self):
964
+ return self._readout_time
965
+
966
+ def set_readout_time(self, readout_time):
967
+ self._readout_time = default_readout_time(self.module_info.product,
968
+ readout_time=readout_time)
969
+ exposure_time = self.exposure_time()
970
+ # self.set_exposure_cycle(-1)
971
+ self.set_exposure_time(exposure_time)
972
+
973
+ def capture_status(self):
974
+ try:
975
+ return self.module.getCaptureStatus()
976
+ except HamaCommandError as ex:
977
+ if ex.hama_err == HamaError.UNSUCCESS:
978
+ return -1, -1
979
+ raise
980
+
981
+ # def readout_time(self):
982
+
983
+ # def set_readout_time(self, readout_time):
984
+ # pass
985
+
986
+ def data_count(self):
987
+ return self.module.getDataCount()
988
+
989
+ def set_data_count(self, data_count):
990
+ # TODO: check data_count_property
991
+ self.module.setDataCount(data_count)
992
+
993
+ def user_exposure_cycle(self):
994
+ return self._user_exposure_cycle
995
+
996
+ def exposure_cycle(self):
997
+ """ Exposure cycle time in microseconds. """
998
+ return self.module.getExposureCycle()
999
+
1000
+ def exposure_time(self):
1001
+ """ Exposure time in microseconds. """
1002
+ return self.module.getExposureTime()
1003
+
1004
+ def image_size(self):
1005
+ """ Image size after binning. """
1006
+ return self.module.getImageSize()
1007
+
1008
+ def data_transmit(self):
1009
+ # TODO: check data_transmit_property
1010
+ return self.module.getDataTransmit()
1011
+
1012
+ def set_data_transmit(self, data_transmit):
1013
+ self.module.setDataTransmit(data_transmit)
1014
+
1015
+ def set_exposure_cycle(self, exposure_cycle):
1016
+ """ Sets the exposure cycle, in us.
1017
+ See Hamamatsu documentation.
1018
+ In short: cycle time = exposure time + readout time
1019
+
1020
+ Calling this method sets the cycle time to the given
1021
+ value. If the provided cycle time is equal or lower than
1022
+ zero, then the cycle time will be computer automatically
1023
+ (= exposure time + readout time).
1024
+ """
1025
+ if exposure_cycle <= 0:
1026
+ exposure_cycle = self.exposure_time() + self.readout_time()
1027
+ self._set_exposure_cycle(exposure_cycle)
1028
+ self._user_exposure_cycle = None
1029
+ else:
1030
+ self._set_exposure_cycle(exposure_cycle)
1031
+ self._user_exposure_cycle = exposure_cycle
1032
+
1033
+ def _set_exposure_cycle(self, exposure_cycle):
1034
+ """
1035
+ Sets the exposure cycle time in microseconds.
1036
+ Given cycle time is checked against
1037
+ the current exposure time value.
1038
+ As per Hamamatsu documentation, cycle time must be greater
1039
+ than exposure time + readout time.
1040
+ Minimumm cycle/exposure times can be retrieved with
1041
+ exposure_property.
1042
+ """
1043
+ expo_time = self.exposure_time()
1044
+ expo_prop = self.exposure_property
1045
+ min_cycle = expo_prop.lowercycle
1046
+ max_cycle = expo_prop.uppercycle
1047
+
1048
+ if exposure_cycle < min_cycle or exposure_cycle > max_cycle:
1049
+ raise ValueError(f"Out of range exposure cycle ({exposure_cycle} us). "
1050
+ f"Range=[{min_cycle} us, {max_cycle} us]")
1051
+
1052
+ if exposure_cycle - expo_time < expo_prop.lowercycle:
1053
+ raise ValueError(
1054
+ f"Requested exposure cycle ({exposure_cycle} us) "
1055
+ f"too low for the current exposure time ({expo_time} us). "
1056
+ f"Requirement: {min_cycle} us < cycle time - expo_time < {max_cycle} us.")
1057
+
1058
+ self.module.setExposureCycle(exposure_cycle)
1059
+
1060
+ def set_exposure_time(self, exposure_time):
1061
+ """
1062
+ Sets the exposure time in microseconds.
1063
+ Given exposure time is checked against
1064
+ the current exposure cycle value.
1065
+ As per Hamamatsu documentation, cycle time must be greater
1066
+ than exposure time + readout time.
1067
+ Minimumm cycle and exposure times can be retrieved from
1068
+ exposure_property.
1069
+ """
1070
+ expo_prop = self.exposure_property
1071
+ min_cycle = expo_prop.lowercycle
1072
+ max_cycle = expo_prop.uppercycle
1073
+
1074
+ if exposure_time < expo_prop.lowertime or exposure_time > expo_prop.uppertime:
1075
+ raise ValueError(f"Out of range exposure time ({exposure_time} us). "
1076
+ f"Range=[{expo_prop.lowertime} us, {expo_prop.uppertime} us]")
1077
+
1078
+ if self._user_exposure_cycle is None:
1079
+ # exposure cycle was not set by user
1080
+ # using readout time to compute the
1081
+ # new exposure cycle
1082
+ exposure_cycle = exposure_time + self.readout_time()
1083
+ # setting the exposure time to the minimum so that we dont
1084
+ # trigger an error on the exposure cycle.
1085
+ self.module.setExposureTime(self.exposure_property.lowertime)
1086
+ self._set_exposure_cycle(exposure_cycle)
1087
+ self.module.setExposureTime(exposure_time)
1088
+ else:
1089
+ # exposure cycle was set by user
1090
+ # making sure it's valid for this exposure time
1091
+ expo_cycle = self.exposure_cycle()
1092
+ if expo_cycle - exposure_time < expo_prop.lowercycle:
1093
+ raise ValueError(
1094
+ f"Requested exposure time ({exposure_time} us) "
1095
+ f"too low for the current exposure cycle ({expo_cycle} us). "
1096
+ f"Requirement: {min_cycle} us < cycle time - expo_time < {max_cycle} us.")
1097
+
1098
+ self.module.setExposureTime(exposure_time)
1099
+
1100
+ def spectrum_size(self):
1101
+ return self.image_size()[0]
1102
+
1103
+ def available_detectors(self):
1104
+ return (0,)
1105
+
1106
+ def n_points(self):
1107
+ """ Number of points to acquire. """
1108
+ return self._n_points
1109
+
1110
+ def set_n_points(self, n_points):
1111
+ self._n_points = n_points
1112
+
1113
+ def apply_mosca(self,
1114
+ acq_nb_points=None,
1115
+ acq_realtime=None,
1116
+ trigger_mode=None,
1117
+ gate_mode=None,
1118
+ block_size=None,
1119
+ **kwargs):
1120
+ if acq_realtime is not None:
1121
+ self.set_exposure_time(acq_realtime * 1e6)
1122
+
1123
+ if block_size is not None:
1124
+ self.set_data_transmit(block_size)
1125
+
1126
+ if acq_nb_points is not None:
1127
+ self.set_n_points(acq_nb_points)
1128
+ else:
1129
+ raise RuntimeError("acq_nb_points must be defined (can't be None).")
1130
+
1131
+ capture_mode, trigger_mode, trigger_polarity, data_count = \
1132
+ mosca_to_hama(trigger_mode, gate_mode, acq_nb_points)
1133
+
1134
+ logger.info("Setting spectro modes: %s, %s, %s, %s.",
1135
+ capture_mode.name,
1136
+ trigger_mode.name,
1137
+ trigger_polarity.name if trigger_polarity is not None else "N/A",
1138
+ data_count)
1139
+
1140
+ if acq_nb_points is not None:
1141
+ self.set_data_count(data_count)
1142
+
1143
+ self.set_capture_mode(capture_mode)
1144
+ self.set_trigger_mode(trigger_mode)
1145
+ if trigger_polarity is not None:
1146
+ self.set_trigger_polarity(trigger_polarity)
1147
+
1148
+ def prepare_acq(self, resume=False):
1149
+ self.module.releaseBuffer()
1150
+
1151
+ # TODO: checks on n_points, datatransmit and datacounts
1152
+
1153
+ # I couldn't find any documented limit for the buffer length
1154
+ # -> 1000 seems to work, leaving it at that
1155
+ self.module.allocateBuffer(1000)
1156
+
1157
+ def start_acq(self, resume=None):
1158
+ self._poller = HamaPoller(self.module, self.n_points())
1159
+ self.module.captureStart(1000)
1160
+ self._poller._set_is_running(True)
1161
+
1162
+ def stop_acq(self):
1163
+ """ Stops the acquisitions. """
1164
+ # TODO: in what order? there is no status for the acquisition
1165
+ if self._poller and self._poller.is_running():
1166
+ self._poller.stop()
1167
+ else:
1168
+ try:
1169
+ self.module.captureStop()
1170
+ except HamaCommandError as ex:
1171
+ if ex.hama_err != HamaError.WAITINGSTOP:
1172
+ logger.exception(ex)
1173
+ raise
1174
+
1175
+ def poll_acq(self):
1176
+ return self._poller()
1177
+
1178
+ def mca_status(self):
1179
+ if self._poller and self._poller.is_running():
1180
+ return Status.RUNNING
1181
+ return Status.READY
1182
+
1183
+ def get_supported_trigger_modes(self):
1184
+ return [TriggerMode.INT_TRIG_READOUT, TriggerMode.EXT_TRIG_READOUT]
1185
+
1186
+
1187
+ class HamaPoller:
1188
+ def __init__(self, module, n_points=None):
1189
+ self._module = module
1190
+ img_x, img_y = module.getImageSize()
1191
+ self._img_size = img_x * img_y
1192
+ self._transmit = module.getDataTransmit()
1193
+ self._n_points = n_points
1194
+ self._stop = False
1195
+ self._n_frame_read = 0
1196
+ self._is_running = False
1197
+
1198
+ def _set_is_running(self, is_running):
1199
+ self._is_running = is_running
1200
+
1201
+ def stop(self):
1202
+ self._stop = True
1203
+
1204
+ def is_running(self):
1205
+ return self._is_running
1206
+
1207
+ def __call__(self):
1208
+ mod = self._module
1209
+ stop = self._stop
1210
+
1211
+ # True if a stop was requested mid acquisition
1212
+ finished = stop
1213
+
1214
+ # number of expected frames, in case "transmit" is != 1
1215
+ # also, the last frame might contain left points than "transmit"
1216
+ # if n_points is not a multiple of transmit
1217
+ if self._n_points > 0:
1218
+ if self._transmit == 1:
1219
+ expected = self._n_points
1220
+ else:
1221
+ expected = math.ceil(self._n_points / self._transmit)
1222
+ else:
1223
+ expected = 0
1224
+
1225
+ try:
1226
+ frame, index = mod.getCaptureStatus()
1227
+ except HamaCommandError as ex:
1228
+ if ex.hama_err == HamaError.UNSUCCESS:
1229
+ # No points available yet... probably.
1230
+ frame, index = -1, -1
1231
+ else:
1232
+ raise
1233
+
1234
+ img_data = None
1235
+ time_data = None
1236
+ n_points = 0
1237
+
1238
+ # we test for frame and index to be valid because
1239
+ # sometimes they act a bit weird...
1240
+ if frame > 0 and index >= 0:
1241
+ # frame available
1242
+
1243
+ # Reallocating arrays every time instead of
1244
+ # allocating them once (with a given max size that could be
1245
+ # the same as the value passed earlier to USB2_allocateBuffer)
1246
+ # because we're not sure about how the SDK works internally...
1247
+ buffers = (Array[UInt16](self._img_size * frame * self._transmit),
1248
+ Array[UInt64](frame * self._transmit))
1249
+ img_buffer, time_buffer = mod.getImageData(index,
1250
+ frame,
1251
+ buffers=buffers)
1252
+
1253
+ # TODO: if we are reading the last frame, discard the
1254
+ # potential empty points
1255
+ img_data = np.array(img_buffer, dtype=np.uint16, copy=True)
1256
+ img_data.shape = 1, frame, -1
1257
+ time_data = np.array(time_buffer, dtype=np.uint64, copy=True)
1258
+ time_data.shape = 1, frame, -1
1259
+
1260
+ # self._n_frame_read += frame
1261
+ n_points = frame * self._transmit
1262
+ if self._n_points > 0:
1263
+ # the last frame may contain fewer valid points than
1264
+ # `transmit` if n_points is not a multiple of transmit;
1265
+ # don't report more valid points than were actually
1266
+ # requested for the whole acquisition
1267
+ already_read = self._n_frame_read * self._transmit
1268
+ missing = self._n_points - already_read
1269
+ if missing < n_points:
1270
+ logger.info("End of scan, discarding extra points (=%s).",
1271
+ n_points - missing)
1272
+ n_points = missing
1273
+
1274
+ self._n_frame_read += frame
1275
+ if expected > 0 and self._n_frame_read >= expected:
1276
+ finished = True
1277
+
1278
+ if finished:
1279
+ self._is_running = False
1280
+ try:
1281
+ mod.captureStop()
1282
+ except HamaCommandError as ex:
1283
+ if ex.hama_err != HamaError.WAITINGSTOP:
1284
+ raise
1285
+
1286
+ # total number of pixels triggered
1287
+ n_triggered = self._n_frame_read * self._transmit
1288
+ if self._n_points > 0:
1289
+ # not an infinite acquisition
1290
+ # capping n_triggered for consistency with the
1291
+ # number of points read at the end of the scan
1292
+ n_triggered = min(self._n_points, n_triggered)
1293
+
1294
+
1295
+ return PollResult(finished=finished,
1296
+ spectra=img_data,
1297
+ n_read=n_points,
1298
+ total_triggered=n_triggered)