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/core/plan.py
ADDED
|
@@ -0,0 +1,623 @@
|
|
|
1
|
+
"""
|
|
2
|
+
The acquisition plan.
|
|
3
|
+
|
|
4
|
+
A :class:`useq.MDASequence` carries the declarative schedule (time plan,
|
|
5
|
+
positions, per-position channels and exposures, PFS offsets) and is written
|
|
6
|
+
next to the data as ``plan.useq.yaml``. :class:`AcquisitionPlan` wraps it with
|
|
7
|
+
the rules useq cannot express and PyCLM needs:
|
|
8
|
+
|
|
9
|
+
- per-channel cadence counted from the experiment's ``t_delay`` (``every_t``),
|
|
10
|
+
and ``t_delay`` / ``t_stop`` themselves,
|
|
11
|
+
- the per-position time offset (``time_between_positions``),
|
|
12
|
+
- the stimulation channel and the SLM-update / pattern-request events that
|
|
13
|
+
surround it,
|
|
14
|
+
- the pattern method's requirements, which set the pattern cadence (the
|
|
15
|
+
Router turns them into subscriptions; nothing about routing is on an event).
|
|
16
|
+
|
|
17
|
+
Everything PyCLM-specific lives under ``metadata["pyclm"]`` in the sequence,
|
|
18
|
+
and this wrapper, not useq's iterator, is the authority for *when* things
|
|
19
|
+
happen. useq's iteration is used only for the structure *within* one
|
|
20
|
+
timepoint at one position (channels now; z and grid later).
|
|
21
|
+
|
|
22
|
+
See docs/stage1-plan-design.md.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import logging
|
|
28
|
+
from collections.abc import Iterator
|
|
29
|
+
from dataclasses import dataclass
|
|
30
|
+
from importlib.metadata import version as _pkg_version
|
|
31
|
+
from math import lcm
|
|
32
|
+
from pathlib import Path
|
|
33
|
+
|
|
34
|
+
import useq
|
|
35
|
+
|
|
36
|
+
from .events import storage_group
|
|
37
|
+
from .experiments import Experiment, ExperimentSchedule, ImagingConfig
|
|
38
|
+
from .kinds import seg_kind
|
|
39
|
+
from .patterns import AcquiredImageRequest
|
|
40
|
+
|
|
41
|
+
logger = logging.getLogger(__name__)
|
|
42
|
+
|
|
43
|
+
PLAN_FORMAT = 1
|
|
44
|
+
PLAN_FILENAME = "plan.useq.yaml"
|
|
45
|
+
PFS_DEVICE_NAME = "PFS"
|
|
46
|
+
DEFAULT_STIM_CHANNEL_NAME = "stimulation"
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass(frozen=True)
|
|
50
|
+
class PlannedEvent:
|
|
51
|
+
"""One step the Manager carries out at timepoint ``t`` for one experiment.
|
|
52
|
+
|
|
53
|
+
``kind`` is one of ``"request_pattern"``, ``"update_pattern"``,
|
|
54
|
+
``"position"``, ``"acquire"``, in that order per position: the SLM
|
|
55
|
+
handshake precedes the stage move. ``index`` identifies the frame
|
|
56
|
+
(``{"t", "p", "c"}``; ``c`` absent for non-acquisition events). Who
|
|
57
|
+
consumes the frame is the Router's decision, not the event's.
|
|
58
|
+
|
|
59
|
+
``skippable`` marks the events of a position whose only acquisition at
|
|
60
|
+
``t`` is the stimulation frame and whose pattern method does not need
|
|
61
|
+
that frame: if the pattern the handshake delivers is blank, the
|
|
62
|
+
microscope skips the move and the exposure (and acknowledges the
|
|
63
|
+
acquisition as skipped).
|
|
64
|
+
"""
|
|
65
|
+
|
|
66
|
+
kind: str
|
|
67
|
+
t: int
|
|
68
|
+
experiment: str
|
|
69
|
+
index: dict
|
|
70
|
+
scheduled_offset_s: float
|
|
71
|
+
channel: str | None = None
|
|
72
|
+
is_stim: bool = False
|
|
73
|
+
save: bool = True
|
|
74
|
+
skippable: bool = False
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
@dataclass(frozen=True)
|
|
78
|
+
class ExpectedDataset:
|
|
79
|
+
"""A frame the plan will produce, described the way the writer needs it."""
|
|
80
|
+
|
|
81
|
+
experiment: str
|
|
82
|
+
t: int
|
|
83
|
+
channel: str
|
|
84
|
+
is_stim: bool
|
|
85
|
+
group: str
|
|
86
|
+
config: ImagingConfig
|
|
87
|
+
save: bool
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _needs(req) -> dict:
|
|
91
|
+
out = {
|
|
92
|
+
"raw": bool(req.needs_raw),
|
|
93
|
+
"seg": bool(req.needs_seg),
|
|
94
|
+
"tracks": bool(getattr(req, "needs_tracks", False)),
|
|
95
|
+
}
|
|
96
|
+
named = [str(n) for n in getattr(req, "segmentations", ())]
|
|
97
|
+
if named:
|
|
98
|
+
out["segmentations"] = named
|
|
99
|
+
return out
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def requirement_kinds(needs: dict) -> list[str]:
|
|
103
|
+
"""The routing kinds a ``pattern_requirements`` entry asks for, in delivery order."""
|
|
104
|
+
kinds = [k for k in ("raw", "seg") if needs.get(k)]
|
|
105
|
+
kinds += [
|
|
106
|
+
seg_kind(n) for n in needs.get("segmentations", ()) if seg_kind(n) != "seg"
|
|
107
|
+
]
|
|
108
|
+
if needs.get("tracks"):
|
|
109
|
+
kinds.append("tracks")
|
|
110
|
+
return kinds
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _channel_group(exp: Experiment) -> str:
|
|
114
|
+
"""The MicroManager config group used to switch imaging channels."""
|
|
115
|
+
for name, cfg in exp.channels.items():
|
|
116
|
+
for cg in cfg.get_config_groups():
|
|
117
|
+
if cg.config == name:
|
|
118
|
+
return cg.group
|
|
119
|
+
return "Channel"
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _stim_channel_name(exp: Experiment, group: str) -> str:
|
|
123
|
+
"""The stimulation channel's preset in the channel group, or a fallback."""
|
|
124
|
+
for cg in exp.stimulation.get_config_groups():
|
|
125
|
+
if cg.group == group:
|
|
126
|
+
return cg.config
|
|
127
|
+
return DEFAULT_STIM_CHANNEL_NAME
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
class AcquisitionPlan:
|
|
131
|
+
"""
|
|
132
|
+
The single place scheduling logic lives.
|
|
133
|
+
|
|
134
|
+
Build with :meth:`from_schedule` (from TOMLs and the position list) or
|
|
135
|
+
:meth:`from_yaml` (from a previously written ``plan.useq.yaml`` plus the
|
|
136
|
+
schedule that supplies hardware detail). Query with :meth:`events_at`,
|
|
137
|
+
:meth:`is_scheduled`, :meth:`expected_datasets` and
|
|
138
|
+
:meth:`estimate_timepoint_s`.
|
|
139
|
+
"""
|
|
140
|
+
|
|
141
|
+
def __init__(
|
|
142
|
+
self,
|
|
143
|
+
sequence: useq.MDASequence,
|
|
144
|
+
schedule: ExperimentSchedule,
|
|
145
|
+
requirements: dict[str, list[AcquiredImageRequest]] | None = None,
|
|
146
|
+
):
|
|
147
|
+
self.sequence = sequence
|
|
148
|
+
self.schedule = schedule
|
|
149
|
+
self.requirements: dict[str, list[AcquiredImageRequest]] = dict(
|
|
150
|
+
requirements or {}
|
|
151
|
+
)
|
|
152
|
+
|
|
153
|
+
self._positions = list(sequence.stage_positions)
|
|
154
|
+
self._names = [p.name for p in self._positions]
|
|
155
|
+
self._validate_structure()
|
|
156
|
+
|
|
157
|
+
self._meta = {
|
|
158
|
+
p.name: dict(p.sequence.metadata["pyclm"]) for p in self._positions
|
|
159
|
+
}
|
|
160
|
+
# intra-timepoint structure from useq's own iteration (channels; later z/grid)
|
|
161
|
+
self._template = {
|
|
162
|
+
p.name: [
|
|
163
|
+
e
|
|
164
|
+
for e in p.sequence
|
|
165
|
+
if isinstance(e.action, useq.AcquireImage) and e.channel is not None
|
|
166
|
+
]
|
|
167
|
+
for p in self._positions
|
|
168
|
+
}
|
|
169
|
+
self._validate_metadata()
|
|
170
|
+
|
|
171
|
+
# useq yields the start of each timepoint in seconds (older versions: timedelta)
|
|
172
|
+
self._t_offsets = [
|
|
173
|
+
float(v.total_seconds()) if hasattr(v, "total_seconds") else float(v)
|
|
174
|
+
for v in sequence.time_plan
|
|
175
|
+
]
|
|
176
|
+
self._required = {
|
|
177
|
+
name: self._resolve_requirements(name) for name in self._names
|
|
178
|
+
}
|
|
179
|
+
# experiments ended early by a stop_experiment command
|
|
180
|
+
self._stopped: set[str] = set()
|
|
181
|
+
self._pattern_lcm = {name: self._compute_lcm(name) for name in self._names}
|
|
182
|
+
|
|
183
|
+
# ------------------------------------------------------------------ build
|
|
184
|
+
@classmethod
|
|
185
|
+
def from_schedule(
|
|
186
|
+
cls,
|
|
187
|
+
schedule: ExperimentSchedule,
|
|
188
|
+
requirements: dict[str, list[AcquiredImageRequest]] | None = None,
|
|
189
|
+
) -> AcquisitionPlan:
|
|
190
|
+
times = schedule.times
|
|
191
|
+
requirements = dict(requirements or {})
|
|
192
|
+
positions = []
|
|
193
|
+
|
|
194
|
+
for name, exp in schedule.experiments.items():
|
|
195
|
+
pos = schedule.positions[name]
|
|
196
|
+
group = _channel_group(exp)
|
|
197
|
+
stim = exp.stimulation
|
|
198
|
+
stim_name = _stim_channel_name(exp, group) if stim.exposure > 0 else None
|
|
199
|
+
|
|
200
|
+
channels = []
|
|
201
|
+
every_t = {}
|
|
202
|
+
binning = {}
|
|
203
|
+
if stim_name is not None:
|
|
204
|
+
channels.append(
|
|
205
|
+
useq.Channel(
|
|
206
|
+
config=stim_name,
|
|
207
|
+
group=group,
|
|
208
|
+
exposure=float(stim.exposure),
|
|
209
|
+
do_stack=False,
|
|
210
|
+
)
|
|
211
|
+
)
|
|
212
|
+
every_t[stim_name] = int(stim.every_t)
|
|
213
|
+
binning[stim_name] = int(stim.binning)
|
|
214
|
+
for cname, cfg in exp.channels.items():
|
|
215
|
+
channels.append(
|
|
216
|
+
useq.Channel(
|
|
217
|
+
config=cname, group=group, exposure=float(cfg.exposure)
|
|
218
|
+
)
|
|
219
|
+
)
|
|
220
|
+
every_t[cname] = int(cfg.every_t)
|
|
221
|
+
binning[cname] = int(cfg.binning)
|
|
222
|
+
|
|
223
|
+
meta = {
|
|
224
|
+
"experiment": name,
|
|
225
|
+
"t_delay": int(exp.t_delay),
|
|
226
|
+
"t_stop": int(exp.t_stop),
|
|
227
|
+
"stim_channel": stim_name,
|
|
228
|
+
"every_t": every_t,
|
|
229
|
+
"pattern_every_t": int(exp.pattern.every_t),
|
|
230
|
+
"binning": binning,
|
|
231
|
+
"pattern_requires": cls._requirements_by_name(
|
|
232
|
+
exp, stim_name, requirements.get(name)
|
|
233
|
+
),
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
sub = {"channels": channels, "metadata": {"pyclm": meta}}
|
|
237
|
+
pfs = pos.extras.get("PFSOffset") if hasattr(pos, "extras") else None
|
|
238
|
+
if pfs is not None:
|
|
239
|
+
# recorded for provenance and tooling; PositionMover still owns focus
|
|
240
|
+
sub["autofocus_plan"] = useq.AxesBasedAF(
|
|
241
|
+
autofocus_device_name=PFS_DEVICE_NAME,
|
|
242
|
+
autofocus_motor_offset=float(pfs),
|
|
243
|
+
axes=("p",),
|
|
244
|
+
)
|
|
245
|
+
|
|
246
|
+
positions.append(
|
|
247
|
+
useq.Position(
|
|
248
|
+
x=pos.x,
|
|
249
|
+
y=pos.y,
|
|
250
|
+
z=pos.z,
|
|
251
|
+
name=name,
|
|
252
|
+
sequence=useq.MDASequence(**sub),
|
|
253
|
+
)
|
|
254
|
+
)
|
|
255
|
+
|
|
256
|
+
sequence = useq.MDASequence(
|
|
257
|
+
time_plan=useq.TIntervalLoops(interval=times.interval, loops=times.count),
|
|
258
|
+
stage_positions=positions,
|
|
259
|
+
metadata={
|
|
260
|
+
"pyclm": {
|
|
261
|
+
"plan_format": PLAN_FORMAT,
|
|
262
|
+
"useq_version": _pkg_version("useq-schema"),
|
|
263
|
+
"pyclm_version": _pyclm_version(),
|
|
264
|
+
"setup_time_seconds": float(times.setup),
|
|
265
|
+
"time_between_positions": float(times.between),
|
|
266
|
+
}
|
|
267
|
+
},
|
|
268
|
+
)
|
|
269
|
+
return cls(sequence, schedule, requirements)
|
|
270
|
+
|
|
271
|
+
@classmethod
|
|
272
|
+
def from_yaml(
|
|
273
|
+
cls,
|
|
274
|
+
path: str | Path,
|
|
275
|
+
schedule: ExperimentSchedule,
|
|
276
|
+
requirements: dict[str, list[AcquiredImageRequest]] | None = None,
|
|
277
|
+
) -> AcquisitionPlan:
|
|
278
|
+
return cls(useq.MDASequence.from_file(str(path)), schedule, requirements)
|
|
279
|
+
|
|
280
|
+
def yaml_str(self) -> str:
|
|
281
|
+
return self.sequence.yaml()
|
|
282
|
+
|
|
283
|
+
def to_yaml(self, path: str | Path) -> Path:
|
|
284
|
+
path = Path(path)
|
|
285
|
+
path.write_text(self.yaml_str(), encoding="utf-8")
|
|
286
|
+
return path
|
|
287
|
+
|
|
288
|
+
@staticmethod
|
|
289
|
+
def _requirements_by_name(exp, stim_name, reqs) -> dict[str, dict[str, bool]]:
|
|
290
|
+
out = {}
|
|
291
|
+
for req in reqs or ():
|
|
292
|
+
if stim_name is not None and req.id == exp.stimulation.channel_id:
|
|
293
|
+
out[stim_name] = _needs(req)
|
|
294
|
+
continue
|
|
295
|
+
for cname, cfg in exp.channels.items():
|
|
296
|
+
if cfg.channel_id == req.id:
|
|
297
|
+
out[cname] = _needs(req)
|
|
298
|
+
return out
|
|
299
|
+
|
|
300
|
+
# --------------------------------------------------------------- validate
|
|
301
|
+
def _validate_structure(self):
|
|
302
|
+
if not self._positions:
|
|
303
|
+
raise ValueError("plan has no positions")
|
|
304
|
+
if len(set(self._names)) != len(self._names):
|
|
305
|
+
raise ValueError(f"duplicate position names in plan: {self._names}")
|
|
306
|
+
if set(self._names) != set(self.schedule.experiment_names):
|
|
307
|
+
raise ValueError(
|
|
308
|
+
f"plan positions {sorted(self._names)} do not match schedule "
|
|
309
|
+
f"experiments {sorted(self.schedule.experiment_names)}"
|
|
310
|
+
)
|
|
311
|
+
for p in self._positions:
|
|
312
|
+
if p.sequence is None or "pyclm" not in p.sequence.metadata:
|
|
313
|
+
raise ValueError(f"position {p.name!r} has no pyclm metadata")
|
|
314
|
+
if self.sequence.time_plan is None:
|
|
315
|
+
raise ValueError("plan has no time plan")
|
|
316
|
+
if "pyclm" not in self.sequence.metadata:
|
|
317
|
+
raise ValueError("plan has no top-level pyclm metadata")
|
|
318
|
+
|
|
319
|
+
def _validate_metadata(self):
|
|
320
|
+
needed = {
|
|
321
|
+
"experiment",
|
|
322
|
+
"t_delay",
|
|
323
|
+
"t_stop",
|
|
324
|
+
"stim_channel",
|
|
325
|
+
"every_t",
|
|
326
|
+
"pattern_every_t",
|
|
327
|
+
}
|
|
328
|
+
for name, meta in self._meta.items():
|
|
329
|
+
missing = needed - set(meta)
|
|
330
|
+
if missing:
|
|
331
|
+
raise ValueError(
|
|
332
|
+
f"position {name!r} metadata missing {sorted(missing)}"
|
|
333
|
+
)
|
|
334
|
+
channels = {e.channel.config for e in self._template[name]}
|
|
335
|
+
unknown = set(meta["every_t"]) - channels
|
|
336
|
+
if unknown:
|
|
337
|
+
raise ValueError(
|
|
338
|
+
f"position {name!r}: every_t names channels not in the sequence: {sorted(unknown)}"
|
|
339
|
+
)
|
|
340
|
+
if (
|
|
341
|
+
meta["stim_channel"] is not None
|
|
342
|
+
and meta["stim_channel"] not in channels
|
|
343
|
+
):
|
|
344
|
+
raise ValueError(
|
|
345
|
+
f"position {name!r}: stimulation channel {meta['stim_channel']!r} not in the sequence"
|
|
346
|
+
)
|
|
347
|
+
|
|
348
|
+
# ------------------------------------------------------------ requirements
|
|
349
|
+
def _resolve_requirements(self, name: str) -> dict[str, dict[str, bool]]:
|
|
350
|
+
"""{channel name: {"raw", "seg", "tracks"}} for the pattern method of one experiment."""
|
|
351
|
+
exp = self.schedule.experiments[name]
|
|
352
|
+
stim_name = self._meta[name]["stim_channel"]
|
|
353
|
+
reqs = self.requirements.get(name)
|
|
354
|
+
if reqs:
|
|
355
|
+
by_name = self._requirements_by_name(exp, stim_name, reqs)
|
|
356
|
+
else:
|
|
357
|
+
by_name = self._meta[name].get("pattern_requires") or {}
|
|
358
|
+
out = {}
|
|
359
|
+
for c, v in by_name.items():
|
|
360
|
+
needs = {k: bool(v.get(k, False)) for k in ("raw", "seg", "tracks")}
|
|
361
|
+
named = [str(n) for n in v.get("segmentations", ())]
|
|
362
|
+
if named:
|
|
363
|
+
needs["segmentations"] = named
|
|
364
|
+
out[c] = needs
|
|
365
|
+
return out
|
|
366
|
+
|
|
367
|
+
def _compute_lcm(self, name: str) -> int:
|
|
368
|
+
meta = self._meta[name]
|
|
369
|
+
values = [int(meta["pattern_every_t"])]
|
|
370
|
+
values += [
|
|
371
|
+
int(meta["every_t"][c])
|
|
372
|
+
for c in self._required[name]
|
|
373
|
+
if c in meta["every_t"]
|
|
374
|
+
]
|
|
375
|
+
return lcm(*values)
|
|
376
|
+
|
|
377
|
+
# --------------------------------------------------------------- queries
|
|
378
|
+
@property
|
|
379
|
+
def experiments(self) -> list[str]:
|
|
380
|
+
"""Experiment (position) names in acquisition order."""
|
|
381
|
+
return list(self._names)
|
|
382
|
+
|
|
383
|
+
@property
|
|
384
|
+
def timepoints(self) -> int:
|
|
385
|
+
return len(self._t_offsets)
|
|
386
|
+
|
|
387
|
+
@property
|
|
388
|
+
def setup_s(self) -> float:
|
|
389
|
+
return float(self.sequence.metadata["pyclm"]["setup_time_seconds"])
|
|
390
|
+
|
|
391
|
+
@property
|
|
392
|
+
def between_s(self) -> float:
|
|
393
|
+
return float(self.sequence.metadata["pyclm"]["time_between_positions"])
|
|
394
|
+
|
|
395
|
+
@property
|
|
396
|
+
def interval_s(self) -> float:
|
|
397
|
+
if len(self._t_offsets) > 1:
|
|
398
|
+
return self._t_offsets[1] - self._t_offsets[0]
|
|
399
|
+
return float(self.schedule.times.interval)
|
|
400
|
+
|
|
401
|
+
def time_offset_s(self, t: int) -> float:
|
|
402
|
+
"""Seconds after the start at which timepoint ``t`` begins."""
|
|
403
|
+
return self._t_offsets[t]
|
|
404
|
+
|
|
405
|
+
def structure(self, experiment: str) -> list[useq.MDAEvent]:
|
|
406
|
+
"""useq's events for one timepoint at one position (channels now; z/grid later)."""
|
|
407
|
+
return list(self._template[experiment])
|
|
408
|
+
|
|
409
|
+
def channels(self, experiment: str) -> list[str]:
|
|
410
|
+
"""Channel names at a position, stimulation first, in acquisition order."""
|
|
411
|
+
return [e.channel.config for e in self._template[experiment]]
|
|
412
|
+
|
|
413
|
+
def stim_channel(self, experiment: str) -> str | None:
|
|
414
|
+
return self._meta[experiment]["stim_channel"]
|
|
415
|
+
|
|
416
|
+
def imaging_config(self, experiment: str, channel: str) -> ImagingConfig:
|
|
417
|
+
exp = self.schedule.experiments[experiment]
|
|
418
|
+
if channel == self._meta[experiment]["stim_channel"]:
|
|
419
|
+
return exp.stimulation
|
|
420
|
+
return exp.channels[channel]
|
|
421
|
+
|
|
422
|
+
def every_t(self, experiment: str, channel: str) -> int:
|
|
423
|
+
return int(self._meta[experiment]["every_t"][channel])
|
|
424
|
+
|
|
425
|
+
def pattern_lcm(self, experiment: str) -> int:
|
|
426
|
+
return self._pattern_lcm[experiment]
|
|
427
|
+
|
|
428
|
+
def _relative_t(self, experiment: str, t: int) -> int | None:
|
|
429
|
+
"""Experiment-relative timepoint, or None when the experiment is inactive at ``t``."""
|
|
430
|
+
if experiment in self._stopped:
|
|
431
|
+
return None
|
|
432
|
+
meta = self._meta[experiment]
|
|
433
|
+
this_t = t - int(meta["t_delay"])
|
|
434
|
+
if this_t < 0:
|
|
435
|
+
return None
|
|
436
|
+
if int(meta["t_stop"]) > 0 and this_t >= int(meta["t_stop"]):
|
|
437
|
+
return None
|
|
438
|
+
return this_t
|
|
439
|
+
|
|
440
|
+
def stop_experiment(self, experiment: str) -> bool:
|
|
441
|
+
"""End one experiment: from now on it has no events. Returns False if unknown or already stopped."""
|
|
442
|
+
if experiment not in self._names or experiment in self._stopped:
|
|
443
|
+
return False
|
|
444
|
+
self._stopped.add(experiment)
|
|
445
|
+
return True
|
|
446
|
+
|
|
447
|
+
@property
|
|
448
|
+
def stopped(self) -> set[str]:
|
|
449
|
+
return set(self._stopped)
|
|
450
|
+
|
|
451
|
+
def is_active(self, experiment: str, t: int) -> bool:
|
|
452
|
+
return self._relative_t(experiment, t) is not None
|
|
453
|
+
|
|
454
|
+
def is_scheduled(self, experiment: str, channel: str, t: int) -> bool:
|
|
455
|
+
"""Whether ``channel`` (a channel or the stimulation channel) is acquired at ``t``."""
|
|
456
|
+
every = self._meta[experiment]["every_t"].get(channel)
|
|
457
|
+
if every is None:
|
|
458
|
+
return False
|
|
459
|
+
this_t = self._relative_t(experiment, t)
|
|
460
|
+
if this_t is None:
|
|
461
|
+
return False
|
|
462
|
+
return this_t % int(every) == 0
|
|
463
|
+
|
|
464
|
+
def pattern_due(self, experiment: str, t: int) -> bool:
|
|
465
|
+
"""Whether the experiment's pattern method runs at ``t`` (so its inputs are routed to it)."""
|
|
466
|
+
this_t = self._relative_t(experiment, t)
|
|
467
|
+
return this_t is not None and this_t % self._pattern_lcm[experiment] == 0
|
|
468
|
+
|
|
469
|
+
def pattern_requirements(self, experiment: str) -> dict[str, dict]:
|
|
470
|
+
"""
|
|
471
|
+
``{channel: {"raw", "seg", "tracks"[, "segmentations"]}}`` the pattern
|
|
472
|
+
method needs when it runs (``segmentations`` lists the named
|
|
473
|
+
segmentation tables; see :func:`requirement_kinds`).
|
|
474
|
+
"""
|
|
475
|
+
return {c: dict(v) for c, v in self._required[experiment].items()}
|
|
476
|
+
|
|
477
|
+
def events_at(self, t: int) -> list[PlannedEvent]:
|
|
478
|
+
"""Everything the Manager does at timepoint ``t``, in order."""
|
|
479
|
+
out: list[PlannedEvent] = []
|
|
480
|
+
t_offset = self.time_offset_s(t)
|
|
481
|
+
|
|
482
|
+
for p_index, name in enumerate(self._names):
|
|
483
|
+
this_t = self._relative_t(name, t)
|
|
484
|
+
if this_t is None:
|
|
485
|
+
continue
|
|
486
|
+
|
|
487
|
+
acquisitions = [
|
|
488
|
+
e
|
|
489
|
+
for e in self._template[name]
|
|
490
|
+
if self.is_scheduled(name, e.channel.config, t)
|
|
491
|
+
]
|
|
492
|
+
if not acquisitions:
|
|
493
|
+
continue
|
|
494
|
+
|
|
495
|
+
offset = t_offset + p_index * self.between_s
|
|
496
|
+
make_pattern = this_t % self._pattern_lcm[name] == 0
|
|
497
|
+
base_index = {"t": t, "p": name}
|
|
498
|
+
stim_name = self._meta[name]["stim_channel"]
|
|
499
|
+
|
|
500
|
+
# only the stimulation frame is due and nothing waits for it: a
|
|
501
|
+
# blank pattern lets the microscope skip this position
|
|
502
|
+
stim_only = all(e.channel.config == stim_name for e in acquisitions)
|
|
503
|
+
stim_needed = make_pattern and stim_name in self._required[name]
|
|
504
|
+
skippable = stim_only and not stim_needed
|
|
505
|
+
|
|
506
|
+
if make_pattern:
|
|
507
|
+
out.append(PlannedEvent("request_pattern", t, name, base_index, offset))
|
|
508
|
+
# the SLM handshake comes before the stage move: the pattern is
|
|
509
|
+
# then in hand before anything is spent on the position
|
|
510
|
+
for e in acquisitions:
|
|
511
|
+
channel = e.channel.config
|
|
512
|
+
if channel == stim_name:
|
|
513
|
+
out.append(
|
|
514
|
+
PlannedEvent(
|
|
515
|
+
"update_pattern",
|
|
516
|
+
t,
|
|
517
|
+
name,
|
|
518
|
+
{**base_index, "c": channel},
|
|
519
|
+
offset,
|
|
520
|
+
channel,
|
|
521
|
+
True,
|
|
522
|
+
skippable=skippable,
|
|
523
|
+
)
|
|
524
|
+
)
|
|
525
|
+
out.append(
|
|
526
|
+
PlannedEvent(
|
|
527
|
+
"position", t, name, base_index, offset, skippable=skippable
|
|
528
|
+
)
|
|
529
|
+
)
|
|
530
|
+
|
|
531
|
+
for e in acquisitions:
|
|
532
|
+
channel = e.channel.config
|
|
533
|
+
is_stim = channel == stim_name
|
|
534
|
+
index = {**base_index, "c": channel}
|
|
535
|
+
config = self.imaging_config(name, channel)
|
|
536
|
+
out.append(
|
|
537
|
+
PlannedEvent(
|
|
538
|
+
"acquire",
|
|
539
|
+
t,
|
|
540
|
+
name,
|
|
541
|
+
index,
|
|
542
|
+
offset,
|
|
543
|
+
channel,
|
|
544
|
+
is_stim,
|
|
545
|
+
save=bool(config.save),
|
|
546
|
+
skippable=skippable and is_stim,
|
|
547
|
+
)
|
|
548
|
+
)
|
|
549
|
+
return out
|
|
550
|
+
|
|
551
|
+
def datasets_at(self, experiment: str, t: int) -> list[ExpectedDataset]:
|
|
552
|
+
out = []
|
|
553
|
+
for e in self._template[experiment]:
|
|
554
|
+
channel = e.channel.config
|
|
555
|
+
if not self.is_scheduled(experiment, channel, t):
|
|
556
|
+
continue
|
|
557
|
+
is_stim = channel == self._meta[experiment]["stim_channel"]
|
|
558
|
+
config = self.imaging_config(experiment, channel)
|
|
559
|
+
out.append(
|
|
560
|
+
ExpectedDataset(
|
|
561
|
+
experiment,
|
|
562
|
+
t,
|
|
563
|
+
channel,
|
|
564
|
+
is_stim,
|
|
565
|
+
storage_group(channel, is_stim),
|
|
566
|
+
config,
|
|
567
|
+
bool(config.save),
|
|
568
|
+
)
|
|
569
|
+
)
|
|
570
|
+
return out
|
|
571
|
+
|
|
572
|
+
def expected_datasets(self) -> Iterator[ExpectedDataset]:
|
|
573
|
+
"""Every frame the plan will produce, in acquisition order."""
|
|
574
|
+
for t in range(self.timepoints):
|
|
575
|
+
for name in self._names:
|
|
576
|
+
yield from self.datasets_at(name, t)
|
|
577
|
+
|
|
578
|
+
# ---------------------------------------------------------------- timing
|
|
579
|
+
def estimate_timepoint_s(
|
|
580
|
+
self, t: int, settle_s: float, move_s: float = 0.0
|
|
581
|
+
) -> float:
|
|
582
|
+
"""
|
|
583
|
+
Rough duration of timepoint ``t``: per acquisition the exposure plus the
|
|
584
|
+
settle time, plus ``move_s`` per position visited. Stage moves and SLM
|
|
585
|
+
uploads are not modelled beyond ``move_s``.
|
|
586
|
+
"""
|
|
587
|
+
total = 0.0
|
|
588
|
+
for ev in self.events_at(t):
|
|
589
|
+
if ev.kind == "position":
|
|
590
|
+
total += move_s
|
|
591
|
+
elif ev.kind == "acquire":
|
|
592
|
+
per_frame = (
|
|
593
|
+
settle_s
|
|
594
|
+
+ self.imaging_config(ev.experiment, ev.channel).exposure / 1000.0
|
|
595
|
+
)
|
|
596
|
+
tiles = getattr(self.schedule.positions[ev.experiment], "tiles", None)
|
|
597
|
+
n = len(tiles) if tiles else 1
|
|
598
|
+
# a grid: every tile is moved to, settled and exposed
|
|
599
|
+
total += n * per_frame + (n - 1) * move_s
|
|
600
|
+
return total
|
|
601
|
+
|
|
602
|
+
def over_budget(
|
|
603
|
+
self, settle_s: float, move_s: float = 0.0
|
|
604
|
+
) -> list[tuple[int, float]]:
|
|
605
|
+
"""Timepoints whose estimated duration exceeds the interval, as (t, seconds)."""
|
|
606
|
+
interval = self.interval_s
|
|
607
|
+
return [
|
|
608
|
+
(t, est)
|
|
609
|
+
for t in range(self.timepoints)
|
|
610
|
+
if (est := self.estimate_timepoint_s(t, settle_s, move_s)) > interval
|
|
611
|
+
]
|
|
612
|
+
|
|
613
|
+
def __repr__(self):
|
|
614
|
+
return (
|
|
615
|
+
f"AcquisitionPlan({len(self._names)} experiments, {self.timepoints} timepoints, "
|
|
616
|
+
f"interval {self.interval_s}s)"
|
|
617
|
+
)
|
|
618
|
+
|
|
619
|
+
|
|
620
|
+
def _pyclm_version() -> str:
|
|
621
|
+
from pyclm import __version__
|
|
622
|
+
|
|
623
|
+
return __version__
|