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,1025 @@
1
+ """Python interface to handel API."""
2
+
3
+ from __future__ import absolute_import
4
+
5
+ import os
6
+ import enum
7
+ import inspect
8
+ import logging
9
+ from functools import reduce
10
+
11
+ CLOCK_TICK = 320e-9
12
+
13
+
14
+ import numpy
15
+ import time
16
+ # import gevent
17
+ # import gevent.queue
18
+ # import gevent.event
19
+ # from bliss.common import event
20
+ # from bliss.config.static import get_config as get_beacon_config
21
+ # from bliss.config.beacon_object import BeaconObject
22
+
23
+ from .error import check_error, HandelError
24
+ from ._cffi import get_handel, ffi
25
+ from .stats import stats_from_normal_mode
26
+ from .parser import parse_xia_ini_file
27
+ from .mapping import parse_mapping_buffer
28
+
29
+ handel = None
30
+
31
+
32
+ __all__ = [
33
+ "load_handel",
34
+ "init_handel",
35
+ "exit_handel",
36
+ "get_num_detectors",
37
+ "get_detectors",
38
+ "get_detector_from_channel",
39
+ "start_run",
40
+ "stop_run",
41
+ "get_channel_realtime",
42
+ "get_spectrum_length",
43
+ "get_spectrum",
44
+ "get_spectrums",
45
+ "is_channel_running",
46
+ "is_running",
47
+ "get_module_statistics",
48
+ "get_statistics",
49
+ "get_buffer_length",
50
+ "get_raw_buffer",
51
+ "get_buffer_data",
52
+ "is_buffer_full",
53
+ "is_buffer_overrun",
54
+ "set_buffer_done",
55
+ "get_buffer_current_pixel",
56
+ "get_current_pixel",
57
+ "set_maximum_pixels_per_buffer",
58
+ "any_buffer_overrun",
59
+ "all_buffer_full",
60
+ "set_all_buffer_done",
61
+ "get_all_buffer_data",
62
+ "get_baseline_length",
63
+ "get_baseline",
64
+ "load_system",
65
+ "save_system",
66
+ "start_system",
67
+ "enable_log_output",
68
+ "disable_log_output",
69
+ "set_log_output",
70
+ "set_log_level",
71
+ "close_log",
72
+ "get_num_modules",
73
+ "get_modules",
74
+ "get_module_from_channel",
75
+ "get_module_type",
76
+ "get_module_interface",
77
+ "get_module_number_of_channels",
78
+ "get_module_channel_at",
79
+ "get_module_channels",
80
+ "get_grouped_channels",
81
+ "get_channels",
82
+ "get_master_channels",
83
+ "get_trigger_channels",
84
+ "set_acquisition_value",
85
+ "get_acquisition_value",
86
+ "remove_acquisition_value",
87
+ "apply_acquisition_values",
88
+ "get_handel_version",
89
+ "get_config_files",
90
+ "get_config",
91
+ ]
92
+
93
+ MAX_STRING_LENGTH = 80
94
+
95
+ LOGGER = logging.getLogger("HANDEL")
96
+
97
+ # Helpers
98
+
99
+ def to_bytes(arg):
100
+ if isinstance(arg, bytes):
101
+ return arg
102
+ return arg.encode()
103
+
104
+
105
+ def to_buffer_id(bid):
106
+ bid = to_bytes(bid.lower())
107
+ if bid in (b"a", b"b"):
108
+ return bid
109
+ msg = "{!r} is not a valid buffer id"
110
+ raise ValueError(msg.format(bid))
111
+
112
+
113
+ def merge_buffer_data(*data):
114
+ if not data:
115
+ return {}, {}
116
+ # Use first argument as result
117
+ result, data = data[0], data[1:]
118
+ # Copy other arguments into the result
119
+ for sources in data:
120
+ for source, dest in zip(sources, result):
121
+ for key, dct in source.items():
122
+ dest.setdefault(key, {})
123
+ dest[key].update(dct)
124
+ return result
125
+
126
+
127
+ # Initializing handel
128
+ def load_handel(lib_path=None):
129
+ global handel
130
+ if lib_path is None or isinstance(lib_path, (str,)):
131
+ handel = get_handel(lib_path=lib_path)
132
+ else:
133
+ handel = lib_path
134
+ return handel
135
+
136
+
137
+ def init_handel(*path):
138
+ #exit_handel()
139
+ filename = to_bytes(os.path.join(*path))
140
+ LOGGER.info("init (config={%s})", filename)
141
+
142
+ # code = handel.xiaInitHandel()
143
+ # check_error(code)
144
+ code = handel.xiaInit(filename)
145
+ check_error(code)
146
+
147
+
148
+ # def init_handel(mca_name):
149
+ # """Called at server startup.
150
+ # Do:
151
+ # - xiaInit()
152
+ # - xiaLoadSystem()
153
+ # """
154
+ # global handel
155
+ # if handel is None:
156
+ # handel = get_handel()
157
+
158
+ # code = handel.xiaInitHandel()
159
+ # check_error(code)
160
+
161
+ # # vmaj, vmin, vrel = get_handel_version() # exit prog ???
162
+ # # vmaj, vmin, vrel = 0, 0, 0
163
+ # # LOGGER.info("init_handel -- %s -- version=%s.%s.%s", mca_name, vmaj, vmin, vrel)
164
+
165
+ # # Get info from Beacon configuration and settings.
166
+ # print(f"get config for {mca_name}")
167
+ # cfg = get_beacon_config()
168
+ # mca_config = cfg.get_config(mca_name)
169
+ # if mca_config is None:
170
+ # raise ValueError(f"Cannot find config for {mca_name}")
171
+ # mca_beacon_obj = BeaconObject(mca_config)
172
+
173
+ # # Get Beacon setting parameters.
174
+ # current_configuration = mca_beacon_obj.settings.get("current_configuration")
175
+ # LOGGER.debug("current_configuration = %s", current_configuration)
176
+
177
+ # # Get Beacon configuration parameters.
178
+ # default_configuration = mca_config.get("default_configuration")
179
+ # LOGGER.debug("default_configuration = %s", default_configuration)
180
+ # config_dir = mca_config.get("configuration_directory")
181
+ # LOGGER.debug("config_dir = %s", config_dir)
182
+
183
+ # # Use default_configuration if current_configuration is not found.
184
+ # if current_configuration is None:
185
+ # print("No 'current_configuration' found in settings")
186
+ # try:
187
+ # init(config_dir, default_configuration)
188
+ # print(f"Default configuration {default_configuration} loaded.")
189
+ # current_configuration = default_configuration
190
+ # except Exception:
191
+ # raise RuntimeError(
192
+ # f"Error loading default configuration {default_configuration}"
193
+ # )
194
+ # else:
195
+ # try:
196
+ # # Load current_configuration.
197
+ # init(config_dir, current_configuration)
198
+ # print(f"Current configuration {current_configuration} loaded.")
199
+ # except Exception:
200
+ # # Load 'default_configuration' in case of failure of
201
+ # # current_configuration loading (incorrect config file for example).
202
+ # print(f"Loading current configuration {current_configuration} failed.")
203
+ # try:
204
+ # init(config_dir, default_configuration)
205
+ # print(f"Default configuration {default_configuration} loaded.")
206
+ # current_configuration = default_configuration
207
+ # except Exception:
208
+ # raise RuntimeError(
209
+ # f"Error loading default configuration {default_configuration}"
210
+ # )
211
+
212
+ # # In case of success, update 'current_configuration' Beacon setting.
213
+ # mca_beacon_obj.settings.set({"current_configuration": current_configuration})
214
+ # print(f"current config is now: {current_configuration}")
215
+
216
+ # start_system()
217
+ # LOGGER.debug("end of init_handel()")
218
+
219
+
220
+ def exit_handel():
221
+ LOGGER.debug("exit_handel()")
222
+ code = handel.xiaExit()
223
+ check_error(code)
224
+
225
+
226
+ # Detectors
227
+
228
+
229
+ def get_num_detectors():
230
+ """Return the number of detectors configured"""
231
+ num = ffi.new("unsigned int *")
232
+ code = handel.xiaGetNumDetectors(num)
233
+ check_error(code)
234
+ return num[0]
235
+
236
+
237
+ def get_detectors():
238
+ det_count = get_num_detectors()
239
+ arg = [ffi.new("char []", MAX_STRING_LENGTH) for _ in range(det_count)]
240
+ code = handel.xiaGetDetectors(arg)
241
+ check_error(code)
242
+ return tuple(ffi.string(x).decode() for x in arg)
243
+
244
+
245
+ def get_detector_from_channel(channel):
246
+ alias = ffi.new("char []", MAX_STRING_LENGTH)
247
+ code = handel.xiaDetectorFromDetChan(channel, alias)
248
+ check_error(code)
249
+ return ffi.string(alias).decode()
250
+
251
+
252
+ # Not exposed
253
+
254
+ # int xiaGetDetectorItem(char *alias, char *name, void *value);
255
+ # int xiaGetDetectors_VB(unsigned int index, char *alias);
256
+
257
+ # Run control
258
+
259
+
260
+ def start_run(channel=None, resume=False):
261
+ LOGGER.debug(f"start_run(channel={channel})")
262
+
263
+ if channel is None:
264
+ channels = get_channels() # All channels
265
+ else:
266
+ try:
267
+ channels = iter(channel)
268
+ except TypeError:
269
+ channels = [channel]
270
+ for channel in channels:
271
+ code = handel.xiaStartRun(channel, resume)
272
+ check_error(code)
273
+
274
+
275
+ def stop_run(channel=None):
276
+ if channel is None:
277
+ channels = get_channels() # All channels
278
+ else:
279
+ try:
280
+ channels = iter(channel)
281
+ except TypeError:
282
+ channels = [channel]
283
+ for channel in channels:
284
+ LOGGER.debug(f"stop_run(channel={channel})")
285
+ code = handel.xiaStopRun(channel)
286
+ check_error(code)
287
+
288
+
289
+ def get_channel_realtime(channel):
290
+ timing = ffi.new("double *")
291
+ code = handel.xiaGetRunData(channel, b"realtime", timing)
292
+ check_error(code)
293
+ return timing[0]
294
+
295
+
296
+ def get_spectrum_length(channel):
297
+ length = ffi.new("unsigned long *")
298
+ code = handel.xiaGetRunData(channel, b"mca_length", length)
299
+ check_error(code)
300
+ return length[0]
301
+
302
+
303
+ def get_spectrum(channel):
304
+ length = get_spectrum_length(channel)
305
+ array = numpy.zeros(length, dtype="uint32")
306
+ data = ffi.cast("uint32_t *", array.ctypes.data)
307
+ code = handel.xiaGetRunData(channel, b"mca", data)
308
+ check_error(code)
309
+ return array
310
+
311
+
312
+ def get_spectrums():
313
+ """Return the spectrums for all enabled channels as a dictionary."""
314
+ LOGGER.debug("get_spectrums()")
315
+ return {channel: get_spectrum(channel) for channel in get_channels()}
316
+
317
+
318
+ def is_channel_running(channel):
319
+ running = ffi.new("short *")
320
+ code = handel.xiaGetRunData(channel, b"run_active", running)
321
+ check_error(code)
322
+ # It turns out running contains 2 bits of information
323
+ # - bit 0: whether the channel is acquiring
324
+ # - bit 1: whether the channel is running (in the start_run/stop_run sense)
325
+ # We're interested in the first bit of information here
326
+ _running = bool(running[0] & 0x1)
327
+
328
+ return _running
329
+
330
+
331
+ def is_running(channel=None):
332
+ """Return True if any channel is running, False otherwise."""
333
+
334
+ if channel is None:
335
+ running = any(is_channel_running(channel) for channel in get_channels())
336
+ else:
337
+ running = is_channel_running(channel)
338
+
339
+ if LOGGER.level == logging.DEBUG:
340
+ if running:
341
+ pass
342
+ # print("\rRunning ", end="")
343
+ else:
344
+ pass
345
+ # print("Not Running")
346
+
347
+ return running
348
+
349
+
350
+ # Statistics
351
+
352
+ """
353
+ handel.xiaGetRunData(master, b'module_statistics_2', data)
354
+ read statistics of a whole module and put results in data.
355
+ 0: realtime
356
+ 1: trigger livetime
357
+ 2: reserved (energy livetime for XMAP)
358
+ 3: triggers
359
+ 4: MCA events
360
+ 5: ICR
361
+ 6: OCR
362
+ 7: reserved (underflows for XMAP)
363
+ 8: reserved (overflows for XMAP)
364
+
365
+ stats_from_normal_mode() returns a Stats named-tuple
366
+ 'realtime livetime triggers events icr ocr deadtime'
367
+ """
368
+
369
+
370
+ def get_module_statistics(module):
371
+ LOGGER.debug(f"get_module_statistics(module={module})")
372
+ channels = get_module_channels(module)
373
+ # FalconX requires a spectrum read for the statistics to be updated
374
+ if get_module_type(module).startswith("falconx"):
375
+ for channel in channels:
376
+ if channel >= 0:
377
+ try:
378
+ get_spectrum(channel)
379
+ except HandelError:
380
+ pass
381
+ # Prepare buffer
382
+ data_size = 9 * len(channels)
383
+ master = next((c for c in channels if c >= 0), -1)
384
+ if master == -1:
385
+ # no module enabled
386
+ return {}
387
+ array = numpy.zeros(data_size, dtype="double")
388
+ data = ffi.cast("double *", array.ctypes.data)
389
+ # Run handel call
390
+ code = handel.xiaGetRunData(master, b"module_statistics_2", data)
391
+ check_error(code)
392
+ LOGGER.info("Parse raw data")
393
+ return {
394
+ channel: stats_from_normal_mode(array[index * 9 :])
395
+ for index, channel in enumerate(channels)
396
+ if channel >= 0
397
+ }
398
+
399
+
400
+ def get_statistics():
401
+ """Return the statistics for all enabled channels as a dictionary."""
402
+ LOGGER.debug("get_statistics()")
403
+ result = {}
404
+ # We're not using get_master_channels here.
405
+ # That's because each FalconX channels is its own master, even though
406
+ # the statistics can be accessed with a single call per module.
407
+ for module in get_modules():
408
+ stats = get_module_statistics(module)
409
+ LOGGER.debug("stats=%r", stats)
410
+ result.update(stats)
411
+
412
+ # print(result)
413
+ return result
414
+
415
+
416
+ # Buffer
417
+
418
+
419
+ def get_buffer_length(channel=None):
420
+ if channel is None:
421
+ channels = get_channels() # All channels
422
+ else:
423
+ try:
424
+ channels = iter(channel)
425
+ except TypeError:
426
+ channels = [channel]
427
+ length = ffi.new("unsigned long *")
428
+ lengths = []
429
+ for channel in channels:
430
+ code = handel.xiaGetRunData(channel, b"buffer_len", length)
431
+ check_error(code)
432
+ lengths += [length[0]]
433
+ if lengths:
434
+ value = reduce(lambda c, x: c if c == x else None, lengths)
435
+ else:
436
+ raise RuntimeError("Can't read buffer length. No enabled channels?")
437
+ # Inconsistency
438
+ if value is None:
439
+ raise ValueError(
440
+ f"The buffer length differs from channel to channel"
441
+ )
442
+
443
+ # LOGGER.debug(f"get_buffer_length(master={master}) --> {buf_len}")
444
+
445
+ return value
446
+
447
+
448
+ def is_buffer_full(master, buffer_id):
449
+ bid = to_buffer_id(buffer_id)
450
+ command = b"buffer_full_%c" % bid
451
+ result = ffi.new("unsigned short *")
452
+ code = handel.xiaGetRunData(master, command, result)
453
+ check_error(code)
454
+ ibf = bool(result[0])
455
+
456
+ LOGGER.debug(f"is_buffer_full(master={master}, buffer_id={buffer_id}) --> {ibf}")
457
+
458
+ return ibf
459
+
460
+
461
+ def is_buffer_overrun(master):
462
+ result = ffi.new("unsigned short *")
463
+ code = handel.xiaGetRunData(master, b"buffer_overrun", result)
464
+ check_error(code)
465
+ ibo = bool(result[0])
466
+ if ibo:
467
+ LOGGER.debug(f"is_buffer_overrun(master={master}) --> {ibo}")
468
+ return ibo
469
+
470
+
471
+ def get_raw_buffer(master, buffer_id):
472
+ """
473
+ Read currently acquiered data from handel.
474
+ Return raw data.
475
+ Used in mapping mode.
476
+ """
477
+ bid = to_buffer_id(buffer_id)
478
+ command = b"buffer_%c" % bid
479
+ length = get_buffer_length(master)
480
+ LOGGER.debug(f"get_raw_buffer(master={master} buff id={buffer_id}) (len={length})")
481
+
482
+ array = numpy.zeros(length * 2, dtype="uint16")
483
+ data = ffi.cast("uint32_t *", array.ctypes.data)
484
+ code = handel.xiaGetRunData(master, command, data)
485
+ check_error(code)
486
+ # Check magic number
487
+ if array[0] == 0:
488
+ raise RuntimeError(
489
+ f"The buffer {str(buffer_id)} associated with channel {master} is empty"
490
+ )
491
+ # Return array
492
+ return array
493
+
494
+
495
+ def get_buffer_data(master, buffer_id):
496
+ LOGGER.debug(f"get_buffer_data(master={master} buff id={buffer_id})")
497
+ raw = get_raw_buffer(master, buffer_id)
498
+ return parse_mapping_buffer(raw)
499
+
500
+
501
+ def get_buffer_current_pixel(master):
502
+ current = ffi.new("unsigned long *")
503
+ code = handel.xiaGetRunData(master, b"current_pixel", current)
504
+ check_error(code)
505
+
506
+ cur_pix = current[0]
507
+ LOGGER.debug(f"get_buffer_current_pixel(master={master}) --> {cur_pix}")
508
+
509
+ return cur_pix
510
+
511
+
512
+ def set_buffer_done(master, buffer_id):
513
+ """Flag the the buffer as read and return an overrun detection.
514
+
515
+ False means no overrun have been detected.
516
+ True means a possible overrun have been detected.
517
+ """
518
+ bid = to_buffer_id(buffer_id)
519
+ code = handel.xiaBoardOperation(master, b"buffer_done", bid)
520
+ check_error(code)
521
+ other = b"b" if bid == b"a" else b"a"
522
+ overrun = is_buffer_full(master, other) and is_channel_running(master)
523
+ LOGGER.debug(
524
+ f"set_buffer_done(master={master} buff id={buffer_id} ) overrun={overrun}"
525
+ )
526
+ return overrun
527
+
528
+
529
+ # Synchronized run
530
+
531
+
532
+ def set_maximum_pixels_per_buffer():
533
+ """Set the maximum number of pixels per buffer.
534
+
535
+ It makes sure all the modules are configured with the same value,
536
+ to be able to perform synchronized run.
537
+ """
538
+ set_acquisition_value("num_map_pixels_per_buffer", -1)
539
+ value = min(
540
+ get_acquisition_value("num_map_pixels_per_buffer", master)
541
+ for master in get_master_channels()
542
+ )
543
+ LOGGER.debug(f"set_maximum_pixels_per_buffer() {value}")
544
+ set_acquisition_value("num_map_pixels_per_buffer", value)
545
+
546
+
547
+ def any_buffer_overrun():
548
+ """Return True if an overrun has been detected by the hardware on any
549
+ module, False otherwise.
550
+ """
551
+ return any(is_buffer_overrun(master) for master in get_master_channels())
552
+
553
+
554
+ def all_buffer_full(buffer_id):
555
+ """Return True if all the given buffers are full and ready to be read,
556
+ False otherwise.
557
+ """
558
+ return all(is_buffer_full(master, buffer_id) for master in get_master_channels())
559
+
560
+
561
+ def set_all_buffer_done(buffer_id):
562
+ """Flag all the given buffers as read and return an overrun detection.
563
+
564
+ False means no overrun have been detected.
565
+ True means an overrun have been detected.
566
+ """
567
+ overruns = [set_buffer_done(master, buffer_id) for master in get_master_channels()]
568
+ return any(overruns)
569
+
570
+
571
+ def get_current_pixel():
572
+ """
573
+ Return the max over all current pixel's channel.
574
+ """
575
+
576
+ # why MAX ???
577
+
578
+ all_current_pixels = (
579
+ get_buffer_current_pixel(master) for master in get_master_channels()
580
+ )
581
+ current_pixel = max(all_current_pixels)
582
+ # current_pixel = min(all_current_pixels)
583
+
584
+ LOGGER.debug(f"get_current_pixel() -> {current_pixel}")
585
+
586
+ return current_pixel
587
+
588
+
589
+ def get_all_buffer_data(buffer_id):
590
+ """Get and merge all the buffer data from the different channels.
591
+
592
+ Return a tuple (spectrums, statistics) where both values are dictionaries
593
+ of dictionaries, first indexed by pixel and then by channel."""
594
+ data = [get_buffer_data(master, buffer_id) for master in get_master_channels()]
595
+
596
+ LOGGER.debug(f"get_all_buffer_data(buffer_id={buffer_id}")
597
+
598
+ return merge_buffer_data(*data)
599
+
600
+
601
+
602
+ # Baseline
603
+
604
+
605
+ def get_baseline_length(channel):
606
+ length = ffi.new("unsigned long *")
607
+ code = handel.xiaGetRunData(channel, b"baseline_length", length)
608
+ check_error(code)
609
+ return length[0]
610
+
611
+
612
+ def get_baseline(channel):
613
+ length = get_baseline_length(channel)
614
+ array = numpy.zeros(length, dtype="uint32")
615
+ data = ffi.cast("uint32_t *", array.ctypes.data)
616
+ code = handel.xiaGetRunData(channel, b"baseline", data)
617
+ check_error(code)
618
+ return array
619
+
620
+
621
+ # Not exposed
622
+
623
+ # int xiaDoSpecialRun(int detChan, char *name, void *info);
624
+ # int xiaGetSpecialRunData(int detChan, char *name, void *value);
625
+
626
+
627
+ # System
628
+
629
+
630
+ def load_system(*path):
631
+ LOGGER.debug("load_system()")
632
+ filename = to_bytes(os.path.join(*path))
633
+ code = handel.xiaLoadSystem(b"handel_ini", filename)
634
+ check_error(code)
635
+
636
+
637
+ def save_system(*path):
638
+ LOGGER.debug("save_system()")
639
+ filename = to_bytes(os.path.join(*path))
640
+ code = handel.xiaSaveSystem(b"handel_ini", filename)
641
+ check_error(code)
642
+
643
+
644
+ def start_system():
645
+ """
646
+ Prepare hardware specified in .ini file.
647
+ To be called once after loading of a .ini file.
648
+ """
649
+ LOGGER.debug("start_system()")
650
+
651
+ code = handel.xiaStartSystem()
652
+ check_error(code)
653
+
654
+
655
+ # Logging
656
+
657
+
658
+ def enable_log_output():
659
+ code = handel.xiaEnableLogOutput()
660
+ check_error(code)
661
+
662
+
663
+ def disable_log_output():
664
+ code = handel.xiaSuppressLogOutput()
665
+ check_error(code)
666
+
667
+
668
+ def set_log_level(level):
669
+ code = handel.xiaSetLogLevel(level)
670
+ check_error(code)
671
+
672
+
673
+ def set_log_output(filename):
674
+ filename = to_bytes(filename)
675
+ code = handel.xiaSetLogOutput(filename)
676
+ check_error(code)
677
+
678
+
679
+ def close_log():
680
+ code = handel.xiaCloseLog()
681
+ check_error(code)
682
+
683
+
684
+ # Firmware
685
+
686
+ # Not exposed
687
+
688
+ # int xiaGetFirmwareItem(char *alias, unsigned short decimation, char *name, void *value);
689
+ # int xiaGetNumFirmwareSets(unsigned int *numFirmware);
690
+ # int xiaGetFirmwareSets(char *firmware[]);
691
+ # int xiaGetFirmwareSets_VB(unsigned int index, char *alias);
692
+ # int xiaGetNumPTRRs(char *alias, unsigned int *numPTRR);
693
+
694
+
695
+ # Module
696
+
697
+
698
+ def get_num_modules():
699
+ num_modules = ffi.new("unsigned int *")
700
+ code = handel.xiaGetNumModules(num_modules)
701
+ check_error(code)
702
+ return num_modules[0]
703
+
704
+
705
+ def get_modules():
706
+ """Return alias(es) of modules.
707
+ Ex: ['module1']
708
+ """
709
+ n = get_num_modules()
710
+ arg = [ffi.new("char []", MAX_STRING_LENGTH) for _ in range(n)]
711
+ code = handel.xiaGetModules(arg)
712
+ check_error(code)
713
+ return tuple(ffi.string(x).decode() for x in arg)
714
+
715
+
716
+ def get_module_url(alias):
717
+ alias = to_bytes(alias)
718
+ value = ffi.new("char []", MAX_STRING_LENGTH)
719
+ code = handel.xiaGetModuleItem(alias, b"inet_address", value)
720
+ check_error(code)
721
+ return ffi.string(value).decode()
722
+
723
+
724
+ def get_module_from_channel(channel):
725
+ alias = ffi.new("char []", MAX_STRING_LENGTH)
726
+ code = handel.xiaModuleFromDetChan(channel, alias)
727
+ check_error(code)
728
+ return ffi.string(alias).decode()
729
+
730
+
731
+ def get_module_type(alias=None):
732
+ if alias is None:
733
+ # Get all the values
734
+ values = [get_module_type(alias) for alias in get_modules()]
735
+ # Compare the values
736
+ if values:
737
+ value = reduce(lambda c, x: c if c == x else None, values)
738
+ else:
739
+ raise RuntimeError("Can't get module type. No enabled modules?")
740
+ # Inconsistency
741
+ if value is None:
742
+ raise ValueError("The module type differs from module to module")
743
+ # Return
744
+ return value
745
+ alias = to_bytes(alias)
746
+ value = ffi.new("char []", MAX_STRING_LENGTH)
747
+ code = handel.xiaGetModuleItem(alias, b"module_type", value)
748
+ check_error(code)
749
+ return ffi.string(value).decode()
750
+
751
+
752
+ def get_module_interface(alias):
753
+ alias = to_bytes(alias)
754
+ value = ffi.new("char []", MAX_STRING_LENGTH)
755
+ code = handel.xiaGetModuleItem(alias, b"interface", value)
756
+ check_error(code)
757
+ return ffi.string(value).decode()
758
+
759
+
760
+ # Detectors
761
+
762
+
763
+ def get_module_number_of_channels(alias):
764
+ alias = to_bytes(alias)
765
+ value = ffi.new("int *")
766
+ code = handel.xiaGetModuleItem(alias, b"number_of_channels", value)
767
+ check_error(code)
768
+ return value[0]
769
+
770
+
771
+ def get_module_channel_at(alias, index):
772
+ alias = to_bytes(alias)
773
+ value = ffi.new("int *")
774
+ key = b"channel%d_alias" % index
775
+ code = handel.xiaGetModuleItem(alias, key, value)
776
+ check_error(code)
777
+ return value[0]
778
+
779
+
780
+ def set_channel_alias(module, channel, alias):
781
+ module = to_bytes(module)
782
+ value = ffi.new("int *", alias)
783
+ key = b"channel%d_alias" % channel
784
+ code = handel.xiaModifyModuleItem(module, key, value)
785
+ check_error(code)
786
+ # return value[0]
787
+
788
+ def get_module_channels(alias):
789
+ """Return the module channels properly indexed.
790
+ Ex: fx2._proxy.get_module_channels(b"module1") -> [0, 1]
791
+ """
792
+ number_of_channels = get_module_number_of_channels(alias)
793
+ return tuple(
794
+ get_module_channel_at(alias, index) for index in range(number_of_channels)
795
+ )
796
+
797
+
798
+ def get_grouped_channels():
799
+ """Return the indexed channels grouped by modules.
800
+ Ex: [[0, 1]] (list in BLISS after rpc transport.)
801
+ """
802
+ grp_chans = tuple(get_module_channels(alias) for alias in get_modules())
803
+ # print("grp_chans= ", grp_chans)
804
+ return grp_chans
805
+
806
+
807
+ def get_channels():
808
+ """Return all the enabled channels."""
809
+ return tuple(
810
+ # sorted(
811
+ channel
812
+ for channels in get_grouped_channels()
813
+ for channel in channels
814
+ if channel >= 0
815
+ # )
816
+ )
817
+
818
+
819
+ def get_master_channels():
820
+ """Return one active channel for each buffer."""
821
+ # For the FalconX, each channel has its own buffer
822
+ if get_module_type().startswith("falconx"):
823
+ return get_channels()
824
+ # Otherwise, one channel per module is enough
825
+ return tuple(
826
+ next(channel for channel in groups if channel >= 0)
827
+ for groups in get_grouped_channels()
828
+ )
829
+
830
+
831
+ def get_trigger_channels():
832
+ """Return the list of channels that can be used
833
+ as gate master or sync master."""
834
+ return tuple(
835
+ groups[0] for groups in get_grouped_channels() if groups and groups[0] >= 0
836
+ )
837
+
838
+
839
+ # Not exposed
840
+
841
+ # int xiaGetModuleItem(char *alias, char *name, void *value);
842
+ # int xiaGetModules_VB(unsigned int index, char *alias);
843
+
844
+
845
+ # Parameters (acquisition values)
846
+
847
+
848
+ def get_acquisition_value(name, channel=None, raise_on_diff=False, reduce_values=True):
849
+ # Get values for all channels
850
+ if channel is None:
851
+ # Get all the values
852
+ values = [get_acquisition_value(name, channel) for channel in get_channels()]
853
+ if reduce_values is False:
854
+ return values
855
+ # Compare the values
856
+ if values:
857
+ value = reduce(lambda c, x: c if c == x else None, values)
858
+ else:
859
+ raise RuntimeError(f"Can't get acquisition value {name}. No enabled channels?")
860
+ # Inconsistency
861
+ if raise_on_diff and value is None:
862
+ raise ValueError(
863
+ f"The acquisition value {name} differs from channel to channel"
864
+ )
865
+ # Return
866
+ return value
867
+ # Get value for a single channel
868
+ name = to_bytes(name)
869
+ pointer = ffi.new("double *")
870
+ code = handel.xiaGetAcquisitionValues(channel, name, pointer)
871
+ check_error(code)
872
+ return pointer[0]
873
+
874
+
875
+ def set_acquisition_value(name, value, channel=None):
876
+ # LOGGER.info(f"set_acquisition_value({name}, \t{value}, ch={channel})")
877
+ if channel is None:
878
+ channels = get_channels() # All channels
879
+ else:
880
+ try:
881
+ channels = iter(channel)
882
+ except TypeError:
883
+ channels = [channel]
884
+ name = to_bytes(name)
885
+ for channel in channels:
886
+ pointer = ffi.new("double *", value)
887
+ code = handel.xiaSetAcquisitionValues(channel, name, pointer)
888
+ check_error(code)
889
+
890
+
891
+ def remove_acquisition_value(name, channel=None):
892
+ if channel is None:
893
+ channels = get_channels() # All channels
894
+ else:
895
+ try:
896
+ channels = iter(channel)
897
+ except TypeError:
898
+ channels = [channel]
899
+ name = to_bytes(name)
900
+ for channel in channels:
901
+ code = handel.xiaRemoveAcquisitionValues(channel, name)
902
+ check_error(code)
903
+
904
+
905
+ def apply_acquisition_values(channel=None):
906
+ # Apply all
907
+ if channel is None:
908
+ # Only one apply operation by module is required
909
+ for master in get_master_channels():
910
+ apply_acquisition_values(master)
911
+ return
912
+ # Apply single
913
+ dummy = ffi.new("int *")
914
+ code = handel.xiaBoardOperation(channel, b"apply", dummy)
915
+ check_error(code)
916
+
917
+
918
+ def print_acq_vals():
919
+ av_list = [
920
+ "analog_gain",
921
+ "analog_offset",
922
+ "detector_polarity",
923
+ "detector_polarity",
924
+ "termination",
925
+ "attenuation",
926
+ "coupling",
927
+ "decay_time",
928
+ # "dc_offset",
929
+ "reset_blanking_enable",
930
+ # "reset_blanking_threshold",
931
+ "reset_blanking_presamples",
932
+ "reset_blanking_postsamples",
933
+ "clock_speed",
934
+ "adc_trace_decimation",
935
+ # "detection_threshold",
936
+ "min_pulse_pair_separation",
937
+ # "risetime_optimization",
938
+ "detection_filter",
939
+ # "scale_factor",
940
+ "number_mca_channels",
941
+ "mca_spectrum_accepted",
942
+ "mca_spectrum_rejected",
943
+ "mca_start_channel",
944
+ "mca_refresh",
945
+ "mca_bin_width",
946
+ "preset_type",
947
+ "preset_value",
948
+ "mapping_mode",
949
+ "sca_advance_mode",
950
+ "sca_pulse_duration",
951
+ "number_of_scas",
952
+ # "sca",
953
+ "num_map_pixels",
954
+ "num_map_pixels_per_buffer",
955
+ "pixel_advance_mode",
956
+ "input_logic_polarity",
957
+ "gate_ignore",
958
+ "sync_count",
959
+ "auto_dc_offset",
960
+ ]
961
+
962
+ for av in av_list:
963
+ value = get_acquisition_value(av)
964
+ print(f"{av} = {value}")
965
+
966
+
967
+ # Not exposed
968
+
969
+ # int xiaGainOperation(int detChan, char *name, void *value);
970
+ # int xiaGainCalibrate(int detChan, double deltaGain);
971
+ # int xiaGetParameter(int detChan, const char *name, unsigned short *value);
972
+ # int xiaSetParameter(int detChan, const char *name, unsigned short value);
973
+ # int xiaGetNumParams(int detChan, unsigned short *numParams);
974
+ # int xiaGetParamData(int detChan, char *name, void *value);
975
+ # int xiaGetParamName(int detChan, unsigned short index, char *name);
976
+
977
+
978
+ # Operation
979
+
980
+ # Not exposed
981
+
982
+ # int xiaBoardOperation(int detChan, char *name, void *value) with mapping_pixel_next (int 0);
983
+ # int xiaMemoryOperation(int detChan, char *name, void *value);
984
+ # int xiaCommandOperation(int detChan, byte_t cmd, unsigned int lenS,
985
+ # byte_t *send, unsigned int lenR, byte_t *recv);
986
+
987
+ # Debugging
988
+
989
+
990
+ def get_handel_version():
991
+ _rel = ffi.new("int *")
992
+ _min = ffi.new("int *")
993
+ _maj = ffi.new("int *")
994
+ _pretty = ffi.new("char []", MAX_STRING_LENGTH)
995
+ handel.xiaGetVersionInfo(_rel, _min, _maj, _pretty)
996
+ return _maj[0], _min[0], _rel[0]
997
+
998
+
999
+ # Not exposed
1000
+
1001
+ # int xiaSetIOPriority(int pri);
1002
+
1003
+
1004
+ # Files
1005
+
1006
+
1007
+ def get_config_files(*path):
1008
+ """Return all the ini files in path (including subdirectories)."""
1009
+
1010
+ path = os.path.join(*path)
1011
+ ext = b".ini" if isinstance(path, bytes) else ".ini"
1012
+ sep = b"/" if isinstance(path, bytes) else "/"
1013
+ return [
1014
+ os.path.relpath(os.path.join(dp, f), path).lstrip(sep)
1015
+ for dp, dn, fn in os.walk(path)
1016
+ for f in fn
1017
+ if f.endswith(ext)
1018
+ ]
1019
+
1020
+
1021
+ def get_config(*path):
1022
+ """Read and return the given config file as a dictionary."""
1023
+ filename = os.path.join(*path)
1024
+ with open(filename) as config_file:
1025
+ return parse_xia_ini_file(config_file.read())