interface.py 13 KB
Newer Older
1
2
3
"""Python interface to handel API."""

from __future__ import absolute_import
Vincent Michel's avatar
Vincent Michel committed
4

Vincent Michel's avatar
Vincent Michel committed
5
6
import os

Vincent Michel's avatar
Vincent Michel committed
7
8
import numpy

9
from .error import check_error
10
from ._cffi import handel, ffi
Vincent Michel's avatar
Vincent Michel committed
11
from .parser import parse_xia_ini_file
12

13
14
__all__ = ['init', 'init_handel', 'exit',
           'new_detector', 'get_num_detectors', 'get_detectors',
15
           'get_detector_from_channel',
16
17
18
19
           'start_run', 'stop_run',
           'get_spectrum_length', 'get_spectrum', 'get_spectrums',
           'is_channel_running', 'is_running',
           'get_module_statistics', 'get_statistics',
20
           'get_buffer_length', 'get_buffer_full', 'get_buffer', 'buffer_done',
21
22
23
           'load_system', 'save_system', 'start_system',
           'enable_log_output', 'disable_log_output',
           'set_log_output', 'set_log_level', 'close_log',
24
           'get_num_modules', 'get_modules', 'get_module_from_channel',
Vincent Michel's avatar
Vincent Michel committed
25
           'get_module_type', 'get_module_interface',
Vincent Michel's avatar
Vincent Michel committed
26
           'get_module_channels', 'get_grouped_channels', 'get_channels',
27
           'set_acquisition_value', 'get_acquisition_value',
28
           'remove_acquisition_value', 'apply_acquisition_values',
29
30
           'get_handel_version']

31
32
MAX_STRING_LENGTH = 80

33
34
35
36
37
38
39
40

# Helpers

def to_bytes(arg):
    if isinstance(arg, bytes):
        return arg
    return arg.encode()

41

42
43
44
45
46
47
48
49
def to_buffer_id(bid):
    bid = to_bytes(bid.lower())
    if bid in (b'a', b'b'):
        return bid
    msg = '{!r} is not a valid buffer id'
    raise ValueError(msg.format(bid))


Vincent Michel's avatar
Vincent Michel committed
50
51
# Initializing handel

Vincent Michel's avatar
Vincent Michel committed
52
53
def init(*path):
    filename = to_bytes(os.path.join(*path))
54
55
    code = handel.xiaInit(filename)
    check_error(code)
56
57
58


def init_handel():
59
60
    code = handel.xiaInitHandel()
    check_error(code)
61
62


Vincent Michel's avatar
Vincent Michel committed
63
def exit():
64
65
    code = handel.xiaExit()
    check_error(code)
Vincent Michel's avatar
Vincent Michel committed
66
67
68
69


# Detectors

70
def new_detector(alias):
71
    alias = to_bytes(alias)
72
73
    code = handel.xiaNewDetector(alias)
    check_error(code)
74
75


76
77
def get_num_detectors():
    num = ffi.new('unsigned int *')
78
79
    code = handel.xiaGetNumDetectors(num)
    check_error(code)
80
81
82
83
84
    return num[0]


def get_detectors():
    n = get_num_detectors()
85
    arg = [ffi.new('char []', MAX_STRING_LENGTH) for _ in range(n)]
86
87
    code = handel.xiaGetDetectors(arg)
    check_error(code)
88
    return tuple(ffi.string(x).decode() for x in arg)
89

Vincent Michel's avatar
Vincent Michel committed
90

91
92
93
94
95
96
97
98
99
def get_detector_from_channel(channel):
    alias = ffi.new('char []', MAX_STRING_LENGTH)
    code = handel.xiaDetectorFromDetChan(channel, alias)
    check_error(code)
    return ffi.string(alias).decode()


# Not exposed

Vincent Michel's avatar
Vincent Michel committed
100
101
102
# int xiaAddDetectorItem(char *alias, char *name, void *value);
# int xiaModifyDetectorItem(char *alias, char *name, void *value);
# int xiaGetDetectorItem(char *alias, char *name, void *value);
103
104
# int xiaGetDetectors_VB(unsigned int index, char *alias);
# int xiaRemoveDetector(char *alias);
Vincent Michel's avatar
Vincent Michel committed
105
106
107
108


# Run control

109
110
111
def start_run(channel=None, resume=False):
    if channel is None:
        channel = -1  # All channels
112
113
    code = handel.xiaStartRun(channel, resume)
    check_error(code)
Vincent Michel's avatar
Vincent Michel committed
114
115


116
117
118
def stop_run(channel=None):
    if channel is None:
        channel = -1  # All channels
119
120
    code = handel.xiaStopRun(channel)
    check_error(code)
Vincent Michel's avatar
Vincent Michel committed
121
122


123
def get_spectrum_length(channel):
Vincent Michel's avatar
Vincent Michel committed
124
    length = ffi.new('unsigned long *')
Vincent Michel's avatar
Vincent Michel committed
125
    code = handel.xiaGetRunData(channel, b'mca_length', length)
126
    check_error(code)
Vincent Michel's avatar
Vincent Michel committed
127
128
129
    return length[0]


130
131
def get_spectrum(channel):
    length = get_spectrum_length(channel)
Vincent Michel's avatar
Vincent Michel committed
132
133
    array = numpy.zeros(length, dtype='uint32')
    data = ffi.cast('uint32_t *', array.ctypes.data)
Vincent Michel's avatar
Vincent Michel committed
134
    code = handel.xiaGetRunData(channel, b'mca', data)
135
    check_error(code)
Vincent Michel's avatar
Vincent Michel committed
136
137
138
    return array


139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
def get_spectrums():
    """Return the spectrums for all enabled channels as a dictionary."""
    return {channel: get_spectrum(channel) for channel in get_channels()}


def is_channel_running(channel):
    running = ffi.new('short *')
    code = handel.xiaGetRunData(channel, b'run_active', running)
    check_error(code)
    return bool(running[0])


def is_running():
    """Return True if any channel is running, False otherwise."""
    return any(map(is_channel_running, get_channels()))


# Statistics

def get_module_statistics(module):
    channels = get_module_channels(module)
    data_size = 7 * len(channels)
    master = next(c for c in channels if c != -1)
    array = numpy.zeros(data_size, dtype='double')
    data = ffi.cast('double *', array.ctypes.data)
    code = handel.xiaGetRunData(master, b'module_statistics', data)
    check_error(code)
    return {channel: array[index:index+7].tolist()
            for index, channel in enumerate(channels)
            if channel != -1}


def get_statistics():
    """Return the statistics for all enabled channels as a dictionary."""
    result = {}
    for module in get_modules():
        result.update(get_module_statistics(module))
    return result


179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
# Buffer

def get_buffer_length(channel):
    length = ffi.new('unsigned long *')
    code = handel.xiaGetRunData(channel, b'buffer_len', length)
    check_error(code)
    return length[0]


def get_buffer_full(channel, buffer_id):
    bid = to_buffer_id(buffer_id)
    command = b'buffer_full_%c' % bid
    result = ffi.new('unsigned short *')
    code = handel.xiaGetRunData(channel, command, result)
    check_error(code)
    return bool(result[0])


def get_buffer(channel, buffer_id):
    bid = to_buffer_id(buffer_id)
    command = b'buffer_%c' % bid
    length = get_buffer_length(channel)
Vincent Michel's avatar
Vincent Michel committed
201
202
    array = numpy.zeros(length, dtype='uint32')
    data = ffi.cast('uint32_t *', array.ctypes.data)
203
204
205
206
207
208
209
210
211
212
213
214
215
    code = handel.xiaGetRunData(channel, command, data)
    check_error(code)
    return array


def buffer_done(channel, buffer_id):
    bid = to_buffer_id(buffer_id)
    code = handel.xiaBoardOperation(channel, b'buffer_done', bid)
    check_error(code)


# Not exposed

Vincent Michel's avatar
Vincent Michel committed
216
217
218
219
220
221
# int xiaDoSpecialRun(int detChan, char *name, void *info);
# int xiaGetSpecialRunData(int detChan, char *name, void *value);


# System

Vincent Michel's avatar
Vincent Michel committed
222
223
def load_system(*path):
    filename = to_bytes(os.path.join(*path))
224
225
    code = handel.xiaLoadSystem(b'handel_ini', filename)
    check_error(code)
Vincent Michel's avatar
Vincent Michel committed
226
227


Vincent Michel's avatar
Vincent Michel committed
228
229
def save_system(*path):
    filename = to_bytes(os.path.join(*path))
230
231
    code = handel.xiaSaveSystem(b'handel_ini', filename)
    check_error(code)
Vincent Michel's avatar
Vincent Michel committed
232
233
234


def start_system():
235
236
    code = handel.xiaStartSystem()
    check_error(code)
Vincent Michel's avatar
Vincent Michel committed
237
238
239
240
241


# Logging

def enable_log_output():
242
243
    code = handel.xiaEnableLogOutput()
    check_error(code)
Vincent Michel's avatar
Vincent Michel committed
244
245
246


def disable_log_output():
247
248
    code = handel.xiaSuppressLogOutput()
    check_error(code)
Vincent Michel's avatar
Vincent Michel committed
249
250
251


def set_log_level(level):
252
253
    code = handel.xiaSetLogLevel(level)
    check_error(code)
Vincent Michel's avatar
Vincent Michel committed
254
255
256


def set_log_output(filename):
257
    filename = to_bytes(filename)
258
259
    code = handel.xiaSetLogOutput(filename)
    check_error(code)
Vincent Michel's avatar
Vincent Michel committed
260
261
262


def close_log():
263
264
    code = handel.xiaCloseLog()
    check_error(code)
Vincent Michel's avatar
Vincent Michel committed
265
266
267

# Firmware

268
269
# Not exposed

270
271
272
273
274
275
276
277
278
# int xiaNewFirmware(char *alias);
# int xiaAddFirmwareItem(char *alias, char *name, void *value);
# int xiaModifyFirmwareItem(char *alias, unsigned short decimation, char *name, void *value);
# int xiaGetFirmwareItem(char *alias, unsigned short decimation, char *name, void *value);
# int xiaGetNumFirmwareSets(unsigned int *numFirmware);
# int xiaGetFirmwareSets(char *firmware[]);
# int xiaGetFirmwareSets_VB(unsigned int index, char *alias);
# int xiaGetNumPTRRs(char *alias, unsigned int *numPTRR);
# int xiaRemoveFirmware(char *alias);
Vincent Michel's avatar
Vincent Michel committed
279
280
281
282
283
# int xiaDownloadFirmware(int detChan, char *type);


# Module

284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
def get_num_modules():
    num_modules = ffi.new('unsigned int *')
    code = handel.xiaGetNumModules(num_modules)
    check_error(code)
    return num_modules[0]


def get_modules():
    n = get_num_modules()
    arg = [ffi.new('char []', MAX_STRING_LENGTH) for _ in range(n)]
    code = handel.xiaGetModules(arg)
    check_error(code)
    return tuple(ffi.string(x).decode() for x in arg)


def get_module_from_channel(channel):
    alias = ffi.new('char []', MAX_STRING_LENGTH)
    code = handel.xiaModuleFromDetChan(channel, alias)
    check_error(code)
    return ffi.string(alias).decode()


306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
def get_module_type(alias):
    alias = to_bytes(alias)
    value = ffi.new('char []', MAX_STRING_LENGTH)
    code = handel.xiaGetModuleItem(alias, b'module_type', value)
    check_error(code)
    return ffi.string(value).decode()


def get_module_interface(alias):
    alias = to_bytes(alias)
    value = ffi.new('char []', MAX_STRING_LENGTH)
    code = handel.xiaGetModuleItem(alias, b'interface', value)
    check_error(code)
    return ffi.string(value).decode()


322
323
# Channels

324
325
326
327
328
329
330
331
def get_module_number_of_channels(alias):
    alias = to_bytes(alias)
    value = ffi.new('int *')
    code = handel.xiaGetModuleItem(alias, b'number_of_channels', value)
    check_error(code)
    return value[0]


Vincent Michel's avatar
Vincent Michel committed
332
333
334
335
336
337
338
339
340
341
def get_module_channel_at(alias, index):
    alias = to_bytes(alias)
    value = ffi.new('int *')
    key = b'channel%d_alias' % index
    code = handel.xiaGetModuleItem(alias, key, value)
    check_error(code)
    return value[0]


def get_module_channels(alias):
Vincent Michel's avatar
Vincent Michel committed
342
    """Return the module channels properly indexed."""
Vincent Michel's avatar
Vincent Michel committed
343
    number_of_channels = get_module_number_of_channels(alias)
Vincent Michel's avatar
Vincent Michel committed
344
345
    return tuple(get_module_channel_at(alias, index)
                 for index in range(number_of_channels))
Vincent Michel's avatar
Vincent Michel committed
346
347


Vincent Michel's avatar
Vincent Michel committed
348
def get_grouped_channels():
Vincent Michel's avatar
Vincent Michel committed
349
350
    """Return the indexed channels grouped by modules."""
    return tuple(get_module_channels(alias) for alias in get_modules())
Vincent Michel's avatar
Vincent Michel committed
351
352


Vincent Michel's avatar
Vincent Michel committed
353
354
def get_channels():
    """Return all the enabled channels."""
Vincent Michel's avatar
Vincent Michel committed
355
356
357
358
359
    return tuple(sorted(
        channel
        for channels in get_grouped_channels()
        for channel in channels
        if channel != -1))
Vincent Michel's avatar
Vincent Michel committed
360
361


362
363
# Not exposed

364
365
366
367
368
369
# int xiaNewModule(char *alias);
# int xiaAddModuleItem(char *alias, char *name, void *value);
# int xiaModifyModuleItem(char *alias, char *name, void *value);
# int xiaGetModuleItem(char *alias, char *name, void *value);
# int xiaGetModules_VB(unsigned int index, char *alias);
# int xiaRemoveModule(char *alias);
Vincent Michel's avatar
Vincent Michel committed
370
371
372
373


# Channel set

374
375
# Not exposed

376
377
378
# int xiaAddChannelSetElem(unsigned int detChanSet, unsigned int newChan);
# int xiaRemoveChannelSetElem(unsigned int detChan, unsigned int chan);
# int xiaRemoveChannelSet(unsigned int detChan);
Vincent Michel's avatar
Vincent Michel committed
379
380


381
382
# Parameters

383
def get_acquisition_value(name, channel):
384
    name = to_bytes(name)
385
386
    pointer = ffi.new('double *')
    code = handel.xiaGetAcquisitionValues(channel, name, pointer)
387
    check_error(code)
388
    return pointer[0]
389
390


391
392
393
def set_acquisition_value(name, value, channel=None):
    if channel is None:
        channel = -1  # All channels
394
    name = to_bytes(name)
395
396
    pointer = ffi.new('double *', value)
    code = handel.xiaSetAcquisitionValues(channel, name, pointer)
397
    check_error(code)
398

Vincent Michel's avatar
Vincent Michel committed
399

400
401
402
def remove_acquisition_value(name, channel=None):
    if channel is None:
        channel = -1  # All channels
403
404
405
406
407
    name = to_bytes(name)
    code = handel.xiaRemoveAcquisitionValues(channel, name)
    check_error(code)


408
409
410
411
412
413
414
415
416
def apply_acquisition_values(channel=None):
    # Apply all
    if channel is None:
        # Only one apply operation by module is required
        grouped = get_grouped_channels()
        for master in map(max, grouped):
            apply_acquisition_values(master)
        return
    # Apply single
417
418
419
420
421
422
423
    dummy = ffi.new('int *')
    code = handel.xiaBoardOperation(channel, b'apply', dummy)
    check_error(code)


# Not exposed

424
425
426
427
428
429
430
431
# int xiaUpdateUserParams(int detChan);
# int xiaGainOperation(int detChan, char *name, void *value);
# int xiaGainCalibrate(int detChan, double deltaGain);
# int xiaGetParameter(int detChan, const char *name, unsigned short *value);
# int xiaSetParameter(int detChan, const char *name, unsigned short value);
# int xiaGetNumParams(int detChan, unsigned short *numParams);
# int xiaGetParamData(int detChan, char *name, void *value);
# int xiaGetParamName(int detChan, unsigned short index, char *name);
Vincent Michel's avatar
Vincent Michel committed
432
433
434
435


# Operation

436
437
438
# Not exposed

# int xiaBoardOperation(int detChan, char *name, void *value) with mapping_pixel_next (int 0);
439
440
# int xiaMemoryOperation(int detChan, char *name, void *value);
# int xiaCommandOperation(int detChan, byte_t cmd, unsigned int lenS, byte_t *send, unsigned int lenR, byte_t *recv);
Vincent Michel's avatar
Vincent Michel committed
441
442
443
444


# Analysis

445
446
# Not exposed

447
448
# int xiaFitGauss(long data[], int lower, int upper, float *pos, float *fwhm);
# int xiaFindPeak(long *data, int numBins, float thresh, int *lower, int *upper);
Vincent Michel's avatar
Vincent Michel committed
449
450
451
452
453


# Debugging


454
def get_handel_version():
Vincent Michel's avatar
Vincent Michel committed
455
456
457
458
459
460
461
462
    rel = ffi.new('int *')
    min = ffi.new('int *')
    maj = ffi.new('int *')
    pretty = ffi.new('char *')
    handel.xiaGetVersionInfo(rel, min, maj, pretty)
    return maj[0], min[0], rel[0]


463
464
# Not exposed

465
466
467
468
# int xiaSetIOPriority(int pri);
# int xiaMemStatistics(unsigned long *total, unsigned long *current, unsigned long *peak);
# void xiaMemSetCheckpoint(void);
# void xiaMemLeaks(char *);
Vincent Michel's avatar
Vincent Michel committed
469
470
471
472


# Files

473
def get_config_files(*path):
Vincent Michel's avatar
Vincent Michel committed
474
    """Return all the ini files in path (including subdirectories)."""
475
    path = os.path.join(*path)
Vincent Michel's avatar
Vincent Michel committed
476
    ext = b'.ini' if isinstance(path, bytes) else '.ini'
Vincent Michel's avatar
Vincent Michel committed
477
478
    sep = b'/' if isinstance(path, bytes) else '/'
    return [os.path.join(dp, f).lstrip(path).lstrip(sep)
Vincent Michel's avatar
Vincent Michel committed
479
480
            for dp, dn, fn in os.walk(path)
            for f in fn
Vincent Michel's avatar
Vincent Michel committed
481
            if f.endswith(ext)]
Vincent Michel's avatar
Vincent Michel committed
482
483


484
def get_config(*path):
Vincent Michel's avatar
Vincent Michel committed
485
    """Read and return the given config file as a dictionary."""
486
    filename = os.path.join(*path)
487
    with open(filename) as f:
Vincent Michel's avatar
Vincent Michel committed
488
        return parse_xia_ini_file(f.read())