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/schema.py ADDED
@@ -0,0 +1,806 @@
1
+ """
2
+ The configuration schema: what the experiment TOML, ``schedule.toml`` and
3
+ ``pyclm_config.toml`` may contain, with defaults and limits, and plain
4
+ messages when they do not.
5
+
6
+ The models validate and then build the same objects the rest of PyCLM has
7
+ always used (:class:`~pyclm.core.experiments.Experiment`, the timing dict
8
+ of ``ExperimentSchedule``), so nothing downstream changes. Unknown keys are
9
+ errors everywhere except in the three method tables (``[segmentation]``,
10
+ ``[tracking]``, ``[pattern]``), whose extra keys are the method's keyword
11
+ arguments; ``pyclm check`` compares those with the method's signature.
12
+
13
+ See docs/stage5-schema-setup-design.md §2.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import difflib
19
+ import tomllib
20
+ from copy import deepcopy
21
+ from pathlib import Path
22
+ from typing import Any, Literal
23
+
24
+ import numpy as np
25
+ from pydantic import BaseModel, ConfigDict, Field, ValidationError, model_validator
26
+
27
+ from .core.experiments import (
28
+ ConfigGroup,
29
+ DeviceProperty,
30
+ Experiment,
31
+ ImagingConfig,
32
+ PatternConfig,
33
+ SegmentationConfig,
34
+ TrackingConfig,
35
+ check_type,
36
+ )
37
+ from .core.kinds import DEFAULT_SEGMENTATION
38
+
39
+ FORMAT_VERSION = 1
40
+
41
+ Scalar = bool | int | float | str
42
+
43
+
44
+ class ConfigError(ValueError):
45
+ """A configuration file has problems; ``problems`` lists them, one line each."""
46
+
47
+ def __init__(self, file: str | Path | None, problems: list[str]):
48
+ self.file = None if file is None else str(file)
49
+ self.problems = list(problems)
50
+ prefix = "" if self.file is None else f"{Path(self.file).name}: "
51
+ super().__init__("\n".join(prefix + p for p in self.problems))
52
+
53
+
54
+ # ------------------------------------------------------------------ pieces
55
+ class Strict(BaseModel):
56
+ model_config = ConfigDict(extra="forbid")
57
+
58
+
59
+ def _check_version(v: int) -> int:
60
+ if v > FORMAT_VERSION:
61
+ raise ValueError(
62
+ f"format_version {v} is newer than this PyCLM understands ({FORMAT_VERSION})"
63
+ )
64
+ if v < 1:
65
+ raise ValueError("format_version must be at least 1")
66
+ return v
67
+
68
+
69
+ def _check_device_properties(table: dict) -> dict:
70
+ for key in table:
71
+ if key.count("-") != 1 or not all(key.split("-")):
72
+ raise ValueError(
73
+ f'device property key {key!r} must be written "Device-Property"'
74
+ )
75
+ return table
76
+
77
+
78
+ class ImagingDefaults(Strict):
79
+ """Defaults for every imaging channel."""
80
+
81
+ exposure: float = Field(10.0, gt=0, description="exposure in ms")
82
+ every_t: int = Field(
83
+ 1, ge=1, description="acquire every N timepoints, counted from t_delay"
84
+ )
85
+ save: bool = Field(True, description="record the frames")
86
+ binning: int = Field(
87
+ 1, ge=1, description="camera binning, the same for every channel"
88
+ )
89
+ config_groups: dict[str, str] = Field(
90
+ default_factory=dict, description="group = preset, applied to imaging channels"
91
+ )
92
+ device_properties: dict[str, Scalar] = Field(
93
+ default_factory=dict,
94
+ description='"Device-Property" = value, applied to imaging channels',
95
+ )
96
+
97
+ @model_validator(mode="after")
98
+ def _props(self):
99
+ _check_device_properties(self.device_properties)
100
+ return self
101
+
102
+
103
+ class ChannelOverride(Strict):
104
+ """Per-preset overrides of the imaging defaults (``[channels.<preset>]``)."""
105
+
106
+ exposure: float | None = Field(None, gt=0, description="exposure in ms")
107
+ every_t: int | None = Field(None, ge=1, description="acquire every N timepoints")
108
+ config_groups: dict[str, str] = Field(
109
+ default_factory=dict, description="group = preset"
110
+ )
111
+ device_properties: dict[str, Scalar] = Field(
112
+ default_factory=dict, description='"Device-Property" = value'
113
+ )
114
+
115
+ @model_validator(mode="before")
116
+ @classmethod
117
+ def _no_binning(cls, data):
118
+ if isinstance(data, dict) and "binning" in data:
119
+ raise ValueError(
120
+ "binning cannot differ between channels; set it once under [imaging]"
121
+ )
122
+ return data
123
+
124
+ @model_validator(mode="after")
125
+ def _props(self):
126
+ _check_device_properties(self.device_properties)
127
+ return self
128
+
129
+
130
+ class Channels(BaseModel):
131
+ """
132
+ Which presets of which config group are the imaging channels. May be
133
+ empty (or the table absent) for an experiment that only stimulates.
134
+ """
135
+
136
+ model_config = ConfigDict(extra="forbid")
137
+
138
+ group: str = Field(
139
+ "Channel", description="the MicroManager config group that switches channels"
140
+ )
141
+ presets: list[str] = Field(
142
+ default_factory=list,
143
+ description="the presets to image, in acquisition order; empty for a "
144
+ "stimulation-only experiment",
145
+ )
146
+ overrides: dict[str, ChannelOverride] = Field(
147
+ default_factory=dict,
148
+ description="[channels.<preset>] tables: exposure, every_t, config_groups, device_properties",
149
+ )
150
+
151
+ @model_validator(mode="before")
152
+ @classmethod
153
+ def _collect_overrides(cls, data):
154
+ if not isinstance(data, dict):
155
+ return data
156
+ data = dict(data)
157
+ overrides = dict(data.pop("overrides", {}) or {})
158
+ for key in list(data):
159
+ if key not in ("group", "presets") and isinstance(data[key], dict):
160
+ overrides[key] = data.pop(key)
161
+ data["overrides"] = overrides
162
+ return data
163
+
164
+ @model_validator(mode="after")
165
+ def _consistent(self):
166
+ if len(set(self.presets)) != len(self.presets):
167
+ raise ValueError(f"presets contains duplicates: {self.presets}")
168
+ for name in self.overrides:
169
+ if name not in self.presets:
170
+ raise ValueError(
171
+ f"[channels.{name}] names a preset that is not in presets {self.presets}"
172
+ )
173
+ return self
174
+
175
+
176
+ class Stimulation(Strict):
177
+ """The light-delivery event (the DMD pattern is applied here)."""
178
+
179
+ exposure: float = Field(
180
+ ..., ge=0, description="exposure in ms; 0 means no stimulation"
181
+ )
182
+ every_t: int = Field(1, ge=1, description="stimulate every N timepoints")
183
+ save: bool = Field(
184
+ True, description="record the camera frame taken during stimulation"
185
+ )
186
+ binning: int | None = Field(None, ge=1, description="default: the imaging binning")
187
+ config_groups: dict[str, str] = Field(
188
+ default_factory=dict, description="group = preset"
189
+ )
190
+ device_properties: dict[str, Scalar] = Field(
191
+ default_factory=dict, description='"Device-Property" = value'
192
+ )
193
+
194
+ @model_validator(mode="after")
195
+ def _props(self):
196
+ _check_device_properties(self.device_properties)
197
+ return self
198
+
199
+
200
+ # keys that belong at the top of the experiment file; a TOML key written after
201
+ # a table header lands inside that table, which is where beginners lose them
202
+ TOP_LEVEL_KEYS = ("t_delay", "t_stop")
203
+
204
+
205
+ class MethodTable(BaseModel):
206
+ """A method and its keyword arguments; extra keys are passed to the method."""
207
+
208
+ model_config = ConfigDict(extra="allow")
209
+
210
+ method: str = Field(..., description="a built-in or registered method name")
211
+ save: bool = Field(True, description="record the method's output")
212
+
213
+ @model_validator(mode="before")
214
+ @classmethod
215
+ def _save_alias(cls, data):
216
+ if isinstance(data, dict) and "save_output" in data:
217
+ data = dict(data)
218
+ if "save" in data:
219
+ raise ValueError("give either save or save_output, not both")
220
+ data["save"] = data.pop("save_output")
221
+ if isinstance(data, dict):
222
+ misplaced = [k for k in TOP_LEVEL_KEYS if k in data]
223
+ if misplaced:
224
+ raise ValueError(
225
+ f"{', '.join(misplaced)} must be written at the top of the file, "
226
+ "before the first table (a key written after a table header "
227
+ "belongs to that table)"
228
+ )
229
+ return data
230
+
231
+ @property
232
+ def kwargs(self) -> dict[str, Any]:
233
+ """The keys passed to the method's constructor."""
234
+ return dict(self.model_extra or {})
235
+
236
+
237
+ class SegmentationTable(MethodTable):
238
+ """``[segmentation]`` or a named ``[segmentation.<name>]``."""
239
+
240
+
241
+ class TrackingTable(MethodTable):
242
+ """``[tracking]``."""
243
+
244
+ segmentation: str = Field(
245
+ DEFAULT_SEGMENTATION,
246
+ description="the segmentation table whose objects are tracked",
247
+ )
248
+
249
+
250
+ class PatternTable(MethodTable):
251
+ """``[pattern]``."""
252
+
253
+ every_t: int = Field(
254
+ 1, ge=1, description="regenerate the pattern every N timepoints"
255
+ )
256
+
257
+
258
+ class ExperimentConfig(Strict):
259
+ """One experiment TOML."""
260
+
261
+ format_version: int = Field(
262
+ FORMAT_VERSION, description="schema version of this file"
263
+ )
264
+ config_groups: dict[str, str] = Field(
265
+ default_factory=dict, description="group = preset, applied to every acquisition"
266
+ )
267
+ device_properties: dict[str, Scalar] = Field(
268
+ default_factory=dict,
269
+ description='"Device-Property" = value, applied to every acquisition',
270
+ )
271
+ imaging: ImagingDefaults = Field(default_factory=ImagingDefaults)
272
+ channels: Channels = Field(
273
+ default_factory=Channels,
274
+ description="the imaging channels; omit for a stimulation-only experiment",
275
+ )
276
+ stimulation: Stimulation
277
+ segmentation: SegmentationTable | None = Field(
278
+ None, description="the default segmentation"
279
+ )
280
+ segmentations: dict[str, SegmentationTable] = Field(
281
+ default_factory=dict, description="named [segmentation.<name>] tables"
282
+ )
283
+ tracking: TrackingTable | None = None
284
+ pattern: PatternTable
285
+ t_delay: int = Field(
286
+ 0, ge=0, description="timepoints to wait before this experiment starts"
287
+ )
288
+ t_stop: int = Field(
289
+ 0,
290
+ ge=0,
291
+ description="stop after this many of its own timepoints (0 = run to the end)",
292
+ )
293
+
294
+ @model_validator(mode="before")
295
+ @classmethod
296
+ def _split_named_segmentations(cls, data):
297
+ """``[segmentation.<name>]`` sub-tables become ``segmentations``."""
298
+ if not isinstance(data, dict):
299
+ return data
300
+ data = dict(data)
301
+ seg = data.get("segmentation")
302
+ if isinstance(seg, dict):
303
+ seg = dict(seg)
304
+ named = dict(data.get("segmentations") or {})
305
+ for key in list(seg):
306
+ if isinstance(seg[key], dict):
307
+ named[key] = seg.pop(key)
308
+ data["segmentations"] = named
309
+ data["segmentation"] = seg if seg else None
310
+ return data
311
+
312
+ @model_validator(mode="after")
313
+ def _cross(self):
314
+ _check_device_properties(self.device_properties)
315
+ _check_version(self.format_version)
316
+ if DEFAULT_SEGMENTATION in self.segmentations:
317
+ raise ValueError(
318
+ f"[segmentation.{DEFAULT_SEGMENTATION}] is reserved for the default [segmentation] table"
319
+ )
320
+ if self.tracking is not None:
321
+ name = self.tracking.segmentation
322
+ have = self.segmentation_names
323
+ if name not in have:
324
+ raise ValueError(
325
+ f"[tracking] segmentation = {name!r} but the experiment configures "
326
+ + (f"only {have}" if have else "no segmentation")
327
+ )
328
+ return self
329
+
330
+ # ----------------------------------------------------------- queries
331
+ @property
332
+ def segmentation_names(self) -> list[str]:
333
+ names = [DEFAULT_SEGMENTATION] if self.segmentation is not None else []
334
+ return names + list(self.segmentations)
335
+
336
+ @property
337
+ def channel_names(self) -> list[str]:
338
+ return list(self.channels.presets)
339
+
340
+ def config_groups_used(self) -> set[tuple[str, str]]:
341
+ """Every (group, preset) the experiment sets, including the channel group."""
342
+ used = set(self.config_groups.items()) | set(self.imaging.config_groups.items())
343
+ used |= {(self.channels.group, p) for p in self.channels.presets}
344
+ for ov in self.channels.overrides.values():
345
+ used |= set(ov.config_groups.items())
346
+ used |= set(self.stimulation.config_groups.items())
347
+ return used
348
+
349
+ def device_properties_used(self) -> set[str]:
350
+ keys = set(self.device_properties) | set(self.imaging.device_properties)
351
+ for ov in self.channels.overrides.values():
352
+ keys |= set(ov.device_properties)
353
+ keys |= set(self.stimulation.device_properties)
354
+ return keys
355
+
356
+ # ------------------------------------------------------------- build
357
+ def to_experiment(self, name: str) -> Experiment:
358
+ """The runtime ``Experiment`` this file describes, for position ``name``."""
359
+ base = ImagingConfig(
360
+ experiment_name=name,
361
+ config_groups=_groups(self.config_groups),
362
+ device_properties=_props(self.device_properties),
363
+ )
364
+
365
+ imaging = deepcopy(base)
366
+ imaging.set_id()
367
+ imaging.update_config_groups(_groups(self.imaging.config_groups))
368
+ imaging.update_device_properties(_props(self.imaging.device_properties))
369
+ imaging.exposure = self.imaging.exposure
370
+ imaging.every_t = self.imaging.every_t
371
+ imaging.save = self.imaging.save
372
+ imaging.binning = self.imaging.binning
373
+
374
+ channels = {}
375
+ for preset in self.channels.presets:
376
+ cfg = deepcopy(imaging)
377
+ cfg.set_id()
378
+ cfg.update_config_groups([ConfigGroup(self.channels.group, preset)])
379
+ ov = self.channels.overrides.get(preset)
380
+ if ov is not None:
381
+ if ov.exposure is not None:
382
+ cfg.exposure = ov.exposure
383
+ if ov.every_t is not None:
384
+ cfg.every_t = ov.every_t
385
+ cfg.update_config_groups(_groups(ov.config_groups))
386
+ cfg.update_device_properties(_props(ov.device_properties))
387
+ channels[preset] = cfg
388
+
389
+ stim = deepcopy(base)
390
+ stim.set_id()
391
+ stim.exposure = self.stimulation.exposure
392
+ stim.every_t = self.stimulation.every_t
393
+ stim.save = self.stimulation.save
394
+ stim.binning = (
395
+ self.imaging.binning
396
+ if self.stimulation.binning is None
397
+ else self.stimulation.binning
398
+ )
399
+ stim.update_config_groups(_groups(self.stimulation.config_groups))
400
+ stim.update_device_properties(_props(self.stimulation.device_properties))
401
+
402
+ segmentation = (
403
+ SegmentationConfig("none")
404
+ if self.segmentation is None
405
+ else SegmentationConfig(
406
+ self.segmentation.method,
407
+ save_output=self.segmentation.save,
408
+ **self.segmentation.kwargs,
409
+ )
410
+ )
411
+ segmentations = {
412
+ n: SegmentationConfig(t.method, save_output=t.save, **t.kwargs)
413
+ for n, t in self.segmentations.items()
414
+ }
415
+ tracking = (
416
+ TrackingConfig("none")
417
+ if self.tracking is None
418
+ else TrackingConfig(
419
+ self.tracking.method,
420
+ save_output=self.tracking.save,
421
+ segmentation=self.tracking.segmentation,
422
+ **self.tracking.kwargs,
423
+ )
424
+ )
425
+ pattern = PatternConfig(
426
+ self.pattern.method,
427
+ save_output=self.pattern.save,
428
+ every_t=self.pattern.every_t,
429
+ **self.pattern.kwargs,
430
+ )
431
+ return Experiment(
432
+ experiment_name=name,
433
+ imaging_configs=channels,
434
+ stimulation_config=stim,
435
+ segmentation=segmentation,
436
+ pattern=pattern,
437
+ t_delay=self.t_delay,
438
+ t_stop=self.t_stop,
439
+ tracking=tracking,
440
+ segmentations=segmentations,
441
+ )
442
+
443
+ @classmethod
444
+ def from_file(cls, path: str | Path) -> ExperimentConfig:
445
+ return load_model(cls, path)
446
+
447
+
448
+ class Timing(Strict):
449
+ """``[timing]`` of ``schedule.toml``."""
450
+
451
+ steps: int = Field(..., ge=1, description="number of timepoints")
452
+ interval_seconds: float = Field(..., gt=0, description="seconds between timepoints")
453
+ setup_time_seconds: float = Field(
454
+ 2.0,
455
+ ge=0,
456
+ description="seconds before each timepoint at which its events are prepared",
457
+ )
458
+ time_between_positions: float = Field(
459
+ 2.0, ge=0, description="seconds between successive positions within a timepoint"
460
+ )
461
+
462
+
463
+ class ScheduleConfig(Strict):
464
+ """``schedule.toml``."""
465
+
466
+ format_version: int = Field(
467
+ FORMAT_VERSION, description="schema version of this file"
468
+ )
469
+ timing: Timing
470
+
471
+ @model_validator(mode="after")
472
+ def _version(self):
473
+ _check_version(self.format_version)
474
+ return self
475
+
476
+ def timing_kwargs(self) -> dict:
477
+ """What ``ExperimentSchedule`` takes."""
478
+ return {
479
+ "t_count": self.timing.steps,
480
+ "t_interval": self.timing.interval_seconds,
481
+ "t_setup": self.timing.setup_time_seconds,
482
+ "t_between": self.timing.time_between_positions,
483
+ }
484
+
485
+ @classmethod
486
+ def from_file(cls, path: str | Path) -> ScheduleConfig:
487
+ return load_model(cls, path)
488
+
489
+
490
+ class OutputConfig(Strict):
491
+ """``[output]`` of ``pyclm_config.toml``."""
492
+
493
+ format: Literal["ome-zarr", "hdf5"] = Field(
494
+ "ome-zarr", description="storage format"
495
+ )
496
+ pattern_policy: Literal["on_change", "imaging", "none"] = Field(
497
+ "on_change",
498
+ description="which patterns to store (ome-zarr only): every distinct one "
499
+ "(on_change), only the one in force at timepoints where an imaging frame "
500
+ "is saved (imaging), or none",
501
+ )
502
+ export_imagej: bool = Field(
503
+ True, description="write ImageJ hyperstacks when the run ends"
504
+ )
505
+
506
+
507
+ class PyclmConfig(Strict):
508
+ """``pyclm_config.toml``: the hardware and output configuration."""
509
+
510
+ format_version: int = Field(
511
+ FORMAT_VERSION, description="schema version of this file"
512
+ )
513
+ config_path: str = Field(..., description="path to the MicroManager .cfg file")
514
+ affine_transform: list[list[float]] = Field(
515
+ ..., description="2 x 3 camera-to-SLM affine matrix [[a, b, tx], [c, d, ty]]"
516
+ )
517
+ slm_shape_h: int = Field(..., gt=0, description="SLM (DMD) height in pixels")
518
+ slm_shape_w: int = Field(..., gt=0, description="SLM (DMD) width in pixels")
519
+ focus_device: str = Field(
520
+ "ZDrive", description="MicroManager focus (Z) device selected at start-up"
521
+ )
522
+ position_mover: str = Field(
523
+ "basic",
524
+ description='how the stage moves to a position: "basic" (XY then Z), "pfs" '
525
+ "(Nikon Perfect Focus: move, apply the PFS offset, wait for the lock), or "
526
+ '"package.module:ClassName" for a custom PositionMover subclass',
527
+ )
528
+ settle_time_seconds: float = Field(
529
+ 1.0,
530
+ ge=0,
531
+ description="seconds to wait after the hardware reports ready, before each snap",
532
+ )
533
+ camera_roi: list[int] | None = Field(
534
+ None,
535
+ description="camera ROI [x, y, width, height] in unbinned pixels, set when a run "
536
+ "starts (for example the region the DMD covers; pyclm check prints it); "
537
+ "omit to leave the camera as it is",
538
+ )
539
+ methods: list[str] = Field(
540
+ default_factory=list,
541
+ description="custom pattern / segmentation / tracking methods to load: Python "
542
+ "files (relative to this file) or module names; each method class is "
543
+ "registered under its name attribute",
544
+ )
545
+ output: OutputConfig = Field(default_factory=OutputConfig)
546
+
547
+ @model_validator(mode="after")
548
+ def _shape(self):
549
+ _check_version(self.format_version)
550
+ at = self.affine_transform
551
+ if len(at) != 2 or any(len(row) != 3 for row in at):
552
+ raise ValueError(
553
+ "affine_transform must be a 2 x 3 matrix [[a, b, tx], [c, d, ty]]"
554
+ )
555
+ roi = self.camera_roi
556
+ if roi is not None:
557
+ if len(roi) != 4 or roi[0] < 0 or roi[1] < 0 or roi[2] <= 0 or roi[3] <= 0:
558
+ raise ValueError(
559
+ "camera_roi must be [x, y, width, height] with x, y >= 0 and "
560
+ "width, height > 0 (unbinned pixels)"
561
+ )
562
+ return self
563
+
564
+ def dmd_footprint(self) -> tuple[int, int, int, int]:
565
+ """
566
+ The camera region the DMD can reach, ``[x, y, width, height]`` in
567
+ unbinned camera pixels: the DMD rectangle mapped through the inverse
568
+ of the camera-to-SLM affine.
569
+ """
570
+ import cv2
571
+
572
+ h, w = self.slm_shape
573
+ inv = cv2.invertAffineTransform(self.affine)
574
+ corners = np.array([[0, 0], [w, 0], [0, h], [w, h]], dtype=np.float32)
575
+ cam = corners @ inv[:, :2].T + inv[:, 2]
576
+ x0, y0 = np.floor(cam.min(axis=0))
577
+ x1, y1 = np.ceil(cam.max(axis=0))
578
+ return (int(x0), int(y0), int(x1 - x0), int(y1 - y0))
579
+
580
+ @property
581
+ def affine(self) -> np.ndarray:
582
+ return np.array(self.affine_transform, dtype=np.float32)
583
+
584
+ @property
585
+ def slm_shape(self) -> tuple[int, int]:
586
+ return (self.slm_shape_h, self.slm_shape_w)
587
+
588
+ @classmethod
589
+ def from_file(cls, path: str | Path) -> PyclmConfig:
590
+ return load_model(cls, path)
591
+
592
+
593
+ # ------------------------------------------------------------- loading
594
+ def _groups(table: dict[str, str]) -> list[ConfigGroup]:
595
+ return [ConfigGroup(g, p) for g, p in table.items()]
596
+
597
+
598
+ def _props(table: dict[str, Scalar]) -> list[DeviceProperty]:
599
+ out = []
600
+ for key, value in table.items():
601
+ device, prop = key.split("-", 1)
602
+ out.append(DeviceProperty(device, prop, value, check_type(value)))
603
+ return out
604
+
605
+
606
+ def read_toml(path: str | Path) -> dict:
607
+ path = Path(path)
608
+ try:
609
+ with open(path, "rb") as f:
610
+ return tomllib.load(f)
611
+ except FileNotFoundError:
612
+ raise ConfigError(path, ["file not found"]) from None
613
+ except Exception as e: # tomllib.TOMLDecodeError, a file that is not UTF-8
614
+ raise ConfigError(path, [f"not valid TOML: {e}"]) from None
615
+
616
+
617
+ def validate_model(model: type[BaseModel], data: dict, file: str | Path | None = None):
618
+ """``model.model_validate(data)``, raising :class:`ConfigError` with readable problems."""
619
+ try:
620
+ return model.model_validate(data)
621
+ except ValidationError as e:
622
+ raise ConfigError(file, describe_errors(e, model)) from None
623
+
624
+
625
+ def load_model(model: type[BaseModel], path: str | Path):
626
+ return validate_model(model, read_toml(path), path)
627
+
628
+
629
+ # ------------------------------------------------------- error messages
630
+ def _table_name(loc: tuple) -> str:
631
+ """The table at ``loc`` as the file writes it: ``[channels.638]``, ``[segmentation.nuclei]``."""
632
+ parts = [str(p) for p in loc if str(p) != "overrides"]
633
+ if parts and parts[0] == "segmentations":
634
+ parts[0] = "segmentation"
635
+ if not parts:
636
+ return "the file"
637
+ return "[" + ".".join(parts) + "]"
638
+
639
+
640
+ def _fields_at(
641
+ model: type[BaseModel] | None, loc: tuple
642
+ ) -> tuple[list[str], str | None]:
643
+ """The allowed keys of the table at ``loc`` and the table's display name."""
644
+ if model is None:
645
+ return [], None
646
+ current: Any = model
647
+ for part in loc:
648
+ if isinstance(current, type) and issubclass(current, BaseModel):
649
+ field = current.model_fields.get(str(part))
650
+ if field is None:
651
+ return [], None
652
+ current = field.annotation
653
+ else:
654
+ # dict[str, Model]: the part is a key, the value type is the model
655
+ args = getattr(current, "__args__", ())
656
+ current = args[1] if len(args) == 2 else None
657
+ # unwrap Optional[Model]
658
+ if current is not None and getattr(current, "__origin__", None) is not None:
659
+ args = [a for a in current.__args__ if a is not type(None)]
660
+ if len(args) == 1:
661
+ current = args[0]
662
+ if current is None:
663
+ return [], None
664
+ if isinstance(current, type) and issubclass(current, BaseModel):
665
+ names = [n for n in current.model_fields if n != "overrides"]
666
+ return sorted(names), current.__name__
667
+ return [], None
668
+
669
+
670
+ def describe_errors(
671
+ error: ValidationError, model: type[BaseModel] | None = None
672
+ ) -> list[str]:
673
+ """One readable line per problem, in the vocabulary of the TOML file."""
674
+ lines = []
675
+ for err in error.errors():
676
+ loc = tuple(err.get("loc", ()))
677
+ kind = err.get("type", "")
678
+ msg = err.get("msg", "")
679
+ given = err.get("input")
680
+ # display names: the last element is the key, the rest the table
681
+ if kind == "extra_forbidden":
682
+ table, key = loc[:-1], str(loc[-1])
683
+ allowed, _ = _fields_at(model, table)
684
+ hint = ""
685
+ close = difflib.get_close_matches(key, allowed, n=1)
686
+ if close:
687
+ hint = f" (did you mean {close[0]!r}?)"
688
+ where = _table_name(table)
689
+ lines.append(
690
+ f"unknown key {key!r} in {where}{hint}"
691
+ + (f"; allowed: {', '.join(allowed)}" if allowed else "")
692
+ )
693
+ elif kind == "missing":
694
+ table, key = loc[:-1], str(loc[-1])
695
+ lines.append(f"{_table_name(table)} is missing the required key {key!r}")
696
+ elif kind == "value_error":
697
+ # our own ValueErrors: strip pydantic's prefix
698
+ text = msg.removeprefix("Value error, ")
699
+ where = _table_name(loc)
700
+ lines.append(text if not loc else f"{where}: {text}")
701
+ else:
702
+ table, key = loc[:-1], (str(loc[-1]) if loc else "")
703
+ text = msg
704
+ if kind in (
705
+ "greater_than",
706
+ "greater_than_equal",
707
+ "less_than",
708
+ "less_than_equal",
709
+ ):
710
+ text = text.replace("Input should be", "must be")
711
+ elif kind.endswith("_type") or kind.endswith("_parsing"):
712
+ text = "must be " + msg.removeprefix(
713
+ "Input should be a valid "
714
+ ).removeprefix("Input should be ")
715
+ shown = (
716
+ f" (got {given!r})"
717
+ if given is not None and not isinstance(given, dict)
718
+ else ""
719
+ )
720
+ lines.append(
721
+ f"{_table_name(table)} {key}: {text}{shown}".replace(" ", " ")
722
+ )
723
+ return lines
724
+
725
+
726
+ # ------------------------------------------------------------- helpers
727
+ def experiment_from_file(path: str | Path, name: str) -> Experiment:
728
+ return ExperimentConfig.from_file(path).to_experiment(name)
729
+
730
+
731
+ def schedule_timing_from_file(path: str | Path) -> dict:
732
+ return ScheduleConfig.from_file(path).timing_kwargs()
733
+
734
+
735
+ def pyclm_config_from_file(path: str | Path) -> PyclmConfig:
736
+ return PyclmConfig.from_file(path)
737
+
738
+
739
+ MODELS = {
740
+ "ExperimentConfig": ExperimentConfig,
741
+ "ImagingDefaults": ImagingDefaults,
742
+ "Channels": Channels,
743
+ "ChannelOverride": ChannelOverride,
744
+ "Stimulation": Stimulation,
745
+ "SegmentationTable": SegmentationTable,
746
+ "TrackingTable": TrackingTable,
747
+ "PatternTable": PatternTable,
748
+ "ScheduleConfig": ScheduleConfig,
749
+ "Timing": Timing,
750
+ "PyclmConfig": PyclmConfig,
751
+ "OutputConfig": OutputConfig,
752
+ }
753
+
754
+
755
+ def field_table(model: type[BaseModel]) -> list[dict]:
756
+ """Rows describing a model's fields (for the generated documentation)."""
757
+ rows = []
758
+ for name, field in model.model_fields.items():
759
+ annotation = field.annotation
760
+ type_name = _type_name(annotation)
761
+ if field.is_required():
762
+ default = "required"
763
+ elif field.default_factory is not None:
764
+ default = "{}" if type_name.startswith("table") else "defaults"
765
+ else:
766
+ default = repr(field.default)
767
+ limits = []
768
+ for meta in field.metadata:
769
+ for attr, sym in (
770
+ ("gt", ">"),
771
+ ("ge", "≥"),
772
+ ("lt", "<"),
773
+ ("le", "≤"),
774
+ ("min_length", "≥ length"),
775
+ ):
776
+ v = getattr(meta, attr, None)
777
+ if v is not None:
778
+ limits.append(f"{sym} {v}")
779
+ rows.append(
780
+ {
781
+ "key": name,
782
+ "type": type_name + (f" ({', '.join(limits)})" if limits else ""),
783
+ "default": default,
784
+ "description": field.description or "",
785
+ }
786
+ )
787
+ return rows
788
+
789
+
790
+ def _type_name(annotation) -> str:
791
+ origin = getattr(annotation, "__origin__", None)
792
+ args = getattr(annotation, "__args__", ())
793
+ if origin is dict:
794
+ return "table"
795
+ if origin is list:
796
+ return f"list of {_type_name(args[0])}" if args else "list"
797
+ if origin is Literal:
798
+ return " | ".join(repr(a) for a in args)
799
+ if args and type(None) in args:
800
+ inner = [a for a in args if a is not type(None)]
801
+ return _type_name(inner[0]) if len(inner) == 1 else "value"
802
+ if isinstance(annotation, type):
803
+ if issubclass(annotation, BaseModel):
804
+ return "table"
805
+ return annotation.__name__
806
+ return str(annotation).replace("typing.", "")