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,185 @@
1
+ """
2
+ Abstractions for moving the microscope stage to a MicroscopePosition.
3
+
4
+ Subclass PositionMover to implement hardware-specific focus maintenance.
5
+ Register a custom mover via Controller(position_mover=...) or by passing it
6
+ to run_pyclm().
7
+ """
8
+
9
+ import inspect
10
+ import logging
11
+ from abc import ABC, abstractmethod
12
+ from time import sleep, time
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+
17
+ class PositionMover(ABC):
18
+ """
19
+ Abstract base for stage movement. Implement ``move_to`` for your hardware.
20
+
21
+ Returns
22
+ -------
23
+ (z_moved, new_z) : tuple[bool, float]
24
+ ``z_moved`` is True when a z-axis adjustment was made.
25
+ ``new_z`` is the actual z coordinate reported by the core after the move.
26
+ """
27
+
28
+ @abstractmethod
29
+ def move_to(self, position, core) -> tuple[bool, float]:
30
+ """Move the stage to *position* using *core*."""
31
+
32
+
33
+ class BasicPositionMover(PositionMover):
34
+ """
35
+ Simple XYZ mover with no focus-maintenance polling.
36
+
37
+ Moves XY then Z and returns the position reported by the core.
38
+ Suitable for microscopes without hardware autofocus or when using the
39
+ simulated core in dry-run mode.
40
+ """
41
+
42
+ def move_to(self, position, core) -> tuple[bool, float]:
43
+ start = time()
44
+
45
+ logger.info(f"moving to xy ({position.x}, {position.y})")
46
+ core.setXYPosition(position.x, position.y)
47
+
48
+ logger.info(f"moving to z {position.z}")
49
+ core.setPosition(position.z)
50
+
51
+ logger.info(f"move took {time() - start:.3f}s")
52
+ return True, core.getZPosition()
53
+
54
+
55
+ class PFSPositionMover(PositionMover):
56
+ """
57
+ Position mover for Nikon microscopes with the Perfect Focus System (PFS).
58
+
59
+ Moves to XY/Z, applies an optional PFS offset stored in
60
+ ``position.extras["PFSOffset"]``, then polls the PFS status property until
61
+ focus is confirmed locked, raising ``TimeoutError`` after ``PFS_TIMEOUT_S``.
62
+
63
+ The PFS can switch itself off (the interface was lost, or someone pressed
64
+ the button) and then ignore a repeated "On"; while waiting, the mover
65
+ switches focus maintenance off and on again every ``PFS_RETRY_S``.
66
+ Override ``PFS_DEVICE``, ``PFS_MAINTENANCE_PROPERTY``, ``PFS_STATUS_PROPERTY``,
67
+ and ``PFS_LOCKED_VALUE`` on a subclass if your hardware differs.
68
+ """
69
+
70
+ PFS_DEVICE = "PFS"
71
+ PFS_MAINTENANCE_PROPERTY = "FocusMaintenance"
72
+ PFS_STATUS_PROPERTY = "PFS Status"
73
+ PFS_LOCKED_VALUE = "0000001100001010"
74
+ PFS_TIMEOUT_S = 30.0
75
+ PFS_POLL_S = 0.01
76
+ PFS_RETRY_S = 5.0 # no lock after this long: switch focus maintenance off and on
77
+
78
+ def move_to(self, position, core) -> tuple[bool, float]:
79
+ start = time()
80
+
81
+ pfs_offset = position.extras.get("PFSOffset")
82
+
83
+ # Move Z down first if needed to avoid objective collision on XY slew
84
+ if position.z < core.getZPosition():
85
+ core.setPosition(position.z)
86
+
87
+ logger.info(f"moving to xy ({position.x}, {position.y})")
88
+ core.setXYPosition(position.x, position.y)
89
+
90
+ logger.info(f"moving to z {position.z}")
91
+ core.setPosition(position.z)
92
+
93
+ if pfs_offset is not None:
94
+ logger.info(f"setting PFS offset {pfs_offset}")
95
+ core.setAutoFocusOffset(pfs_offset)
96
+
97
+ core.setProperty(self.PFS_DEVICE, self.PFS_MAINTENANCE_PROPERTY, "On")
98
+
99
+ lock_start = time()
100
+ seen: dict[str, int] = {}
101
+ retries = 0
102
+ next_retry = lock_start + self.PFS_RETRY_S
103
+ while (
104
+ status := core.getProperty(self.PFS_DEVICE, self.PFS_STATUS_PROPERTY)
105
+ ) != self.PFS_LOCKED_VALUE:
106
+ seen[status] = seen.get(status, 0) + 1
107
+ if time() - lock_start > self.PFS_TIMEOUT_S:
108
+ # the status strings seen say why: searching, out of range, off
109
+ history = ", ".join(f"{s!r} x{n}" for s, n in seen.items())
110
+ raise TimeoutError(
111
+ f"PFS did not report focus lock within {self.PFS_TIMEOUT_S}s "
112
+ f"at x={position.x}, y={position.y}, z={position.z} "
113
+ f"(offset {pfs_offset}, z now {core.getZPosition():.2f}); "
114
+ f"status seen: {history}; focus maintenance was switched "
115
+ f"off and on {retries} time(s)"
116
+ )
117
+ if time() >= next_retry:
118
+ retries += 1
119
+ next_retry = time() + self.PFS_RETRY_S
120
+ logger.warning(
121
+ f"PFS not locked after {time() - lock_start:.1f}s (status "
122
+ f"{status!r}); switching focus maintenance off and on "
123
+ f"(attempt {retries})"
124
+ )
125
+ self._restart_focus_maintenance(core)
126
+ sleep(self.PFS_POLL_S)
127
+
128
+ if retries:
129
+ logger.warning(
130
+ f"PFS locked after {retries} restart(s) of focus maintenance"
131
+ )
132
+
133
+ logger.info(f"move+focus took {time() - start:.3f}s")
134
+ return True, core.getZPosition()
135
+
136
+ def _restart_focus_maintenance(self, core) -> None:
137
+ """Off then on: a repeated "On" alone does not restart a PFS that switched itself off."""
138
+ try:
139
+ core.setProperty(self.PFS_DEVICE, self.PFS_MAINTENANCE_PROPERTY, "Off")
140
+ sleep(0.2)
141
+ core.setProperty(self.PFS_DEVICE, self.PFS_MAINTENANCE_PROPERTY, "On")
142
+ except Exception as e:
143
+ logger.warning(f"restarting PFS focus maintenance failed: {e}")
144
+
145
+
146
+ MOVERS: dict[str, type[PositionMover]] = {
147
+ "basic": BasicPositionMover,
148
+ "pfs": PFSPositionMover,
149
+ }
150
+
151
+
152
+ def resolve_mover(spec: str) -> type[PositionMover]:
153
+ """
154
+ The :class:`PositionMover` subclass named by ``spec``: one of
155
+ :data:`MOVERS` (``"basic"``, ``"pfs"``) or a dotted path
156
+ ``"package.module:ClassName"`` to a custom subclass.
157
+ """
158
+ key = (spec or "basic").strip()
159
+ if key.lower() in MOVERS:
160
+ return MOVERS[key.lower()]
161
+ if ":" not in key:
162
+ raise ValueError(
163
+ f"position_mover {spec!r} is not one of {sorted(MOVERS)} and is not a "
164
+ "'package.module:ClassName' path"
165
+ )
166
+ module_name, _, class_name = key.partition(":")
167
+ import importlib
168
+
169
+ try:
170
+ module = importlib.import_module(module_name)
171
+ except ImportError as e:
172
+ raise ValueError(
173
+ f"position_mover {spec!r}: cannot import {module_name!r} ({e})"
174
+ ) from e
175
+ cls = getattr(module, class_name, None)
176
+ if (
177
+ cls is None
178
+ or not (isinstance(cls, type) and issubclass(cls, PositionMover))
179
+ or inspect.isabstract(cls)
180
+ ):
181
+ raise ValueError(
182
+ f"position_mover {spec!r}: {class_name!r} in {module_name!r} is not a "
183
+ "concrete PositionMover subclass"
184
+ )
185
+ return cls
pyclm/core/queues.py ADDED
@@ -0,0 +1,41 @@
1
+ """
2
+ Control queues connecting the pipeline processes.
3
+
4
+ All processes run as threads in one interpreter (see ``Controller.run``), so
5
+ the queues are plain ``queue.Queue`` objects: items are passed by reference,
6
+ never copied, and ``empty()`` / ``get_nowait()`` are reliable.
7
+
8
+ Only addressed control messages travel here (the Manager's events, the
9
+ SLM handshake). Frame-derived data (raw frames, segmentations, tracks) is
10
+ fanned out by the :class:`~pyclm.core.router.Router`, which owns one data
11
+ inbox per consumer.
12
+ """
13
+
14
+ from queue import Empty, Queue
15
+
16
+
17
+ class AllQueues:
18
+ def __init__(self):
19
+ # messages from manager
20
+ self.manager_to_microscope = Queue()
21
+ self.manager_to_slm_buffer = Queue()
22
+ self.manager_to_pattern = Queue()
23
+
24
+ # messages to manager
25
+ self.microscope_to_manager = Queue() # UpdateZPositionMessage, EventDoneMessage
26
+ self.pattern_to_manager = Queue() # SettingsRequestMessage
27
+
28
+ # pattern to slm buffer, slm buffer to microscope (synchronous handshake)
29
+ self.pattern_to_slm = Queue()
30
+ self.slm_to_microscope = Queue()
31
+
32
+ self.all_queues = [q for q in vars(self).values() if isinstance(q, Queue)]
33
+
34
+ def close(self):
35
+ """Discard anything left in the queues once every process has exited."""
36
+ for queue in self.all_queues:
37
+ while True:
38
+ try:
39
+ queue.get_nowait()
40
+ except Empty:
41
+ break
@@ -0,0 +1,158 @@
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ from collections.abc import Sequence
5
+ from typing import Any
6
+
7
+ from pymmcore_plus import CMMCorePlus
8
+
9
+ from .core_interface import MicroscopeCoreInterface
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+
14
+ class RealMicroscopeCore(MicroscopeCoreInterface):
15
+ """
16
+ Delegates everything to an internal CMMCorePlus.
17
+ """
18
+
19
+ def __init__(self):
20
+ self._core = CMMCorePlus()
21
+
22
+ def loadSystemConfiguration(self, configuration):
23
+ try:
24
+ self._core.loadSystemConfiguration(str(configuration))
25
+ except Exception as e:
26
+ if "interface" in str(e).lower():
27
+ raise RuntimeError(f"{e}" + chr(10) + device_interface_hint()) from e
28
+ raise
29
+ # a pymmcore-plus that does not belong with the installed pymmcore
30
+ # answers list-returning calls with None instead of a tuple; catch it
31
+ # here, once, rather than in every caller
32
+ groups = self._core.getAvailableConfigGroups()
33
+ if groups is None:
34
+ raise RuntimeError(
35
+ "the microscope core returned None for getAvailableConfigGroups "
36
+ "after loading the configuration: the installed pymmcore-plus and "
37
+ f"pymmcore do not belong together ({versions_hint()}). Run "
38
+ "`uv sync` in the repository to install the locked pair "
39
+ "(pyproject.toml, [tool.uv])."
40
+ )
41
+ logger.info(f"microscope core: {versions_hint()}; {len(groups)} config groups")
42
+
43
+ def getSLMDevice(self) -> str:
44
+ return self._core.getSLMDevice()
45
+
46
+ def getSLMHeight(self, device: str) -> int:
47
+ return self._core.getSLMHeight(device)
48
+
49
+ def getSLMWidth(self, device: str) -> int:
50
+ return self._core.getSLMWidth(device)
51
+
52
+ def setSLMImage(self, device: str, image: Any) -> None:
53
+ self._core.setSLMImage(device, image)
54
+
55
+ # Config/device properties
56
+ def setConfig(self, group: str, config: str) -> None:
57
+ self._core.setConfig(group, config)
58
+
59
+ def setProperty(self, label: str, name: str, value: Any) -> None:
60
+ self._core.setProperty(label, name, value)
61
+
62
+ def getProperty(self, label: str, name: str) -> str:
63
+ return self._core.getProperty(label, name)
64
+
65
+ def getAllowedPropertyValues(self, device: str, prop_name: str) -> Sequence[str]:
66
+ return self._core.getAllowedPropertyValues(device, prop_name)
67
+
68
+ def describe(self) -> str:
69
+ return self._core.describe()
70
+
71
+ def setFocusDevice(self, label: str) -> None:
72
+ self._core.setFocusDevice(label)
73
+
74
+ def getAvailableConfigGroups(self) -> Sequence[str]:
75
+ return self._core.getAvailableConfigGroups()
76
+
77
+ def getConfigGroupObject(self, group: str, include_read_only: bool = False):
78
+ return self._core.getConfigGroupObject(group, include_read_only)
79
+
80
+ # Camera-related
81
+ def getCameraDevice(self) -> str:
82
+ return self._core.getCameraDevice()
83
+
84
+ def setExposure(self, exposure_ms: float) -> None:
85
+ self._core.setExposure(exposure_ms)
86
+
87
+ def snapImage(self) -> None:
88
+ self._core.snapImage()
89
+
90
+ def getImage(self) -> Any:
91
+ return self._core.getImage()
92
+
93
+ def getPixelSizeUm(self) -> float:
94
+ return self._core.getPixelSizeUm()
95
+
96
+ def getROI(self):
97
+ return self._core.getROI()
98
+
99
+ def setROI(self, x: int, y: int, width: int, height: int) -> None:
100
+ self._core.setROI(int(x), int(y), int(width), int(height))
101
+
102
+ # Stage/focus/positioning
103
+ def getXYPosition(self) -> tuple[float, float]:
104
+ x, y = self._core.getXYPosition()
105
+ return float(x), float(y)
106
+
107
+ def getZPosition(self) -> float:
108
+ return self._core.getZPosition()
109
+
110
+ def setPosition(self, z: float) -> None:
111
+ self._core.setPosition(z)
112
+
113
+ def setXYPosition(self, x: float, y: float) -> None:
114
+ self._core.setXYPosition(x, y)
115
+
116
+ def setAutoFocusOffset(self, offset: float) -> None:
117
+ self._core.setAutoFocusOffset(offset)
118
+
119
+ # Synchronization
120
+ def waitForSystem(self) -> None:
121
+ self._core.waitForSystem()
122
+
123
+
124
+ def versions_hint() -> str:
125
+ import importlib.metadata as md
126
+
127
+ def v(name):
128
+ try:
129
+ return md.version(name)
130
+ except Exception:
131
+ return "?"
132
+
133
+ return (
134
+ f"pymmcore {v('pymmcore')}, pymmcore-plus {v('pymmcore-plus')}, "
135
+ f"device interface {device_interface()}"
136
+ )
137
+
138
+
139
+ def device_interface() -> int | None:
140
+ """The Micro-Manager device interface version this pymmcore was built for."""
141
+ try:
142
+ import pymmcore
143
+
144
+ return int(pymmcore.__version__.split(".")[3])
145
+ except Exception:
146
+ return None
147
+
148
+
149
+ def device_interface_hint() -> str:
150
+ di = device_interface()
151
+ return (
152
+ f"pymmcore speaks Micro-Manager device interface {di}: every device "
153
+ "adapter DLL it loads must be built for the same interface. Install a "
154
+ "Micro-Manager build of that interface (or the vendor's matching adapter), "
155
+ "or change the pymmcore pin (see pyproject.toml, [tool.uv])."
156
+ )
157
+
158
+ # SLM-related