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,28 @@
1
+ """Tracking methods: stable identities for labelled regions across timepoints."""
2
+
3
+ from .centroid import CentroidTracker
4
+ from .tracking import (
5
+ TRACK_COLUMNS,
6
+ TRACK_LABEL_DTYPE,
7
+ TRACK_SCHEMA,
8
+ TrackingMethod,
9
+ TrackRow,
10
+ Tracks,
11
+ rows_to_table,
12
+ )
13
+
14
+ known_tracking_methods: dict[str, type[TrackingMethod]] = {
15
+ CentroidTracker.name: CentroidTracker,
16
+ }
17
+
18
+ __all__ = [
19
+ "TRACK_COLUMNS",
20
+ "TRACK_LABEL_DTYPE",
21
+ "TRACK_SCHEMA",
22
+ "CentroidTracker",
23
+ "TrackRow",
24
+ "TrackingMethod",
25
+ "Tracks",
26
+ "known_tracking_methods",
27
+ "rows_to_table",
28
+ ]
@@ -0,0 +1,75 @@
1
+ """
2
+ The built-in tracker: nearest-centroid linking with a Hungarian assignment,
3
+ gated by a maximum displacement in micrometres. No divisions, no gap
4
+ closing; an object that is not matched starts a new track and one that
5
+ disappears simply ends.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import numpy as np
11
+ from scipy.optimize import linear_sum_assignment
12
+ from scipy.spatial.distance import cdist
13
+ from skimage.measure import regionprops_table
14
+
15
+ from .tracking import TRACK_LABEL_DTYPE, TrackingMethod, TrackRow
16
+
17
+
18
+ class CentroidTracker(TrackingMethod):
19
+ """
20
+ Links each region to the nearest region of the previous timepoint when
21
+ the centroid moved less than ``max_distance_um``; every region gets at
22
+ most one partner (Hungarian assignment on centroid distance).
23
+ """
24
+
25
+ name = "centroid"
26
+
27
+ def __init__(
28
+ self,
29
+ experiment_name: str,
30
+ channel: str,
31
+ max_distance_um: float = 20.0,
32
+ **kwargs,
33
+ ):
34
+ super().__init__(experiment_name, channel, **kwargs)
35
+ self.max_distance_um = float(max_distance_um)
36
+ self._prev_ids = np.zeros(0, dtype=np.int64)
37
+ self._prev_centroids = np.zeros((0, 2), dtype=float)
38
+ self._next_id = 1
39
+
40
+ def track(self, labels, t, pixel_size_um):
41
+ labels = np.asarray(labels)
42
+ props = regionprops_table(
43
+ labels.astype(np.int64), properties=("label", "centroid", "area")
44
+ )
45
+ found = np.asarray(props["label"], dtype=np.int64)
46
+ centroids = (
47
+ np.stack([props["centroid-0"], props["centroid-1"]], axis=1)
48
+ if len(found)
49
+ else np.zeros((0, 2), dtype=float)
50
+ )
51
+ areas = np.asarray(props["area"], dtype=np.int64)
52
+
53
+ ids = np.zeros(len(found), dtype=np.int64)
54
+ if len(self._prev_ids) and len(found):
55
+ distance = cdist(self._prev_centroids, centroids) * float(pixel_size_um)
56
+ rows, cols = linear_sum_assignment(distance)
57
+ for r, c in zip(rows, cols, strict=True):
58
+ if distance[r, c] <= self.max_distance_um:
59
+ ids[c] = self._prev_ids[r]
60
+ for i in range(len(ids)):
61
+ if ids[i] == 0:
62
+ ids[i] = self._next_id
63
+ self._next_id += 1
64
+
65
+ lut = np.zeros(int(labels.max()) + 1 if labels.size else 1, dtype=np.int64)
66
+ lut[found] = ids
67
+ relabelled = lut[labels].astype(TRACK_LABEL_DTYPE)
68
+
69
+ out = [
70
+ TrackRow(int(tid), int(lab), float(c[0]), float(c[1]), int(a), 0)
71
+ for tid, lab, c, a in zip(ids, found, centroids, areas, strict=True)
72
+ ]
73
+ self._prev_ids = ids
74
+ self._prev_centroids = centroids
75
+ return relabelled, out
@@ -0,0 +1,124 @@
1
+ """
2
+ Tracking: stable identities for labelled regions across timepoints.
3
+
4
+ A :class:`TrackingMethod` receives one label image per acquired frame of a
5
+ channel (cells, organoids, tissue regions: whatever the segmentation method
6
+ labels) and returns the same image relabelled with track ids plus one
7
+ :class:`TrackRow` per object. The interface is "labelled regions in,
8
+ relabelled regions and a table out"; the method decides what a region is
9
+ and keeps whatever state it needs between calls, the way segmentation
10
+ methods do.
11
+
12
+ See docs/stage3-router-design.md §5.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from typing import NamedTuple
18
+
19
+ import numpy as np
20
+ import pyarrow as pa
21
+
22
+ from ..measure import Regions
23
+
24
+ TRACK_COLUMNS = ("track_id", "label", "y", "x", "area", "parent")
25
+ TRACK_SCHEMA = pa.schema(
26
+ [
27
+ ("track_id", pa.int64()),
28
+ ("label", pa.int64()),
29
+ ("y", pa.float64()),
30
+ ("x", pa.float64()),
31
+ ("area", pa.int64()),
32
+ ("parent", pa.int64()),
33
+ ]
34
+ )
35
+ # dtype of relabelled images: ids keep growing for the whole run
36
+ TRACK_LABEL_DTYPE = np.uint32
37
+
38
+
39
+ class TrackRow(NamedTuple):
40
+ """One tracked object at one timepoint. ``y``/``x`` are the centroid in pixels of the (binned) frame."""
41
+
42
+ track_id: int
43
+ label: int
44
+ y: float
45
+ x: float
46
+ area: int
47
+ parent: int = 0
48
+
49
+
50
+ def rows_to_table(rows) -> pa.Table:
51
+ rows = list(rows)
52
+ return pa.table(
53
+ {col: [getattr(r, col) for r in rows] for col in TRACK_COLUMNS},
54
+ schema=TRACK_SCHEMA,
55
+ )
56
+
57
+
58
+ class Tracks(Regions):
59
+ """
60
+ What a pattern method sees for one channel at one timepoint: the label
61
+ image relabelled with track ids (``labels``) and the per-object rows.
62
+ A :class:`~pyclm.core.measure.Regions`, so ``measure``, ``paint``,
63
+ ``select`` and ``owner_of`` work on tracked objects too.
64
+ """
65
+
66
+ def __init__(self, labels: np.ndarray, rows):
67
+ super().__init__(labels)
68
+ self.rows: list[TrackRow] = list(rows)
69
+
70
+ @property
71
+ def ids(self) -> np.ndarray:
72
+ return np.array([r.track_id for r in self.rows], dtype=np.int64)
73
+
74
+ @property
75
+ def table(self) -> pa.Table:
76
+ return rows_to_table(self.rows)
77
+
78
+ def to_pandas(self):
79
+ return self.table.to_pandas()
80
+
81
+ def row(self, track_id: int) -> TrackRow | None:
82
+ for r in self.rows:
83
+ if r.track_id == track_id:
84
+ return r
85
+ return None
86
+
87
+ def centroid(self, track_id: int) -> tuple[float, float] | None:
88
+ r = self.row(track_id)
89
+ return None if r is None else (r.y, r.x)
90
+
91
+ def mask(self, track_id: int) -> np.ndarray:
92
+ return self.labels == track_id
93
+
94
+ def __len__(self) -> int:
95
+ return len(self.rows)
96
+
97
+ def __repr__(self) -> str:
98
+ return f"Tracks({len(self.rows)} objects, labels {self.labels.shape})"
99
+
100
+
101
+ class TrackingMethod:
102
+ """
103
+ Base class for tracking methods. Subclass, set ``name``, implement
104
+ :meth:`track`, and register with ``Controller.register_tracking_method``
105
+ or ``run_pyclm(tracking_methods={...})``. Keyword arguments come from the
106
+ ``[tracking]`` table of the experiment TOML (all keys except ``method``
107
+ and ``save``).
108
+ """
109
+
110
+ name = "base"
111
+
112
+ def __init__(self, experiment_name: str, channel: str, **kwargs):
113
+ self.experiment_name = experiment_name
114
+ self.channel = channel
115
+
116
+ def track(
117
+ self, labels: np.ndarray, t: int, pixel_size_um: float
118
+ ) -> tuple[np.ndarray, list[TrackRow]]:
119
+ """
120
+ Link ``labels`` (one label image, 0 = background) to the objects seen
121
+ before. Returns the image relabelled with track ids and the rows for
122
+ this timepoint.
123
+ """
124
+ raise NotImplementedError(f"{self.name} does not implement track()")
@@ -0,0 +1,106 @@
1
+ """
2
+ The tracking process: produces ``tracks`` from ``seg`` for every channel
3
+ some consumer demands tracks of. It is ``continuous``: once it runs for a
4
+ channel it receives every acquired frame's segmentation, because a tracker
5
+ cannot link objects across frames it never saw.
6
+
7
+ The first consumer added through the Router as a registration rather than
8
+ a surgery (docs/stage3-router-design.md §5).
9
+ """
10
+
11
+ import logging
12
+ from threading import Event
13
+ from typing import ClassVar
14
+
15
+ import numpy as np
16
+
17
+ from .base_process import PipelineProcess
18
+ from .datatypes import SegmentationData, TrackingData
19
+ from .experiments import Experiment
20
+ from .kinds import seg_kind
21
+ from .tracking import TrackingMethod, known_tracking_methods
22
+
23
+ logger = logging.getLogger(__name__)
24
+
25
+
26
+ class TrackingProcess(PipelineProcess):
27
+ produces: ClassVar[dict[str, tuple[str, ...]]] = {"tracks": ("seg",)}
28
+ continuous = True
29
+
30
+ def __init__(self, stop_event: Event | None = None):
31
+ super().__init__(stop_event, name="tracking")
32
+ # per-instance copy so registrations do not leak between controllers
33
+ self.known_methods: dict[str, type[TrackingMethod]] = dict(
34
+ known_tracking_methods
35
+ )
36
+ # (experiment name, channel id) -> method instance
37
+ self.methods: dict[tuple, TrackingMethod] = {}
38
+
39
+ def can_produce(self, kind: str, experiment: Experiment, channel: str) -> bool:
40
+ tracking = getattr(experiment, "tracking", None)
41
+ return (
42
+ kind == "tracks" and tracking is not None and tracking.method_name != "none"
43
+ )
44
+
45
+ def inputs(
46
+ self, kind: str, experiment: Experiment, channel: str
47
+ ) -> tuple[str, ...]:
48
+ """Tracking links the segmentation named by ``[tracking] segmentation`` (default: the default table)."""
49
+ name = getattr(experiment.tracking, "segmentation", None)
50
+ return (seg_kind(name),)
51
+
52
+ def register_method(self, method: type, name: str | None = None):
53
+ assert issubclass(method, TrackingMethod), (
54
+ "method must be a subclass of TrackingMethod"
55
+ )
56
+ method_name = method.name if name is None else name
57
+ if method_name in self.known_methods:
58
+ logger.warning(f"overwriting known tracking method {method_name}")
59
+ self.known_methods[method_name] = method
60
+
61
+ def request_method(self, experiment: Experiment, channel: str) -> TrackingMethod:
62
+ """Construct the experiment's tracking method for one channel."""
63
+ method_name = experiment.tracking.method_name
64
+ method_class = self.known_methods.get(method_name)
65
+ assert method_class is not None, (
66
+ f"tracking method {method_name} is not registered"
67
+ )
68
+ assert issubclass(method_class, TrackingMethod), (
69
+ f"{method_name} is not a TrackingMethod"
70
+ )
71
+
72
+ name = experiment.experiment_name
73
+ cfg = (
74
+ experiment.stimulation
75
+ if channel not in experiment.channels
76
+ else experiment.channels[channel]
77
+ )
78
+ method = method_class(name, channel, **experiment.tracking.kwargs)
79
+ self.methods[(name, cfg.channel_id)] = method
80
+ logger.info(f'{name}/{channel}: initialised tracking method "{method_name}"')
81
+ return method
82
+
83
+ def handle_data(self, data):
84
+ assert isinstance(data, SegmentationData), (
85
+ f"tracking received {type(data)}, expected SegmentationData"
86
+ )
87
+ event = data.event
88
+ method = self.methods.get((event.experiment_name, event.channel_id))
89
+ if method is None:
90
+ logger.warning(
91
+ f"no tracking method for {event.experiment_name}/{event.index.get('c')}; "
92
+ "dropping segmentation"
93
+ )
94
+ return
95
+
96
+ pixel_size_um = event.pixel_width_um
97
+ if not pixel_size_um:
98
+ pixel_size_um = 1.0
99
+ labels, rows = method.track(
100
+ np.asarray(data.data), event.t_index, float(pixel_size_um)
101
+ )
102
+ logger.debug(
103
+ f"{event.experiment_name}/{event.index.get('c')} t={event.t_index}: "
104
+ f"{len(rows)} tracked objects"
105
+ )
106
+ self.publish(TrackingData(event, labels, rows))
File without changes
@@ -0,0 +1,262 @@
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ from collections.abc import Iterable, Sequence
5
+ from dataclasses import dataclass
6
+ from typing import Any
7
+
8
+ import numpy as np
9
+
10
+ from ..core_interface import MicroscopeCoreInterface
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+
15
+ @dataclass
16
+ class SimulatedConfigGroup:
17
+ name: str
18
+ _items: dict[str, str]
19
+
20
+ def items(self) -> Iterable[tuple[str, str]]:
21
+ return self._items.items()
22
+
23
+
24
+ class SimulatedMicroscopeCore(MicroscopeCoreInterface):
25
+ PFS_STATUS_LOCKED = "0000001100001010"
26
+
27
+ def __init__(
28
+ self,
29
+ image_source,
30
+ pixel_size_um: float = 0.33,
31
+ camera_name: str = "SimulatedCamera",
32
+ slm_device: str = "SimulatedSLM",
33
+ slm_shape: tuple[int, int] = (1140, 900),
34
+ initial_xy: tuple[float, float] = (0.0, 0.0),
35
+ initial_z: float = 0.0,
36
+ ):
37
+ self._image_source = image_source
38
+ self._camera_name = camera_name
39
+ self._pixel_size_um = float(pixel_size_um)
40
+
41
+ h, w = image_source.shape[:2]
42
+ self._roi = (0, 0, int(w), int(h))
43
+
44
+ self._last_image: np.ndarray | None = None
45
+ self._exposure_ms: float = 0.0
46
+
47
+ self._properties: dict[str, dict[str, Any]] = {camera_name: {"Binning": "1x1"}}
48
+ self._config_groups: dict[str, str] = {}
49
+
50
+ self._x, self._y = float(initial_xy[0]), float(initial_xy[1])
51
+ self._z = float(initial_z)
52
+ self._autofocus_offset = 0.0
53
+
54
+ self._properties.setdefault("PFS", {})
55
+ self._properties["PFS"].setdefault("FocusMaintenance", "Off")
56
+ self._properties["PFS"].setdefault("PFS Status", self.PFS_STATUS_LOCKED)
57
+
58
+ self._slm_device = slm_device # set None to simulate no SLM device
59
+ self._slm_h, self._slm_w = int(slm_shape[0]), int(slm_shape[1])
60
+ self._slm_image: np.ndarray | None = None
61
+
62
+ self._focus_device: str | None = None
63
+ self._config_group_definitions: dict[str, dict[str, str]] = {
64
+ "Channel": {"DAPI": "DAPI", "GFP": "GFP"},
65
+ "Illumination": {"On": "On", "Off": "Off"},
66
+ }
67
+
68
+ def loadSystemConfiguration(self, configuration) -> None:
69
+ cfg = str(configuration)
70
+ self._loaded_configuration = cfg
71
+
72
+ # SLM-related
73
+ def getSLMDevice(self) -> str:
74
+ return "" if self._slm_device is None else str(self._slm_device)
75
+
76
+ def getSLMHeight(self, device: str) -> int:
77
+ return self._slm_h
78
+
79
+ def getSLMWidth(self, device: str) -> int:
80
+ return self._slm_w
81
+
82
+ def setSLMImage(self, device: str, image: Any) -> None:
83
+ self._slm_image = np.asarray(image)
84
+
85
+ # Config/device properties
86
+ def setConfig(self, group: str, config: str) -> None:
87
+ self._config_groups[str(group)] = str(config)
88
+
89
+ def getAllowedPropertyValues(self, device: str, prop_name: str) -> Sequence[str]:
90
+ if device == self._camera_name and prop_name == "Binning":
91
+ return ["1x1", "2x2", "4x4"]
92
+ if device == "PFS" and prop_name == "FocusMaintenance":
93
+ return ["On", "Off"]
94
+ return []
95
+
96
+ def setProperty(self, label: str, name: str, value: Any) -> None:
97
+ self._properties.setdefault(label, {})
98
+ self._properties[label][name] = value
99
+ if label == "PFS" and name == "FocusMaintenance" and str(value) == "On":
100
+ self._properties["PFS"]["PFS Status"] = self.PFS_STATUS_LOCKED
101
+
102
+ def getProperty(self, label: str, name: str) -> str:
103
+ return str(self._properties.get(label, {}).get(name, ""))
104
+
105
+ def describe(self) -> str:
106
+ cam = self._camera_name
107
+ roi = self._roi
108
+ binning = self._properties.get(cam, {}).get("Binning", "1x1")
109
+
110
+ lines = []
111
+ lines.append("=== SimulatedMicroscopeCore ===")
112
+ lines.append(f"Camera: {cam}")
113
+ lines.append(f"Pixel size (um): {self._pixel_size_um}")
114
+ lines.append(f"Exposure (ms): {self._exposure_ms}")
115
+ lines.append(f"ROI (x, y, w, h): {roi}")
116
+ lines.append(f"Binning: {binning}")
117
+ lines.append("")
118
+ lines.append(f"Stage XY: ({self._x:.3f}, {self._y:.3f})")
119
+ lines.append(f"Stage Z: {self._z:.3f}")
120
+ lines.append(f"Autofocus offset: {self._autofocus_offset:.3f}")
121
+ lines.append("")
122
+ slm_dev = "" if self._slm_device is None else str(self._slm_device)
123
+ lines.append(f"SLM device: {slm_dev if slm_dev else '(none)'}")
124
+ lines.append(f"SLM shape (h, w): ({self._slm_h}, {self._slm_w})")
125
+ lines.append(f"SLM image set: {'yes' if self._slm_image is not None else 'no'}")
126
+ lines.append("")
127
+ lines.append("Config groups set:")
128
+ if self._config_groups:
129
+ for k, v in sorted(self._config_groups.items()):
130
+ lines.append(f" - {k}: {v}")
131
+ else:
132
+ lines.append(" (none)")
133
+ lines.append("")
134
+ lines.append("Properties:")
135
+ for dev, props in sorted(self._properties.items()):
136
+ lines.append(f" [{dev}]")
137
+ for name, val in sorted(props.items()):
138
+ lines.append(f" {name} = {val}")
139
+
140
+ desc = "\n".join(lines)
141
+ print(desc)
142
+ return desc
143
+
144
+ def setFocusDevice(self, label: str) -> None:
145
+ self._focus_device = str(label)
146
+
147
+ def getAvailableConfigGroups(self) -> Sequence[str]:
148
+ return list(self._config_group_definitions.keys())
149
+
150
+ def getConfigGroupObject(self, group: str, include_read_only: bool = False):
151
+ name = str(group)
152
+ items = self._config_group_definitions.get(name, {})
153
+ return SimulatedConfigGroup(name=name, _items=dict(items))
154
+
155
+ # Camera-related
156
+ def getCameraDevice(self) -> str:
157
+ return self._camera_name
158
+
159
+ def setExposure(self, exposure_ms: float) -> None:
160
+ self._exposure_ms = float(exposure_ms)
161
+
162
+ def snapImage(self) -> None:
163
+ frame = np.asarray(self._image_source.next_frame([self._x, self._y]))
164
+ frame = self._window(frame)
165
+ logger.debug(f"Simulated image shape: {frame.shape}")
166
+
167
+ # binning_str = self._properties.get(self._camera_name, {}).get("Binning", "1x1")
168
+ # binning = int(binning_str.split("x")[0])
169
+ # if binning > 1 and frame.ndim >= 2:
170
+ # h_out, w_out = frame.shape[0] // binning, frame.shape[1] // binning
171
+ # frame = (
172
+ # frame[: h_out * binning, : w_out * binning]
173
+ # .reshape(h_out, binning, w_out, binning)
174
+ # .mean(axis=(1, 3))
175
+ # .astype(frame.dtype)
176
+ # )
177
+
178
+ self._last_image = frame
179
+
180
+ def _window(self, frame: np.ndarray) -> np.ndarray:
181
+ """
182
+ The part of the source frame the camera sees. A frame of the ROI's
183
+ size is the camera frame; a larger one is a region the stage moves
184
+ over (a grid's TIF): the window is centred on the listed position
185
+ and shifted by the stage's offset from it, in the TIF's pixels.
186
+ """
187
+ if frame.ndim < 2:
188
+ return frame
189
+ x, y, w, h = self._roi
190
+ fh, fw = frame.shape[:2]
191
+ if (fh, fw) == (h, w) or fh < h or fw < w:
192
+ return frame[y : y + h, x : x + w, ...]
193
+ nearest = getattr(self._image_source, "nearest", None)
194
+ ref = nearest([self._x, self._y]) if nearest is not None else None
195
+ px = float(getattr(self._image_source, "pixel_size_um", 0.0) or 0.0)
196
+ dx = dy = 0.0
197
+ if ref is not None and px > 0:
198
+ # stage um -> reported camera pixels -> TIF pixels (ROI_FACTOR smaller)
199
+ dx = (self._x - ref[0]) / px / self.ROI_FACTOR
200
+ dy = (self._y - ref[1]) / px / self.ROI_FACTOR
201
+ ox = round(fw / 2 + dx - w / 2)
202
+ oy = round(fh / 2 + dy - h / 2)
203
+ out = np.zeros((h, w, *frame.shape[2:]), dtype=frame.dtype)
204
+ sy0, sx0 = max(oy, 0), max(ox, 0)
205
+ sy1, sx1 = min(oy + h, fh), min(ox + w, fw)
206
+ if sy1 > sy0 and sx1 > sx0:
207
+ out[sy0 - oy : sy1 - oy, sx0 - ox : sx1 - ox] = frame[sy0:sy1, sx0:sx1]
208
+ return out
209
+
210
+ def getImage(self) -> Any:
211
+ if self._last_image is None:
212
+ self.snapImage()
213
+ return self._last_image
214
+
215
+ def getPixelSizeUm(self) -> float:
216
+ binning_str = self._properties.get(self._camera_name, {}).get("Binning", "1x1")
217
+ binning = int(binning_str.split("x")[0])
218
+ return self._pixel_size_um * binning
219
+
220
+ # the TIFs stand for a camera ROI_FACTOR times larger (the frames of the
221
+ # dry-run resources are 4x binned), so the reported ROI is scaled up and a
222
+ # requested ROI is scaled down onto the TIF
223
+ ROI_FACTOR = 4
224
+
225
+ def getROI(self):
226
+ x, y, w, h = self._roi
227
+ f = self.ROI_FACTOR
228
+ return (x * f, y * f, w * f, h * f)
229
+
230
+ def setROI(self, x: int, y: int, width: int, height: int) -> None:
231
+ f = self.ROI_FACTOR
232
+ h_src, w_src = self._image_source.shape[:2]
233
+ x0, y0 = int(x) // f, int(y) // f
234
+ w0, h0 = max(1, int(width) // f), max(1, int(height) // f)
235
+ if x0 + w0 > w_src or y0 + h0 > h_src:
236
+ raise ValueError(
237
+ f"ROI {(x, y, width, height)} exceeds the virtual camera "
238
+ f"{(w_src * f, h_src * f)} (unbinned pixels)"
239
+ )
240
+ self._roi = (x0, y0, w0, h0)
241
+
242
+ # Stage/focus/positioning
243
+ def getXYPosition(self) -> tuple[float, float]:
244
+ return float(self._x), float(self._y)
245
+
246
+ def getZPosition(self) -> float:
247
+ return float(self._z)
248
+
249
+ def setPosition(self, z: float) -> None:
250
+ self._z = float(z)
251
+
252
+ def setXYPosition(self, x: float, y: float) -> None:
253
+ self._x, self._y = float(x), float(y)
254
+
255
+ def setAutoFocusOffset(self, offset: float) -> None:
256
+ self._autofocus_offset = float(offset)
257
+ if self.getProperty("PFS", "FocusMaintenance") == "On":
258
+ self._properties["PFS"]["PFS Status"] = self.PFS_STATUS_LOCKED
259
+
260
+ # Synchronization
261
+ def waitForSystem(self) -> None:
262
+ return None