/
_engine.py
341 lines (294 loc) · 12.2 KB
/
_engine.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
from __future__ import annotations
import time
from numbers import Real
from typing import TYPE_CHECKING, Any, NamedTuple
import numpy as np
from loguru import logger
from pymmcore_plus import CMMCorePlus
from pymmcore_plus.mda import MDAEngine
from useq import MDAEvent
from ._error_handling import slack_notify
from ._events import QRamanSignaler as RamanSignaler
from .aiming import RamanAimingSource, SnappableRamanAimingSource
if TYPE_CHECKING:
from mda_simulator import ImageGenerator
from useq import MDASequence
class EventPayload(NamedTuple):
image: np.ndarray
class fakeAcquirer:
"""For development."""
def collect_spectra_relative(self, points, exposure=20):
points = np.asarray(points)
if points.min() < 0 or points.max() > 1:
raise ValueError("Points must be in [0, 1]")
if points.shape[1] != 2 or points.ndim != 2:
raise ValueError(
f"volts must have shape (N, 2) but has shape {points.shape}"
)
points = (np.ascontiguousarray(points) - 0.5) * 1.2
return self.collect_spectra_volts(points, exposure)
def collect_spectra_volts(self, points, exposure=20):
points = np.ascontiguousarray(points)
assert points.shape[1] == 2
arr = np.random.randn(points.shape[0], 1340) * exposure
return np.cumsum(arr, axis=1)
class RamanEngine(MDAEngine):
def __init__(
self,
mmc: CMMCorePlus = None,
default_rm_exp: float = 20.0,
spectra_collector=None,
sources: list[RamanAimingSource] = None,
) -> None:
"""
Create a pymmcore-plus mda engine that also collects Raman data.
Parameters
----------
mmc : CMMCorePlus
The core to use, or None to use the current instance
default_rm_exp : float
The default raman exposure in ms. Used if nothing else provided.
spectra_collector : SpectraCollector instance
If None use the default - or nothign if not importable
sources : iterable
Collection of aiming sources to aim the raman laser.
"""
super().__init__(mmc)
self.raman_events = RamanSignaler()
self._rng = np.random.default_rng()
self._img_gen: ImageGenerator | None = None
self._default_rm_exp = default_rm_exp
self.raman_events = RamanSignaler()
self._spectra_collector = spectra_collector
if self._spectra_collector is None:
try:
from raman_control import SpectraCollector
self._spectra_collector = SpectraCollector.instance()
except ImportError:
self._spectra_collector = None
logger.warning(
"Could not import SpectraCollector - No raman collection"
)
self._rm_meta = None
self.aiming_sources = sources if sources is not None else []
self._sources: list[RamanAimingSource]
# default engine doesn't do this in super to avoid import loops
self._mmc = CMMCorePlus.instance()
@property
def aiming_sources(self) -> list[RamanAimingSource]:
return self._sources
@aiming_sources.setter
def aiming_sources(self, val: list[RamanAimingSource]):
if val is None:
self._sources = []
elif all([isinstance(source, RamanAimingSource) for source in val]):
self._sources = list(val)
else:
raise TypeError(
"aiming_sources must be a list of objects"
" conforming to the RamanAimingSource protocol."
)
@property
def default_rm_exposure(self) -> Real:
return self._default_rm_exp # type: ignore
@default_rm_exposure.setter
def default_rm_exposure(self, val: Real):
if not isinstance(val, Real):
raise TypeError(
f"default_rm_exposure must be a real number, got {type(val)}"
)
# ignore typing here because above is the best check
# but mypy doesn't see float as part of Real so it's a mess
self._default_rm_exp = val # type: ignore
def _sequence_axis_order(self, seq: MDASequence) -> tuple:
event = next(seq.iter_events())
event_axes = list(event.index.keys())
return tuple(a for a in seq.axis_order if a in event_axes)
def _event_to_index(self, event: MDAEvent) -> tuple[int, ...]:
return tuple(event.index[a] for a in self._axis_order)
def record_raman(self, event: MDAEvent):
"""
Record and save the raman spectra for the current position and time.
Parameters
----------
event : MDAEvent
From the mda sequence.
Returns
-------
spec : (N, 1340) array of float
"""
points = []
which = []
for source in self.aiming_sources:
new_points = source.get_mda_points(event)
points.append(new_points)
which.extend([source.name] * len(new_points))
points = np.vstack(points)
p, t = event.index["p"], event.index.get("t", 0)
logger.info(f"collecting raman: {p=}, {t=}")
spec = self._spectra_collector.collect_spectra_relative(
points, self._default_rm_exp
)
self.raman_events.ramanSpectraReady.emit(event, spec, points, which)
@slack_notify
def snap_raman(
self,
exposure: Real = None,
aiming_sources: None
| (SnappableRamanAimingSource | list[SnappableRamanAimingSource]) = None,
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
"""
Record raman.
Parameters
----------
exposure : real, optional
The exposure time to use, defaults to the *default_rm_exposure*
aiming_sources : list[SnappableAimingSource]
The aiming sources to use
Returns
-------
spec : (N, 1340) np.ndarray
points : (N, 2) absolute positions in image space where laser was aimed
which : (N,) label (e.g. 'cell' or 'bkd') for each point
"""
points = []
which = []
if aiming_sources is None:
aiming_sources = [
source
for source in self.aiming_sources
if isinstance(source, SnappableRamanAimingSource)
]
elif not isinstance(aiming_sources, list):
aiming_sources = [aiming_sources]
for source in aiming_sources:
if not isinstance(source, SnappableRamanAimingSource):
raise TypeError(
"All aiming sources must be SnappableRamanAimingSources"
)
new_points = source.get_current_points()
points.append(new_points)
which.extend([source.name] * len(new_points))
points = np.vstack(points)
if exposure is None:
exposure = self._default_rm_exp # type: ignore
spec = self._spectra_collector.collect_spectra_relative(points, exposure)
return spec, points, which
@slack_notify
def setup_sequence(self, sequence: MDASequence) -> None:
super().setup_sequence(sequence)
raman_meta = sequence.metadata.get("raman", None)
if raman_meta:
if self._spectra_collector is None:
raise RuntimeError("Spectra Collector not set - cannot collect Raman.")
if len(self.aiming_sources) == 0:
raise RuntimeError("No aiming sources - cannot collect Raman.")
self._rm_channel = raman_meta.get("channel", "BF")
z = raman_meta.get("z", "all")
z_index = self._sequence_axis_order(sequence).index("z")
if isinstance(z, str):
if z.lower() == "center":
n_z = sequence.shape[z_index]
if n_z % 2 == 0:
raise ValueError("for z=center n_z must be odd.")
z = np.array(n_z // 2)
elif z.lower() in ["all", "stack"]:
z = np.arange(sequence.shape[z_index])
else:
z = np.asanyarray(z)
self._rm_z = z
self._rm_meta = raman_meta
self._z_rel = sequence.z_plan.positions()
if "autofocus" in sequence.metadata:
auto_meta = sequence.metadata["autofocus"]
self._autofocus = True
self._auto_device = auto_meta["autofocus_device"]
self._rel_device = auto_meta["rel_focus_device"]
self._ref_z = {}
else:
self._autofocus = False
self._last_pos = -1
def _run_autofocus(self, event: MDAEvent, pos: int):
if (self._spectra_collector is not None) and (
type(self._spectra_collector) is not fakeAcquirer
):
# we're at MIT and should insert the filter
self._spectra_collector.daq.insert_filter()
time.sleep(4)
# set to the last known good z for this position
# to give ourselves the best shot of PFS working
if pos in self._ref_z:
self._mmc.setPosition(self._rel_device, self._ref_z[pos])
elif (pos - 1) in self._ref_z:
# nothing found here yet, use the previous position as
# guessed starting point
self._mmc.setPosition(self._rel_device, self._ref_z[pos - 1])
self._mmc.waitForSystem()
# compute new focus
self._mmc.enableContinuousFocus(False)
pfs_z = np.array(event.z_pos - self._z_rel)
self._mmc.setPosition(self._auto_device, pfs_z[0])
self._mmc.waitForSystem()
try:
self._mmc.fullFocus()
self._mmc.waitForSystem()
except RuntimeError:
try:
self._mmc.fullFocus()
self._mmc.waitForSystem()
except RuntimeError:
self._mmc.fullFocus()
self._mmc.waitForSystem()
self._ref_z[pos] = self._mmc.getPosition(self._rel_device)
self._mmc.enableContinuousFocus(False)
# put before the wait for system, so that these independent
# parts can run at the same time.
if (self._spectra_collector is not None) and (
type(self._spectra_collector) is not fakeAcquirer
):
# we're at MIT and should insert the filter
self._spectra_collector.daq.remove_filter()
time.sleep(4)
self._mmc.waitForSystem()
@slack_notify
def setup_event(self, event: MDAEvent) -> None:
if event.x_pos is not None or event.y_pos is not None:
x = event.x_pos if event.x_pos is not None else self._mmc.getXPosition()
y = event.y_pos if event.y_pos is not None else self._mmc.getYPosition()
self._mmc.setXYPosition(x, y)
if event.channel is not None:
self._mmc.setConfig(event.channel.group, event.channel.config)
if event.z_pos is not None:
if self._autofocus:
pos = event.index["p"]
if pos != self._last_pos:
self._last_pos = pos
# moved to a new position
# figure out what the PFS-Offset was
self._run_autofocus(event, pos)
z_pos = self._ref_z[pos] + self._z_rel[event.index["z"]]
self._mmc.setPosition(self._rel_device, z_pos)
else:
self._mmc.setPosition(event.z_pos)
if event.exposure is not None:
self._mmc.setExposure(event.exposure)
self._mmc.waitForSystem()
@slack_notify
def exec_event(self, event: MDAEvent) -> Any:
if self._rm_meta:
if (
event.channel.config == self._rm_channel
and event.index["z"] in self._rm_z
):
self.record_raman(event)
try:
self._mmc.snapImage()
except RuntimeError:
time.sleep(0.5)
self._mmc.waitForSystem()
self._mmc.snapImage()
# TODO: need a return object including the raman channel so that
# napari-micro can interpret. Currently cannot make raman events
# bc they mess with the shape of the acquisition for napari-micro
# and it messes up display.
return EventPayload(image=self._mmc.getImage())