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/preview.py ADDED
@@ -0,0 +1,414 @@
1
+ """
2
+ ``pyclm preview``: run one experiment's segmentation(s) and pattern method
3
+ on one image and write what a user needs to judge them.
4
+
5
+ The machinery is the run's own (``SegmentationProcess``, ``TrackingProcess``,
6
+ ``PatternProcess``, a ``DataDock`` and ``PatternContext``, the SLM buffer's
7
+ camera-to-DMD transform), so what preview shows is what the run does. The
8
+ image is a TIF (used for every channel the method needs) or one frame
9
+ snapped per channel from the microscope.
10
+
11
+ See docs/stage5-schema-setup-design.md §6.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import logging
18
+ import time
19
+ from dataclasses import dataclass, field
20
+ from pathlib import Path
21
+
22
+ import numpy as np
23
+
24
+ from .check import find_pyclm_config
25
+ from .core.datatypes import AcquisitionData, TrackingData
26
+ from .core.events import AcquisitionEvent
27
+ from .core.experiments import ImagingConfig, MicroscopePosition
28
+ from .core.grid import cut, geometry_for, stitch
29
+ from .core.kinds import is_seg_kind, seg_name
30
+ from .core.manager import SLMBuffer
31
+ from .core.pattern_process import PatternProcess
32
+ from .core.patterns import (
33
+ ROI,
34
+ CameraProperties,
35
+ DataDock,
36
+ PatternContext,
37
+ )
38
+ from .core.plan import _channel_group, _stim_channel_name
39
+ from .core.queues import AllQueues
40
+ from .core.segmentation_process import SegmentationProcess
41
+ from .core.tracking_process import TrackingProcess
42
+ from .directories import dry_settings_from_directory, find_schedule
43
+ from .schema import ConfigError, ExperimentConfig, PyclmConfig, ScheduleConfig
44
+
45
+ logger = logging.getLogger(__name__)
46
+
47
+
48
+ @dataclass
49
+ class PreviewResult:
50
+ directory: Path
51
+ label: str
52
+ out_dir: Path
53
+ paths: dict[str, Path] = field(default_factory=dict)
54
+ pattern: np.ndarray | None = None
55
+ requests: list = field(default_factory=list)
56
+ info: dict = field(default_factory=dict)
57
+
58
+ def text(self) -> str:
59
+ lines = [f"preview of {self.label} -> {self.out_dir}"]
60
+ info = self.info
61
+ lines.append(
62
+ f" pattern method '{info.get('method')}' {info.get('kwargs', {})}: "
63
+ f"{info.get('lit_fraction', 0) * 100:.1f} % of the field lit, "
64
+ f"generated in {info.get('generate_s', 0):.2f} s"
65
+ )
66
+ for name, seconds in info.get("segmentation_s", {}).items():
67
+ lines.append(
68
+ f" segmentation '{name}': {info['objects'].get(name, 0)} objects in {seconds:.2f} s"
69
+ )
70
+ for change in self.requests:
71
+ lines.append(f" would change: {change}")
72
+ for key, path in self.paths.items():
73
+ lines.append(f" {key}: {path.name}")
74
+ return "\n".join(lines)
75
+
76
+
77
+ def _resolve_experiment(directory: Path, experiment: str) -> tuple[Path, str]:
78
+ """(TOML path, position label) for a position label or a TOML stem."""
79
+ stem = experiment.split(".")[0]
80
+ toml = directory / f"{stem}.toml"
81
+ if not toml.exists():
82
+ raise ConfigError(toml, [f"no experiment file for '{experiment}'"])
83
+ label = experiment if "." in experiment else f"{stem}.preview"
84
+ return toml, label
85
+
86
+
87
+ def _position_for(directory: Path, label: str) -> MicroscopePosition:
88
+ """The directory's position with this label (a grid keeps its tiles), else a stand-in."""
89
+ from .check import _load_positions
90
+
91
+ try:
92
+ _name, positions = _load_positions(directory)
93
+ except Exception:
94
+ positions = None
95
+ for pos in positions or ():
96
+ if pos.label == label:
97
+ return pos
98
+ return MicroscopePosition(0.0, 0.0, 0.0, label=label)
99
+
100
+
101
+ def _load_image(path: Path) -> np.ndarray:
102
+ import tifffile
103
+
104
+ arr = np.asarray(tifffile.imread(str(path)))
105
+ while arr.ndim > 2:
106
+ arr = arr[0]
107
+ return arr
108
+
109
+
110
+ def _apply_channel(core, cfg: ImagingConfig):
111
+ for group, preset in cfg.get_config_groups():
112
+ core.setConfig(group, preset)
113
+ for dp in cfg.get_device_properties():
114
+ core.setProperty(dp.device, dp.property, dp.value)
115
+ core.setExposure(cfg.exposure)
116
+
117
+
118
+ def _overlay(raw: np.ndarray, pattern: np.ndarray) -> np.ndarray:
119
+ lo, hi = np.percentile(raw, (1, 99.5))
120
+ grey = np.clip((raw.astype(float) - lo) / max(hi - lo, 1e-6), 0, 1)
121
+ rgb = np.stack([grey, grey, grey], axis=-1)
122
+ pat = np.clip(np.asarray(pattern, dtype=float), 0, 1)
123
+ if pat.shape != grey.shape:
124
+ from skimage.transform import resize
125
+
126
+ pat = resize(pat, grey.shape, order=0, preserve_range=True)
127
+ rgb[..., 1] = np.maximum(rgb[..., 1], pat)
128
+ rgb[..., 2] = np.maximum(rgb[..., 2], pat)
129
+ return (rgb * 255).astype(np.uint8)
130
+
131
+
132
+ def preview(
133
+ directory,
134
+ experiment: str,
135
+ image=None,
136
+ snap: bool = False,
137
+ config_path=None,
138
+ out_dir=None,
139
+ t: int = 0,
140
+ pixel_size_um: float | None = None,
141
+ pattern_methods=None,
142
+ segmentation_methods=None,
143
+ tracking_methods=None,
144
+ ) -> PreviewResult:
145
+ """See the module docstring. Returns the written paths and the pattern."""
146
+ import tifffile
147
+ from skimage.io import imsave
148
+
149
+ directory = Path(directory)
150
+ toml, label = _resolve_experiment(directory, experiment)
151
+ cfg = ExperimentConfig.from_file(toml)
152
+ exp = cfg.to_experiment(label)
153
+ stem = toml.stem
154
+
155
+ interval_s = 0.0
156
+ schedule_path = find_schedule(directory)
157
+ if schedule_path is not None:
158
+ interval_s = ScheduleConfig.from_file(schedule_path).timing.interval_seconds
159
+ config = None
160
+ found = find_pyclm_config(directory, config_path)
161
+ if found is not None:
162
+ config = PyclmConfig.from_file(found)
163
+
164
+ from .methods import discover
165
+
166
+ custom, _ = discover(config, found)
167
+ pattern_methods, segmentation_methods, tracking_methods = custom.merged_with(
168
+ pattern_methods, segmentation_methods, tracking_methods
169
+ )
170
+
171
+ if out_dir is None:
172
+ out_dir = directory / "preview" / label
173
+ out_dir = Path(out_dir)
174
+ out_dir.mkdir(parents=True, exist_ok=True)
175
+ result = PreviewResult(directory, label, out_dir)
176
+
177
+ # ---------------------------------------------------- image source
178
+ core = None
179
+ dry = dry_settings_from_directory(directory)
180
+ source_binning = 1
181
+ if image is not None:
182
+ frame = _load_image(Path(image))
183
+ # no pixel size given: the directory's dry_run.yml (or its defaults)
184
+ # says what the TIFs are
185
+ px = dry.pixel_size_um if pixel_size_um is None else float(pixel_size_um)
186
+ source_binning = dry.binning
187
+
188
+ def get_frame(channel_cfg: ImagingConfig) -> np.ndarray:
189
+ return frame
190
+
191
+ source = str(image)
192
+ elif snap:
193
+ if config is None:
194
+ raise ConfigError(
195
+ None,
196
+ [
197
+ "--snap needs pyclm_config.toml (config_path to the MicroManager .cfg)"
198
+ ],
199
+ )
200
+ from .core.real_core import RealMicroscopeCore
201
+
202
+ core = RealMicroscopeCore()
203
+ core.loadSystemConfiguration(config.config_path)
204
+ if config.focus_device:
205
+ core.setFocusDevice(config.focus_device)
206
+ if config.camera_roi is not None:
207
+ core.setROI(*[int(v) for v in config.camera_roi])
208
+ px = (
209
+ float(core.getPixelSizeUm())
210
+ if pixel_size_um is None
211
+ else float(pixel_size_um)
212
+ )
213
+ snapped: dict = {}
214
+
215
+ def get_frame(channel_cfg: ImagingConfig) -> np.ndarray:
216
+ key = channel_cfg.channel_id
217
+ if key not in snapped:
218
+ _apply_channel(core, channel_cfg)
219
+ core.waitForSystem()
220
+ core.snapImage()
221
+ snapped[key] = np.asarray(core.getImage())
222
+ return snapped[key]
223
+
224
+ source = "snapped from the microscope"
225
+ else:
226
+ raise ValueError("preview needs an image (image=...) or snap=True")
227
+
228
+ # ------------------------------------------------------ processes
229
+ seg_proc = SegmentationProcess()
230
+ for name, cls in (segmentation_methods or {}).items():
231
+ seg_proc.register_method(cls, name)
232
+ tracking_proc = TrackingProcess()
233
+ for name, cls in (tracking_methods or {}).items():
234
+ tracking_proc.register_method(cls, name)
235
+ pp = PatternProcess(AllQueues())
236
+ for name, cls in (pattern_methods or {}).items():
237
+ pp.register_method(cls, name)
238
+
239
+ binning = int(exp.stimulation.binning)
240
+ # the image is at the imaging binning; the camera ROI is the unbinned size
241
+ # the first imaging channel, or the stimulation channel of an experiment
242
+ # that images nothing else
243
+ if exp.channels:
244
+ probe_channel = next(iter(exp.channels))
245
+ probe_cfg = exp.channels[probe_channel]
246
+ else:
247
+ probe_channel = _stim_channel_name(exp, _channel_group(exp))
248
+ probe_cfg = exp.stimulation
249
+ probe = get_frame(probe_cfg)
250
+ h, w = probe.shape
251
+
252
+ # a grid position: the method sees the stitched frame. A tile-sized image
253
+ # is tiled rows x columns; a stitched-size one is used as it is.
254
+ position = _position_for(directory, label)
255
+ geometry = None
256
+ if position.is_grid:
257
+ tile_h, tile_w = h * binning, w * binning
258
+ stitched = geometry_for(position, (0, 0, tile_w, tile_h), px)
259
+ if (h, w) == tuple(stitched.shape(binning)):
260
+ # already stitched: the tile is the frame divided by the layout
261
+ tile_h = (h * binning - (stitched.rows - 1) * stitched.pitch(1)[0]) // 1
262
+ tile_w = (w * binning - (stitched.columns - 1) * stitched.pitch(1)[1]) // 1
263
+ geometry = geometry_for(position, (0, 0, tile_w, tile_h), px)
264
+ else:
265
+ geometry = stitched
266
+ tiles = [probe] * len(geometry.tiles)
267
+ probe = stitch(tiles, geometry, binning)
268
+
269
+ def get_frame(channel_cfg: ImagingConfig, _f=get_frame) -> np.ndarray:
270
+ return stitch(
271
+ [_f(channel_cfg)] * len(geometry.tiles), geometry, binning
272
+ )
273
+
274
+ h, w = probe.shape
275
+ position.geometry = geometry
276
+ pp.grids = {label: geometry}
277
+ tile_h, tile_w = geometry.tile_shape(1)
278
+ pp.initialize(CameraProperties(ROI(0, 0, tile_w, tile_h), px / binning))
279
+ else:
280
+ pp.initialize(
281
+ CameraProperties(ROI(0, 0, w * binning, h * binning), px / binning)
282
+ )
283
+ reqs = pp.request_method(exp)
284
+ pp.initialize_models()
285
+ model = pp.models[label]
286
+
287
+ by_id = {c.channel_id: (name, c) for name, c in exp.channels.items()}
288
+ by_id[exp.stimulation.channel_id] = ("stimulation", exp.stimulation)
289
+ pp.positions = {label: position}
290
+
291
+ dock = DataDock(t * interval_s, reqs)
292
+ seg_seconds: dict[str, float] = {}
293
+ objects: dict[str, int] = {}
294
+ labels_by_channel: dict[tuple[str, str], np.ndarray] = {}
295
+ frames: dict[str, np.ndarray] = {}
296
+ for req in reqs:
297
+ channel, channel_cfg = by_id[req.id]
298
+ raw = get_frame(channel_cfg)
299
+ frames[channel] = raw
300
+ event = AcquisitionEvent(
301
+ label,
302
+ position,
303
+ req.id,
304
+ index={"t": t, "p": label, "c": channel},
305
+ exposure_time_ms=channel_cfg.exposure,
306
+ binning=channel_cfg.binning,
307
+ )
308
+ event.pixel_width_um = px
309
+ data = AcquisitionData(event, raw)
310
+ for kind in req.kinds:
311
+ if kind == "raw":
312
+ dock.add(data)
313
+ elif is_seg_kind(kind):
314
+ name = seg_name(kind)
315
+ if (label, name) not in seg_proc.models:
316
+ seg_proc.request_method(exp, name)
317
+ started = time.perf_counter()
318
+ seg = seg_proc.run_model(label, data, name)
319
+ seg_seconds[name] = (
320
+ seg_seconds.get(name, 0.0) + time.perf_counter() - started
321
+ )
322
+ lab = np.asarray(seg.data)
323
+ objects[name] = len(np.unique(lab[lab > 0]))
324
+ labels_by_channel[(channel, name)] = lab
325
+ dock.add(seg)
326
+ elif kind == "tracks":
327
+ tracked = exp.tracking.segmentation
328
+ if (channel, tracked) not in labels_by_channel:
329
+ if (label, tracked) not in seg_proc.models:
330
+ seg_proc.request_method(exp, tracked)
331
+ seg = seg_proc.run_model(label, data, tracked)
332
+ labels_by_channel[(channel, tracked)] = np.asarray(seg.data)
333
+ method = tracking_proc.request_method(exp, channel)
334
+ lab, rows = method.track(labels_by_channel[(channel, tracked)], t, px)
335
+ dock.add(TrackingData(event, lab, rows))
336
+ labels_by_channel[(channel, "tracks")] = lab
337
+ if not dock.check_complete():
338
+ raise RuntimeError(f"preview could not gather {dock.get_awaiting()}")
339
+ if not frames:
340
+ # an open-loop method asks for nothing; still show the image it would light
341
+ frames[probe_channel] = probe
342
+
343
+ # -------------------------------------------------------- pattern
344
+ context = PatternContext(dock, exp, t=t, position=position)
345
+ started = time.perf_counter()
346
+ pattern = np.asarray(model.generate(context), dtype=np.float32)
347
+ generate_s = time.perf_counter() - started
348
+ result.pattern = pattern
349
+ result.requests = [c.describe() for c in context.requests]
350
+
351
+ # ---------------------------------------------------------- outputs
352
+ for channel, raw in frames.items():
353
+ path = out_dir / f"raw_{channel}.tif"
354
+ tifffile.imwrite(path, np.asarray(raw))
355
+ result.paths[f"raw {channel}"] = path
356
+ for (channel, name), lab in labels_by_channel.items():
357
+ path = out_dir / f"labels_{channel}_{name}.tif"
358
+ tifffile.imwrite(path, lab.astype(np.uint32 if name == "tracks" else np.uint16))
359
+ result.paths[f"labels {channel} {name}"] = path
360
+ camera_pattern = np.clip(pattern, 0, 1)
361
+ path = out_dir / "pattern_camera.tif"
362
+ tifffile.imwrite(path, camera_pattern.astype(np.float32))
363
+ result.paths["pattern (camera)"] = path
364
+ first = next(iter(frames.values()), None)
365
+ if first is not None:
366
+ path = out_dir / "pattern_overlay.png"
367
+ imsave(path, _overlay(first, camera_pattern), check_contrast=False)
368
+ result.paths["overlay"] = path
369
+ if config is not None:
370
+ slm = SLMBuffer(AllQueues())
371
+ slm.initialize(config.slm_shape, config.affine, [label], roi=config.camera_roi)
372
+ if geometry is not None:
373
+ # one DMD image per tile, stacked in tile order
374
+ dmd = np.stack(
375
+ [
376
+ slm.pattern_to_slm(tile, model.binning * source_binning)
377
+ for tile in cut(pattern, geometry, model.binning * source_binning)
378
+ ]
379
+ )
380
+ else:
381
+ dmd = slm.pattern_to_slm(pattern, model.binning * source_binning)
382
+ path = out_dir / "pattern_dmd.tif"
383
+ tifffile.imwrite(path, np.asarray(dmd, dtype=np.uint8))
384
+ result.paths["pattern (DMD)"] = path
385
+ dmd_lit = float((np.asarray(dmd) > 0).mean())
386
+ else:
387
+ dmd_lit = None
388
+ lit = float((pattern > 0).mean()) if pattern.size else 0.0
389
+
390
+ result.info = {
391
+ "experiment": stem,
392
+ "label": label,
393
+ "t": t,
394
+ "time_s": t * interval_s,
395
+ "source": source,
396
+ "pixel_size_um": px,
397
+ "binning": binning,
398
+ "source_binning": source_binning,
399
+ "grid": None if geometry is None else geometry.as_dict(),
400
+ "method": exp.pattern.method_name,
401
+ "kwargs": exp.pattern.kwargs,
402
+ "requirements": {by_id[r.id][0]: list(r.kinds) for r in reqs},
403
+ "segmentation_s": seg_seconds,
404
+ "objects": objects,
405
+ "generate_s": generate_s,
406
+ "lit_fraction": lit,
407
+ "dmd_lit_fraction": dmd_lit,
408
+ "requested_settings": result.requests,
409
+ "outputs": {k: str(v) for k, v in result.paths.items()},
410
+ }
411
+ path = out_dir / "preview.json"
412
+ path.write_text(json.dumps(result.info, indent=1, default=str), encoding="utf-8")
413
+ result.paths["summary"] = path
414
+ return result