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/methods.py ADDED
@@ -0,0 +1,249 @@
1
+ """
2
+ Custom methods without writing Python to run them.
3
+
4
+ Pattern, segmentation and tracking methods outside PyCLM reach a run in
5
+ two ways:
6
+
7
+ - ``methods`` in ``pyclm_config.toml``: a list of Python files (relative
8
+ to the configuration file) or importable module names::
9
+
10
+ methods = ["my_patterns.py", "mylab.patterns"]
11
+
12
+ - the ``pyclm.methods`` entry-point group, for an installed package::
13
+
14
+ [project.entry-points."pyclm.methods"]
15
+ mylab = "mylab.patterns"
16
+
17
+ Every :class:`~pyclm.PatternMethod`, :class:`~pyclm.SegmentationMethod`
18
+ and :class:`~pyclm.TrackingMethod` subclass *defined* in such a module is
19
+ registered under its ``name`` class attribute, which is what
20
+ ``[pattern] method = ...`` (or ``[segmentation]``, ``[tracking]``) selects.
21
+ Classes the module imports from elsewhere are not registered again.
22
+ ``pyclm run``, ``pyclm check`` and ``pyclm preview`` all load them; methods
23
+ passed to :func:`~pyclm.run_pyclm` in code take precedence.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import importlib
29
+ import importlib.util
30
+ import inspect
31
+ import logging
32
+ import sys
33
+ from dataclasses import dataclass, field
34
+ from importlib.metadata import entry_points
35
+ from pathlib import Path
36
+ from types import ModuleType
37
+
38
+ logger = logging.getLogger(__name__)
39
+
40
+ ENTRY_POINT_GROUP = "pyclm.methods"
41
+
42
+
43
+ class MethodLoadError(Exception):
44
+ """A methods module could not be loaded or holds a method PyCLM cannot register."""
45
+
46
+
47
+ @dataclass
48
+ class MethodSet:
49
+ """Custom methods by kind, as ``{name: class}``, and where each came from."""
50
+
51
+ pattern: dict[str, type] = field(default_factory=dict)
52
+ segmentation: dict[str, type] = field(default_factory=dict)
53
+ tracking: dict[str, type] = field(default_factory=dict)
54
+ sources: dict[tuple[str, str], str] = field(default_factory=dict)
55
+
56
+ def kinds(self) -> dict[str, dict[str, type]]:
57
+ return {
58
+ "pattern": self.pattern,
59
+ "segmentation": self.segmentation,
60
+ "tracking": self.tracking,
61
+ }
62
+
63
+ def __len__(self) -> int:
64
+ return len(self.pattern) + len(self.segmentation) + len(self.tracking)
65
+
66
+ def add(self, kind: str, name: str, cls: type, source: str) -> None:
67
+ table = self.kinds()[kind]
68
+ have = table.get(name)
69
+ if have is not None and have is not cls:
70
+ raise MethodLoadError(
71
+ f"{kind} method {name!r} is defined twice: in "
72
+ f"{self.sources[(kind, name)]} and in {source}"
73
+ )
74
+ table[name] = cls
75
+ self.sources[(kind, name)] = source
76
+
77
+ def merged_with(
78
+ self, pattern=None, segmentation=None, tracking=None
79
+ ) -> tuple[dict, dict, dict]:
80
+ """These methods plus ones given in code (which win), per kind."""
81
+ return (
82
+ {**self.pattern, **(pattern or {})},
83
+ {**self.segmentation, **(segmentation or {})},
84
+ {**self.tracking, **(tracking or {})},
85
+ )
86
+
87
+ def summary(self) -> list[str]:
88
+ return [
89
+ f"{kind} method {name!r} from {self.sources[(kind, name)]}"
90
+ for kind, table in self.kinds().items()
91
+ for name in sorted(table)
92
+ ]
93
+
94
+
95
+ def _bases() -> dict[str, type]:
96
+ from .core.patterns.pattern import PatternMethod
97
+ from .core.segmentation.segmentation import SegmentationMethod
98
+ from .core.tracking.tracking import TrackingMethod
99
+
100
+ return {
101
+ "pattern": PatternMethod,
102
+ "segmentation": SegmentationMethod,
103
+ "tracking": TrackingMethod,
104
+ }
105
+
106
+
107
+ def _builtin_names() -> dict[str, set[str]]:
108
+ from .core.patterns import known_models
109
+ from .core.segmentation_process import SegmentationProcess
110
+ from .core.tracking import known_tracking_methods
111
+
112
+ return {
113
+ "pattern": set(known_models),
114
+ "segmentation": set(SegmentationProcess.default_models),
115
+ "tracking": set(known_tracking_methods),
116
+ }
117
+
118
+
119
+ def methods_in_module(module: ModuleType, source: str, into: MethodSet) -> int:
120
+ """Register the method classes ``module`` defines; returns how many."""
121
+ bases = _bases()
122
+ builtins = _builtin_names()
123
+ found = 0
124
+ defined = [
125
+ cls
126
+ for _, cls in inspect.getmembers(module, inspect.isclass)
127
+ if cls.__module__ == module.__name__ and not inspect.isabstract(cls)
128
+ ]
129
+ # a class another one here builds on may be a shared base without a name
130
+ parents = {base for cls in defined for base in cls.__mro__[1:]}
131
+ for cls in defined:
132
+ for kind, base in bases.items():
133
+ if not issubclass(cls, base) or cls is base:
134
+ continue
135
+ name = vars(cls).get("name")
136
+ if (not isinstance(name, str) or not name) and cls in parents:
137
+ continue
138
+ if not isinstance(name, str) or not name:
139
+ raise MethodLoadError(
140
+ f"{cls.__name__} in {source} is a {kind} method without its "
141
+ f'own name; add name = "..." to the class (the TOML selects '
142
+ "methods by it)"
143
+ )
144
+ if name in builtins[kind]:
145
+ raise MethodLoadError(
146
+ f"{cls.__name__} in {source}: {name!r} is the name of a built-in "
147
+ f"{kind} method; choose another name"
148
+ )
149
+ into.add(kind, name, cls, source)
150
+ found += 1
151
+ return found
152
+
153
+
154
+ def _import_file(path: Path) -> ModuleType:
155
+ module_name = f"pyclm_user_methods.{path.stem}"
156
+ spec = importlib.util.spec_from_file_location(module_name, path)
157
+ if spec is None or spec.loader is None:
158
+ raise MethodLoadError(f"{path} cannot be imported as a Python file")
159
+ module = importlib.util.module_from_spec(spec)
160
+ # siblings of the file (helper modules) import as they would from a script
161
+ folder = str(path.parent)
162
+ if folder not in sys.path:
163
+ sys.path.insert(0, folder)
164
+ sys.modules[module_name] = module
165
+ try:
166
+ spec.loader.exec_module(module)
167
+ except Exception as e:
168
+ sys.modules.pop(module_name, None)
169
+ raise MethodLoadError(f"{path}: {type(e).__name__}: {e}") from e
170
+ return module
171
+
172
+
173
+ def load_methods(specs: list[str], base_dir: Path) -> MethodSet:
174
+ """
175
+ The methods of ``specs``: ``.py`` paths (relative to ``base_dir``) or
176
+ module names. Raises :class:`MethodLoadError` on the first problem.
177
+ """
178
+ out = MethodSet()
179
+ for spec in specs:
180
+ if spec.endswith(".py") or "/" in spec or "\\" in spec:
181
+ path = Path(spec)
182
+ if not path.is_absolute():
183
+ path = Path(base_dir) / path
184
+ if not path.exists():
185
+ raise MethodLoadError(f"methods file {spec!r} not found ({path})")
186
+ module = _import_file(path.resolve())
187
+ source = str(spec)
188
+ else:
189
+ try:
190
+ module = importlib.import_module(spec)
191
+ except Exception as e:
192
+ raise MethodLoadError(
193
+ f"methods module {spec!r}: {type(e).__name__}: {e}"
194
+ ) from e
195
+ source = spec
196
+ if methods_in_module(module, source, out) == 0:
197
+ raise MethodLoadError(
198
+ f"{source} defines no PatternMethod, SegmentationMethod or "
199
+ "TrackingMethod subclass"
200
+ )
201
+ return out
202
+
203
+
204
+ def entry_point_methods(into: MethodSet | None = None) -> tuple[MethodSet, list[str]]:
205
+ """
206
+ The methods of installed packages' ``pyclm.methods`` entry points, and a
207
+ warning per entry point that failed (an unrelated broken package must
208
+ not stop a run).
209
+ """
210
+ out = into if into is not None else MethodSet()
211
+ warnings = []
212
+ for ep in entry_points(group=ENTRY_POINT_GROUP):
213
+ source = f"entry point {ep.name!r} ({ep.value})"
214
+ try:
215
+ target = ep.load()
216
+ if isinstance(target, ModuleType):
217
+ methods_in_module(target, source, out)
218
+ elif inspect.isclass(target):
219
+ module = sys.modules[target.__module__]
220
+ before = len(out)
221
+ methods_in_module(module, source, out)
222
+ if len(out) == before:
223
+ raise MethodLoadError(f"{target.__name__} is not a method class")
224
+ else:
225
+ raise MethodLoadError("must name a module or a method class")
226
+ except Exception as e:
227
+ warnings.append(f"{source} not loaded: {e}")
228
+ return out, warnings
229
+
230
+
231
+ def discover(
232
+ config=None, config_path: Path | None = None
233
+ ) -> tuple[MethodSet, list[str]]:
234
+ """
235
+ Every custom method a run sees: the entry points, then the
236
+ configuration's ``methods``. Returns the methods and the entry-point
237
+ warnings; a problem with ``methods`` raises :class:`MethodLoadError`.
238
+ """
239
+ methods, warnings = entry_point_methods()
240
+ specs = list(getattr(config, "methods", None) or [])
241
+ if specs:
242
+ base = Path(config_path).parent if config_path is not None else Path.cwd()
243
+ mine = load_methods(specs, base)
244
+ for kind, table in mine.kinds().items():
245
+ for name, cls in table.items():
246
+ methods.add(kind, name, cls, mine.sources[(kind, name)])
247
+ for line in methods.summary():
248
+ logger.info(f"custom {line}")
249
+ return methods, warnings
pyclm/mmconfig.py ADDED
@@ -0,0 +1,143 @@
1
+ """
2
+ A text reader for MicroManager ``.cfg`` files, so ``pyclm check`` can tell
3
+ whether the config groups, presets, devices and properties an experiment
4
+ uses exist, without loading the hardware.
5
+
6
+ Only the lines that matter are read::
7
+
8
+ Device,<label>,<library>,<adapter>
9
+ Property,<device>,<property>,<value>
10
+ ConfigGroup,<group>,<preset>,<device>,<property>,<value>
11
+ ConfigPixelSize,<preset>,<device>,<property>,<value>
12
+ PixelSize_um,<preset>,<value>
13
+
14
+ A property that never appears in the file may still exist on the device,
15
+ so :meth:`MMConfig.has_property` returns None for "unknown" rather than
16
+ False.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from dataclasses import dataclass, field
22
+ from pathlib import Path
23
+
24
+ CORE_DEVICE = "Core"
25
+
26
+
27
+ @dataclass
28
+ class MMConfig:
29
+ path: Path | None = None
30
+ devices: set[str] = field(default_factory=lambda: {CORE_DEVICE})
31
+ properties: dict[str, set[str]] = field(default_factory=dict)
32
+ # group -> preset -> [(device, property, value), ...]
33
+ groups: dict[str, dict[str, list[tuple[str, str, str]]]] = field(
34
+ default_factory=dict
35
+ )
36
+ # pixel-size preset -> (um per pixel, [(device, property, value), ...])
37
+ pixel_sizes: dict[str, tuple[float | None, list[tuple[str, str, str]]]] = field(
38
+ default_factory=dict
39
+ )
40
+
41
+ @classmethod
42
+ def from_file(cls, path: str | Path) -> MMConfig:
43
+ path = Path(path)
44
+ cfg = cls(path=path)
45
+ with open(path, encoding="utf-8", errors="replace") as f:
46
+ for raw in f:
47
+ line = raw.strip()
48
+ if not line or line.startswith("#"):
49
+ continue
50
+ parts = [p.strip() for p in line.split(",")]
51
+ kind = parts[0]
52
+ if kind == "Device" and len(parts) >= 2:
53
+ cfg.devices.add(parts[1])
54
+ elif kind == "Property" and len(parts) >= 3:
55
+ cfg.devices.add(parts[1])
56
+ cfg.properties.setdefault(parts[1], set()).add(parts[2])
57
+ elif kind == "ConfigPixelSize" and len(parts) >= 5:
58
+ _um, conds = cfg.pixel_sizes.setdefault(parts[1], (None, []))
59
+ conds.append((parts[2], parts[3], ",".join(parts[4:])))
60
+ elif kind == "PixelSize_um" and len(parts) >= 3:
61
+ _um, conds = cfg.pixel_sizes.setdefault(parts[1], (None, []))
62
+ try:
63
+ cfg.pixel_sizes[parts[1]] = (float(parts[2]), conds)
64
+ except ValueError:
65
+ pass
66
+ elif kind == "ConfigGroup" and len(parts) >= 3:
67
+ group = cfg.groups.setdefault(parts[1], {})
68
+ preset = group.setdefault(parts[2], [])
69
+ if len(parts) >= 6:
70
+ preset.append((parts[3], parts[4], ",".join(parts[5:])))
71
+ cfg.devices.add(parts[3])
72
+ cfg.properties.setdefault(parts[3], set()).add(parts[4])
73
+ return cfg
74
+
75
+ def has_group(self, group: str) -> bool:
76
+ return group in self.groups
77
+
78
+ def has_preset(self, group: str, preset: str) -> bool:
79
+ return preset in self.groups.get(group, {})
80
+
81
+ def presets(self, group: str) -> list[str]:
82
+ return sorted(self.groups.get(group, {}))
83
+
84
+ def has_device(self, label: str) -> bool:
85
+ return label in self.devices
86
+
87
+ def has_property(self, device: str, prop: str) -> bool | None:
88
+ """True / False when the device is known, None when the property is simply not listed."""
89
+ if device not in self.devices:
90
+ return False
91
+ return True if prop in self.properties.get(device, set()) else None
92
+
93
+ def device_state(
94
+ self, presets: list[tuple[str, str]]
95
+ ) -> dict[tuple[str, str], str]:
96
+ """The (device, property) -> value the given (group, preset) pairs set."""
97
+ state: dict[tuple[str, str], str] = {}
98
+ for group, preset in presets:
99
+ for device, prop, value in self.groups.get(group, {}).get(preset, []):
100
+ state[(device, prop)] = value
101
+ return state
102
+
103
+ def pixel_size_candidates(self, presets: list[tuple[str, str]]) -> list[dict]:
104
+ """
105
+ Every pixel-size preset against the device state the given (group,
106
+ preset) pairs produce: ``{"name", "um", "unmet", "unknown"}`` where
107
+ ``unmet`` lists conditions the state contradicts and ``unknown``
108
+ conditions on properties no given preset sets (MicroManager would
109
+ use the device's current value for those). Exact matches first.
110
+ """
111
+ state = self.device_state(presets)
112
+ out = []
113
+ for name, (um, conds) in self.pixel_sizes.items():
114
+ unmet, unknown = [], []
115
+ for device, prop, value in conds:
116
+ have = state.get((device, prop))
117
+ if have is None:
118
+ unknown.append((device, prop, value))
119
+ elif str(have).strip() != str(value).strip():
120
+ unmet.append((device, prop, value, have))
121
+ out.append({"name": name, "um": um, "unmet": unmet, "unknown": unknown})
122
+ out.sort(key=lambda c: (len(c["unmet"]), len(c["unknown"]), c["name"]))
123
+ return out
124
+
125
+ def pixel_size_for(
126
+ self, presets: list[tuple[str, str]]
127
+ ) -> tuple[str, float | None] | None:
128
+ """
129
+ The pixel-size preset whose conditions are all met by the device
130
+ state the given (group, preset) pairs produce, as (name, um), or
131
+ None. MicroManager resolves the pixel size the same way: every
132
+ condition of a preset must match the current device properties.
133
+ """
134
+ for c in self.pixel_size_candidates(presets):
135
+ if not c["unmet"] and not c["unknown"]:
136
+ return c["name"], c["um"]
137
+ return None
138
+
139
+ def summary(self) -> str:
140
+ return (
141
+ f"{len(self.devices)} devices, {len(self.groups)} config groups "
142
+ f"({', '.join(sorted(self.groups))})"
143
+ )