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/manager.py
ADDED
|
@@ -0,0 +1,861 @@
|
|
|
1
|
+
"""
|
|
2
|
+
The Manager is the timing brain of the feedback loop: it walks the
|
|
3
|
+
acquisition plan and turns each timepoint into messages for the microscope,
|
|
4
|
+
the SLM buffer and the pattern process. The SLMBuffer holds the current DMD
|
|
5
|
+
pattern per experiment and answers the microscope's pattern requests.
|
|
6
|
+
|
|
7
|
+
Frame routing lives in ``router.py`` and persistence in ``writer_process.py``
|
|
8
|
+
(before Stage 3 both were the "microscope outbox" defined here;
|
|
9
|
+
``MicroscopeOutbox`` is still importable from this module).
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import datetime
|
|
13
|
+
import json
|
|
14
|
+
import logging
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from queue import Empty
|
|
17
|
+
from threading import Event
|
|
18
|
+
from time import sleep, time
|
|
19
|
+
from typing import Any
|
|
20
|
+
|
|
21
|
+
import numpy as np
|
|
22
|
+
from cv2 import warpAffine
|
|
23
|
+
|
|
24
|
+
from pyclm.core.pattern_process import RequestPattern
|
|
25
|
+
|
|
26
|
+
from .base_process import BaseProcess
|
|
27
|
+
from .datatypes import CameraPattern, EventSLMPattern, SkippedAcquisition
|
|
28
|
+
from .events import (
|
|
29
|
+
AcquisitionEvent,
|
|
30
|
+
UpdatePatternEvent,
|
|
31
|
+
UpdateStagePositionEvent,
|
|
32
|
+
)
|
|
33
|
+
from .experiments import ConfigGroup, DeviceProperty, Experiment
|
|
34
|
+
from .grid import cut
|
|
35
|
+
from .messages import (
|
|
36
|
+
AcquisitionEventMessage,
|
|
37
|
+
CloseMessage,
|
|
38
|
+
EventDoneMessage,
|
|
39
|
+
Message,
|
|
40
|
+
SettingsRequestMessage,
|
|
41
|
+
UpdatePatternEventMessage,
|
|
42
|
+
UpdatePatternParamsMessage,
|
|
43
|
+
UpdatePositionEventMessage,
|
|
44
|
+
UpdateZPositionMessage,
|
|
45
|
+
)
|
|
46
|
+
from .plan import AcquisitionPlan, PlannedEvent
|
|
47
|
+
from .queues import AllQueues
|
|
48
|
+
from .settings import STIMULATION, SettingChange, check_change, property_type
|
|
49
|
+
from .storage.events import EventLog
|
|
50
|
+
from .writer_process import MicroscopeOutbox, WriterProcess
|
|
51
|
+
|
|
52
|
+
logger = logging.getLogger(__name__)
|
|
53
|
+
|
|
54
|
+
__all__ = ["Manager", "MicroscopeOutbox", "SLMBuffer", "WriterProcess"]
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def compose_affine(affine, roi_offset=(0.0, 0.0), binning=1) -> np.ndarray:
|
|
58
|
+
"""
|
|
59
|
+
The camera-to-SLM affine for a pattern expressed in a camera ROI at a
|
|
60
|
+
binning: ``affine`` is calibrated in full-frame unbinned pixels, so a
|
|
61
|
+
pattern pixel ``p`` sits at ``binning * p + roi_offset`` in that frame.
|
|
62
|
+
"""
|
|
63
|
+
at = np.array(affine, dtype=np.float32)
|
|
64
|
+
ox, oy = roi_offset
|
|
65
|
+
if ox or oy:
|
|
66
|
+
at[:, 2] = at[:, 2] + at[:, :2] @ np.array([ox, oy], dtype=np.float32)
|
|
67
|
+
if binning != 1:
|
|
68
|
+
at[:, :2] = at[:, :2] * binning
|
|
69
|
+
return at
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class SLMBuffer(BaseProcess):
|
|
73
|
+
"""
|
|
74
|
+
Holds the most recent pattern per experiment in SLM coordinates and
|
|
75
|
+
answers the Manager's ``update_pattern_event`` with it (the microscope
|
|
76
|
+
waits for that reply before a stimulation frame).
|
|
77
|
+
"""
|
|
78
|
+
|
|
79
|
+
def __init__(self, aq: AllQueues, stop_event: Event | None = None):
|
|
80
|
+
super().__init__(stop_event, name="slm buffer")
|
|
81
|
+
|
|
82
|
+
self.from_manager = aq.manager_to_slm_buffer
|
|
83
|
+
self.from_pattern = aq.pattern_to_slm
|
|
84
|
+
self.to_microscope = aq.slm_to_microscope
|
|
85
|
+
|
|
86
|
+
self.slm_patterns = {}
|
|
87
|
+
|
|
88
|
+
self.slm_shape = None
|
|
89
|
+
self.affine_transform = None
|
|
90
|
+
|
|
91
|
+
self.initialized = False
|
|
92
|
+
|
|
93
|
+
self.manager_done = False
|
|
94
|
+
self.pattern_done = False
|
|
95
|
+
|
|
96
|
+
self.register_queue(self.from_manager, self.handle_message)
|
|
97
|
+
self.register_queue(self.from_pattern, self._handle_from_pattern)
|
|
98
|
+
|
|
99
|
+
def initialize(
|
|
100
|
+
self,
|
|
101
|
+
shape: tuple[int, int],
|
|
102
|
+
affine_transform: np.ndarray[Any, np.float32],
|
|
103
|
+
experiment_names: list[str],
|
|
104
|
+
roi=None,
|
|
105
|
+
grids: dict | None = None,
|
|
106
|
+
):
|
|
107
|
+
"""
|
|
108
|
+
:param roi: the camera ROI ``(x, y, width, height)`` in unbinned pixels
|
|
109
|
+
the patterns are expressed in; the affine is calibrated in the
|
|
110
|
+
full frame, so the offset is composed into it
|
|
111
|
+
:param grids: ``{experiment: GridGeometry}`` for grid experiments, whose
|
|
112
|
+
(stitched) patterns are cut into one DMD image per tile
|
|
113
|
+
"""
|
|
114
|
+
self.slm_shape = shape
|
|
115
|
+
self.affine_transform = np.array(affine_transform)
|
|
116
|
+
self.roi_offset = (0.0, 0.0) if roi is None else (float(roi[0]), float(roi[1]))
|
|
117
|
+
self.grids = dict(grids or {})
|
|
118
|
+
|
|
119
|
+
assert affine_transform.shape == (2, 3), "Affine transform must be a 2x3 matrix"
|
|
120
|
+
|
|
121
|
+
# Initialize patterns for each experiment
|
|
122
|
+
for name in experiment_names:
|
|
123
|
+
slm_pattern = np.zeros(
|
|
124
|
+
self.slm_shape, dtype=np.uint8
|
|
125
|
+
) # Initialize a blank pattern
|
|
126
|
+
# (pattern id, DMD image(s), camera-space uint8 pattern or None, DMD ids)
|
|
127
|
+
geom = self.grids.get(name)
|
|
128
|
+
if geom is None:
|
|
129
|
+
self.slm_patterns[name] = (0, slm_pattern, None, None)
|
|
130
|
+
else:
|
|
131
|
+
n = len(geom.tiles)
|
|
132
|
+
self.slm_patterns[name] = (
|
|
133
|
+
0,
|
|
134
|
+
[np.zeros(self.slm_shape, dtype=np.uint8) for _ in range(n)],
|
|
135
|
+
None,
|
|
136
|
+
[f"0:{k}" for k in range(n)],
|
|
137
|
+
)
|
|
138
|
+
|
|
139
|
+
self.initialized = True
|
|
140
|
+
|
|
141
|
+
def pattern_to_slm(self, pattern: np.ndarray, binning=1):
|
|
142
|
+
"""
|
|
143
|
+
This function takes a pattern and applies the stored affine transformation
|
|
144
|
+
:param pattern: np array of type float scaled from 0-1, in coordinates of camera
|
|
145
|
+
:param binning: the camera binning the pattern is at
|
|
146
|
+
:return: at_slm_pattern: np array of type uint8, transformed to SLM coordinates
|
|
147
|
+
"""
|
|
148
|
+
assert self.initialized, (
|
|
149
|
+
"SLMBuffer must be initialized before converting patterns"
|
|
150
|
+
)
|
|
151
|
+
|
|
152
|
+
at = compose_affine(self.affine_transform, self.roi_offset, binning)
|
|
153
|
+
|
|
154
|
+
return warpAffine(
|
|
155
|
+
np.round(pattern * 255).astype(np.uint8),
|
|
156
|
+
at,
|
|
157
|
+
(self.slm_shape[1], self.slm_shape[0]),
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
def _handle_from_pattern(self, item):
|
|
161
|
+
if isinstance(item, Message):
|
|
162
|
+
return self.handle_message(item)
|
|
163
|
+
self.handle_data(item)
|
|
164
|
+
return False
|
|
165
|
+
|
|
166
|
+
def handle_data(self, data: CameraPattern):
|
|
167
|
+
logger.info("SLM buffer received a pattern")
|
|
168
|
+
|
|
169
|
+
pattern = data.data
|
|
170
|
+
pattern_id = data.pattern_id
|
|
171
|
+
|
|
172
|
+
experiment_name = data.experiment
|
|
173
|
+
|
|
174
|
+
camera = np.round(np.clip(np.asarray(pattern, dtype=np.float32), 0, 1) * 255)
|
|
175
|
+
camera = camera.astype(np.uint8)
|
|
176
|
+
geom = self.grids.get(experiment_name)
|
|
177
|
+
if geom is None:
|
|
178
|
+
slm_pattern = self.pattern_to_slm(pattern, data.binning)
|
|
179
|
+
dmd_ids = None
|
|
180
|
+
else:
|
|
181
|
+
# the method returned the stitched pattern: one DMD image per tile
|
|
182
|
+
expected = geom.shape(data.binning)
|
|
183
|
+
if tuple(np.asarray(pattern).shape[:2]) != tuple(expected):
|
|
184
|
+
logger.warning(
|
|
185
|
+
f"{experiment_name}: pattern shape {np.asarray(pattern).shape} "
|
|
186
|
+
f"is not the stitched shape {expected}; cutting what fits"
|
|
187
|
+
)
|
|
188
|
+
slm_pattern = [
|
|
189
|
+
self.pattern_to_slm(tile, data.binning)
|
|
190
|
+
for tile in cut(pattern, geom, data.binning)
|
|
191
|
+
]
|
|
192
|
+
dmd_ids = [f"{pattern_id}:{k}" for k in range(len(slm_pattern))]
|
|
193
|
+
|
|
194
|
+
# Store the pattern in the dictionary
|
|
195
|
+
if experiment_name in self.slm_patterns:
|
|
196
|
+
# set the current pattern and id
|
|
197
|
+
self.slm_patterns[experiment_name] = (
|
|
198
|
+
pattern_id,
|
|
199
|
+
slm_pattern,
|
|
200
|
+
camera,
|
|
201
|
+
dmd_ids,
|
|
202
|
+
)
|
|
203
|
+
else:
|
|
204
|
+
logger.warning(
|
|
205
|
+
f"Experiment name '{experiment_name}' not found in SLM patterns."
|
|
206
|
+
)
|
|
207
|
+
|
|
208
|
+
def handle_message(self, msg):
|
|
209
|
+
"""
|
|
210
|
+
Handle messages sent to the SLMBuffer from the manager (and the
|
|
211
|
+
pattern process's stream close).
|
|
212
|
+
:param msg: Message object
|
|
213
|
+
:return: bool indicating whether to close the process
|
|
214
|
+
"""
|
|
215
|
+
match msg.message:
|
|
216
|
+
case "close":
|
|
217
|
+
self.manager_done = True
|
|
218
|
+
|
|
219
|
+
case "stream_close":
|
|
220
|
+
self.pattern_done = True
|
|
221
|
+
|
|
222
|
+
case "update_pattern_event":
|
|
223
|
+
event = msg.event
|
|
224
|
+
|
|
225
|
+
update_pattern_event_id = event.id
|
|
226
|
+
experiment_name = event.experiment_name
|
|
227
|
+
|
|
228
|
+
pattern = self.slm_patterns[experiment_name]
|
|
229
|
+
|
|
230
|
+
data = EventSLMPattern(
|
|
231
|
+
update_pattern_event_id,
|
|
232
|
+
pattern[1],
|
|
233
|
+
pattern[0],
|
|
234
|
+
camera_pattern=pattern[2],
|
|
235
|
+
dmd_ids=pattern[3],
|
|
236
|
+
)
|
|
237
|
+
|
|
238
|
+
self.to_microscope.put(data)
|
|
239
|
+
|
|
240
|
+
case _:
|
|
241
|
+
raise ValueError(f"Unexpected message: {msg}")
|
|
242
|
+
|
|
243
|
+
if self.manager_done and self.pattern_done:
|
|
244
|
+
return True
|
|
245
|
+
|
|
246
|
+
return False
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
class Manager:
|
|
250
|
+
"""
|
|
251
|
+
Walks the acquisition plan: waits for each timepoint, then turns the plan's
|
|
252
|
+
events for that timepoint into messages for the other processes.
|
|
253
|
+
"""
|
|
254
|
+
|
|
255
|
+
def __init__(self, aq: AllQueues, stop_event: Event | None = None):
|
|
256
|
+
self.stop_event = stop_event
|
|
257
|
+
self.msgout = {
|
|
258
|
+
"microscope": aq.manager_to_microscope,
|
|
259
|
+
"slm_buffer": aq.manager_to_slm_buffer,
|
|
260
|
+
"pattern": aq.manager_to_pattern,
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
self.msgin = {
|
|
264
|
+
"microscope": aq.microscope_to_manager,
|
|
265
|
+
"pattern": aq.pattern_to_manager,
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
# seconds to sleep between inbox checks while waiting for the next timepoint
|
|
269
|
+
self.sleep_interval = 0.01
|
|
270
|
+
|
|
271
|
+
self.initialized = False
|
|
272
|
+
self.plan: AcquisitionPlan | None = None
|
|
273
|
+
self.schedule = None
|
|
274
|
+
self.experiments = None
|
|
275
|
+
self.times = None
|
|
276
|
+
self.positions = None
|
|
277
|
+
|
|
278
|
+
# runtime edits (core/settings.py) and feedback from the microscope
|
|
279
|
+
self.event_log: EventLog = EventLog(None)
|
|
280
|
+
self.status_path: Path | None = None
|
|
281
|
+
self.health = None # optional callable returning process counters
|
|
282
|
+
self.current_t = 0 # the timepoint being awaited or dispatched
|
|
283
|
+
self._last_burst_t = -1 # the last timepoint whose events were emitted
|
|
284
|
+
self.start_time = 0.0
|
|
285
|
+
# (experiment, channel) -> {frames-table column: value} in force
|
|
286
|
+
self.overrides: dict[tuple[str, str], dict] = {}
|
|
287
|
+
# t -> experiment -> {"frames", "errors", "lateness_s"} from acknowledgements
|
|
288
|
+
self.acks: dict[int, dict[str, dict]] = {}
|
|
289
|
+
self.settings_applied = 0
|
|
290
|
+
self.settings_refused = 0
|
|
291
|
+
self._late_warned: set[int] = set()
|
|
292
|
+
self.finished = False
|
|
293
|
+
# the experiment the microscope last acknowledged (where it is now)
|
|
294
|
+
self.current_experiment: str | None = None
|
|
295
|
+
# commands (core/commands.py): polled from a directory at the boundary
|
|
296
|
+
self.commands_dir: Path | None = None
|
|
297
|
+
self.paused = False
|
|
298
|
+
self._pause_started = 0.0
|
|
299
|
+
self.paused_s = 0.0
|
|
300
|
+
self.stopping = False
|
|
301
|
+
self.pending_commands = 0
|
|
302
|
+
self.commands_applied = 0
|
|
303
|
+
self._last_poll = 0.0
|
|
304
|
+
self.poll_interval = 0.5
|
|
305
|
+
|
|
306
|
+
def initialize(
|
|
307
|
+
self,
|
|
308
|
+
plan: AcquisitionPlan,
|
|
309
|
+
event_log: EventLog | None = None,
|
|
310
|
+
status_path: Path | None = None,
|
|
311
|
+
health=None,
|
|
312
|
+
commands_dir: Path | None = None,
|
|
313
|
+
):
|
|
314
|
+
self.plan = plan
|
|
315
|
+
self.schedule = plan.schedule
|
|
316
|
+
self.skipped = 0
|
|
317
|
+
self.experiments: dict[str, Experiment] = plan.schedule.experiments
|
|
318
|
+
self.positions = plan.schedule.positions
|
|
319
|
+
self.times = plan.schedule.times
|
|
320
|
+
if event_log is not None:
|
|
321
|
+
self.event_log = event_log
|
|
322
|
+
self.status_path = None if status_path is None else Path(status_path)
|
|
323
|
+
self.health = health
|
|
324
|
+
self.commands_dir = None if commands_dir is None else Path(commands_dir)
|
|
325
|
+
|
|
326
|
+
self.initialized = True
|
|
327
|
+
|
|
328
|
+
def handle_message(self, msg: Message):
|
|
329
|
+
match msg.message:
|
|
330
|
+
case "update_z_position":
|
|
331
|
+
assert isinstance(msg, UpdateZPositionMessage)
|
|
332
|
+
name = msg.experiment_name
|
|
333
|
+
val = msg.new_z_position
|
|
334
|
+
|
|
335
|
+
old = self.positions[name].z
|
|
336
|
+
self.positions[name].z = val
|
|
337
|
+
self.event_log.record(
|
|
338
|
+
"z_correction",
|
|
339
|
+
name,
|
|
340
|
+
None,
|
|
341
|
+
"z",
|
|
342
|
+
old,
|
|
343
|
+
val,
|
|
344
|
+
"applied",
|
|
345
|
+
"focus lock moved z",
|
|
346
|
+
self.current_t,
|
|
347
|
+
self.current_t,
|
|
348
|
+
)
|
|
349
|
+
|
|
350
|
+
case "settings_request":
|
|
351
|
+
assert isinstance(msg, SettingsRequestMessage)
|
|
352
|
+
self.apply_settings(msg)
|
|
353
|
+
|
|
354
|
+
case "event_done":
|
|
355
|
+
assert isinstance(msg, EventDoneMessage)
|
|
356
|
+
self.handle_event_done(msg)
|
|
357
|
+
|
|
358
|
+
case "pattern_params_result":
|
|
359
|
+
for key, value in msg.applied.items():
|
|
360
|
+
self.event_log.record(
|
|
361
|
+
"pattern",
|
|
362
|
+
msg.experiment_name,
|
|
363
|
+
None,
|
|
364
|
+
key,
|
|
365
|
+
None,
|
|
366
|
+
value,
|
|
367
|
+
"applied",
|
|
368
|
+
None,
|
|
369
|
+
self.current_t,
|
|
370
|
+
self.next_timepoint(),
|
|
371
|
+
"command",
|
|
372
|
+
)
|
|
373
|
+
for key, reason in msg.refused.items():
|
|
374
|
+
self.event_log.record(
|
|
375
|
+
"pattern",
|
|
376
|
+
msg.experiment_name,
|
|
377
|
+
None,
|
|
378
|
+
key,
|
|
379
|
+
None,
|
|
380
|
+
None,
|
|
381
|
+
"refused",
|
|
382
|
+
reason,
|
|
383
|
+
self.current_t,
|
|
384
|
+
self.next_timepoint(),
|
|
385
|
+
"command",
|
|
386
|
+
)
|
|
387
|
+
|
|
388
|
+
case _:
|
|
389
|
+
raise ValueError(f"Unexpected message: {msg}")
|
|
390
|
+
|
|
391
|
+
def drain_inboxes(self) -> bool:
|
|
392
|
+
"""Handle every pending inbound message. Returns True if any was handled."""
|
|
393
|
+
handled = False
|
|
394
|
+
|
|
395
|
+
for inbox in self.msgin.values():
|
|
396
|
+
while True:
|
|
397
|
+
try:
|
|
398
|
+
msg = inbox.get_nowait()
|
|
399
|
+
except Empty:
|
|
400
|
+
break
|
|
401
|
+
|
|
402
|
+
self.handle_message(msg)
|
|
403
|
+
handled = True
|
|
404
|
+
|
|
405
|
+
return handled
|
|
406
|
+
|
|
407
|
+
# ------------------------------------------------------ runtime edits
|
|
408
|
+
def _config_for(self, name: str, channel: str | None):
|
|
409
|
+
"""(ImagingConfig, canonical channel name) for a channel of an experiment, or (None, channel)."""
|
|
410
|
+
exp = self.experiments[name]
|
|
411
|
+
stim = self.plan.stim_channel(name)
|
|
412
|
+
if channel == STIMULATION or (stim is not None and channel == stim):
|
|
413
|
+
return exp.stimulation, stim or STIMULATION
|
|
414
|
+
return exp.channels.get(channel), channel
|
|
415
|
+
|
|
416
|
+
def apply_settings(self, msg: SettingsRequestMessage, source: str = "pattern"):
|
|
417
|
+
"""
|
|
418
|
+
Validate and apply a pattern method's requested changes to its own
|
|
419
|
+
experiment. They take effect from ``current_t`` (the next timepoint
|
|
420
|
+
whose events have not been emitted) and every one is recorded.
|
|
421
|
+
"""
|
|
422
|
+
name = msg.experiment_name
|
|
423
|
+
t_apply = self.next_timepoint()
|
|
424
|
+
for change in msg.changes:
|
|
425
|
+
reason = (
|
|
426
|
+
None if name in self.experiments else f"unknown experiment {name!r}"
|
|
427
|
+
)
|
|
428
|
+
channel = change.channel
|
|
429
|
+
cfg = None
|
|
430
|
+
if reason is None:
|
|
431
|
+
reason = check_change(change)
|
|
432
|
+
if reason is None and change.kind != "position":
|
|
433
|
+
cfg, channel = self._config_for(name, change.channel)
|
|
434
|
+
if cfg is None:
|
|
435
|
+
reason = (
|
|
436
|
+
f"unknown channel {change.channel!r} "
|
|
437
|
+
f"(channels: {self.plan.channels(name)}, or '{STIMULATION}')"
|
|
438
|
+
)
|
|
439
|
+
if reason is not None:
|
|
440
|
+
self.settings_refused += 1
|
|
441
|
+
logger.warning(f"{name}: refused {change.describe()}: {reason}")
|
|
442
|
+
self.event_log.record(
|
|
443
|
+
change.kind,
|
|
444
|
+
name,
|
|
445
|
+
channel,
|
|
446
|
+
change.key,
|
|
447
|
+
None,
|
|
448
|
+
change.value,
|
|
449
|
+
"refused",
|
|
450
|
+
reason,
|
|
451
|
+
msg.t_requested,
|
|
452
|
+
t_apply,
|
|
453
|
+
source,
|
|
454
|
+
)
|
|
455
|
+
continue
|
|
456
|
+
old = self._apply_change(name, cfg, channel, change)
|
|
457
|
+
self.settings_applied += 1
|
|
458
|
+
logger.info(f"{name}: {change.describe()} (was {old!r}) from t = {t_apply}")
|
|
459
|
+
self.event_log.record(
|
|
460
|
+
change.kind,
|
|
461
|
+
name,
|
|
462
|
+
channel,
|
|
463
|
+
change.key,
|
|
464
|
+
old,
|
|
465
|
+
change.value,
|
|
466
|
+
"applied",
|
|
467
|
+
None,
|
|
468
|
+
msg.t_requested,
|
|
469
|
+
t_apply,
|
|
470
|
+
source,
|
|
471
|
+
)
|
|
472
|
+
|
|
473
|
+
def next_timepoint(self) -> int:
|
|
474
|
+
"""The first timepoint whose events have not been emitted: where a change takes effect."""
|
|
475
|
+
if self.current_t > self._last_burst_t:
|
|
476
|
+
return self.current_t
|
|
477
|
+
return self._last_burst_t + 1
|
|
478
|
+
|
|
479
|
+
def _apply_change(self, name: str, cfg, channel: str | None, change: SettingChange):
|
|
480
|
+
if change.kind == "position":
|
|
481
|
+
pos = self.positions[name]
|
|
482
|
+
if change.key == "pfs_offset":
|
|
483
|
+
old = pos.extras.get("PFSOffset")
|
|
484
|
+
pos.extras["PFSOffset"] = float(change.value)
|
|
485
|
+
else:
|
|
486
|
+
old = getattr(pos, change.key)
|
|
487
|
+
setattr(pos, change.key, float(change.value))
|
|
488
|
+
return old
|
|
489
|
+
if change.kind == "exposure":
|
|
490
|
+
old = cfg.exposure
|
|
491
|
+
cfg.exposure = float(change.value)
|
|
492
|
+
return old
|
|
493
|
+
if change.kind == "config":
|
|
494
|
+
old = {g.group: g.config for g in cfg.get_config_groups()}.get(change.key)
|
|
495
|
+
cfg.update_config_groups([ConfigGroup(change.key, change.value)])
|
|
496
|
+
else:
|
|
497
|
+
old = next(
|
|
498
|
+
(
|
|
499
|
+
d.value
|
|
500
|
+
for d in cfg.get_device_properties()
|
|
501
|
+
if d.device == change.device and d.property == change.prop
|
|
502
|
+
),
|
|
503
|
+
None,
|
|
504
|
+
)
|
|
505
|
+
cfg.update_device_properties(
|
|
506
|
+
[
|
|
507
|
+
DeviceProperty(
|
|
508
|
+
change.device,
|
|
509
|
+
change.prop,
|
|
510
|
+
change.value,
|
|
511
|
+
property_type(change.value),
|
|
512
|
+
)
|
|
513
|
+
]
|
|
514
|
+
)
|
|
515
|
+
self.overrides.setdefault((name, channel), {})[change.column] = change.value
|
|
516
|
+
return old
|
|
517
|
+
|
|
518
|
+
def construct_position_event_message(self, position, name, **kwargs):
|
|
519
|
+
self.msgout["microscope"].put(
|
|
520
|
+
UpdatePositionEventMessage(
|
|
521
|
+
UpdateStagePositionEvent(position, name, **kwargs)
|
|
522
|
+
)
|
|
523
|
+
)
|
|
524
|
+
|
|
525
|
+
# ------------------------------------------------------------ commands
|
|
526
|
+
def poll_commands(self) -> bool:
|
|
527
|
+
"""Apply the command files waiting in ``commands_dir`` (at most every ``poll_interval`` s)."""
|
|
528
|
+
if self.commands_dir is None:
|
|
529
|
+
return False
|
|
530
|
+
now = time()
|
|
531
|
+
if now - self._last_poll < self.poll_interval:
|
|
532
|
+
return False
|
|
533
|
+
self._last_poll = now
|
|
534
|
+
from ..commands import mark_done, pending_in
|
|
535
|
+
|
|
536
|
+
found = pending_in(self.commands_dir)
|
|
537
|
+
self.pending_commands = len(found)
|
|
538
|
+
handled = False
|
|
539
|
+
for path, command, problem in found:
|
|
540
|
+
if command is None:
|
|
541
|
+
logger.warning(f"command file {path.name} refused: {problem}")
|
|
542
|
+
self.event_log.record(
|
|
543
|
+
"command",
|
|
544
|
+
None,
|
|
545
|
+
None,
|
|
546
|
+
path.name,
|
|
547
|
+
None,
|
|
548
|
+
None,
|
|
549
|
+
"refused",
|
|
550
|
+
problem,
|
|
551
|
+
self.current_t,
|
|
552
|
+
self.next_timepoint(),
|
|
553
|
+
"command",
|
|
554
|
+
)
|
|
555
|
+
else:
|
|
556
|
+
self.apply_command(command, path.name)
|
|
557
|
+
mark_done(path)
|
|
558
|
+
handled = True
|
|
559
|
+
self.pending_commands = 0
|
|
560
|
+
return handled
|
|
561
|
+
|
|
562
|
+
def apply_command(self, command, name: str = "") -> bool:
|
|
563
|
+
"""Apply one command; every outcome is an events row. Returns True if applied."""
|
|
564
|
+
text = command.describe()
|
|
565
|
+
t_apply = self.next_timepoint()
|
|
566
|
+
|
|
567
|
+
def record(status, detail=None, old=None, new=None):
|
|
568
|
+
self.event_log.record(
|
|
569
|
+
"command",
|
|
570
|
+
command.experiment,
|
|
571
|
+
command.channel,
|
|
572
|
+
command.command,
|
|
573
|
+
old,
|
|
574
|
+
new if new is not None else text,
|
|
575
|
+
status,
|
|
576
|
+
detail,
|
|
577
|
+
self.current_t,
|
|
578
|
+
t_apply,
|
|
579
|
+
"command",
|
|
580
|
+
)
|
|
581
|
+
|
|
582
|
+
kind = command.command
|
|
583
|
+
if kind == "pause":
|
|
584
|
+
if not self.paused:
|
|
585
|
+
self.paused = True
|
|
586
|
+
self._pause_started = time()
|
|
587
|
+
logger.warning("run paused by command")
|
|
588
|
+
record("applied")
|
|
589
|
+
elif kind == "resume":
|
|
590
|
+
if not self.paused:
|
|
591
|
+
record("refused", "not paused")
|
|
592
|
+
return False
|
|
593
|
+
shift = time() - self._pause_started
|
|
594
|
+
self.start_time += shift
|
|
595
|
+
self.paused_s += shift
|
|
596
|
+
self.paused = False
|
|
597
|
+
logger.warning(f"run resumed after {shift:.1f}s")
|
|
598
|
+
record("applied", f"paused {shift:.1f} s")
|
|
599
|
+
elif kind == "stop_run":
|
|
600
|
+
self.stopping = True
|
|
601
|
+
logger.warning("run will stop after this timepoint (command)")
|
|
602
|
+
record("applied")
|
|
603
|
+
elif kind == "stop_experiment":
|
|
604
|
+
if not self.plan.stop_experiment(command.experiment):
|
|
605
|
+
record(
|
|
606
|
+
"refused",
|
|
607
|
+
f"unknown or already stopped experiment {command.experiment!r}",
|
|
608
|
+
)
|
|
609
|
+
return False
|
|
610
|
+
logger.warning(f"{command.experiment} stopped by command")
|
|
611
|
+
record("applied")
|
|
612
|
+
elif kind == "set_pattern":
|
|
613
|
+
if command.experiment not in self.experiments:
|
|
614
|
+
record("refused", f"unknown experiment {command.experiment!r}")
|
|
615
|
+
return False
|
|
616
|
+
self.msgout["pattern"].put(
|
|
617
|
+
UpdatePatternParamsMessage(command.experiment, command.parameters)
|
|
618
|
+
)
|
|
619
|
+
record("applied", "sent to the pattern method; see the pattern rows")
|
|
620
|
+
else:
|
|
621
|
+
before = self.settings_refused
|
|
622
|
+
self.apply_settings(
|
|
623
|
+
SettingsRequestMessage(
|
|
624
|
+
command.experiment, self.current_t, command.to_changes()
|
|
625
|
+
),
|
|
626
|
+
source="command",
|
|
627
|
+
)
|
|
628
|
+
refused = self.settings_refused - before
|
|
629
|
+
if refused:
|
|
630
|
+
record("refused", f"{refused} change(s) refused; see the rows above")
|
|
631
|
+
return False
|
|
632
|
+
record("applied")
|
|
633
|
+
self.commands_applied += 1
|
|
634
|
+
return True
|
|
635
|
+
|
|
636
|
+
# -------------------------------------------------- acknowledgements
|
|
637
|
+
def handle_event_done(self, msg: EventDoneMessage):
|
|
638
|
+
rec = self.acks.setdefault(msg.t_index, {}).setdefault(
|
|
639
|
+
msg.experiment_name,
|
|
640
|
+
{"frames": 0, "errors": 0, "lateness_s": 0.0, "skipped": 0},
|
|
641
|
+
)
|
|
642
|
+
if getattr(msg, "skipped", False):
|
|
643
|
+
rec["skipped"] = rec.get("skipped", 0) + 1
|
|
644
|
+
self.skipped += 1
|
|
645
|
+
self.event_log.record(
|
|
646
|
+
"position_skipped",
|
|
647
|
+
msg.experiment_name,
|
|
648
|
+
msg.channel,
|
|
649
|
+
None,
|
|
650
|
+
None,
|
|
651
|
+
None,
|
|
652
|
+
"skipped",
|
|
653
|
+
"only the stimulation frame was due and the pattern was blank",
|
|
654
|
+
msg.t_index,
|
|
655
|
+
msg.t_index,
|
|
656
|
+
)
|
|
657
|
+
return
|
|
658
|
+
rec["frames"] += 1
|
|
659
|
+
self.current_experiment = msg.experiment_name
|
|
660
|
+
if msg.error:
|
|
661
|
+
rec["errors"] += 1
|
|
662
|
+
self.event_log.record(
|
|
663
|
+
"acquisition_error",
|
|
664
|
+
msg.experiment_name,
|
|
665
|
+
msg.channel,
|
|
666
|
+
None,
|
|
667
|
+
None,
|
|
668
|
+
None,
|
|
669
|
+
"failed",
|
|
670
|
+
msg.error,
|
|
671
|
+
msg.t_index,
|
|
672
|
+
msg.t_index,
|
|
673
|
+
)
|
|
674
|
+
return
|
|
675
|
+
late = msg.lateness_s or 0.0
|
|
676
|
+
rec["lateness_s"] = max(rec["lateness_s"], late)
|
|
677
|
+
if late > self.plan.interval_s and msg.t_index not in self._late_warned:
|
|
678
|
+
self._late_warned.add(msg.t_index)
|
|
679
|
+
logger.warning(
|
|
680
|
+
f"t = {msg.t_index}: {msg.experiment_name}/{msg.channel} completed "
|
|
681
|
+
f"{late:.1f}s late (interval {self.plan.interval_s:.1f}s)"
|
|
682
|
+
)
|
|
683
|
+
self.event_log.record(
|
|
684
|
+
"late",
|
|
685
|
+
msg.experiment_name,
|
|
686
|
+
msg.channel,
|
|
687
|
+
None,
|
|
688
|
+
None,
|
|
689
|
+
f"{late:.3f}",
|
|
690
|
+
"warning",
|
|
691
|
+
"completed more than one interval late",
|
|
692
|
+
msg.t_index,
|
|
693
|
+
msg.t_index,
|
|
694
|
+
)
|
|
695
|
+
|
|
696
|
+
def status(self, done: bool = False) -> dict:
|
|
697
|
+
"""What the run looks like now: progress, per-experiment lateness and errors, process health."""
|
|
698
|
+
experiments = {}
|
|
699
|
+
for name in self.plan.experiments:
|
|
700
|
+
seen = [(t, recs[name]) for t, recs in self.acks.items() if name in recs]
|
|
701
|
+
errors = sum(r["errors"] for _, r in seen)
|
|
702
|
+
skipped = sum(r.get("skipped", 0) for _, r in seen)
|
|
703
|
+
if seen:
|
|
704
|
+
t_last, last = max(seen, key=lambda item: item[0])
|
|
705
|
+
experiments[name] = {
|
|
706
|
+
"last_t": t_last,
|
|
707
|
+
"lateness_s": round(last["lateness_s"], 3),
|
|
708
|
+
"errors": errors,
|
|
709
|
+
"skipped": skipped,
|
|
710
|
+
}
|
|
711
|
+
else:
|
|
712
|
+
experiments[name] = {
|
|
713
|
+
"last_t": None,
|
|
714
|
+
"lateness_s": None,
|
|
715
|
+
"errors": 0,
|
|
716
|
+
"skipped": 0,
|
|
717
|
+
}
|
|
718
|
+
return {
|
|
719
|
+
"t": self.current_t,
|
|
720
|
+
"timepoints": self.plan.timepoints,
|
|
721
|
+
"done": done,
|
|
722
|
+
"current_experiment": self.current_experiment,
|
|
723
|
+
"wall_time": datetime.datetime.now().isoformat(timespec="seconds"),
|
|
724
|
+
"elapsed_s": round(time() - self.start_time, 1) if self.start_time else 0.0,
|
|
725
|
+
"settings_applied": self.settings_applied,
|
|
726
|
+
"settings_refused": self.settings_refused,
|
|
727
|
+
"paused": self.paused,
|
|
728
|
+
"paused_s": round(
|
|
729
|
+
self.paused_s + (time() - self._pause_started if self.paused else 0.0),
|
|
730
|
+
1,
|
|
731
|
+
),
|
|
732
|
+
"stopping": self.stopping,
|
|
733
|
+
"pending_commands": self.pending_commands,
|
|
734
|
+
"commands_applied": self.commands_applied,
|
|
735
|
+
"skipped": self.skipped,
|
|
736
|
+
"experiments": experiments,
|
|
737
|
+
"health": self.health() if self.health is not None else {},
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
def write_status(self, done: bool = False):
|
|
741
|
+
if self.status_path is None:
|
|
742
|
+
return
|
|
743
|
+
try:
|
|
744
|
+
tmp = self.status_path.with_suffix(".json.tmp")
|
|
745
|
+
tmp.write_text(json.dumps(self.status(done), indent=1, default=str))
|
|
746
|
+
tmp.replace(self.status_path)
|
|
747
|
+
except Exception as e:
|
|
748
|
+
logger.error(f"failed to write {self.status_path}: {e}")
|
|
749
|
+
|
|
750
|
+
def finish(self):
|
|
751
|
+
"""Absorb the last acknowledgements, write the final status, close the events table."""
|
|
752
|
+
if self.finished or not self.initialized:
|
|
753
|
+
return
|
|
754
|
+
self.finished = True
|
|
755
|
+
self.drain_inboxes()
|
|
756
|
+
self.write_status(done=True)
|
|
757
|
+
self.event_log.close()
|
|
758
|
+
|
|
759
|
+
def dispatch(self, ev: PlannedEvent, start_time: float):
|
|
760
|
+
"""Turn one planned event into the message(s) the other processes expect."""
|
|
761
|
+
name = ev.experiment
|
|
762
|
+
scheduled_time = start_time + ev.scheduled_offset_s
|
|
763
|
+
since_start = ev.scheduled_offset_s
|
|
764
|
+
|
|
765
|
+
match ev.kind:
|
|
766
|
+
case "request_pattern":
|
|
767
|
+
self.msgout["pattern"].put(
|
|
768
|
+
RequestPattern(
|
|
769
|
+
ev.t, since_start, name, self.plan.requirements.get(name, [])
|
|
770
|
+
)
|
|
771
|
+
)
|
|
772
|
+
|
|
773
|
+
case "position":
|
|
774
|
+
self.construct_position_event_message(
|
|
775
|
+
self.positions[name],
|
|
776
|
+
name,
|
|
777
|
+
index=ev.index,
|
|
778
|
+
skippable_if_blank=ev.skippable,
|
|
779
|
+
)
|
|
780
|
+
|
|
781
|
+
case "update_pattern":
|
|
782
|
+
cfg = self.plan.imaging_config(name, ev.channel)
|
|
783
|
+
upmsg = UpdatePatternEventMessage(
|
|
784
|
+
UpdatePatternEvent(
|
|
785
|
+
name,
|
|
786
|
+
cfg.get_config_groups(),
|
|
787
|
+
cfg.get_device_properties(),
|
|
788
|
+
index=ev.index,
|
|
789
|
+
skippable_if_blank=ev.skippable,
|
|
790
|
+
)
|
|
791
|
+
)
|
|
792
|
+
self.msgout["slm_buffer"].put(upmsg)
|
|
793
|
+
self.msgout["microscope"].put(upmsg)
|
|
794
|
+
|
|
795
|
+
case "acquire":
|
|
796
|
+
cfg = self.plan.imaging_config(name, ev.channel)
|
|
797
|
+
event = AcquisitionEvent(
|
|
798
|
+
name,
|
|
799
|
+
self.positions[name],
|
|
800
|
+
cfg.channel_id,
|
|
801
|
+
index=ev.index,
|
|
802
|
+
scheduled_time=scheduled_time,
|
|
803
|
+
scheduled_time_since_start=since_start,
|
|
804
|
+
exposure_time_ms=cfg.exposure,
|
|
805
|
+
needs_slm=ev.is_stim,
|
|
806
|
+
config_groups=cfg.get_config_groups(),
|
|
807
|
+
devices=cfg.get_device_properties(),
|
|
808
|
+
save_output=ev.save,
|
|
809
|
+
binning=cfg.binning,
|
|
810
|
+
)
|
|
811
|
+
event.overrides = dict(self.overrides.get((name, ev.channel), {}))
|
|
812
|
+
event.skippable_if_blank = ev.skippable
|
|
813
|
+
self.msgout["microscope"].put(AcquisitionEventMessage(event))
|
|
814
|
+
|
|
815
|
+
case _:
|
|
816
|
+
raise ValueError(f"unknown planned event kind {ev.kind!r}")
|
|
817
|
+
|
|
818
|
+
def process(self):
|
|
819
|
+
assert self.initialized, (
|
|
820
|
+
"manager must be initialized with an acquisition plan to start"
|
|
821
|
+
)
|
|
822
|
+
|
|
823
|
+
plan = self.plan
|
|
824
|
+
setup = plan.setup_s
|
|
825
|
+
self.start_time = time() + setup
|
|
826
|
+
|
|
827
|
+
# time iter loop
|
|
828
|
+
for t in range(plan.timepoints):
|
|
829
|
+
self.current_t = t
|
|
830
|
+
# operator-facing progress line (the console log handler only shows warnings)
|
|
831
|
+
print(f"t = {t}: {(time() - self.start_time) / 60: 0.1f} minutes")
|
|
832
|
+
|
|
833
|
+
# wait until the preparatory phase; settings requests, acknowledgements
|
|
834
|
+
# and command files are handled here, so they apply at this boundary
|
|
835
|
+
while True:
|
|
836
|
+
if self.stop_event and self.stop_event.is_set():
|
|
837
|
+
logger.info("force stopping manager process")
|
|
838
|
+
return
|
|
839
|
+
due = (time() - self.start_time) >= plan.time_offset_s(t) - setup
|
|
840
|
+
if due and not self.paused:
|
|
841
|
+
break
|
|
842
|
+
handled = self.drain_inboxes()
|
|
843
|
+
handled = self.poll_commands() or handled
|
|
844
|
+
if not handled:
|
|
845
|
+
sleep(self.sleep_interval)
|
|
846
|
+
|
|
847
|
+
if self.stopping:
|
|
848
|
+
logger.info(f"stopping before t = {t} (stop_run command)")
|
|
849
|
+
self.write_status()
|
|
850
|
+
break
|
|
851
|
+
|
|
852
|
+
self.write_status()
|
|
853
|
+
for ev in plan.events_at(t):
|
|
854
|
+
self.dispatch(ev, self.start_time)
|
|
855
|
+
self._last_burst_t = t
|
|
856
|
+
|
|
857
|
+
print("DONE")
|
|
858
|
+
logger.info("Manager finished the schedule; sending close to all processes")
|
|
859
|
+
|
|
860
|
+
for box in self.msgout:
|
|
861
|
+
self.msgout[box].put(CloseMessage())
|