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/controller.py
ADDED
|
@@ -0,0 +1,447 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import logging
|
|
3
|
+
import math
|
|
4
|
+
import traceback
|
|
5
|
+
from concurrent.futures import (
|
|
6
|
+
ALL_COMPLETED,
|
|
7
|
+
FIRST_COMPLETED,
|
|
8
|
+
ThreadPoolExecutor,
|
|
9
|
+
wait,
|
|
10
|
+
)
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from threading import Event
|
|
13
|
+
|
|
14
|
+
import numpy as np
|
|
15
|
+
|
|
16
|
+
from .core import (
|
|
17
|
+
ROI,
|
|
18
|
+
AllQueues,
|
|
19
|
+
CameraProperties,
|
|
20
|
+
ExperimentSchedule,
|
|
21
|
+
Manager,
|
|
22
|
+
MicroscopeProcess,
|
|
23
|
+
PatternProcess,
|
|
24
|
+
SegmentationProcess,
|
|
25
|
+
SLMBuffer,
|
|
26
|
+
WriterProcess,
|
|
27
|
+
)
|
|
28
|
+
from .core.base_process import PipelineProcess
|
|
29
|
+
from .core.experiments import ConfigGroup
|
|
30
|
+
from .core.grid import geometry_for
|
|
31
|
+
from .core.kinds import DEFAULT_SEGMENTATION, seg_name
|
|
32
|
+
from .core.plan import PLAN_FILENAME, AcquisitionPlan
|
|
33
|
+
from .core.position_mover import PositionMover
|
|
34
|
+
from .core.real_core import RealMicroscopeCore
|
|
35
|
+
from .core.router import Router
|
|
36
|
+
from .core.storage import make_writer
|
|
37
|
+
from .core.storage.events import EventLog
|
|
38
|
+
from .core.tracking_process import TrackingProcess
|
|
39
|
+
from .core.virtual_microscope.simulated_core import SimulatedMicroscopeCore
|
|
40
|
+
|
|
41
|
+
logger = logging.getLogger(__name__)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class Controller:
|
|
45
|
+
"""
|
|
46
|
+
Owns the pipeline processes and runs them as threads.
|
|
47
|
+
|
|
48
|
+
The fixed processes are the microscope (produces raw frames), the manager
|
|
49
|
+
(timing), the SLM buffer, the writer, segmentation and pattern
|
|
50
|
+
generation. Extra consumers or producers are added with
|
|
51
|
+
:meth:`add_process` before :meth:`initialize`, which builds the
|
|
52
|
+
:class:`~pyclm.core.router.Router` from every process's declared
|
|
53
|
+
requirements and starts only the processes that will receive data.
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
def __init__(
|
|
57
|
+
self,
|
|
58
|
+
config="MMConfig_demo.cfg",
|
|
59
|
+
dry=False,
|
|
60
|
+
position_mover: PositionMover | None = None,
|
|
61
|
+
dry_image_source: Path | None = None,
|
|
62
|
+
settle_time_s: float = 1.0,
|
|
63
|
+
storage_format: str = "ome-zarr",
|
|
64
|
+
pattern_policy: str = "on_change",
|
|
65
|
+
):
|
|
66
|
+
if not dry:
|
|
67
|
+
# Applies if config specifies that a real microscope is in use
|
|
68
|
+
self.core = RealMicroscopeCore()
|
|
69
|
+
else:
|
|
70
|
+
if dry_image_source is None:
|
|
71
|
+
raise ValueError("dry_image_source must be provided when dry=True.")
|
|
72
|
+
self.core = SimulatedMicroscopeCore(
|
|
73
|
+
dry_image_source,
|
|
74
|
+
pixel_size_um=getattr(dry_image_source, "pixel_size_um", 0.33),
|
|
75
|
+
slm_device="SimulatedSLM",
|
|
76
|
+
)
|
|
77
|
+
self.dry_binning = int(getattr(dry_image_source, "binning", 1))
|
|
78
|
+
self.core.loadSystemConfiguration(config)
|
|
79
|
+
self.all_queues = AllQueues()
|
|
80
|
+
|
|
81
|
+
self.stop_event = Event()
|
|
82
|
+
|
|
83
|
+
self.microscope = MicroscopeProcess(
|
|
84
|
+
core=self.core,
|
|
85
|
+
aq=self.all_queues,
|
|
86
|
+
position_mover=position_mover,
|
|
87
|
+
stop_event=self.stop_event,
|
|
88
|
+
settle_time_s=settle_time_s,
|
|
89
|
+
)
|
|
90
|
+
self.manager = Manager(aq=self.all_queues, stop_event=self.stop_event)
|
|
91
|
+
self.writer_process = WriterProcess(
|
|
92
|
+
stop_event=self.stop_event,
|
|
93
|
+
writer=make_writer(storage_format, pattern_policy),
|
|
94
|
+
)
|
|
95
|
+
# the writer was the "outbox" before Stage 3; the old name still works
|
|
96
|
+
self.outbox = self.writer_process
|
|
97
|
+
self.slm_buffer = SLMBuffer(aq=self.all_queues, stop_event=self.stop_event)
|
|
98
|
+
self.segmentation = SegmentationProcess(stop_event=self.stop_event)
|
|
99
|
+
self.tracking = TrackingProcess(stop_event=self.stop_event)
|
|
100
|
+
self.pattern = PatternProcess(aq=self.all_queues, stop_event=self.stop_event)
|
|
101
|
+
|
|
102
|
+
# processes the router manages, in registration order (raw producer first)
|
|
103
|
+
self.pipeline_processes: list = [
|
|
104
|
+
self.microscope,
|
|
105
|
+
self.writer_process,
|
|
106
|
+
self.segmentation,
|
|
107
|
+
self.tracking,
|
|
108
|
+
self.pattern,
|
|
109
|
+
]
|
|
110
|
+
self.router: Router | None = None
|
|
111
|
+
|
|
112
|
+
# everything that could run; narrowed to the active set by initialize()
|
|
113
|
+
self.processes = [
|
|
114
|
+
self.microscope,
|
|
115
|
+
self.manager,
|
|
116
|
+
self.writer_process,
|
|
117
|
+
self.slm_buffer,
|
|
118
|
+
self.segmentation,
|
|
119
|
+
self.tracking,
|
|
120
|
+
self.pattern,
|
|
121
|
+
]
|
|
122
|
+
|
|
123
|
+
self.camera_properties = None
|
|
124
|
+
self.settle_time_s = settle_time_s
|
|
125
|
+
|
|
126
|
+
self.plan: AcquisitionPlan | None = None
|
|
127
|
+
self.all_layers = None
|
|
128
|
+
self.t_gcd = 1
|
|
129
|
+
|
|
130
|
+
def register_pattern_method(self, name: str, method: type):
|
|
131
|
+
self.pattern.register_method(method, name)
|
|
132
|
+
|
|
133
|
+
def register_segmentation_method(self, name: str, method: type):
|
|
134
|
+
self.segmentation.register_method(method, name)
|
|
135
|
+
|
|
136
|
+
def register_tracking_method(self, name: str, method: type):
|
|
137
|
+
self.tracking.register_method(method, name)
|
|
138
|
+
|
|
139
|
+
def add_process(self, process: PipelineProcess):
|
|
140
|
+
"""
|
|
141
|
+
Register an extra pipeline process (a consumer, a producer, or both)
|
|
142
|
+
before :meth:`initialize`. It declares what it wants and makes; the
|
|
143
|
+
router wires it in and derives its shutdown from the same table.
|
|
144
|
+
"""
|
|
145
|
+
if self.router is not None:
|
|
146
|
+
raise RuntimeError("add_process must be called before initialize()")
|
|
147
|
+
if not isinstance(process, PipelineProcess):
|
|
148
|
+
raise TypeError(
|
|
149
|
+
f"add_process expects a PipelineProcess, got {type(process).__name__}"
|
|
150
|
+
)
|
|
151
|
+
if process.stop_event is None:
|
|
152
|
+
process.stop_event = self.stop_event
|
|
153
|
+
self.pipeline_processes.append(process)
|
|
154
|
+
|
|
155
|
+
def initialize(
|
|
156
|
+
self,
|
|
157
|
+
schedule: ExperimentSchedule,
|
|
158
|
+
slm_shape: tuple[int, int],
|
|
159
|
+
affine_transform: np.ndarray,
|
|
160
|
+
out_path: Path,
|
|
161
|
+
camera_roi=None,
|
|
162
|
+
):
|
|
163
|
+
"""
|
|
164
|
+
:param camera_roi: ``[x, y, width, height]`` in unbinned pixels to set on
|
|
165
|
+
the camera before anything is measured; None leaves the camera as it is
|
|
166
|
+
"""
|
|
167
|
+
# refuse to run before any models are loaded if outputs already exist
|
|
168
|
+
out_path = Path(out_path)
|
|
169
|
+
planned = self.writer_process.writer.planned_paths(
|
|
170
|
+
schedule.experiment_names, out_path
|
|
171
|
+
)
|
|
172
|
+
existing = [path for path in planned.values() if path.exists()]
|
|
173
|
+
if existing:
|
|
174
|
+
raise FileExistsError(
|
|
175
|
+
"output already exists; move or delete before re-running: "
|
|
176
|
+
+ ", ".join(str(path) for path in existing)
|
|
177
|
+
)
|
|
178
|
+
|
|
179
|
+
if isinstance(self.core, SimulatedMicroscopeCore):
|
|
180
|
+
self.core._slm_h, self.core._slm_w = int(slm_shape[0]), int(slm_shape[1])
|
|
181
|
+
binning = getattr(self, "dry_binning", 1)
|
|
182
|
+
if binning != 1:
|
|
183
|
+
# the TIFs are binned relative to the camera the affine was
|
|
184
|
+
# calibrated for: scale the camera -> SLM affine to match
|
|
185
|
+
affine_transform = np.array(affine_transform, dtype=np.float32)
|
|
186
|
+
affine_transform[:, :2] *= binning
|
|
187
|
+
logger.info(
|
|
188
|
+
f"dry run: affine transform scaled by the source binning {binning}"
|
|
189
|
+
)
|
|
190
|
+
|
|
191
|
+
# the presets every experiment shares (the objective among them) decide
|
|
192
|
+
# the pixel size: apply them before it is read, whatever the microscope
|
|
193
|
+
# was left at
|
|
194
|
+
shared = self._shared_config_groups(schedule)
|
|
195
|
+
if shared:
|
|
196
|
+
self.microscope.handle_config_update(shared)
|
|
197
|
+
logger.info(
|
|
198
|
+
"applied the shared config groups before reading the camera: "
|
|
199
|
+
+ ", ".join(f"{g.group}={g.config}" for g in shared)
|
|
200
|
+
)
|
|
201
|
+
self.microscope.set_binning(1)
|
|
202
|
+
if camera_roi is not None:
|
|
203
|
+
self.core.setROI(*[int(v) for v in camera_roi])
|
|
204
|
+
logger.info(f"camera ROI set to {tuple(int(v) for v in camera_roi)}")
|
|
205
|
+
|
|
206
|
+
camera_roi = ROI(*self.core.getROI())
|
|
207
|
+
camera_resolution = self.core.getPixelSizeUm()
|
|
208
|
+
if not camera_resolution:
|
|
209
|
+
logger.warning(
|
|
210
|
+
"the camera reports a pixel size of 0: no MicroManager pixel-size "
|
|
211
|
+
"preset matches the current objective and binning; distances in "
|
|
212
|
+
"pattern methods and tracking will be wrong (see pyclm check)"
|
|
213
|
+
)
|
|
214
|
+
|
|
215
|
+
self.camera_properties = CameraProperties(camera_roi, camera_resolution)
|
|
216
|
+
|
|
217
|
+
logger.info(f"camera properties: {self.camera_properties}")
|
|
218
|
+
|
|
219
|
+
# grid positions: the tiles' layout in camera pixels, shared by the
|
|
220
|
+
# pattern process (stitched pattern shape), the SLM buffer (cutting)
|
|
221
|
+
# and the writer (stitched frame shape) through the position object
|
|
222
|
+
self.grids = {}
|
|
223
|
+
for name, position in schedule.positions.items():
|
|
224
|
+
geometry = geometry_for(position, camera_roi, camera_resolution)
|
|
225
|
+
position.geometry = geometry
|
|
226
|
+
if geometry is not None:
|
|
227
|
+
self.grids[name] = geometry
|
|
228
|
+
oy, ox = geometry.overlap(1)
|
|
229
|
+
logger.info(
|
|
230
|
+
f"{name}: grid of {geometry.rows} x {geometry.columns} tiles, "
|
|
231
|
+
f"stitched frame {geometry.shape(1)} px, overlap {oy} x {ox} px"
|
|
232
|
+
)
|
|
233
|
+
self.pattern.grids = self.grids
|
|
234
|
+
|
|
235
|
+
self.pattern.initialize(self.camera_properties)
|
|
236
|
+
|
|
237
|
+
pattern_requirements = {}
|
|
238
|
+
t_seen = set()
|
|
239
|
+
for name, experiment in schedule.experiments.items():
|
|
240
|
+
pattern_requirements[name] = self.pattern.request_method(experiment)
|
|
241
|
+
|
|
242
|
+
for channel in experiment.channels.values():
|
|
243
|
+
t_seen.add(channel.every_t)
|
|
244
|
+
|
|
245
|
+
if len(t_seen) == 1:
|
|
246
|
+
self.t_gcd = t_seen.pop()
|
|
247
|
+
|
|
248
|
+
elif len(t_seen) > 1:
|
|
249
|
+
self.t_gcd = math.gcd(*t_seen)
|
|
250
|
+
|
|
251
|
+
self.pattern.initialize_models()
|
|
252
|
+
|
|
253
|
+
# the plan is the single description of what is acquired when
|
|
254
|
+
plan = AcquisitionPlan.from_schedule(schedule, pattern_requirements)
|
|
255
|
+
self.plan = plan
|
|
256
|
+
plan_path = plan.to_yaml(out_path / PLAN_FILENAME)
|
|
257
|
+
logger.info(f"wrote acquisition plan to {plan_path}: {plan}")
|
|
258
|
+
|
|
259
|
+
over = plan.over_budget(settle_s=self.settle_time_s)
|
|
260
|
+
if over:
|
|
261
|
+
worst_t, worst = max(over, key=lambda item: item[1])
|
|
262
|
+
logger.warning(
|
|
263
|
+
f"{len(over)} of {plan.timepoints} timepoints are estimated to take "
|
|
264
|
+
f"longer than the {plan.interval_s:.1f}s interval (worst: t={worst_t}, "
|
|
265
|
+
f"{worst:.1f}s with settle time {self.settle_time_s}s); acquisitions "
|
|
266
|
+
"will run late"
|
|
267
|
+
)
|
|
268
|
+
|
|
269
|
+
# who receives what: resolved once from the methods' requirements
|
|
270
|
+
router = Router(plan)
|
|
271
|
+
for process in self.pipeline_processes:
|
|
272
|
+
router.add(process)
|
|
273
|
+
router.resolve()
|
|
274
|
+
self.router = router
|
|
275
|
+
self._instantiate_producers(schedule, router)
|
|
276
|
+
logger.info(f"routing table: {json.dumps(router.as_dict())}")
|
|
277
|
+
|
|
278
|
+
self.event_log = EventLog(out_path / "events.parquet")
|
|
279
|
+
self.manager.initialize(
|
|
280
|
+
plan,
|
|
281
|
+
event_log=self.event_log,
|
|
282
|
+
status_path=out_path / "status.json",
|
|
283
|
+
health=self.health,
|
|
284
|
+
commands_dir=out_path / "commands",
|
|
285
|
+
)
|
|
286
|
+
self.pattern.positions = schedule.positions
|
|
287
|
+
self.slm_buffer.initialize(
|
|
288
|
+
slm_shape,
|
|
289
|
+
affine_transform,
|
|
290
|
+
schedule.experiment_names,
|
|
291
|
+
roi=camera_roi,
|
|
292
|
+
grids=self.grids,
|
|
293
|
+
)
|
|
294
|
+
self.microscope.declare_slm()
|
|
295
|
+
self.writer_process.base_path = out_path
|
|
296
|
+
all_layers = self.writer_process.initialize(
|
|
297
|
+
plan, self.core, affine_transform, slm_shape
|
|
298
|
+
)
|
|
299
|
+
|
|
300
|
+
self.all_layers = all_layers
|
|
301
|
+
self.processes = [self.manager, self.slm_buffer, *router.active_processes()]
|
|
302
|
+
|
|
303
|
+
@staticmethod
|
|
304
|
+
def _shared_config_groups(schedule: ExperimentSchedule) -> list[ConfigGroup]:
|
|
305
|
+
"""The (group, preset) pairs every channel of every experiment sets."""
|
|
306
|
+
shared: set[tuple[str, str]] | None = None
|
|
307
|
+
for experiment in schedule.experiments.values():
|
|
308
|
+
for cfg in (*experiment.channels.values(), experiment.stimulation):
|
|
309
|
+
pairs = {(g.group, g.config) for g in cfg.get_config_groups()}
|
|
310
|
+
shared = pairs if shared is None else shared & pairs
|
|
311
|
+
return [ConfigGroup(g, p) for g, p in sorted(shared or ())]
|
|
312
|
+
|
|
313
|
+
def _instantiate_producers(self, schedule: ExperimentSchedule, router: Router):
|
|
314
|
+
"""Construct the methods of producer stages only where their output is demanded."""
|
|
315
|
+
seg_demanded = sorted(
|
|
316
|
+
{(exp, seg_name(kind)) for exp, _ch, kind in router.demanded_kinds("seg")}
|
|
317
|
+
)
|
|
318
|
+
for name, seg in seg_demanded:
|
|
319
|
+
self.segmentation.request_method(schedule.experiments[name], seg)
|
|
320
|
+
seg_demanded = set(seg_demanded)
|
|
321
|
+
|
|
322
|
+
tracked = sorted(router.demanded("tracks"))
|
|
323
|
+
for name, channel in tracked:
|
|
324
|
+
self.tracking.request_method(schedule.experiments[name], channel)
|
|
325
|
+
tracked_experiments = {name for name, _ in tracked}
|
|
326
|
+
|
|
327
|
+
for name, experiment in schedule.experiments.items():
|
|
328
|
+
for seg, cfg in experiment.segmentations.items():
|
|
329
|
+
if cfg.method_name == "none" or (name, seg) in seg_demanded:
|
|
330
|
+
continue
|
|
331
|
+
table = (
|
|
332
|
+
"[segmentation]"
|
|
333
|
+
if seg == DEFAULT_SEGMENTATION
|
|
334
|
+
else f"[segmentation.{seg}]"
|
|
335
|
+
)
|
|
336
|
+
which = "" if seg == DEFAULT_SEGMENTATION else f" {seg!r}"
|
|
337
|
+
logger.warning(
|
|
338
|
+
f"experiment {name}: {table} method '{cfg.method_name}' is "
|
|
339
|
+
f"configured but the pattern method "
|
|
340
|
+
f"'{experiment.pattern.method_name}' does not request "
|
|
341
|
+
f"segmentation{which}, so it will not run"
|
|
342
|
+
)
|
|
343
|
+
method = experiment.tracking.method_name
|
|
344
|
+
if name not in tracked_experiments and method != "none":
|
|
345
|
+
logger.warning(
|
|
346
|
+
f"experiment {name}: tracking method '{method}' is configured "
|
|
347
|
+
f"but the pattern method '{experiment.pattern.method_name}' "
|
|
348
|
+
"does not request tracks, so no tracking will run"
|
|
349
|
+
)
|
|
350
|
+
|
|
351
|
+
def health(self) -> dict:
|
|
352
|
+
"""Process error counters, undeliverable frames and dropped frames, for status.json."""
|
|
353
|
+
errors = {
|
|
354
|
+
p.name: p.error_count
|
|
355
|
+
for p in self.processes
|
|
356
|
+
if hasattr(p, "error_count") and hasattr(p, "name")
|
|
357
|
+
}
|
|
358
|
+
return {
|
|
359
|
+
"errors": errors,
|
|
360
|
+
"undeliverable": self.router.undeliverable if self.router else 0,
|
|
361
|
+
"dropped_frames": self.writer_process.dropped_frames,
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
def run(self):
|
|
365
|
+
with ThreadPoolExecutor() as executor:
|
|
366
|
+
# Map processes to futures
|
|
367
|
+
future_to_process = {
|
|
368
|
+
executor.submit(process.process): process for process in self.processes
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
# manager should be first to finish in a successful run
|
|
372
|
+
manager_future = None
|
|
373
|
+
for f, p in future_to_process.items():
|
|
374
|
+
if p == self.manager:
|
|
375
|
+
manager_future = f
|
|
376
|
+
break
|
|
377
|
+
|
|
378
|
+
try:
|
|
379
|
+
# main process loop, checks for process exits
|
|
380
|
+
while True:
|
|
381
|
+
# check if any process has exited (e.g., manager finishes, or crash)
|
|
382
|
+
done, _not_done = wait(
|
|
383
|
+
future_to_process.keys(),
|
|
384
|
+
return_when=FIRST_COMPLETED,
|
|
385
|
+
timeout=0.5,
|
|
386
|
+
)
|
|
387
|
+
|
|
388
|
+
"""
|
|
389
|
+
Case 1: Manager first to finish
|
|
390
|
+
"""
|
|
391
|
+
if manager_future in done:
|
|
392
|
+
exc = manager_future.exception()
|
|
393
|
+
if exc:
|
|
394
|
+
raise exc
|
|
395
|
+
|
|
396
|
+
logger.info(
|
|
397
|
+
"Manager finished successfully. Initiating graceful shutdown."
|
|
398
|
+
)
|
|
399
|
+
break
|
|
400
|
+
|
|
401
|
+
"""
|
|
402
|
+
Case 2: Something else finished first
|
|
403
|
+
"""
|
|
404
|
+
for f in done:
|
|
405
|
+
exc = f.exception()
|
|
406
|
+
if exc:
|
|
407
|
+
logger.error(
|
|
408
|
+
f"Process {future_to_process[f]} crashed with exception: {exc}"
|
|
409
|
+
)
|
|
410
|
+
raise exc
|
|
411
|
+
|
|
412
|
+
logger.warning(
|
|
413
|
+
f"Process {future_to_process[f]} exited unexpectedly (no exception)."
|
|
414
|
+
)
|
|
415
|
+
|
|
416
|
+
except KeyboardInterrupt:
|
|
417
|
+
logger.warning(
|
|
418
|
+
"KeyboardInterrupt caught in controller. Stopping all processes."
|
|
419
|
+
)
|
|
420
|
+
self.stop_event.set()
|
|
421
|
+
|
|
422
|
+
except Exception as e:
|
|
423
|
+
logger.error(f"Exception during run: {e}")
|
|
424
|
+
logger.error(traceback.format_exc())
|
|
425
|
+
self.stop_event.set()
|
|
426
|
+
|
|
427
|
+
finally:
|
|
428
|
+
logger.info("Waiting for all processes to exit...")
|
|
429
|
+
|
|
430
|
+
try:
|
|
431
|
+
wait(future_to_process.keys(), return_when=ALL_COMPLETED)
|
|
432
|
+
|
|
433
|
+
except KeyboardInterrupt:
|
|
434
|
+
logger.warning(
|
|
435
|
+
"Overriding stop_event handling, cancelling futures."
|
|
436
|
+
)
|
|
437
|
+
for f in future_to_process:
|
|
438
|
+
f.cancel()
|
|
439
|
+
|
|
440
|
+
# the writer closes its own outputs when its loop exits; this covers
|
|
441
|
+
# the case where the writer thread never ran
|
|
442
|
+
# the last acknowledgements, the final status and the events table
|
|
443
|
+
self.manager.finish()
|
|
444
|
+
self.writer_process.close_files()
|
|
445
|
+
self.all_queues.close()
|
|
446
|
+
|
|
447
|
+
logger.info("Controller run finished.")
|