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,206 @@
1
+ from pathlib import Path
2
+
3
+ import numpy as np
4
+ import tifffile as tiff
5
+ import yaml
6
+
7
+ DEFAULT_PIXEL_SIZE_UM = 0.33
8
+
9
+
10
+ class TimeSeriesImageSource:
11
+ """
12
+ Frames for the virtual microscope, per position. ``pixel_size_um`` is
13
+ the size of one pixel of the TIFs; ``binning`` is the binning the TIFs
14
+ were acquired at relative to the camera the affine transform of
15
+ ``pyclm_config.toml`` was calibrated for (the dry run scales the affine
16
+ by it).
17
+ """
18
+
19
+ pixel_size_um: float = DEFAULT_PIXEL_SIZE_UM
20
+ binning: int = 1
21
+
22
+ def __init__(self, folder: Path, loop: bool = True):
23
+ self._loop = loop
24
+ self._pos_map: dict[tuple[float, float], str] = {}
25
+ self._index_map: dict[str, int] = {}
26
+ self._frames_map: dict[str, list[np.ndarray]] = {}
27
+ self._default_stack: str | None = None
28
+ self._use_default_for_unknown: bool = False
29
+
30
+ self.initialize_from_folder(folder)
31
+
32
+ @classmethod
33
+ def from_mapping(
34
+ cls,
35
+ pos_to_tif: dict[tuple[float, float], Path],
36
+ loop: bool = True,
37
+ pixel_size_um: float = DEFAULT_PIXEL_SIZE_UM,
38
+ binning: int = 1,
39
+ ) -> "TimeSeriesImageSource":
40
+ """Build a source directly from a coordinate → TIF-path mapping."""
41
+ instance = cls.__new__(cls)
42
+ instance._loop = loop
43
+ instance.pixel_size_um = float(pixel_size_um)
44
+ instance.binning = int(binning)
45
+ instance._pos_map = {}
46
+ instance._index_map = {}
47
+ instance._frames_map = {}
48
+ instance._default_stack = None
49
+ instance._use_default_for_unknown = False
50
+
51
+ for pos, tif_path in pos_to_tif.items():
52
+ tif_path = Path(tif_path)
53
+ name = str(tif_path)
54
+ instance._pos_map[pos] = name
55
+ if name not in instance._frames_map:
56
+ data = instance._load_and_normalize_tiff(tif_path)
57
+ frames = [data[t, 0, 0] for t in range(data.shape[0])]
58
+ instance._frames_map[name] = frames
59
+ instance._index_map[name] = 0
60
+
61
+ if instance._frames_map:
62
+ instance._default_stack = next(iter(instance._frames_map.keys()))
63
+
64
+ return instance
65
+
66
+ @classmethod
67
+ def from_tiff_stack(
68
+ cls,
69
+ tif_path: Path,
70
+ loop: bool = True,
71
+ ) -> "TimeSeriesImageSource":
72
+ """Build a source from a single TIF stack used for all positions."""
73
+ instance = cls.__new__(cls)
74
+ instance._loop = loop
75
+ instance._pos_map = {}
76
+ instance._index_map = {}
77
+ instance._frames_map = {}
78
+ instance._default_stack = None
79
+ instance._use_default_for_unknown = True
80
+
81
+ tif_path = Path(tif_path)
82
+ name = str(tif_path)
83
+ data = instance._load_and_normalize_tiff(tif_path)
84
+ frames = [data[t, 0, 0] for t in range(data.shape[0])]
85
+ instance._frames_map[name] = frames
86
+ instance._index_map[name] = 0
87
+ instance._default_stack = name
88
+
89
+ return instance
90
+
91
+ def read_yaml(self, data_directory: Path):
92
+ yaml_path = Path.joinpath(data_directory, "image_positions.yaml")
93
+ with open(yaml_path) as file:
94
+ data = yaml.safe_load(file)
95
+ if data is None:
96
+ raise ValueError(f"{yaml_path} is empty")
97
+ positions = data.get("positions")
98
+ pos_map: dict[tuple[float, float], str] = {}
99
+ for entry in positions:
100
+ x = entry["x"]
101
+ y = entry["y"]
102
+ file = str(entry["file"])
103
+ key = (x, y)
104
+ pos_map[key] = file
105
+ return pos_map
106
+
107
+ def initialize_from_folder(self, folder: Path) -> None:
108
+ folder = Path(folder)
109
+ self._pos_map = self.read_yaml(folder)
110
+ self._index_map: dict[str, int] = {}
111
+ self._frames_map: dict[str, list[np.ndarray]] = {}
112
+ for name in self._pos_map.values():
113
+ file_path = Path.joinpath(folder, Path(name))
114
+ data = self._load_and_normalize_tiff(file_path)
115
+ frames = [data[t, 0, 0] for t in range(data.shape[0])]
116
+ self._frames_map[name] = frames
117
+ self._index_map[name] = 0
118
+ self._default_stack = next(iter(self._frames_map.keys()))
119
+
120
+ @property
121
+ def shape(self) -> tuple[int, ...]:
122
+ if self._default_stack is None:
123
+ raise RuntimeError("TimeSeriesImageSource not initialized")
124
+ return self._frames_map[self._default_stack][0].shape
125
+
126
+ def nearest(self, pos) -> tuple[float, float] | None:
127
+ """
128
+ The listed position closest to ``pos`` (exact match first), or None
129
+ when the source has no positions. A grid's tiles resolve to the grid
130
+ position this way.
131
+ """
132
+ pos = tuple(float(v) for v in pos)
133
+ if pos in self._pos_map:
134
+ return pos
135
+ if not self._pos_map:
136
+ return None
137
+ return min(
138
+ self._pos_map,
139
+ key=lambda k: (k[0] - pos[0]) ** 2 + (k[1] - pos[1]) ** 2,
140
+ )
141
+
142
+ def next_frame(self, pos) -> np.ndarray:
143
+ key = self.nearest(pos)
144
+ if key is None:
145
+ if self._use_default_for_unknown and self._default_stack is not None:
146
+ stack_name = self._default_stack
147
+ else:
148
+ raise KeyError(f"Position {tuple(pos)} not found in image source")
149
+ else:
150
+ stack_name = self._pos_map[key]
151
+ frames = self._frames_map[stack_name]
152
+ frame = frames[self._index_map[stack_name]]
153
+ self._index_map[stack_name] += 1
154
+ if self._index_map[stack_name] >= len(frames):
155
+ if self._loop:
156
+ self._index_map[stack_name] = 0
157
+ else:
158
+ self._index_map[stack_name] = len(frames) - 1
159
+ return frame
160
+
161
+ @staticmethod
162
+ def _normalize_axes_ome(data: np.ndarray, axes: str) -> np.ndarray:
163
+ target = "TCZYX"
164
+ axes = axes.upper()
165
+ axis_map = {ax: i for i, ax in enumerate(axes)}
166
+ for ax in target:
167
+ if ax not in axis_map:
168
+ data = np.expand_dims(data, axis=0)
169
+ axis_map = {k: v + 1 for k, v in axis_map.items()}
170
+ axis_map[ax] = 0
171
+
172
+ order = [axis_map[ax] for ax in target]
173
+ return np.moveaxis(data, order, range(len(order)))
174
+
175
+ def _load_and_normalize_tiff(self, file_path: Path) -> np.ndarray:
176
+ with tiff.TiffFile(file_path) as tif:
177
+ data = tif.asarray()
178
+ if tif.is_ome:
179
+ axes = tif.series[0].axes
180
+ data = self._normalize_axes_ome(data, axes)
181
+ else:
182
+ # Non-OME fallback: infer axes from ndim, then normalize to TCZYX
183
+ # Heuristics (common cases):
184
+ # 2D: YX
185
+ # 3D: TYX
186
+ # 4D: TCYX
187
+ # 5D: TCZYX
188
+ if data.ndim == 2:
189
+ axes = "YX"
190
+ elif data.ndim == 3:
191
+ axes = "TYX"
192
+ elif data.ndim == 4:
193
+ axes = "TCYX"
194
+ elif data.ndim == 5:
195
+ axes = "TCZYX"
196
+ else:
197
+ raise ValueError(
198
+ f"{file_path} has unsupported ndim={data.ndim}. "
199
+ "Expected 2D-5D TIFF for non-OME fallback."
200
+ )
201
+
202
+ data = self._normalize_axes_ome(data, axes)
203
+
204
+ if data.ndim != 5:
205
+ raise RuntimeError("TIFF data not 5D after normalization")
206
+ return data
@@ -0,0 +1,130 @@
1
+ """
2
+ The writer: a pipeline consumer that hands every frame, label image and
3
+ track table it receives to the configured :class:`~pyclm.core.storage.FrameWriter`.
4
+
5
+ It subscribes to every raw frame (so stimulation events and DMD patterns are
6
+ recorded even when the camera frame is not saved) and, with ``demand=False``,
7
+ to the segmentation and tracking output of channels whose method has
8
+ ``save = true``: those subscriptions record what is produced anyway and never
9
+ cause a stage to run (docs/stage3-router-design.md §3.4).
10
+ """
11
+
12
+ import logging
13
+ from pathlib import Path
14
+ from threading import Event
15
+
16
+ from .base_process import PipelineProcess
17
+ from .core_interface import MicroscopeCoreInterface
18
+ from .kinds import base_kind, seg_kind
19
+ from .plan import AcquisitionPlan
20
+ from .router import Subscription
21
+ from .storage import FrameWriter, HDF5WriterV1
22
+
23
+ logger = logging.getLogger(__name__)
24
+
25
+
26
+ class WriterProcess(PipelineProcess):
27
+ always_active = True
28
+
29
+ def __init__(
30
+ self,
31
+ base_path: Path | None = None,
32
+ stop_event: Event | None = None,
33
+ writer: FrameWriter | None = None,
34
+ ):
35
+ super().__init__(stop_event, name="writer")
36
+ self.base_path = Path(base_path) if base_path is not None else Path.cwd()
37
+ self.writer: FrameWriter = writer if writer is not None else HDF5WriterV1()
38
+ self.plan: AcquisitionPlan | None = None
39
+
40
+ @property
41
+ def open_files(self) -> dict:
42
+ """Open HDF5 handles when the HDF5 writer is in use (empty otherwise)."""
43
+ return getattr(self.writer, "open_files", {})
44
+
45
+ @property
46
+ def dropped_frames(self) -> int:
47
+ return getattr(self.writer, "dropped_frames", 0)
48
+
49
+ # ------------------------------------------------------------ routing
50
+ def subscriptions(self, plan: AcquisitionPlan) -> list[Subscription]:
51
+ subs = []
52
+ for name in plan.experiments:
53
+ experiment = plan.schedule.experiments[name]
54
+ record = {
55
+ seg_kind(seg): bool(cfg.save)
56
+ for seg, cfg in experiment.segmentations.items()
57
+ }
58
+ tracking = getattr(experiment, "tracking", None)
59
+ record["tracks"] = bool(tracking is not None and tracking.save)
60
+ stim = plan.stim_channel(name)
61
+ for channel in plan.channels(name):
62
+ subs.append(Subscription(self.name, name, channel, "raw", demand=False))
63
+ if channel == stim:
64
+ subs.append(
65
+ Subscription(self.name, name, channel, "skipped", demand=False)
66
+ )
67
+ for kind, wanted in record.items():
68
+ if wanted:
69
+ subs.append(
70
+ Subscription(self.name, name, channel, kind, demand=False)
71
+ )
72
+ return subs
73
+
74
+ # ---------------------------------------------------------- lifecycle
75
+ def initialize(
76
+ self,
77
+ plan: AcquisitionPlan,
78
+ core: MicroscopeCoreInterface,
79
+ affine_transform=None,
80
+ slm_shape=None,
81
+ ):
82
+ """Create the outputs for the plan. Returns the (path, layer) pairs for the GUI."""
83
+ self.plan = plan
84
+ recorded = routing = None
85
+ if self.router is not None:
86
+ recorded = self.router.deliveries_to(self.name)
87
+ routing = self.router.as_dict()
88
+ return self.writer.open(
89
+ plan,
90
+ core,
91
+ self.base_path,
92
+ affine_transform,
93
+ slm_shape,
94
+ recorded=recorded,
95
+ routing=routing,
96
+ )
97
+
98
+ def close_files(self):
99
+ """Finalise and close all outputs (idempotent)."""
100
+ self.writer.close()
101
+
102
+ def process(self):
103
+ """Run the poll loop and close the outputs however the loop exits."""
104
+ try:
105
+ super().process()
106
+ finally:
107
+ self.close_files()
108
+
109
+ def on_stream_end(self) -> bool:
110
+ self.close_files()
111
+ return super().on_stream_end()
112
+
113
+ # ------------------------------------------------------------ writing
114
+ def write_data(self, data):
115
+ kind = base_kind(getattr(data, "kind", "raw"))
116
+ if kind == "skipped":
117
+ self.writer.write_skipped(data)
118
+ elif kind == "seg":
119
+ self.writer.write_labels(data)
120
+ elif kind == "tracks":
121
+ self.writer.write_tracks(data)
122
+ else:
123
+ self.writer.write_frame(data)
124
+
125
+ def handle_data(self, data):
126
+ self.write_data(data)
127
+
128
+
129
+ # the writer was the "microscope outbox" before Stage 3
130
+ MicroscopeOutbox = WriterProcess
pyclm/demo.py ADDED
@@ -0,0 +1,225 @@
1
+ """
2
+ ``pyclm new <dir> --demo``: an experiment directory that runs on any
3
+ computer, without a microscope or downloaded data.
4
+
5
+ It holds two experiments on the virtual microscope:
6
+
7
+ - ``bar``: open loop, a bar of light sweeping across the field;
8
+ - ``cells``: closed loop, cells found by a threshold segmentation that the
9
+ directory brings with it (``demo_methods.py``, loaded through ``methods``
10
+ in ``pyclm_config.toml``), lit on their outward-facing half (``move_out``).
11
+
12
+ The images are synthetic cells drawn here, so nothing is downloaded; the
13
+ configuration's DMD calibration covers the whole simulated camera. Run it
14
+ with ``pyclm run <dir> --dry`` (add ``--gui`` with the gui extra).
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from pathlib import Path
20
+
21
+ import numpy as np
22
+
23
+ from .templates import CLOSED_LOOP, OPEN_LOOP
24
+
25
+ FRAMES = 10
26
+ SIZE = 512 # pixels of the demo TIFs (4x binned: the simulated camera is 2048 square)
27
+ PIXEL_SIZE_UM = 0.325 # unbinned: 1.3 um per TIF pixel at the experiments' binning 4
28
+
29
+ SCHEDULE = """# The demo's timing: ten timepoints three seconds apart
30
+ [timing]
31
+ steps = 10
32
+ interval_seconds = 3
33
+ setup_time_seconds = 0.5
34
+ time_between_positions = 0.2
35
+ """
36
+
37
+ CONFIG = """# The demo's configuration for the virtual microscope (pyclm run --dry).
38
+ # config_path is only read on a real microscope.
39
+ config_path = "C:\\\\Program Files\\\\Micro-Manager-2.0\\\\MMConfig.cfg"
40
+
41
+ # a calibration that maps the whole simulated camera (2048 x 2048 unbinned
42
+ # pixels) onto the DMD; a real one comes from the Projector plugin
43
+ affine_transform = [[0.4453125, 0.0, 0.0], [0.0, 0.556640625, 0.0]]
44
+ slm_shape_h = 1140
45
+ slm_shape_w = 912
46
+
47
+ settle_time_seconds = 0.0
48
+
49
+ # methods of this directory: the threshold segmentation cells.toml uses
50
+ methods = ["demo_methods.py"]
51
+
52
+ [output]
53
+ format = "ome-zarr"
54
+ pattern_policy = "on_change"
55
+ export_imagej = true
56
+ """
57
+
58
+ DRY_RUN = f"""# What the virtual microscope shows at each position. The simulated camera
59
+ # is 2048 pixels square; the TIFs are its frames at binning 4, which the
60
+ # experiment TOMLs ask for, as they would on a real camera.
61
+ pixel_size_um: {PIXEL_SIZE_UM} # unbinned camera pixel size
62
+ positions:
63
+ - name: bar.00
64
+ x: 0.0
65
+ y: 0.0
66
+ source: bar.tif
67
+ - name: cells.00
68
+ x: 2000.0
69
+ y: 0.0
70
+ source: cells.tif
71
+ """
72
+
73
+ METHODS = '''"""
74
+ The demo's own segmentation, loaded through ``methods`` in pyclm_config.toml.
75
+
76
+ A method of your own looks like this: a subclass with a ``name`` (what the
77
+ TOML's ``method = ...`` selects) and keyword arguments the TOML can set.
78
+ """
79
+
80
+ import numpy as np
81
+ from skimage.filters import threshold_otsu
82
+ from skimage.measure import label
83
+ from skimage.morphology import remove_small_objects
84
+
85
+ from pyclm import SegmentationMethod
86
+
87
+
88
+ class ThresholdSegmentation(SegmentationMethod):
89
+ """Cells are the connected regions brighter than Otsu's threshold."""
90
+
91
+ name = "threshold"
92
+
93
+ def __init__(self, experiment_name, min_size_px=20, **kwargs):
94
+ super().__init__(experiment_name, **kwargs)
95
+ self.min_size_px = int(min_size_px)
96
+
97
+ def segment(self, data: np.ndarray) -> np.ndarray:
98
+ image = np.asarray(data, dtype=np.float32)
99
+ mask = image > threshold_otsu(image)
100
+ mask = remove_small_objects(mask, self.min_size_px)
101
+ return label(mask).astype(np.int32)
102
+ '''
103
+
104
+ README = """This directory was created by `pyclm new --demo`. It runs on the virtual
105
+ microscope; no microscope, Micro-Manager or downloaded data is needed.
106
+
107
+ bar.toml open loop: a bar of light sweeping across the field
108
+ cells.toml closed loop: threshold segmentation, then light the
109
+ outward-facing half of every cell (move_out)
110
+ demo_methods.py the threshold segmentation: a custom method, listed under
111
+ methods in pyclm_config.toml
112
+ bar.tif, cells.tif synthetic cells the virtual microscope shows
113
+ dry_run.yml which TIF each position shows, and their pixel size
114
+ schedule.toml ten timepoints, three seconds apart
115
+ pyclm_config.toml the configuration (a calibration covering the whole camera)
116
+
117
+ Try
118
+ pyclm check <this directory>
119
+ pyclm preview <this directory> cells --image cells.tif
120
+ pyclm run <this directory> --dry (add --gui to watch, with the gui extra)
121
+
122
+ Then open the results: <experiment>.00.zarr in napari or Fiji, or in Python
123
+ import pyclm.io; exp = pyclm.io.open("cells.00.zarr")
124
+ To run again, delete the outputs (*.zarr, *_imaging.tif, frames.*, events.*,
125
+ status.json, log.log).
126
+ """
127
+
128
+
129
+ def synthetic_cells(
130
+ seed: int, frames: int = FRAMES, size: int = SIZE, n_cells: int = 60
131
+ ) -> np.ndarray:
132
+ """
133
+ A (frames, size, size) uint16 movie of round cells on a noisy background,
134
+ drifting slowly outward from the centre (what move_out would encourage).
135
+ """
136
+ rng = np.random.default_rng(seed)
137
+ # cells on a jittered grid, so that they rarely touch
138
+ side = int(np.ceil(np.sqrt(n_cells)))
139
+ pitch = size / side
140
+ gy, gx = np.mgrid[0:side, 0:side]
141
+ centres = (np.stack([gy.ravel(), gx.ravel()], axis=1) + 0.5) * pitch
142
+ centres = centres[:n_cells] + rng.uniform(-0.2, 0.2, (n_cells, 2)) * pitch
143
+ radii = rng.uniform(0.18, 0.3, n_cells) * pitch
144
+ brightness = rng.uniform(1500, 4000, n_cells)
145
+ outward = centres - size / 2
146
+ outward /= np.maximum(np.linalg.norm(outward, axis=1, keepdims=True), 1.0)
147
+
148
+ yy, xx = np.mgrid[0:size, 0:size].astype(np.float32)
149
+ movie = np.empty((frames, size, size), np.uint16)
150
+ for t in range(frames):
151
+ frame = np.full((size, size), 300.0, np.float32)
152
+ here = centres + outward * 0.8 * t
153
+ for (cy, cx), r, b in zip(here, radii, brightness, strict=True):
154
+ y0, y1 = max(int(cy - 2 * r), 0), min(int(cy + 2 * r) + 1, size)
155
+ x0, x1 = max(int(cx - 2 * r), 0), min(int(cx + 2 * r) + 1, size)
156
+ d2 = (yy[y0:y1, x0:x1] - cy) ** 2 + (xx[y0:y1, x0:x1] - cx) ** 2
157
+ # a soft-edged disc
158
+ frame[y0:y1, x0:x1] += b / (1.0 + np.exp((np.sqrt(d2) - r) / 1.5))
159
+ frame += rng.normal(0, 60, frame.shape)
160
+ movie[t] = np.clip(frame, 0, 65535).astype(np.uint16)
161
+ return movie
162
+
163
+
164
+ def _swap(text: str, old: str, new: str) -> str:
165
+ if old not in text:
166
+ raise RuntimeError(f"the demo expected {old!r} in the template")
167
+ return text.replace(old, new, 1)
168
+
169
+
170
+ def create_demo(directory: Path) -> list[Path]:
171
+ """Write the demo into ``directory`` (created if needed); existing files are kept."""
172
+ import tifffile
173
+
174
+ directory = Path(directory)
175
+ directory.mkdir(parents=True, exist_ok=True)
176
+
177
+ binned = (
178
+ "binning = 1\n",
179
+ "binning = 4 # the demo TIFs are 4x binned frames\n",
180
+ )
181
+ bar = _swap(OPEN_LOOP.format(name="bar"), *binned)
182
+ bar = _swap(
183
+ bar,
184
+ "every_t = 5 # image every 5th timepoint",
185
+ "every_t = 2 # image every 2nd timepoint",
186
+ )
187
+ bar = _swap(
188
+ bar,
189
+ "bar_speed = 1.0 # um per minute",
190
+ "bar_speed = 600.0 # um per minute: fast, for a 30 s demo",
191
+ )
192
+ cells = _swap(CLOSED_LOOP.format(name="cells"), *binned)
193
+ cells = _swap(
194
+ cells,
195
+ "every_t = 5 # image every 5th timepoint",
196
+ "every_t = 1 # image every timepoint",
197
+ )
198
+ cells = _swap(
199
+ cells,
200
+ 'method = "cellpose"\nmodel = "cpsam"',
201
+ 'method = "threshold" # from demo_methods.py\nmin_size_px = 20',
202
+ )
203
+ files = {
204
+ "bar.toml": bar,
205
+ "cells.toml": cells,
206
+ "schedule.toml": SCHEDULE,
207
+ "pyclm_config.toml": CONFIG,
208
+ "dry_run.yml": DRY_RUN,
209
+ "demo_methods.py": METHODS,
210
+ "README.txt": README,
211
+ }
212
+ written = []
213
+ for filename, text in files.items():
214
+ path = directory / filename
215
+ if path.exists():
216
+ continue
217
+ path.write_text(text, encoding="utf-8")
218
+ written.append(path)
219
+ for filename, seed in (("bar.tif", 1), ("cells.tif", 2)):
220
+ path = directory / filename
221
+ if path.exists():
222
+ continue
223
+ tifffile.imwrite(path, synthetic_cells(seed), metadata={"axes": "TYX"})
224
+ written.append(path)
225
+ return written