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
@@ -0,0 +1,261 @@
1
+ """
2
+ Open-loop pulse trains: stimulation that varies in time but never moves.
3
+
4
+ ``global_pulse`` gates the whole field on a period; ``pulse_schedule`` gates
5
+ it on an explicit list of intervals; ``blinking_bar`` gates the stationary
6
+ bar's stripes with the same temporal gate as ``global_pulse``.
7
+ """
8
+
9
+ import numpy as np
10
+
11
+ from .bar_patterns import _stripe_is_on
12
+ from .pattern import PatternMethod
13
+ from .zoo import ZooMeta
14
+
15
+
16
+ def _in_window(t_minutes, start_min, stop_min) -> bool:
17
+ """Whether ``t_minutes`` lies in ``[start_min, stop_min)``; no ``stop_min`` means no end."""
18
+ if t_minutes < start_min:
19
+ return False
20
+ return stop_min is None or t_minutes < stop_min
21
+
22
+
23
+ def _gate_is_on(t_minutes, period_min, on_min, phase_min, start_min, stop_min) -> bool:
24
+ """
25
+ Whether a periodic gate is open at ``t_minutes``: on for ``on_min`` out of
26
+ every ``period_min``, the first on-edge at ``start_min + phase_min``, and
27
+ nothing at all outside ``[start_min, stop_min)``.
28
+ """
29
+ if not _in_window(t_minutes, start_min, stop_min):
30
+ return False
31
+ t_rel = (t_minutes - start_min - phase_min) % period_min
32
+ return t_rel < on_min
33
+
34
+
35
+ def _check_gate(period_min, on_min, name):
36
+ if period_min <= 0:
37
+ raise ValueError(f"{name}: period_min must be positive, got {period_min}")
38
+ if not 0 <= on_min <= period_min:
39
+ raise ValueError(
40
+ f"{name}: on_min must be between 0 and period_min "
41
+ f"({period_min}), got {on_min}"
42
+ )
43
+
44
+
45
+ class GlobalPulsePattern(PatternMethod):
46
+ """
47
+ Spatially uniform pulse train: the whole field on for ``on_min`` out of
48
+ every ``period_min``, within ``[start_min, stop_min)``.
49
+
50
+ ``phase_min`` offsets the first on-edge from ``start_min``. To make the
51
+ train the temporal twin of a ``bar``, set ``reference_bar_speed`` to that
52
+ bar's speed instead and the phase is derived from the field geometry: see
53
+ :attr:`effective_phase_min`.
54
+ """
55
+
56
+ name = "global_pulse"
57
+
58
+ def __init__(
59
+ self,
60
+ period_min=100.0,
61
+ on_min=20.0,
62
+ phase_min=0.0,
63
+ reference_bar_speed=None,
64
+ start_min=0.0,
65
+ stop_min=None,
66
+ **kwargs,
67
+ ):
68
+ """
69
+ :param period_min: minutes between successive on-edges
70
+ :param on_min: minutes the field stays on at each on-edge
71
+ :param phase_min: minutes from ``start_min`` to the first on-edge
72
+ :param reference_bar_speed: um/min of the ``bar`` this train twins;
73
+ phases the first on-edge to that bar
74
+ reaching the field centre
75
+ :param start_min: experiment minute stimulation begins
76
+ :param stop_min: experiment minute stimulation ends (None: never)
77
+ """
78
+ super().__init__(**kwargs)
79
+
80
+ _check_gate(period_min, on_min, self.name)
81
+ if reference_bar_speed == 0:
82
+ raise ValueError(
83
+ f"{self.name}: reference_bar_speed must be non-zero "
84
+ "(a stationary bar has no arrival time)"
85
+ )
86
+
87
+ self.period_min = period_min
88
+ self.on_min = on_min
89
+ self.phase_min = phase_min
90
+ self.reference_bar_speed = reference_bar_speed
91
+ self.start_min = start_min
92
+ self.stop_min = stop_min
93
+
94
+ @property
95
+ def effective_phase_min(self) -> float:
96
+ """
97
+ The phase actually used, in minutes after ``start_min``.
98
+
99
+ With ``reference_bar_speed`` set, ``phase_min`` is added to the minute
100
+ at which a ``bar`` of that speed reaches the centre of the field.
101
+ ``bar`` lights a point ``y`` when ``(t - y / bar_speed) % period_time``
102
+ is within its duty cycle, so that on-edge falls at ``y / bar_speed``;
103
+ taking ``y`` from :meth:`~pyclm.core.patterns.pattern.PatternMethod.center_um`
104
+ keeps the two in one micron frame, and the result needs nothing beyond
105
+ the camera geometry PyCLM already injects. It follows a binning change,
106
+ since the field's size in microns does not.
107
+
108
+ This is only the twin of that bar if ``period_min`` is the bar's
109
+ temporal period, i.e. its spacing divided by its speed.
110
+ """
111
+ phase = self.phase_min
112
+ if self.reference_bar_speed:
113
+ _centre_x, centre_y = self.center_um()
114
+ phase += centre_y / self.reference_bar_speed
115
+ return phase % self.period_min
116
+
117
+ def is_on(self, t_minutes) -> bool:
118
+ """Whether the field is lit at ``t_minutes`` of the experiment."""
119
+ return _gate_is_on(
120
+ t_minutes,
121
+ self.period_min,
122
+ self.on_min,
123
+ self.effective_phase_min,
124
+ self.start_min,
125
+ self.stop_min,
126
+ )
127
+
128
+ def generate(self, context):
129
+ h, w = self.pattern_shape
130
+
131
+ return np.full(
132
+ (int(h), int(w)), self.is_on(context.time / 60), dtype=np.float16
133
+ )
134
+
135
+
136
+ class PulseSchedulePattern(PatternMethod):
137
+ """
138
+ Spatially uniform stimulation on an explicit schedule: the whole field is
139
+ on whenever the experiment time falls inside one of the listed intervals.
140
+ ``global_pulse`` with a list instead of a period, for isolated pulses::
141
+
142
+ pulses = [[60, 20], [540, 20]] # 20 min at 1 h and at 9 h
143
+ """
144
+
145
+ name = "pulse_schedule"
146
+
147
+ def __init__(self, pulses=(), start_min=0.0, **kwargs):
148
+ """
149
+ :param pulses: list of ``[start_min, duration_min]`` pairs, each
150
+ measured from ``start_min``
151
+ :param start_min: experiment minute the schedule is measured from
152
+ """
153
+ super().__init__(**kwargs)
154
+
155
+ self.pulses = [self._check_pulse(p) for p in pulses]
156
+ self.start_min = start_min
157
+
158
+ def _check_pulse(self, pulse):
159
+ try:
160
+ start, duration = pulse
161
+ except (TypeError, ValueError):
162
+ raise ValueError(
163
+ f"{self.name}: each pulse must be a [start_min, duration_min] "
164
+ f"pair, got {pulse!r}"
165
+ ) from None
166
+ if duration <= 0:
167
+ raise ValueError(
168
+ f"{self.name}: pulse duration must be positive, got {duration}"
169
+ )
170
+ return [float(start), float(duration)]
171
+
172
+ def is_on(self, t_minutes) -> bool:
173
+ """Whether the field is lit at ``t_minutes`` of the experiment."""
174
+ t_rel = t_minutes - self.start_min
175
+ return any(start <= t_rel < start + duration for start, duration in self.pulses)
176
+
177
+ def generate(self, context):
178
+ h, w = self.pattern_shape
179
+
180
+ return np.full(
181
+ (int(h), int(w)), self.is_on(context.time / 60), dtype=np.float16
182
+ )
183
+
184
+
185
+ class BlinkingBarPattern(PatternMethod):
186
+ """
187
+ Stationary stripes that blink: the spatial mask of ``bar`` at speed 0
188
+ (stripes of width ``duty_cycle * spacing_um``, repeating every
189
+ ``spacing_um``, the first edge at ``offset_um``) ANDed with the temporal
190
+ gate of ``global_pulse``. ``on_min = period_min`` is the limiting case of
191
+ stripes that never blink.
192
+ """
193
+
194
+ name = "blinking_bar"
195
+ zoo_meta = ZooMeta(
196
+ source="mdck",
197
+ kwargs={"spacing_um": 100, "duty_cycle": 0.2, "period_min": 100, "on_min": 20},
198
+ title="Blinking Bar",
199
+ description="Stationary stripes gated on and off by a periodic pulse train.",
200
+ )
201
+
202
+ def __init__(
203
+ self,
204
+ spacing_um=100.0,
205
+ duty_cycle=0.2,
206
+ period_min=100.0,
207
+ on_min=20.0,
208
+ offset_um=0.0,
209
+ phase_min=0.0,
210
+ start_min=0.0,
211
+ stop_min=None,
212
+ **kwargs,
213
+ ):
214
+ """
215
+ :param spacing_um: stripe period along the bar axis, in um
216
+ :param duty_cycle: fraction of ``spacing_um`` that is lit (float 0-1)
217
+ :param period_min: minutes between successive on-edges
218
+ :param on_min: minutes the stripes stay on at each on-edge
219
+ :param offset_um: position of the first stripe edge, in um
220
+ :param phase_min: minutes from ``start_min`` to the first on-edge
221
+ :param start_min: experiment minute stimulation begins
222
+ :param stop_min: experiment minute stimulation ends (None: never)
223
+ """
224
+ super().__init__(**kwargs)
225
+
226
+ _check_gate(period_min, on_min, self.name)
227
+ if spacing_um <= 0:
228
+ raise ValueError(f"{self.name}: spacing_um must be positive")
229
+
230
+ self.spacing_um = spacing_um
231
+ self.duty_cycle = duty_cycle
232
+ self.period_min = period_min
233
+ self.on_min = on_min
234
+ self.offset_um = offset_um
235
+ self.phase_min = phase_min
236
+ self.start_min = start_min
237
+ self.stop_min = stop_min
238
+
239
+ def is_on(self, t_minutes) -> bool:
240
+ """Whether the stripes are lit at ``t_minutes`` of the experiment."""
241
+ return _gate_is_on(
242
+ t_minutes,
243
+ self.period_min,
244
+ self.on_min,
245
+ self.phase_min,
246
+ self.start_min,
247
+ self.stop_min,
248
+ )
249
+
250
+ def spatial_mask(self) -> np.ndarray:
251
+ """The stripes, as ``bar`` draws them at speed 0."""
252
+ _xx, yy = self.get_um_meshgrid()
253
+
254
+ return _stripe_is_on(yy, self.spacing_um, self.duty_cycle, self.offset_um)
255
+
256
+ def generate(self, context):
257
+ if not self.is_on(context.time / 60):
258
+ h, w = self.pattern_shape
259
+ return np.zeros((int(h), int(w)), dtype=np.float16)
260
+
261
+ return self.spatial_mask().astype(np.float16)
@@ -0,0 +1,58 @@
1
+ import numpy as np
2
+
3
+ from .pattern import PatternMethod
4
+ from .zoo import ZooMeta
5
+
6
+
7
+ class CirclePattern(PatternMethod):
8
+ """
9
+ Projects a circle of radius rad in the center of the camera
10
+ """
11
+
12
+ name = "circle"
13
+ zoo_meta = ZooMeta(
14
+ source="mdck",
15
+ kwargs={"rad": 60},
16
+ title="Circle",
17
+ description="Filled circle centerd on the camera field of view.",
18
+ )
19
+
20
+ def __init__(self, rad=1, **kwargs):
21
+ super().__init__(**kwargs)
22
+
23
+ self.rad = rad
24
+
25
+ def generate(self, context):
26
+ h, w = self.pattern_shape
27
+
28
+ center_x = self.pixel_size_um * w / 2.0
29
+ center_y = self.pixel_size_um * h / 2.0
30
+
31
+ xx, yy = self.get_um_meshgrid()
32
+
33
+ return (((xx - center_x) ** 2 + (yy - center_y) ** 2) < (self.rad**2)).astype(
34
+ np.float16
35
+ )
36
+
37
+
38
+ class FullOnPattern(PatternMethod):
39
+ """
40
+ Turns on the entire ROI
41
+ """
42
+
43
+ name = "full_on"
44
+ zoo_meta = ZooMeta(
45
+ source="mdck",
46
+ kwargs={},
47
+ title="Full On",
48
+ description="Illuminates the entire camera field of view.",
49
+ )
50
+
51
+ def __init__(self, **kwargs):
52
+ super().__init__(**kwargs)
53
+
54
+ def generate(self, context):
55
+ h, w = self.pattern_shape
56
+ pattern = np.ones((int(h), int(w)), dtype=np.float16)
57
+
58
+ return pattern
@@ -0,0 +1,95 @@
1
+ import numpy as np
2
+
3
+ from .pattern import PatternMethod
4
+ from .zoo import ZooMeta
5
+
6
+
7
+ class WavePatternBase(PatternMethod):
8
+ """
9
+ Creates a WavePattern or StationaryWavePattern depending on the requested wavespeed
10
+ """
11
+
12
+ def __new__(cls, *args, **kwargs):
13
+ if cls is WavePatternBase: # Check if the base class is being instantiated
14
+ if kwargs.get("wave_speed") != 0:
15
+ return super().__new__(WavePattern)
16
+ else:
17
+ return super().__new__(StationaryWavePattern)
18
+ return super().__new__(cls)
19
+
20
+ def __init__(self, *args, **kwargs):
21
+ super().__init__(*args, **kwargs)
22
+
23
+
24
+ class StationaryWavePattern(WavePatternBase):
25
+ """
26
+ Wave coming out from the center
27
+ """
28
+
29
+ name = "wave (stationary)"
30
+
31
+ def __init__(self, duty_cycle=0.2, wave_speed=0, period=30, **kwargs):
32
+ """
33
+ :param duty_cycle: fraction of time spent on (float 0-1), and consequently fraction of
34
+ vertical axis containing "on" pixels
35
+ :param wave_speed: speed in um/min
36
+ :param period: period in um
37
+ """
38
+ super().__init__(**kwargs)
39
+
40
+ self.duty_cycle = duty_cycle
41
+ self.wave_speed = 0
42
+ self.period_space = period # in um
43
+ self.period_time = 0 # in minutes
44
+
45
+ def generate(self, context):
46
+ xx, yy = self.get_um_meshgrid()
47
+ center_x, center_y = self.center_um()
48
+ distance = np.sqrt((xx - center_x) ** 2 + (yy - center_y) ** 2)
49
+
50
+ is_on = ((distance / self.period_space) % 1.0) < self.duty_cycle
51
+
52
+ return is_on.astype(np.float16)
53
+
54
+
55
+ class WavePattern(WavePatternBase):
56
+ """
57
+ moves a wave in or out of the center
58
+ """
59
+
60
+ name = "wave"
61
+ zoo_meta = ZooMeta(
62
+ source="mdck",
63
+ kwargs={"duty_cycle": 0.2, "wave_speed": 10, "period": 100, "direction": 1},
64
+ title="Radial Wave",
65
+ description="Concentric rings propagating outward from the center.",
66
+ )
67
+
68
+ def __init__(self, duty_cycle=0.2, wave_speed=1, period=30, direction=1, **kwargs):
69
+ """
70
+ :param duty_cycle: fraction of time spent on (float 0-1), and consequently fraction of
71
+ radial axis containing "on" pixels
72
+ :param wave_speed: speed in um/min
73
+ :param period: period in um
74
+ :param direction: movement in/out relative to the center. 1 is out; -1 is in
75
+ """
76
+ super().__init__(**kwargs)
77
+
78
+ self.duty_cycle = duty_cycle
79
+ self.wave_speed = wave_speed
80
+ self.period_space = period # in um
81
+ self.period_time = period / wave_speed # in minutes
82
+ self.direction = direction
83
+
84
+ def generate(self, context):
85
+ t = context.time / 60
86
+
87
+ xx, yy = self.get_um_meshgrid()
88
+ center_x, center_y = self.center_um()
89
+ distance = np.sqrt((xx - center_x) ** 2 + (yy - center_y) ** 2)
90
+
91
+ is_on = (
92
+ ((t * self.direction) - (distance / self.wave_speed)) % self.period_time
93
+ ) < self.duty_cycle * self.period_time
94
+
95
+ return is_on.astype(np.float16)
@@ -0,0 +1,231 @@
1
+ """
2
+ Zoo metadata and context for the pattern-method documentation gallery.
3
+
4
+ Usage
5
+ -----
6
+ Attach a ``zoo_meta`` class variable to any :class:`PatternMethod` subclass
7
+ to include it in the generated gallery::
8
+
9
+ class MyPattern(PatternMethod):
10
+ zoo_meta = ZooMeta(
11
+ source="mdck",
12
+ kwargs={"period": 40, "duty_cycle": 0.3},
13
+ time_seconds=120.0,
14
+ title="My Pattern",
15
+ description="A one-line description shown in the gallery card.",
16
+ )
17
+
18
+ The ``source`` field names a sample image stored in
19
+ ``documentation/zoo_sources/<source>.tif`` (and optionally
20
+ ``<source>_seg.tif`` for a label image). ``kwargs`` are passed verbatim
21
+ to the pattern constructor.
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ from dataclasses import dataclass, field
27
+
28
+ import numpy as np
29
+
30
+ # ---------------------------------------------------------------------------
31
+ # ZooMeta
32
+ # ---------------------------------------------------------------------------
33
+
34
+
35
+ @dataclass
36
+ class ZooMeta:
37
+ """Declares how a PatternMethod should appear in the documentation zoo.
38
+
39
+ Parameters
40
+ ----------
41
+ source:
42
+ Name of the sample image set, e.g. ``"mdck"``, ``"fly"``, or
43
+ ``"mcf10a"``. A file ``documentation/zoo_sources/<source>.tif``
44
+ must exist; ``<source>_seg.tif`` is optional (synthetic blobs are
45
+ used when absent).
46
+ kwargs:
47
+ Keyword arguments forwarded to the pattern-method constructor.
48
+ time_seconds:
49
+ Experiment time (seconds) injected into the context.
50
+ title:
51
+ Gallery-card heading. Defaults to the class ``name`` attribute.
52
+ description:
53
+ One-sentence description shown beneath the image.
54
+ """
55
+
56
+ source: str
57
+ kwargs: dict = field(default_factory=dict)
58
+ time_seconds: float = 0.0
59
+ title: str = ""
60
+ description: str = ""
61
+
62
+
63
+ # ---------------------------------------------------------------------------
64
+ # ZooContext - minimal PatternContext substitute
65
+ # ---------------------------------------------------------------------------
66
+
67
+
68
+ class ZooContext:
69
+ """Minimal substitute for :class:`PatternContext` used during zoo builds.
70
+
71
+ Any channel name is accepted; all channels map to the same raw/seg
72
+ images supplied at construction time.
73
+
74
+ Parameters
75
+ ----------
76
+ raw_image:
77
+ 2-D uint16 (or similar) array representing a raw fluorescence image.
78
+ seg_image:
79
+ 2-D integer label array (0 = background, >0 = cell id).
80
+ time_seconds:
81
+ Value exposed as ``context.time``.
82
+ """
83
+
84
+ def __init__(
85
+ self,
86
+ raw_image: np.ndarray,
87
+ seg_image: np.ndarray,
88
+ time_seconds: float = 0.0,
89
+ ) -> None:
90
+ self._raw = raw_image
91
+ self._seg = seg_image
92
+ self.time = time_seconds
93
+
94
+ # --- PatternContext interface (channel-agnostic variants) ---------------
95
+
96
+ def raw(self, channel_name: str) -> np.ndarray:
97
+ return self._raw
98
+
99
+ def segmentation(self, channel_name: str, name: str = "segmentation") -> np.ndarray:
100
+ return self._seg
101
+
102
+ def regions(self, channel_name: str, name: str = "segmentation"):
103
+ from ..measure import Regions
104
+
105
+ return Regions(self._seg)
106
+
107
+ # --- runtime settings: recorded, never applied, in the zoo ---------------
108
+ @property
109
+ def requests(self) -> list:
110
+ return list(getattr(self, "_requests", []))
111
+
112
+ def settings(self, channel_name: str) -> dict:
113
+ return {
114
+ "exposure_ms": 10.0,
115
+ "binning": 1,
116
+ "config_groups": {},
117
+ "device_properties": {},
118
+ }
119
+
120
+ def position(self):
121
+ return None
122
+
123
+ def _remember(self, change):
124
+ self.__dict__.setdefault("_requests", []).append(change)
125
+
126
+ def set_exposure(self, channel_name, ms):
127
+ self._remember(("exposure", channel_name, "exposure_ms", ms))
128
+
129
+ def set_config(self, channel_name, group, preset):
130
+ self._remember(("config", channel_name, group, preset))
131
+
132
+ def set_property(self, channel_name, device, prop, value):
133
+ self._remember(("property", channel_name, f"{device}-{prop}", value))
134
+
135
+ def set_position(self, x=None, y=None, z=None, pfs_offset=None):
136
+ for key, value in (("x", x), ("y", y), ("z", z), ("pfs_offset", pfs_offset)):
137
+ if value is not None:
138
+ self._remember(("position", None, key, value))
139
+
140
+ def stim_raw(self) -> np.ndarray:
141
+ return self._raw
142
+
143
+ def stim_seg(self) -> np.ndarray:
144
+ return self._seg
145
+
146
+ # --- Stage 3 additions: timepoint, history, tracks, previous patterns ---
147
+
148
+ t = 0
149
+ generation = 0
150
+
151
+ def tracks(self, channel_name: str):
152
+ from skimage.measure import regionprops_table
153
+
154
+ from ..tracking import TrackRow, Tracks
155
+
156
+ props = regionprops_table(
157
+ np.asarray(self._seg).astype(np.int64),
158
+ properties=("label", "centroid", "area"),
159
+ )
160
+ rows = [
161
+ TrackRow(int(lab), int(lab), float(y), float(x), int(a), 0)
162
+ for lab, y, x, a in zip(
163
+ props["label"],
164
+ props["centroid-0"],
165
+ props["centroid-1"],
166
+ props["area"],
167
+ strict=True,
168
+ )
169
+ ]
170
+ return Tracks(self._seg, rows)
171
+
172
+ def history(self, channel_name: str, kind: str = "seg", n=None) -> list:
173
+ if kind == "tracks":
174
+ return [self.tracks(channel_name)]
175
+ return [self._seg if kind.startswith("seg") else self._raw]
176
+
177
+ def stim_history(self, kind: str = "raw", n=None) -> list:
178
+ return self.history("", kind, n)
179
+
180
+ def last_pattern(self):
181
+ return None
182
+
183
+ def pattern_history(self, n=None) -> list:
184
+ return []
185
+
186
+
187
+ # ---------------------------------------------------------------------------
188
+ # Zoo subclass factory
189
+ # ---------------------------------------------------------------------------
190
+
191
+
192
+ def make_zoo_subclass(cls: type, pattern_shape: tuple[int, int], pixel_size_um: float):
193
+ """Return a zoo-safe subclass of *cls*.
194
+
195
+ The subclass pre-computes the um-coordinate meshgrid from the sample
196
+ image geometry and overrides :meth:`get_um_meshgrid` and
197
+ :meth:`center_um` so that ``generate()`` is fully independent of any
198
+ hardware state that would normally be injected by
199
+ :meth:`PatternMethod.configure_system`.
200
+
201
+ Parameters
202
+ ----------
203
+ cls:
204
+ A :class:`PatternMethod` subclass.
205
+ pattern_shape:
206
+ ``(height, width)`` of the sample image in pixels.
207
+ pixel_size_um:
208
+ Physical pixel size in micrometres (from the source metadata).
209
+
210
+ Returns
211
+ -------
212
+ type
213
+ A new class (not an instance) ready to be instantiated with the
214
+ pattern's ``zoo_meta.kwargs``.
215
+ """
216
+ h, w = pattern_shape
217
+ y_range = np.arange(h) * pixel_size_um
218
+ x_range = np.arange(w) * pixel_size_um
219
+ _xx, _yy = np.meshgrid(x_range, y_range)
220
+ _center = (h * pixel_size_um / 2.0, w * pixel_size_um / 2.0)
221
+
222
+ class _ZooVariant(cls):
223
+ def get_um_meshgrid(self) -> tuple[np.ndarray, np.ndarray]:
224
+ return _xx, _yy
225
+
226
+ def center_um(self) -> tuple[float, float]:
227
+ return _center
228
+
229
+ _ZooVariant.__name__ = f"{cls.__name__}ZooVariant"
230
+ _ZooVariant.__qualname__ = _ZooVariant.__name__
231
+ return _ZooVariant