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
pyclm/directories.py
ADDED
|
@@ -0,0 +1,563 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import logging
|
|
3
|
+
import re
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from xml.etree import ElementTree
|
|
7
|
+
|
|
8
|
+
import yaml
|
|
9
|
+
|
|
10
|
+
from .core import ExperimentSchedule
|
|
11
|
+
from .core.experiments import MicroscopePosition, PositionWithAutoFocus
|
|
12
|
+
from .core.virtual_microscope.simulated_source import (
|
|
13
|
+
DEFAULT_PIXEL_SIZE_UM,
|
|
14
|
+
TimeSeriesImageSource,
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
logger = logging.getLogger(__name__)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
# ---------------------------------------------------------------- file names
|
|
21
|
+
# ``schedule.toml`` and ``pyclm_config.toml`` may carry a qualifier between the
|
|
22
|
+
# name and the suffix (``schedule.fast.toml``, ``pyclm_config.ti2.toml``) so a
|
|
23
|
+
# directory can be labelled by what it was run with; exactly one of each.
|
|
24
|
+
SCHEDULE_PATTERN = re.compile(r"^schedule(\..+)?\.toml$", re.IGNORECASE)
|
|
25
|
+
CONFIG_PATTERN = re.compile(r"^pyclm_config(\..+)?\.toml$", re.IGNORECASE)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class AmbiguousFileError(ValueError):
|
|
29
|
+
"""More than one file in a directory matches a name that must be unique."""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _find_one(directory, pattern: re.Pattern, what: str) -> Path | None:
|
|
33
|
+
directory = Path(directory)
|
|
34
|
+
if not directory.is_dir():
|
|
35
|
+
return None
|
|
36
|
+
matches = sorted(p for p in directory.iterdir() if pattern.match(p.name))
|
|
37
|
+
if len(matches) > 1:
|
|
38
|
+
raise AmbiguousFileError(
|
|
39
|
+
f"{directory} has {len(matches)} {what} files "
|
|
40
|
+
f"({', '.join(m.name for m in matches)}); keep exactly one"
|
|
41
|
+
)
|
|
42
|
+
return matches[0] if matches else None
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def find_schedule(directory) -> Path | None:
|
|
46
|
+
"""The directory's ``schedule[.<anything>].toml``; None if absent, error if several."""
|
|
47
|
+
return _find_one(directory, SCHEDULE_PATTERN, "schedule")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def find_config_in(directory) -> Path | None:
|
|
51
|
+
"""The directory's ``pyclm_config[.<anything>].toml``; None if absent, error if several."""
|
|
52
|
+
return _find_one(directory, CONFIG_PATTERN, "pyclm_config")
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def is_reserved_toml(name: str) -> bool:
|
|
56
|
+
"""Whether a TOML file name is the schedule or the configuration, not an experiment."""
|
|
57
|
+
return bool(SCHEDULE_PATTERN.match(name) or CONFIG_PATTERN.match(name))
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
# the ImageJ export writes <label>_<cadence group>.tif next to the stores
|
|
61
|
+
EXPORT_TIF = re.compile(r"^.+_(imaging|stim|imaging_every\d+)$")
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def is_export_tif(path) -> bool:
|
|
65
|
+
"""Whether a TIF is an ImageJ hyperstack PyCLM exported (not a dry-run source)."""
|
|
66
|
+
return bool(EXPORT_TIF.match(Path(path).stem))
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def dry_run_tifs(directory) -> list[Path]:
|
|
70
|
+
"""The TIFs of a directory that can feed a dry run, exports excluded."""
|
|
71
|
+
return sorted(p for p in Path(directory).glob("*.tif") if not is_export_tif(p))
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def experiment_tomls(directory) -> dict[str, Path]:
|
|
75
|
+
"""``{stem: path}`` of the experiment TOMLs in a directory (schedule and config excluded)."""
|
|
76
|
+
directory = Path(directory)
|
|
77
|
+
return {
|
|
78
|
+
p.stem: p
|
|
79
|
+
for p in sorted(directory.glob("*.toml"))
|
|
80
|
+
if not is_reserved_toml(p.name)
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def experiment_from_toml(toml_path, name="SampleExperiment"):
|
|
85
|
+
"""
|
|
86
|
+
The ``Experiment`` described by one experiment TOML, for position ``name``.
|
|
87
|
+
Validated against :class:`pyclm.schema.ExperimentConfig`; raises
|
|
88
|
+
:class:`pyclm.schema.ConfigError` listing every problem in the file.
|
|
89
|
+
"""
|
|
90
|
+
from .schema import ExperimentConfig
|
|
91
|
+
|
|
92
|
+
return ExperimentConfig.from_file(toml_path).to_experiment(name)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _schedule_path(directory) -> Path:
|
|
96
|
+
path = find_schedule(directory)
|
|
97
|
+
if path is None:
|
|
98
|
+
raise FileNotFoundError(
|
|
99
|
+
f"no schedule.toml (or schedule.<name>.toml) in {Path(directory)}"
|
|
100
|
+
)
|
|
101
|
+
return path
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def read_schedule(toml_path):
|
|
105
|
+
"""The timing of ``schedule.toml`` as ``ExperimentSchedule`` keyword arguments."""
|
|
106
|
+
from .schema import ScheduleConfig
|
|
107
|
+
|
|
108
|
+
return ScheduleConfig.from_file(toml_path).timing_kwargs()
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def positions_from_pos(fp) -> list[MicroscopePosition]:
|
|
112
|
+
"""
|
|
113
|
+
Parse a MicroManager PositionList.pos file (JSON Property Map v2).
|
|
114
|
+
|
|
115
|
+
The XY stage is identified by the ``DefaultXYStage`` field in each position
|
|
116
|
+
entry. The Z stage is the first single-axis device whose name is not the
|
|
117
|
+
XY stage. All remaining single-axis devices are stored as optional extras
|
|
118
|
+
keyed by their device name (e.g. ``{"PFSOffset": 11122.0}``).
|
|
119
|
+
"""
|
|
120
|
+
with open(fp) as f:
|
|
121
|
+
data = json.load(f)
|
|
122
|
+
|
|
123
|
+
positions = []
|
|
124
|
+
raw_labels: list[str] = []
|
|
125
|
+
grid_rc: list[tuple[int, int] | None] = []
|
|
126
|
+
|
|
127
|
+
for pos_data in data["map"]["StagePositions"]["array"]:
|
|
128
|
+
raw_label = str(pos_data["Label"]["scalar"])
|
|
129
|
+
label = raw_label.replace("-", ".")
|
|
130
|
+
raw_labels.append(raw_label)
|
|
131
|
+
grid_rc.append(_grid_rc(pos_data))
|
|
132
|
+
xy_stage = pos_data["DefaultXYStage"]["scalar"]
|
|
133
|
+
z_stage = pos_data["DefaultZStage"]["scalar"]
|
|
134
|
+
|
|
135
|
+
x = y = z = None
|
|
136
|
+
extras: dict = {}
|
|
137
|
+
|
|
138
|
+
for dev_entry in pos_data["DevicePositions"]["array"]:
|
|
139
|
+
device = dev_entry["Device"]["scalar"]
|
|
140
|
+
values = [float(v) for v in dev_entry["Position_um"]["array"]]
|
|
141
|
+
|
|
142
|
+
if device == xy_stage:
|
|
143
|
+
x, y = values[0], values[1]
|
|
144
|
+
elif device == z_stage:
|
|
145
|
+
z = values[0]
|
|
146
|
+
elif z_stage == "" and z is None and len(values) == 1:
|
|
147
|
+
# First non-XY single-axis device is the Z stage
|
|
148
|
+
z = values[0]
|
|
149
|
+
else:
|
|
150
|
+
extras[device] = values[0] if len(values) == 1 else values
|
|
151
|
+
|
|
152
|
+
if x is None or y is None:
|
|
153
|
+
raise ValueError(f"Position '{label}' in {fp} has no XY stage entry.")
|
|
154
|
+
if z is None:
|
|
155
|
+
raise ValueError(f"Position '{label}' in {fp} has no Z stage entry.")
|
|
156
|
+
|
|
157
|
+
positions.append(MicroscopePosition(x=x, y=y, z=z, label=label, extras=extras))
|
|
158
|
+
|
|
159
|
+
from .core.grid import group_tiles
|
|
160
|
+
|
|
161
|
+
return group_tiles(positions, raw_labels, grid_rc)
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _grid_rc(pos_data: dict) -> tuple[int, int] | None:
|
|
165
|
+
"""(GridRow, GridCol) of a position-list entry, None when absent."""
|
|
166
|
+
try:
|
|
167
|
+
row, col = pos_data["GridRow"], pos_data["GridCol"]
|
|
168
|
+
except KeyError:
|
|
169
|
+
return None
|
|
170
|
+
row = row["scalar"] if isinstance(row, dict) else row
|
|
171
|
+
col = col["scalar"] if isinstance(col, dict) else col
|
|
172
|
+
return (int(row), int(col))
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def positions_from_xml(fp):
|
|
176
|
+
tree = ElementTree.parse(fp)
|
|
177
|
+
root = tree.getroot()
|
|
178
|
+
|
|
179
|
+
positions = []
|
|
180
|
+
|
|
181
|
+
for node in root[0]:
|
|
182
|
+
if node.attrib["runtype"] != "NDSetupMultipointListItem":
|
|
183
|
+
continue
|
|
184
|
+
|
|
185
|
+
nv = {
|
|
186
|
+
n.tag: n.attrib["value"]
|
|
187
|
+
for n in node
|
|
188
|
+
if n.attrib.get("value", None) is not None
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
for tag in ["dXPosition", "dYPosition", "dZPosition", "dPFSOffset"]:
|
|
192
|
+
val = nv.get(tag)
|
|
193
|
+
if val is not None:
|
|
194
|
+
val = float(val)
|
|
195
|
+
|
|
196
|
+
nv[tag] = val
|
|
197
|
+
|
|
198
|
+
if (nv["dPFSOffset"] is not None) and (nv["dPFSOffset"] < 0):
|
|
199
|
+
nv["dPFSOffset"] = None
|
|
200
|
+
|
|
201
|
+
positions.append(
|
|
202
|
+
PositionWithAutoFocus(
|
|
203
|
+
x=nv["dXPosition"],
|
|
204
|
+
y=nv["dYPosition"],
|
|
205
|
+
z=nv["dZPosition"],
|
|
206
|
+
autofocus_offset=nv["dPFSOffset"],
|
|
207
|
+
label=nv["strName"],
|
|
208
|
+
)
|
|
209
|
+
)
|
|
210
|
+
|
|
211
|
+
return positions
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def schedule_from_directory(experiment_dir: Path):
|
|
215
|
+
tomls = {stem: str(p) for stem, p in experiment_tomls(experiment_dir).items()}
|
|
216
|
+
|
|
217
|
+
pos_path = experiment_dir / "PositionList.pos"
|
|
218
|
+
xml_path = experiment_dir / "multipoints.xml"
|
|
219
|
+
|
|
220
|
+
if pos_path.exists():
|
|
221
|
+
pos_list = positions_from_pos(str(pos_path))
|
|
222
|
+
elif xml_path.exists():
|
|
223
|
+
pos_list = positions_from_xml(str(xml_path))
|
|
224
|
+
else:
|
|
225
|
+
raise FileNotFoundError(
|
|
226
|
+
f"No position list found in {experiment_dir}. "
|
|
227
|
+
"Expected 'PositionList.pos' or 'multipoints.xml'."
|
|
228
|
+
)
|
|
229
|
+
|
|
230
|
+
positions = {}
|
|
231
|
+
experiments = {}
|
|
232
|
+
|
|
233
|
+
for position in pos_list:
|
|
234
|
+
name: str = position.label
|
|
235
|
+
|
|
236
|
+
exp_stem = name.split(".")[0]
|
|
237
|
+
|
|
238
|
+
experiment_path = tomls.get(exp_stem)
|
|
239
|
+
|
|
240
|
+
if experiment_path is None:
|
|
241
|
+
logger.warning(
|
|
242
|
+
f"position '{name}': no experiment toml named '{exp_stem}' in "
|
|
243
|
+
f"{sorted(tomls)}; position skipped"
|
|
244
|
+
)
|
|
245
|
+
continue
|
|
246
|
+
|
|
247
|
+
positions[name] = position
|
|
248
|
+
experiments[name] = experiment_from_toml(experiment_path, name)
|
|
249
|
+
|
|
250
|
+
timing = read_schedule(str(_schedule_path(experiment_dir)))
|
|
251
|
+
|
|
252
|
+
schedule = ExperimentSchedule(experiments, positions, **timing)
|
|
253
|
+
|
|
254
|
+
return schedule
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
# ---------------------------------------------------------------------------
|
|
258
|
+
# Dry-run schedule discovery
|
|
259
|
+
# ---------------------------------------------------------------------------
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def _dry_schedule_from_yml(
|
|
263
|
+
experiment_dir: Path,
|
|
264
|
+
yml_path: Path,
|
|
265
|
+
tomls: dict[str, str],
|
|
266
|
+
timing: dict,
|
|
267
|
+
) -> tuple[ExperimentSchedule, TimeSeriesImageSource]:
|
|
268
|
+
"""Build a dry-run schedule from an explicit dry_run.yml file.
|
|
269
|
+
|
|
270
|
+
Each entry must have ``name`` (position label) and ``source`` (TIF path
|
|
271
|
+
relative to the experiment directory). Optional ``x``, ``y``, ``z``
|
|
272
|
+
fields override the placeholder coordinates.
|
|
273
|
+
"""
|
|
274
|
+
with open(yml_path) as f:
|
|
275
|
+
data = yaml.safe_load(f) or {}
|
|
276
|
+
|
|
277
|
+
entries = data.get("positions", [])
|
|
278
|
+
if not entries:
|
|
279
|
+
raise ValueError(f"{yml_path} contains no positions")
|
|
280
|
+
settings = DrySettings.from_mapping(data, yml_path)
|
|
281
|
+
|
|
282
|
+
positions: dict[str, MicroscopePosition] = {}
|
|
283
|
+
experiments: dict[str, object] = {}
|
|
284
|
+
pos_to_tif: dict[tuple[float, float], Path] = {}
|
|
285
|
+
|
|
286
|
+
for i, entry in enumerate(entries):
|
|
287
|
+
name: str = entry["name"]
|
|
288
|
+
tif_path = experiment_dir / entry["source"]
|
|
289
|
+
|
|
290
|
+
if not tif_path.exists():
|
|
291
|
+
raise FileNotFoundError(
|
|
292
|
+
f"dry_run.yml source '{entry['source']}' not found: {tif_path}"
|
|
293
|
+
)
|
|
294
|
+
|
|
295
|
+
exp_stem = name.split(".")[0]
|
|
296
|
+
experiment_path = tomls.get(exp_stem)
|
|
297
|
+
if experiment_path is None:
|
|
298
|
+
raise FileNotFoundError(
|
|
299
|
+
f"No TOML found for stem '{exp_stem}' (from position '{name}'). "
|
|
300
|
+
f"Available TOMLs: {list(tomls.keys())}"
|
|
301
|
+
)
|
|
302
|
+
|
|
303
|
+
x = float(entry.get("x", i * 10000))
|
|
304
|
+
y = float(entry.get("y", 0.0))
|
|
305
|
+
z = float(entry.get("z", 0.0))
|
|
306
|
+
|
|
307
|
+
pos = MicroscopePosition(x=x, y=y, z=z, label=name)
|
|
308
|
+
positions[name] = pos
|
|
309
|
+
experiments[name] = experiment_from_toml(experiment_path, name)
|
|
310
|
+
pos_to_tif[(x, y)] = tif_path
|
|
311
|
+
|
|
312
|
+
schedule = ExperimentSchedule(experiments, positions, **timing)
|
|
313
|
+
image_source = TimeSeriesImageSource.from_mapping(
|
|
314
|
+
pos_to_tif, loop=True, **settings.as_kwargs()
|
|
315
|
+
)
|
|
316
|
+
return schedule, image_source
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def _dry_schedule_from_position_list(
|
|
320
|
+
experiment_dir: Path,
|
|
321
|
+
tomls: dict[str, str],
|
|
322
|
+
timing: dict,
|
|
323
|
+
settings: "DrySettings | None" = None,
|
|
324
|
+
) -> tuple[ExperimentSchedule, TimeSeriesImageSource]:
|
|
325
|
+
"""Build a dry-run schedule from an existing position list (pos/xml).
|
|
326
|
+
|
|
327
|
+
For each position, TIF matching order:
|
|
328
|
+
1. ``{label}.tif`` — exact label match
|
|
329
|
+
2. ``{experiment_stem}.tif`` — stem match (e.g. bar10.tif for bar10.pos1)
|
|
330
|
+
3. Round-robin from all TIFs in the directory
|
|
331
|
+
"""
|
|
332
|
+
pos_path = experiment_dir / "PositionList.pos"
|
|
333
|
+
xml_path = experiment_dir / "multipoints.xml"
|
|
334
|
+
|
|
335
|
+
if pos_path.exists():
|
|
336
|
+
pos_list = positions_from_pos(str(pos_path))
|
|
337
|
+
else:
|
|
338
|
+
pos_list = positions_from_xml(str(xml_path))
|
|
339
|
+
|
|
340
|
+
available_tifs = dry_run_tifs(experiment_dir)
|
|
341
|
+
if not available_tifs:
|
|
342
|
+
raise FileNotFoundError(f"No TIF files found in {experiment_dir} for dry run")
|
|
343
|
+
|
|
344
|
+
tif_by_name = {t.stem: t for t in available_tifs}
|
|
345
|
+
|
|
346
|
+
positions: dict[str, MicroscopePosition] = {}
|
|
347
|
+
experiments: dict[str, object] = {}
|
|
348
|
+
pos_to_tif: dict[tuple[float, float], Path] = {}
|
|
349
|
+
|
|
350
|
+
for position in pos_list:
|
|
351
|
+
name: str = position.label
|
|
352
|
+
exp_stem = name.split(".")[0]
|
|
353
|
+
|
|
354
|
+
experiment_path = tomls.get(exp_stem)
|
|
355
|
+
if experiment_path is None:
|
|
356
|
+
continue
|
|
357
|
+
|
|
358
|
+
if name in tif_by_name:
|
|
359
|
+
tif_path = tif_by_name[name]
|
|
360
|
+
elif exp_stem in tif_by_name:
|
|
361
|
+
tif_path = tif_by_name[exp_stem]
|
|
362
|
+
else:
|
|
363
|
+
tif_path = available_tifs[len(positions) % len(available_tifs)]
|
|
364
|
+
|
|
365
|
+
pos_to_tif[(position.x, position.y)] = tif_path
|
|
366
|
+
positions[name] = position
|
|
367
|
+
experiments[name] = experiment_from_toml(experiment_path, name)
|
|
368
|
+
|
|
369
|
+
if not positions:
|
|
370
|
+
raise FileNotFoundError(
|
|
371
|
+
f"No positions in the position list matched any TOML files. "
|
|
372
|
+
f"Available TOMLs: {list(tomls.keys())}"
|
|
373
|
+
)
|
|
374
|
+
|
|
375
|
+
schedule = ExperimentSchedule(experiments, positions, **timing)
|
|
376
|
+
image_source = TimeSeriesImageSource.from_mapping(
|
|
377
|
+
pos_to_tif, loop=True, **(settings or DrySettings()).as_kwargs()
|
|
378
|
+
)
|
|
379
|
+
return schedule, image_source
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
def _dry_schedule_from_tifs(
|
|
383
|
+
experiment_dir: Path,
|
|
384
|
+
tomls: dict[str, str],
|
|
385
|
+
timing: dict,
|
|
386
|
+
settings: "DrySettings | None" = None,
|
|
387
|
+
) -> tuple[ExperimentSchedule, TimeSeriesImageSource]:
|
|
388
|
+
"""Build a dry-run schedule from TIF filenames alone.
|
|
389
|
+
|
|
390
|
+
Each TIF stem becomes a position label; the first dot-separated token
|
|
391
|
+
is matched to a TOML (e.g. ``fast.00.tif`` → label ``fast.00``,
|
|
392
|
+
experiment ``fast.toml``). TIFs with no matching TOML are silently
|
|
393
|
+
skipped. Placeholder coordinates are assigned sequentially.
|
|
394
|
+
"""
|
|
395
|
+
tif_files = dry_run_tifs(experiment_dir)
|
|
396
|
+
if not tif_files:
|
|
397
|
+
raise FileNotFoundError(f"No TIF files found in {experiment_dir} for dry run")
|
|
398
|
+
|
|
399
|
+
positions: dict[str, MicroscopePosition] = {}
|
|
400
|
+
experiments: dict[str, object] = {}
|
|
401
|
+
pos_to_tif: dict[tuple[float, float], Path] = {}
|
|
402
|
+
|
|
403
|
+
for i, tif_path in enumerate(tif_files):
|
|
404
|
+
label = tif_path.stem
|
|
405
|
+
exp_stem = label.split(".")[0]
|
|
406
|
+
|
|
407
|
+
experiment_path = tomls.get(exp_stem)
|
|
408
|
+
if experiment_path is None:
|
|
409
|
+
continue
|
|
410
|
+
|
|
411
|
+
x, y = float(i * 10000), 0.0
|
|
412
|
+
pos = MicroscopePosition(x=x, y=y, z=0.0, label=label)
|
|
413
|
+
positions[label] = pos
|
|
414
|
+
experiments[label] = experiment_from_toml(experiment_path, label)
|
|
415
|
+
pos_to_tif[(x, y)] = tif_path
|
|
416
|
+
|
|
417
|
+
if not positions:
|
|
418
|
+
raise FileNotFoundError(
|
|
419
|
+
f"No TIF files in {experiment_dir} matched any TOML files. "
|
|
420
|
+
f"TIF stems: {[t.stem for t in tif_files]}, "
|
|
421
|
+
f"available TOMLs: {list(tomls.keys())}"
|
|
422
|
+
)
|
|
423
|
+
|
|
424
|
+
schedule = ExperimentSchedule(experiments, positions, **timing)
|
|
425
|
+
image_source = TimeSeriesImageSource.from_mapping(
|
|
426
|
+
pos_to_tif, loop=True, **(settings or DrySettings()).as_kwargs()
|
|
427
|
+
)
|
|
428
|
+
return schedule, image_source
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
@dataclass
|
|
432
|
+
class DrySettings:
|
|
433
|
+
"""
|
|
434
|
+
The optional top-level keys of ``dry_run.yml``: ``pixel_size_um``, the
|
|
435
|
+
size of one pixel of the TIFs (default 0.33), and ``binning``, the
|
|
436
|
+
binning the TIFs were acquired at relative to the camera the affine
|
|
437
|
+
transform was calibrated for (default 1; the dry run scales the affine).
|
|
438
|
+
"""
|
|
439
|
+
|
|
440
|
+
pixel_size_um: float = DEFAULT_PIXEL_SIZE_UM
|
|
441
|
+
binning: int = 1
|
|
442
|
+
|
|
443
|
+
@classmethod
|
|
444
|
+
def from_mapping(cls, data: dict, path=None) -> "DrySettings":
|
|
445
|
+
where = f"{path}: " if path else ""
|
|
446
|
+
px = data.get("pixel_size_um", DEFAULT_PIXEL_SIZE_UM)
|
|
447
|
+
binning = data.get("binning", 1)
|
|
448
|
+
try:
|
|
449
|
+
px = float(px)
|
|
450
|
+
binning = int(binning)
|
|
451
|
+
except (TypeError, ValueError) as e:
|
|
452
|
+
raise ValueError(
|
|
453
|
+
f"{where}pixel_size_um must be a number and binning an integer"
|
|
454
|
+
) from e
|
|
455
|
+
if px <= 0 or binning < 1:
|
|
456
|
+
raise ValueError(
|
|
457
|
+
f"{where}pixel_size_um must be > 0 and binning >= 1 "
|
|
458
|
+
f"(got {px}, {binning})"
|
|
459
|
+
)
|
|
460
|
+
return cls(px, binning)
|
|
461
|
+
|
|
462
|
+
def as_kwargs(self) -> dict:
|
|
463
|
+
return {"pixel_size_um": self.pixel_size_um, "binning": self.binning}
|
|
464
|
+
|
|
465
|
+
|
|
466
|
+
def dry_settings_from_directory(experiment_dir: Path) -> DrySettings:
|
|
467
|
+
"""The dry-run pixel size and binning of a directory (its ``dry_run.yml``, if any)."""
|
|
468
|
+
yml_path = Path(experiment_dir) / "dry_run.yml"
|
|
469
|
+
if not yml_path.exists():
|
|
470
|
+
return DrySettings()
|
|
471
|
+
with open(yml_path) as f:
|
|
472
|
+
data = yaml.safe_load(f) or {}
|
|
473
|
+
return DrySettings.from_mapping(data, yml_path)
|
|
474
|
+
|
|
475
|
+
|
|
476
|
+
def dry_schedule_from_directory(
|
|
477
|
+
experiment_dir: Path,
|
|
478
|
+
) -> tuple[ExperimentSchedule, TimeSeriesImageSource]:
|
|
479
|
+
"""Discover experiments and image sources for a dry run.
|
|
480
|
+
|
|
481
|
+
Priority order:
|
|
482
|
+
1. ``dry_run.yml`` — explicit position-to-TIF mapping
|
|
483
|
+
2. ``PositionList.pos`` or ``multipoints.xml`` — real positions,
|
|
484
|
+
TIFs matched by label/stem/round-robin
|
|
485
|
+
3. TIF filenames in the directory — position labels inferred from stems
|
|
486
|
+
"""
|
|
487
|
+
experiment_dir = Path(experiment_dir)
|
|
488
|
+
tomls = {stem: str(p) for stem, p in experiment_tomls(experiment_dir).items()}
|
|
489
|
+
timing = read_schedule(str(_schedule_path(experiment_dir)))
|
|
490
|
+
|
|
491
|
+
yml_path = experiment_dir / "dry_run.yml"
|
|
492
|
+
pos_path = experiment_dir / "PositionList.pos"
|
|
493
|
+
xml_path = experiment_dir / "multipoints.xml"
|
|
494
|
+
|
|
495
|
+
settings = DrySettings()
|
|
496
|
+
if yml_path.exists():
|
|
497
|
+
with open(yml_path) as f:
|
|
498
|
+
data = yaml.safe_load(f) or {}
|
|
499
|
+
if data.get("positions"):
|
|
500
|
+
return _dry_schedule_from_yml(experiment_dir, yml_path, tomls, timing)
|
|
501
|
+
# a dry_run.yml with only pixel_size_um / binning applies to the
|
|
502
|
+
# positions found the other two ways
|
|
503
|
+
settings = DrySettings.from_mapping(data, yml_path)
|
|
504
|
+
|
|
505
|
+
if pos_path.exists() or xml_path.exists():
|
|
506
|
+
return _dry_schedule_from_position_list(experiment_dir, tomls, timing, settings)
|
|
507
|
+
|
|
508
|
+
return _dry_schedule_from_tifs(experiment_dir, tomls, timing, settings)
|
|
509
|
+
|
|
510
|
+
|
|
511
|
+
def write_position_list(path, positions, xy_stage="XYStage", z_stage="ZDrive"):
|
|
512
|
+
"""
|
|
513
|
+
Write positions as a MicroManager ``PositionList.pos`` (property map v2),
|
|
514
|
+
the format :func:`positions_from_pos` reads and MicroManager imports.
|
|
515
|
+
``extras`` of a position (e.g. ``PFSOffset``) become single-axis devices.
|
|
516
|
+
"""
|
|
517
|
+
path = Path(path)
|
|
518
|
+
entries = []
|
|
519
|
+
for i, pos in enumerate(positions):
|
|
520
|
+
devices = [
|
|
521
|
+
{
|
|
522
|
+
"Device": {"type": "STRING", "scalar": xy_stage},
|
|
523
|
+
"Position_um": {
|
|
524
|
+
"type": "DOUBLE",
|
|
525
|
+
"array": [float(pos.x), float(pos.y)],
|
|
526
|
+
},
|
|
527
|
+
},
|
|
528
|
+
{
|
|
529
|
+
"Device": {"type": "STRING", "scalar": z_stage},
|
|
530
|
+
"Position_um": {"type": "DOUBLE", "array": [float(pos.z)]},
|
|
531
|
+
},
|
|
532
|
+
]
|
|
533
|
+
for device, value in (getattr(pos, "extras", {}) or {}).items():
|
|
534
|
+
values = list(value) if isinstance(value, (list, tuple)) else [value]
|
|
535
|
+
devices.append(
|
|
536
|
+
{
|
|
537
|
+
"Device": {"type": "STRING", "scalar": str(device)},
|
|
538
|
+
"Position_um": {
|
|
539
|
+
"type": "DOUBLE",
|
|
540
|
+
"array": [float(v) for v in values],
|
|
541
|
+
},
|
|
542
|
+
}
|
|
543
|
+
)
|
|
544
|
+
entries.append(
|
|
545
|
+
{
|
|
546
|
+
"DefaultXYStage": {"type": "STRING", "scalar": xy_stage},
|
|
547
|
+
"DefaultZStage": {"type": "STRING", "scalar": z_stage},
|
|
548
|
+
"DevicePositions": {"type": "PROPERTY_MAP", "array": devices},
|
|
549
|
+
"GridCol": {"type": "INTEGER", "scalar": 0},
|
|
550
|
+
"GridRow": {"type": "INTEGER", "scalar": i},
|
|
551
|
+
"Label": {"type": "STRING", "scalar": str(pos.label)},
|
|
552
|
+
"Properties": {"type": "PROPERTY_MAP", "scalar": {}},
|
|
553
|
+
}
|
|
554
|
+
)
|
|
555
|
+
document = {
|
|
556
|
+
"encoding": "UTF-8",
|
|
557
|
+
"format": "Micro-Manager Property Map",
|
|
558
|
+
"major_version": 2,
|
|
559
|
+
"minor_version": 0,
|
|
560
|
+
"map": {"StagePositions": {"type": "PROPERTY_MAP", "array": entries}},
|
|
561
|
+
}
|
|
562
|
+
path.write_text(json.dumps(document, indent=2), encoding="utf-8")
|
|
563
|
+
return path
|
pyclm/gui/__init__.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""The live viewer (napari, Qt). Installed with the ``gui`` extra."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import importlib.util
|
|
6
|
+
|
|
7
|
+
INSTALL_HINT = (
|
|
8
|
+
'the viewer needs the gui extra: pip install "closed-loop-microscopy[gui]" '
|
|
9
|
+
"(in a clone: uv sync --extra gui)"
|
|
10
|
+
)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class GuiUnavailable(RuntimeError):
|
|
14
|
+
"""napari or a Qt binding is not installed."""
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def require_gui() -> None:
|
|
18
|
+
"""Raise :class:`GuiUnavailable`, naming the install line, when the viewer cannot start."""
|
|
19
|
+
missing = [
|
|
20
|
+
name for name in ("napari", "qtpy") if importlib.util.find_spec(name) is None
|
|
21
|
+
]
|
|
22
|
+
if not any(
|
|
23
|
+
importlib.util.find_spec(binding) is not None
|
|
24
|
+
for binding in ("PySide6", "PyQt6", "PyQt5", "PySide2")
|
|
25
|
+
):
|
|
26
|
+
missing.append("a Qt binding (PySide6)")
|
|
27
|
+
if missing:
|
|
28
|
+
raise GuiUnavailable(f"{', '.join(missing)} not installed; {INSTALL_HINT}")
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import os
|
|
2
|
+
|
|
3
|
+
os.environ.setdefault("NAPARI_DISABLE_PLUGIN_AUTOLOAD", "1")
|
|
4
|
+
|
|
5
|
+
import sys
|
|
6
|
+
|
|
7
|
+
import napari
|
|
8
|
+
import numpy as np
|
|
9
|
+
from h5py import File
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def view_hdf5(filepath: str, channel="channel_638"):
|
|
13
|
+
viewer = napari.Viewer()
|
|
14
|
+
with File(filepath, mode="r", libver="latest", swmr=True) as f:
|
|
15
|
+
timepoints = sorted(f.keys())
|
|
16
|
+
print("Timepoints:", timepoints)
|
|
17
|
+
|
|
18
|
+
stack = []
|
|
19
|
+
for t in timepoints:
|
|
20
|
+
if channel in f[t] and "data" in f[t][channel]:
|
|
21
|
+
data = np.array(f[t][channel]["data"])
|
|
22
|
+
stack.append(data)
|
|
23
|
+
|
|
24
|
+
if not stack:
|
|
25
|
+
raise RuntimeError(f"No data found for channel {channel}")
|
|
26
|
+
|
|
27
|
+
stack = np.stack(stack)
|
|
28
|
+
print("Stack shape:", stack.shape)
|
|
29
|
+
print("dtype/min/max:", stack.dtype, stack.min(), stack.max())
|
|
30
|
+
|
|
31
|
+
viewer.add_image(stack, name=channel)
|
|
32
|
+
|
|
33
|
+
napari.run()
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
if __name__ == "__main__":
|
|
37
|
+
if len(sys.argv) < 2:
|
|
38
|
+
sys.exit(1)
|
|
39
|
+
filepath = sys.argv[1]
|
|
40
|
+
channel = sys.argv[2] if len(sys.argv) > 2 else "channel_638"
|
|
41
|
+
view_hdf5(filepath, channel)
|