closed-loop-microscopy 1.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. closed_loop_microscopy-1.1.0.dist-info/METADATA +118 -0
  2. closed_loop_microscopy-1.1.0.dist-info/RECORD +74 -0
  3. closed_loop_microscopy-1.1.0.dist-info/WHEEL +4 -0
  4. closed_loop_microscopy-1.1.0.dist-info/entry_points.txt +5 -0
  5. closed_loop_microscopy-1.1.0.dist-info/licenses/LICENSE.md +7 -0
  6. pyclm/__init__.py +26 -0
  7. pyclm/__main__.py +8 -0
  8. pyclm/check.py +931 -0
  9. pyclm/cli.py +256 -0
  10. pyclm/commands.py +183 -0
  11. pyclm/controller.py +447 -0
  12. pyclm/convert_hdf5s.py +273 -0
  13. pyclm/core/__init__.py +20 -0
  14. pyclm/core/base_process.py +166 -0
  15. pyclm/core/core_interface.py +47 -0
  16. pyclm/core/datatypes.py +142 -0
  17. pyclm/core/events.py +194 -0
  18. pyclm/core/experiments.py +403 -0
  19. pyclm/core/grid.py +272 -0
  20. pyclm/core/kinds.py +42 -0
  21. pyclm/core/manager.py +861 -0
  22. pyclm/core/measure.py +266 -0
  23. pyclm/core/messages.py +124 -0
  24. pyclm/core/microscope.py +504 -0
  25. pyclm/core/pattern_process.py +282 -0
  26. pyclm/core/patterns/__init__.py +60 -0
  27. pyclm/core/patterns/bar_patterns.py +259 -0
  28. pyclm/core/patterns/cell_intensity_patterns.py +181 -0
  29. pyclm/core/patterns/composite.py +220 -0
  30. pyclm/core/patterns/embryo_patterns.py +90 -0
  31. pyclm/core/patterns/fbc_cell_movement.py +295 -0
  32. pyclm/core/patterns/pattern.py +610 -0
  33. pyclm/core/patterns/pulse_patterns.py +261 -0
  34. pyclm/core/patterns/static_patterns.py +58 -0
  35. pyclm/core/patterns/wave_patterns.py +95 -0
  36. pyclm/core/patterns/zoo.py +231 -0
  37. pyclm/core/plan.py +623 -0
  38. pyclm/core/position_mover.py +185 -0
  39. pyclm/core/queues.py +41 -0
  40. pyclm/core/real_core.py +158 -0
  41. pyclm/core/router.py +422 -0
  42. pyclm/core/segmentation/__init__.py +2 -0
  43. pyclm/core/segmentation/cellpose_segmentation.py +113 -0
  44. pyclm/core/segmentation/segmentation.py +48 -0
  45. pyclm/core/segmentation_process.py +179 -0
  46. pyclm/core/settings.py +120 -0
  47. pyclm/core/storage/__init__.py +37 -0
  48. pyclm/core/storage/base.py +234 -0
  49. pyclm/core/storage/events.py +130 -0
  50. pyclm/core/storage/hdf5_v1.py +337 -0
  51. pyclm/core/storage/ome_zarr.py +861 -0
  52. pyclm/core/tracking/__init__.py +28 -0
  53. pyclm/core/tracking/centroid.py +75 -0
  54. pyclm/core/tracking/tracking.py +124 -0
  55. pyclm/core/tracking_process.py +106 -0
  56. pyclm/core/virtual_microscope/__init__.py +0 -0
  57. pyclm/core/virtual_microscope/simulated_core.py +262 -0
  58. pyclm/core/virtual_microscope/simulated_source.py +206 -0
  59. pyclm/core/writer_process.py +130 -0
  60. pyclm/demo.py +225 -0
  61. pyclm/directories.py +563 -0
  62. pyclm/gui/__init__.py +28 -0
  63. pyclm/gui/debug_viewer.py +41 -0
  64. pyclm/gui/gui_controller.py +551 -0
  65. pyclm/gui/widgets.py +292 -0
  66. pyclm/io/__init__.py +29 -0
  67. pyclm/io/export.py +202 -0
  68. pyclm/io/readers.py +589 -0
  69. pyclm/methods.py +249 -0
  70. pyclm/mmconfig.py +143 -0
  71. pyclm/preview.py +414 -0
  72. pyclm/run_pyclm.py +298 -0
  73. pyclm/schema.py +806 -0
  74. pyclm/templates.py +165 -0
pyclm/convert_hdf5s.py ADDED
@@ -0,0 +1,273 @@
1
+ import json
2
+ import re
3
+ import tomllib
4
+ from argparse import ArgumentParser
5
+ from pathlib import Path
6
+
7
+ import cv2
8
+ import h5py
9
+ import numpy as np
10
+ import tifffile
11
+ from h5py import File
12
+ from natsort import natsorted
13
+ from skimage.transform import downscale_local_mean
14
+
15
+
16
+ def grayscale_lut():
17
+ ramp = np.arange(256, dtype=np.uint8)
18
+ return np.stack([ramp, ramp, ramp])
19
+
20
+
21
+ def cyan_lut():
22
+ zero = np.zeros(256, dtype=np.uint8)
23
+ ramp = np.arange(256, dtype=np.uint8)
24
+ return np.stack([zero, ramp, ramp])
25
+
26
+
27
+ def yellow_lut():
28
+ zero = np.zeros(256, dtype=np.uint8)
29
+ ramp = np.arange(256, dtype=np.uint8)
30
+ return np.stack([ramp, ramp, zero])
31
+
32
+
33
+ pattern_imagej_metadata = {
34
+ "mode": "composite",
35
+ "LUTs": [
36
+ grayscale_lut(),
37
+ cyan_lut(),
38
+ ],
39
+ "Ranges": [0, 5000, 0, 1000],
40
+ }
41
+
42
+ seg_imagej_metadata = {
43
+ "mode": "composite",
44
+ "LUTs": [
45
+ grayscale_lut(),
46
+ yellow_lut(),
47
+ cyan_lut(),
48
+ ],
49
+ "Ranges": [0, 5000, 0, 1, 0, 1000],
50
+ }
51
+
52
+
53
+ def get_mapping(projector_api):
54
+ mapping = projector_api.load_mapping(projector_api.get_projection_device())
55
+
56
+ m = mapping.get_map().values()
57
+
58
+ # horrible regex, TODO use ast instead
59
+ pattern = r"AffineTransform\[\[([-+]?\d*\.?\d+(?:[eE][-+]?\d+)?), ([-+]?\d*\.?\d+(?:[eE][-+]?\d+)?), ([-+]?\d*\.?\d+(?:[eE][-+]?\d+)?)\], \[([-+]?\d*\.?\d+(?:[eE][-+]?\d+)?), ([-+]?\d*\.?\d+(?:[eE][-+]?\d+)?), ([-+]?\d*\.?\d+(?:[eE][-+]?\d+)?)\]\]"
60
+
61
+ # Find all matches
62
+ matches = re.findall(pattern, m.to_string())
63
+
64
+ M = np.stack(np.array(matches).astype(float)).reshape(-1, 2, 3)
65
+ at = np.median(M, axis=0)
66
+
67
+ print(f"Affine Transform from calibration: {at}")
68
+ return at
69
+
70
+
71
+ def get_binning_from_metadata(f: File, chan_key: str):
72
+ """
73
+ Extract binning from file attributes or return default 1.
74
+ """
75
+ if "experiment_metadata" in list(f.attrs.keys()):
76
+ try:
77
+ meta = json.loads(f.attrs["experiment_metadata"])
78
+ # chan_key is typically "channel_NAME"
79
+ # channel keys in metadata are "NAME"
80
+ if chan_key.startswith("channel_"):
81
+ short_name = chan_key.replace("channel_", "", 1)
82
+ if short_name in meta.get("channels", {}):
83
+ return meta["channels"][short_name].get("binning", 1)
84
+ else:
85
+ return meta["segmentation"].get("binning", 1)
86
+ except Exception as e:
87
+ print(f"Error reading binning from metadata: {e}")
88
+ return 1
89
+
90
+
91
+ def make_tif(fp, at, chan="channel_638", binning_override=None):
92
+ ati = cv2.invertAffineTransform(at)
93
+ patterned = []
94
+
95
+ collected_frames = []
96
+ channel_key = f"{chan}"
97
+
98
+ # Open with SWMR support
99
+ try:
100
+ f = File(fp, mode="r", libver="latest", swmr=True)
101
+ except OSError:
102
+ # Fallback if file not accessible or not HDF5
103
+ print(f"Could not open {fp}")
104
+ return
105
+
106
+ # Attempt to read binning from metadata
107
+ binning = get_binning_from_metadata(f, channel_key)
108
+
109
+ if binning_override:
110
+ binning = binning_override
111
+
112
+ try:
113
+ indices = []
114
+
115
+ keys = list(f.keys())
116
+ for t_val in keys:
117
+ if t_val not in f:
118
+ continue
119
+ data_group = f[t_val]
120
+
121
+ if not isinstance(data_group, h5py.Group):
122
+ continue
123
+
124
+ if channel_key not in data_group:
125
+ continue
126
+
127
+ indices.append(t_val)
128
+
129
+ seg_seen = False
130
+
131
+ for t_val in natsorted(indices):
132
+ # Check if dataset exists / is complete
133
+ try:
134
+ if channel_key not in f[t_val] or "data" not in f[t_val][channel_key]:
135
+ continue
136
+
137
+ data_dset = f[t_val][channel_key]["data"]
138
+ # Ensure data is accessible (SWMR safety)
139
+ data_dset.refresh()
140
+ data = np.array(data_dset)
141
+
142
+ if data.shape == (0, 0):
143
+ continue
144
+
145
+ except Exception as e:
146
+ # might happen if writing is in progress for this specific frame
147
+ continue
148
+
149
+ collected_frames.append(data)
150
+
151
+ patterned_stack = [data]
152
+
153
+ # seg datasets are pre-allocated for every channel; an unwritten one
154
+ # stays (0, 0) and must be treated as absent
155
+ seg = f[t_val][channel_key].get("seg")
156
+ if seg is not None and seg.shape == data.shape:
157
+ patterned_stack.append(seg)
158
+ seg_seen = True
159
+
160
+ elif seg_seen:
161
+ continue
162
+
163
+ if "stim_aq" in f[t_val].keys() and "dmd" in f[t_val]["stim_aq"]:
164
+ pattern = np.array(f[t_val]["stim_aq"]["dmd"])
165
+ target_size = data.shape
166
+
167
+ # Ensure binning is valid integer
168
+ b = int(binning)
169
+
170
+ tf = cv2.warpAffine(
171
+ np.round(pattern).astype(np.uint8),
172
+ ati,
173
+ (target_size[1] * b, target_size[0] * b),
174
+ ).astype(np.uint16)
175
+ ds = downscale_local_mean(tf, (b, b)).astype(np.uint16)
176
+ patterned_stack.append(ds)
177
+
178
+ else:
179
+ patterned_stack.append(np.zeros(data.shape))
180
+
181
+ patterned.append(np.stack(patterned_stack).astype(np.uint16))
182
+
183
+ finally:
184
+ f.close()
185
+
186
+ if not collected_frames:
187
+ return
188
+
189
+ metadata = {"axes": "tcyx"}
190
+ if np.array(patterned).shape[1] > 2:
191
+ metadata.update(seg_imagej_metadata)
192
+ else:
193
+ metadata.update(pattern_imagej_metadata)
194
+
195
+ # Save patterned output
196
+ if patterned:
197
+ # Construct output filename
198
+ outpath_pattern = str(fp)[:-5] + f"_{chan}_patterns.tif"
199
+ tifffile.imwrite(
200
+ outpath_pattern,
201
+ np.array(patterned).astype(np.uint16),
202
+ imagej=True,
203
+ metadata=metadata,
204
+ )
205
+ print(f"Saved {outpath_pattern}")
206
+
207
+
208
+ def process_args():
209
+ parser = ArgumentParser(
210
+ description="Export PyCLM outputs (.zarr or .hdf5) to ImageJ hyperstacks"
211
+ )
212
+ parser.add_argument("directory", help="directory containing experiment outputs")
213
+ parser.add_argument(
214
+ "channels",
215
+ nargs="*",
216
+ help="channels/groups to export (default: all); e.g. 545 stim imaging",
217
+ )
218
+ parser.add_argument(
219
+ "--config", type=str, help="path to pyclm_config.toml file", default=None
220
+ )
221
+ parser.add_argument(
222
+ "--binning",
223
+ help="ignored (binning is read from the data)",
224
+ default=None,
225
+ )
226
+ return parser.parse_args()
227
+
228
+
229
+ def find_affine_transform(input_dir, config_path):
230
+ """Affine transform from pyclm_config.toml, or None if no config is found."""
231
+ if config_path is None:
232
+ from .directories import find_config_in
233
+
234
+ config_path = find_config_in(input_dir) or find_config_in(Path.cwd())
235
+ if config_path is None:
236
+ return None
237
+ config_path = Path(config_path)
238
+ if not config_path.exists():
239
+ return None
240
+ with open(config_path, "rb") as f:
241
+ config = tomllib.load(f)
242
+ return np.array(config["affine_transform"], dtype=np.float32)
243
+
244
+
245
+ def main():
246
+ from . import io as pyclm_io
247
+
248
+ args = process_args()
249
+ input_dir = Path(args.directory)
250
+ fallback_affine = find_affine_transform(input_dir, args.config)
251
+ wanted = set(args.channels)
252
+
253
+ for path in pyclm_io.find_experiments(input_dir):
254
+ with pyclm_io.open(path) as exp:
255
+ groups = None
256
+ if wanted:
257
+ groups = [
258
+ name
259
+ for name, g in exp.groups.items()
260
+ if name in wanted
261
+ or any(c in wanted for c in g.channels)
262
+ or ("stim" in wanted and g.name == "stim_aq")
263
+ ]
264
+ affine = (
265
+ exp.affine_transform
266
+ if exp.affine_transform is not None
267
+ else fallback_affine
268
+ )
269
+ pyclm_io.export_imagej(exp, groups=groups, affine=affine)
270
+
271
+
272
+ if __name__ == "__main__":
273
+ main()
pyclm/core/__init__.py ADDED
@@ -0,0 +1,20 @@
1
+ """
2
+ Import modules needed for controller.py
3
+ Import modules that may be used in creating custom pattern and segmentation methods
4
+ """
5
+
6
+ from .base_process import BaseProcess, PipelineProcess
7
+ from .experiments import ExperimentSchedule, MicroscopePosition
8
+ from .manager import Manager, MicroscopeOutbox, SLMBuffer
9
+ from .microscope import MicroscopeProcess
10
+ from .pattern_process import PatternProcess
11
+ from .patterns import ROI, CameraProperties, PatternContext, PatternMethod
12
+ from .plan import AcquisitionPlan, PlannedEvent
13
+ from .position_mover import BasicPositionMover, PFSPositionMover, PositionMover
14
+ from .queues import AllQueues
15
+ from .router import Router, RoutingError, Subscription
16
+ from .segmentation import SegmentationMethod
17
+ from .segmentation_process import SegmentationProcess
18
+ from .tracking import TrackingMethod, TrackRow, Tracks
19
+ from .tracking_process import TrackingProcess
20
+ from .writer_process import WriterProcess
@@ -0,0 +1,166 @@
1
+ import logging
2
+ from collections.abc import Callable
3
+ from queue import Empty, Queue
4
+ from threading import Event
5
+ from time import sleep
6
+ from typing import Any, ClassVar, NamedTuple
7
+
8
+ from .messages import Message
9
+
10
+ logger = logging.getLogger(__name__)
11
+
12
+
13
+ class QueueHandler(NamedTuple):
14
+ queue: Queue
15
+ handler: Callable[[Any], bool | None]
16
+
17
+
18
+ class BaseProcess:
19
+ """
20
+ Base class for processes that poll queues.
21
+ Eliminates busy waiting by sleeping when all queues are empty.
22
+
23
+ An exception raised by a handler is logged with its traceback and counted
24
+ in ``error_count``; the process keeps running.
25
+ """
26
+
27
+ def __init__(self, stop_event: Event | None = None, name: str = "process"):
28
+ self.stop_event = stop_event
29
+ self.name = name
30
+ self.queues: list[QueueHandler] = []
31
+ self.sleep_interval = 0.001
32
+ self.error_count = 0
33
+
34
+ def register_queue(self, queue: Queue, handler: Callable[[Any], bool | None]):
35
+ """
36
+ Register a queue to be polled.
37
+ :param queue: The queue to poll.
38
+ :param handler: A callable that takes the item from the queue.
39
+ It can optionally return True to signal the process loop to break (stop).
40
+ """
41
+ self.queues.append(QueueHandler(queue, handler))
42
+
43
+ def process(self):
44
+ """
45
+ Main process loop.
46
+ Polls all registered queues. SLEEPS if no work was done in a cycle.
47
+ """
48
+ logger.info(f"Started {self.name}")
49
+
50
+ while True:
51
+ if self.stop_event and self.stop_event.is_set():
52
+ logger.info(f"Force closing {self.name}")
53
+ break
54
+
55
+ did_work = False
56
+
57
+ for q_handler in self.queues:
58
+ try:
59
+ item = q_handler.queue.get_nowait()
60
+ except Empty:
61
+ continue
62
+
63
+ did_work = True
64
+
65
+ try:
66
+ should_stop = q_handler.handler(item)
67
+ except Exception:
68
+ self.error_count += 1
69
+ logger.error(
70
+ f"Error handling item in {self.name} "
71
+ f"({self.error_count} total)",
72
+ exc_info=True,
73
+ )
74
+ continue
75
+
76
+ if should_stop:
77
+ logger.info(f"{self.name} received stop signal from handler")
78
+ return
79
+
80
+ # If no queues had items, sleep briefly to avoid 100% CPU
81
+ if not did_work:
82
+ sleep(self.sleep_interval)
83
+
84
+ logger.info(f"Stopped {self.name}")
85
+
86
+
87
+ class PipelineProcess(BaseProcess):
88
+ """
89
+ A process that receives frame-derived data from the
90
+ :class:`~pyclm.core.router.Router` and may publish more.
91
+
92
+ Subclasses declare what they make in ``produces`` (``{kind: (input
93
+ kinds, ...)}``), say what they want in :meth:`subscriptions`, and
94
+ implement :meth:`handle_data`. The router calls :meth:`attach` with the
95
+ process's data inbox; data and the final ``StreamCloseMessage`` arrive on
96
+ it in order. When the stream ends the default :meth:`on_stream_end` ends
97
+ this process's own stream and exits the loop.
98
+
99
+ ``continuous`` producers need every acquired frame of their inputs once
100
+ they run for a channel at all (tracking); others run at whatever cadence
101
+ their consumers ask for (segmentation). ``always_active`` processes are
102
+ started even when nothing is routed to them (the pattern process answers
103
+ the Manager; the writer records every frame).
104
+ """
105
+
106
+ produces: ClassVar[dict[str, tuple[str, ...]]] = {}
107
+ continuous: ClassVar[bool] = False
108
+ always_active: ClassVar[bool] = False
109
+
110
+ def __init__(self, stop_event: Event | None = None, name: str = "process"):
111
+ super().__init__(stop_event, name)
112
+ self.router = None
113
+ self.data_inbox: Queue | None = None
114
+ self.stream_ended = False
115
+ self._own_stream_ended = False
116
+
117
+ # ------------------------------------------------------------ routing
118
+ def subscriptions(self, plan) -> list:
119
+ """What this process wants: a list of :class:`~pyclm.core.router.Subscription`."""
120
+ return []
121
+
122
+ def can_produce(self, kind: str, experiment, channel: str) -> bool:
123
+ """Whether this process can make ``kind`` for ``channel`` of ``experiment``."""
124
+ return kind in self.produces
125
+
126
+ def attach(self, router, data_inbox: Queue) -> None:
127
+ self.router = router
128
+ self.data_inbox = data_inbox
129
+ self.register_queue(data_inbox, self._handle_inbox)
130
+
131
+ def publish(self, data) -> int:
132
+ if self.router is None:
133
+ raise RuntimeError(f"{self.name} is not attached to a router")
134
+ return self.router.publish(data)
135
+
136
+ def end_stream(self) -> None:
137
+ """Tell the router this process will publish nothing more (idempotent)."""
138
+ if self._own_stream_ended or self.router is None:
139
+ return
140
+ self._own_stream_ended = True
141
+ self.router.end_stream(self.name)
142
+
143
+ # ----------------------------------------------------------- handling
144
+ def _handle_inbox(self, item) -> bool:
145
+ if isinstance(item, Message):
146
+ if item.message == "stream_close":
147
+ self.stream_ended = True
148
+ logger.info(f"{self.name}: data stream ended")
149
+ return bool(self.on_stream_end())
150
+ raise ValueError(f"{self.name}: unexpected message on data inbox: {item}")
151
+ self.handle_data(item)
152
+ return False
153
+
154
+ def handle_data(self, data) -> None:
155
+ raise NotImplementedError
156
+
157
+ def on_stream_end(self) -> bool:
158
+ """Called once after the last data item. Return True to exit the loop."""
159
+ self.end_stream()
160
+ return True
161
+
162
+ def process(self):
163
+ try:
164
+ super().process()
165
+ finally:
166
+ self.end_stream()
@@ -0,0 +1,47 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Sequence
4
+ from typing import Any, Protocol
5
+
6
+
7
+ class MicroscopeCoreInterface(Protocol):
8
+ def loadSystemConfiguration(self, configuration): ...
9
+
10
+ # SLM-related
11
+ def getSLMDevice(self) -> str: ...
12
+ def getSLMHeight(self, device: str) -> int: ...
13
+ def getSLMWidth(self, device: str) -> int: ...
14
+ def setSLMImage(self, device: str, image: Any) -> None: ...
15
+
16
+ # Config/device properties
17
+ def setConfig(self, group: str, config: str) -> None: ...
18
+ def setProperty(self, label: str, name: str, value: Any) -> None: ...
19
+ def getProperty(self, label: str, name: str) -> str: ...
20
+ def getAllowedPropertyValues(
21
+ self, device: str, prop_name: str
22
+ ) -> Sequence[str]: ...
23
+ def describe(self) -> str: ...
24
+ def setFocusDevice(self, label: str) -> None: ...
25
+ def getAvailableConfigGroups(self) -> Sequence[str]: ...
26
+ def getConfigGroupObject(
27
+ self, group: str, include_read_only: bool = False
28
+ ) -> Any: ...
29
+
30
+ # Camera-related
31
+ def getCameraDevice(self) -> str: ...
32
+ def setExposure(self, exposure_ms: float) -> None: ...
33
+ def snapImage(self) -> None: ...
34
+ def getImage(self) -> Any: ...
35
+ def getPixelSizeUm(self) -> float: ...
36
+ def getROI(self): ...
37
+ def setROI(self, x: int, y: int, width: int, height: int) -> None: ...
38
+
39
+ # Stage/focus/positioning
40
+ def getZPosition(self) -> float: ...
41
+ def getXYPosition(self) -> tuple[float, float]: ...
42
+ def setPosition(self, z: float) -> None: ...
43
+ def setXYPosition(self, x: float, y: float) -> None: ...
44
+ def setAutoFocusOffset(self, offset: float) -> None: ...
45
+
46
+ # Synchronization
47
+ def waitForSystem(self) -> None: ...
@@ -0,0 +1,142 @@
1
+ """
2
+ Contains classes for passing structured data between processes.
3
+
4
+ Frame-derived data carries the acquisition event it came from and a
5
+ ``kind`` (``"raw"``, ``"seg"``, ``"tracks"``) that the Router uses to look up
6
+ its subscribers.
7
+ """
8
+
9
+ from typing import ClassVar
10
+ from uuid import uuid4
11
+
12
+ import numpy as np
13
+
14
+ from .events import AcquisitionEvent
15
+ from .kinds import DEFAULT_SEGMENTATION, seg_kind
16
+
17
+
18
+ class EventSLMPattern:
19
+ """
20
+ The SLM buffer's reply to an update-pattern handshake: the DMD image to
21
+ apply, its id, and the camera-space pattern (uint8, at the stimulation
22
+ binning) it was made from, for the record.
23
+ """
24
+
25
+ def __init__(
26
+ self,
27
+ event_id,
28
+ pattern,
29
+ pattern_unique_id=0,
30
+ camera_pattern=None,
31
+ dmd_ids=None,
32
+ ):
33
+ self.event_id = event_id
34
+ # one DMD image, or a list of them (one per tile of a grid experiment)
35
+ self.pattern = pattern
36
+ self.pattern_unique_id = pattern_unique_id
37
+ self.camera_pattern = camera_pattern
38
+ # the per-tile DMD image ids of a grid experiment, else None
39
+ self.dmd_ids = dmd_ids
40
+
41
+
42
+ class SkippedAcquisition:
43
+ """
44
+ A planned frame the microscope did not take: the position's only
45
+ acquisition was the stimulation frame and the pattern was blank. The
46
+ Manager hands it to the writer so the timepoint still completes.
47
+ """
48
+
49
+ kind = "skipped"
50
+
51
+ def __init__(self, event: AcquisitionEvent):
52
+ self.event = event
53
+
54
+
55
+ class GenericData:
56
+ def __init__(self, data: np.ndarray):
57
+ self.data = data
58
+
59
+
60
+ class AcquisitionData(GenericData):
61
+ """A raw camera frame and the event that produced it."""
62
+
63
+ kind: ClassVar[str] = "raw"
64
+
65
+ def __init__(self, event: AcquisitionEvent, data: np.ndarray):
66
+ super().__init__(data)
67
+
68
+ self.event = event
69
+ self.event_id = event.id
70
+ self.channel_id = event.channel_id
71
+
72
+
73
+ class StimulationData(AcquisitionData):
74
+ """
75
+ A camera frame taken during stimulation, with the DMD pattern that was
76
+ applied and, when known, the camera-space pattern it came from.
77
+ """
78
+
79
+ def __init__(
80
+ self,
81
+ event: AcquisitionEvent,
82
+ data: np.ndarray,
83
+ dmd_pattern: np.ndarray,
84
+ pattern_id,
85
+ camera_pattern: np.ndarray | None = None,
86
+ dmd_ids=None,
87
+ ):
88
+ super().__init__(event, data)
89
+ # one DMD image, or a list of them (one per tile of a grid experiment)
90
+ self.dmd_pattern = dmd_pattern
91
+ self.pattern_id = pattern_id
92
+ self.camera_pattern = camera_pattern
93
+ self.dmd_ids = dmd_ids
94
+
95
+
96
+ class SegmentationData(AcquisitionData):
97
+ """
98
+ A label image for one frame (``data``), sharing the frame's event.
99
+ ``name`` says which ``[segmentation]`` table produced it; the routing
100
+ ``kind`` is ``"seg"`` for the default table and ``"seg:<name>"`` otherwise.
101
+ """
102
+
103
+ kind: ClassVar[str] = "seg"
104
+
105
+ def __init__(
106
+ self,
107
+ event: AcquisitionEvent,
108
+ data: np.ndarray,
109
+ name: str = DEFAULT_SEGMENTATION,
110
+ ):
111
+ super().__init__(event, data)
112
+ self.name = name or DEFAULT_SEGMENTATION
113
+ self.kind = seg_kind(self.name)
114
+
115
+
116
+ class TrackingData(AcquisitionData):
117
+ """
118
+ Tracking output for one frame: ``data`` (alias ``labels``) is the label
119
+ image relabelled with stable track ids; ``rows`` are the per-object
120
+ records for this timepoint (see ``pyclm.core.tracking.TrackRow``).
121
+ """
122
+
123
+ kind: ClassVar[str] = "tracks"
124
+
125
+ def __init__(self, event: AcquisitionEvent, labels: np.ndarray, rows: list):
126
+ super().__init__(event, labels)
127
+ self.rows = list(rows)
128
+
129
+ @property
130
+ def labels(self) -> np.ndarray:
131
+ return self.data
132
+
133
+
134
+ class CameraPattern(GenericData):
135
+ """A pattern in camera coordinates (0-1 floats at ``binning``) from a pattern method."""
136
+
137
+ def __init__(self, experiment_name, data: np.ndarray, binning=1):
138
+ super().__init__(data)
139
+
140
+ self.experiment = experiment_name
141
+ self.pattern_id = uuid4()
142
+ self.binning = binning