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,610 @@
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ from collections import defaultdict, deque
5
+ from pathlib import Path
6
+ from typing import NamedTuple
7
+ from uuid import UUID
8
+
9
+ import numpy as np
10
+ from h5py import File
11
+ from natsort import natsorted
12
+
13
+ from ..datatypes import AcquisitionData, SegmentationData
14
+ from ..experiments import Experiment
15
+ from ..kinds import DEFAULT_SEGMENTATION, base_kind, seg_kind
16
+ from ..measure import Regions
17
+ from ..settings import STIMULATION
18
+ from ..settings import config as _config_change
19
+ from ..settings import device_property as _property_change
20
+ from ..settings import exposure as _exposure_change
21
+ from ..settings import position as _position_change
22
+ from ..tracking import Tracks
23
+
24
+ logger = logging.getLogger(__name__)
25
+
26
+
27
+ class ROI(NamedTuple):
28
+ x_offset: int
29
+ y_offset: int
30
+ width: int
31
+ height: int
32
+
33
+
34
+ class CameraProperties(NamedTuple):
35
+ roi: ROI
36
+ pixel_size_um: float
37
+
38
+
39
+ class AcquiredImageRequest(NamedTuple):
40
+ """What a pattern method needs of one channel each time it runs."""
41
+
42
+ id: UUID
43
+ needs_raw: bool
44
+ needs_seg: bool
45
+ needs_tracks: bool = False
46
+ # how many past deliveries of this channel to keep for context.history()
47
+ history: int = 1
48
+ # named segmentations wanted besides the default one (add_requirement(seg="nuclei"))
49
+ segmentations: tuple[str, ...] = ()
50
+
51
+ @property
52
+ def kinds(self) -> tuple[str, ...]:
53
+ """The routing kinds this request asks for, in delivery order."""
54
+ kinds = []
55
+ if self.needs_raw:
56
+ kinds.append("raw")
57
+ if self.needs_seg:
58
+ kinds.append("seg")
59
+ kinds += [seg_kind(n) for n in self.segmentations if seg_kind(n) != "seg"]
60
+ if self.needs_tracks:
61
+ kinds.append("tracks")
62
+ return tuple(kinds)
63
+
64
+
65
+ def _seg_names(seg) -> tuple[str, ...]:
66
+ """Normalise the ``seg`` argument of add_requirement to segmentation names."""
67
+ if seg is True:
68
+ return (DEFAULT_SEGMENTATION,)
69
+ if not seg:
70
+ return ()
71
+ if isinstance(seg, str):
72
+ return (seg,)
73
+ return tuple(str(s) for s in seg)
74
+
75
+
76
+ class DataDock:
77
+ def __init__(self, time_seconds, requirements: list[AcquiredImageRequest]):
78
+ self.time_seconds = time_seconds
79
+ self.requirements = requirements
80
+ self.data = defaultdict(dict)
81
+
82
+ for req in requirements:
83
+ for kind in req.kinds:
84
+ self.data[req.id][kind] = None
85
+
86
+ self.complete = self.check_complete()
87
+
88
+ def _add(self, channel_id, kind: str, data):
89
+ # ensure channel id was expected
90
+ assert channel_id in self.data, "unexpected data passed to pattern module"
91
+
92
+ # ensure this kind was expected and not already passed
93
+ assert kind in self.data[channel_id], (
94
+ f"{kind} data being passed, but not expected"
95
+ )
96
+ assert self.data[channel_id][kind] is None, (
97
+ f"expected none, found {self.data[channel_id][kind]}"
98
+ )
99
+
100
+ self.data[channel_id][kind] = data
101
+
102
+ def add(self, data: AcquisitionData):
103
+ """Slot a delivery by its ``kind`` (raw, seg or tracks)."""
104
+ self._add(data.channel_id, getattr(data, "kind", "raw"), data)
105
+
106
+ def add_raw(self, data: AcquisitionData):
107
+ self._add(data.channel_id, "raw", data)
108
+
109
+ def add_seg(self, data: SegmentationData):
110
+ self._add(data.channel_id, "seg", data)
111
+
112
+ def add_tracks(self, data):
113
+ self._add(data.channel_id, "tracks", data)
114
+
115
+ def get_awaiting(self):
116
+ awaiting = []
117
+
118
+ for channel in self.data:
119
+ for img in self.data[channel]:
120
+ if self.data[channel][img] is None:
121
+ awaiting.append((channel, img))
122
+
123
+ return awaiting
124
+
125
+ def check_complete(self):
126
+ return len(self.get_awaiting()) == 0
127
+
128
+
129
+ class ExperimentState:
130
+ """
131
+ Per-experiment memory in the pattern process: bounded histories of the
132
+ deliveries a method asked for (depth = the ``history`` of its
133
+ requirement, default 1) and of the patterns it generated.
134
+ """
135
+
136
+ def __init__(
137
+ self,
138
+ requirements: list[AcquiredImageRequest] | None = None,
139
+ pattern_history: int = 2,
140
+ ):
141
+ self.depth: dict[UUID, int] = {}
142
+ self.requested: set[tuple[UUID, str]] = set()
143
+ for req in requirements or ():
144
+ self.depth[req.id] = max(1, int(getattr(req, "history", 1)))
145
+ for kind in req.kinds:
146
+ self.requested.add((req.id, kind))
147
+ self.history: dict[tuple[UUID, str], deque] = {}
148
+ self.patterns: deque = deque(maxlen=max(1, int(pattern_history)))
149
+ self.t: int | None = None
150
+ self.time_seconds: float = 0.0
151
+ self.generations = 0
152
+
153
+ @classmethod
154
+ def from_dock(cls, dock: DataDock, t: int | None = None) -> ExperimentState:
155
+ state = cls(dock.requirements)
156
+ state.absorb(dock, t)
157
+ return state
158
+
159
+ def absorb(self, dock: DataDock, t: int | None = None):
160
+ """Append a completed dock's deliveries to the histories."""
161
+ for channel_id, kinds in dock.data.items():
162
+ for kind, data in kinds.items():
163
+ if data is None:
164
+ continue
165
+ key = (channel_id, kind)
166
+ self.requested.add(key)
167
+ if key not in self.history:
168
+ self.history[key] = deque(maxlen=self.depth.get(channel_id, 1))
169
+ self.history[key].append(data)
170
+ self.time_seconds = dock.time_seconds
171
+ if t is not None:
172
+ self.t = int(t)
173
+
174
+ def record_pattern(self, pattern_id, pattern: np.ndarray):
175
+ self.patterns.append((pattern_id, pattern))
176
+ self.generations += 1
177
+
178
+ def latest(self, channel_id, kind: str):
179
+ h = self.history.get((channel_id, kind))
180
+ return h[-1] if h else None
181
+
182
+ def series(self, channel_id, kind: str, n: int | None = None) -> list:
183
+ h = list(self.history.get((channel_id, kind), ()))
184
+ return h if n is None else h[-int(n) :]
185
+
186
+
187
+ class PatternContext:
188
+ """
189
+ What ``PatternMethod.generate`` receives: the current deliveries for the
190
+ channels the method asked for, their bounded history, the method's own
191
+ previous patterns, and the timepoint. Build it on an
192
+ :class:`ExperimentState` (the pattern process does) or on a single
193
+ :class:`DataDock` for one-off use.
194
+ """
195
+
196
+ def __init__(
197
+ self,
198
+ source: ExperimentState | DataDock,
199
+ experiment: Experiment,
200
+ t: int | None = None,
201
+ position=None,
202
+ ):
203
+ if isinstance(source, DataDock):
204
+ source = ExperimentState.from_dock(source, t)
205
+ self._state: ExperimentState = source
206
+ self._experiment = experiment
207
+ self._position = position
208
+ self._requests: list = []
209
+ self._channel_map = {
210
+ name: ch.channel_id for name, ch in experiment.channels.items()
211
+ }
212
+
213
+ # ------------------------------------------------------------ timing
214
+ @property
215
+ def time(self) -> float:
216
+ """Scheduled seconds since the start of the run."""
217
+ return self._state.time_seconds
218
+
219
+ @property
220
+ def t(self) -> int | None:
221
+ """Plan timepoint of the current deliveries."""
222
+ return self._state.t
223
+
224
+ @property
225
+ def generation(self) -> int:
226
+ """How many patterns this method has generated so far in the run."""
227
+ return self._state.generations
228
+
229
+ # ----------------------------------------------------------- helpers
230
+ def _get_channel_id(self, channel_name: str) -> UUID:
231
+ if channel_name not in self._channel_map:
232
+ raise ValueError(f"Channel '{channel_name}' not found in experiment.")
233
+ return self._channel_map[channel_name]
234
+
235
+ def _require(self, channel_id: UUID, kind: str, what: str):
236
+ if (channel_id, kind) not in self._state.requested:
237
+ raise ValueError(f"{what} was not requested.")
238
+
239
+ def _latest_array(self, channel_id: UUID, kind: str):
240
+ data = self._state.latest(channel_id, kind)
241
+ return None if data is None else data.data
242
+
243
+ @staticmethod
244
+ def _unwrap(kind: str, data):
245
+ if kind == "tracks":
246
+ return Tracks(data.labels, data.rows)
247
+ return data.data
248
+
249
+ # ----------------------------------------------------------- current
250
+ def raw(self, channel_name: str) -> np.ndarray:
251
+ """Get raw image for a channel."""
252
+ cid = self._get_channel_id(channel_name)
253
+ self._require(cid, "raw", f"Raw data for channel '{channel_name}'")
254
+ return self._latest_array(cid, "raw")
255
+
256
+ def segmentation(
257
+ self, channel_name: str, name: str = DEFAULT_SEGMENTATION
258
+ ) -> np.ndarray:
259
+ """Label image of a channel from the ``[segmentation]`` table ``name`` (default: the default table)."""
260
+ cid = self._get_channel_id(channel_name)
261
+ kind = seg_kind(name)
262
+ what = (
263
+ f"Segmentation data for channel '{channel_name}'"
264
+ if kind == "seg"
265
+ else f"Segmentation '{name}' of channel '{channel_name}'"
266
+ )
267
+ self._require(cid, kind, what)
268
+ return self._latest_array(cid, kind)
269
+
270
+ def regions(self, channel_name: str, name: str = DEFAULT_SEGMENTATION) -> Regions:
271
+ """The segmentation of a channel as :class:`~pyclm.core.measure.Regions` (measure, paint, ...)."""
272
+ return Regions(self.segmentation(channel_name, name))
273
+
274
+ def tracks(self, channel_name: str) -> Tracks | None:
275
+ """Tracked objects of a channel: relabelled mask plus a per-object table."""
276
+ cid = self._get_channel_id(channel_name)
277
+ self._require(cid, "tracks", f"Tracks for channel '{channel_name}'")
278
+ data = self._state.latest(cid, "tracks")
279
+ return None if data is None else self._unwrap("tracks", data)
280
+
281
+ def stim_raw(self):
282
+ cid = self._experiment.stimulation.channel_id
283
+ self._require(
284
+ cid,
285
+ "raw",
286
+ "Raw data for the stimulation output was not requested. "
287
+ "Use PatternMethod.request_stim(raw=True); it",
288
+ )
289
+ return self._latest_array(cid, "raw")
290
+
291
+ def stim_seg(self):
292
+ cid = self._experiment.stimulation.channel_id
293
+ self._require(
294
+ cid,
295
+ "seg",
296
+ "Segmentation data for the stimulation output was not requested. "
297
+ "Use PatternMethod.request_stim(seg=True); it",
298
+ )
299
+ return self._latest_array(cid, "seg")
300
+
301
+ # ----------------------------------------------------------- history
302
+ def history(
303
+ self,
304
+ channel_name: str,
305
+ kind: str = "seg",
306
+ n: int | None = None,
307
+ name: str | None = None,
308
+ ) -> list:
309
+ """
310
+ Past deliveries of a channel, oldest first, the current one last. At
311
+ most the ``history`` depth declared in ``add_requirement``. ``kind``
312
+ is ``"raw"``, ``"seg"`` or ``"tracks"``; ``name`` picks a named
313
+ segmentation when ``kind`` is ``"seg"``.
314
+ """
315
+ cid = self._get_channel_id(channel_name)
316
+ if name is not None and base_kind(kind) == "seg":
317
+ kind = seg_kind(name)
318
+ self._require(cid, kind, f"{kind} data for channel '{channel_name}'")
319
+ return [self._unwrap(kind, d) for d in self._state.series(cid, kind, n)]
320
+
321
+ def stim_history(self, kind: str = "raw", n: int | None = None) -> list:
322
+ """Past deliveries of the stimulation frame (see ``request_stim``)."""
323
+ cid = self._experiment.stimulation.channel_id
324
+ self._require(cid, kind, f"{kind} data for the stimulation output")
325
+ return [self._unwrap(kind, d) for d in self._state.series(cid, kind, n)]
326
+
327
+ def last_pattern(self) -> np.ndarray | None:
328
+ """The pattern this method generated last time, or None on the first call."""
329
+ return self._state.patterns[-1][1] if self._state.patterns else None
330
+
331
+ def pattern_history(self, n: int | None = None) -> list[np.ndarray]:
332
+ """Previous patterns, oldest first (at most ``PatternMethod.pattern_history``)."""
333
+ patterns = [p for _, p in self._state.patterns]
334
+ return patterns if n is None else patterns[-int(n) :]
335
+
336
+ # ---------------------------------------------------------- settings
337
+ # A method may change its own experiment's acquisition settings: the
338
+ # values apply from the next timepoint (the same delay as the pattern),
339
+ # are recorded in events.parquet, and appear as frames-table columns.
340
+ @property
341
+ def requests(self) -> list:
342
+ """Setting changes requested so far in this ``generate`` call."""
343
+ return list(self._requests)
344
+
345
+ def _channel_config(self, channel_name: str):
346
+ if channel_name == STIMULATION:
347
+ return self._experiment.stimulation
348
+ cfg = self._experiment.channels.get(channel_name)
349
+ if cfg is None:
350
+ raise ValueError(
351
+ f"Channel '{channel_name}' not found in experiment "
352
+ f"(use '{STIMULATION}' for the stimulation channel)."
353
+ )
354
+ return cfg
355
+
356
+ def settings(self, channel_name: str) -> dict:
357
+ """
358
+ The acquisition settings of one channel of this experiment as they
359
+ stand now: ``exposure_ms``, ``binning``, ``config_groups`` (group →
360
+ preset) and ``device_properties`` (``"<device>-<property>"`` → value).
361
+ ``"stimulation"`` names the stimulation channel.
362
+ """
363
+ cfg = self._channel_config(channel_name)
364
+ return {
365
+ "exposure_ms": float(cfg.exposure),
366
+ "binning": int(cfg.binning),
367
+ "config_groups": {g.group: g.config for g in cfg.get_config_groups()},
368
+ "device_properties": {
369
+ f"{d.device}-{d.property}": d.value for d in cfg.get_device_properties()
370
+ },
371
+ }
372
+
373
+ def grid(self):
374
+ """
375
+ The :class:`~pyclm.core.grid.GridGeometry` of a grid experiment (rows,
376
+ columns, tile shape, pitch, the tiles' order), or None for a plain
377
+ position. ``raw()`` and the pattern are in the stitched frame either way.
378
+ """
379
+ return getattr(self._position, "geometry", None)
380
+
381
+ def position(self) -> dict | None:
382
+ """The stage position of this experiment (``x``, ``y``, ``z`` and extras), if known."""
383
+ return None if self._position is None else dict(self._position.as_dict())
384
+
385
+ def set_exposure(self, channel_name: str, ms: float) -> None:
386
+ """Change a channel's exposure (ms) from the next timepoint on."""
387
+ self._channel_config(channel_name)
388
+ self._requests.append(_exposure_change(channel_name, ms))
389
+
390
+ def set_config(self, channel_name: str, group: str, preset: str) -> None:
391
+ """Select a MicroManager preset of a config group for a channel from the next timepoint on."""
392
+ self._channel_config(channel_name)
393
+ self._requests.append(_config_change(channel_name, group, preset))
394
+
395
+ def set_property(self, channel_name: str, device: str, prop: str, value) -> None:
396
+ """Set a device property (e.g. a laser intensity) for a channel from the next timepoint on."""
397
+ self._channel_config(channel_name)
398
+ self._requests.append(_property_change(channel_name, device, prop, value))
399
+
400
+ def set_position(self, x=None, y=None, z=None, pfs_offset=None) -> None:
401
+ """Move this experiment's position (absolute stage coordinates) from the next timepoint on."""
402
+ for key, value in (("x", x), ("y", y), ("z", z), ("pfs_offset", pfs_offset)):
403
+ if value is not None:
404
+ self._requests.append(_position_change(key, value))
405
+
406
+
407
+ class PatternMethod:
408
+ name = "base"
409
+ # how many of this method's previous patterns the context keeps
410
+ pattern_history = 2
411
+
412
+ def __init__(
413
+ self, experiment_name=None, camera_properties: CameraProperties = None, **kwargs
414
+ ):
415
+ # Support legacy init where these are passed
416
+ self.experiment_name = experiment_name
417
+ self.camera_properties = camera_properties
418
+ if camera_properties:
419
+ self.pixel_size_um = camera_properties.pixel_size_um
420
+ self.pattern_shape = (
421
+ camera_properties.roi.height,
422
+ camera_properties.roi.width,
423
+ )
424
+ else:
425
+ self.pixel_size_um = 1.0
426
+ self.pattern_shape = (100, 100) # Default placeholders
427
+
428
+ self.binning = 1
429
+ # (channel_name, raw, seg, tracks, history)
430
+ self._requirements_list = []
431
+ self._experiment_ref = None
432
+
433
+ self._stim_requested = False
434
+ self._stim_request_raw = False
435
+ self._stim_request_seg = False
436
+ self._stim_request_history = 1
437
+
438
+ def add_requirement(
439
+ self,
440
+ channel_name: str,
441
+ raw: bool = False,
442
+ seg=False,
443
+ tracks: bool = False,
444
+ history: int = 1,
445
+ ):
446
+ """
447
+ Declare what ``generate`` needs of a channel: the raw frame, its
448
+ segmentation, its tracks, and how many past deliveries to keep for
449
+ ``context.history()`` (deliveries happen at the pattern's cadence).
450
+
451
+ ``seg`` is ``True`` for the experiment's default ``[segmentation]``
452
+ table, the name of a ``[segmentation.<name>]`` table, or a list of
453
+ names (``"segmentation"`` stands for the default one).
454
+ """
455
+ self._requirements_list.append(
456
+ (
457
+ channel_name,
458
+ bool(raw),
459
+ _seg_names(seg),
460
+ bool(tracks),
461
+ max(1, int(history)),
462
+ )
463
+ )
464
+
465
+ @classmethod
466
+ def nested_methods(cls, kwargs: dict) -> list[tuple[str, str, dict]]:
467
+ """
468
+ Pattern methods this one builds from its TOML arguments, as
469
+ ``(label, method name, kwargs)``; ``pyclm check`` validates them.
470
+ Empty for an ordinary method.
471
+ """
472
+ return []
473
+
474
+ def bind_registry(self, registry: dict[str, type]) -> None:
475
+ """
476
+ Called by the pattern process, with the registered pattern methods,
477
+ after construction and before ``initialize``: a method that builds
478
+ other methods (``split``) constructs them here.
479
+ """
480
+ return None
481
+
482
+ def request_stim(self, raw: bool = False, seg: bool = False, history: int = 1):
483
+ """Request the imaged stimulation"""
484
+ self._stim_requested = True
485
+ self._stim_request_raw = raw
486
+ self._stim_request_seg = seg
487
+ self._stim_request_history = max(1, int(history))
488
+
489
+ # initialize happens shortly after init
490
+ def initialize(self, experiment: Experiment) -> list[AcquiredImageRequest]:
491
+ # If user used add_requirement, process them
492
+ reqs = []
493
+ for (
494
+ name,
495
+ needs_raw,
496
+ seg_names,
497
+ needs_tracks,
498
+ history,
499
+ ) in self._requirements_list:
500
+ ch = experiment.channels.get(name)
501
+ if ch:
502
+ named = tuple(n for n in seg_names if n != DEFAULT_SEGMENTATION)
503
+ for seg in named:
504
+ if seg not in experiment.segmentations:
505
+ logger.warning(
506
+ f"Pattern {self.name} requested segmentation {seg!r} of "
507
+ f"channel {name}, which the experiment does not configure"
508
+ )
509
+ reqs.append(
510
+ AcquiredImageRequest(
511
+ ch.channel_id,
512
+ needs_raw,
513
+ DEFAULT_SEGMENTATION in seg_names,
514
+ needs_tracks,
515
+ history,
516
+ named,
517
+ )
518
+ )
519
+ else:
520
+ logger.warning(f"Pattern {self.name} requested unknown channel {name}")
521
+
522
+ if self._stim_requested:
523
+ reqs.append(
524
+ AcquiredImageRequest(
525
+ experiment.stimulation.channel_id,
526
+ self._stim_request_raw,
527
+ self._stim_request_seg,
528
+ False,
529
+ self._stim_request_history,
530
+ )
531
+ )
532
+
533
+ return reqs
534
+
535
+ # configure system is run after all pattern methods are initialized
536
+ def configure_system(
537
+ self,
538
+ experiment_name: str,
539
+ camera_properties: CameraProperties,
540
+ experiment: Experiment,
541
+ ):
542
+ """Called by the system to inject dependencies."""
543
+ self.experiment_name = experiment_name
544
+ self.camera_properties = camera_properties
545
+ self.pixel_size_um = camera_properties.pixel_size_um
546
+ self.pattern_shape = (camera_properties.roi.height, camera_properties.roi.width)
547
+ self._experiment_ref = experiment
548
+
549
+ # this binning should actually take effect
550
+ binning = experiment.stimulation.binning
551
+ self.update_binning(binning)
552
+
553
+ def update(self, **parameters) -> tuple[dict, dict]:
554
+ """
555
+ Change parameters while the run is in progress (a ``set_pattern``
556
+ command). The default sets attributes that already exist on the
557
+ method and refuses the rest; override it for anything smarter.
558
+ Returns ``(applied, refused)`` where ``refused`` maps a name to the
559
+ reason.
560
+ """
561
+ applied, refused = {}, {}
562
+ for name, value in parameters.items():
563
+ if (
564
+ name.startswith("_")
565
+ or not hasattr(self, name)
566
+ or callable(getattr(self, name))
567
+ ):
568
+ refused[name] = "unknown parameter"
569
+ continue
570
+ setattr(self, name, value)
571
+ applied[name] = value
572
+ return applied, refused
573
+
574
+ def get_um_meshgrid(self) -> tuple[np.ndarray, np.ndarray]:
575
+ h, w = self.pattern_shape
576
+
577
+ y_range = np.arange(h) * self.pixel_size_um
578
+ x_range = np.arange(w) * self.pixel_size_um
579
+
580
+ xx, yy = np.meshgrid(x_range, y_range)
581
+
582
+ return xx, yy
583
+
584
+ def center_um(self) -> tuple[float, float]:
585
+ h, w = self.pattern_shape
586
+ return (w * self.pixel_size_um / 2.0, h * self.pixel_size_um / 2.0)
587
+
588
+ def generate(self, data_dock: DataDock | PatternContext) -> np.ndarray:
589
+ # If passed PatternContext, user is using new API.
590
+ # But if user implemented old generate(self, data_dock: DataDock), we need to support that.
591
+ # This method is called by the system.
592
+ raise NotImplementedError
593
+
594
+ def update_binning(self, binning: int):
595
+ binning = int(binning)
596
+ binning_rescale = binning / self.binning
597
+
598
+ self.pixel_size_um = self.pixel_size_um * binning_rescale
599
+
600
+ # recover the unbinned shape, then rebin, keeping the shape integral
601
+ h_unbinned = round(self.pattern_shape[0] * self.binning)
602
+ w_unbinned = round(self.pattern_shape[1] * self.binning)
603
+ self.pattern_shape = (h_unbinned // binning, w_unbinned // binning)
604
+
605
+ logger.info(
606
+ f"model {self.name} updated pixel size (um) to {self.pixel_size_um}"
607
+ )
608
+ logger.info(f"model {self.name} updated pattern_shape to {self.pattern_shape}")
609
+
610
+ self.binning = binning