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
@@ -0,0 +1,861 @@
1
+ """
2
+ OME-Zarr (NGFF 0.4, zarr v2) writer: PyCLM storage format 2.
3
+
4
+ Layout per experiment (``<experiment>.zarr/``):
5
+
6
+ .zattrs pyclm: {format: 2, plan, experiment, schedule, affine_transform,
7
+ slm_shape, groups: {...}, current_t, useq_version}
8
+ <group>/ one NGFF image per cadence group ("imaging", "stim", ...)
9
+ .zattrs multiscales (axes t,c,y,x; time scale = every_t * interval), omero
10
+ 0 (T, C, Y, X) uint16, chunks (1, 1, Y, X), zstd; compact T
11
+ labels/segmentation/0 (T, C, Y, X) uint16 label images (only if segmentation.save)
12
+ labels/<name>/0 the same for each named [segmentation.<name>] table
13
+ patterns/dmd/0 (N, H_slm, W_slm) uint8, one per distinct pattern_id
14
+ (policy "on_change"), or one per stimulation event ("all")
15
+ frames.parquet / frames.csv one row per acquired frame and per stimulation event
16
+
17
+ Skipped timepoints are never written: a chunk that was not acquired does not
18
+ exist on disk and reads as the fill value.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import datetime
24
+ import json
25
+ import logging
26
+ import shutil
27
+ from importlib.metadata import version as _pkg_version
28
+ from pathlib import Path
29
+ from time import sleep
30
+
31
+ import numcodecs
32
+ import numpy as np
33
+ import pyarrow as pa
34
+ import pyarrow.csv as pacsv
35
+ import pyarrow.parquet as pq
36
+ import zarr
37
+
38
+ from ..core_interface import MicroscopeCoreInterface
39
+ from ..datatypes import AcquisitionData, SegmentationData, StimulationData
40
+ from ..kinds import DEFAULT_SEGMENTATION, is_seg_kind, seg_name
41
+ from ..plan import AcquisitionPlan
42
+ from .base import (
43
+ PATTERN_POLICIES,
44
+ CadenceGroup,
45
+ FrameWriter,
46
+ cadence_groups,
47
+ image_shape,
48
+ )
49
+
50
+ logger = logging.getLogger(__name__)
51
+
52
+ STORAGE_FORMAT_VERSION = 3
53
+ NGFF_VERSION = "0.4"
54
+ FRAMES_COLUMNS = (
55
+ "experiment",
56
+ "kind",
57
+ "t",
58
+ "group",
59
+ "local_index",
60
+ "channel",
61
+ "scheduled_at",
62
+ "completed_at",
63
+ "exposure_ms",
64
+ "binning",
65
+ "x",
66
+ "y",
67
+ "z",
68
+ "pfs_offset",
69
+ "pattern_id",
70
+ "pattern_index",
71
+ "dmd_index",
72
+ "pixel_size_um",
73
+ )
74
+ TRACKS_COLUMNS = (
75
+ "experiment",
76
+ "t",
77
+ "channel",
78
+ "group",
79
+ "local_index",
80
+ "track_id",
81
+ "label",
82
+ "y",
83
+ "x",
84
+ "y_um",
85
+ "x_um",
86
+ "area",
87
+ "parent",
88
+ )
89
+ TRACKS_SCHEMA = pa.schema(
90
+ [
91
+ ("experiment", pa.string()),
92
+ ("t", pa.int32()),
93
+ ("channel", pa.string()),
94
+ ("group", pa.string()),
95
+ ("local_index", pa.int32()),
96
+ ("track_id", pa.int64()),
97
+ ("label", pa.int64()),
98
+ ("y", pa.float64()),
99
+ ("x", pa.float64()),
100
+ ("y_um", pa.float64()),
101
+ ("x_um", pa.float64()),
102
+ ("area", pa.int64()),
103
+ ("parent", pa.int64()),
104
+ ]
105
+ )
106
+
107
+
108
+ def _iso(timestamp) -> str | None:
109
+ if not timestamp:
110
+ return None
111
+ return datetime.datetime.fromtimestamp(timestamp).isoformat(timespec="milliseconds")
112
+
113
+
114
+ # Windows refuses to replace a file another process has open: the viewer
115
+ # re-reads .zgroup / .zattrs / .zarray every second, so a metadata write
116
+ # collides with it now and then. Retry with a short backoff before giving up.
117
+ _RETRY_DELAYS_S = (0.05, 0.1, 0.2, 0.4, 0.8)
118
+
119
+
120
+ def _retry_write(fn, what: str):
121
+ for attempt, delay in enumerate(_RETRY_DELAYS_S):
122
+ try:
123
+ return fn()
124
+ except PermissionError as e:
125
+ logger.warning(
126
+ f"{what}: {e.strerror or e} (attempt {attempt + 1}); retrying in {delay:.2f}s"
127
+ )
128
+ sleep(delay)
129
+ return fn()
130
+
131
+
132
+ def _set_attrs(node, meta: dict, what: str, key: str = "pyclm") -> None:
133
+ def put():
134
+ node.attrs[key] = meta
135
+
136
+ _retry_write(put, what)
137
+
138
+
139
+ def _update_attrs(node, attrs: dict, what: str) -> None:
140
+ _retry_write(lambda: node.attrs.update(attrs), what)
141
+
142
+
143
+ def _resize(arr, shape, what: str) -> None:
144
+ _retry_write(lambda: arr.resize(shape), what)
145
+
146
+
147
+ def _compressor():
148
+ return numcodecs.Blosc(cname="zstd", clevel=5, shuffle=numcodecs.Blosc.BITSHUFFLE)
149
+
150
+
151
+ def ngff_image_attrs(
152
+ name, axes_scale, channel_names, unit_time="second", unit_space="micrometer"
153
+ ):
154
+ """NGFF 0.4 multiscales + omero attributes for a (t, c, y, x) image."""
155
+ return {
156
+ "multiscales": [
157
+ {
158
+ "version": NGFF_VERSION,
159
+ "name": name,
160
+ "axes": [
161
+ {"name": "t", "type": "time", "unit": unit_time},
162
+ {"name": "c", "type": "channel"},
163
+ {"name": "y", "type": "space", "unit": unit_space},
164
+ {"name": "x", "type": "space", "unit": unit_space},
165
+ ],
166
+ "datasets": [
167
+ {
168
+ "path": "0",
169
+ "coordinateTransformations": [
170
+ {"type": "scale", "scale": [float(v) for v in axes_scale]}
171
+ ],
172
+ }
173
+ ],
174
+ }
175
+ ],
176
+ "omero": {
177
+ "channels": [
178
+ {"label": c, "active": True, "color": "FFFFFF"} for c in channel_names
179
+ ]
180
+ },
181
+ }
182
+
183
+
184
+ class _ExperimentStore:
185
+ """Open zarr handles and bookkeeping for one experiment."""
186
+
187
+ def __init__(self, root: zarr.Group, groups: list[CadenceGroup]):
188
+ self.root = root
189
+ self.groups = {g.name: g for g in groups}
190
+ self.images: dict[str, zarr.Array] = {}
191
+ # (cadence group, segmentation name) -> label array
192
+ self.labels: dict[tuple[str, str], zarr.Array] = {}
193
+ self.tracks: dict[str, zarr.Array] = {}
194
+ self.pattern_array: zarr.Array | None = None # patterns/dmd/0
195
+ self.pattern_ids: list[str] = [] # one per DMD image
196
+ self.dmd_camera_ids: list[
197
+ str
198
+ ] = [] # the camera pattern each DMD image came from
199
+ self.dmd_tiles: list = [] # [row, col] of the tile, None for a plain experiment
200
+ self.camera_array: zarr.Array | None = None # patterns/camera/0
201
+ self.camera_ids: list[str] = []
202
+ self.geometry = None # GridGeometry of a grid experiment
203
+ self.written: set[tuple[int, str]] = set() # (t, channel) frames written
204
+ self.written_groups: set[str] = set() # groups with at least one frame
205
+ self.current_t = -1
206
+
207
+ def group_for(self, channel: str) -> CadenceGroup | None:
208
+ for g in self.groups.values():
209
+ if channel in g.channels:
210
+ return g
211
+ return None
212
+
213
+
214
+ class OMEZarrWriter(FrameWriter):
215
+ format = "ome-zarr"
216
+
217
+ def __init__(self, pattern_policy: str = "on_change"):
218
+ super().__init__()
219
+ if pattern_policy not in PATTERN_POLICIES:
220
+ raise ValueError(f"pattern_policy must be one of {PATTERN_POLICIES}")
221
+ self.pattern_policy = pattern_policy
222
+ self.stores: dict[str, _ExperimentStore] = {}
223
+ self.rows: list[dict] = []
224
+ self.track_rows: list[dict] = []
225
+ self.dropped_frames = 0
226
+ self.error_count = 0
227
+ self.frames_path: Path | None = None
228
+ self.tracks_path: Path | None = None
229
+ self.routing: dict | None = None
230
+ self._pixel_size_um: float = 1.0
231
+
232
+ def planned_paths(self, names, base_path):
233
+ return {name: Path(base_path) / f"{name}.zarr" for name in names}
234
+
235
+ def output_paths(self):
236
+ return (
237
+ self.planned_paths(self.plan.experiments, self.base_path)
238
+ if self.plan
239
+ else {}
240
+ )
241
+
242
+ # ---------------------------------------------------------------- open
243
+ def open(
244
+ self,
245
+ plan,
246
+ core,
247
+ base_path,
248
+ affine_transform=None,
249
+ slm_shape=None,
250
+ recorded=None,
251
+ routing=None,
252
+ ):
253
+ self.plan = plan
254
+ self.recorded = recorded
255
+ self.routing = routing
256
+ self.base_path = Path(base_path)
257
+ self.base_path.mkdir(parents=True, exist_ok=True)
258
+ self.frames_path = self.base_path / "frames.parquet"
259
+ self.tracks_path = self.base_path / "tracks.parquet"
260
+ self._pixel_size_um = float(core.getPixelSizeUm())
261
+
262
+ slm_device = core.getSLMDevice()
263
+ if slm_shape is None and slm_device:
264
+ slm_shape = (core.getSLMHeight(slm_device), core.getSLMWidth(slm_device))
265
+
266
+ all_layers = []
267
+ try:
268
+ for exp_name in plan.experiments:
269
+ path = self.base_path / f"{exp_name}.zarr"
270
+ if path.exists():
271
+ raise FileExistsError(f"output already exists: {path}")
272
+ all_layers += self._open_experiment(
273
+ exp_name, path, core, affine_transform, slm_shape
274
+ )
275
+ except Exception:
276
+ self.close()
277
+ raise
278
+
279
+ self._write_frames_table()
280
+ self.is_open = True
281
+ return all_layers
282
+
283
+ def _open_experiment(self, exp_name, path, core, affine_transform, slm_shape):
284
+ plan = self.plan
285
+ experiment = plan.schedule.experiments[exp_name]
286
+ groups = cadence_groups(plan, exp_name)
287
+ geometry = getattr(plan.schedule.positions.get(exp_name), "geometry", None)
288
+ root = zarr.open_group(str(path), mode="w", zarr_format=2)
289
+ store = _ExperimentStore(root, groups)
290
+ store.geometry = geometry
291
+ layers = []
292
+
293
+ for g in groups:
294
+ h, w = image_shape(core, g.binning, geometry)
295
+ px = self._pixel_size_um * g.binning
296
+ img_group = root.create_group(g.name)
297
+ _update_attrs(
298
+ img_group,
299
+ ngff_image_attrs(
300
+ f"{exp_name}/{g.name}",
301
+ [g.every_t * plan.interval_s, 1.0, px, px],
302
+ g.channels,
303
+ ),
304
+ "writing image metadata",
305
+ )
306
+ _set_attrs(
307
+ img_group,
308
+ {
309
+ "channels": list(g.channels),
310
+ "stim_channel": g.stim_channel,
311
+ "every_t": g.every_t,
312
+ "t_delay": g.t_delay,
313
+ "t_stop": g.t_stop,
314
+ "binning": g.binning,
315
+ "timepoints": g.timepoints,
316
+ "interval_seconds": plan.interval_s,
317
+ },
318
+ "writing group metadata",
319
+ key="pyclm",
320
+ )
321
+ store.images[g.name] = img_group.create_array(
322
+ "0",
323
+ shape=(g.timepoints, len(g.channels), h, w),
324
+ chunks=(1, 1, h, w),
325
+ dtype="uint16",
326
+ compressors=_compressor(),
327
+ fill_value=0,
328
+ )
329
+ seg_names = self._recorded_segmentations(exp_name, g.channels)
330
+ record_tracks = any(self.records(exp_name, c, "tracks") for c in g.channels)
331
+ if seg_names or record_tracks:
332
+ labels = img_group.create_group("labels")
333
+ _set_attrs(
334
+ labels,
335
+ [
336
+ *seg_names,
337
+ *(["tracks"] if record_tracks else []),
338
+ ],
339
+ "writing labels metadata",
340
+ key="labels",
341
+ )
342
+ scale = [g.every_t * plan.interval_s, 1.0, px, px]
343
+ for seg in seg_names:
344
+ store.labels[(g.name, seg)] = self._label_array(
345
+ labels, seg, exp_name, g, scale, (h, w), "uint16"
346
+ )
347
+ if record_tracks:
348
+ store.tracks[g.name] = self._label_array(
349
+ labels, "tracks", exp_name, g, scale, (h, w), "uint32"
350
+ )
351
+ for c in g.channels:
352
+ layers.append((str(path.resolve()), f"{g.name}/{c}"))
353
+
354
+ if slm_shape is not None and self.pattern_policy != "none":
355
+ patterns = root.create_group("patterns/dmd")
356
+ _set_attrs(
357
+ patterns,
358
+ {
359
+ "policy": self.pattern_policy,
360
+ "pattern_ids": [],
361
+ "camera_ids": [],
362
+ "tiles": [],
363
+ },
364
+ "writing pattern metadata",
365
+ key="pyclm",
366
+ )
367
+ store.pattern_array = patterns.create_array(
368
+ "0",
369
+ shape=(0, int(slm_shape[0]), int(slm_shape[1])),
370
+ chunks=(1, int(slm_shape[0]), int(slm_shape[1])),
371
+ dtype="uint8",
372
+ compressors=_compressor(),
373
+ fill_value=0,
374
+ )
375
+ # the camera-space pattern the method returned, at the stimulation
376
+ # binning in the ROI frame; resized to the first pattern if the
377
+ # camera reports a different ROI (as the image groups are)
378
+ ch, cw = image_shape(core, experiment.stimulation.binning, geometry)
379
+ camera = root.create_group("patterns/camera")
380
+ _set_attrs(
381
+ camera,
382
+ {"policy": self.pattern_policy, "pattern_ids": []},
383
+ "writing pattern metadata",
384
+ key="pyclm",
385
+ )
386
+ store.camera_array = camera.create_array(
387
+ "0",
388
+ shape=(0, int(ch), int(cw)),
389
+ chunks=(1, int(ch), int(cw)),
390
+ dtype="uint8",
391
+ compressors=_compressor(),
392
+ fill_value=0,
393
+ )
394
+
395
+ _set_attrs(
396
+ root,
397
+ {
398
+ "format": STORAGE_FORMAT_VERSION,
399
+ "ngff_version": NGFF_VERSION,
400
+ "useq_version": _pkg_version("useq-schema"),
401
+ "pyclm_version": _pyclm_version(),
402
+ "experiment": exp_name,
403
+ "plan": plan.yaml_str(),
404
+ "experiment_metadata": experiment.as_dict(),
405
+ "schedule_metadata": plan.schedule.as_dict(),
406
+ "affine_transform": None
407
+ if affine_transform is None
408
+ else np.asarray(affine_transform, dtype=float).tolist(),
409
+ "slm_shape": None if slm_shape is None else [int(v) for v in slm_shape],
410
+ "camera_roi": [int(v) for v in core.getROI()],
411
+ "grid": None if geometry is None else geometry.as_dict(),
412
+ "pattern_policy": self.pattern_policy,
413
+ "routing": self.routing,
414
+ "groups": {
415
+ g.name: {
416
+ "channels": list(g.channels),
417
+ "every_t": g.every_t,
418
+ "t_delay": g.t_delay,
419
+ "t_stop": g.t_stop,
420
+ "binning": g.binning,
421
+ "timepoints": g.timepoints,
422
+ }
423
+ for g in groups
424
+ },
425
+ "plan_timepoints": plan.timepoints,
426
+ "current_t": -1,
427
+ },
428
+ "writing store metadata",
429
+ key="pyclm",
430
+ )
431
+ self.stores[exp_name] = store
432
+ logger.info(f"Initialized OME-Zarr store {path}")
433
+ return layers
434
+
435
+ def _recorded_segmentations(self, exp_name: str, channels) -> list[str]:
436
+ """Segmentation tables whose labels will reach the writer for these channels, default first."""
437
+ if self.recorded is not None:
438
+ names = {
439
+ seg_name(kind)
440
+ for kind, pairs in self.recorded.items()
441
+ if is_seg_kind(kind) and any((exp_name, c) in pairs for c in channels)
442
+ }
443
+ else:
444
+ exp = self.plan.schedule.experiments[exp_name]
445
+ names = set()
446
+ if any(self.records(exp_name, c, "seg") for c in channels):
447
+ names.add(DEFAULT_SEGMENTATION)
448
+ for n, cfg in exp.segmentations.items():
449
+ if n != DEFAULT_SEGMENTATION and cfg.method_name != "none" and cfg.save:
450
+ names.add(n)
451
+ return sorted(names, key=lambda n: (n != DEFAULT_SEGMENTATION, n))
452
+
453
+ @staticmethod
454
+ def _label_array(labels, name, exp_name, g, scale, shape, dtype):
455
+ """One NGFF label image (segmentation or tracks) under a cadence group."""
456
+ h, w = shape
457
+ grp = labels.create_group(name)
458
+ _update_attrs(
459
+ grp,
460
+ ngff_image_attrs(f"{exp_name}/{g.name}/{name}", scale, g.channels),
461
+ "writing label metadata",
462
+ )
463
+ _set_attrs(
464
+ grp,
465
+ {
466
+ "version": NGFF_VERSION,
467
+ "source": {"image": "../../"},
468
+ },
469
+ "writing label metadata",
470
+ key="image-label",
471
+ )
472
+ return grp.create_array(
473
+ "0",
474
+ shape=(g.timepoints, len(g.channels), h, w),
475
+ chunks=(1, 1, h, w),
476
+ dtype=dtype,
477
+ compressors=_compressor(),
478
+ fill_value=0,
479
+ )
480
+
481
+ # --------------------------------------------------------------- write
482
+ def _row(
483
+ self,
484
+ data: AcquisitionData,
485
+ kind: str,
486
+ group: str | None,
487
+ local_index,
488
+ channel,
489
+ pattern_id=None,
490
+ pattern_index=None,
491
+ dmd_index=None,
492
+ ) -> dict:
493
+ ev = data.event
494
+ pos = ev.position.as_dict()
495
+ row = {
496
+ "experiment": ev.experiment_name,
497
+ "kind": kind,
498
+ "t": int(ev.t_index),
499
+ "group": group,
500
+ "local_index": local_index,
501
+ "channel": channel,
502
+ "scheduled_at": _iso(ev.scheduled_time),
503
+ "completed_at": _iso(ev.completed_time),
504
+ "exposure_ms": float(ev.exposure_time_ms),
505
+ "binning": int(ev.binning),
506
+ "x": pos.get("x"),
507
+ "y": pos.get("y"),
508
+ "z": pos.get("z"),
509
+ "pfs_offset": pos.get("PFSOffset", pos.get("autofocus_offset")),
510
+ "pattern_id": None if pattern_id is None else str(pattern_id),
511
+ "pattern_index": pattern_index,
512
+ "dmd_index": dmd_index,
513
+ "pixel_size_um": None
514
+ if ev.pixel_width_um is None
515
+ else float(ev.pixel_width_um),
516
+ }
517
+ # settings a pattern method changed at runtime, in force for this frame
518
+ row.update(getattr(ev, "overrides", None) or {})
519
+ return row
520
+
521
+ def write_frame(self, data: AcquisitionData):
522
+ try:
523
+ ev = data.event
524
+ store = self.stores.get(ev.experiment_name)
525
+ if store is None:
526
+ logger.warning(f"no store for experiment {ev.experiment_name}")
527
+ return
528
+ channel = ev.index.get("c")
529
+ plan = self.plan
530
+
531
+ pattern_index = None
532
+ dmd_index = None
533
+ pattern_id = None
534
+ if isinstance(data, StimulationData):
535
+ pattern_id = data.pattern_id
536
+ pattern_index, dmd_index = self._record_pattern(
537
+ store, data, ev.experiment_name, ev.t_index
538
+ )
539
+ self.rows.append(
540
+ self._row(
541
+ data,
542
+ "stim_event",
543
+ None,
544
+ None,
545
+ channel,
546
+ pattern_id,
547
+ pattern_index,
548
+ dmd_index,
549
+ )
550
+ )
551
+
552
+ if ev.save_output:
553
+ g = store.group_for(channel)
554
+ i = None if g is None else g.local_index(ev.t_index)
555
+ if g is None or i is None:
556
+ self.dropped_frames += 1
557
+ logger.error(
558
+ f"no slot for frame {ev.index} of {ev.experiment_name}; dropped "
559
+ f"({self.dropped_frames} so far)"
560
+ )
561
+ else:
562
+ arr = store.images[g.name]
563
+ frame = np.asarray(data.data, dtype=np.uint16)
564
+ self._fit_group_shape(store, g, frame.shape)
565
+ arr[i, g.channel_index(channel)] = frame
566
+ store.written.add((ev.t_index, channel))
567
+ store.written_groups.add(g.name)
568
+ self.rows.append(
569
+ self._row(
570
+ data,
571
+ "frame",
572
+ g.name,
573
+ i,
574
+ channel,
575
+ pattern_id,
576
+ pattern_index,
577
+ dmd_index,
578
+ )
579
+ )
580
+
581
+ # progress counts every planned frame, saved or not (a stimulation event
582
+ # whose frame is not saved still completes its timepoint)
583
+ self._update_progress(store, ev.experiment_name, ev.t_index)
584
+ self._write_frames_table()
585
+ except Exception as e:
586
+ self.error_count += 1
587
+ logger.error(f"Failed to write frame: {e}", exc_info=True)
588
+
589
+ def write_skipped(self, data):
590
+ """A stimulation frame the microscope skipped: a row, and the slot counts as done."""
591
+ try:
592
+ ev = data.event
593
+ store = self.stores.get(ev.experiment_name)
594
+ if store is None:
595
+ return
596
+ channel = ev.index.get("c")
597
+ self.rows.append(self._row(data, "skipped", None, None, channel))
598
+ store.written.add((ev.t_index, channel))
599
+ self._update_progress(store, ev.experiment_name, ev.t_index)
600
+ self._write_frames_table()
601
+ except Exception as e:
602
+ self.error_count += 1
603
+ logger.error(f"Failed to record a skipped frame: {e}", exc_info=True)
604
+
605
+ def _fit_group_shape(self, store: _ExperimentStore, g: CadenceGroup, shape):
606
+ """
607
+ Resize a group's arrays to the first frame's shape if the camera ROI
608
+ reported at open time disagrees with what was delivered (the HDF5
609
+ writer tolerated this by resizing datasets; the simulator relies on it).
610
+ """
611
+ arr = store.images[g.name]
612
+ if tuple(arr.shape[2:]) == tuple(shape):
613
+ return
614
+ if g.name in store.written_groups:
615
+ raise ValueError(
616
+ f"frame shape {shape} does not match {g.name} array {arr.shape[2:]}"
617
+ )
618
+ logger.info(f"{g.name}: resizing arrays from {arr.shape[2:]} to {shape}")
619
+ _resize(
620
+ arr,
621
+ (arr.shape[0], arr.shape[1], *shape),
622
+ f"{g.name}: fitting the frame shape",
623
+ )
624
+ extras = [a for (gname, _n), a in store.labels.items() if gname == g.name]
625
+ if g.name in store.tracks:
626
+ extras.append(store.tracks[g.name])
627
+ for lab in extras:
628
+ _resize(
629
+ lab,
630
+ (lab.shape[0], lab.shape[1], *shape),
631
+ f"{g.name}: fitting the label shape",
632
+ )
633
+
634
+ def _record_pattern(
635
+ self, store: _ExperimentStore, data: StimulationData, exp_name: str, t: int
636
+ ) -> tuple[int | None, int | None]:
637
+ """
638
+ Store the pattern of a stimulation event according to the policy.
639
+ Returns ``(camera index, dmd index)`` into ``patterns/camera/0`` and
640
+ ``patterns/dmd/0``; None where nothing was stored.
641
+ """
642
+ if store.pattern_array is None or self.pattern_policy == "none":
643
+ return None, None
644
+ if self.pattern_policy == "imaging" and not any(
645
+ ds.save and not ds.is_stim for ds in self.plan.datasets_at(exp_name, t)
646
+ ):
647
+ return None, None
648
+ pid = str(data.pattern_id)
649
+
650
+ # DMD image (one per tile for a grid experiment, contiguous in tile order)
651
+ if isinstance(data.dmd_pattern, list | tuple):
652
+ images = list(data.dmd_pattern)
653
+ ids = list(data.dmd_ids or [f"{pid}:{k}" for k in range(len(images))])
654
+ tiles = (
655
+ [list(rc) for rc in store.geometry.tiles]
656
+ if store.geometry is not None
657
+ else [None] * len(images)
658
+ )
659
+ else:
660
+ images, ids, tiles = [data.dmd_pattern], [pid], [None]
661
+ if ids[0] in store.pattern_ids:
662
+ dmd_index = store.pattern_ids.index(ids[0])
663
+ else:
664
+ dmd_index = None
665
+ for image, dmd_id, tile in zip(images, ids, tiles, strict=True):
666
+ n = self._append(store.pattern_array, image)
667
+ dmd_index = n if dmd_index is None else dmd_index
668
+ store.pattern_ids.append(dmd_id)
669
+ store.dmd_camera_ids.append(pid)
670
+ store.dmd_tiles.append(tile)
671
+ grp = store.root["patterns/dmd"]
672
+ meta = dict(grp.attrs.get("pyclm", {}))
673
+ meta["pattern_ids"] = list(store.pattern_ids)
674
+ meta["camera_ids"] = list(store.dmd_camera_ids)
675
+ meta["tiles"] = list(store.dmd_tiles)
676
+ _set_attrs(grp, meta, f"{exp_name}: recording DMD pattern ids")
677
+
678
+ # camera-space pattern (absent for the blank pattern before the first generate)
679
+ camera_index = None
680
+ if store.camera_array is not None and data.camera_pattern is not None:
681
+ if pid in store.camera_ids:
682
+ camera_index = store.camera_ids.index(pid)
683
+ else:
684
+ cam = np.asarray(data.camera_pattern, dtype=np.uint8)
685
+ arr = store.camera_array
686
+ if arr.shape[0] == 0 and tuple(arr.shape[1:]) != cam.shape:
687
+ arr.resize((0, *cam.shape))
688
+ camera_index = self._append(arr, cam)
689
+ store.camera_ids.append(pid)
690
+ grp = store.root["patterns/camera"]
691
+ meta = dict(grp.attrs.get("pyclm", {}))
692
+ meta["pattern_ids"] = list(store.camera_ids)
693
+ _set_attrs(grp, meta, f"{exp_name}: recording camera pattern ids")
694
+ return camera_index, dmd_index
695
+
696
+ @staticmethod
697
+ def _append(arr: zarr.Array, image) -> int:
698
+ n = arr.shape[0]
699
+ _resize(arr, (n + 1, *arr.shape[1:]), "growing the pattern array")
700
+ arr[n] = np.asarray(image, dtype=np.uint8)
701
+ return n
702
+
703
+ def write_labels(self, data: SegmentationData):
704
+ try:
705
+ ev = data.event
706
+ store = self.stores.get(ev.experiment_name)
707
+ if store is None:
708
+ return
709
+ channel = ev.index.get("c")
710
+ g = store.group_for(channel)
711
+ if g is None:
712
+ return
713
+ key = (g.name, getattr(data, "name", DEFAULT_SEGMENTATION))
714
+ if key not in store.labels:
715
+ return
716
+ i = g.local_index(ev.t_index)
717
+ if i is None:
718
+ return
719
+ store.labels[key][i, g.channel_index(channel)] = np.asarray(
720
+ data.data, dtype=np.uint16
721
+ )
722
+ except Exception as e:
723
+ self.error_count += 1
724
+ logger.error(f"Failed to write labels: {e}", exc_info=True)
725
+
726
+ def write_tracks(self, data):
727
+ try:
728
+ ev = data.event
729
+ store = self.stores.get(ev.experiment_name)
730
+ if store is None:
731
+ return
732
+ channel = ev.index.get("c")
733
+ g = store.group_for(channel)
734
+ if g is None or g.name not in store.tracks:
735
+ return
736
+ i = g.local_index(ev.t_index)
737
+ if i is None:
738
+ return
739
+ labels = np.asarray(data.data, dtype=np.uint32)
740
+ self._fit_group_shape(store, g, labels.shape)
741
+ store.tracks[g.name][i, g.channel_index(channel)] = labels
742
+
743
+ px = ev.pixel_width_um
744
+ if not px:
745
+ px = self._pixel_size_um * g.binning
746
+ for r in data.rows:
747
+ self.track_rows.append(
748
+ {
749
+ "experiment": ev.experiment_name,
750
+ "t": int(ev.t_index),
751
+ "channel": channel,
752
+ "group": g.name,
753
+ "local_index": int(i),
754
+ "track_id": int(r.track_id),
755
+ "label": int(r.label),
756
+ "y": float(r.y),
757
+ "x": float(r.x),
758
+ "y_um": float(r.y) * float(px),
759
+ "x_um": float(r.x) * float(px),
760
+ "area": int(r.area),
761
+ "parent": int(r.parent),
762
+ }
763
+ )
764
+ self._write_tracks_table()
765
+ except Exception as e:
766
+ self.error_count += 1
767
+ logger.error(f"Failed to write tracks: {e}", exc_info=True)
768
+
769
+ def _update_progress(self, store: _ExperimentStore, exp_name: str, t: int):
770
+ if t <= store.current_t:
771
+ return
772
+ for ds in self.plan.datasets_at(exp_name, t):
773
+ if ds.save and (t, ds.channel) not in store.written:
774
+ return
775
+ store.current_t = t
776
+ meta = dict(store.root.attrs["pyclm"])
777
+ meta["current_t"] = t
778
+ _set_attrs(store.root, meta, f"{exp_name}: recording current_t = {t}")
779
+
780
+ def _frames_table(self) -> pa.Table:
781
+ columns = {k: [r.get(k) for r in self.rows] for k in FRAMES_COLUMNS}
782
+ schema = pa.schema(
783
+ [
784
+ ("experiment", pa.string()),
785
+ ("kind", pa.string()),
786
+ ("t", pa.int32()),
787
+ ("group", pa.string()),
788
+ ("local_index", pa.int32()),
789
+ ("channel", pa.string()),
790
+ ("scheduled_at", pa.string()),
791
+ ("completed_at", pa.string()),
792
+ ("exposure_ms", pa.float64()),
793
+ ("binning", pa.int16()),
794
+ ("x", pa.float64()),
795
+ ("y", pa.float64()),
796
+ ("z", pa.float64()),
797
+ ("pfs_offset", pa.float64()),
798
+ ("pattern_id", pa.string()),
799
+ ("pattern_index", pa.int32()),
800
+ ("dmd_index", pa.int32()),
801
+ ("pixel_size_um", pa.float64()),
802
+ ]
803
+ )
804
+ table = pa.table(columns, schema=schema)
805
+ # one column per setting a pattern method changed during the run
806
+ extras = sorted({k for r in self.rows for k in r if k not in FRAMES_COLUMNS})
807
+ for key in extras:
808
+ values = [r.get(key) for r in self.rows]
809
+ try:
810
+ column = pa.array(values)
811
+ except (pa.ArrowInvalid, pa.ArrowTypeError):
812
+ column = pa.array([None if v is None else str(v) for v in values])
813
+ table = table.append_column(key, column)
814
+ return table
815
+
816
+ def _write_frames_table(self):
817
+ if self.frames_path is None:
818
+ return
819
+ self._write_parquet(self._frames_table(), self.frames_path)
820
+
821
+ def _tracks_table(self) -> pa.Table:
822
+ columns = {k: [r.get(k) for r in self.track_rows] for k in TRACKS_COLUMNS}
823
+ return pa.table(columns, schema=TRACKS_SCHEMA)
824
+
825
+ def _write_tracks_table(self):
826
+ if self.tracks_path is None:
827
+ return
828
+ self._write_parquet(self._tracks_table(), self.tracks_path)
829
+
830
+ @staticmethod
831
+ def _write_parquet(table: pa.Table, path: Path):
832
+ tmp = path.with_suffix(".parquet.tmp")
833
+ pq.write_table(table, tmp)
834
+ _retry_write(lambda: shutil.move(str(tmp), str(path)), f"writing {path.name}")
835
+
836
+ # --------------------------------------------------------------- close
837
+ def close(self):
838
+ if self.frames_path is not None and self.rows:
839
+ try:
840
+ self._write_frames_table()
841
+ pacsv.write_csv(
842
+ self._frames_table(), self.frames_path.with_suffix(".csv")
843
+ )
844
+ except Exception as e:
845
+ logger.error(f"failed to finalise frames table: {e}", exc_info=True)
846
+ if self.tracks_path is not None and self.track_rows:
847
+ try:
848
+ self._write_tracks_table()
849
+ pacsv.write_csv(
850
+ self._tracks_table(), self.tracks_path.with_suffix(".csv")
851
+ )
852
+ except Exception as e:
853
+ logger.error(f"failed to finalise tracks table: {e}", exc_info=True)
854
+ self.stores.clear()
855
+ self.is_open = False
856
+
857
+
858
+ def _pyclm_version() -> str:
859
+ from pyclm import __version__
860
+
861
+ return __version__