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,179 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
from threading import Event
|
|
3
|
+
from typing import ClassVar
|
|
4
|
+
|
|
5
|
+
from .base_process import PipelineProcess
|
|
6
|
+
from .datatypes import AcquisitionData, SegmentationData
|
|
7
|
+
from .experiments import Experiment
|
|
8
|
+
from .kinds import DEFAULT_SEGMENTATION, base_kind, seg_name
|
|
9
|
+
from .segmentation import SegmentationMethod
|
|
10
|
+
from .segmentation.cellpose_segmentation import (
|
|
11
|
+
CellposeSegmentationMethod,
|
|
12
|
+
EmbryoSegmentationMethod,
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
logger = logging.getLogger(__name__)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class SegmentationProcess(PipelineProcess):
|
|
19
|
+
"""
|
|
20
|
+
Produces ``seg`` from ``raw``: runs the experiment's segmentation methods
|
|
21
|
+
on every frame the Router delivers and publishes one label image per
|
|
22
|
+
demanded ``[segmentation]`` table (the default one travels as ``seg``, a
|
|
23
|
+
named ``[segmentation.<name>]`` as ``seg:<name>``).
|
|
24
|
+
|
|
25
|
+
Runs only where some consumer demands a segmentation (the Router
|
|
26
|
+
decides; the Controller then calls :meth:`request_method` per name).
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
produces: ClassVar[dict[str, tuple[str, ...]]] = {"seg": ("raw",)}
|
|
30
|
+
|
|
31
|
+
default_models: ClassVar[dict[str, type[SegmentationMethod]]] = {
|
|
32
|
+
"cellpose": CellposeSegmentationMethod,
|
|
33
|
+
"embryo_resizing": EmbryoSegmentationMethod,
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
def __init__(self, stop_event: Event | None = None):
|
|
37
|
+
super().__init__(stop_event, name="segmentation")
|
|
38
|
+
|
|
39
|
+
# per-instance copy so registrations do not leak between controllers
|
|
40
|
+
self.known_models: dict[str, type[SegmentationMethod]] = dict(
|
|
41
|
+
self.default_models
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
self.initialized = False
|
|
45
|
+
|
|
46
|
+
self.models = {}
|
|
47
|
+
|
|
48
|
+
self.accommodated_requests = []
|
|
49
|
+
self.shared_resources = dict()
|
|
50
|
+
|
|
51
|
+
def initialize(self):
|
|
52
|
+
self.initialized = True
|
|
53
|
+
|
|
54
|
+
def can_produce(self, kind: str, experiment: Experiment, channel: str) -> bool:
|
|
55
|
+
if base_kind(kind) != "seg":
|
|
56
|
+
return False
|
|
57
|
+
cfg = experiment.segmentations.get(seg_name(kind))
|
|
58
|
+
return cfg is not None and cfg.method_name != "none"
|
|
59
|
+
|
|
60
|
+
def register_method(self, method: type, name: str | None = None):
|
|
61
|
+
assert issubclass(method, SegmentationMethod), (
|
|
62
|
+
"model must be a subclass of PatternModel"
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
model_name = method.name
|
|
66
|
+
if name is not None:
|
|
67
|
+
model_name = name
|
|
68
|
+
|
|
69
|
+
if model_name in self.known_models:
|
|
70
|
+
logger.warning(f"overwriting known model {model_name}")
|
|
71
|
+
|
|
72
|
+
self.known_models[model_name] = method
|
|
73
|
+
|
|
74
|
+
def request_method(self, experiment: Experiment, name: str = DEFAULT_SEGMENTATION):
|
|
75
|
+
"""Construct the method of one ``[segmentation]`` table for an experiment."""
|
|
76
|
+
cfg = experiment.segmentations[name]
|
|
77
|
+
method_name = cfg.method_name
|
|
78
|
+
|
|
79
|
+
model_class: type = self.known_models.get(method_name)
|
|
80
|
+
|
|
81
|
+
assert model_class is not None, (
|
|
82
|
+
f"method {method_name} is not a registered model"
|
|
83
|
+
)
|
|
84
|
+
assert issubclass(model_class, SegmentationMethod), (
|
|
85
|
+
f"{method_name} is not a SegmentationModel"
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
experiment_name = experiment.experiment_name
|
|
89
|
+
method_kwargs = cfg.kwargs
|
|
90
|
+
|
|
91
|
+
model = model_class(experiment_name, **method_kwargs)
|
|
92
|
+
|
|
93
|
+
this_resource_request = model.request_resource()
|
|
94
|
+
|
|
95
|
+
if this_resource_request:
|
|
96
|
+
self.handle_resource_request(model, this_resource_request)
|
|
97
|
+
|
|
98
|
+
self.models[(experiment_name, name)] = model
|
|
99
|
+
|
|
100
|
+
def handle_resource_request(self, model, request):
|
|
101
|
+
preexisting_resource = None
|
|
102
|
+
|
|
103
|
+
for accommodated_resource_request in self.accommodated_requests:
|
|
104
|
+
if accommodated_resource_request == request:
|
|
105
|
+
preexisting_resource = accommodated_resource_request.request_id
|
|
106
|
+
|
|
107
|
+
if preexisting_resource:
|
|
108
|
+
logger.info("using existing shared segmentation resource")
|
|
109
|
+
model.provide_resource(self.shared_resources[preexisting_resource])
|
|
110
|
+
|
|
111
|
+
else:
|
|
112
|
+
logger.info("creating new shared segmentation resource")
|
|
113
|
+
# initialize the resource
|
|
114
|
+
resource_class = request.resource
|
|
115
|
+
kwargs = request.init_kwargs
|
|
116
|
+
|
|
117
|
+
resource = resource_class(**kwargs)
|
|
118
|
+
|
|
119
|
+
# keep track of the requested resource for future requests
|
|
120
|
+
self.accommodated_requests.append(request)
|
|
121
|
+
|
|
122
|
+
this_request_id = request.request_id
|
|
123
|
+
self.shared_resources[this_request_id] = resource
|
|
124
|
+
|
|
125
|
+
# provide the resource to the model
|
|
126
|
+
model.provide_resource(resource)
|
|
127
|
+
|
|
128
|
+
def run_model(
|
|
129
|
+
self,
|
|
130
|
+
experiment_name,
|
|
131
|
+
aq_data: AcquisitionData,
|
|
132
|
+
name: str = DEFAULT_SEGMENTATION,
|
|
133
|
+
) -> SegmentationData:
|
|
134
|
+
model = self.models.get((experiment_name, name), None)
|
|
135
|
+
|
|
136
|
+
assert isinstance(model, SegmentationMethod), (
|
|
137
|
+
f"self.models[{(experiment_name, name)}] is not a SegmentationModel"
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
data_to_seg = aq_data.data
|
|
141
|
+
segmented = model.segment(data_to_seg)
|
|
142
|
+
|
|
143
|
+
event = aq_data.event
|
|
144
|
+
seg_data = SegmentationData(event, segmented, name)
|
|
145
|
+
|
|
146
|
+
return seg_data
|
|
147
|
+
|
|
148
|
+
def segmentations_for(
|
|
149
|
+
self, experiment_name: str, channel: str
|
|
150
|
+
) -> list[tuple[str, str]]:
|
|
151
|
+
"""
|
|
152
|
+
``[(segmentation name, cadence)]`` to run on a frame of that channel:
|
|
153
|
+
from the routing table when attached to a router, else every method
|
|
154
|
+
constructed for the experiment.
|
|
155
|
+
"""
|
|
156
|
+
produced = getattr(self.router, "produced_by", None)
|
|
157
|
+
if produced is not None:
|
|
158
|
+
wanted = produced(self.name).get((experiment_name, channel))
|
|
159
|
+
if wanted is not None:
|
|
160
|
+
return [(seg_name(kind), cadence) for kind, cadence in wanted]
|
|
161
|
+
return [(n, "always") for (e, n) in self.models if e == experiment_name]
|
|
162
|
+
|
|
163
|
+
def handle_data(self, data):
|
|
164
|
+
assert isinstance(data, AcquisitionData), (
|
|
165
|
+
f"segmentation received {type(data)}, expected AcquisitionData"
|
|
166
|
+
)
|
|
167
|
+
event = data.event
|
|
168
|
+
experiment_name = event.experiment_name
|
|
169
|
+
channel = event.index.get("c")
|
|
170
|
+
|
|
171
|
+
for name, cadence in self.segmentations_for(experiment_name, channel):
|
|
172
|
+
if cadence == "pattern" and not self.router.plan.pattern_due(
|
|
173
|
+
experiment_name, event.t_index
|
|
174
|
+
):
|
|
175
|
+
continue
|
|
176
|
+
logger.debug(
|
|
177
|
+
f"segmenting {experiment_name}/{channel} ({name}): t = {event.t_index}"
|
|
178
|
+
)
|
|
179
|
+
self.publish(self.run_model(experiment_name, data, name))
|
pyclm/core/settings.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Runtime setting changes requested by a pattern method for its own experiment.
|
|
3
|
+
|
|
4
|
+
A method asks through its :class:`~pyclm.core.patterns.pattern.PatternContext`
|
|
5
|
+
(``set_exposure``, ``set_config``, ``set_property``, ``set_position``); the
|
|
6
|
+
pattern process ships the collected :class:`SettingChange` records to the
|
|
7
|
+
Manager in a :class:`~pyclm.core.messages.SettingsRequestMessage`; the
|
|
8
|
+
Manager validates and applies them at the next timepoint boundary
|
|
9
|
+
(:meth:`~pyclm.core.manager.Manager.apply_settings`), records each one in
|
|
10
|
+
the events table, and stamps the values in force on every later
|
|
11
|
+
acquisition event so they appear as columns of the frames table.
|
|
12
|
+
|
|
13
|
+
The structure of the experiment (channels, cadence, timepoints) never
|
|
14
|
+
changes; only the values inside it do. See docs/stage4-control-plane-design.md.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import math
|
|
20
|
+
from dataclasses import dataclass
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
# the alias a method may use for its experiment's stimulation channel
|
|
24
|
+
STIMULATION = "stimulation"
|
|
25
|
+
KINDS = ("exposure", "config", "property", "position")
|
|
26
|
+
POSITION_KEYS = ("x", "y", "z", "pfs_offset")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass(frozen=True)
|
|
30
|
+
class SettingChange:
|
|
31
|
+
"""
|
|
32
|
+
One requested change. ``kind`` is ``"exposure"`` (``key`` =
|
|
33
|
+
``"exposure_ms"``), ``"config"`` (``key`` = the config group, ``value``
|
|
34
|
+
= the preset), ``"property"`` (``key`` = ``"<device>-<property>"``) or
|
|
35
|
+
``"position"`` (``key`` in ``x``, ``y``, ``z``, ``pfs_offset``;
|
|
36
|
+
``channel`` is None).
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
kind: str
|
|
40
|
+
channel: str | None
|
|
41
|
+
key: str
|
|
42
|
+
value: Any
|
|
43
|
+
device: str | None = None
|
|
44
|
+
prop: str | None = None
|
|
45
|
+
|
|
46
|
+
@property
|
|
47
|
+
def column(self) -> str:
|
|
48
|
+
"""The frames-table column that carries this value once changed."""
|
|
49
|
+
return self.key
|
|
50
|
+
|
|
51
|
+
def describe(self) -> str:
|
|
52
|
+
where = "position" if self.channel is None else self.channel
|
|
53
|
+
return f"{self.kind} {where}.{self.key} = {self.value!r}"
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def property_type(value: Any) -> str:
|
|
57
|
+
"""The MicroManager property type string PyCLM uses for a Python value."""
|
|
58
|
+
if isinstance(value, bool):
|
|
59
|
+
return "bool"
|
|
60
|
+
if isinstance(value, int):
|
|
61
|
+
return "int"
|
|
62
|
+
if isinstance(value, float):
|
|
63
|
+
return "float"
|
|
64
|
+
return "str"
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def check_change(change: SettingChange) -> str | None:
|
|
68
|
+
"""Structural validation. Returns a reason to refuse, or None if fine."""
|
|
69
|
+
if change.kind not in KINDS:
|
|
70
|
+
return f"unknown setting kind {change.kind!r}"
|
|
71
|
+
if change.kind == "position":
|
|
72
|
+
if change.key not in POSITION_KEYS:
|
|
73
|
+
return f"unknown position key {change.key!r}"
|
|
74
|
+
try:
|
|
75
|
+
v = float(change.value)
|
|
76
|
+
except (TypeError, ValueError):
|
|
77
|
+
return f"{change.key} must be a number, got {change.value!r}"
|
|
78
|
+
if not math.isfinite(v):
|
|
79
|
+
return f"{change.key} must be finite, got {change.value!r}"
|
|
80
|
+
return None
|
|
81
|
+
if not change.channel:
|
|
82
|
+
return f"{change.kind} needs a channel"
|
|
83
|
+
if change.kind == "exposure":
|
|
84
|
+
try:
|
|
85
|
+
v = float(change.value)
|
|
86
|
+
except (TypeError, ValueError):
|
|
87
|
+
return f"exposure must be a number, got {change.value!r}"
|
|
88
|
+
if not (v > 0 and math.isfinite(v)):
|
|
89
|
+
return f"exposure must be positive, got {change.value!r}"
|
|
90
|
+
return None
|
|
91
|
+
if change.kind == "config":
|
|
92
|
+
if not change.key or not isinstance(change.value, str) or not change.value:
|
|
93
|
+
return "config needs a group and a preset name"
|
|
94
|
+
return None
|
|
95
|
+
if not change.device or not change.prop:
|
|
96
|
+
return "property needs a device and a property name"
|
|
97
|
+
return None
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def exposure(channel: str, ms: float) -> SettingChange:
|
|
101
|
+
return SettingChange("exposure", channel, "exposure_ms", float(ms))
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def config(channel: str, group: str, preset: str) -> SettingChange:
|
|
105
|
+
return SettingChange("config", channel, str(group), str(preset))
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def device_property(channel: str, device: str, prop: str, value: Any) -> SettingChange:
|
|
109
|
+
return SettingChange(
|
|
110
|
+
"property",
|
|
111
|
+
channel,
|
|
112
|
+
f"{device}-{prop}",
|
|
113
|
+
value,
|
|
114
|
+
device=str(device),
|
|
115
|
+
prop=str(prop),
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def position(key: str, value: float) -> SettingChange:
|
|
120
|
+
return SettingChange("position", None, key, float(value))
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""Frame writers: the HDF5 v1 layout and the OME-Zarr layout (format 2)."""
|
|
2
|
+
|
|
3
|
+
from .base import (
|
|
4
|
+
PATTERN_POLICIES,
|
|
5
|
+
STORAGE_FORMATS,
|
|
6
|
+
CadenceGroup,
|
|
7
|
+
FrameWriter,
|
|
8
|
+
cadence_groups,
|
|
9
|
+
image_shape,
|
|
10
|
+
)
|
|
11
|
+
from .hdf5_v1 import HDF5WriterV1
|
|
12
|
+
from .ome_zarr import OMEZarrWriter
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def make_writer(
|
|
16
|
+
storage_format: str = "hdf5", pattern_policy: str = "on_change"
|
|
17
|
+
) -> FrameWriter:
|
|
18
|
+
if storage_format == "hdf5":
|
|
19
|
+
return HDF5WriterV1()
|
|
20
|
+
if storage_format == "ome-zarr":
|
|
21
|
+
return OMEZarrWriter(pattern_policy=pattern_policy)
|
|
22
|
+
raise ValueError(
|
|
23
|
+
f"unknown storage format {storage_format!r}; expected one of {STORAGE_FORMATS}"
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
__all__ = [
|
|
28
|
+
"PATTERN_POLICIES",
|
|
29
|
+
"STORAGE_FORMATS",
|
|
30
|
+
"CadenceGroup",
|
|
31
|
+
"FrameWriter",
|
|
32
|
+
"HDF5WriterV1",
|
|
33
|
+
"OMEZarrWriter",
|
|
34
|
+
"cadence_groups",
|
|
35
|
+
"image_shape",
|
|
36
|
+
"make_writer",
|
|
37
|
+
]
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Frame writers and the cadence-group model shared by writers and readers.
|
|
3
|
+
|
|
4
|
+
A *cadence group* is the set of channels of one experiment that are acquired
|
|
5
|
+
on the same ``every_t``. Each group gets its own image with a compact time
|
|
6
|
+
axis (one slot per acquisition of that group), so readers never see blank
|
|
7
|
+
frames for timepoints a channel was not scheduled at. In the common
|
|
8
|
+
configuration (all imaging channels on one cadence, stimulation frame not
|
|
9
|
+
saved) an experiment has a single group called ``imaging``.
|
|
10
|
+
|
|
11
|
+
See docs/stage2-storage-options.md.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import logging
|
|
17
|
+
from abc import ABC, abstractmethod
|
|
18
|
+
from dataclasses import dataclass
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
|
|
21
|
+
import numpy as np
|
|
22
|
+
|
|
23
|
+
from ..core_interface import MicroscopeCoreInterface
|
|
24
|
+
from ..datatypes import AcquisitionData, SegmentationData
|
|
25
|
+
from ..kinds import is_seg_kind, seg_name
|
|
26
|
+
from ..plan import AcquisitionPlan
|
|
27
|
+
|
|
28
|
+
logger = logging.getLogger(__name__)
|
|
29
|
+
|
|
30
|
+
STORAGE_FORMATS = ("hdf5", "ome-zarr")
|
|
31
|
+
PATTERN_POLICIES = ("on_change", "imaging", "none")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass(frozen=True)
|
|
35
|
+
class CadenceGroup:
|
|
36
|
+
"""Channels of one experiment that share a cadence, and their compact time axis."""
|
|
37
|
+
|
|
38
|
+
name: str
|
|
39
|
+
experiment: str
|
|
40
|
+
every_t: int
|
|
41
|
+
t_delay: int
|
|
42
|
+
t_stop: int
|
|
43
|
+
channels: tuple[str, ...]
|
|
44
|
+
stim_channel: str | None # the stimulation channel's name if it is in this group
|
|
45
|
+
timepoints: int # slots on the compact time axis
|
|
46
|
+
binning: int
|
|
47
|
+
plan_timepoints: int
|
|
48
|
+
|
|
49
|
+
def local_index(self, t: int) -> int | None:
|
|
50
|
+
"""Slot on the compact axis for plan timepoint ``t``, or None if not scheduled."""
|
|
51
|
+
this_t = t - self.t_delay
|
|
52
|
+
if this_t < 0 or this_t % self.every_t != 0:
|
|
53
|
+
return None
|
|
54
|
+
if self.t_stop > 0 and this_t >= self.t_stop:
|
|
55
|
+
return None
|
|
56
|
+
return this_t // self.every_t
|
|
57
|
+
|
|
58
|
+
def global_t(self, i: int) -> int:
|
|
59
|
+
return self.t_delay + i * self.every_t
|
|
60
|
+
|
|
61
|
+
def channel_index(self, channel: str) -> int:
|
|
62
|
+
return self.channels.index(channel)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def cadence_groups(plan: AcquisitionPlan, experiment: str) -> list[CadenceGroup]:
|
|
66
|
+
"""
|
|
67
|
+
Group the saved channels of ``experiment`` by ``every_t``.
|
|
68
|
+
|
|
69
|
+
The stimulation camera frame is included only when ``stimulation.save`` is
|
|
70
|
+
set; it joins the group of its cadence (its own group if no imaging
|
|
71
|
+
channel shares it). Naming: the group holding the first imaging channel
|
|
72
|
+
is ``imaging``; a group holding only the stimulation frame is ``stim``;
|
|
73
|
+
any other is ``imaging_every<N>``.
|
|
74
|
+
"""
|
|
75
|
+
exp = plan.schedule.experiments[experiment]
|
|
76
|
+
stim_name = plan.stim_channel(experiment)
|
|
77
|
+
meta_t_delay = int(exp.t_delay)
|
|
78
|
+
meta_t_stop = int(exp.t_stop)
|
|
79
|
+
|
|
80
|
+
by_cadence: dict[int, list[str]] = {}
|
|
81
|
+
for channel in plan.channels(experiment):
|
|
82
|
+
is_stim = channel == stim_name
|
|
83
|
+
if is_stim and not exp.stimulation.save:
|
|
84
|
+
continue
|
|
85
|
+
by_cadence.setdefault(plan.every_t(experiment, channel), []).append(channel)
|
|
86
|
+
|
|
87
|
+
imaging_channels = [c for c in plan.channels(experiment) if c != stim_name]
|
|
88
|
+
first_imaging = imaging_channels[0] if imaging_channels else None
|
|
89
|
+
|
|
90
|
+
groups = []
|
|
91
|
+
# the group holding the first imaging channel comes first, then by cadence
|
|
92
|
+
ordered = sorted(
|
|
93
|
+
by_cadence.items(), key=lambda kv: (first_imaging not in kv[1], kv[0])
|
|
94
|
+
)
|
|
95
|
+
for every_t, channels in ordered:
|
|
96
|
+
# stimulation frame last within its group
|
|
97
|
+
channels = [c for c in channels if c != stim_name] + [
|
|
98
|
+
c for c in channels if c == stim_name
|
|
99
|
+
]
|
|
100
|
+
if first_imaging in channels:
|
|
101
|
+
name = "imaging"
|
|
102
|
+
elif channels == [stim_name]:
|
|
103
|
+
name = "stim"
|
|
104
|
+
else:
|
|
105
|
+
name = f"imaging_every{every_t}"
|
|
106
|
+
|
|
107
|
+
binnings = {plan.imaging_config(experiment, c).binning for c in channels}
|
|
108
|
+
if len(binnings) != 1:
|
|
109
|
+
raise ValueError(
|
|
110
|
+
f"{experiment}: channels {channels} share cadence {every_t} but "
|
|
111
|
+
f"have different binning {sorted(binnings)}"
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
timepoints = sum(
|
|
115
|
+
1
|
|
116
|
+
for t in range(plan.timepoints)
|
|
117
|
+
if plan.is_scheduled(experiment, channels[0], t)
|
|
118
|
+
)
|
|
119
|
+
groups.append(
|
|
120
|
+
CadenceGroup(
|
|
121
|
+
name=name,
|
|
122
|
+
experiment=experiment,
|
|
123
|
+
every_t=int(every_t),
|
|
124
|
+
t_delay=meta_t_delay,
|
|
125
|
+
t_stop=meta_t_stop,
|
|
126
|
+
channels=tuple(channels),
|
|
127
|
+
stim_channel=stim_name if stim_name in channels else None,
|
|
128
|
+
timepoints=timepoints,
|
|
129
|
+
binning=int(binnings.pop()),
|
|
130
|
+
plan_timepoints=plan.timepoints,
|
|
131
|
+
)
|
|
132
|
+
)
|
|
133
|
+
return groups
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def image_shape(
|
|
137
|
+
core: MicroscopeCoreInterface, binning: int = 1, geometry=None
|
|
138
|
+
) -> tuple[int, int]:
|
|
139
|
+
"""
|
|
140
|
+
(height, width) of a frame at the given binning, from the camera ROI, or
|
|
141
|
+
of the stitched frame of a grid position (``geometry``).
|
|
142
|
+
"""
|
|
143
|
+
if geometry is not None:
|
|
144
|
+
return tuple(int(v) for v in geometry.shape(binning))
|
|
145
|
+
roi = core.getROI()
|
|
146
|
+
h, w = roi[3], roi[2]
|
|
147
|
+
return (h // binning, w // binning)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
class FrameWriter(ABC):
|
|
151
|
+
"""
|
|
152
|
+
Persists what the pipeline produces for one run.
|
|
153
|
+
|
|
154
|
+
``open`` prepares every output for the plan (readers may open the outputs
|
|
155
|
+
as soon as it returns); ``write_frame`` receives raw and stimulation
|
|
156
|
+
frames, ``write_labels`` segmentation masks, ``write_tracks`` tracking
|
|
157
|
+
output; ``close`` finalises. Writers must never block on readers.
|
|
158
|
+
|
|
159
|
+
``recorded`` (from the Router) says which ``(experiment, channel)`` pairs
|
|
160
|
+
will actually arrive for each kind; without it :meth:`records` falls back
|
|
161
|
+
to the experiment configuration. ``routing`` is the resolved routing
|
|
162
|
+
table, stored with the data as provenance.
|
|
163
|
+
"""
|
|
164
|
+
|
|
165
|
+
format: str = "base"
|
|
166
|
+
|
|
167
|
+
def __init__(self):
|
|
168
|
+
self.base_path: Path = Path.cwd()
|
|
169
|
+
self.plan: AcquisitionPlan | None = None
|
|
170
|
+
self.recorded: dict[str, set[tuple[str, str]]] | None = None
|
|
171
|
+
self.is_open = False
|
|
172
|
+
self._warned_tracks = False
|
|
173
|
+
|
|
174
|
+
@abstractmethod
|
|
175
|
+
def open(
|
|
176
|
+
self,
|
|
177
|
+
plan: AcquisitionPlan,
|
|
178
|
+
core: MicroscopeCoreInterface,
|
|
179
|
+
base_path: Path,
|
|
180
|
+
affine_transform: np.ndarray | None = None,
|
|
181
|
+
slm_shape: tuple[int, int] | None = None,
|
|
182
|
+
recorded: dict[str, set[tuple[str, str]]] | None = None,
|
|
183
|
+
routing: dict | None = None,
|
|
184
|
+
) -> list[tuple[str, str]]:
|
|
185
|
+
"""Create the outputs. Returns ``(path, layer)`` pairs for the live GUI."""
|
|
186
|
+
|
|
187
|
+
def records(self, experiment: str, channel: str, kind: str) -> bool:
|
|
188
|
+
"""Whether ``kind`` for this channel will reach the writer (Router table, else config)."""
|
|
189
|
+
if self.recorded is not None:
|
|
190
|
+
return (experiment, channel) in self.recorded.get(kind, ())
|
|
191
|
+
exp = self.plan.schedule.experiments[experiment]
|
|
192
|
+
if is_seg_kind(kind):
|
|
193
|
+
cfg = exp.segmentations.get(seg_name(kind))
|
|
194
|
+
return cfg is not None and bool(cfg.save)
|
|
195
|
+
if kind == "tracks":
|
|
196
|
+
tracking = getattr(exp, "tracking", None)
|
|
197
|
+
return bool(
|
|
198
|
+
tracking is not None
|
|
199
|
+
and tracking.save
|
|
200
|
+
and tracking.method_name != "none"
|
|
201
|
+
)
|
|
202
|
+
return True
|
|
203
|
+
|
|
204
|
+
@abstractmethod
|
|
205
|
+
def write_frame(self, data: AcquisitionData) -> None: ...
|
|
206
|
+
|
|
207
|
+
@abstractmethod
|
|
208
|
+
def write_labels(self, data: SegmentationData) -> None: ...
|
|
209
|
+
|
|
210
|
+
def write_skipped(self, data) -> None:
|
|
211
|
+
"""
|
|
212
|
+
A planned frame that will not arrive (``SkippedAcquisition``): record
|
|
213
|
+
it so the timepoint's progress does not wait for it. Optional.
|
|
214
|
+
"""
|
|
215
|
+
return None
|
|
216
|
+
|
|
217
|
+
def write_tracks(self, data) -> None:
|
|
218
|
+
"""Record tracking output. Writers that cannot store tracks log once and drop them."""
|
|
219
|
+
if not self._warned_tracks:
|
|
220
|
+
self._warned_tracks = True
|
|
221
|
+
logger.warning(
|
|
222
|
+
f"the {self.format} writer does not store tracks; they are dropped"
|
|
223
|
+
)
|
|
224
|
+
|
|
225
|
+
@abstractmethod
|
|
226
|
+
def close(self) -> None: ...
|
|
227
|
+
|
|
228
|
+
@abstractmethod
|
|
229
|
+
def output_paths(self) -> dict[str, Path]:
|
|
230
|
+
"""Experiment name → the file or directory holding its data."""
|
|
231
|
+
|
|
232
|
+
@abstractmethod
|
|
233
|
+
def planned_paths(self, names, base_path: Path) -> dict[str, Path]:
|
|
234
|
+
"""Experiment name → output path that ``open`` would create."""
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
"""
|
|
2
|
+
The events table: what changed during a run, and what went wrong.
|
|
3
|
+
|
|
4
|
+
One row per applied or refused setting request, per late timepoint and per
|
|
5
|
+
acquisition error, written by the Manager to ``events.parquet`` in the
|
|
6
|
+
experiment directory (rewritten on every row) and to ``events.csv`` at
|
|
7
|
+
close. ``pyclm.io`` exposes it as ``ExperimentData.events``.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import datetime
|
|
13
|
+
import logging
|
|
14
|
+
import shutil
|
|
15
|
+
import threading
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
|
|
18
|
+
import pyarrow as pa
|
|
19
|
+
import pyarrow.csv as pacsv
|
|
20
|
+
import pyarrow.parquet as pq
|
|
21
|
+
|
|
22
|
+
logger = logging.getLogger(__name__)
|
|
23
|
+
|
|
24
|
+
EVENT_COLUMNS = (
|
|
25
|
+
"wall_time",
|
|
26
|
+
"t_requested",
|
|
27
|
+
"t_applied",
|
|
28
|
+
"experiment",
|
|
29
|
+
"channel",
|
|
30
|
+
"kind",
|
|
31
|
+
"key",
|
|
32
|
+
"old",
|
|
33
|
+
"new",
|
|
34
|
+
"status",
|
|
35
|
+
"detail",
|
|
36
|
+
"source",
|
|
37
|
+
)
|
|
38
|
+
EVENT_SCHEMA = pa.schema(
|
|
39
|
+
[
|
|
40
|
+
("wall_time", pa.string()),
|
|
41
|
+
("t_requested", pa.int32()),
|
|
42
|
+
("t_applied", pa.int32()),
|
|
43
|
+
("experiment", pa.string()),
|
|
44
|
+
("channel", pa.string()),
|
|
45
|
+
("kind", pa.string()),
|
|
46
|
+
("key", pa.string()),
|
|
47
|
+
("old", pa.string()),
|
|
48
|
+
("new", pa.string()),
|
|
49
|
+
("status", pa.string()),
|
|
50
|
+
("detail", pa.string()),
|
|
51
|
+
("source", pa.string()),
|
|
52
|
+
]
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _text(value) -> str | None:
|
|
57
|
+
return None if value is None else str(value)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class EventLog:
|
|
61
|
+
"""Append-only record of runtime events, persisted as parquet (and CSV at close)."""
|
|
62
|
+
|
|
63
|
+
def __init__(self, path: Path | None):
|
|
64
|
+
self.path = None if path is None else Path(path)
|
|
65
|
+
self.rows: list[dict] = []
|
|
66
|
+
self._lock = threading.Lock()
|
|
67
|
+
self.closed = False
|
|
68
|
+
|
|
69
|
+
def record(
|
|
70
|
+
self,
|
|
71
|
+
kind: str,
|
|
72
|
+
experiment: str | None = None,
|
|
73
|
+
channel: str | None = None,
|
|
74
|
+
key: str | None = None,
|
|
75
|
+
old=None,
|
|
76
|
+
new=None,
|
|
77
|
+
status: str = "applied",
|
|
78
|
+
detail: str | None = None,
|
|
79
|
+
t_requested: int | None = None,
|
|
80
|
+
t_applied: int | None = None,
|
|
81
|
+
source: str | None = None,
|
|
82
|
+
) -> dict:
|
|
83
|
+
row = {
|
|
84
|
+
"wall_time": datetime.datetime.now().isoformat(timespec="milliseconds"),
|
|
85
|
+
"t_requested": t_requested,
|
|
86
|
+
"t_applied": t_applied,
|
|
87
|
+
"experiment": experiment,
|
|
88
|
+
"channel": channel,
|
|
89
|
+
"kind": kind,
|
|
90
|
+
"key": key,
|
|
91
|
+
"old": _text(old),
|
|
92
|
+
"new": _text(new),
|
|
93
|
+
"status": status,
|
|
94
|
+
"detail": detail,
|
|
95
|
+
"source": source,
|
|
96
|
+
}
|
|
97
|
+
with self._lock:
|
|
98
|
+
self.rows.append(row)
|
|
99
|
+
self._write()
|
|
100
|
+
return row
|
|
101
|
+
|
|
102
|
+
def table(self) -> pa.Table:
|
|
103
|
+
columns = {k: [r.get(k) for r in self.rows] for k in EVENT_COLUMNS}
|
|
104
|
+
return pa.table(columns, schema=EVENT_SCHEMA)
|
|
105
|
+
|
|
106
|
+
def _write(self):
|
|
107
|
+
if self.path is None:
|
|
108
|
+
return
|
|
109
|
+
try:
|
|
110
|
+
tmp = self.path.with_suffix(".parquet.tmp")
|
|
111
|
+
pq.write_table(self.table(), tmp)
|
|
112
|
+
shutil.move(str(tmp), str(self.path))
|
|
113
|
+
except Exception as e:
|
|
114
|
+
logger.error(f"failed to write {self.path}: {e}", exc_info=True)
|
|
115
|
+
|
|
116
|
+
def close(self):
|
|
117
|
+
if self.closed:
|
|
118
|
+
return
|
|
119
|
+
self.closed = True
|
|
120
|
+
if self.path is None or not self.rows:
|
|
121
|
+
return
|
|
122
|
+
with self._lock:
|
|
123
|
+
self._write()
|
|
124
|
+
try:
|
|
125
|
+
pacsv.write_csv(self.table(), self.path.with_suffix(".csv"))
|
|
126
|
+
except Exception as e:
|
|
127
|
+
logger.error(f"failed to write events csv: {e}", exc_info=True)
|
|
128
|
+
|
|
129
|
+
def __len__(self) -> int:
|
|
130
|
+
return len(self.rows)
|