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,107 @@
1
+ """Helpers specific to the mapping mode."""
2
+
3
+ from .stats import stats_from_mapping_mode
4
+
5
+
6
+ def dword(array, index, bitsize=16):
7
+ """Extract a dword value from two words starting at the given index."""
8
+ # casting to prevent overflow (numpy 2+ keeps the same input type for the result)
9
+ return int(array[index]) | int(array[index + 1]) << bitsize
10
+
11
+
12
+ def parse_mapping_buffer(raw):
13
+ """Parse the given mapping buffer and return a (spectrums, statistics) tuple.
14
+
15
+ Both results are dictionaries of dictionaries, first indexed by pixel,
16
+ then channels:
17
+ - spectrums: <pixel: <channel: spectrum (1D array)>
18
+ - statistics: <pixel: <channel: stats (Stats object)>
19
+ """
20
+ spectrums, statistics = {}, {}
21
+
22
+ # XMAP/Mercury parsing
23
+ if raw[1] == 0:
24
+ raw = raw[::2]
25
+ spectrum_type = "uint16"
26
+ # FalconX parsing
27
+ else:
28
+ spectrum_type = "uint32"
29
+
30
+ # Header advance
31
+ header = raw[0:256]
32
+ current = 256
33
+
34
+ # Header parsing
35
+ assert header[0] == 0x55AA
36
+ assert header[1] == 0xAA55
37
+ assert header[2] == 0x100
38
+ mapping_mode = header[3]
39
+ buffer_index = dword(header, 4)
40
+ buffer_id = header[7]
41
+ pixel_number = header[8]
42
+ starting_pixel = dword(header, 9)
43
+ module_serial_number = header[11]
44
+ channel_ids = header[12:20:2]
45
+ channel_detector_ids = header[13:20:2]
46
+
47
+ # Checks
48
+ assert mapping_mode == 1 # MCA mapping mode
49
+ assert starting_pixel == dword(raw, 256 + 4)
50
+ assert buffer_id in (0, 1)
51
+
52
+ # Unused information, should we do something with it?
53
+ buffer_index, module_serial_number, channel_detector_ids
54
+
55
+ # Iterate over pixels
56
+ for _ in range(pixel_number):
57
+
58
+ # Pixel header advance
59
+ pixel_header = raw[current : current + 256]
60
+ current += 256
61
+
62
+ # Pixel header parsing
63
+ assert pixel_header[0] == 0x33CC
64
+ assert pixel_header[1] == 0xCC33
65
+ assert pixel_header[2] == 0x100
66
+ assert pixel_header[3] == mapping_mode
67
+ pixel = dword(pixel_header, 4)
68
+ total_size = dword(pixel_header, 6)
69
+ sizes = pixel_header[8:12]
70
+
71
+ # Statistics block
72
+ stats_block = [
73
+ [dword(pixel_header, 32 + 8 * i + 2 * j) for j in range(4)]
74
+ for i in range(4)
75
+ ]
76
+
77
+ # Iterate over channels
78
+ spectrums[pixel] = {}
79
+ statistics[pixel] = {}
80
+ remaining = total_size - 256
81
+ for index, channel_id, size in zip(range(4), channel_ids, sizes):
82
+
83
+ # Update remaining size
84
+ assert remaining >= 0
85
+ if remaining == 0:
86
+ break
87
+ remaining -= size
88
+
89
+ # Sectrum Advance
90
+ spectrum = raw[current : current + size]
91
+ spectrum.dtype = spectrum_type
92
+ current += size
93
+
94
+ # Discard garbage
95
+ if channel_id in spectrums[pixel]:
96
+ continue
97
+
98
+ # Set data
99
+ stats = stats_from_mapping_mode(stats_block[index])
100
+ spectrums[pixel][channel_id] = spectrum
101
+ statistics[pixel][channel_id] = stats
102
+
103
+ # Checks
104
+ assert remaining == 0
105
+
106
+ # Return results
107
+ return spectrums, statistics
@@ -0,0 +1,62 @@
1
+ """Parsers for the specific XIA INI file format."""
2
+
3
+
4
+ def parse_xia_ini_file(content):
5
+ """Parse the content of a XIA INI file.
6
+
7
+ The return result is an dict of <section name: list>,
8
+ where the list items are dict of <key: value>.
9
+ """
10
+ dct = dict()
11
+ section, item = None, None
12
+ # Loop over striped lines
13
+ for line in content.splitlines():
14
+ line = line.strip()
15
+ # Comment
16
+ if line.startswith("*"):
17
+ pass
18
+ # New section
19
+ elif line.startswith("[") and line.endswith("]"):
20
+ if item is not None:
21
+ msg = "New section within section {} item {}"
22
+ raise ValueError(msg.format(section, item))
23
+ item = None
24
+ section = line[1:-1].strip()
25
+ dct[section] = []
26
+ # New item
27
+ elif line.startswith("START #"):
28
+ if item is not None:
29
+ msg = "New item within section {} item {}"
30
+ raise ValueError(msg.format(section, item))
31
+ item = int(line.split("#")[1])
32
+ if section is None:
33
+ msg = "Item {} outside of section"
34
+ raise ValueError(msg.format(item))
35
+ if item != len(dct[section]):
36
+ msg = "Corrupted start (section {}, {} should be {})"
37
+ msg = msg.format(section, item, len(dct[section]))
38
+ raise ValueError(msg)
39
+ dct[section].append(dict())
40
+ # End item
41
+ elif line.startswith("END #"):
42
+ if item is None:
43
+ msg = "End markup outside of item"
44
+ raise ValueError(msg)
45
+ item = int(line.split("#")[1])
46
+ if item != len(dct[section]) - 1:
47
+ msg = "Corrupted end (section {}, {} should be {})"
48
+ msg = msg.format(section, item, len(dct[section]) - 1)
49
+ raise ValueError(msg)
50
+ item = None
51
+ # New pair
52
+ elif "=" in line:
53
+ key, value = map(str.strip, line.split("="))
54
+ if item is None:
55
+ msg = "Key/value pair {} outside of item"
56
+ raise ValueError(msg.format((key, value)))
57
+ dct[section][item][key] = value
58
+ # Error
59
+ elif line:
60
+ raise ValueError("Line not recognized: {!r}".format(line))
61
+ # Return result
62
+ return dct
@@ -0,0 +1,85 @@
1
+ """Statistics handling."""
2
+
3
+ import logging
4
+
5
+ import numpy as np
6
+
7
+ CLOCK_TICK = 320e-9
8
+
9
+ _logger = logging.getLogger(__name__)
10
+
11
+ # trigger_livetime = fast channel livetime (input)
12
+ # energy_livetime = slow channel livetime (output)
13
+
14
+
15
+ def stats_from_normal_mode(array):
16
+ """
17
+ input: 9 elements array
18
+ output: 8 elements named-tuple
19
+ """
20
+ realtime = float(array[0])
21
+ trigger_livetime = float(array[1])
22
+ energy_livetime = float(array[2])
23
+ triggers = int(array[3])
24
+ events = int(array[4]) # without under/over flows
25
+ icr = float(array[5])
26
+ ocr = float(array[6])
27
+ underflows = int(array[7])
28
+ overflows = int(array[8])
29
+ total_events = events + underflows + overflows
30
+
31
+ # Double check the ICR computation
32
+ expected_icr = triggers / trigger_livetime if trigger_livetime != 0 else 0.0
33
+ if expected_icr != icr:
34
+ msg = "ICR buffer inconsistency: %s != %s (expected/handel)"
35
+ _logger.warning(msg, icr, expected_icr)
36
+
37
+ # Double check the OCR computation
38
+ expected_ocr = total_events / realtime if realtime != 0 else 0.0
39
+ if expected_ocr != ocr:
40
+ msg = "OCR buffer inconsistency: %s != %s (expected/handel)"
41
+ _logger.warning(msg, ocr, expected_ocr)
42
+
43
+ # Double check the energy_livetime computation
44
+ expected_e_livetime = events / icr if icr != 0 else 0.0
45
+ if expected_e_livetime != energy_livetime:
46
+ msg = "Energy_Livetime inconsistency: %s != %s (expected/handel)"
47
+ _logger.warning(msg, energy_livetime, expected_e_livetime)
48
+
49
+ # Note that the OCR reported by handel includes underflows and overflows,
50
+ # while the computed OCR in the returned statistics does not.
51
+ return make_stats(realtime, trigger_livetime, triggers, events)
52
+
53
+
54
+ def stats_from_mapping_mode(array):
55
+ realtime = array[0] * CLOCK_TICK
56
+ trigger_livetime = array[1] * CLOCK_TICK
57
+ triggers = int(array[2])
58
+ events = int(array[3]) # does not include over / undef flows ???
59
+
60
+ return make_stats(realtime, trigger_livetime, triggers, events)
61
+
62
+
63
+ def make_stats(realtime, trigger_livetime, triggers, events):
64
+ # ICR/OCR computation
65
+ icr = triggers / trigger_livetime if trigger_livetime != 0 else 0.0
66
+ ocr = events / realtime if realtime != 0 else 0.0
67
+ # Deadtime computation
68
+ # It's unclear whether icr=ocr=0 should result in a 0.0 or 1.0 deadtime
69
+ # Prospect uses 0% so 0. it is.
70
+ deadtime = 1 - float(ocr) / icr if icr != 0 else 0.0
71
+
72
+ # no icr -> 0 ?
73
+ energy_livetime = events / icr if icr != 0 else 0.0
74
+
75
+ return np.array([
76
+ realtime,
77
+ trigger_livetime,
78
+ energy_livetime,
79
+ triggers,
80
+ events,
81
+ icr,
82
+ ocr,
83
+ deadtime],
84
+ dtype=np.float64
85
+ )
@@ -0,0 +1,160 @@
1
+ import logging
2
+ logger = logging.getLogger(__name__)
3
+
4
+ # from tango.server import device_property, attribute, command
5
+
6
+ import numpy as np
7
+
8
+ from ...tango import TangoDevInfo
9
+ from .xiads import XiaDS
10
+ from .xia import Xia, TrigPoller
11
+ from .handel.stats import stats_from_mapping_mode
12
+
13
+
14
+ def dword(array, index, bitsize=16):
15
+ """Extract a dword value from two words starting at the given index."""
16
+ # casting to prevent overflow (numpy 2+ keeps the same input type for the result)
17
+ return int(array[index]) | int(array[index + 1]) << bitsize
18
+
19
+
20
+ class MercuryTrigPoller(TrigPoller):
21
+
22
+ def _parse_map_buffer(self, master, channels, ini_channels, raw, spectra, stats, module_index):
23
+ """Parse the given mapping buffer and return a (spectrums, statistics) tuple.
24
+
25
+ Both results are dictionaries of dictionaries, first indexed by pixel,
26
+ then channels:
27
+ - spectrums: <pixel: <channel: spectrum (1D array)>
28
+ - statistics: <pixel: <channel: stats (Stats object)>
29
+
30
+ `ini_channels` and `channels` are built once across *all* modules
31
+ (Xia._update_channels flattens `hi.get_grouped_channels()`, 4 slots
32
+ per module), while this method is called once per module with the
33
+ raw buffer of that single module. `module_index` (this module's
34
+ position among self._masters, matching its position among the
35
+ flattened groups) is therefore needed to:
36
+ - look up this module's own slots in `ini_channels` (module_index*4
37
+ .. module_index*4+3), instead of always reading slots 0-3, and
38
+ - offset where this module's channels land in the shared `spectra`/
39
+ `stats` arrays, instead of always starting at row 0 and clobbering
40
+ the previous module's data.
41
+ """
42
+
43
+ raw.dtype = np.uint16
44
+ raw = raw[::2]
45
+ spectrum_type = "uint16"
46
+
47
+ # Header advance
48
+ header = raw[0:256]
49
+ current = 256
50
+
51
+ # Header parsing
52
+ assert header[0] == 0x55AA
53
+ assert header[1] == 0xAA55
54
+ assert header[2] == 0x100
55
+ mapping_mode = header[3]
56
+ buffer_index = dword(header, 4)
57
+ buffer_id = header[7]
58
+ pixel_number = header[8]
59
+ starting_pixel = dword(header, 9)
60
+ module_serial_number = header[11]
61
+ channel_ids = header[12:20:2]
62
+ channel_detector_ids = header[13:20:2]
63
+
64
+ # Checks
65
+ assert mapping_mode == 1 # MCA mapping mode
66
+ assert starting_pixel == dword(raw, 256 + 4)
67
+ assert buffer_id in (0, 1)
68
+
69
+ # Unused information, should we do something with it?
70
+ buffer_index, module_serial_number, channel_detector_ids
71
+
72
+ n_chan = len(channels)
73
+
74
+ # This module's own block within the flattened, all-modules
75
+ # ini_channels list (4 hardware channels per module).
76
+ ini_offset = module_index * 4
77
+ # Number of enabled channels belonging to earlier modules, i.e. the
78
+ # row offset of this module's channels within the shared spectra/
79
+ # stats arrays (channels is the ordered tuple of enabled, flattened
80
+ # slot indices, built by Xia._update_channels).
81
+ ch_offset = sum(1 for chan in channels if chan < ini_offset)
82
+
83
+ # Iterate over pixels
84
+ for ipix in range(pixel_number):
85
+
86
+ # Pixel header advance
87
+ pixel_header = raw[current : current + 256]
88
+ current += 256
89
+
90
+ # Pixel header parsing
91
+ assert pixel_header[0] == 0x33CC
92
+ assert pixel_header[1] == 0xCC33
93
+ assert pixel_header[2] == 0x100
94
+ assert pixel_header[3] == mapping_mode
95
+ pixel = dword(pixel_header, 4)
96
+ total_size = dword(pixel_header, 6)
97
+ sizes = pixel_header[8:12]
98
+
99
+ # Statistics block
100
+ stats_block = [
101
+ [dword(pixel_header, 32 + 8 * i + 2 * j) for j in range(4)]
102
+ for i in range(4)
103
+ ]
104
+
105
+ remaining = total_size - 256
106
+
107
+ ch_idx = 0
108
+ for index, channel_id, size in zip(range(4), channel_ids, sizes):
109
+ # Update remaining size
110
+ assert remaining >= 0
111
+ if remaining == 0:
112
+ break
113
+ remaining -= size
114
+
115
+ if ini_channels[ini_offset + index] == -1 or channel_id not in channels:
116
+ current += size
117
+ continue
118
+
119
+ # Sectrum Advance
120
+ spectrum = raw[current : current + size]
121
+ spectrum.dtype = spectrum_type
122
+ current += size
123
+
124
+ # TODO ?
125
+ # # Discard garbage
126
+ # if channel_id in spectrums[pixel]:
127
+ # continue
128
+
129
+ # Set data
130
+ pix_stats = stats_from_mapping_mode(stats_block[index])
131
+ stats[ch_offset + ch_idx, ipix, :] = pix_stats
132
+
133
+ spectra[ch_offset + ch_idx, ipix, :] = spectrum
134
+
135
+ ch_idx += 1
136
+
137
+ # Checks
138
+ assert remaining == 0
139
+ return pixel_number
140
+
141
+
142
+ class Mercury(XiaDS):
143
+ def _create_control(self, *args, **kwargs):
144
+ lib_path = self.lib_path
145
+ if lib_path is None:
146
+ logger.warning("Property lib_path not set. Will use system wide handel.dll, if found.")
147
+ else:
148
+ logger.info("Looking for handel.dll in [%s].", lib_path)
149
+ return MercuryHW(*args, lib_path=lib_path, **kwargs)
150
+
151
+
152
+ class MercuryHW(Xia):
153
+ TrigPollerCls = MercuryTrigPoller
154
+
155
+
156
+ MERCURY_DEVINFO = TangoDevInfo(
157
+ klass=Mercury,
158
+ properties={"default_ini_dir": "",
159
+ "default_ini_file": "",
160
+ "lib_path": "c:/blissadm/mercury/handel/"})
@@ -0,0 +1,47 @@
1
+ import os
2
+ import re
3
+ import argparse
4
+ from datetime import datetime
5
+
6
+
7
+ _KEYS = ["list_mode_variant"]
8
+
9
+
10
+ if __name__ == "__main__":
11
+ parser = argparse.ArgumentParser(
12
+ prog='ProgramName',
13
+ description='What the program does',
14
+ epilog='Text at the bottom of help')
15
+ parser.add_argument('ini_in')
16
+ parser.add_argument('ini_out', nargs="?", default=None)
17
+ parsed = parser.parse_args()
18
+
19
+ f_in = parsed.ini_in
20
+ f_out = parsed.ini_out
21
+
22
+ if f_out is None:
23
+ now = datetime.now()
24
+ date_time = now.strftime("%Y%m%d_%H%M%S")
25
+ f_out = os.path.basename(os.path.splitext(f_in)[0]) + "_fixed_" + date_time + ".ini"
26
+
27
+ print("=======================================\n")
28
+ print(f" > Input: {f_in}\n")
29
+
30
+ print("----\n")
31
+
32
+ print("Filtering unsupported keyword(s):")
33
+ print(" - " + " - ".join(_KEYS) + "\n")
34
+
35
+
36
+ rex = re.compile(r"\s*(" + "|".join(_KEYS) + ")\s*=\s*.*")
37
+
38
+ with open(f_in, "r") as inf:
39
+ with open(f_out, "w") as outf:
40
+ for iline, line in enumerate(inf):
41
+ if rex.match(line):
42
+ print(f"Removed @ line {iline}: {line.rstrip()}")
43
+ continue
44
+ outf.write(line)
45
+
46
+ print(f" < Output: {f_out}")
47
+ print("=======================================")