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.
Files changed (74) hide show
  1. closed_loop_microscopy-1.1.0.dist-info/METADATA +118 -0
  2. closed_loop_microscopy-1.1.0.dist-info/RECORD +74 -0
  3. closed_loop_microscopy-1.1.0.dist-info/WHEEL +4 -0
  4. closed_loop_microscopy-1.1.0.dist-info/entry_points.txt +5 -0
  5. closed_loop_microscopy-1.1.0.dist-info/licenses/LICENSE.md +7 -0
  6. pyclm/__init__.py +26 -0
  7. pyclm/__main__.py +8 -0
  8. pyclm/check.py +931 -0
  9. pyclm/cli.py +256 -0
  10. pyclm/commands.py +183 -0
  11. pyclm/controller.py +447 -0
  12. pyclm/convert_hdf5s.py +273 -0
  13. pyclm/core/__init__.py +20 -0
  14. pyclm/core/base_process.py +166 -0
  15. pyclm/core/core_interface.py +47 -0
  16. pyclm/core/datatypes.py +142 -0
  17. pyclm/core/events.py +194 -0
  18. pyclm/core/experiments.py +403 -0
  19. pyclm/core/grid.py +272 -0
  20. pyclm/core/kinds.py +42 -0
  21. pyclm/core/manager.py +861 -0
  22. pyclm/core/measure.py +266 -0
  23. pyclm/core/messages.py +124 -0
  24. pyclm/core/microscope.py +504 -0
  25. pyclm/core/pattern_process.py +282 -0
  26. pyclm/core/patterns/__init__.py +60 -0
  27. pyclm/core/patterns/bar_patterns.py +259 -0
  28. pyclm/core/patterns/cell_intensity_patterns.py +181 -0
  29. pyclm/core/patterns/composite.py +220 -0
  30. pyclm/core/patterns/embryo_patterns.py +90 -0
  31. pyclm/core/patterns/fbc_cell_movement.py +295 -0
  32. pyclm/core/patterns/pattern.py +610 -0
  33. pyclm/core/patterns/pulse_patterns.py +261 -0
  34. pyclm/core/patterns/static_patterns.py +58 -0
  35. pyclm/core/patterns/wave_patterns.py +95 -0
  36. pyclm/core/patterns/zoo.py +231 -0
  37. pyclm/core/plan.py +623 -0
  38. pyclm/core/position_mover.py +185 -0
  39. pyclm/core/queues.py +41 -0
  40. pyclm/core/real_core.py +158 -0
  41. pyclm/core/router.py +422 -0
  42. pyclm/core/segmentation/__init__.py +2 -0
  43. pyclm/core/segmentation/cellpose_segmentation.py +113 -0
  44. pyclm/core/segmentation/segmentation.py +48 -0
  45. pyclm/core/segmentation_process.py +179 -0
  46. pyclm/core/settings.py +120 -0
  47. pyclm/core/storage/__init__.py +37 -0
  48. pyclm/core/storage/base.py +234 -0
  49. pyclm/core/storage/events.py +130 -0
  50. pyclm/core/storage/hdf5_v1.py +337 -0
  51. pyclm/core/storage/ome_zarr.py +861 -0
  52. pyclm/core/tracking/__init__.py +28 -0
  53. pyclm/core/tracking/centroid.py +75 -0
  54. pyclm/core/tracking/tracking.py +124 -0
  55. pyclm/core/tracking_process.py +106 -0
  56. pyclm/core/virtual_microscope/__init__.py +0 -0
  57. pyclm/core/virtual_microscope/simulated_core.py +262 -0
  58. pyclm/core/virtual_microscope/simulated_source.py +206 -0
  59. pyclm/core/writer_process.py +130 -0
  60. pyclm/demo.py +225 -0
  61. pyclm/directories.py +563 -0
  62. pyclm/gui/__init__.py +28 -0
  63. pyclm/gui/debug_viewer.py +41 -0
  64. pyclm/gui/gui_controller.py +551 -0
  65. pyclm/gui/widgets.py +292 -0
  66. pyclm/io/__init__.py +29 -0
  67. pyclm/io/export.py +202 -0
  68. pyclm/io/readers.py +589 -0
  69. pyclm/methods.py +249 -0
  70. pyclm/mmconfig.py +143 -0
  71. pyclm/preview.py +414 -0
  72. pyclm/run_pyclm.py +298 -0
  73. pyclm/schema.py +806 -0
  74. pyclm/templates.py +165 -0
pyclm/check.py ADDED
@@ -0,0 +1,931 @@
1
+ """
2
+ ``pyclm check``: read an experiment directory and report what is wrong
3
+ with it before the microscope is touched.
4
+
5
+ Every finding names a file and, where it applies, a table or key, and is
6
+ an error (the run cannot start), a warning (it can, but something looks
7
+ unintended) or an info line (a fact worth knowing: frames per experiment,
8
+ what was not checked). ``pyclm run`` runs the same check first.
9
+
10
+ See docs/stage5-schema-setup-design.md §4.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import difflib
16
+ import inspect
17
+ import logging
18
+ import shutil
19
+ import tempfile
20
+ from dataclasses import dataclass, field
21
+ from pathlib import Path
22
+
23
+ from .core.patterns import known_models
24
+ from .core.plan import AcquisitionPlan
25
+ from .core.segmentation_process import SegmentationProcess
26
+ from .core.tracking import known_tracking_methods
27
+ from .mmconfig import MMConfig
28
+ from .schema import (
29
+ ConfigError,
30
+ ExperimentConfig,
31
+ PyclmConfig,
32
+ ScheduleConfig,
33
+ )
34
+
35
+ logger = logging.getLogger(__name__)
36
+
37
+ CONFIG_NAME = "pyclm_config.toml"
38
+ SCHEDULE_NAME = "schedule.toml"
39
+ OUTPUT_SUFFIXES = (".zarr", ".hdf5")
40
+
41
+
42
+ class CheckFailed(RuntimeError):
43
+ """``pyclm run`` stopped because the check found errors (see ``report``)."""
44
+
45
+ def __init__(self, report: CheckReport):
46
+ self.report = report
47
+ super().__init__(
48
+ f"{report.summary()} in {report.directory}; fix them or run with --force"
49
+ )
50
+
51
+
52
+ @dataclass
53
+ class Finding:
54
+ level: str # "error" | "warning" | "info"
55
+ file: str
56
+ where: str
57
+ message: str
58
+
59
+ def __str__(self) -> str:
60
+ where = f" {self.where}" if self.where else ""
61
+ return f"{self.level.upper():8}{self.file}{where}: {self.message}"
62
+
63
+
64
+ @dataclass
65
+ class CheckReport:
66
+ directory: Path
67
+ findings: list[Finding] = field(default_factory=list)
68
+
69
+ def add(self, level: str, file: str, where: str, message: str) -> Finding:
70
+ f = Finding(level, file, where, message)
71
+ self.findings.append(f)
72
+ return f
73
+
74
+ def error(self, file, where, message):
75
+ return self.add("error", file, where, message)
76
+
77
+ def warning(self, file, where, message):
78
+ return self.add("warning", file, where, message)
79
+
80
+ def info(self, file, where, message):
81
+ return self.add("info", file, where, message)
82
+
83
+ @property
84
+ def errors(self) -> list[Finding]:
85
+ return [f for f in self.findings if f.level == "error"]
86
+
87
+ @property
88
+ def warnings(self) -> list[Finding]:
89
+ return [f for f in self.findings if f.level == "warning"]
90
+
91
+ @property
92
+ def ok(self) -> bool:
93
+ return not self.errors
94
+
95
+ def summary(self) -> str:
96
+ n_err, n_warn = len(self.errors), len(self.warnings)
97
+ if not n_err and not n_warn:
98
+ return "no problems found"
99
+ parts = []
100
+ if n_err:
101
+ parts.append(f"{n_err} error{'s' if n_err != 1 else ''}")
102
+ if n_warn:
103
+ parts.append(f"{n_warn} warning{'s' if n_warn != 1 else ''}")
104
+ return ", ".join(parts)
105
+
106
+ def text(self) -> str:
107
+ lines = [f"pyclm check {self.directory}"]
108
+ lines += [f" {f}" for f in self.findings]
109
+ lines.append(f" {self.summary()}")
110
+ return "\n".join(lines)
111
+
112
+
113
+ # --------------------------------------------------------------- helpers
114
+ def _check_grids(report, list_name, positions, config, directory, pixel_size_um):
115
+ """Describe each grid; compare its pitch with the camera ROI when the pixel size is known."""
116
+ from .directories import dry_settings_from_directory
117
+
118
+ grids = [p for p in positions if getattr(p, "tiles", None)]
119
+ if not grids:
120
+ return
121
+ if pixel_size_um is None:
122
+ try:
123
+ dry = dry_settings_from_directory(directory)
124
+ if (directory / "dry_run.yml").exists():
125
+ pixel_size_um = dry.pixel_size_um * dry.binning
126
+ except Exception:
127
+ pixel_size_um = None
128
+ if config is not None and config.output.format == "hdf5":
129
+ report.error(
130
+ CONFIG_NAME,
131
+ "[output] format",
132
+ f"grid positions ({', '.join(g.label for g in grids)}) need "
133
+ 'format = "ome-zarr"',
134
+ )
135
+ for g in grids:
136
+ info = g.grid
137
+ col_um, row_um = info["pitch_um"]
138
+ line = (
139
+ f"grid of {info['rows']} x {info['columns']} tiles, spacing "
140
+ f"{col_um:.1f} x {row_um:.1f} um"
141
+ )
142
+ roi = None if config is None else config.camera_roi
143
+ if roi is not None and pixel_size_um:
144
+ w_um, h_um = roi[2] * pixel_size_um, roi[3] * pixel_size_um
145
+ ox, oy = w_um - col_um, h_um - row_um
146
+ line += (
147
+ f"; with camera_roi {roi[2]} x {roi[3]} px at {pixel_size_um:g} um/px "
148
+ f"the tiles overlap {ox:.1f} x {oy:.1f} um"
149
+ )
150
+ if ox < -0.5 or oy < -0.5:
151
+ report.warning(
152
+ list_name,
153
+ g.label,
154
+ "the tiles are spaced wider than the camera ROI: the stitched "
155
+ "frame will have gaps (was the grid created with this ROI?)",
156
+ )
157
+ elif (ox > 0.5 or oy > 0.5) and any(
158
+ cfg.stimulation.exposure > 0
159
+ for stem, cfg in _configs_for(directory, g.label).items()
160
+ ):
161
+ report.warning(
162
+ list_name,
163
+ g.label,
164
+ "the tiles overlap and this experiment stimulates: the overlap "
165
+ "strips are lit from two tiles (overlap 0 is recommended)",
166
+ )
167
+ elif roi is None:
168
+ line += "; set camera_roi to check the spacing against the camera"
169
+ else:
170
+ line += "; give --pixel-size-um to check the spacing against the camera"
171
+ report.info(list_name, g.label, line)
172
+
173
+
174
+ def _configs_for(directory: Path, label: str) -> dict:
175
+ from .schema import ExperimentConfig
176
+
177
+ stem = label.split(".")[0]
178
+ path = directory / f"{stem}.toml"
179
+ try:
180
+ return {stem: ExperimentConfig.from_file(path)}
181
+ except Exception:
182
+ return {}
183
+
184
+
185
+ def _check_shared_config_groups(report: CheckReport, configs: dict) -> None:
186
+ """
187
+ The run reads the camera's pixel size once, at start, with the presets
188
+ every experiment shares applied (the objective lives there), and the
189
+ affine and camera ROI are calibrated for one objective: experiments that
190
+ disagree on a global config group get a warning.
191
+ """
192
+ if len(configs) < 2:
193
+ return
194
+ by_group: dict[str, dict[str, set[str]]] = {}
195
+ for stem, cfg in configs.items():
196
+ for group, preset in cfg.config_groups.items():
197
+ by_group.setdefault(group, {}).setdefault(preset, set()).add(stem)
198
+ for group, presets in sorted(by_group.items()):
199
+ if len(presets) > 1:
200
+ detail = "; ".join(
201
+ f"{preset}: {', '.join(sorted(stems))}"
202
+ for preset, stems in presets.items()
203
+ )
204
+ report.warning(
205
+ "experiments",
206
+ f"[config_groups] {group}",
207
+ f"differs between experiments ({detail}); the pixel size is read "
208
+ "once at start under the shared presets and the affine and "
209
+ "camera_roi are calibrated for one objective",
210
+ )
211
+
212
+
213
+ def _check_pixel_size(report: CheckReport, file: str, cfg, mm: MMConfig) -> None:
214
+ """Which MicroManager pixel-size preset the experiment's [config_groups] select."""
215
+ if not mm.pixel_sizes:
216
+ report.info(
217
+ file,
218
+ "[config_groups]",
219
+ "the MicroManager configuration defines no pixel-size presets; "
220
+ "the run will report a pixel size of 0 (Devices > Pixel Size Calibration)",
221
+ )
222
+ return
223
+ presets = sorted(cfg.config_groups.items())
224
+ candidates = mm.pixel_size_candidates(presets)
225
+ if not candidates:
226
+ return
227
+ best = candidates[0]
228
+ size = (
229
+ f"pixel size {best['um']:g} um (preset '{best['name']}')"
230
+ if best["um"]
231
+ else f"pixel-size preset '{best['name']}'"
232
+ )
233
+ if not best["unmet"] and not best["unknown"]:
234
+ report.info(file, "[config_groups]", size)
235
+ return
236
+ if not best["unmet"]:
237
+ # the preset is conditioned on properties no config group sets;
238
+ # MicroManager compares them with the device's current value
239
+ conds = ", ".join(f"{d}-{p} = {v!r}" for d, p, v in best["unknown"])
240
+ report.info(
241
+ file,
242
+ "[config_groups]",
243
+ f"{size} applies if {conds} (no config group sets it; MicroManager "
244
+ "uses the device's current value)",
245
+ )
246
+ return
247
+ unmet = ", ".join(
248
+ f"{d}-{p} is {have!r}, preset wants {v!r}" for d, p, v, have in best["unmet"]
249
+ )
250
+ report.warning(
251
+ file,
252
+ "[config_groups]",
253
+ f"no pixel-size preset matches {dict(presets)}: closest is '{best['name']}' "
254
+ f"but {unmet}; the run would report a pixel size of 0 "
255
+ f"(presets: {', '.join(sorted(mm.pixel_sizes))})",
256
+ )
257
+
258
+
259
+ def _check_position_mover(report: CheckReport, file: str, config: PyclmConfig) -> None:
260
+ from .core.position_mover import resolve_mover
261
+
262
+ try:
263
+ cls = resolve_mover(config.position_mover)
264
+ except ValueError as e:
265
+ report.error(file, "position_mover", str(e))
266
+ return
267
+ note = ""
268
+ if cls.__name__ == "BasicPositionMover":
269
+ note = ' (XY then Z, no focus maintenance; a Nikon with PFS wants "pfs")'
270
+ report.info(file, "position_mover", f"{cls.__name__}{note}")
271
+
272
+
273
+ def _check_camera_roi(report: CheckReport, file: str, config: PyclmConfig) -> None:
274
+ """Report the DMD's footprint on the camera and how the configured ROI relates to it."""
275
+ fx, fy, fw, fh = config.dmd_footprint()
276
+ footprint = f"x {fx}..{fx + fw}, y {fy}..{fy + fh} ({fw} x {fh} unbinned pixels)"
277
+ roi = config.camera_roi
278
+ if roi is None:
279
+ report.info(
280
+ file,
281
+ "camera_roi",
282
+ f"not set: the camera keeps its current ROI; the DMD covers {footprint}, "
283
+ f"so camera_roi = [{max(fx, 0)}, {max(fy, 0)}, {fw}, {fh}] would image "
284
+ "exactly the region it can light",
285
+ )
286
+ return
287
+ x, y, w, h = roi
288
+ report.info(
289
+ file, "camera_roi", f"{list(roi)} will be set; the DMD covers {footprint}"
290
+ )
291
+ if x < fx or y < fy or x + w > fx + fw or y + h > fy + fh:
292
+ report.warning(
293
+ file,
294
+ "camera_roi",
295
+ "extends beyond the region the DMD can light: part of every frame "
296
+ "can never be stimulated (a grid stimulated with overlap 0 will have "
297
+ "dark strips)",
298
+ )
299
+
300
+
301
+ def find_pyclm_config(directory: Path, config_path=None) -> Path | None:
302
+ """
303
+ The configuration: the given path, else the directory's
304
+ ``pyclm_config[.<anything>].toml``, else the working directory's.
305
+ Raises :class:`~pyclm.directories.AmbiguousFileError` when a directory
306
+ holds more than one.
307
+ """
308
+ from .directories import find_config_in
309
+
310
+ if config_path is not None:
311
+ return Path(config_path)
312
+ for folder in (Path(directory), Path.cwd()):
313
+ found = find_config_in(folder)
314
+ if found is not None:
315
+ return found
316
+ return None
317
+
318
+
319
+ def method_registries(
320
+ pattern_methods=None, segmentation_methods=None, tracking_methods=None
321
+ ):
322
+ patterns = dict(known_models)
323
+ patterns.update(pattern_methods or {})
324
+ segmentations = dict(SegmentationProcess.default_models)
325
+ segmentations.update(segmentation_methods or {})
326
+ trackers = dict(known_tracking_methods)
327
+ trackers.update(tracking_methods or {})
328
+ return patterns, segmentations, trackers
329
+
330
+
331
+ CUSTOM_HINT = (
332
+ "; a method of your own is listed by its file under methods in pyclm_config.toml"
333
+ )
334
+
335
+ # constructor parameters PyCLM supplies itself, per kind of method
336
+ SUPPLIED = {
337
+ "pattern": {"self", "experiment_name", "camera_properties"},
338
+ "segmentation": {"self", "experiment_name"},
339
+ "tracking": {"self", "experiment_name", "channel"},
340
+ }
341
+
342
+
343
+ def _named_parameters(cls: type, supplied: set) -> tuple[dict, bool]:
344
+ """``cls.__init__``'s named parameters (minus the ones PyCLM supplies) and whether it takes **kwargs."""
345
+ try:
346
+ sig = inspect.signature(cls.__init__)
347
+ except (TypeError, ValueError):
348
+ return {}, True
349
+ named = {}
350
+ var_kw = False
351
+ for name, param in sig.parameters.items():
352
+ if name in supplied:
353
+ continue
354
+ if param.kind is inspect.Parameter.VAR_KEYWORD:
355
+ var_kw = True
356
+ elif param.kind in (
357
+ inspect.Parameter.POSITIONAL_OR_KEYWORD,
358
+ inspect.Parameter.KEYWORD_ONLY,
359
+ ):
360
+ named[name] = param
361
+ return named, var_kw
362
+
363
+
364
+ def _all_subclasses(cls: type) -> list[type]:
365
+ out = []
366
+ for sub in cls.__subclasses__():
367
+ out.append(sub)
368
+ out += _all_subclasses(sub)
369
+ return out
370
+
371
+
372
+ def check_kwargs(
373
+ cls: type, kwargs: dict, kind: str = "pattern", method_name: str | None = None
374
+ ) -> list[str]:
375
+ """
376
+ Problems with ``kwargs`` against ``cls.__init__``: unknown names (with a
377
+ did-you-mean) and missing required ones. ``kind`` says which parameters
378
+ PyCLM supplies itself; ``method_name`` is the TOML name for messages.
379
+ """
380
+ supplied = SUPPLIED.get(kind, SUPPLIED["pattern"])
381
+ label = method_name or getattr(cls, "name", cls.__name__)
382
+ named, var_kw = _named_parameters(cls, supplied)
383
+ dispatching = False
384
+ if not named and "__new__" in vars(cls):
385
+ # a base that picks a subclass in __new__ (bar, wave): accept what any subclass accepts
386
+ dispatching = True
387
+ for sub in _all_subclasses(cls):
388
+ sub_named, _ = _named_parameters(sub, supplied)
389
+ named.update(sub_named)
390
+ problems = []
391
+ for key in kwargs:
392
+ if key in named:
393
+ continue
394
+ hint = ""
395
+ close = difflib.get_close_matches(key, list(named), n=1)
396
+ if close:
397
+ hint = f" (did you mean {close[0]!r}?)"
398
+ accepted = ", ".join(sorted(named)) or "none"
399
+ problems.append(
400
+ f"unknown argument {key!r} for method '{label}'{hint}; accepted: {accepted}"
401
+ + (
402
+ ""
403
+ if not var_kw
404
+ else " (extra keys are silently ignored by this method)"
405
+ )
406
+ )
407
+ if not dispatching:
408
+ for name, param in named.items():
409
+ if param.default is inspect.Parameter.empty and name not in kwargs:
410
+ problems.append(f"method '{label}' requires the argument {name!r}")
411
+ return problems
412
+
413
+
414
+ def _load_positions(directory: Path):
415
+ from .directories import positions_from_pos, positions_from_xml
416
+
417
+ pos_path = directory / "PositionList.pos"
418
+ xml_path = directory / "multipoints.xml"
419
+ if pos_path.exists():
420
+ return pos_path.name, positions_from_pos(str(pos_path))
421
+ if xml_path.exists():
422
+ return xml_path.name, positions_from_xml(str(xml_path))
423
+ return None, None
424
+
425
+
426
+ # ------------------------------------------------------------------ check
427
+ def check_directory(
428
+ directory,
429
+ config_path=None,
430
+ mm_config=None,
431
+ pattern_methods=None,
432
+ segmentation_methods=None,
433
+ tracking_methods=None,
434
+ dry: bool = False,
435
+ pixel_size_um: float | None = None,
436
+ ) -> CheckReport:
437
+ """
438
+ Check an experiment directory; see the module docstring for what is covered.
439
+ ``pixel_size_um`` (unbinned) lets a grid's tile spacing be compared with
440
+ the camera ROI; without it the directory's ``dry_run.yml`` value is used
441
+ when there is one.
442
+ """
443
+ directory = Path(directory)
444
+ report = CheckReport(directory)
445
+ if not directory.is_dir():
446
+ report.error(str(directory), "", "is not a directory")
447
+ return report
448
+
449
+ from .directories import AmbiguousFileError, experiment_tomls, find_schedule
450
+
451
+ # 1. pyclm_config.toml
452
+ config = None
453
+ try:
454
+ cfg_path = find_pyclm_config(directory, config_path)
455
+ except AmbiguousFileError as e:
456
+ cfg_path = None
457
+ report.error(CONFIG_NAME, "", str(e))
458
+ if cfg_path is None:
459
+ if not report.errors:
460
+ report.error(
461
+ CONFIG_NAME, "", "not found in the directory or the working directory"
462
+ )
463
+ else:
464
+ try:
465
+ config = PyclmConfig.from_file(cfg_path)
466
+ report.info(cfg_path.name, "", f"ok ({cfg_path})")
467
+ _check_camera_roi(report, cfg_path.name, config)
468
+ _check_position_mover(report, cfg_path.name, config)
469
+ except ConfigError as e:
470
+ for problem in e.problems:
471
+ report.error(cfg_path.name, "", problem)
472
+
473
+ # 1b. custom methods: entry points and the configuration's `methods`
474
+ from .methods import MethodLoadError, MethodSet, discover
475
+
476
+ try:
477
+ found, ep_warnings = discover(config, cfg_path)
478
+ except MethodLoadError as e:
479
+ found, ep_warnings = MethodSet(), []
480
+ report.error(cfg_path.name if cfg_path else CONFIG_NAME, "methods", str(e))
481
+ for warning in ep_warnings:
482
+ report.warning("methods", "", warning)
483
+ for line in found.summary():
484
+ report.info("methods", "", line)
485
+ patterns, segmentations, trackers = method_registries(
486
+ *found.merged_with(pattern_methods, segmentation_methods, tracking_methods)
487
+ )
488
+
489
+ # 2. schedule.toml
490
+ schedule = None
491
+ schedule_name = SCHEDULE_NAME
492
+ try:
493
+ schedule_path = find_schedule(directory)
494
+ if schedule_path is None:
495
+ schedule_path = directory / SCHEDULE_NAME
496
+ schedule_name = schedule_path.name
497
+ schedule = ScheduleConfig.from_file(schedule_path)
498
+ t = schedule.timing
499
+ report.info(
500
+ schedule_name,
501
+ "",
502
+ f"{t.steps} timepoints every {t.interval_seconds:g} s "
503
+ f"({t.steps * t.interval_seconds / 60:.1f} min)",
504
+ )
505
+ except AmbiguousFileError as e:
506
+ report.error(SCHEDULE_NAME, "", str(e))
507
+ except ConfigError as e:
508
+ for problem in e.problems:
509
+ report.error(schedule_name, "", problem)
510
+
511
+ # 3. experiment TOMLs
512
+ configs: dict[str, ExperimentConfig] = {}
513
+ toml_paths = list(experiment_tomls(directory).values())
514
+ if not toml_paths:
515
+ report.error(str(directory.name), "", "no experiment TOML files found")
516
+ for path in toml_paths:
517
+ try:
518
+ configs[path.stem] = ExperimentConfig.from_file(path)
519
+ except ConfigError as e:
520
+ for problem in e.problems:
521
+ report.error(path.name, "", problem)
522
+
523
+ # 4. positions
524
+ labels: dict[str, str] = {} # label -> stem
525
+ positions = None
526
+ try:
527
+ list_name, positions = _load_positions(directory)
528
+ except Exception as e:
529
+ list_name, positions = None, None
530
+ report.error("position list", "", f"could not be read: {e}")
531
+ if positions is not None:
532
+ seen = set()
533
+ for pos in positions:
534
+ label = pos.label
535
+ if label in seen:
536
+ report.error(list_name, label, "duplicate position label")
537
+ seen.add(label)
538
+ stem = label.split(".")[0]
539
+ if stem in configs:
540
+ labels[label] = stem
541
+ elif stem in {p.stem for p in toml_paths}:
542
+ labels[label] = stem # its TOML failed validation; reported above
543
+ else:
544
+ report.error(
545
+ list_name,
546
+ label,
547
+ f"no experiment file '{stem}.toml' for this position "
548
+ f"(files: {', '.join(p.stem for p in toml_paths) or 'none'})",
549
+ )
550
+ _check_grids(report, list_name, positions, config, directory, pixel_size_um)
551
+ used = {stem for stem in labels.values()}
552
+ for path in toml_paths:
553
+ if path.stem not in used:
554
+ report.warning(path.name, "", "not used by any position")
555
+ report.info(
556
+ list_name, "", f"{len(labels)} position(s): {', '.join(labels) or 'none'}"
557
+ )
558
+ else:
559
+ from .directories import dry_run_tifs
560
+
561
+ dry_sources = dry_run_tifs(directory) + list(directory.glob("dry_run.yml"))
562
+ if dry_sources:
563
+ report.info(
564
+ "positions",
565
+ "",
566
+ "no PositionList.pos or multipoints.xml; a dry run will use the TIF files",
567
+ )
568
+ else:
569
+ report.error(
570
+ "positions",
571
+ "",
572
+ "no PositionList.pos or multipoints.xml in the directory",
573
+ )
574
+
575
+ # 5 + 6. methods and requirements, per TOML
576
+ requirements_by_stem: dict[str, list] = {}
577
+ methods_by_stem: dict[str, object] = {}
578
+ for stem, cfg in configs.items():
579
+ file = f"{stem}.toml"
580
+ if not cfg.channels.presets:
581
+ report.info(
582
+ file,
583
+ "[channels]",
584
+ "no imaging channels: the experiment only stimulates "
585
+ "(the DMD frame is the only image, if [stimulation] save = true)",
586
+ )
587
+ pattern_cls = patterns.get(cfg.pattern.method)
588
+ if pattern_cls is None:
589
+ report.error(
590
+ file,
591
+ "[pattern]",
592
+ f"unknown pattern method '{cfg.pattern.method}' "
593
+ f"(known: {', '.join(sorted(patterns))}){CUSTOM_HINT}",
594
+ )
595
+ else:
596
+ for problem in check_kwargs(
597
+ pattern_cls, cfg.pattern.kwargs, "pattern", cfg.pattern.method
598
+ ):
599
+ report.error(file, "[pattern]", problem)
600
+ # a method built from other methods (split): check each of them
601
+ for label, sub_name, sub_kwargs in pattern_cls.nested_methods(
602
+ cfg.pattern.kwargs
603
+ ):
604
+ sub_cls = patterns.get(sub_name)
605
+ if sub_cls is None:
606
+ report.error(
607
+ file,
608
+ f"[pattern.{label}]",
609
+ f"unknown pattern method '{sub_name}' "
610
+ f"(known: {', '.join(sorted(patterns))}){CUSTOM_HINT}",
611
+ )
612
+ continue
613
+ for problem in check_kwargs(sub_cls, sub_kwargs, "pattern", sub_name):
614
+ report.error(file, f"[pattern.{label}]", problem)
615
+
616
+ for name, table in (
617
+ [("segmentation", cfg.segmentation)] if cfg.segmentation else []
618
+ ) + [(f"segmentation.{n}", t) for n, t in cfg.segmentations.items()]:
619
+ seg_cls = segmentations.get(table.method)
620
+ if table.method == "none":
621
+ continue
622
+ if seg_cls is None:
623
+ report.error(
624
+ file,
625
+ f"[{name}]",
626
+ f"unknown segmentation method '{table.method}' "
627
+ f"(known: {', '.join(sorted(segmentations))}){CUSTOM_HINT}",
628
+ )
629
+ else:
630
+ for problem in check_kwargs(
631
+ seg_cls, table.kwargs, "segmentation", table.method
632
+ ):
633
+ report.error(file, f"[{name}]", problem)
634
+
635
+ if cfg.tracking is not None:
636
+ tr_cls = trackers.get(cfg.tracking.method)
637
+ if tr_cls is None:
638
+ report.error(
639
+ file,
640
+ "[tracking]",
641
+ f"unknown tracking method '{cfg.tracking.method}' "
642
+ f"(known: {', '.join(sorted(trackers))}){CUSTOM_HINT}",
643
+ )
644
+ else:
645
+ for problem in check_kwargs(
646
+ tr_cls, cfg.tracking.kwargs, "tracking", cfg.tracking.method
647
+ ):
648
+ report.error(file, "[tracking]", problem)
649
+
650
+ if pattern_cls is None:
651
+ continue
652
+ try:
653
+ method = pattern_cls(**cfg.pattern.kwargs)
654
+ method.bind_registry(patterns)
655
+ except Exception as e:
656
+ report.error(
657
+ file, "[pattern]", f"constructing '{cfg.pattern.method}' failed: {e!r}"
658
+ )
659
+ continue
660
+ methods_by_stem[stem] = method
661
+ experiment = cfg.to_experiment(f"{stem}.check")
662
+ wanted = list(getattr(method, "_requirements_list", []))
663
+ needs_default_seg = needs_tracks = False
664
+ named_wanted: set[str] = set()
665
+ for channel, _raw, seg_names, tracks, _history in wanted:
666
+ if channel not in cfg.channels.presets:
667
+ report.error(
668
+ file,
669
+ "[pattern]",
670
+ f"method '{cfg.pattern.method}' needs channel '{channel}', "
671
+ f"which is not in [channels] presets {cfg.channels.presets}",
672
+ )
673
+ for seg in seg_names:
674
+ if seg == "segmentation":
675
+ needs_default_seg = True
676
+ else:
677
+ named_wanted.add(seg)
678
+ needs_tracks = needs_tracks or bool(tracks)
679
+ if getattr(method, "_stim_requested", False):
680
+ if getattr(method, "_stim_request_seg", False):
681
+ needs_default_seg = True
682
+ if cfg.stimulation.exposure <= 0:
683
+ report.error(
684
+ file,
685
+ "[pattern]",
686
+ f"method '{cfg.pattern.method}' requests the stimulation frame but "
687
+ "[stimulation] exposure is 0",
688
+ )
689
+ if needs_default_seg and cfg.segmentation is None:
690
+ report.error(
691
+ file,
692
+ "[segmentation]",
693
+ f"method '{cfg.pattern.method}' needs a segmentation but the file has no [segmentation] table",
694
+ )
695
+ for seg in sorted(named_wanted):
696
+ if seg not in cfg.segmentations:
697
+ report.error(
698
+ file,
699
+ f"[segmentation.{seg}]",
700
+ f"method '{cfg.pattern.method}' needs segmentation '{seg}', which is not configured",
701
+ )
702
+ if needs_tracks and cfg.tracking is None:
703
+ report.error(
704
+ file,
705
+ "[tracking]",
706
+ f"method '{cfg.pattern.method}' needs tracks but the file has no [tracking] table",
707
+ )
708
+ if (
709
+ cfg.segmentation is not None
710
+ and not needs_default_seg
711
+ and not (
712
+ needs_tracks
713
+ and cfg.tracking is not None
714
+ and cfg.tracking.segmentation == "segmentation"
715
+ )
716
+ ):
717
+ report.warning(
718
+ file,
719
+ "[segmentation]",
720
+ f"configured but the pattern method '{cfg.pattern.method}' does not ask for it; "
721
+ "it will not run",
722
+ )
723
+ for seg in cfg.segmentations:
724
+ tracked = (
725
+ cfg.tracking is not None
726
+ and cfg.tracking.segmentation == seg
727
+ and needs_tracks
728
+ )
729
+ if seg not in named_wanted and not tracked:
730
+ report.warning(
731
+ file,
732
+ f"[segmentation.{seg}]",
733
+ f"configured but nothing asks for it; it will not run",
734
+ )
735
+ if cfg.tracking is not None and not needs_tracks:
736
+ report.warning(
737
+ file,
738
+ "[tracking]",
739
+ f"configured but the pattern method '{cfg.pattern.method}' does not ask for tracks; "
740
+ "it will not run",
741
+ )
742
+ try:
743
+ requirements_by_stem[stem] = method.initialize(experiment)
744
+ except Exception as e:
745
+ report.error(
746
+ file, "[pattern]", f"initialising '{cfg.pattern.method}' failed: {e!r}"
747
+ )
748
+
749
+ # 7. MicroManager configuration
750
+ mm = None
751
+ mm_path = None
752
+ if mm_config is not None:
753
+ mm_path = Path(mm_config)
754
+ elif config is not None:
755
+ mm_path = Path(config.config_path)
756
+ if mm_path is not None:
757
+ from .core.real_core import device_interface
758
+
759
+ di = device_interface()
760
+ if di is not None:
761
+ report.info(
762
+ "pymmcore",
763
+ "",
764
+ f"device interface {di}: the Micro-Manager adapters at "
765
+ f"{mm_path.parent} must be built for interface {di}",
766
+ )
767
+ if mm_path is not None and mm_path.exists():
768
+ try:
769
+ mm = MMConfig.from_file(mm_path)
770
+ report.info(
771
+ mm_path.name, "", f"MicroManager configuration read: {mm.summary()}"
772
+ )
773
+ except Exception as e:
774
+ report.warning(
775
+ mm_path.name, "", f"could not be read ({e}); presets not checked"
776
+ )
777
+ elif mm_path is not None:
778
+ report.info(
779
+ CONFIG_NAME,
780
+ "config_path",
781
+ f"MicroManager configuration not found at {mm_path}; presets and devices not checked",
782
+ )
783
+ _check_shared_config_groups(report, configs)
784
+ if mm is not None:
785
+ for stem, cfg in configs.items():
786
+ file = f"{stem}.toml"
787
+ _check_pixel_size(report, file, cfg, mm)
788
+ for group, preset in sorted(cfg.config_groups_used()):
789
+ if not mm.has_group(group):
790
+ report.error(
791
+ file,
792
+ "",
793
+ f"config group '{group}' is not in the MicroManager configuration "
794
+ f"(groups: {', '.join(sorted(mm.groups)) or 'none'})",
795
+ )
796
+ elif not mm.has_preset(group, preset):
797
+ report.error(
798
+ file,
799
+ "",
800
+ f"preset '{preset}' is not in config group '{group}' "
801
+ f"(presets: {', '.join(mm.presets(group)) or 'none'})",
802
+ )
803
+ for key in sorted(cfg.device_properties_used()):
804
+ device, prop = key.split("-", 1)
805
+ known = mm.has_property(device, prop)
806
+ if known is False:
807
+ report.error(
808
+ file,
809
+ "",
810
+ f"device '{device}' ('{key}') is not in the MicroManager configuration",
811
+ )
812
+ elif known is None:
813
+ report.warning(
814
+ file,
815
+ "",
816
+ f"property '{prop}' of device '{device}' is not listed in the MicroManager "
817
+ "configuration (it may still exist on the device)",
818
+ )
819
+
820
+ # 8. timing and frame counts
821
+ if schedule is not None and labels and all(s in configs for s in labels.values()):
822
+ from .core.experiments import ExperimentSchedule
823
+
824
+ experiments = {
825
+ label: configs[stem].to_experiment(label) for label, stem in labels.items()
826
+ }
827
+ pos_by_label = {p.label: p for p in positions or []}
828
+ requirements = {}
829
+ for label, stem in labels.items():
830
+ method = methods_by_stem.get(stem)
831
+ if method is not None:
832
+ try:
833
+ requirements[label] = method.initialize(experiments[label])
834
+ except Exception:
835
+ pass
836
+ try:
837
+ sched = ExperimentSchedule(
838
+ experiments,
839
+ {label: pos_by_label[label] for label in labels},
840
+ **schedule.timing_kwargs(),
841
+ )
842
+ plan = AcquisitionPlan.from_schedule(sched, requirements)
843
+ except Exception as e:
844
+ report.error(SCHEDULE_NAME, "", f"the plan could not be built: {e!r}")
845
+ plan = None
846
+ if plan is not None:
847
+ settle = config.settle_time_seconds if config is not None else 1.0
848
+ over = plan.over_budget(settle_s=settle)
849
+ if over:
850
+ worst_t, worst = max(over, key=lambda item: item[1])
851
+ report.warning(
852
+ SCHEDULE_NAME,
853
+ "[timing]",
854
+ f"{len(over)} of {plan.timepoints} timepoints are estimated to take longer "
855
+ f"than the {plan.interval_s:g} s interval (worst t={worst_t}: {worst:.1f} s "
856
+ f"with settle time {settle:g} s); acquisitions will run late",
857
+ )
858
+ counts: dict[str, int] = {}
859
+ for ds in plan.expected_datasets():
860
+ counts[ds.experiment] = counts.get(ds.experiment, 0) + 1
861
+ for label, n in counts.items():
862
+ report.info(label, "", f"{n} frames over {plan.timepoints} timepoints")
863
+
864
+ # 9. existing outputs
865
+ for label in labels:
866
+ for suffix in OUTPUT_SUFFIXES:
867
+ out = directory / f"{label}{suffix}"
868
+ if out.exists():
869
+ report.error(
870
+ out.name,
871
+ "",
872
+ "output already exists; move or delete it before running",
873
+ )
874
+
875
+ # 10. dry rehearsal
876
+ if dry:
877
+ _dry_rehearsal(
878
+ directory,
879
+ report,
880
+ cfg_path,
881
+ pattern_methods,
882
+ segmentation_methods,
883
+ tracking_methods,
884
+ )
885
+ return report
886
+
887
+
888
+ def _dry_rehearsal(
889
+ directory, report, cfg_path, pattern_methods, segmentation_methods, tracking_methods
890
+ ):
891
+ """Copy the directory, cut it to two quick timepoints, run it on the virtual microscope."""
892
+ from .run_pyclm import run_pyclm
893
+
894
+ if not list(directory.glob("*.tif")) and not (directory / "dry_run.yml").exists():
895
+ report.warning(
896
+ "dry run",
897
+ "",
898
+ "no TIF files in the directory; the virtual microscope needs them",
899
+ )
900
+ return
901
+ tmp = Path(tempfile.mkdtemp(prefix="pyclm-check-"))
902
+ try:
903
+ for item in directory.iterdir():
904
+ if item.suffix in OUTPUT_SUFFIXES or item.name in ("preview", "log.log"):
905
+ continue
906
+ if item.is_dir():
907
+ shutil.copytree(item, tmp / item.name)
908
+ else:
909
+ shutil.copy(item, tmp / item.name)
910
+ from .directories import find_schedule
911
+
912
+ schedule_file = find_schedule(tmp) or (tmp / SCHEDULE_NAME)
913
+ schedule = ScheduleConfig.from_file(schedule_file)
914
+ schedule_file.write_text(
915
+ "[timing]\nsteps = 2\ninterval_seconds = 1.0\nsetup_time_seconds = 0.0\n"
916
+ f"time_between_positions = {min(schedule.timing.time_between_positions, 0.1):g}\n"
917
+ )
918
+ run_pyclm(
919
+ tmp,
920
+ None if cfg_path is None else str(cfg_path),
921
+ dry=True,
922
+ pattern_methods=pattern_methods,
923
+ segmentation_methods=segmentation_methods,
924
+ tracking_methods=tracking_methods,
925
+ check=False,
926
+ )
927
+ report.info("dry run", "", "two timepoints ran on the virtual microscope")
928
+ except Exception as e:
929
+ report.error("dry run", "", f"failed: {e!r}")
930
+ finally:
931
+ shutil.rmtree(tmp, ignore_errors=True)