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.
- closed_loop_microscopy-1.1.0.dist-info/METADATA +118 -0
- closed_loop_microscopy-1.1.0.dist-info/RECORD +74 -0
- closed_loop_microscopy-1.1.0.dist-info/WHEEL +4 -0
- closed_loop_microscopy-1.1.0.dist-info/entry_points.txt +5 -0
- closed_loop_microscopy-1.1.0.dist-info/licenses/LICENSE.md +7 -0
- pyclm/__init__.py +26 -0
- pyclm/__main__.py +8 -0
- pyclm/check.py +931 -0
- pyclm/cli.py +256 -0
- pyclm/commands.py +183 -0
- pyclm/controller.py +447 -0
- pyclm/convert_hdf5s.py +273 -0
- pyclm/core/__init__.py +20 -0
- pyclm/core/base_process.py +166 -0
- pyclm/core/core_interface.py +47 -0
- pyclm/core/datatypes.py +142 -0
- pyclm/core/events.py +194 -0
- pyclm/core/experiments.py +403 -0
- pyclm/core/grid.py +272 -0
- pyclm/core/kinds.py +42 -0
- pyclm/core/manager.py +861 -0
- pyclm/core/measure.py +266 -0
- pyclm/core/messages.py +124 -0
- pyclm/core/microscope.py +504 -0
- pyclm/core/pattern_process.py +282 -0
- pyclm/core/patterns/__init__.py +60 -0
- pyclm/core/patterns/bar_patterns.py +259 -0
- pyclm/core/patterns/cell_intensity_patterns.py +181 -0
- pyclm/core/patterns/composite.py +220 -0
- pyclm/core/patterns/embryo_patterns.py +90 -0
- pyclm/core/patterns/fbc_cell_movement.py +295 -0
- pyclm/core/patterns/pattern.py +610 -0
- pyclm/core/patterns/pulse_patterns.py +261 -0
- pyclm/core/patterns/static_patterns.py +58 -0
- pyclm/core/patterns/wave_patterns.py +95 -0
- pyclm/core/patterns/zoo.py +231 -0
- pyclm/core/plan.py +623 -0
- pyclm/core/position_mover.py +185 -0
- pyclm/core/queues.py +41 -0
- pyclm/core/real_core.py +158 -0
- pyclm/core/router.py +422 -0
- pyclm/core/segmentation/__init__.py +2 -0
- pyclm/core/segmentation/cellpose_segmentation.py +113 -0
- pyclm/core/segmentation/segmentation.py +48 -0
- pyclm/core/segmentation_process.py +179 -0
- pyclm/core/settings.py +120 -0
- pyclm/core/storage/__init__.py +37 -0
- pyclm/core/storage/base.py +234 -0
- pyclm/core/storage/events.py +130 -0
- pyclm/core/storage/hdf5_v1.py +337 -0
- pyclm/core/storage/ome_zarr.py +861 -0
- pyclm/core/tracking/__init__.py +28 -0
- pyclm/core/tracking/centroid.py +75 -0
- pyclm/core/tracking/tracking.py +124 -0
- pyclm/core/tracking_process.py +106 -0
- pyclm/core/virtual_microscope/__init__.py +0 -0
- pyclm/core/virtual_microscope/simulated_core.py +262 -0
- pyclm/core/virtual_microscope/simulated_source.py +206 -0
- pyclm/core/writer_process.py +130 -0
- pyclm/demo.py +225 -0
- pyclm/directories.py +563 -0
- pyclm/gui/__init__.py +28 -0
- pyclm/gui/debug_viewer.py +41 -0
- pyclm/gui/gui_controller.py +551 -0
- pyclm/gui/widgets.py +292 -0
- pyclm/io/__init__.py +29 -0
- pyclm/io/export.py +202 -0
- pyclm/io/readers.py +589 -0
- pyclm/methods.py +249 -0
- pyclm/mmconfig.py +143 -0
- pyclm/preview.py +414 -0
- pyclm/run_pyclm.py +298 -0
- pyclm/schema.py +806 -0
- pyclm/templates.py +165 -0
|
@@ -0,0 +1,551 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Live napari viewer for a running (or finished) PyCLM experiment directory.
|
|
3
|
+
|
|
4
|
+
Reads every output through ``pyclm.io`` so it works for both the HDF5 (format 1)
|
|
5
|
+
and OME-Zarr (format 2) layouts.
|
|
6
|
+
|
|
7
|
+
Positions are an axis, not layers: every channel of a cadence group is one
|
|
8
|
+
layer whose data is stacked over (position, t, y, x), so the layer list has
|
|
9
|
+
one entry per channel however many positions are imaged, the position slider
|
|
10
|
+
(or the positions list in the dock, the minimap, the ``[`` / ``]`` keys)
|
|
11
|
+
switches between positions, and contrast limits are one setting per channel
|
|
12
|
+
that applies to every position. Groups of different cadence get their own
|
|
13
|
+
layers with the time scale set to the group's ``every_t``, so they line up
|
|
14
|
+
on the plan's time axis without blank frames. A cyan overlay shows the DMD
|
|
15
|
+
pattern in force at each frame when the affine transform is known.
|
|
16
|
+
|
|
17
|
+
Contrast is normalised automatically as frames arrive until you touch a
|
|
18
|
+
layer's limits; then they stay where you put them ("Auto-contrast" in the
|
|
19
|
+
dock turns it back on, "Normalise now" resets every channel once).
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import os
|
|
25
|
+
import sys
|
|
26
|
+
|
|
27
|
+
os.environ.setdefault("NAPARI_DISABLE_PLUGIN_AUTOLOAD", "1")
|
|
28
|
+
|
|
29
|
+
import argparse
|
|
30
|
+
import json
|
|
31
|
+
import logging
|
|
32
|
+
from dataclasses import dataclass, field
|
|
33
|
+
from pathlib import Path
|
|
34
|
+
|
|
35
|
+
import napari
|
|
36
|
+
import numpy as np
|
|
37
|
+
from qtpy import QtCore, QtWidgets
|
|
38
|
+
|
|
39
|
+
from pyclm import io as pyclm_io
|
|
40
|
+
from pyclm.io.export import pattern_overlay
|
|
41
|
+
|
|
42
|
+
from .widgets import RunOverview
|
|
43
|
+
|
|
44
|
+
logger = logging.getLogger(__name__)
|
|
45
|
+
|
|
46
|
+
AXIS_LABELS = ("position", "t", "y", "x")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _load_layers_file(path: Path) -> list[tuple[str, str]]:
|
|
50
|
+
with open(path, encoding="utf-8") as fh:
|
|
51
|
+
text = fh.read()
|
|
52
|
+
layers = []
|
|
53
|
+
try:
|
|
54
|
+
data = json.loads(text)
|
|
55
|
+
entries = data["all_layers"] if isinstance(data, dict) else data
|
|
56
|
+
except json.JSONDecodeError:
|
|
57
|
+
entries = [line for line in text.splitlines() if line.strip()]
|
|
58
|
+
for entry in entries:
|
|
59
|
+
path_str, layer = entry.rsplit(":", 1)
|
|
60
|
+
layers.append((path_str.strip().strip('"'), layer.strip()))
|
|
61
|
+
return layers
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _parse_src(s: str) -> tuple[str, str]:
|
|
65
|
+
if ":" not in s:
|
|
66
|
+
raise argparse.ArgumentTypeError(
|
|
67
|
+
'Each --src must be in the form "path:group/channel"'
|
|
68
|
+
)
|
|
69
|
+
path, layer = s.rsplit(":", 1)
|
|
70
|
+
return path.strip().strip('"'), layer.strip()
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _resolve_layer(exp: pyclm_io.ExperimentData, layer: str) -> tuple[str, str] | None:
|
|
74
|
+
"""Map a layer key ("imaging/545", "channel_545", "stim_aq") to (group, channel)."""
|
|
75
|
+
if "/" in layer:
|
|
76
|
+
group, channel = layer.split("/", 1)
|
|
77
|
+
if group in exp.groups and channel in exp.groups[group].channels:
|
|
78
|
+
return group, channel
|
|
79
|
+
return None
|
|
80
|
+
for name, g in exp.groups.items():
|
|
81
|
+
if name == layer or (
|
|
82
|
+
layer.startswith("channel_")
|
|
83
|
+
and name == layer.replace("channel_", "imaging_", 1)
|
|
84
|
+
):
|
|
85
|
+
return name, g.channels[0]
|
|
86
|
+
if layer in g.channels:
|
|
87
|
+
return name, layer
|
|
88
|
+
return None
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
# ================================================================ stacks
|
|
92
|
+
@dataclass(eq=False) # hashed by identity: stacks live in sets
|
|
93
|
+
class ChannelStack:
|
|
94
|
+
"""
|
|
95
|
+
One napari layer holding one channel of one cadence group for every
|
|
96
|
+
position: data (position, t, y, x). ``every_t`` / ``t_delay`` are the
|
|
97
|
+
cadence the layer's time axis is scaled to.
|
|
98
|
+
"""
|
|
99
|
+
|
|
100
|
+
key: str
|
|
101
|
+
every_t: int
|
|
102
|
+
t_delay: int
|
|
103
|
+
layer: napari.layers.Image
|
|
104
|
+
loaded: set[tuple[int, int]] = field(default_factory=set)
|
|
105
|
+
auto_contrast: bool = True
|
|
106
|
+
_resetting: bool = False
|
|
107
|
+
|
|
108
|
+
@property
|
|
109
|
+
def data(self) -> np.ndarray:
|
|
110
|
+
return self.layer.data
|
|
111
|
+
|
|
112
|
+
def put(self, p: int, i: int, frame: np.ndarray) -> None:
|
|
113
|
+
"""Store ``frame`` at (position p, local timepoint i), growing the stack as needed."""
|
|
114
|
+
data = self.layer.data
|
|
115
|
+
n_p, n_t = data.shape[0], data.shape[1]
|
|
116
|
+
h = max(data.shape[2], frame.shape[0])
|
|
117
|
+
w = max(data.shape[3], frame.shape[1])
|
|
118
|
+
grow = p >= n_p or i >= n_t or (h, w) != data.shape[2:]
|
|
119
|
+
if grow:
|
|
120
|
+
new = np.zeros((max(n_p, p + 1), max(n_t, i + 1), h, w), data.dtype)
|
|
121
|
+
new[:n_p, :n_t, : data.shape[2], : data.shape[3]] = data
|
|
122
|
+
data = new
|
|
123
|
+
data[p, i, : frame.shape[0], : frame.shape[1]] = frame
|
|
124
|
+
if grow:
|
|
125
|
+
self.layer.data = data
|
|
126
|
+
else:
|
|
127
|
+
self.layer.refresh()
|
|
128
|
+
self.loaded.add((p, i))
|
|
129
|
+
|
|
130
|
+
def reset_contrast(self) -> None:
|
|
131
|
+
self._resetting = True
|
|
132
|
+
try:
|
|
133
|
+
self.layer.reset_contrast_limits()
|
|
134
|
+
finally:
|
|
135
|
+
self._resetting = False
|
|
136
|
+
|
|
137
|
+
def _on_contrast_changed(self, event=None) -> None:
|
|
138
|
+
# the user moved the slider (our own resets are flagged): keep it
|
|
139
|
+
if not self._resetting:
|
|
140
|
+
self.auto_contrast = False
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
class Stacks:
|
|
144
|
+
"""The shared layers of a viewer, keyed by cadence group / channel."""
|
|
145
|
+
|
|
146
|
+
def __init__(self, viewer: napari.Viewer):
|
|
147
|
+
self.viewer = viewer
|
|
148
|
+
self.channels: dict[str, ChannelStack] = {}
|
|
149
|
+
self.patterns: dict[str, ChannelStack] = {}
|
|
150
|
+
self._cadence: dict[str, tuple[int, int]] = {}
|
|
151
|
+
|
|
152
|
+
def group_key(self, group: str, every_t: int, t_delay: int) -> str:
|
|
153
|
+
"""
|
|
154
|
+
The layer name for a cadence group: the group's name, or, if another
|
|
155
|
+
experiment uses the same name at a different cadence, name@every_t.
|
|
156
|
+
"""
|
|
157
|
+
key = group
|
|
158
|
+
seen = self._cadence.setdefault(key, (every_t, t_delay))
|
|
159
|
+
if seen != (every_t, t_delay):
|
|
160
|
+
key = f"{group}@{every_t}"
|
|
161
|
+
if t_delay:
|
|
162
|
+
key += f"+{t_delay}"
|
|
163
|
+
self._cadence.setdefault(key, (every_t, t_delay))
|
|
164
|
+
return key
|
|
165
|
+
|
|
166
|
+
def _new_layer(self, name, every_t, t_delay, shape, **kwargs):
|
|
167
|
+
data = np.zeros((1, 1, *shape), dtype=np.uint16)
|
|
168
|
+
return self.viewer.add_image(
|
|
169
|
+
data,
|
|
170
|
+
name=name,
|
|
171
|
+
scale=(1, every_t, 1, 1),
|
|
172
|
+
translate=(0, t_delay, 0, 0),
|
|
173
|
+
**kwargs,
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
def channel(self, gkey: str, channel: str, every_t, t_delay, shape) -> ChannelStack:
|
|
177
|
+
key = f"{gkey}/{channel}"
|
|
178
|
+
stack = self.channels.get(key)
|
|
179
|
+
if stack is None:
|
|
180
|
+
layer = self._new_layer(key, every_t, t_delay, shape)
|
|
181
|
+
stack = ChannelStack(key, every_t, t_delay, layer)
|
|
182
|
+
layer.events.contrast_limits.connect(stack._on_contrast_changed)
|
|
183
|
+
self.channels[key] = stack
|
|
184
|
+
return stack
|
|
185
|
+
|
|
186
|
+
def pattern(self, gkey: str, every_t, t_delay, shape) -> ChannelStack:
|
|
187
|
+
key = f"{gkey}/pattern"
|
|
188
|
+
stack = self.patterns.get(key)
|
|
189
|
+
if stack is None:
|
|
190
|
+
layer = self._new_layer(
|
|
191
|
+
key,
|
|
192
|
+
every_t,
|
|
193
|
+
t_delay,
|
|
194
|
+
shape,
|
|
195
|
+
colormap="cyan",
|
|
196
|
+
opacity=0.25,
|
|
197
|
+
contrast_limits=(0, 255),
|
|
198
|
+
blending="additive",
|
|
199
|
+
)
|
|
200
|
+
stack = ChannelStack(key, every_t, t_delay, layer, auto_contrast=False)
|
|
201
|
+
self.patterns[key] = stack
|
|
202
|
+
return stack
|
|
203
|
+
|
|
204
|
+
def all(self) -> list[ChannelStack]:
|
|
205
|
+
return [*self.channels.values(), *self.patterns.values()]
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
# ============================================================ experiments
|
|
209
|
+
class LiveExperiment:
|
|
210
|
+
"""One experiment output feeding position ``index`` of the shared stacks."""
|
|
211
|
+
|
|
212
|
+
def __init__(self, stacks: Stacks, path: str, layers: list[str], index: int):
|
|
213
|
+
self.stacks = stacks
|
|
214
|
+
self.index = index
|
|
215
|
+
self.exp = pyclm_io.open(path)
|
|
216
|
+
self.requested = [_resolve_layer(self.exp, k) for k in layers]
|
|
217
|
+
self.requested = [r for r in self.requested if r is not None]
|
|
218
|
+
self.gkeys: dict[str, str] = {}
|
|
219
|
+
for group, channel in self.requested:
|
|
220
|
+
g = self.exp.groups[group]
|
|
221
|
+
shape = g.shape if g.shape != (0, 0) else (1, 1)
|
|
222
|
+
gkey = self.gkeys.setdefault(
|
|
223
|
+
group, stacks.group_key(group, g.every_t, g.t_delay)
|
|
224
|
+
)
|
|
225
|
+
stacks.channel(gkey, channel, g.every_t, g.t_delay, shape)
|
|
226
|
+
if self.exp.affine_transform is not None:
|
|
227
|
+
stacks.pattern(gkey, g.every_t, g.t_delay, shape)
|
|
228
|
+
self.refresh()
|
|
229
|
+
|
|
230
|
+
@property
|
|
231
|
+
def name(self) -> str:
|
|
232
|
+
return self.exp.name
|
|
233
|
+
|
|
234
|
+
def refresh(self) -> set[ChannelStack]:
|
|
235
|
+
"""Load the frames written since last time; returns the stacks that changed."""
|
|
236
|
+
try:
|
|
237
|
+
self.exp.refresh()
|
|
238
|
+
except Exception as e: # file being written, retry next tick
|
|
239
|
+
logger.debug(f"refresh failed: {e}")
|
|
240
|
+
return set()
|
|
241
|
+
|
|
242
|
+
changed: set[ChannelStack] = set()
|
|
243
|
+
for group, channel in self.requested:
|
|
244
|
+
g = self.exp.groups[group]
|
|
245
|
+
gkey = self.gkeys[group]
|
|
246
|
+
stack = self.stacks.channel(gkey, channel, g.every_t, g.t_delay, (1, 1))
|
|
247
|
+
for i in g.acquired():
|
|
248
|
+
if (self.index, i) in stack.loaded:
|
|
249
|
+
continue
|
|
250
|
+
frame = g.frame(i, channel)
|
|
251
|
+
if frame is None:
|
|
252
|
+
continue
|
|
253
|
+
stack.put(self.index, i, frame)
|
|
254
|
+
changed.add(stack)
|
|
255
|
+
|
|
256
|
+
if self.exp.affine_transform is not None:
|
|
257
|
+
pstack = self.stacks.pattern(gkey, g.every_t, g.t_delay, (1, 1))
|
|
258
|
+
if (self.index, i) not in pstack.loaded:
|
|
259
|
+
overlay = pattern_overlay(
|
|
260
|
+
self.exp, g, frame.shape, g.global_t(i)
|
|
261
|
+
)
|
|
262
|
+
if overlay is not None:
|
|
263
|
+
pstack.put(self.index, i, overlay)
|
|
264
|
+
return changed
|
|
265
|
+
|
|
266
|
+
def close(self):
|
|
267
|
+
self.exp.close()
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
# =============================================================== controls
|
|
271
|
+
class ViewerControls(QtWidgets.QWidget):
|
|
272
|
+
"""
|
|
273
|
+
The positions list (click to view), "follow the run", and the contrast
|
|
274
|
+
controls, under the status line and minimap in the viewer's dock.
|
|
275
|
+
"""
|
|
276
|
+
|
|
277
|
+
positionChosen = QtCore.Signal(int)
|
|
278
|
+
normalizeRequested = QtCore.Signal()
|
|
279
|
+
autoContrastChanged = QtCore.Signal(bool)
|
|
280
|
+
|
|
281
|
+
def __init__(self, parent=None):
|
|
282
|
+
super().__init__(parent)
|
|
283
|
+
self.list = QtWidgets.QListWidget()
|
|
284
|
+
self.list.setSelectionMode(QtWidgets.QAbstractItemView.SingleSelection)
|
|
285
|
+
self.list.currentRowChanged.connect(self._row_changed)
|
|
286
|
+
self.follow = QtWidgets.QCheckBox("Follow the run")
|
|
287
|
+
self.follow.setToolTip(
|
|
288
|
+
"Show the position the microscope is acquiring (from status.json)"
|
|
289
|
+
)
|
|
290
|
+
self.auto_contrast = QtWidgets.QCheckBox("Auto-contrast")
|
|
291
|
+
self.auto_contrast.setChecked(True)
|
|
292
|
+
self.auto_contrast.setToolTip(
|
|
293
|
+
"Normalise each channel as frames arrive; turns off when you move a "
|
|
294
|
+
"contrast slider"
|
|
295
|
+
)
|
|
296
|
+
self.auto_contrast.toggled.connect(self.autoContrastChanged)
|
|
297
|
+
self.normalize = QtWidgets.QPushButton("Normalise now")
|
|
298
|
+
self.normalize.setToolTip("Reset the contrast limits of every channel once")
|
|
299
|
+
self.normalize.clicked.connect(self.normalizeRequested)
|
|
300
|
+
self.hint = QtWidgets.QLabel("[ / ] : previous / next position")
|
|
301
|
+
self.hint.setStyleSheet("color: gray")
|
|
302
|
+
|
|
303
|
+
layout = QtWidgets.QVBoxLayout(self)
|
|
304
|
+
layout.setContentsMargins(4, 4, 4, 4)
|
|
305
|
+
layout.addWidget(QtWidgets.QLabel("Positions"))
|
|
306
|
+
layout.addWidget(self.list, stretch=1)
|
|
307
|
+
layout.addWidget(self.follow)
|
|
308
|
+
row = QtWidgets.QHBoxLayout()
|
|
309
|
+
row.addWidget(self.auto_contrast)
|
|
310
|
+
row.addWidget(self.normalize)
|
|
311
|
+
layout.addLayout(row)
|
|
312
|
+
layout.addWidget(self.hint)
|
|
313
|
+
self._labels: list[str] = []
|
|
314
|
+
|
|
315
|
+
def set_positions(self, labels: list[str]) -> None:
|
|
316
|
+
self._labels = list(labels)
|
|
317
|
+
self.list.blockSignals(True)
|
|
318
|
+
self.list.clear()
|
|
319
|
+
self.list.addItems(self._labels)
|
|
320
|
+
self.list.blockSignals(False)
|
|
321
|
+
|
|
322
|
+
def select(self, index: int) -> None:
|
|
323
|
+
"""Reflect the viewed position without emitting positionChosen."""
|
|
324
|
+
if 0 <= index < self.list.count() and self.list.currentRow() != index:
|
|
325
|
+
self.list.blockSignals(True)
|
|
326
|
+
self.list.setCurrentRow(index)
|
|
327
|
+
self.list.blockSignals(False)
|
|
328
|
+
|
|
329
|
+
def _row_changed(self, row: int) -> None:
|
|
330
|
+
if row >= 0:
|
|
331
|
+
self.positionChosen.emit(row)
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
class ViewerDock(QtWidgets.QWidget):
|
|
335
|
+
"""The status line, the minimap and the viewer controls in one dock."""
|
|
336
|
+
|
|
337
|
+
def __init__(self, directory: Path | None, parent=None):
|
|
338
|
+
super().__init__(parent)
|
|
339
|
+
self.overview = RunOverview(directory)
|
|
340
|
+
self.controls = ViewerControls()
|
|
341
|
+
layout = QtWidgets.QVBoxLayout(self)
|
|
342
|
+
layout.setContentsMargins(0, 0, 0, 0)
|
|
343
|
+
layout.addWidget(self.overview, stretch=2)
|
|
344
|
+
layout.addWidget(self.controls, stretch=1)
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
# ================================================================== app
|
|
348
|
+
class ViewerApp:
|
|
349
|
+
def __init__(
|
|
350
|
+
self,
|
|
351
|
+
specs: list[tuple[str, str]],
|
|
352
|
+
status_path: Path | None = None,
|
|
353
|
+
experiment_dir: Path | None = None,
|
|
354
|
+
show: bool = True,
|
|
355
|
+
):
|
|
356
|
+
self.viewer = napari.Viewer(show=show)
|
|
357
|
+
self.status_path = status_path
|
|
358
|
+
if experiment_dir is None and status_path is not None:
|
|
359
|
+
experiment_dir = Path(status_path).parent
|
|
360
|
+
self.dock = ViewerDock(experiment_dir)
|
|
361
|
+
self.overview = self.dock.overview
|
|
362
|
+
self.controls = self.dock.controls
|
|
363
|
+
self.viewer.window.add_dock_widget(
|
|
364
|
+
self.dock, name="Run", area="right", tabify=False
|
|
365
|
+
)
|
|
366
|
+
|
|
367
|
+
by_path: dict[str, list[str]] = {}
|
|
368
|
+
for path, layer in specs:
|
|
369
|
+
by_path.setdefault(path, []).append(layer)
|
|
370
|
+
self.overview.refresh()
|
|
371
|
+
order = self._position_order(list(by_path))
|
|
372
|
+
self.stacks = Stacks(self.viewer)
|
|
373
|
+
self.experiments = [
|
|
374
|
+
LiveExperiment(self.stacks, path, by_path[path], index)
|
|
375
|
+
for index, path in enumerate(order)
|
|
376
|
+
]
|
|
377
|
+
self.positions = [e.name for e in self.experiments]
|
|
378
|
+
self.controls.set_positions(self.positions)
|
|
379
|
+
self.viewer.dims.axis_labels = AXIS_LABELS
|
|
380
|
+
first = next(iter(self.stacks.channels.values()), None)
|
|
381
|
+
if first is not None:
|
|
382
|
+
self.viewer.layers.selection.active = first.layer
|
|
383
|
+
self.normalize_all()
|
|
384
|
+
|
|
385
|
+
# position selection: list, minimap, keys, slider -> all in sync
|
|
386
|
+
self.controls.positionChosen.connect(self.view_position)
|
|
387
|
+
self.overview.minimap.positionClicked.connect(self.view_label)
|
|
388
|
+
self.controls.normalizeRequested.connect(self.normalize_all)
|
|
389
|
+
self.controls.autoContrastChanged.connect(self._set_auto_contrast)
|
|
390
|
+
self.viewer.dims.events.current_step.connect(self._slider_moved)
|
|
391
|
+
self.viewer.bind_key("]", self.next_position, overwrite=True)
|
|
392
|
+
self.viewer.bind_key("[", self.previous_position, overwrite=True)
|
|
393
|
+
self.controls.select(0)
|
|
394
|
+
|
|
395
|
+
self._fov_applied = False
|
|
396
|
+
self._timer = QtCore.QTimer()
|
|
397
|
+
self._timer.setInterval(1000)
|
|
398
|
+
self._timer.timeout.connect(self.refresh)
|
|
399
|
+
self._timer.start()
|
|
400
|
+
try:
|
|
401
|
+
self.viewer.window._qt_window.destroyed.connect(lambda *_: self.close())
|
|
402
|
+
except Exception:
|
|
403
|
+
pass
|
|
404
|
+
|
|
405
|
+
# ------------------------------------------------------- positions
|
|
406
|
+
def _position_order(self, paths: list[str]) -> list[str]:
|
|
407
|
+
"""Outputs in the order of the position list (minimap), the rest after."""
|
|
408
|
+
names = {}
|
|
409
|
+
for path in paths:
|
|
410
|
+
try:
|
|
411
|
+
with pyclm_io.open(path) as exp:
|
|
412
|
+
names[path] = exp.name
|
|
413
|
+
except Exception:
|
|
414
|
+
names[path] = Path(path).stem
|
|
415
|
+
listed = [p.label for p in self.overview.minimap.positions]
|
|
416
|
+
rank = {label: i for i, label in enumerate(listed)}
|
|
417
|
+
return sorted(paths, key=lambda p: (rank.get(names[p], len(rank)), names[p]))
|
|
418
|
+
|
|
419
|
+
@property
|
|
420
|
+
def current_position(self) -> int:
|
|
421
|
+
return int(self.viewer.dims.current_step[0])
|
|
422
|
+
|
|
423
|
+
def view_position(self, index: int) -> None:
|
|
424
|
+
"""Show position ``index``: the position slider, the list and the minimap follow."""
|
|
425
|
+
if not 0 <= index < len(self.positions):
|
|
426
|
+
return
|
|
427
|
+
if self.current_position != index:
|
|
428
|
+
self.viewer.dims.set_current_step(0, index)
|
|
429
|
+
self.controls.select(index)
|
|
430
|
+
|
|
431
|
+
def view_label(self, label: str) -> None:
|
|
432
|
+
if label in self.positions:
|
|
433
|
+
self.view_position(self.positions.index(label))
|
|
434
|
+
|
|
435
|
+
def next_position(self, viewer=None) -> None:
|
|
436
|
+
self.view_position((self.current_position + 1) % max(len(self.positions), 1))
|
|
437
|
+
|
|
438
|
+
def previous_position(self, viewer=None) -> None:
|
|
439
|
+
self.view_position((self.current_position - 1) % max(len(self.positions), 1))
|
|
440
|
+
|
|
441
|
+
def _slider_moved(self, event=None) -> None:
|
|
442
|
+
self.controls.select(self.current_position)
|
|
443
|
+
|
|
444
|
+
# -------------------------------------------------------- contrast
|
|
445
|
+
def _set_auto_contrast(self, on: bool) -> None:
|
|
446
|
+
for stack in self.stacks.channels.values():
|
|
447
|
+
stack.auto_contrast = on
|
|
448
|
+
if on:
|
|
449
|
+
self.normalize_all()
|
|
450
|
+
|
|
451
|
+
def normalize_all(self) -> None:
|
|
452
|
+
for stack in self.stacks.channels.values():
|
|
453
|
+
stack.reset_contrast()
|
|
454
|
+
|
|
455
|
+
# --------------------------------------------------------- refresh
|
|
456
|
+
def refresh(self) -> int:
|
|
457
|
+
status = self.overview.refresh()
|
|
458
|
+
self.show_status()
|
|
459
|
+
self._apply_fov()
|
|
460
|
+
changed: set[ChannelStack] = set()
|
|
461
|
+
for e in self.experiments:
|
|
462
|
+
changed |= e.refresh()
|
|
463
|
+
for stack in changed:
|
|
464
|
+
if stack.auto_contrast:
|
|
465
|
+
stack.reset_contrast()
|
|
466
|
+
if self.controls.auto_contrast.isChecked() and not all(
|
|
467
|
+
s.auto_contrast for s in self.stacks.channels.values()
|
|
468
|
+
):
|
|
469
|
+
# a slider was moved: reflect it in the checkbox without re-triggering
|
|
470
|
+
self.controls.auto_contrast.blockSignals(True)
|
|
471
|
+
self.controls.auto_contrast.setChecked(False)
|
|
472
|
+
self.controls.auto_contrast.blockSignals(False)
|
|
473
|
+
if self.controls.follow.isChecked() and status:
|
|
474
|
+
current = status.get("current_experiment")
|
|
475
|
+
if current in self.positions:
|
|
476
|
+
self.view_label(current)
|
|
477
|
+
return len(changed)
|
|
478
|
+
|
|
479
|
+
def _apply_fov(self):
|
|
480
|
+
"""Draw each position's field of view once the stores report a shape and pixel size."""
|
|
481
|
+
if self._fov_applied or not self.overview.minimap.positions:
|
|
482
|
+
return
|
|
483
|
+
fov = {}
|
|
484
|
+
for live in self.experiments:
|
|
485
|
+
for g in live.exp.groups.values():
|
|
486
|
+
if g.shape != (0, 0) and g.pixel_size_um:
|
|
487
|
+
fov[live.exp.name] = (
|
|
488
|
+
g.shape[0] * g.pixel_size_um,
|
|
489
|
+
g.shape[1] * g.pixel_size_um,
|
|
490
|
+
)
|
|
491
|
+
break
|
|
492
|
+
if not fov:
|
|
493
|
+
return
|
|
494
|
+
for p in self.overview.minimap.positions:
|
|
495
|
+
p.fov_um = fov.get(p.label)
|
|
496
|
+
self.overview.minimap.redraw()
|
|
497
|
+
self._fov_applied = True
|
|
498
|
+
|
|
499
|
+
def show_status(self):
|
|
500
|
+
"""The status line (from status.json, written by the Manager) in napari's status bar."""
|
|
501
|
+
try:
|
|
502
|
+
self.viewer.status = self.overview.status.text()
|
|
503
|
+
except Exception:
|
|
504
|
+
pass
|
|
505
|
+
|
|
506
|
+
def close(self):
|
|
507
|
+
self._timer.stop()
|
|
508
|
+
for e in self.experiments:
|
|
509
|
+
e.close()
|
|
510
|
+
|
|
511
|
+
def run(self):
|
|
512
|
+
napari.run()
|
|
513
|
+
|
|
514
|
+
|
|
515
|
+
def main(argv: list[str] | None = None) -> int:
|
|
516
|
+
p = argparse.ArgumentParser(description="Live napari viewer for PyCLM outputs")
|
|
517
|
+
p.add_argument("experiment", help="directory containing experiment files")
|
|
518
|
+
p.add_argument(
|
|
519
|
+
"--src",
|
|
520
|
+
action="append",
|
|
521
|
+
type=_parse_src,
|
|
522
|
+
help='Repeatable: "file.zarr:imaging/545"',
|
|
523
|
+
)
|
|
524
|
+
p.add_argument(
|
|
525
|
+
"--every_t", default=0, type=int, help="ignored; kept for compatibility"
|
|
526
|
+
)
|
|
527
|
+
p.add_argument("--config", help="ignored; kept for compatibility", default=None)
|
|
528
|
+
args = p.parse_args(argv)
|
|
529
|
+
experiment_dir = Path(args.experiment)
|
|
530
|
+
|
|
531
|
+
if args.src:
|
|
532
|
+
specs = args.src
|
|
533
|
+
else:
|
|
534
|
+
layers_file = experiment_dir / "all_layers.txt"
|
|
535
|
+
if layers_file.exists():
|
|
536
|
+
specs = _load_layers_file(layers_file)
|
|
537
|
+
else:
|
|
538
|
+
specs = []
|
|
539
|
+
for out in pyclm_io.find_experiments(experiment_dir):
|
|
540
|
+
with pyclm_io.open(out) as exp:
|
|
541
|
+
for gname, g in exp.groups.items():
|
|
542
|
+
specs += [(str(out), f"{gname}/{c}") for c in g.channels]
|
|
543
|
+
if not specs:
|
|
544
|
+
raise SystemExit(f"no experiment outputs found in {experiment_dir}")
|
|
545
|
+
|
|
546
|
+
ViewerApp(specs, experiment_dir / "status.json", experiment_dir).run()
|
|
547
|
+
return 0
|
|
548
|
+
|
|
549
|
+
|
|
550
|
+
if __name__ == "__main__":
|
|
551
|
+
sys.exit(main())
|