closed-loop-microscopy 1.1.0__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.
- closed_loop_microscopy-1.1.0.dist-info/METADATA +118 -0
- closed_loop_microscopy-1.1.0.dist-info/RECORD +74 -0
- closed_loop_microscopy-1.1.0.dist-info/WHEEL +4 -0
- closed_loop_microscopy-1.1.0.dist-info/entry_points.txt +5 -0
- closed_loop_microscopy-1.1.0.dist-info/licenses/LICENSE.md +7 -0
- pyclm/__init__.py +26 -0
- pyclm/__main__.py +8 -0
- pyclm/check.py +931 -0
- pyclm/cli.py +256 -0
- pyclm/commands.py +183 -0
- pyclm/controller.py +447 -0
- pyclm/convert_hdf5s.py +273 -0
- pyclm/core/__init__.py +20 -0
- pyclm/core/base_process.py +166 -0
- pyclm/core/core_interface.py +47 -0
- pyclm/core/datatypes.py +142 -0
- pyclm/core/events.py +194 -0
- pyclm/core/experiments.py +403 -0
- pyclm/core/grid.py +272 -0
- pyclm/core/kinds.py +42 -0
- pyclm/core/manager.py +861 -0
- pyclm/core/measure.py +266 -0
- pyclm/core/messages.py +124 -0
- pyclm/core/microscope.py +504 -0
- pyclm/core/pattern_process.py +282 -0
- pyclm/core/patterns/__init__.py +60 -0
- pyclm/core/patterns/bar_patterns.py +259 -0
- pyclm/core/patterns/cell_intensity_patterns.py +181 -0
- pyclm/core/patterns/composite.py +220 -0
- pyclm/core/patterns/embryo_patterns.py +90 -0
- pyclm/core/patterns/fbc_cell_movement.py +295 -0
- pyclm/core/patterns/pattern.py +610 -0
- pyclm/core/patterns/pulse_patterns.py +261 -0
- pyclm/core/patterns/static_patterns.py +58 -0
- pyclm/core/patterns/wave_patterns.py +95 -0
- pyclm/core/patterns/zoo.py +231 -0
- pyclm/core/plan.py +623 -0
- pyclm/core/position_mover.py +185 -0
- pyclm/core/queues.py +41 -0
- pyclm/core/real_core.py +158 -0
- pyclm/core/router.py +422 -0
- pyclm/core/segmentation/__init__.py +2 -0
- pyclm/core/segmentation/cellpose_segmentation.py +113 -0
- pyclm/core/segmentation/segmentation.py +48 -0
- pyclm/core/segmentation_process.py +179 -0
- pyclm/core/settings.py +120 -0
- pyclm/core/storage/__init__.py +37 -0
- pyclm/core/storage/base.py +234 -0
- pyclm/core/storage/events.py +130 -0
- pyclm/core/storage/hdf5_v1.py +337 -0
- pyclm/core/storage/ome_zarr.py +861 -0
- pyclm/core/tracking/__init__.py +28 -0
- pyclm/core/tracking/centroid.py +75 -0
- pyclm/core/tracking/tracking.py +124 -0
- pyclm/core/tracking_process.py +106 -0
- pyclm/core/virtual_microscope/__init__.py +0 -0
- pyclm/core/virtual_microscope/simulated_core.py +262 -0
- pyclm/core/virtual_microscope/simulated_source.py +206 -0
- pyclm/core/writer_process.py +130 -0
- pyclm/demo.py +225 -0
- pyclm/directories.py +563 -0
- pyclm/gui/__init__.py +28 -0
- pyclm/gui/debug_viewer.py +41 -0
- pyclm/gui/gui_controller.py +551 -0
- pyclm/gui/widgets.py +292 -0
- pyclm/io/__init__.py +29 -0
- pyclm/io/export.py +202 -0
- pyclm/io/readers.py +589 -0
- pyclm/methods.py +249 -0
- pyclm/mmconfig.py +143 -0
- pyclm/preview.py +414 -0
- pyclm/run_pyclm.py +298 -0
- pyclm/schema.py +806 -0
- pyclm/templates.py +165 -0
pyclm/core/microscope.py
ADDED
|
@@ -0,0 +1,504 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
from queue import Empty
|
|
3
|
+
from threading import Event
|
|
4
|
+
from time import sleep, time
|
|
5
|
+
from typing import ClassVar
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
|
|
9
|
+
from .base_process import BaseProcess
|
|
10
|
+
from .core_interface import MicroscopeCoreInterface
|
|
11
|
+
from .datatypes import (
|
|
12
|
+
AcquisitionData,
|
|
13
|
+
EventSLMPattern,
|
|
14
|
+
SkippedAcquisition,
|
|
15
|
+
StimulationData,
|
|
16
|
+
)
|
|
17
|
+
from .events import AcquisitionEvent, UpdatePatternEvent, UpdateStagePositionEvent
|
|
18
|
+
from .experiments import ConfigGroup, DeviceProperty
|
|
19
|
+
from .grid import stitch
|
|
20
|
+
from .messages import EventDoneMessage, Message, UpdateZPositionMessage
|
|
21
|
+
from .position_mover import BasicPositionMover, PositionMover
|
|
22
|
+
from .queues import AllQueues
|
|
23
|
+
|
|
24
|
+
logger = logging.getLogger(__name__)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def pattern_is_blank(pattern) -> bool:
|
|
28
|
+
"""True when nothing in the DMD image (or any tile of a list of them) is lit."""
|
|
29
|
+
if pattern is None:
|
|
30
|
+
return True
|
|
31
|
+
if isinstance(pattern, list | tuple):
|
|
32
|
+
return all(pattern_is_blank(p) for p in pattern)
|
|
33
|
+
return not np.any(np.asarray(pattern))
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class MicroscopeProcess(BaseProcess):
|
|
37
|
+
"""
|
|
38
|
+
Executes acquisition, stage and SLM events against a MicroscopeCoreInterface.
|
|
39
|
+
|
|
40
|
+
Every frame it takes is published to the Router (it is the producer of
|
|
41
|
+
``raw``); nothing about who consumes a frame is decided here.
|
|
42
|
+
|
|
43
|
+
An error while handling one message is logged and counted, and the process
|
|
44
|
+
moves on to the next message, so a single failed event does not end the
|
|
45
|
+
experiment. After ``max_consecutive_errors`` failures in a row the error is
|
|
46
|
+
re-raised, which makes the Controller abort the run.
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
produces: ClassVar[dict[str, tuple[str, ...]]] = {"raw": (), "skipped": ()}
|
|
50
|
+
always_active: ClassVar[bool] = True
|
|
51
|
+
|
|
52
|
+
def __init__(
|
|
53
|
+
self,
|
|
54
|
+
core: MicroscopeCoreInterface,
|
|
55
|
+
aq: AllQueues,
|
|
56
|
+
position_mover: PositionMover | None = None,
|
|
57
|
+
stop_event: Event | None = None,
|
|
58
|
+
settle_time_s: float = 1.0,
|
|
59
|
+
slm_await_s: float = 5.0,
|
|
60
|
+
max_consecutive_errors: int = 10,
|
|
61
|
+
):
|
|
62
|
+
super().__init__(stop_event, name="microscope")
|
|
63
|
+
self.core = core
|
|
64
|
+
self.position_mover = (
|
|
65
|
+
position_mover if position_mover is not None else BasicPositionMover()
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
self.inbox = aq.manager_to_microscope # receives messages/events from manager
|
|
69
|
+
self.manager = aq.microscope_to_manager # send messages to manager
|
|
70
|
+
self.slm_queue = aq.slm_to_microscope # receives SLM updates
|
|
71
|
+
|
|
72
|
+
# set by Router.resolve(); frames are published through it
|
|
73
|
+
self.router = None
|
|
74
|
+
self._stream_ended = False
|
|
75
|
+
|
|
76
|
+
# seconds to wait after waitForSystem() before snapping
|
|
77
|
+
self.settle_time_s = settle_time_s
|
|
78
|
+
# seconds to wait for the SLM buffer to answer an update_pattern_event
|
|
79
|
+
self.slm_await_s = slm_await_s
|
|
80
|
+
self.max_consecutive_errors = max_consecutive_errors
|
|
81
|
+
self.consecutive_errors = 0
|
|
82
|
+
|
|
83
|
+
# how long inbox.get() blocks before the stop event is re-checked
|
|
84
|
+
self.poll_interval = 0.05
|
|
85
|
+
|
|
86
|
+
self.slm_initialized = False
|
|
87
|
+
self.slm_device = None
|
|
88
|
+
self.slm_h = None
|
|
89
|
+
self.slm_w = None
|
|
90
|
+
|
|
91
|
+
self.start = 0
|
|
92
|
+
|
|
93
|
+
self.current_pattern = None
|
|
94
|
+
self.current_pattern_id = None
|
|
95
|
+
self.current_camera_pattern = None
|
|
96
|
+
self.current_dmd_ids = None
|
|
97
|
+
# (t, experiment) whose stimulation-only visit a blank pattern cancelled
|
|
98
|
+
self._blank_skips: set[tuple[int, str]] = set()
|
|
99
|
+
self.skipped_moves = 0
|
|
100
|
+
self.skipped_acquisitions = 0
|
|
101
|
+
|
|
102
|
+
self.warned_binning = False
|
|
103
|
+
|
|
104
|
+
# ------------------------------------------------------------ routing
|
|
105
|
+
def subscriptions(self, plan) -> list:
|
|
106
|
+
return []
|
|
107
|
+
|
|
108
|
+
def attach(self, router, data_inbox=None):
|
|
109
|
+
"""Called by the Router; the microscope consumes nothing, so the inbox is unused."""
|
|
110
|
+
self.router = router
|
|
111
|
+
|
|
112
|
+
def _emit(self, data):
|
|
113
|
+
if self.router is None:
|
|
114
|
+
raise RuntimeError("microscope process is not attached to a router")
|
|
115
|
+
self.router.publish(data)
|
|
116
|
+
|
|
117
|
+
def end_stream(self):
|
|
118
|
+
"""Tell the router no more frames are coming (idempotent)."""
|
|
119
|
+
if self._stream_ended or self.router is None:
|
|
120
|
+
return
|
|
121
|
+
self._stream_ended = True
|
|
122
|
+
self.router.end_stream(self.name)
|
|
123
|
+
|
|
124
|
+
def declare_slm(self):
|
|
125
|
+
core = self.core
|
|
126
|
+
dev = core.getSLMDevice()
|
|
127
|
+
|
|
128
|
+
if dev == "":
|
|
129
|
+
logger.warning("SLM Device not initialized, using dummy slm")
|
|
130
|
+
|
|
131
|
+
self.slm_device = "dummy"
|
|
132
|
+
self.slm_h = 1140
|
|
133
|
+
self.slm_w = 900
|
|
134
|
+
|
|
135
|
+
else:
|
|
136
|
+
self.slm_device = dev
|
|
137
|
+
self.slm_h = core.getSLMHeight(dev)
|
|
138
|
+
self.slm_w = core.getSLMWidth(dev)
|
|
139
|
+
|
|
140
|
+
self.current_pattern = np.zeros((self.slm_h, self.slm_w))
|
|
141
|
+
|
|
142
|
+
self.slm_initialized = True
|
|
143
|
+
|
|
144
|
+
def process(self, event_await_s=0, slm_await_s=None):
|
|
145
|
+
logger.debug(f"started MicroscopeProcess on {self.core}")
|
|
146
|
+
self.start = time()
|
|
147
|
+
|
|
148
|
+
event_await_start = time()
|
|
149
|
+
|
|
150
|
+
while True:
|
|
151
|
+
if self.stop_event and self.stop_event.is_set():
|
|
152
|
+
logger.info("force stopping microscope process")
|
|
153
|
+
break
|
|
154
|
+
|
|
155
|
+
try:
|
|
156
|
+
msg = self.inbox.get(timeout=self.poll_interval)
|
|
157
|
+
except Empty:
|
|
158
|
+
if (event_await_s != 0) and (
|
|
159
|
+
time() - event_await_start > event_await_s
|
|
160
|
+
):
|
|
161
|
+
raise TimeoutError(
|
|
162
|
+
f"No events in queue for {time() - event_await_start: .3f}s"
|
|
163
|
+
) from None
|
|
164
|
+
continue
|
|
165
|
+
|
|
166
|
+
try:
|
|
167
|
+
should_stop = self.handle_message(msg, slm_await_s)
|
|
168
|
+
except Exception as exc:
|
|
169
|
+
self.error_count += 1
|
|
170
|
+
self.consecutive_errors += 1
|
|
171
|
+
logger.error(
|
|
172
|
+
f"Error handling {msg} in microscope process "
|
|
173
|
+
f"({self.consecutive_errors} consecutive, {self.error_count} total)",
|
|
174
|
+
exc_info=True,
|
|
175
|
+
)
|
|
176
|
+
if getattr(msg, "message", None) == "acquisition_event":
|
|
177
|
+
self.manager.put(EventDoneMessage(msg.event, error=repr(exc)))
|
|
178
|
+
if self.consecutive_errors >= self.max_consecutive_errors:
|
|
179
|
+
logger.critical(
|
|
180
|
+
f"{self.consecutive_errors} consecutive microscope errors; "
|
|
181
|
+
"aborting run"
|
|
182
|
+
)
|
|
183
|
+
raise
|
|
184
|
+
else:
|
|
185
|
+
self.consecutive_errors = 0
|
|
186
|
+
if should_stop:
|
|
187
|
+
return 0
|
|
188
|
+
|
|
189
|
+
event_await_start = time()
|
|
190
|
+
|
|
191
|
+
def handle_message(self, msg: Message, slm_await_s: float | None = None) -> bool:
|
|
192
|
+
"""Dispatch one message from the manager. Returns True when the process should exit."""
|
|
193
|
+
match msg.message:
|
|
194
|
+
case "update_pattern_event":
|
|
195
|
+
self.handle_update_pattern_event(msg.event, slm_await_s)
|
|
196
|
+
|
|
197
|
+
case "acquisition_event":
|
|
198
|
+
self.handle_acquisition_event(msg.event)
|
|
199
|
+
|
|
200
|
+
case "update_position_event":
|
|
201
|
+
self.handle_update_position_event(msg.event)
|
|
202
|
+
|
|
203
|
+
case "close":
|
|
204
|
+
# no more events from the manager: end the raw stream
|
|
205
|
+
self.end_stream()
|
|
206
|
+
return True
|
|
207
|
+
|
|
208
|
+
case _:
|
|
209
|
+
raise NotImplementedError(f"Unknown message type: {msg.message}")
|
|
210
|
+
|
|
211
|
+
return False
|
|
212
|
+
|
|
213
|
+
def handle_config_update(self, config_groups: list[ConfigGroup]):
|
|
214
|
+
if config_groups is None:
|
|
215
|
+
return 0
|
|
216
|
+
|
|
217
|
+
logger.info("setting config groups:")
|
|
218
|
+
|
|
219
|
+
for group, config in config_groups:
|
|
220
|
+
self.core.setConfig(group, config)
|
|
221
|
+
|
|
222
|
+
logger.info(f"{group} = {config}")
|
|
223
|
+
|
|
224
|
+
return 0
|
|
225
|
+
|
|
226
|
+
def handle_device_update(self, devices: list[DeviceProperty]):
|
|
227
|
+
if devices is None:
|
|
228
|
+
return 0
|
|
229
|
+
|
|
230
|
+
logger.info("setting device properties:")
|
|
231
|
+
|
|
232
|
+
for label, name, value, t in devices:
|
|
233
|
+
t_func = {
|
|
234
|
+
"str": str,
|
|
235
|
+
"float": float,
|
|
236
|
+
"int": int,
|
|
237
|
+
"bool": bool,
|
|
238
|
+
}[t]
|
|
239
|
+
|
|
240
|
+
logger.info(f"{label}-{name}: {t} = {value}")
|
|
241
|
+
|
|
242
|
+
self.core.setProperty(label, name, t_func(value))
|
|
243
|
+
|
|
244
|
+
return 1
|
|
245
|
+
|
|
246
|
+
def set_binning(self, binning: int):
|
|
247
|
+
core = self.core
|
|
248
|
+
camera = self.core.getCameraDevice()
|
|
249
|
+
|
|
250
|
+
try:
|
|
251
|
+
allowed = core.getAllowedPropertyValues(camera, "Binning")
|
|
252
|
+
except Exception:
|
|
253
|
+
return None
|
|
254
|
+
if allowed is None:
|
|
255
|
+
# seen with a pymmcore-plus / pymmcore pair that do not belong
|
|
256
|
+
# together (the real core refuses to load in that state; this is
|
|
257
|
+
# a last line of defence for other cores)
|
|
258
|
+
if not self.warned_binning:
|
|
259
|
+
logger.warning(
|
|
260
|
+
f"camera {camera!r} reported no allowed binnings (None); "
|
|
261
|
+
"binning left as it is"
|
|
262
|
+
)
|
|
263
|
+
self.warned_binning = True
|
|
264
|
+
return None
|
|
265
|
+
|
|
266
|
+
binning_str = f"{binning}x{binning}"
|
|
267
|
+
|
|
268
|
+
if binning_str in allowed:
|
|
269
|
+
core.setProperty(camera, "Binning", binning_str)
|
|
270
|
+
|
|
271
|
+
else:
|
|
272
|
+
if self.warned_binning:
|
|
273
|
+
return None
|
|
274
|
+
|
|
275
|
+
logger.warning(
|
|
276
|
+
f"attempted set binning {binning_str}, allowed binnings {allowed}"
|
|
277
|
+
)
|
|
278
|
+
self.warned_binning = True
|
|
279
|
+
|
|
280
|
+
@staticmethod
|
|
281
|
+
def _skip_key(event) -> tuple[int, str] | None:
|
|
282
|
+
index = getattr(event, "index", None) or {}
|
|
283
|
+
if "t" not in index:
|
|
284
|
+
return None
|
|
285
|
+
return (int(index["t"]), event.experiment_name)
|
|
286
|
+
|
|
287
|
+
def _skipping(self, event) -> bool:
|
|
288
|
+
"""Whether this event belongs to a visit a blank pattern cancelled."""
|
|
289
|
+
if not getattr(event, "skippable_if_blank", False):
|
|
290
|
+
return False
|
|
291
|
+
key = self._skip_key(event)
|
|
292
|
+
return key is not None and key in self._blank_skips
|
|
293
|
+
|
|
294
|
+
def handle_update_position_event(self, up_event: UpdateStagePositionEvent):
|
|
295
|
+
if self._skipping(up_event):
|
|
296
|
+
self.skipped_moves += 1
|
|
297
|
+
logger.info(
|
|
298
|
+
f"experiment {up_event.experiment_name}: blank pattern, "
|
|
299
|
+
"stimulation only; stage move skipped"
|
|
300
|
+
)
|
|
301
|
+
return
|
|
302
|
+
position = up_event.position
|
|
303
|
+
# a grid is visited tile by tile inside each acquisition; the position
|
|
304
|
+
# event brings the stage to its first tile
|
|
305
|
+
tiles = getattr(position, "tiles", None)
|
|
306
|
+
target = tiles[0] if tiles else position
|
|
307
|
+
z_moved, z_new_position = self.position_mover.move_to(target, self.core)
|
|
308
|
+
|
|
309
|
+
if z_moved:
|
|
310
|
+
old_z = position.z
|
|
311
|
+
|
|
312
|
+
if np.abs(old_z - z_new_position) > 5:
|
|
313
|
+
logger.warning(f"Major Z position change: {old_z}, {z_new_position}")
|
|
314
|
+
|
|
315
|
+
if abs(z_new_position - old_z) > 1.0:
|
|
316
|
+
self.manager.put(
|
|
317
|
+
UpdateZPositionMessage(z_new_position, up_event.experiment_name)
|
|
318
|
+
)
|
|
319
|
+
|
|
320
|
+
def _await_slm_pattern(self, event_id, timeout_s: float) -> EventSLMPattern | None:
|
|
321
|
+
"""
|
|
322
|
+
Wait for the SLM buffer's reply to ``event_id``.
|
|
323
|
+
|
|
324
|
+
Replies for other events (left over from an earlier timeout) are
|
|
325
|
+
discarded. Returns None if no matching reply arrives within ``timeout_s``.
|
|
326
|
+
"""
|
|
327
|
+
deadline = time() + timeout_s
|
|
328
|
+
|
|
329
|
+
while True:
|
|
330
|
+
remaining = deadline - time()
|
|
331
|
+
if remaining <= 0:
|
|
332
|
+
return None
|
|
333
|
+
|
|
334
|
+
try:
|
|
335
|
+
pattern_data = self.slm_queue.get(True, remaining)
|
|
336
|
+
except Empty:
|
|
337
|
+
return None
|
|
338
|
+
|
|
339
|
+
if not isinstance(pattern_data, EventSLMPattern):
|
|
340
|
+
logger.warning(
|
|
341
|
+
f"discarding unexpected item on slm queue: {type(pattern_data)}"
|
|
342
|
+
)
|
|
343
|
+
continue
|
|
344
|
+
|
|
345
|
+
if pattern_data.event_id != event_id:
|
|
346
|
+
logger.warning(
|
|
347
|
+
f"discarding stale SLM pattern for event {pattern_data.event_id}"
|
|
348
|
+
)
|
|
349
|
+
continue
|
|
350
|
+
|
|
351
|
+
return pattern_data
|
|
352
|
+
|
|
353
|
+
def handle_update_pattern_event(
|
|
354
|
+
self, up_event: UpdatePatternEvent, slm_await_s: float | None = None
|
|
355
|
+
):
|
|
356
|
+
if slm_await_s is None:
|
|
357
|
+
slm_await_s = self.slm_await_s
|
|
358
|
+
|
|
359
|
+
event_id = up_event.id
|
|
360
|
+
logger.debug(f"handling update pattern event {event_id}")
|
|
361
|
+
|
|
362
|
+
if not self.slm_initialized:
|
|
363
|
+
raise RuntimeError(
|
|
364
|
+
"slm not declared to microscope process, run declare_slm first"
|
|
365
|
+
)
|
|
366
|
+
|
|
367
|
+
pattern_data = self._await_slm_pattern(event_id, slm_await_s)
|
|
368
|
+
|
|
369
|
+
if pattern_data is None:
|
|
370
|
+
logger.warning(
|
|
371
|
+
f"experiment {up_event.experiment_name}: SLM buffer did not answer "
|
|
372
|
+
f"within {slm_await_s}s; keeping the current pattern "
|
|
373
|
+
f"(id {self.current_pattern_id})"
|
|
374
|
+
)
|
|
375
|
+
return 0
|
|
376
|
+
|
|
377
|
+
pattern = pattern_data.pattern
|
|
378
|
+
|
|
379
|
+
if getattr(up_event, "skippable_if_blank", False):
|
|
380
|
+
key = self._skip_key(up_event)
|
|
381
|
+
if key is not None:
|
|
382
|
+
if pattern_is_blank(pattern):
|
|
383
|
+
self._blank_skips.add(key)
|
|
384
|
+
else:
|
|
385
|
+
self._blank_skips.discard(key)
|
|
386
|
+
# keep the set small: earlier timepoints are over
|
|
387
|
+
self._blank_skips = {k for k in self._blank_skips if k[0] >= key[0] - 1}
|
|
388
|
+
|
|
389
|
+
# a grid experiment's pattern is one DMD image per tile; the first goes
|
|
390
|
+
# up now, the others as the tiles are visited
|
|
391
|
+
first = pattern[0] if isinstance(pattern, list | tuple) else pattern
|
|
392
|
+
if self.slm_device == "dummy":
|
|
393
|
+
logger.info(f"experiment {up_event.experiment_name}: dummy slm set image")
|
|
394
|
+
else:
|
|
395
|
+
self.core.setSLMImage(self.slm_device, first)
|
|
396
|
+
logger.info(f"experiment {up_event.experiment_name}: set slm image")
|
|
397
|
+
|
|
398
|
+
self.current_pattern = pattern
|
|
399
|
+
self.current_pattern_id = pattern_data.pattern_unique_id
|
|
400
|
+
self.current_camera_pattern = pattern_data.camera_pattern
|
|
401
|
+
self.current_dmd_ids = pattern_data.dmd_ids
|
|
402
|
+
|
|
403
|
+
return 0
|
|
404
|
+
|
|
405
|
+
def handle_acquisition_event(self, aq_event: AcquisitionEvent):
|
|
406
|
+
if self._skipping(aq_event):
|
|
407
|
+
self.skipped_acquisitions += 1
|
|
408
|
+
aq_event.completed_time = time()
|
|
409
|
+
logger.info(
|
|
410
|
+
f"experiment {aq_event.experiment_name} t={aq_event.t_index}: "
|
|
411
|
+
"stimulation skipped (blank pattern)"
|
|
412
|
+
)
|
|
413
|
+
# the writer learns of it on the data stream, in order with the frames
|
|
414
|
+
self._emit(SkippedAcquisition(aq_event))
|
|
415
|
+
self.manager.put(EventDoneMessage(aq_event, skipped=True))
|
|
416
|
+
return
|
|
417
|
+
event_id = aq_event.id
|
|
418
|
+
logger.debug(f"{self.t(): .3f}| handling acquisition event {event_id}")
|
|
419
|
+
|
|
420
|
+
self.handle_config_update(aq_event.config_groups)
|
|
421
|
+
self.handle_device_update(aq_event.devices)
|
|
422
|
+
self.core.setExposure(aq_event.exposure_time_ms)
|
|
423
|
+
|
|
424
|
+
self.set_binning(aq_event.binning)
|
|
425
|
+
|
|
426
|
+
target_time = aq_event.scheduled_time
|
|
427
|
+
t_delta = target_time - time() - 0.1
|
|
428
|
+
|
|
429
|
+
if t_delta > 0:
|
|
430
|
+
logger.info(
|
|
431
|
+
f"{self.t(): .3f}| waiting {t_delta: .3f}s until next acquisition"
|
|
432
|
+
)
|
|
433
|
+
sleep(t_delta)
|
|
434
|
+
|
|
435
|
+
tiles = getattr(aq_event.position, "tiles", None)
|
|
436
|
+
geometry = getattr(aq_event.position, "geometry", None)
|
|
437
|
+
if tiles and geometry is not None:
|
|
438
|
+
image = self._acquire_grid(aq_event, tiles, geometry)
|
|
439
|
+
else:
|
|
440
|
+
self._settle()
|
|
441
|
+
logger.info(
|
|
442
|
+
f"{self.t(): .3f}| acquiring image: {aq_event.exposure_time_ms}ms"
|
|
443
|
+
)
|
|
444
|
+
image = self.snap()
|
|
445
|
+
aq_event.completed_time = time()
|
|
446
|
+
logger.info(f"{self.t(): .3f}| image acquired")
|
|
447
|
+
|
|
448
|
+
aq_event.pixel_width_um = self.core.getPixelSizeUm()
|
|
449
|
+
|
|
450
|
+
if aq_event.needs_slm:
|
|
451
|
+
data_out = StimulationData(
|
|
452
|
+
aq_event,
|
|
453
|
+
image,
|
|
454
|
+
self.current_pattern,
|
|
455
|
+
self.current_pattern_id,
|
|
456
|
+
camera_pattern=self.current_camera_pattern,
|
|
457
|
+
dmd_ids=self.current_dmd_ids,
|
|
458
|
+
)
|
|
459
|
+
else:
|
|
460
|
+
data_out = AcquisitionData(aq_event, image)
|
|
461
|
+
|
|
462
|
+
self._emit(data_out)
|
|
463
|
+
# acknowledge to the Manager: lateness and errors are tracked there
|
|
464
|
+
self.manager.put(EventDoneMessage(aq_event))
|
|
465
|
+
|
|
466
|
+
def _settle(self):
|
|
467
|
+
logger.debug("wait for system")
|
|
468
|
+
wait_time = time()
|
|
469
|
+
self.core.waitForSystem()
|
|
470
|
+
logger.debug(f"took {time() - wait_time: .3f}s")
|
|
471
|
+
if self.settle_time_s > 0:
|
|
472
|
+
sleep(self.settle_time_s)
|
|
473
|
+
|
|
474
|
+
def _acquire_grid(self, aq_event: AcquisitionEvent, tiles, geometry):
|
|
475
|
+
"""
|
|
476
|
+
Visit every tile of a grid position for one channel: move, settle,
|
|
477
|
+
snap (with the tile's own DMD image up for a stimulation frame), then
|
|
478
|
+
stitch the tiles into the one frame the pipeline consumes.
|
|
479
|
+
"""
|
|
480
|
+
patterns = self.current_pattern if aq_event.needs_slm else None
|
|
481
|
+
per_tile = isinstance(patterns, list | tuple)
|
|
482
|
+
frames = []
|
|
483
|
+
for k, tile in enumerate(tiles):
|
|
484
|
+
if per_tile and self.slm_device != "dummy":
|
|
485
|
+
self.core.setSLMImage(self.slm_device, patterns[k])
|
|
486
|
+
self.position_mover.move_to(tile, self.core)
|
|
487
|
+
self._settle()
|
|
488
|
+
logger.info(
|
|
489
|
+
f"{self.t(): .3f}| tile {k + 1}/{len(tiles)} of "
|
|
490
|
+
f"{aq_event.experiment_name}: {aq_event.exposure_time_ms}ms"
|
|
491
|
+
)
|
|
492
|
+
frames.append(self.snap())
|
|
493
|
+
return stitch(frames, geometry, aq_event.binning)
|
|
494
|
+
|
|
495
|
+
def snap(self):
|
|
496
|
+
core = self.core
|
|
497
|
+
|
|
498
|
+
core.snapImage()
|
|
499
|
+
image = core.getImage()
|
|
500
|
+
|
|
501
|
+
return image
|
|
502
|
+
|
|
503
|
+
def t(self):
|
|
504
|
+
return time() - self.start
|