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.
- closed_loop_microscopy-1.1.0.dist-info/METADATA +118 -0
- closed_loop_microscopy-1.1.0.dist-info/RECORD +74 -0
- closed_loop_microscopy-1.1.0.dist-info/WHEEL +4 -0
- closed_loop_microscopy-1.1.0.dist-info/entry_points.txt +5 -0
- closed_loop_microscopy-1.1.0.dist-info/licenses/LICENSE.md +7 -0
- pyclm/__init__.py +26 -0
- pyclm/__main__.py +8 -0
- pyclm/check.py +931 -0
- pyclm/cli.py +256 -0
- pyclm/commands.py +183 -0
- pyclm/controller.py +447 -0
- pyclm/convert_hdf5s.py +273 -0
- pyclm/core/__init__.py +20 -0
- pyclm/core/base_process.py +166 -0
- pyclm/core/core_interface.py +47 -0
- pyclm/core/datatypes.py +142 -0
- pyclm/core/events.py +194 -0
- pyclm/core/experiments.py +403 -0
- pyclm/core/grid.py +272 -0
- pyclm/core/kinds.py +42 -0
- pyclm/core/manager.py +861 -0
- pyclm/core/measure.py +266 -0
- pyclm/core/messages.py +124 -0
- pyclm/core/microscope.py +504 -0
- pyclm/core/pattern_process.py +282 -0
- pyclm/core/patterns/__init__.py +60 -0
- pyclm/core/patterns/bar_patterns.py +259 -0
- pyclm/core/patterns/cell_intensity_patterns.py +181 -0
- pyclm/core/patterns/composite.py +220 -0
- pyclm/core/patterns/embryo_patterns.py +90 -0
- pyclm/core/patterns/fbc_cell_movement.py +295 -0
- pyclm/core/patterns/pattern.py +610 -0
- pyclm/core/patterns/pulse_patterns.py +261 -0
- pyclm/core/patterns/static_patterns.py +58 -0
- pyclm/core/patterns/wave_patterns.py +95 -0
- pyclm/core/patterns/zoo.py +231 -0
- pyclm/core/plan.py +623 -0
- pyclm/core/position_mover.py +185 -0
- pyclm/core/queues.py +41 -0
- pyclm/core/real_core.py +158 -0
- pyclm/core/router.py +422 -0
- pyclm/core/segmentation/__init__.py +2 -0
- pyclm/core/segmentation/cellpose_segmentation.py +113 -0
- pyclm/core/segmentation/segmentation.py +48 -0
- pyclm/core/segmentation_process.py +179 -0
- pyclm/core/settings.py +120 -0
- pyclm/core/storage/__init__.py +37 -0
- pyclm/core/storage/base.py +234 -0
- pyclm/core/storage/events.py +130 -0
- pyclm/core/storage/hdf5_v1.py +337 -0
- pyclm/core/storage/ome_zarr.py +861 -0
- pyclm/core/tracking/__init__.py +28 -0
- pyclm/core/tracking/centroid.py +75 -0
- pyclm/core/tracking/tracking.py +124 -0
- pyclm/core/tracking_process.py +106 -0
- pyclm/core/virtual_microscope/__init__.py +0 -0
- pyclm/core/virtual_microscope/simulated_core.py +262 -0
- pyclm/core/virtual_microscope/simulated_source.py +206 -0
- pyclm/core/writer_process.py +130 -0
- pyclm/demo.py +225 -0
- pyclm/directories.py +563 -0
- pyclm/gui/__init__.py +28 -0
- pyclm/gui/debug_viewer.py +41 -0
- pyclm/gui/gui_controller.py +551 -0
- pyclm/gui/widgets.py +292 -0
- pyclm/io/__init__.py +29 -0
- pyclm/io/export.py +202 -0
- pyclm/io/readers.py +589 -0
- pyclm/methods.py +249 -0
- pyclm/mmconfig.py +143 -0
- pyclm/preview.py +414 -0
- pyclm/run_pyclm.py +298 -0
- pyclm/schema.py +806 -0
- pyclm/templates.py +165 -0
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
"""
|
|
2
|
+
The original PyCLM HDF5 layout (format 1), kept for compatibility.
|
|
3
|
+
|
|
4
|
+
One SWMR file per experiment, one pre-allocated 2-D dataset per
|
|
5
|
+
``{t:05d}/<group>/{data,seg,dmd}``, per-dataset attributes. This is exactly
|
|
6
|
+
what ``MicroscopeOutbox`` wrote before Stage 2; only the home moved.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
import logging
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from time import sleep
|
|
15
|
+
|
|
16
|
+
import numpy as np
|
|
17
|
+
from h5py import File
|
|
18
|
+
|
|
19
|
+
from ..core_interface import MicroscopeCoreInterface
|
|
20
|
+
from ..datatypes import AcquisitionData, SegmentationData, StimulationData
|
|
21
|
+
from ..events import storage_group
|
|
22
|
+
from ..experiments import ImagingConfig
|
|
23
|
+
from ..kinds import DEFAULT_SEGMENTATION
|
|
24
|
+
from ..plan import PLAN_FORMAT, AcquisitionPlan
|
|
25
|
+
from .base import FrameWriter, image_shape
|
|
26
|
+
|
|
27
|
+
logger = logging.getLogger(__name__)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class HDF5WriterV1(FrameWriter):
|
|
31
|
+
format = "hdf5"
|
|
32
|
+
|
|
33
|
+
def __init__(self):
|
|
34
|
+
super().__init__()
|
|
35
|
+
self.open_files: dict[str, File] = {}
|
|
36
|
+
self.experiments = {}
|
|
37
|
+
self.dropped_frames = 0
|
|
38
|
+
self.error_count = 0
|
|
39
|
+
|
|
40
|
+
def planned_paths(self, names, base_path):
|
|
41
|
+
return {name: Path(base_path) / f"{name}.hdf5" for name in names}
|
|
42
|
+
|
|
43
|
+
def output_paths(self):
|
|
44
|
+
return (
|
|
45
|
+
self.planned_paths(self.plan.experiments, self.base_path)
|
|
46
|
+
if self.plan
|
|
47
|
+
else {}
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
# ---------------------------------------------------------------- open
|
|
51
|
+
def open(
|
|
52
|
+
self,
|
|
53
|
+
plan,
|
|
54
|
+
core,
|
|
55
|
+
base_path,
|
|
56
|
+
affine_transform=None,
|
|
57
|
+
slm_shape=None,
|
|
58
|
+
recorded=None,
|
|
59
|
+
routing=None,
|
|
60
|
+
):
|
|
61
|
+
self.plan = plan
|
|
62
|
+
self.recorded = recorded
|
|
63
|
+
self.base_path = Path(base_path)
|
|
64
|
+
schedule = plan.schedule
|
|
65
|
+
metadata = schedule.as_dict()
|
|
66
|
+
plan_yaml = plan.yaml_str()
|
|
67
|
+
|
|
68
|
+
try:
|
|
69
|
+
for exp_name in plan.experiments:
|
|
70
|
+
filepath = self.base_path / f"{exp_name}.hdf5"
|
|
71
|
+
filepath.parent.mkdir(parents=True, exist_ok=True)
|
|
72
|
+
if filepath.exists():
|
|
73
|
+
raise FileExistsError(
|
|
74
|
+
f"HDF5 file with this name already exists: {filepath}"
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
f = File(filepath, "w", libver="latest")
|
|
78
|
+
|
|
79
|
+
experiment = schedule.experiments[exp_name]
|
|
80
|
+
self.experiments[exp_name] = experiment
|
|
81
|
+
|
|
82
|
+
f.attrs["schedule_metadata"] = json.dumps(metadata, default=str)
|
|
83
|
+
f.attrs["experiment_metadata"] = json.dumps(
|
|
84
|
+
experiment.as_dict(), default=str
|
|
85
|
+
)
|
|
86
|
+
f.attrs["plan"] = plan_yaml
|
|
87
|
+
f.attrs["plan_format"] = PLAN_FORMAT
|
|
88
|
+
if routing is not None:
|
|
89
|
+
f.attrs["routing"] = json.dumps(routing, default=str)
|
|
90
|
+
if affine_transform is not None:
|
|
91
|
+
f.attrs["affine_transform"] = np.asarray(
|
|
92
|
+
affine_transform, dtype=float
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
f.create_dataset("current_t_index", data=np.int32(-1))
|
|
96
|
+
|
|
97
|
+
stim_name = plan.stim_channel(exp_name)
|
|
98
|
+
every_t_map = {
|
|
99
|
+
storage_group(c, c == stim_name): plan.every_t(exp_name, c)
|
|
100
|
+
for c in plan.channels(exp_name)
|
|
101
|
+
}
|
|
102
|
+
f.attrs["every_t"] = json.dumps(every_t_map)
|
|
103
|
+
f.attrs["t_delay"] = experiment.t_delay
|
|
104
|
+
f.attrs["t_stop"] = experiment.t_stop
|
|
105
|
+
f.attrs["t_count"] = plan.timepoints
|
|
106
|
+
|
|
107
|
+
self.open_files[exp_name] = f
|
|
108
|
+
|
|
109
|
+
grids = [
|
|
110
|
+
name
|
|
111
|
+
for name, pos in plan.schedule.positions.items()
|
|
112
|
+
if getattr(pos, "tiles", None)
|
|
113
|
+
]
|
|
114
|
+
if grids:
|
|
115
|
+
raise ValueError(
|
|
116
|
+
f"grid positions ({', '.join(grids)}) need [output] format = "
|
|
117
|
+
'"ome-zarr": HDF5 format 1 has no place for a stitched pattern'
|
|
118
|
+
)
|
|
119
|
+
slm_device = core.getSLMDevice()
|
|
120
|
+
dmd_shape = None
|
|
121
|
+
if slm_device:
|
|
122
|
+
dmd_shape = (
|
|
123
|
+
core.getSLMHeight(slm_device),
|
|
124
|
+
core.getSLMWidth(slm_device),
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
for ds in plan.expected_datasets():
|
|
128
|
+
f = self.open_files[ds.experiment]
|
|
129
|
+
experiment = self.experiments[ds.experiment]
|
|
130
|
+
shape = image_shape(core, ds.config.binning)
|
|
131
|
+
prefix = f"{ds.t:05d}/{ds.group}"
|
|
132
|
+
|
|
133
|
+
self._create_frame_dataset(
|
|
134
|
+
f, f"{prefix}/data", shape, np.uint16, ds.config
|
|
135
|
+
)
|
|
136
|
+
if experiment.segmentation.save:
|
|
137
|
+
self._create_frame_dataset(
|
|
138
|
+
f, f"{prefix}/seg", shape, np.uint16, ds.config
|
|
139
|
+
)
|
|
140
|
+
if ds.is_stim and dmd_shape is not None:
|
|
141
|
+
# binary patterns compress ~50x; raw they dominated the file
|
|
142
|
+
self._create_frame_dataset(
|
|
143
|
+
f,
|
|
144
|
+
f"{prefix}/dmd",
|
|
145
|
+
dmd_shape,
|
|
146
|
+
np.uint8,
|
|
147
|
+
ds.config,
|
|
148
|
+
compress=True,
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
# Enable SWMR only after all datasets exist
|
|
152
|
+
for exp_name, f in self.open_files.items():
|
|
153
|
+
f.swmr_mode = True
|
|
154
|
+
logger.info(f"Initialized HDF5 file for {exp_name} in SWMR mode.")
|
|
155
|
+
|
|
156
|
+
except Exception as e:
|
|
157
|
+
logger.error(f"Failed to initialize outbox files: {e}", exc_info=True)
|
|
158
|
+
self.close()
|
|
159
|
+
raise e
|
|
160
|
+
|
|
161
|
+
self.is_open = True
|
|
162
|
+
|
|
163
|
+
all_layers = []
|
|
164
|
+
for exp_name, experiment in schedule.experiments.items():
|
|
165
|
+
filepath = str((self.base_path / f"{exp_name}.hdf5").resolve())
|
|
166
|
+
for channel_name in experiment.channels:
|
|
167
|
+
all_layers.append((filepath, f"channel_{channel_name}"))
|
|
168
|
+
if experiment.stimulation.save:
|
|
169
|
+
all_layers.append((filepath, "stim_aq"))
|
|
170
|
+
return all_layers
|
|
171
|
+
|
|
172
|
+
def _create_frame_dataset(
|
|
173
|
+
self, f, path, maxshape, dtype, config: ImagingConfig, compress: bool = False
|
|
174
|
+
):
|
|
175
|
+
extra = {"compression": "gzip", "compression_opts": 4} if compress else {}
|
|
176
|
+
dset = f.create_dataset(
|
|
177
|
+
path, shape=(0, 0), maxshape=maxshape, dtype=dtype, chunks=True, **extra
|
|
178
|
+
)
|
|
179
|
+
self._preallocate_attrs(dset, config)
|
|
180
|
+
|
|
181
|
+
def _preallocate_attrs(self, dset, channel: ImagingConfig):
|
|
182
|
+
dset.attrs["id"] = ""
|
|
183
|
+
dset.attrs["position"] = [("", "")]
|
|
184
|
+
dset.attrs["experiment_name"] = ""
|
|
185
|
+
dset.attrs["time_scheduled"] = ""
|
|
186
|
+
dset.attrs["time_since_start"] = ""
|
|
187
|
+
dset.attrs["time_completed"] = ""
|
|
188
|
+
dset.attrs["complete"] = False
|
|
189
|
+
dset.attrs["skipped"] = False
|
|
190
|
+
dset.attrs["exposure_time_ms"] = 0.0
|
|
191
|
+
dset.attrs["needs_slm"] = False
|
|
192
|
+
dset.attrs["binning"] = 1
|
|
193
|
+
dset.attrs["index"] = ""
|
|
194
|
+
dset.attrs["save_output"] = False
|
|
195
|
+
dset.attrs["channel_id"] = ""
|
|
196
|
+
dset.attrs["pixel_width_um"] = ""
|
|
197
|
+
dset.attrs["pattern_id"] = ""
|
|
198
|
+
|
|
199
|
+
for cg in channel.get_config_groups():
|
|
200
|
+
dset.attrs[f"config_groups: {cg.group}"] = ""
|
|
201
|
+
for dp in channel.get_device_properties():
|
|
202
|
+
dset.attrs[f"devices: {dp.device}-{dp.property}"] = ""
|
|
203
|
+
|
|
204
|
+
# --------------------------------------------------------------- write
|
|
205
|
+
def write_frame(self, data: AcquisitionData):
|
|
206
|
+
self._write(data, "data")
|
|
207
|
+
|
|
208
|
+
def write_labels(self, data: SegmentationData):
|
|
209
|
+
name = getattr(data, "name", DEFAULT_SEGMENTATION)
|
|
210
|
+
if name != DEFAULT_SEGMENTATION:
|
|
211
|
+
# format 1 has one seg dataset per frame; named segmentations need format 2
|
|
212
|
+
if not getattr(self, "_warned_named_seg", False):
|
|
213
|
+
self._warned_named_seg = True
|
|
214
|
+
logger.warning(
|
|
215
|
+
f"HDF5 format 1 stores only the default segmentation; dropping "
|
|
216
|
+
f'the {name!r} labels (use [output] format = "ome-zarr")'
|
|
217
|
+
)
|
|
218
|
+
return
|
|
219
|
+
self._write(data, "seg")
|
|
220
|
+
|
|
221
|
+
def _timepoint_complete(self, f, t_index: int, exp_name: str) -> bool:
|
|
222
|
+
for ds in self.plan.datasets_at(exp_name, t_index):
|
|
223
|
+
if not ds.save:
|
|
224
|
+
continue
|
|
225
|
+
path = f"{ds.t:05d}/{ds.group}/data"
|
|
226
|
+
try:
|
|
227
|
+
dset = f[path]
|
|
228
|
+
if dset.shape == (0, 0) and not bool(dset.attrs.get("skipped", False)):
|
|
229
|
+
return False
|
|
230
|
+
except KeyError:
|
|
231
|
+
return False
|
|
232
|
+
return True
|
|
233
|
+
|
|
234
|
+
def write_skipped(self, data):
|
|
235
|
+
"""Mark a pre-allocated dataset as skipped so the timepoint can complete."""
|
|
236
|
+
aq_event = data.event
|
|
237
|
+
exp_name = aq_event.experiment_name
|
|
238
|
+
try:
|
|
239
|
+
f = self.open_files.get(exp_name)
|
|
240
|
+
if f is None:
|
|
241
|
+
return
|
|
242
|
+
path = aq_event.get_rel_path() + "data"
|
|
243
|
+
if path in f:
|
|
244
|
+
dset = f[path]
|
|
245
|
+
|
|
246
|
+
def mark():
|
|
247
|
+
dset.attrs["skipped"] = True
|
|
248
|
+
f.flush()
|
|
249
|
+
|
|
250
|
+
self._retry(mark)
|
|
251
|
+
self._bump_progress(f, aq_event.t_index, exp_name)
|
|
252
|
+
except Exception as e:
|
|
253
|
+
self.error_count += 1
|
|
254
|
+
logger.error(f"Failed to record a skipped frame: {e}", exc_info=True)
|
|
255
|
+
|
|
256
|
+
def _bump_progress(self, f, t_index: int, exp_name: str) -> None:
|
|
257
|
+
if f["current_t_index"][()] < t_index and self._timepoint_complete(
|
|
258
|
+
f, t_index, exp_name
|
|
259
|
+
):
|
|
260
|
+
|
|
261
|
+
def bump():
|
|
262
|
+
f["current_t_index"][...] = np.int32(t_index)
|
|
263
|
+
f.flush()
|
|
264
|
+
|
|
265
|
+
self._retry(bump)
|
|
266
|
+
|
|
267
|
+
@staticmethod
|
|
268
|
+
def _retry(fn):
|
|
269
|
+
for _attempt in range(3):
|
|
270
|
+
try:
|
|
271
|
+
fn()
|
|
272
|
+
return
|
|
273
|
+
except PermissionError:
|
|
274
|
+
sleep(0.05)
|
|
275
|
+
|
|
276
|
+
def _write(self, data: AcquisitionData, dset_name: str):
|
|
277
|
+
aq_event = data.event
|
|
278
|
+
relpath = aq_event.get_rel_path()
|
|
279
|
+
exp_name = aq_event.experiment_name
|
|
280
|
+
|
|
281
|
+
try:
|
|
282
|
+
f = self.open_files.get(exp_name)
|
|
283
|
+
if f is None:
|
|
284
|
+
logger.warning(f"No open file found for experiment: {exp_name}")
|
|
285
|
+
return
|
|
286
|
+
|
|
287
|
+
if aq_event.save_output:
|
|
288
|
+
if (relpath + dset_name) not in f:
|
|
289
|
+
self.dropped_frames += 1
|
|
290
|
+
logger.error(
|
|
291
|
+
f"no pre-allocated dataset {relpath + dset_name} in "
|
|
292
|
+
f"{exp_name}.hdf5; frame dropped "
|
|
293
|
+
f"({self.dropped_frames} dropped so far)"
|
|
294
|
+
)
|
|
295
|
+
return
|
|
296
|
+
|
|
297
|
+
dset = f[relpath + dset_name]
|
|
298
|
+
if dset.shape != data.data.shape:
|
|
299
|
+
dset.resize(data.data.shape)
|
|
300
|
+
|
|
301
|
+
def put():
|
|
302
|
+
dset[...] = data.data
|
|
303
|
+
aq_event.write_attrs(dset)
|
|
304
|
+
f.flush()
|
|
305
|
+
|
|
306
|
+
self._retry(put)
|
|
307
|
+
|
|
308
|
+
if isinstance(data, StimulationData) and dset_name == "data":
|
|
309
|
+
if (relpath + "dmd") in f:
|
|
310
|
+
dmd = f[relpath + "dmd"]
|
|
311
|
+
if dmd.shape != data.dmd_pattern.shape:
|
|
312
|
+
dmd.resize(data.dmd_pattern.shape)
|
|
313
|
+
|
|
314
|
+
def put_dmd():
|
|
315
|
+
dmd[...] = data.dmd_pattern
|
|
316
|
+
dmd.attrs["pattern_id"] = str(data.pattern_id)
|
|
317
|
+
aq_event.write_attrs(dmd)
|
|
318
|
+
f.flush()
|
|
319
|
+
|
|
320
|
+
self._retry(put_dmd)
|
|
321
|
+
|
|
322
|
+
self._bump_progress(f, aq_event.t_index, exp_name)
|
|
323
|
+
|
|
324
|
+
except Exception as e:
|
|
325
|
+
self.error_count += 1
|
|
326
|
+
logger.error(f"Failed to write data: {e}", exc_info=True)
|
|
327
|
+
|
|
328
|
+
# --------------------------------------------------------------- close
|
|
329
|
+
def close(self):
|
|
330
|
+
for name, f in self.open_files.items():
|
|
331
|
+
try:
|
|
332
|
+
f.close()
|
|
333
|
+
logger.info(f"Closed HDF5 file for {name}")
|
|
334
|
+
except Exception as e:
|
|
335
|
+
logger.error(f"Error closing file for {name}: {e}")
|
|
336
|
+
self.open_files.clear()
|
|
337
|
+
self.is_open = False
|