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.
- mosca/__init__.py +11 -0
- mosca/common/__init__.py +9 -0
- mosca/common/enums.py +79 -0
- mosca/common/logger.py +139 -0
- mosca/common/threads.py +199 -0
- mosca/common/utils.py +70 -0
- mosca/control/__init__.py +4 -0
- mosca/control/buffer.py +526 -0
- mosca/control/controller.py +278 -0
- mosca/control/datahandler.py +261 -0
- mosca/control/detectors.py +116 -0
- mosca/control/mosca.py +693 -0
- mosca/control/spectra.py +36 -0
- mosca/control/stats.py +43 -0
- mosca/control/tasks/__init__.py +3 -0
- mosca/control/tasks/background.py +118 -0
- mosca/control/tasks/rois.py +466 -0
- mosca/control/tasks/saving.py +391 -0
- mosca/control/tasks/spectrasums.py +185 -0
- mosca/control/tasks/task.py +201 -0
- mosca/control/tasks/taskmanager.py +133 -0
- mosca/devices/__init__.py +28 -0
- mosca/devices/hamamatsu/__init__.py +0 -0
- mosca/devices/hamamatsu/hamamatsu.py +88 -0
- mosca/devices/hamamatsu/hamamatsuhw.py +1298 -0
- mosca/devices/oceanoptics/__init__.py +0 -0
- mosca/devices/oceanoptics/oceanoptics.py +59 -0
- mosca/devices/oceanoptics/oceanopticshw.py +379 -0
- mosca/devices/simulation/__init__.py +0 -0
- mosca/devices/simulation/dante/__init__.py +1 -0
- mosca/devices/simulation/dante/simdante.py +33 -0
- mosca/devices/simulation/dante/simdantehw.py +506 -0
- mosca/devices/simulation/dummy/__init__.py +1 -0
- mosca/devices/simulation/dummy/dummy.py +299 -0
- mosca/devices/simulation/generator.py +607 -0
- mosca/devices/simulation/xia/__init__.py +1 -0
- mosca/devices/simulation/xia/iniparser.py +99 -0
- mosca/devices/simulation/xia/simfalconx.py +26 -0
- mosca/devices/simulation/xia/simfalconxhw.py +599 -0
- mosca/devices/xglab/__init__.py +0 -0
- mosca/devices/xglab/dante.py +126 -0
- mosca/devices/xglab/dantehw.py +1178 -0
- mosca/devices/xia/__init__.py +0 -0
- mosca/devices/xia/falconx.py +232 -0
- mosca/devices/xia/handel/__init__.py +14 -0
- mosca/devices/xia/handel/_cffi.py +62 -0
- mosca/devices/xia/handel/error.py +272 -0
- mosca/devices/xia/handel/handel_inc/handel_constants.h +127 -0
- mosca/devices/xia/handel/handel_inc/handel_errors.h +254 -0
- mosca/devices/xia/handel/handel_inc/handel_generic.h +66 -0
- mosca/devices/xia/handel/interface.py +1025 -0
- mosca/devices/xia/handel/mapping.py +107 -0
- mosca/devices/xia/handel/parser.py +62 -0
- mosca/devices/xia/handel/stats.py +85 -0
- mosca/devices/xia/mercury.py +160 -0
- mosca/devices/xia/utils.py +47 -0
- mosca/devices/xia/xia.py +575 -0
- mosca/devices/xia/xiads.py +161 -0
- mosca/mosca.py +0 -0
- mosca/tango/__init__.py +2 -0
- mosca/tango/controller.py +80 -0
- mosca/tango/main.py +163 -0
- mosca/tango/mosca.py +513 -0
- mosca/tango/moscav1.py +408 -0
- mosca/tango/shared.py +23 -0
- mosca/tango/tasks/__init__.py +0 -0
- mosca/tango/tasks/background.py +55 -0
- mosca/tango/utils.py +109 -0
- mosca-2.0.2.dist-info/METADATA +32 -0
- mosca-2.0.2.dist-info/RECORD +73 -0
- mosca-2.0.2.dist-info/WHEEL +4 -0
- mosca-2.0.2.dist-info/entry_points.txt +2 -0
- mosca-2.0.2.dist-info/licenses/LICENSE +166 -0
mosca/control/spectra.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
|
|
3
|
+
from .buffer import CircularBuffer
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
import logging
|
|
7
|
+
logger = logging.getLogger(__name__)
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class Spectra:
|
|
11
|
+
# TODO: accumulation
|
|
12
|
+
n_points = property(lambda self: self._data.n_points)
|
|
13
|
+
|
|
14
|
+
buffer_size = property(lambda self: self._data.buffer_size)
|
|
15
|
+
|
|
16
|
+
clear = property(lambda self: self._data.clear)
|
|
17
|
+
locked = property(lambda self: self._data.locked)
|
|
18
|
+
lock = property(lambda self: self._data.lock)
|
|
19
|
+
unlock = property(lambda self: self._data.unlock)
|
|
20
|
+
|
|
21
|
+
spectrum_size = property(lambda self: self._data.data_size)
|
|
22
|
+
|
|
23
|
+
__getitem__ = property(lambda self: self._data.__getitem__)
|
|
24
|
+
flatten = property(lambda self: self._data.flatten)
|
|
25
|
+
|
|
26
|
+
def __init__(self, buffer_size=15000, dtype=np.uint32):
|
|
27
|
+
self._data = CircularBuffer(buffer_size=buffer_size, dtype=dtype)
|
|
28
|
+
|
|
29
|
+
def prepare(self, n_items=None, spectrum_size=None):
|
|
30
|
+
self._data.prepare(n_items=n_items, data_size=spectrum_size)
|
|
31
|
+
|
|
32
|
+
def add_spectra(self, spectra):
|
|
33
|
+
return self._data.add_data(spectra)
|
|
34
|
+
|
|
35
|
+
def get_spectra(self, *args, **kwargs):
|
|
36
|
+
return self._data.get_data(*args, **kwargs)
|
mosca/control/stats.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
|
|
3
|
+
from .buffer import CircularBuffer
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
logger = logging.getLogger(__name__)
|
|
7
|
+
|
|
8
|
+
class Stats:
|
|
9
|
+
# TODO: accumulation
|
|
10
|
+
|
|
11
|
+
names = property(lambda self: self._names)
|
|
12
|
+
|
|
13
|
+
n_points = property(lambda self: self._data.n_points)
|
|
14
|
+
|
|
15
|
+
buffer_size = property(lambda self: self._data.buffer_size)
|
|
16
|
+
|
|
17
|
+
locked = property(lambda self: self._data.locked)
|
|
18
|
+
lock = property(lambda self: self._data.lock)
|
|
19
|
+
unlock = property(lambda self: self._data.unlock)
|
|
20
|
+
|
|
21
|
+
__getitem__ = property(lambda self: self._data.__getitem__)
|
|
22
|
+
flatten = property(lambda self: self._data.flatten)
|
|
23
|
+
|
|
24
|
+
def __init__(self, buffer_size=15000, dtype=np.float64):
|
|
25
|
+
self._data = CircularBuffer(buffer_size=buffer_size, dtype=dtype)
|
|
26
|
+
self._names = tuple()
|
|
27
|
+
|
|
28
|
+
def prepare(self, n_items=None, names=None):
|
|
29
|
+
if not names:
|
|
30
|
+
self._names = tuple()
|
|
31
|
+
else:
|
|
32
|
+
self._names = tuple(names)
|
|
33
|
+
|
|
34
|
+
self._data.prepare(n_items=n_items, data_size=len(self._names))
|
|
35
|
+
|
|
36
|
+
def clear(self):
|
|
37
|
+
self._data.clear()
|
|
38
|
+
|
|
39
|
+
def add_stats(self, stats):
|
|
40
|
+
return self._data.add_data(stats)
|
|
41
|
+
|
|
42
|
+
def get_stats(self, *args, **kwargs):
|
|
43
|
+
return self._data.get_data(*args, **kwargs)
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import time
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
from .task import LinkTask
|
|
7
|
+
|
|
8
|
+
import logging
|
|
9
|
+
logger = logging.getLogger(__name__)
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Background(LinkTask):
|
|
13
|
+
def __init__(self, *args, **kwargs):
|
|
14
|
+
super().__init__(*args, **kwargs)
|
|
15
|
+
|
|
16
|
+
# True if the background is enabled to acquired data
|
|
17
|
+
self._is_bkg_applied = False
|
|
18
|
+
|
|
19
|
+
# stored spectra used for background
|
|
20
|
+
self._bkg_spectra = None
|
|
21
|
+
# stats associated with the spectra used for background
|
|
22
|
+
self._bkg_stats = None
|
|
23
|
+
# detectors associated with the spectra used for background
|
|
24
|
+
self._bkg_detectors = None
|
|
25
|
+
|
|
26
|
+
# last acquired spectra/stats, will be used if user call store_background
|
|
27
|
+
self._last_spectra = None
|
|
28
|
+
self._last_stats = None
|
|
29
|
+
self._last_detectors = None
|
|
30
|
+
|
|
31
|
+
@property
|
|
32
|
+
def is_background_applied(self) -> bool:
|
|
33
|
+
""" True if the background processing is enabled. """
|
|
34
|
+
return self._is_bkg_applied
|
|
35
|
+
|
|
36
|
+
@is_background_applied.setter
|
|
37
|
+
def is_background_applied(self, background_applied: bool):
|
|
38
|
+
""" Turns background processing on. Only if a background has been
|
|
39
|
+
stored. """
|
|
40
|
+
if background_applied and self._bkg_spectra is None:
|
|
41
|
+
raise RuntimeError("Can't enable background processing "
|
|
42
|
+
"without background data.")
|
|
43
|
+
self._is_bkg_applied = background_applied
|
|
44
|
+
|
|
45
|
+
def is_active(self):
|
|
46
|
+
""" Always True for the datamanager to pass it new data, even if the
|
|
47
|
+
background processing is disabled, so that the task can store the last
|
|
48
|
+
point, in case the user decides to use it as background. """
|
|
49
|
+
return True
|
|
50
|
+
|
|
51
|
+
def _new_data(self, spectra, stats):
|
|
52
|
+
""" Processed new data.
|
|
53
|
+
If background is not enabled, it stores the last point and stats.
|
|
54
|
+
This stored data can then be used as background if store_background is called.
|
|
55
|
+
|
|
56
|
+
If the background is enabled, the stored "last spectra" is cleared.
|
|
57
|
+
To change the enabled background, the user has to disable background processing,
|
|
58
|
+
acquire a point, call store_background, and reenable the background processing. """
|
|
59
|
+
if self._bkg_spectra is not None and self.is_background_applied:
|
|
60
|
+
self._last_spectra = None
|
|
61
|
+
self._last_stats = None
|
|
62
|
+
self._last_detectors = None
|
|
63
|
+
spectra -= self._bkg_spectra
|
|
64
|
+
|
|
65
|
+
oflow = np.where(spectra < 0)
|
|
66
|
+
spectra[oflow] = 0
|
|
67
|
+
else:
|
|
68
|
+
self._last_spectra = spectra[:, -1, :]
|
|
69
|
+
if stats is not None:
|
|
70
|
+
self._last_stats = stats[:, -1, :]
|
|
71
|
+
# this is a tuple, no need to copy
|
|
72
|
+
self._last_detectors = self._detectors
|
|
73
|
+
|
|
74
|
+
return spectra, stats
|
|
75
|
+
|
|
76
|
+
def store_background(self):
|
|
77
|
+
""" Use the last point, if available, as background.
|
|
78
|
+
User then need to """
|
|
79
|
+
if self._last_spectra is None:
|
|
80
|
+
raise RuntimeError("No data available, please run an acquisition first."
|
|
81
|
+
" then call this function again.")
|
|
82
|
+
self._bkg_spectra = self._last_spectra
|
|
83
|
+
self._bkg_spectra.shape = len(self._last_detectors), 1, -1
|
|
84
|
+
self._last_spectra = None
|
|
85
|
+
self._bkg_stats = self._last_stats
|
|
86
|
+
self._last_stats = None
|
|
87
|
+
self._bkg_detectors = self._last_detectors
|
|
88
|
+
self._last_detectors = None
|
|
89
|
+
|
|
90
|
+
def _prepare(self, *args, **kwargs):
|
|
91
|
+
""" Mostly just checks for background/controller configuration coherence. """
|
|
92
|
+
spectrum_size = self.spectrum_size
|
|
93
|
+
if not self.is_background_applied:
|
|
94
|
+
return
|
|
95
|
+
if self.detectors != self._bkg_detectors:
|
|
96
|
+
raise RuntimeError("Detectors mismatch between stored background and "
|
|
97
|
+
"detector configuration: "
|
|
98
|
+
f"{self.detectors} != {self._bkg_detectors}.")
|
|
99
|
+
|
|
100
|
+
if self._bkg_spectra.shape[-1] != spectrum_size:
|
|
101
|
+
raise RuntimeError("Spectrum size mismatch between stored background and "
|
|
102
|
+
"detector configuration:"
|
|
103
|
+
f"{spectrum_size, self._bkg_spectra.shape[-1]}")
|
|
104
|
+
|
|
105
|
+
def background_spectra(self):
|
|
106
|
+
if self._bkg_spectra is not None:
|
|
107
|
+
return self._bkg_spectra[:]
|
|
108
|
+
return np.array([])
|
|
109
|
+
|
|
110
|
+
def background_stats(self):
|
|
111
|
+
if self._bkg_stats is not None:
|
|
112
|
+
return self._bkg_stats[:]
|
|
113
|
+
return np.array([])
|
|
114
|
+
|
|
115
|
+
def background_detectors(self):
|
|
116
|
+
if self._bkg_detectors is not None:
|
|
117
|
+
return self._bkg_detectors
|
|
118
|
+
return tuple()
|
|
@@ -0,0 +1,466 @@
|
|
|
1
|
+
# for python < 3.10
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import logging
|
|
5
|
+
logger = logging.getLogger(__name__)
|
|
6
|
+
|
|
7
|
+
import copy
|
|
8
|
+
import time
|
|
9
|
+
from dataclasses import dataclass, astuple, asdict
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
|
|
13
|
+
from .task import SinkTask
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass
|
|
17
|
+
class RoiParams:
|
|
18
|
+
"""
|
|
19
|
+
Class used for roi definitions and individual rois.
|
|
20
|
+
"""
|
|
21
|
+
basename: str = ""
|
|
22
|
+
name: str | None = None
|
|
23
|
+
ch0: int | None = None
|
|
24
|
+
ch1: int | None = None
|
|
25
|
+
detectors: int | tuple[int] | None = None
|
|
26
|
+
is_sum: bool = False
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class InvalidRoiException(Exception):
|
|
30
|
+
pass
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class Roi:
|
|
34
|
+
def __init__(self, roi, spectrum_size: int, available_detectors: list[int], dtype=int):
|
|
35
|
+
# TODO: just store the roi struct
|
|
36
|
+
self._dtype = dtype
|
|
37
|
+
self.name = roi.name
|
|
38
|
+
self.basename = roi.basename
|
|
39
|
+
self.is_sum = roi.is_sum
|
|
40
|
+
self.ch0, self.ch1 = roi.ch0, roi.ch1
|
|
41
|
+
self.detectors = copy.copy(roi.detectors)
|
|
42
|
+
|
|
43
|
+
if spectrum_size <= 0:
|
|
44
|
+
raise InvalidRoiException(f"Roi {self.name}: "
|
|
45
|
+
f"invalid spectrum_size (={spectrum_size}).")
|
|
46
|
+
|
|
47
|
+
if not available_detectors:
|
|
48
|
+
raise InvalidRoiException(f"Roi {self.name}: "
|
|
49
|
+
"missing detector detectors.")
|
|
50
|
+
|
|
51
|
+
b0 = roi.ch0
|
|
52
|
+
b1 = roi.ch1
|
|
53
|
+
roi_detectors = roi.detectors
|
|
54
|
+
|
|
55
|
+
if not roi.is_sum:
|
|
56
|
+
roi_detectors = [roi_detectors]
|
|
57
|
+
|
|
58
|
+
if b1 > spectrum_size:
|
|
59
|
+
logger.warning("Roi: clipping roi (id=%s) "
|
|
60
|
+
"range=%s to fit "
|
|
61
|
+
"spectrum size of %d.",
|
|
62
|
+
self.name, (b0, b1), spectrum_size)
|
|
63
|
+
b1 = spectrum_size - 1
|
|
64
|
+
bins_slice = np.s_[b0:b1 + 1]
|
|
65
|
+
|
|
66
|
+
detectors_slice = None
|
|
67
|
+
|
|
68
|
+
index = [i_chan for i_chan, chan in enumerate(available_detectors)
|
|
69
|
+
if chan in roi_detectors]
|
|
70
|
+
if len(index) == 1:
|
|
71
|
+
detectors_slice = index
|
|
72
|
+
elif index:
|
|
73
|
+
# checking if detectors are consecutive => use np.s_ to get a view instead of a copy
|
|
74
|
+
imin = min(index)
|
|
75
|
+
imax = max(index)
|
|
76
|
+
if np.array_equal(sorted(index), np.arange(imin, imax + 1)):
|
|
77
|
+
detectors_slice = np.s_[imin:imax + 1]
|
|
78
|
+
else:
|
|
79
|
+
detectors_slice = np.array(index, dtype=np.int32)
|
|
80
|
+
else:
|
|
81
|
+
raise InvalidRoiException(f"No valid detectors available for roi {self.name}."
|
|
82
|
+
f"roi detectors={roi.detectors}, "
|
|
83
|
+
f"avail detectors={available_detectors}.")
|
|
84
|
+
|
|
85
|
+
logger.info("Roi(name=%s, bins_slice=%s, detectors_slice=%s)",
|
|
86
|
+
roi.name,
|
|
87
|
+
bins_slice,
|
|
88
|
+
detectors_slice)
|
|
89
|
+
self._channels_slice = bins_slice
|
|
90
|
+
self._detectors_slice = detectors_slice
|
|
91
|
+
|
|
92
|
+
def __call__(self, spectra):
|
|
93
|
+
return np.sum(spectra[self._detectors_slice, :, self._channels_slice],
|
|
94
|
+
axis=(0, 2),
|
|
95
|
+
dtype=self._dtype)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class Rois(SinkTask):
|
|
99
|
+
""" Task handling the Rois.
|
|
100
|
+
|
|
101
|
+
User adds roi definitions.
|
|
102
|
+
When the list of valid rois is requested, the definitions
|
|
103
|
+
are parsed and actual rois are created,
|
|
104
|
+
depending on the enabled detectors.
|
|
105
|
+
"""
|
|
106
|
+
|
|
107
|
+
n_roi_definitions = property(lambda self: len(self._roi_definitions))
|
|
108
|
+
""" Number of roi definitions. """
|
|
109
|
+
|
|
110
|
+
def __init__(self, *args, **kwargs):
|
|
111
|
+
if "dtype" not in kwargs:
|
|
112
|
+
kwargs['dtype'] = int
|
|
113
|
+
super().__init__(*args, **kwargs)
|
|
114
|
+
self._roi_definitions = {}
|
|
115
|
+
|
|
116
|
+
# WARNING! None == uninitialized. Dont change it!
|
|
117
|
+
# self._roi_singles = None
|
|
118
|
+
# self._roi_sums = None
|
|
119
|
+
self._rois = None
|
|
120
|
+
self._roi_invalid = None
|
|
121
|
+
self._counters = None
|
|
122
|
+
|
|
123
|
+
def rois_dict(self):
|
|
124
|
+
return {idx: asdict(roi) for idx, roi in enumerate(self.rois().values())}
|
|
125
|
+
|
|
126
|
+
def definitions_dict(self):
|
|
127
|
+
return {idx: asdict(definition)
|
|
128
|
+
for idx, definition in enumerate(self.roi_definitions().values())}
|
|
129
|
+
|
|
130
|
+
def metadata(self):
|
|
131
|
+
# TODO: cache metadata?
|
|
132
|
+
metadata = copy.deepcopy(super().metadata())
|
|
133
|
+
n_rois = self.n_items
|
|
134
|
+
metadata["n_rois"] = n_rois
|
|
135
|
+
metadata["definitions"] = self.definitions_dict()
|
|
136
|
+
metadata["rois"] = self.rois_dict()
|
|
137
|
+
return metadata
|
|
138
|
+
|
|
139
|
+
def roi_definitions(self):
|
|
140
|
+
""" roi definitions. """
|
|
141
|
+
return self._roi_definitions
|
|
142
|
+
|
|
143
|
+
def clear_definitions(self):
|
|
144
|
+
self._roi_definitions = {}
|
|
145
|
+
self.clear()
|
|
146
|
+
|
|
147
|
+
def rois(self):
|
|
148
|
+
self._parse_definitions()
|
|
149
|
+
return self._rois
|
|
150
|
+
|
|
151
|
+
def roi_singles(self):
|
|
152
|
+
""" roi counters. """
|
|
153
|
+
# self._parse_definitions()
|
|
154
|
+
# return self._roi_singles
|
|
155
|
+
return {key: value for key, value in self.rois().items() if not value.is_sum}
|
|
156
|
+
# singles, sums = {}, {}
|
|
157
|
+
# for key, value in parsed.items():
|
|
158
|
+
# (singles, sums)[value.is_sum].update({key:value})
|
|
159
|
+
|
|
160
|
+
def roi_sums(self):
|
|
161
|
+
""" sum of rois """
|
|
162
|
+
# self._parse_definitions()
|
|
163
|
+
# return self._roi_sums
|
|
164
|
+
return {key: value for key, value in self.rois().items() if value.is_sum}
|
|
165
|
+
|
|
166
|
+
def roi_invalid(self):
|
|
167
|
+
""" Rois that are invalid,
|
|
168
|
+
usually because they have no enabled detectors. """
|
|
169
|
+
self._parse_definitions()
|
|
170
|
+
return self._roi_invalid
|
|
171
|
+
|
|
172
|
+
def n_rois(self):
|
|
173
|
+
""" Number of valid rois (single and sums). """
|
|
174
|
+
return len(self.rois())
|
|
175
|
+
# return len(self.roi_singles()) + len(self.roi_sums())
|
|
176
|
+
|
|
177
|
+
def roi_counters(self):
|
|
178
|
+
""" Compute units generated from the roi definitions.
|
|
179
|
+
Only rois which detectors are enabled. """
|
|
180
|
+
if self._counters is None:
|
|
181
|
+
self._init_counters()
|
|
182
|
+
return self._counters[:]
|
|
183
|
+
|
|
184
|
+
def add_roi(self, name, first_chan, last_chan, *detectors):
|
|
185
|
+
""" Adds a roi definition. If detector is not provided,
|
|
186
|
+
a roi will be computed on each available detectors.
|
|
187
|
+
"""
|
|
188
|
+
# unicity is base on [name, detectors]
|
|
189
|
+
self.clear()
|
|
190
|
+
logger.info("New roi definition: basename=%s, channels=[%d..%d], detectors=%s.",
|
|
191
|
+
name, first_chan, last_chan, detectors)
|
|
192
|
+
n = len(detectors)
|
|
193
|
+
if n == 0:
|
|
194
|
+
detectors = None
|
|
195
|
+
elif n == 1:
|
|
196
|
+
detectors = detectors[0]
|
|
197
|
+
# False because NOT is_sum
|
|
198
|
+
self._roi_definitions[(name, detectors, False)] = \
|
|
199
|
+
RoiParams(basename=name,
|
|
200
|
+
ch0=first_chan,
|
|
201
|
+
ch1=last_chan,
|
|
202
|
+
detectors=detectors,
|
|
203
|
+
is_sum=False)
|
|
204
|
+
# (name, first_chan, last_chan, detectors, False)
|
|
205
|
+
|
|
206
|
+
def add_roi_sum(self, name, first_chan, last_chan, *detectors):
|
|
207
|
+
""" Adds a roi sum definition. If detector is not provided,
|
|
208
|
+
all available detectors will be used.
|
|
209
|
+
"""
|
|
210
|
+
# unicity is base on [name, detectors]
|
|
211
|
+
self.clear()
|
|
212
|
+
logger.info("New roi sunm definition: name=%s, channels=[%d..%d], detectors=%s.",
|
|
213
|
+
name, first_chan, last_chan, detectors)
|
|
214
|
+
n = len(detectors)
|
|
215
|
+
if n == 0:
|
|
216
|
+
detectors = None
|
|
217
|
+
# True because is_sum
|
|
218
|
+
self._roi_definitions[(name, detectors, True)] = \
|
|
219
|
+
RoiParams(basename=name,
|
|
220
|
+
ch0=first_chan,
|
|
221
|
+
ch1=last_chan,
|
|
222
|
+
detectors=detectors,
|
|
223
|
+
is_sum=True)
|
|
224
|
+
# (name, first_chan, last_chan, detectors, True)
|
|
225
|
+
|
|
226
|
+
def remove_roi(self, name, *detectors):
|
|
227
|
+
""" Remove the single roi definition matching
|
|
228
|
+
at least name, and detectors if provided.
|
|
229
|
+
"""
|
|
230
|
+
return self._remove_roi(name, *detectors, is_sum=False)
|
|
231
|
+
|
|
232
|
+
def remove_roi_sum(self, name, *detectors):
|
|
233
|
+
""" Remove the roi sum definition matching
|
|
234
|
+
at least name, and detectors if provided.
|
|
235
|
+
"""
|
|
236
|
+
return self._remove_roi(name, *detectors, is_sum=True)
|
|
237
|
+
|
|
238
|
+
def remove_roi_by_index(self, index):
|
|
239
|
+
keys = list(self._roi_definitions.keys())
|
|
240
|
+
try:
|
|
241
|
+
key = keys[index]
|
|
242
|
+
except IndexError:
|
|
243
|
+
rc = False
|
|
244
|
+
else:
|
|
245
|
+
self._roi_definitions.pop(key)
|
|
246
|
+
logger.info("Removed roi #%d (%s, %s, %s).",
|
|
247
|
+
index, *key)
|
|
248
|
+
self.clear()
|
|
249
|
+
rc = True
|
|
250
|
+
return rc
|
|
251
|
+
|
|
252
|
+
def _remove_roi(self, name, *detectors, is_sum=False):
|
|
253
|
+
""" Remove roi definition(s):
|
|
254
|
+
- if detector is provided: matches name, detectors and is_sum
|
|
255
|
+
- if detector is not provided: matches name and is_sum
|
|
256
|
+
"""
|
|
257
|
+
if not detectors:
|
|
258
|
+
# remove all rois matching name
|
|
259
|
+
detectors = None
|
|
260
|
+
elif not is_sum and len(detectors) == 1:
|
|
261
|
+
detectors = detectors[0]
|
|
262
|
+
|
|
263
|
+
self.clear()
|
|
264
|
+
if detectors is None:
|
|
265
|
+
for definition in list(self._roi_definitions.keys()):
|
|
266
|
+
if definition[0] == name and definition[2] == is_sum:
|
|
267
|
+
del self._roi_definitions[definition]
|
|
268
|
+
else:
|
|
269
|
+
try:
|
|
270
|
+
self._roi_definitions.pop((name, detectors, is_sum))
|
|
271
|
+
logger.info("Removed roi (%s, %s, %s).",
|
|
272
|
+
name, detectors, is_sum)
|
|
273
|
+
return True
|
|
274
|
+
except KeyError:
|
|
275
|
+
logger.warning("Can't remove roi (%s, %s, %s), no match.",
|
|
276
|
+
name, detectors, is_sum)
|
|
277
|
+
return False
|
|
278
|
+
|
|
279
|
+
def _clear(self):
|
|
280
|
+
logger.debug("Clearing rois counters.")
|
|
281
|
+
# WARNING! None == uninitialized. Dont change it!
|
|
282
|
+
# self._roi_singles = None
|
|
283
|
+
# self._roi_sums = None
|
|
284
|
+
self._rois = None
|
|
285
|
+
self._roi_invalid = None
|
|
286
|
+
self._counters = None
|
|
287
|
+
|
|
288
|
+
def is_active(self):
|
|
289
|
+
return self.n_roi_definitions > 0
|
|
290
|
+
|
|
291
|
+
def is_running(self):
|
|
292
|
+
""" Redefinitions of method, roi task can have rois defined
|
|
293
|
+
on disabled detectors, so return False if there are only
|
|
294
|
+
definitions for disabled detectors.
|
|
295
|
+
"""
|
|
296
|
+
return self.is_active() and self.n_rois() > 0
|
|
297
|
+
|
|
298
|
+
def _prepare(self, *args, **kwargs):
|
|
299
|
+
self._parse_definitions()
|
|
300
|
+
self._init_counters()
|
|
301
|
+
|
|
302
|
+
def _n_items(self):
|
|
303
|
+
return self.n_rois()
|
|
304
|
+
|
|
305
|
+
def _data_size(self):
|
|
306
|
+
return 1
|
|
307
|
+
|
|
308
|
+
def _new_data(self, spectra, stats):
|
|
309
|
+
self._calc_rois(spectra, stats)
|
|
310
|
+
|
|
311
|
+
def _parse_definitions(self):
|
|
312
|
+
detectors = self.detectors
|
|
313
|
+
if self._rois is None:
|
|
314
|
+
# self._roi_singles = {}
|
|
315
|
+
# self._roi_sums = {}
|
|
316
|
+
self._rois = {}
|
|
317
|
+
self._roi_invalid = {}
|
|
318
|
+
parsed = {}
|
|
319
|
+
n_sums = 0
|
|
320
|
+
|
|
321
|
+
dtype = self.dtype
|
|
322
|
+
spectrum_size = self.spectrum_size
|
|
323
|
+
logger.info("Initializing ROIS. Detectors=%s,"
|
|
324
|
+
"spectrum size=%s, dtype=%s.",
|
|
325
|
+
self.detectors, spectrum_size, dtype)
|
|
326
|
+
for roidef in self._roi_definitions.values():
|
|
327
|
+
name, _, ch0, ch1, detectors, is_sum = astuple(roidef)
|
|
328
|
+
try:
|
|
329
|
+
_ = len(detectors)
|
|
330
|
+
except TypeError:
|
|
331
|
+
detectors = [detectors]
|
|
332
|
+
|
|
333
|
+
rois, invalid = roidef_to_rois(self.detectors,
|
|
334
|
+
name,
|
|
335
|
+
ch0,
|
|
336
|
+
ch1,
|
|
337
|
+
*detectors,
|
|
338
|
+
is_sum=is_sum)
|
|
339
|
+
|
|
340
|
+
# if not is_sum:
|
|
341
|
+
for (name, detector), value in rois.items():
|
|
342
|
+
if not is_sum:
|
|
343
|
+
roi_cnt_name = f"{name}_det{detector:02d}"
|
|
344
|
+
else:
|
|
345
|
+
if not detector or detector == -1:
|
|
346
|
+
# a sum over all available detectors
|
|
347
|
+
roi_cnt_name = f"{name}_sum_all"
|
|
348
|
+
else:
|
|
349
|
+
# a sum over the given set of detectors
|
|
350
|
+
roi_cnt_name = f"{name}_sum{n_sums:02d}"
|
|
351
|
+
n_sums += 1
|
|
352
|
+
roi = RoiParams(basename=name,
|
|
353
|
+
name=roi_cnt_name,
|
|
354
|
+
ch0=value[0][0],
|
|
355
|
+
ch1=value[0][1],
|
|
356
|
+
detectors=value[1],
|
|
357
|
+
is_sum=is_sum)
|
|
358
|
+
try:
|
|
359
|
+
prev = parsed[(roi_cnt_name, detector)]
|
|
360
|
+
# that definition overwrites a previous one
|
|
361
|
+
# e.g : a roi named Fe was defined on detectors 2, 3, 4
|
|
362
|
+
# then a second definition was added with the same name (Fe)
|
|
363
|
+
# on detector 2 => Fe_det02 is overwritten
|
|
364
|
+
logger.warning("Some roi definitions are in conflict, keeping the one that was added last:\n"
|
|
365
|
+
" - discarding: name=%s, det=%s, ch=[%s .. %s]\n"
|
|
366
|
+
" - keeping: name=%s, det=%s, ch=[%s .. %s]\n",
|
|
367
|
+
name, detector, roi.ch0, roi.ch1,
|
|
368
|
+
name, detector, prev.ch0, prev.ch1)
|
|
369
|
+
except KeyError:
|
|
370
|
+
pass
|
|
371
|
+
parsed[(roi_cnt_name, detector)] = roi
|
|
372
|
+
|
|
373
|
+
for (name, detectors), value in invalid.items():
|
|
374
|
+
logger.warning("Ignoring invalid roi: name=%s, "
|
|
375
|
+
"bins=%s, detector(s)=%s",
|
|
376
|
+
name, value[0], value[1])
|
|
377
|
+
self._roi_invalid.update({(name, detectors): value})
|
|
378
|
+
|
|
379
|
+
self._rois = parsed
|
|
380
|
+
# singles, sums = {}, {}
|
|
381
|
+
# for key, value in parsed.items():
|
|
382
|
+
# (singles, sums)[value.is_sum].update({key:value})
|
|
383
|
+
# self._roi_singles = singles
|
|
384
|
+
# self._roi_sums = sums
|
|
385
|
+
|
|
386
|
+
def _init_counters(self):
|
|
387
|
+
# initialize the rois computational units
|
|
388
|
+
# using the roi definitions
|
|
389
|
+
# first singles, then sums
|
|
390
|
+
# self._counters = [
|
|
391
|
+
# Roi(roi, self.spectrum_size,
|
|
392
|
+
# self.detectors, self.dtype)
|
|
393
|
+
# for roi in self.roi_singles().values()
|
|
394
|
+
# ]
|
|
395
|
+
|
|
396
|
+
# self._counters.extend(
|
|
397
|
+
# [Roi(roi, self.spectrum_size,
|
|
398
|
+
# self.detectors, self.dtype)
|
|
399
|
+
# for roi in self.roi_sums().values()]
|
|
400
|
+
# )
|
|
401
|
+
self._counters = [
|
|
402
|
+
Roi(roi, self.spectrum_size,
|
|
403
|
+
self.detectors, self.dtype)
|
|
404
|
+
for roi in self.rois().values()
|
|
405
|
+
]
|
|
406
|
+
|
|
407
|
+
# self._counters.extend(
|
|
408
|
+
# [Roi(roi, self.spectrum_size,
|
|
409
|
+
# self.detectors, self.dtype)
|
|
410
|
+
# for roi in self.roi_sums().values()]
|
|
411
|
+
# )
|
|
412
|
+
|
|
413
|
+
def _calc_rois(self, spectra, stats):
|
|
414
|
+
t0 = time.perf_counter()
|
|
415
|
+
counters = self._counters
|
|
416
|
+
new_points = spectra.shape[1]
|
|
417
|
+
if counters:
|
|
418
|
+
buffer = self.buffer
|
|
419
|
+
roi_data = np.ndarray((self.n_items, new_points), dtype=buffer.dtype)
|
|
420
|
+
for i_roi, roi in enumerate(counters):
|
|
421
|
+
roi_data[i_roi] = roi(spectra)
|
|
422
|
+
buffer.add_data(roi_data)
|
|
423
|
+
logger.info("Took %ss to process %s rois on %s points.",
|
|
424
|
+
time.perf_counter() - t0, len(counters), new_points)
|
|
425
|
+
else:
|
|
426
|
+
# shouldn't happen if the taskmanager
|
|
427
|
+
# correctly ignores the roi task
|
|
428
|
+
# when there are no rois.
|
|
429
|
+
logger.debug("No rois defined (new points=%s)", new_points)
|
|
430
|
+
|
|
431
|
+
|
|
432
|
+
def roidef_to_rois(available_detectors, name, ch0, ch1, *roi_detectors, is_sum=False):
|
|
433
|
+
bins = ch0, ch1
|
|
434
|
+
rois = {}
|
|
435
|
+
invalid = {}
|
|
436
|
+
|
|
437
|
+
if not is_sum:
|
|
438
|
+
# single roi definition
|
|
439
|
+
|
|
440
|
+
if len(roi_detectors) == 0 or roi_detectors[0] is None:
|
|
441
|
+
# a single roi on each available detectors
|
|
442
|
+
roi_detectors = available_detectors
|
|
443
|
+
|
|
444
|
+
invalid_det = set(roi_detectors) - set(available_detectors)
|
|
445
|
+
if invalid_det:
|
|
446
|
+
# roi is defined on a detector that is either disabled
|
|
447
|
+
# or not present at all
|
|
448
|
+
invalid.update({(name, det): (bins, det) for det in invalid_det})
|
|
449
|
+
roi_detectors = set(roi_detectors) - invalid_det
|
|
450
|
+
rois.update({(name, detector):(bins, detector)
|
|
451
|
+
for detector in roi_detectors})
|
|
452
|
+
else:
|
|
453
|
+
# a roi sum definition
|
|
454
|
+
if not roi_detectors or roi_detectors[0] is None:
|
|
455
|
+
# roi sum on all detectors
|
|
456
|
+
rois[(name, tuple())] = bins, tuple(available_detectors)
|
|
457
|
+
|
|
458
|
+
else:
|
|
459
|
+
# sum on the given detectors
|
|
460
|
+
# sorted is just there to make testing easier
|
|
461
|
+
valid_dets = set(roi_detectors).intersection(available_detectors)
|
|
462
|
+
if valid_dets:
|
|
463
|
+
rois[(name, roi_detectors)] = bins, tuple(sorted(valid_dets))
|
|
464
|
+
else:
|
|
465
|
+
invalid[(name, roi_detectors)] = bins, roi_detectors
|
|
466
|
+
return rois, invalid
|