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/core/measure.py ADDED
@@ -0,0 +1,266 @@
1
+ """
2
+ The measurement toolbox for pattern methods.
3
+
4
+ Three small things that every per-cell method otherwise re-implements:
5
+
6
+ - :class:`Regions`: a label image with per-object helpers. ``measure``
7
+ gives one value per object, ``paint`` turns per-object values back into
8
+ an image, ``owner_of`` matches the objects of one segmentation (nuclei)
9
+ to those of another (cells). A :class:`~pyclm.core.tracking.Tracks` is a
10
+ ``Regions`` whose ids persist across timepoints.
11
+ - :class:`PerTrack`: a value remembered per track id, read back as an array
12
+ aligned with the ids you ask for, with a population default for ids that
13
+ were never seen.
14
+ - :func:`nuclear_cytosolic_ratio`: the KTR biosensor readout, from a
15
+ nuclear and a cell segmentation and one intensity image.
16
+
17
+ regions = context.regions("545") # or context.tracks("545")
18
+ means = regions.measure(context.raw("545")) # one value per regions.ids
19
+ pattern = regions.paint(np.clip(duty, 0, 1)) # each object filled with its duty
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ from typing import NamedTuple
25
+
26
+ import numpy as np
27
+ from scipy import ndimage
28
+
29
+ _STATS = {
30
+ "mean": ndimage.mean,
31
+ "median": ndimage.median,
32
+ "min": ndimage.minimum,
33
+ "max": ndimage.maximum,
34
+ "sum": ndimage.sum_labels,
35
+ "std": ndimage.standard_deviation,
36
+ "var": ndimage.variance,
37
+ }
38
+
39
+
40
+ class Regions:
41
+ """
42
+ Labelled regions of one frame (0 = background). Every per-object result
43
+ is an array aligned with :attr:`ids`.
44
+ """
45
+
46
+ def __init__(self, labels: np.ndarray):
47
+ self.labels = np.asarray(labels)
48
+ self._ids: np.ndarray | None = None
49
+
50
+ @property
51
+ def ids(self) -> np.ndarray:
52
+ """The object ids present, ascending."""
53
+ if self._ids is None:
54
+ lab = self.labels
55
+ self._ids = np.unique(lab[lab > 0]).astype(np.int64)
56
+ return self._ids
57
+
58
+ def __len__(self) -> int:
59
+ return len(self.ids)
60
+
61
+ def __repr__(self) -> str:
62
+ return f"{type(self).__name__}({len(self)} objects, labels {self.labels.shape})"
63
+
64
+ def mask(self, region_id: int) -> np.ndarray:
65
+ """Boolean mask of one object."""
66
+ return self.labels == region_id
67
+
68
+ def areas(self) -> np.ndarray:
69
+ """Pixels per object."""
70
+ ids = self.ids
71
+ if len(ids) == 0:
72
+ return np.zeros(0, dtype=np.int64)
73
+ ones = np.ones(self.labels.shape, dtype=np.int64)
74
+ return np.asarray(ndimage.sum_labels(ones, self.labels, ids), dtype=np.int64)
75
+
76
+ def centroids(self) -> np.ndarray:
77
+ """``(N, 2)`` centroids as ``(y, x)`` in pixels."""
78
+ ids = self.ids
79
+ if len(ids) == 0:
80
+ return np.zeros((0, 2), dtype=float)
81
+ ones = np.ones(self.labels.shape, dtype=float)
82
+ return np.asarray(
83
+ ndimage.center_of_mass(ones, self.labels, ids), dtype=float
84
+ ).reshape(-1, 2)
85
+
86
+ def measure(self, image: np.ndarray, stat: str = "mean") -> np.ndarray:
87
+ """
88
+ One statistic of ``image`` per object: ``"mean"`` (default),
89
+ ``"median"``, ``"min"``, ``"max"``, ``"sum"``, ``"std"`` or ``"var"``.
90
+ """
91
+ fn = _STATS.get(stat)
92
+ if fn is None:
93
+ raise ValueError(f"unknown stat {stat!r}; choose from {sorted(_STATS)}")
94
+ image = np.asarray(image)
95
+ if image.shape != self.labels.shape:
96
+ raise ValueError(
97
+ f"image shape {image.shape} does not match labels {self.labels.shape}"
98
+ )
99
+ ids = self.ids
100
+ if len(ids) == 0:
101
+ return np.zeros(0, dtype=float)
102
+ return np.asarray(fn(image, self.labels, ids), dtype=float)
103
+
104
+ def paint(
105
+ self,
106
+ values,
107
+ ids=None,
108
+ background: float = 0.0,
109
+ dtype=np.float32,
110
+ ) -> np.ndarray:
111
+ """
112
+ An image with every object filled with its value. ``values`` is a
113
+ scalar (every object), a ``{id: value}`` dict, or an array aligned
114
+ with :attr:`ids` (or with ``ids`` if given). Pixels outside the
115
+ objects, and objects without a value, get ``background``.
116
+ """
117
+ size = int(self.labels.max()) + 1 if self.labels.size else 1
118
+ lut = np.full(size, background, dtype=dtype)
119
+ if isinstance(values, dict):
120
+ for k, v in values.items():
121
+ if 0 < int(k) < size:
122
+ lut[int(k)] = v
123
+ elif np.ndim(values) == 0:
124
+ lut[self.ids] = values
125
+ else:
126
+ target = self.ids if ids is None else np.asarray(ids, dtype=np.int64)
127
+ values = np.asarray(values)
128
+ if values.shape != target.shape:
129
+ raise ValueError(
130
+ f"{len(values)} values for {len(target)} ids; pass one value per id"
131
+ )
132
+ keep = (target > 0) & (target < size)
133
+ lut[target[keep]] = values[keep]
134
+ return lut[self.labels]
135
+
136
+ def select(self, ids) -> Regions:
137
+ """The same frame keeping only the objects in ``ids``."""
138
+ keep = np.isin(self.labels, np.asarray(list(ids), dtype=np.int64))
139
+ return Regions(np.where(keep, self.labels, 0))
140
+
141
+ def owner_of(self, other: Regions) -> np.ndarray:
142
+ """
143
+ For each object of ``other`` (say, a nucleus), the id of the object
144
+ of this frame (the cell) under its centroid, or 0 if there is none.
145
+ Aligned with ``other.ids``.
146
+ """
147
+ if other.labels.shape != self.labels.shape:
148
+ raise ValueError("owner_of needs two label images of the same shape")
149
+ c = other.centroids()
150
+ if len(c) == 0:
151
+ return np.zeros(0, dtype=np.int64)
152
+ yy = np.clip(np.rint(c[:, 0]).astype(int), 0, self.labels.shape[0] - 1)
153
+ xx = np.clip(np.rint(c[:, 1]).astype(int), 0, self.labels.shape[1] - 1)
154
+ return self.labels[yy, xx].astype(np.int64)
155
+
156
+
157
+ def as_regions(labels) -> Regions:
158
+ return labels if isinstance(labels, Regions) else Regions(labels)
159
+
160
+
161
+ class PerTrack:
162
+ """
163
+ A value remembered per track id (or region id). ``update`` stores the
164
+ latest value for each id; ``get`` reads values back aligned with the ids
165
+ you pass, filling ids never seen with a default.
166
+ """
167
+
168
+ def __init__(self, values: dict | None = None):
169
+ self._values: dict[int, float] = {
170
+ int(k): float(v) for k, v in (values or {}).items()
171
+ }
172
+
173
+ def update(self, ids, values) -> None:
174
+ for i, v in zip(ids, values, strict=True):
175
+ self._values[int(i)] = float(v)
176
+
177
+ def get(self, ids, default=None) -> np.ndarray:
178
+ """
179
+ Values for ``ids``. An unknown id gets ``default``: a number,
180
+ ``"median"`` or ``"mean"`` of the values known so far, or NaN when
181
+ ``default`` is None.
182
+ """
183
+ fill = self._fill(default)
184
+ return np.array([self._values.get(int(i), fill) for i in ids], dtype=float)
185
+
186
+ def known(self, ids) -> np.ndarray:
187
+ """Boolean array: which of ``ids`` have a value."""
188
+ return np.array([int(i) in self._values for i in ids], dtype=bool)
189
+
190
+ def _fill(self, default) -> float:
191
+ if default is None:
192
+ return float("nan")
193
+ if isinstance(default, str):
194
+ if not self._values:
195
+ return float("nan")
196
+ values = np.fromiter(self._values.values(), dtype=float)
197
+ if default == "median":
198
+ return float(np.median(values))
199
+ if default == "mean":
200
+ return float(np.mean(values))
201
+ raise ValueError(
202
+ f"unknown default {default!r}; use a number, 'median' or 'mean'"
203
+ )
204
+ return float(default)
205
+
206
+ @property
207
+ def ids(self) -> np.ndarray:
208
+ return np.array(sorted(self._values), dtype=np.int64)
209
+
210
+ def values(self) -> np.ndarray:
211
+ return np.array([self._values[i] for i in sorted(self._values)], dtype=float)
212
+
213
+ def forget(self, ids) -> None:
214
+ for i in ids:
215
+ self._values.pop(int(i), None)
216
+
217
+ def clear(self) -> None:
218
+ self._values.clear()
219
+
220
+ def as_dict(self) -> dict[int, float]:
221
+ return dict(self._values)
222
+
223
+ def __contains__(self, track_id) -> bool:
224
+ return int(track_id) in self._values
225
+
226
+ def __getitem__(self, track_id) -> float:
227
+ return self._values[int(track_id)]
228
+
229
+ def __len__(self) -> int:
230
+ return len(self._values)
231
+
232
+ def __repr__(self) -> str:
233
+ return f"PerTrack({len(self._values)} ids)"
234
+
235
+
236
+ class NuclearCytosolicRatio(NamedTuple):
237
+ """Per nucleus: its id, the cell it sits in (0 if none), and the readout."""
238
+
239
+ nucleus_ids: np.ndarray
240
+ cell_ids: np.ndarray
241
+ nuclear: np.ndarray
242
+ cytosolic: np.ndarray
243
+ ratio: np.ndarray
244
+
245
+
246
+ def nuclear_cytosolic_ratio(
247
+ nuclei, cells, image: np.ndarray, stat: str = "mean"
248
+ ) -> NuclearCytosolicRatio:
249
+ """
250
+ The KTR readout: for every nucleus, its intensity in ``image`` divided by
251
+ the intensity of the cytosol of the cell it sits in (that cell minus
252
+ every nucleus). ``nuclei`` and ``cells`` are label images or
253
+ :class:`Regions` of the same frame. Nuclei outside any cell, or in a
254
+ cell with no cytosol pixels, get NaN.
255
+ """
256
+ nuclei = as_regions(nuclei)
257
+ cells = as_regions(cells)
258
+ owner = cells.owner_of(nuclei)
259
+ nuclear = nuclei.measure(image, stat)
260
+ cytosol = Regions(np.where(nuclei.labels > 0, 0, cells.labels))
261
+ by_cell = dict(zip(cytosol.ids.tolist(), cytosol.measure(image, stat), strict=True))
262
+ cytosolic = np.array([by_cell.get(int(c), np.nan) for c in owner], dtype=float)
263
+ with np.errstate(divide="ignore", invalid="ignore"):
264
+ ratio = nuclear / cytosolic
265
+ ratio = np.where((owner > 0) & (cytosolic > 0), ratio, np.nan)
266
+ return NuclearCytosolicRatio(nuclei.ids, owner, nuclear, cytosolic, ratio)
pyclm/core/messages.py ADDED
@@ -0,0 +1,124 @@
1
+ """
2
+ Contains classes for passing messages between processes.
3
+
4
+ These messages are allowed to contain small bits of information, but
5
+ should not pass numpy arrays (see datatypes.py)
6
+ """
7
+
8
+ from .events import AcquisitionEvent, UpdatePatternEvent, UpdateStagePositionEvent
9
+
10
+
11
+ class Message:
12
+ # will always be a string
13
+ message = "BASE_MESSAGE"
14
+
15
+ def __repr__(self):
16
+ return f"message: {self.message}"
17
+
18
+
19
+ class CloseMessage(Message):
20
+ """Sent by the manager to every process once the schedule is complete."""
21
+
22
+ message = "close"
23
+
24
+
25
+ class AcquisitionEventMessage(Message):
26
+ message = "acquisition_event"
27
+
28
+ def __init__(self, event: AcquisitionEvent):
29
+ self.event = event
30
+
31
+
32
+ class UpdatePatternEventMessage(Message):
33
+ message = "update_pattern_event"
34
+
35
+ def __init__(self, event: UpdatePatternEvent):
36
+ self.event = event
37
+
38
+
39
+ class UpdatePositionEventMessage(Message):
40
+ message = "update_position_event"
41
+
42
+ def __init__(self, event: UpdateStagePositionEvent):
43
+ self.event = event
44
+
45
+
46
+ class StreamCloseMessage(Message):
47
+ message = "stream_close"
48
+
49
+
50
+ class UpdateZPositionMessage(Message):
51
+ message = "update_z_position"
52
+
53
+ def __init__(self, new_z_position, experiment_name):
54
+ self.new_z_position = new_z_position
55
+ self.experiment_name = experiment_name
56
+
57
+
58
+ class SettingsRequestMessage(Message):
59
+ """
60
+ Setting changes a pattern method asked for during ``generate`` at
61
+ timepoint ``t_requested``, sent by the pattern process to the Manager
62
+ (``changes`` are :class:`~pyclm.core.settings.SettingChange`).
63
+ """
64
+
65
+ message = "settings_request"
66
+
67
+ def __init__(self, experiment_name: str, t_requested: int, changes: list):
68
+ self.experiment_name = experiment_name
69
+ self.t_requested = int(t_requested)
70
+ self.changes = list(changes)
71
+
72
+
73
+ class UpdatePatternParamsMessage(Message):
74
+ """The Manager asks the pattern process to change a method's parameters (a command)."""
75
+
76
+ message = "update_pattern_params"
77
+
78
+ def __init__(self, experiment_name: str, parameters: dict):
79
+ self.experiment_name = experiment_name
80
+ self.parameters = dict(parameters)
81
+
82
+
83
+ class PatternParamsResultMessage(Message):
84
+ """The pattern process's answer: which parameters were applied and which refused (with reasons)."""
85
+
86
+ message = "pattern_params_result"
87
+
88
+ def __init__(self, experiment_name: str, applied: dict, refused: dict):
89
+ self.experiment_name = experiment_name
90
+ self.applied = dict(applied)
91
+ self.refused = dict(refused)
92
+
93
+
94
+ class EventDoneMessage(Message):
95
+ """
96
+ The microscope's acknowledgement of one acquisition event: when it was
97
+ scheduled, when it completed, and the error text if it failed.
98
+ """
99
+
100
+ message = "event_done"
101
+
102
+ def __init__(
103
+ self, event: AcquisitionEvent, error: str | None = None, skipped: bool = False
104
+ ):
105
+ self.event = event
106
+ self.event_id = event.id
107
+ self.experiment_name = event.experiment_name
108
+ self.index = dict(event.index)
109
+ self.channel = event.index.get("c")
110
+ self.scheduled_time = event.scheduled_time
111
+ self.completed_time = event.completed_time
112
+ self.error = error
113
+ # the microscope skipped the exposure (stimulation only, blank pattern)
114
+ self.skipped = skipped
115
+
116
+ @property
117
+ def t_index(self) -> int:
118
+ return int(self.index.get("t", 0))
119
+
120
+ @property
121
+ def lateness_s(self) -> float | None:
122
+ if self.completed_time is None or not self.scheduled_time:
123
+ return None
124
+ return float(self.completed_time - self.scheduled_time)