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/cli.py ADDED
@@ -0,0 +1,256 @@
1
+ """
2
+ The ``pyclm`` command.
3
+
4
+ ::
5
+
6
+ pyclm run <dir> [--config FILE] [--dry] [--gui] [--no-check | --force]
7
+ pyclm check <dir> [--config FILE] [--mm-config FILE] [--dry]
8
+ pyclm preview <dir> <experiment> (--image FILE | --snap) [--config FILE] [--out DIR] [--t N]
9
+ pyclm export <dir> [channels ...] [--config FILE]
10
+ pyclm gui <dir>
11
+ pyclm new <dir> [--template open-loop|closed-loop] [--name NAME] [--demo]
12
+
13
+ ``pyclm <dir> [--dry] [--gui]`` (the form before Stage 5) still means ``run``.
14
+ Custom methods are loaded from ``methods`` in ``pyclm_config.toml`` and
15
+ from ``pyclm.methods`` entry points (:mod:`pyclm.methods`).
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import argparse
21
+ import sys
22
+ from pathlib import Path
23
+
24
+ COMMANDS = ("run", "check", "preview", "export", "gui", "new")
25
+
26
+
27
+ def build_parser() -> argparse.ArgumentParser:
28
+ parser = argparse.ArgumentParser(
29
+ prog="pyclm", description="Closed-loop optogenetic microscopy experiments."
30
+ )
31
+ sub = parser.add_subparsers(dest="command", required=True)
32
+
33
+ p = sub.add_parser("run", help="check an experiment directory, then run it")
34
+ p.add_argument("directory", help="directory containing the experiment files")
35
+ p.add_argument("--config", default=None, help="path to pyclm_config.toml")
36
+ p.add_argument("--dry", action="store_true", help="run on the virtual microscope")
37
+ p.add_argument("--gui", action="store_true", help="open the live viewer")
38
+ g = p.add_mutually_exclusive_group()
39
+ g.add_argument("--no-check", action="store_true", help="skip the check")
40
+ g.add_argument(
41
+ "--force", action="store_true", help="run even if the check finds errors"
42
+ )
43
+ p.set_defaults(func=cmd_run)
44
+
45
+ p = sub.add_parser("check", help="report problems in an experiment directory")
46
+ p.add_argument("directory")
47
+ p.add_argument("--config", default=None, help="path to pyclm_config.toml")
48
+ p.add_argument(
49
+ "--mm-config", default=None, help="MicroManager .cfg to check presets against"
50
+ )
51
+ p.add_argument(
52
+ "--dry",
53
+ action="store_true",
54
+ help="also run two timepoints on the virtual microscope",
55
+ )
56
+ p.add_argument(
57
+ "--pixel-size-um",
58
+ type=float,
59
+ default=None,
60
+ help="unbinned camera pixel size, to compare a grid's spacing with camera_roi",
61
+ )
62
+ p.set_defaults(func=cmd_check)
63
+
64
+ p = sub.add_parser(
65
+ "preview",
66
+ help="run one experiment's segmentation and pattern method on one image",
67
+ )
68
+ p.add_argument("directory")
69
+ p.add_argument(
70
+ "experiment", help="a position label (bar10.00) or a TOML stem (bar10)"
71
+ )
72
+ src = p.add_mutually_exclusive_group(required=True)
73
+ src.add_argument("--image", default=None, help="a TIF to use for every channel")
74
+ src.add_argument("--snap", action="store_true", help="snap from the microscope")
75
+ p.add_argument("--config", default=None, help="path to pyclm_config.toml")
76
+ p.add_argument(
77
+ "--out", default=None, help="output directory (default: <dir>/preview/<label>)"
78
+ )
79
+ p.add_argument("--t", type=int, default=0, help="the timepoint to pretend it is")
80
+ p.add_argument(
81
+ "--pixel-size-um",
82
+ type=float,
83
+ default=None,
84
+ help="pixel size of --image (default 1.0)",
85
+ )
86
+ p.set_defaults(func=cmd_preview)
87
+
88
+ p = sub.add_parser("export", help="write ImageJ hyperstacks for finished outputs")
89
+ p.add_argument("directory")
90
+ p.add_argument(
91
+ "channels", nargs="*", help="channels or groups to export (default: all)"
92
+ )
93
+ p.add_argument(
94
+ "--config", default=None, help="pyclm_config.toml for older HDF5 files"
95
+ )
96
+ p.set_defaults(func=cmd_export)
97
+
98
+ p = sub.add_parser("gui", help="open the live viewer on an experiment directory")
99
+ p.add_argument("directory")
100
+ p.set_defaults(func=cmd_gui)
101
+
102
+ p = sub.add_parser("new", help="create an experiment directory from a template")
103
+ p.add_argument("directory")
104
+ p.add_argument(
105
+ "--template",
106
+ default="closed-loop",
107
+ choices=("open-loop", "closed-loop"),
108
+ help="which template (default: closed-loop)",
109
+ )
110
+ p.add_argument(
111
+ "--name", default="experiment", help="the experiment name (<name>.toml)"
112
+ )
113
+ p.add_argument(
114
+ "--demo",
115
+ action="store_true",
116
+ help="a demo that runs on the virtual microscope: two experiments and "
117
+ "synthetic images (ignores --template and --name)",
118
+ )
119
+ p.set_defaults(func=cmd_new)
120
+ return parser
121
+
122
+
123
+ # --------------------------------------------------------------- commands
124
+ def cmd_run(args) -> int:
125
+ from .check import CheckFailed
126
+ from .gui import GuiUnavailable
127
+ from .methods import MethodLoadError
128
+ from .run_pyclm import run_pyclm
129
+
130
+ try:
131
+ run_pyclm(
132
+ Path(args.directory),
133
+ args.config,
134
+ dry=args.dry,
135
+ gui=args.gui,
136
+ check=not args.no_check,
137
+ force=args.force,
138
+ )
139
+ except CheckFailed as e:
140
+ print(str(e))
141
+ return 1
142
+ except (GuiUnavailable, MethodLoadError) as e:
143
+ print(f"error: {e}")
144
+ return 1
145
+ return 0
146
+
147
+
148
+ def cmd_check(args) -> int:
149
+ from .check import check_directory
150
+
151
+ report = check_directory(
152
+ Path(args.directory),
153
+ args.config,
154
+ mm_config=args.mm_config,
155
+ dry=args.dry,
156
+ pixel_size_um=args.pixel_size_um,
157
+ )
158
+ print(report.text())
159
+ return 0 if report.ok else 1
160
+
161
+
162
+ def cmd_preview(args) -> int:
163
+ from .methods import MethodLoadError
164
+ from .preview import preview
165
+
166
+ try:
167
+ result = preview(
168
+ Path(args.directory),
169
+ args.experiment,
170
+ image=args.image,
171
+ snap=args.snap,
172
+ config_path=args.config,
173
+ out_dir=args.out,
174
+ t=args.t,
175
+ pixel_size_um=args.pixel_size_um,
176
+ )
177
+ except MethodLoadError as e:
178
+ print(f"error: {e}")
179
+ return 1
180
+ print(result.text())
181
+ return 0
182
+
183
+
184
+ def cmd_export(args) -> int:
185
+ from . import io as pyclm_io
186
+ from .convert_hdf5s import find_affine_transform
187
+
188
+ directory = Path(args.directory)
189
+ wanted = set(args.channels)
190
+ fallback = find_affine_transform(directory, args.config)
191
+ written = []
192
+ for path in pyclm_io.find_experiments(directory):
193
+ with pyclm_io.open(path) as exp:
194
+ groups = None
195
+ if wanted:
196
+ groups = [
197
+ name
198
+ for name, g in exp.groups.items()
199
+ if name in wanted
200
+ or any(c in wanted for c in g.channels)
201
+ or ("stim" in wanted and g.name == "stim_aq")
202
+ ]
203
+ affine = (
204
+ exp.affine_transform if exp.affine_transform is not None else fallback
205
+ )
206
+ written += pyclm_io.export_imagej(exp, groups=groups, affine=affine)
207
+ print(f"exported {len(written)} stack(s)")
208
+ for path in written:
209
+ print(f" {path}")
210
+ return 0
211
+
212
+
213
+ def cmd_gui(args) -> int:
214
+ from .gui import GuiUnavailable, require_gui
215
+
216
+ try:
217
+ require_gui()
218
+ except GuiUnavailable as e:
219
+ print(f"error: {e}")
220
+ return 1
221
+ from .gui.gui_controller import main as gui_main
222
+
223
+ return gui_main([args.directory])
224
+
225
+
226
+ def cmd_new(args) -> int:
227
+ if args.demo:
228
+ from .demo import create_demo
229
+
230
+ written = create_demo(Path(args.directory))
231
+ print(f"created the demo in {args.directory}")
232
+ for path in written:
233
+ print(f" {path.name}")
234
+ print(f"try: pyclm run {args.directory} --dry (add --gui to watch)")
235
+ return 0
236
+ from .templates import create
237
+
238
+ written = create(Path(args.directory), args.template, args.name)
239
+ print(f"created {args.template} experiment in {args.directory}")
240
+ for path in written:
241
+ print(f" {path.name}")
242
+ print("edit the files, then: pyclm check " + args.directory)
243
+ return 0
244
+
245
+
246
+ def main(argv: list[str] | None = None) -> int:
247
+ argv = list(sys.argv[1:] if argv is None else argv)
248
+ # the pre-Stage-5 form: pyclm <dir> [--dry] [--gui] [--config X]
249
+ if argv and argv[0] not in COMMANDS and not argv[0].startswith("-"):
250
+ argv = ["run", *argv]
251
+ args = build_parser().parse_args(argv)
252
+ return int(args.func(args) or 0)
253
+
254
+
255
+ if __name__ == "__main__":
256
+ sys.exit(main())
pyclm/commands.py ADDED
@@ -0,0 +1,183 @@
1
+ """
2
+ Commands to a running experiment.
3
+
4
+ A command is one small JSON file in ``<experiment directory>/commands/``,
5
+ written atomically (a temporary name, then a rename). The Manager lists the
6
+ directory at the timepoint boundary, applies each command in name order,
7
+ records it in ``events.parquet`` and moves the file to ``commands/done/``.
8
+ Anything can write one: a script, a person with an
9
+ editor::
10
+
11
+ {"command": "set_exposure", "experiment": "bar10.00", "channel": "545", "ms": 80}
12
+
13
+ None of the commands changes the structure of the plan; ``stop_experiment``
14
+ ends one experiment early, which the storage handles as skipped frames.
15
+ See docs/stage5b-interactivity-design.md §6.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import json
21
+ import os
22
+ import shutil
23
+ import time
24
+ from pathlib import Path
25
+ from typing import Any, Literal
26
+
27
+ from pydantic import BaseModel, ConfigDict, ValidationError, model_validator
28
+
29
+ from .core import settings as runtime_settings
30
+ from .core.settings import STIMULATION, SettingChange
31
+
32
+ COMMANDS_DIR = "commands"
33
+ DONE_DIR = "done"
34
+ COMMAND_NAMES = (
35
+ "pause",
36
+ "resume",
37
+ "stop_run",
38
+ "stop_experiment",
39
+ "set_exposure",
40
+ "set_config",
41
+ "set_property",
42
+ "set_position",
43
+ "set_pattern",
44
+ )
45
+ # which fields each command needs
46
+ REQUIRED = {
47
+ "pause": (),
48
+ "resume": (),
49
+ "stop_run": (),
50
+ "stop_experiment": ("experiment",),
51
+ "set_exposure": ("experiment", "channel", "ms"),
52
+ "set_config": ("experiment", "channel", "group", "preset"),
53
+ "set_property": ("experiment", "channel", "device", "property", "value"),
54
+ "set_position": ("experiment",),
55
+ "set_pattern": ("experiment", "parameters"),
56
+ }
57
+
58
+ _counter = [0]
59
+
60
+
61
+ class Command(BaseModel):
62
+ """One command; ``describe()`` is what the events table records."""
63
+
64
+ model_config = ConfigDict(extra="forbid")
65
+
66
+ command: Literal[COMMAND_NAMES]
67
+ experiment: str | None = None
68
+ channel: str | None = None
69
+ ms: float | None = None
70
+ group: str | None = None
71
+ preset: str | None = None
72
+ device: str | None = None
73
+ property: str | None = None
74
+ value: bool | int | float | str | None = None
75
+ x: float | None = None
76
+ y: float | None = None
77
+ z: float | None = None
78
+ pfs_offset: float | None = None
79
+ parameters: dict[str, Any] | None = None
80
+ note: str | None = None
81
+
82
+ @model_validator(mode="after")
83
+ def _required(self):
84
+ missing = [f for f in REQUIRED[self.command] if getattr(self, f) is None]
85
+ if missing:
86
+ raise ValueError(f"{self.command} needs {', '.join(missing)}")
87
+ if self.command == "set_position" and all(
88
+ getattr(self, k) is None for k in ("x", "y", "z", "pfs_offset")
89
+ ):
90
+ raise ValueError("set_position needs at least one of x, y, z, pfs_offset")
91
+ if self.command == "set_exposure" and not (self.ms and self.ms > 0):
92
+ raise ValueError("ms must be positive")
93
+ return self
94
+
95
+ def describe(self) -> str:
96
+ fields = {
97
+ k: v
98
+ for k, v in self.model_dump().items()
99
+ if v is not None and k not in ("command", "note")
100
+ }
101
+ text = self.command
102
+ if fields:
103
+ text += " " + json.dumps(fields, default=str)
104
+ return text
105
+
106
+ def to_changes(self) -> list[SettingChange]:
107
+ """The setting changes of a ``set_*`` command (``set_pattern`` has none)."""
108
+ ch = self.channel if self.channel != STIMULATION else STIMULATION
109
+ if self.command == "set_exposure":
110
+ return [runtime_settings.exposure(ch, self.ms)]
111
+ if self.command == "set_config":
112
+ return [runtime_settings.config(ch, self.group, self.preset)]
113
+ if self.command == "set_property":
114
+ return [
115
+ runtime_settings.device_property(
116
+ ch, self.device, self.property, self.value
117
+ )
118
+ ]
119
+ if self.command == "set_position":
120
+ return [
121
+ runtime_settings.position(key, getattr(self, key))
122
+ for key in ("x", "y", "z", "pfs_offset")
123
+ if getattr(self, key) is not None
124
+ ]
125
+ return []
126
+
127
+
128
+ def commands_dir(directory) -> Path:
129
+ return Path(directory) / COMMANDS_DIR
130
+
131
+
132
+ def write_command(directory, command: Command | dict) -> Path:
133
+ """Write one command file atomically; returns its path."""
134
+ if not isinstance(command, Command):
135
+ command = Command.model_validate(command)
136
+ folder = commands_dir(directory)
137
+ folder.mkdir(parents=True, exist_ok=True)
138
+ _counter[0] += 1
139
+ stamp = time.strftime("%Y%m%d-%H%M%S")
140
+ # sorts by wall-clock time across writers, then by order within this process
141
+ name = f"{stamp}-{time.time_ns():020d}-{_counter[0]:04d}.json"
142
+ tmp = folder / f".{name}.tmp"
143
+ tmp.write_text(
144
+ command.model_dump_json(exclude_none=True, indent=1), encoding="utf-8"
145
+ )
146
+ final = folder / name
147
+ os.replace(tmp, final)
148
+ return final
149
+
150
+
151
+ def pending(directory) -> list[tuple[Path, Command | None, str | None]]:
152
+ """Command files not yet processed in ``<directory>/commands``, in name order."""
153
+ return pending_in(commands_dir(directory))
154
+
155
+
156
+ def pending_in(folder: Path) -> list[tuple[Path, Command | None, str | None]]:
157
+ """Command files in ``folder``: (path, command or None, problem or None), in name order."""
158
+ folder = Path(folder)
159
+ if not folder.is_dir():
160
+ return []
161
+ out = []
162
+ for path in sorted(p for p in folder.glob("*.json") if not p.name.startswith(".")):
163
+ try:
164
+ data = json.loads(path.read_text(encoding="utf-8"))
165
+ out.append((path, Command.model_validate(data), None))
166
+ except (OSError, ValueError, ValidationError) as e:
167
+ out.append((path, None, _problem(e)))
168
+ return out
169
+
170
+
171
+ def _problem(e: Exception) -> str:
172
+ if isinstance(e, ValidationError):
173
+ return "; ".join(err.get("msg", "") for err in e.errors())
174
+ return f"{type(e).__name__}: {e}"
175
+
176
+
177
+ def mark_done(path: Path) -> Path:
178
+ """Move a processed command file to ``commands/done/``."""
179
+ done = path.parent / DONE_DIR
180
+ done.mkdir(exist_ok=True)
181
+ target = done / path.name
182
+ shutil.move(str(path), str(target))
183
+ return target