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/io/readers.py ADDED
@@ -0,0 +1,589 @@
1
+ """
2
+ Read PyCLM output in any format it has written: the original HDF5 layout
3
+ (format 1) and OME-Zarr (format 2). One API for the GUI, the exporter, and
4
+ analysis code.
5
+
6
+ exp = pyclm.io.open("bar10.pos1.zarr") # or "bar10.pos1.hdf5"
7
+ g = exp.groups["imaging"] # a cadence group
8
+ g.frame(i, "545") # numpy array or None if not (yet) acquired
9
+ g.labels(i, "545") # segmentation labels or None
10
+ g.labels(i, "545", "nuclei") # labels of a named [segmentation.nuclei] table
11
+ g.global_t(i) # plan timepoint of slot i
12
+ exp.pattern_at(t) # DMD pattern in force at plan timepoint t
13
+ exp.frames # pyarrow.Table (format 2) or None
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import json
19
+ import sys
20
+ from abc import ABC, abstractmethod
21
+ from pathlib import Path
22
+
23
+ import numpy as np
24
+
25
+
26
+ class GroupData(ABC):
27
+ """One image: channels sharing a cadence, compact time axis."""
28
+
29
+ name: str
30
+ channels: tuple[str, ...]
31
+ every_t: int
32
+ t_delay: int
33
+ t_stop: int
34
+ timepoints: int
35
+ binning: int
36
+ interval_s: float | None = None # plan interval in seconds
37
+ pixel_size_um: float | None = None # at this group's binning
38
+
39
+ def local_index(self, t: int) -> int | None:
40
+ this_t = t - self.t_delay
41
+ if this_t < 0 or this_t % self.every_t != 0:
42
+ return None
43
+ if self.t_stop > 0 and this_t >= self.t_stop:
44
+ return None
45
+ return this_t // self.every_t
46
+
47
+ def global_t(self, i: int) -> int:
48
+ return self.t_delay + i * self.every_t
49
+
50
+ @property
51
+ @abstractmethod
52
+ def shape(self) -> tuple[int, int]:
53
+ """(height, width) of one frame."""
54
+
55
+ @abstractmethod
56
+ def acquired(self) -> list[int]:
57
+ """Slots that hold at least one written channel, ascending."""
58
+
59
+ @abstractmethod
60
+ def frame(self, i: int, channel: str) -> np.ndarray | None: ...
61
+
62
+ @abstractmethod
63
+ def labels(
64
+ self, i: int, channel: str, name: str = "segmentation"
65
+ ) -> np.ndarray | None:
66
+ """Label image of a slot from the segmentation table ``name``, or None."""
67
+
68
+ @property
69
+ def has_labels(self) -> bool:
70
+ return bool(self.label_names)
71
+
72
+ @property
73
+ def label_names(self) -> tuple[str, ...]:
74
+ """Segmentation tables stored for this group (the default one is ``"segmentation"``)."""
75
+ return ()
76
+
77
+ def tracks(self, i: int, channel: str) -> np.ndarray | None:
78
+ """Label image relabelled with track ids for a slot, or None."""
79
+ return None
80
+
81
+ @property
82
+ def has_tracks(self) -> bool:
83
+ return False
84
+
85
+
86
+ class ExperimentData(ABC):
87
+ """Everything PyCLM stored for one experiment (one position)."""
88
+
89
+ format: int
90
+ path: Path
91
+ name: str
92
+ groups: dict[str, GroupData]
93
+ affine_transform: np.ndarray | None
94
+ camera_roi: tuple[int, int, int, int] | None = None
95
+ slm_shape: tuple[int, int] | None
96
+ plan_yaml: str | None
97
+
98
+ @property
99
+ @abstractmethod
100
+ def current_t(self) -> int:
101
+ """Highest plan timepoint whose saved frames are all written, or -1."""
102
+
103
+ @abstractmethod
104
+ def pattern_at(self, t: int) -> np.ndarray | None:
105
+ """DMD-space pattern in force at plan timepoint ``t`` (latest at or before ``t``)."""
106
+
107
+ def camera_pattern_at(self, t: int) -> np.ndarray | None:
108
+ """
109
+ Camera-space pattern (uint8 0-255, stimulation binning, ROI frame) in
110
+ force at plan timepoint ``t``; None when the store has none (HDF5, or
111
+ OME-Zarr written before format 3).
112
+ """
113
+ return None
114
+
115
+ @property
116
+ def frames(self):
117
+ """The frames table rows for this experiment (pyarrow), or None."""
118
+ return None
119
+
120
+ @property
121
+ def tracks(self):
122
+ """The tracks table rows for this experiment (pyarrow), or None."""
123
+ return None
124
+
125
+ @property
126
+ def events(self):
127
+ """
128
+ Runtime events of this experiment (pyarrow): setting changes a
129
+ pattern method requested, late timepoints, acquisition errors. From
130
+ ``events.parquet`` in the experiment directory; None if absent.
131
+ """
132
+ path = Path(self.path).parent / "events.parquet"
133
+ if not path.exists():
134
+ return None
135
+ import pyarrow.parquet as pq
136
+
137
+ table = pq.read_table(path)
138
+ mask = np.asarray(
139
+ table["experiment"].to_numpy(zero_copy_only=False) == self.name
140
+ )
141
+ return table.filter(mask)
142
+
143
+ def refresh(self) -> None:
144
+ """Re-read metadata that changes while the experiment is running."""
145
+ return None
146
+
147
+ def close(self) -> None:
148
+ return None
149
+
150
+ def __enter__(self):
151
+ return self
152
+
153
+ def __exit__(self, *exc):
154
+ self.close()
155
+
156
+
157
+ # ============================================================ OME-Zarr (format 2)
158
+ class _ZarrGroup(GroupData):
159
+ @staticmethod
160
+ def _path_for(root_path, name):
161
+ return root_path / name
162
+
163
+ def __init__(
164
+ self,
165
+ root_path: Path,
166
+ name: str,
167
+ meta: dict,
168
+ label_names=(),
169
+ has_tracks: bool = False,
170
+ ):
171
+ import zarr
172
+
173
+ self.name = name
174
+ self.channels = tuple(meta["channels"])
175
+ self.every_t = int(meta["every_t"])
176
+ self.t_delay = int(meta["t_delay"])
177
+ self.t_stop = int(meta["t_stop"])
178
+ self.timepoints = int(meta["timepoints"])
179
+ self.binning = int(meta["binning"])
180
+ self.interval_s = meta.get("interval_seconds")
181
+ self.pixel_size_um = None
182
+ try:
183
+ import zarr
184
+
185
+ scale = zarr.open_group(
186
+ str(self._path_for(root_path, name)), mode="r"
187
+ ).attrs["multiscales"][0]["datasets"][0]["coordinateTransformations"][0][
188
+ "scale"
189
+ ]
190
+ self.pixel_size_um = float(scale[-1])
191
+ if self.interval_s is None and self.every_t:
192
+ self.interval_s = float(scale[0]) / self.every_t
193
+ except Exception:
194
+ pass
195
+ self._path = root_path / name
196
+ self._arr = zarr.open_array(str(self._path / "0"), mode="r")
197
+ self._labels = {
198
+ n: zarr.open_array(str(self._path / "labels" / n / "0"), mode="r")
199
+ for n in label_names
200
+ }
201
+ self._tracks = (
202
+ zarr.open_array(str(self._path / "labels" / "tracks" / "0"), mode="r")
203
+ if has_tracks
204
+ else None
205
+ )
206
+
207
+ @property
208
+ def shape(self):
209
+ return tuple(int(v) for v in self._arr.shape[2:])
210
+
211
+ @property
212
+ def label_names(self):
213
+ return tuple(self._labels)
214
+
215
+ @property
216
+ def has_tracks(self):
217
+ return self._tracks is not None
218
+
219
+ def _chunk_exists(self, i: int, c: int, labels=None, tracks=False) -> bool:
220
+ if tracks:
221
+ base = self._path / "labels" / "tracks" / "0"
222
+ elif labels:
223
+ base = self._path / "labels" / str(labels) / "0"
224
+ else:
225
+ base = self._path / "0"
226
+ return (base / f"{i}.{c}.0.0").exists()
227
+
228
+ def acquired(self):
229
+ return [
230
+ i
231
+ for i in range(self._arr.shape[0])
232
+ if any(self._chunk_exists(i, c) for c in range(len(self.channels)))
233
+ ]
234
+
235
+ def frame(self, i, channel):
236
+ c = self.channels.index(channel)
237
+ if not self._chunk_exists(i, c):
238
+ return None
239
+ return np.asarray(self._arr[i, c])
240
+
241
+ def labels(self, i, channel, name="segmentation"):
242
+ arr = self._labels.get(name)
243
+ if arr is None:
244
+ return None
245
+ c = self.channels.index(channel)
246
+ if not self._chunk_exists(i, c, labels=name):
247
+ return None
248
+ return np.asarray(arr[i, c])
249
+
250
+ def tracks(self, i, channel):
251
+ if self._tracks is None:
252
+ return None
253
+ c = self.channels.index(channel)
254
+ if not self._chunk_exists(i, c, tracks=True):
255
+ return None
256
+ return np.asarray(self._tracks[i, c])
257
+
258
+
259
+ class ZarrExperiment(ExperimentData):
260
+ format = 2
261
+
262
+ def __init__(self, path):
263
+ import zarr
264
+
265
+ self.path = Path(path)
266
+ self._root = zarr.open_group(str(self.path), mode="r")
267
+ meta = dict(self._root.attrs["pyclm"])
268
+ self._meta = meta
269
+ self.format = int(meta.get("format", 2))
270
+ self.name = meta["experiment"]
271
+ self.plan_yaml = meta.get("plan")
272
+ at = meta.get("affine_transform")
273
+ self.affine_transform = None if at is None else np.asarray(at, dtype=np.float32)
274
+ self.slm_shape = (
275
+ None if meta.get("slm_shape") is None else tuple(meta["slm_shape"])
276
+ )
277
+ roi = meta.get("camera_roi")
278
+ self.camera_roi = None if roi is None else tuple(int(v) for v in roi)
279
+ # rows, columns, pitch, tile shape and tile order of a grid experiment
280
+ self.grid = meta.get("grid")
281
+ self.groups = {
282
+ name: _ZarrGroup(
283
+ self.path,
284
+ name,
285
+ gmeta,
286
+ self._label_names(self.path / name / "labels"),
287
+ (self.path / name / "labels" / "tracks" / "0").exists(),
288
+ )
289
+ for name, gmeta in meta["groups"].items()
290
+ }
291
+ self._frames_path = self.path.parent / "frames.parquet"
292
+ self._frames = None
293
+ self._tracks_path = self.path.parent / "tracks.parquet"
294
+ self._tracks = None
295
+ self._pattern_arr = None
296
+ if (self.path / "patterns" / "dmd" / "0").exists():
297
+ self._pattern_arr = zarr.open_array(
298
+ str(self.path / "patterns" / "dmd" / "0"), mode="r"
299
+ )
300
+ self._camera_arr = None
301
+ if (self.path / "patterns" / "camera" / "0").exists():
302
+ self._camera_arr = zarr.open_array(
303
+ str(self.path / "patterns" / "camera" / "0"), mode="r"
304
+ )
305
+
306
+ @staticmethod
307
+ def _label_names(labels_dir: Path) -> tuple[str, ...]:
308
+ """Segmentation label images under a group (NGFF ``labels`` list, minus tracks)."""
309
+ attrs = labels_dir / ".zattrs"
310
+ names: list[str] = []
311
+ if attrs.exists():
312
+ try:
313
+ names = list(json.loads(attrs.read_text()).get("labels", []))
314
+ except Exception:
315
+ names = []
316
+ if not names and labels_dir.exists():
317
+ names = sorted(p.name for p in labels_dir.iterdir() if p.is_dir())
318
+ return tuple(
319
+ n for n in names if n != "tracks" and (labels_dir / n / "0").exists()
320
+ )
321
+
322
+ def refresh(self):
323
+ import zarr
324
+
325
+ self._root = zarr.open_group(str(self.path), mode="r")
326
+ self._meta = dict(self._root.attrs["pyclm"])
327
+ self._frames = None
328
+ self._tracks = None
329
+ for g in self.groups.values():
330
+ g._arr = zarr.open_array(str(g._path / "0"), mode="r")
331
+ for n in list(g._labels):
332
+ g._labels[n] = zarr.open_array(
333
+ str(g._path / "labels" / n / "0"), mode="r"
334
+ )
335
+ if g._tracks is not None:
336
+ g._tracks = zarr.open_array(
337
+ str(g._path / "labels" / "tracks" / "0"), mode="r"
338
+ )
339
+ if self._pattern_arr is not None:
340
+ self._pattern_arr = zarr.open_array(
341
+ str(self.path / "patterns" / "dmd" / "0"), mode="r"
342
+ )
343
+ if self._camera_arr is not None:
344
+ self._camera_arr = zarr.open_array(
345
+ str(self.path / "patterns" / "camera" / "0"), mode="r"
346
+ )
347
+
348
+ @property
349
+ def current_t(self):
350
+ return int(self._meta.get("current_t", -1))
351
+
352
+ def _read_rows(self, path):
353
+ import pyarrow.parquet as pq
354
+
355
+ table = pq.read_table(path)
356
+ mask = np.asarray(
357
+ table["experiment"].to_numpy(zero_copy_only=False) == self.name
358
+ )
359
+ return table.filter(mask)
360
+
361
+ @property
362
+ def frames(self):
363
+ if self._frames is None and self._frames_path.exists():
364
+ self._frames = self._read_rows(self._frames_path)
365
+ return self._frames
366
+
367
+ @property
368
+ def tracks(self):
369
+ if self._tracks is None and self._tracks_path.exists():
370
+ self._tracks = self._read_rows(self._tracks_path)
371
+ return self._tracks
372
+
373
+ @property
374
+ def routing(self) -> dict | None:
375
+ """The resolved routing table recorded at the start of the run, if any."""
376
+ return self._meta.get("routing")
377
+
378
+ def _pattern_index_at(self, t: int, column: str = "pattern_index") -> int | None:
379
+ table = self.frames
380
+ if table is None or table.num_rows == 0 or column not in table.column_names:
381
+ return None
382
+ kinds = table["kind"].to_pylist()
383
+ ts = table["t"].to_pylist()
384
+ idx = table[column].to_pylist()
385
+ best = None
386
+ for k, tt, pi in zip(kinds, ts, idx, strict=False):
387
+ if (
388
+ k == "stim_event"
389
+ and pi is not None
390
+ and tt <= t
391
+ and (best is None or tt >= best[0])
392
+ ):
393
+ best = (tt, pi)
394
+ return None if best is None else int(best[1])
395
+
396
+ def pattern_at(self, t):
397
+ if self._pattern_arr is None:
398
+ return None
399
+ # format 2 stores indexed the DMD array with pattern_index
400
+ column = "dmd_index" if self.format >= 3 else "pattern_index"
401
+ i = self._pattern_index_at(t, column)
402
+ if i is None or i >= self._pattern_arr.shape[0]:
403
+ return None
404
+ return np.asarray(self._pattern_arr[i])
405
+
406
+ def camera_pattern_at(self, t):
407
+ if self._camera_arr is None:
408
+ return None
409
+ i = self._pattern_index_at(t, "pattern_index")
410
+ if i is None or i >= self._camera_arr.shape[0]:
411
+ return None
412
+ return np.asarray(self._camera_arr[i])
413
+
414
+ @property
415
+ def pattern_ids(self) -> list[str]:
416
+ try:
417
+ return list(self._root["patterns/dmd"].attrs["pyclm"]["pattern_ids"])
418
+ except KeyError:
419
+ return []
420
+
421
+
422
+ # ============================================================ HDF5 (format 1)
423
+ class _HDF5Group(GroupData):
424
+ """One channel of the v1 layout, presented as a single-channel group."""
425
+
426
+ def __init__(self, exp: HDF5Experiment, key: str, every_t: int):
427
+ self._exp = exp
428
+ self.key = key # "channel_545" or "stim_aq"
429
+ self.name = key if key == "stim_aq" else key.replace("channel_", "imaging_", 1)
430
+ self.channels = (
431
+ "stim" if key == "stim_aq" else key.replace("channel_", "", 1),
432
+ )
433
+ self.every_t = every_t
434
+ self.t_delay = exp._t_delay
435
+ self.t_stop = exp._t_stop
436
+ self.timepoints = sum(
437
+ 1 for t in range(exp._t_count) if self.local_index(t) is not None
438
+ )
439
+ self.binning = exp._binning_for(key)
440
+ self.interval_s = exp._interval_s
441
+ self.pixel_size_um = None
442
+ self._shape = None
443
+
444
+ @property
445
+ def shape(self):
446
+ if self._shape is None:
447
+ self._read_pixel_size()
448
+ for i in self.acquired():
449
+ fr = self.frame(i, self.channels[0])
450
+ if fr is not None:
451
+ self._shape = fr.shape
452
+ break
453
+ return self._shape or (0, 0)
454
+
455
+ @property
456
+ def label_names(self):
457
+ # v1 pre-allocates empty seg datasets for every channel; only a written one counts
458
+ if any(self._dset(i, "seg") is not None for i in self.acquired()):
459
+ return ("segmentation",)
460
+ return ()
461
+
462
+ def _read_pixel_size(self):
463
+ f = self._exp._file
464
+ for i in self.acquired():
465
+ key = f"{self.global_t(i):05d}/{self.key}/data"
466
+ val = f[key].attrs.get("pixel_width_um", "")
467
+ try:
468
+ self.pixel_size_um = float(val)
469
+ return
470
+ except (TypeError, ValueError):
471
+ continue
472
+
473
+ def _dset(self, i, name):
474
+ f = self._exp._file
475
+ key = f"{self.global_t(i):05d}/{self.key}/{name}"
476
+ if key not in f:
477
+ return None
478
+ d = f[key]
479
+ try:
480
+ d.id.refresh()
481
+ except Exception:
482
+ pass
483
+ if 0 in d.shape:
484
+ return None
485
+ return np.asarray(d)
486
+
487
+ def acquired(self):
488
+ return [i for i in range(self.timepoints) if self._dset(i, "data") is not None]
489
+
490
+ def frame(self, i, channel):
491
+ return self._dset(i, "data")
492
+
493
+ def labels(self, i, channel, name="segmentation"):
494
+ if name != "segmentation":
495
+ return None
496
+ return self._dset(i, "seg")
497
+
498
+
499
+ class HDF5Experiment(ExperimentData):
500
+ format = 1
501
+
502
+ def __init__(self, path):
503
+ import h5py
504
+
505
+ self.path = Path(path)
506
+ self.name = self.path.stem
507
+ self._file = h5py.File(str(self.path), mode="r", libver="latest", swmr=True)
508
+ attrs = self._file.attrs
509
+ self.plan_yaml = attrs.get("plan")
510
+ at = attrs.get("affine_transform")
511
+ self.affine_transform = None if at is None else np.asarray(at, dtype=np.float32)
512
+ self.slm_shape = None
513
+ self._t_delay = int(attrs.get("t_delay", 0))
514
+ self._t_stop = int(attrs.get("t_stop", 0))
515
+ self._t_count = int(attrs.get("t_count", 0)) or len(
516
+ [k for k in self._file.keys() if k[:1].isdigit()]
517
+ )
518
+ every_t = json.loads(attrs.get("every_t", "{}"))
519
+ self._experiment_meta = json.loads(attrs.get("experiment_metadata", "{}"))
520
+ schedule_meta = json.loads(attrs.get("schedule_metadata", "{}"))
521
+ self._interval_s = schedule_meta.get("times", {}).get("interval")
522
+ self.groups = {}
523
+ for key, n in every_t.items():
524
+ g = _HDF5Group(self, key, int(n))
525
+ self.groups[g.name] = g
526
+
527
+ def _binning_for(self, key: str) -> int:
528
+ meta = self._experiment_meta
529
+ if key == "stim_aq":
530
+ return int(meta.get("stimulation", {}).get("binning", 1))
531
+ short = key.replace("channel_", "", 1)
532
+ return int(meta.get("channels", {}).get(short, {}).get("binning", 1))
533
+
534
+ def refresh(self):
535
+ # SWMR readers on Windows do not always see new data through one handle
536
+ if sys.platform == "win32":
537
+ import h5py
538
+
539
+ self._file.close()
540
+ self._file = h5py.File(str(self.path), mode="r", libver="latest", swmr=True)
541
+
542
+ def close(self):
543
+ try:
544
+ self._file.close()
545
+ except Exception:
546
+ pass
547
+
548
+ @property
549
+ def current_t(self):
550
+ try:
551
+ d = self._file["current_t_index"]
552
+ d.id.refresh()
553
+ return int(d[()])
554
+ except Exception:
555
+ return -1
556
+
557
+ def pattern_at(self, t):
558
+ f = self._file
559
+ for tt in range(t, -1, -1):
560
+ key = f"{tt:05d}/stim_aq/dmd"
561
+ if key in f:
562
+ d = f[key]
563
+ try:
564
+ d.id.refresh()
565
+ except Exception:
566
+ pass
567
+ if 0 not in d.shape:
568
+ return np.asarray(d)
569
+ return None
570
+
571
+
572
+ def open(path) -> ExperimentData:
573
+ """Open a PyCLM experiment output, whichever format it was written in."""
574
+ path = Path(path)
575
+ if path.is_dir() and (path / ".zattrs").exists():
576
+ return ZarrExperiment(path)
577
+ if path.suffix in (".hdf5", ".h5"):
578
+ return HDF5Experiment(path)
579
+ raise ValueError(
580
+ f"{path} is not a PyCLM experiment output (.zarr directory or .hdf5 file)"
581
+ )
582
+
583
+
584
+ def find_experiments(directory) -> list[Path]:
585
+ """All experiment outputs in a directory, newest layout first."""
586
+ directory = Path(directory)
587
+ zarrs = sorted(p for p in directory.glob("*.zarr") if (p / ".zattrs").exists())
588
+ h5s = sorted(directory.glob("*.hdf5"))
589
+ return zarrs + h5s