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
pyclm/gui/widgets.py
ADDED
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Plain Qt widgets the viewer shows as a napari dock: a status line built
|
|
3
|
+
from ``status.json`` and a minimap of the positions in stage coordinates.
|
|
4
|
+
They depend on qtpy only, so any host can show them and none can break the
|
|
5
|
+
run.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from qtpy import QtCore, QtGui, QtWidgets
|
|
15
|
+
|
|
16
|
+
# a fixed palette, one colour per experiment (stem), cycled
|
|
17
|
+
PALETTE = (
|
|
18
|
+
"#4e79a7",
|
|
19
|
+
"#f28e2b",
|
|
20
|
+
"#59a14f",
|
|
21
|
+
"#e15759",
|
|
22
|
+
"#b07aa1",
|
|
23
|
+
"#76b7b2",
|
|
24
|
+
"#edc948",
|
|
25
|
+
"#ff9da7",
|
|
26
|
+
"#9c755f",
|
|
27
|
+
"#bab0ac",
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def status_text(status: dict | None) -> str:
|
|
32
|
+
"""One line from a status.json dict."""
|
|
33
|
+
if not status:
|
|
34
|
+
return "no status yet"
|
|
35
|
+
parts = [f"t {status.get('t')}/{status.get('timepoints')}"]
|
|
36
|
+
if status.get("done"):
|
|
37
|
+
parts.append("done")
|
|
38
|
+
elif status.get("paused"):
|
|
39
|
+
parts.append("paused")
|
|
40
|
+
elif status.get("stopping"):
|
|
41
|
+
parts.append("stopping")
|
|
42
|
+
current = status.get("current_experiment")
|
|
43
|
+
if current:
|
|
44
|
+
parts.append(f"at {current}")
|
|
45
|
+
late = [
|
|
46
|
+
f"{name} late {info['lateness_s']:.1f}s"
|
|
47
|
+
for name, info in status.get("experiments", {}).items()
|
|
48
|
+
if info.get("lateness_s")
|
|
49
|
+
]
|
|
50
|
+
parts += late
|
|
51
|
+
errors = sum(
|
|
52
|
+
info.get("errors", 0) for info in status.get("experiments", {}).values()
|
|
53
|
+
)
|
|
54
|
+
if errors:
|
|
55
|
+
parts.append(f"{errors} acquisition error{'s' if errors != 1 else ''}")
|
|
56
|
+
if status.get("skipped"):
|
|
57
|
+
parts.append(f"{status['skipped']} skipped")
|
|
58
|
+
if status.get("settings_applied"):
|
|
59
|
+
parts.append(f"{status['settings_applied']} settings changed")
|
|
60
|
+
pending = status.get("pending_commands")
|
|
61
|
+
if pending:
|
|
62
|
+
parts.append(f"{pending} command{'s' if pending != 1 else ''} pending")
|
|
63
|
+
return " | ".join(parts)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def read_status(path: Path | None) -> dict | None:
|
|
67
|
+
if path is None or not Path(path).exists():
|
|
68
|
+
return None
|
|
69
|
+
try:
|
|
70
|
+
return json.loads(Path(path).read_text())
|
|
71
|
+
except Exception:
|
|
72
|
+
return None
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class StatusLine(QtWidgets.QLabel):
|
|
76
|
+
"""A label showing :func:`status_text`; call :meth:`update_from` every tick."""
|
|
77
|
+
|
|
78
|
+
def __init__(self, parent=None):
|
|
79
|
+
super().__init__("no status yet", parent)
|
|
80
|
+
self.setTextInteractionFlags(QtCore.Qt.TextSelectableByMouse)
|
|
81
|
+
self.setWordWrap(True)
|
|
82
|
+
|
|
83
|
+
def update_from(self, status: dict | None) -> str:
|
|
84
|
+
text = status_text(status)
|
|
85
|
+
self.setText(text)
|
|
86
|
+
return text
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
@dataclass
|
|
90
|
+
class MapPosition:
|
|
91
|
+
label: str
|
|
92
|
+
experiment: str
|
|
93
|
+
x: float
|
|
94
|
+
y: float
|
|
95
|
+
fov_um: tuple[float, float] | None = None # (height, width) of the field, if known
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def positions_from_plan(plan_path: Path) -> list[MapPosition]:
|
|
99
|
+
"""Positions of a run from its ``plan.useq.yaml``."""
|
|
100
|
+
import useq
|
|
101
|
+
|
|
102
|
+
seq = useq.MDASequence.from_file(str(plan_path))
|
|
103
|
+
out = []
|
|
104
|
+
for pos in seq.stage_positions:
|
|
105
|
+
name = pos.name or ""
|
|
106
|
+
out.append(
|
|
107
|
+
MapPosition(
|
|
108
|
+
name, name.split(".")[0], float(pos.x or 0.0), float(pos.y or 0.0)
|
|
109
|
+
)
|
|
110
|
+
)
|
|
111
|
+
return out
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def positions_from_directory(directory: Path) -> list[MapPosition]:
|
|
115
|
+
"""Positions from ``plan.useq.yaml`` if a run has been started, else from the position list."""
|
|
116
|
+
directory = Path(directory)
|
|
117
|
+
plan = directory / "plan.useq.yaml"
|
|
118
|
+
if plan.exists():
|
|
119
|
+
try:
|
|
120
|
+
return positions_from_plan(plan)
|
|
121
|
+
except Exception:
|
|
122
|
+
pass
|
|
123
|
+
from ..directories import positions_from_pos, positions_from_xml
|
|
124
|
+
|
|
125
|
+
pos_path = directory / "PositionList.pos"
|
|
126
|
+
xml_path = directory / "multipoints.xml"
|
|
127
|
+
if pos_path.exists():
|
|
128
|
+
found = positions_from_pos(str(pos_path))
|
|
129
|
+
elif xml_path.exists():
|
|
130
|
+
found = positions_from_xml(str(xml_path))
|
|
131
|
+
else:
|
|
132
|
+
return []
|
|
133
|
+
return [
|
|
134
|
+
MapPosition(p.label, str(p.label).split(".")[0], float(p.x), float(p.y))
|
|
135
|
+
for p in found
|
|
136
|
+
]
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
class Minimap(QtWidgets.QGraphicsView):
|
|
140
|
+
"""
|
|
141
|
+
The positions of a run drawn in stage coordinates (µm), coloured by
|
|
142
|
+
experiment, with the field of view drawn when its size is known and the
|
|
143
|
+
position the microscope is at highlighted. Read-only.
|
|
144
|
+
"""
|
|
145
|
+
|
|
146
|
+
positionClicked = QtCore.Signal(str)
|
|
147
|
+
|
|
148
|
+
def __init__(self, parent=None):
|
|
149
|
+
super().__init__(parent)
|
|
150
|
+
self._scene = QtWidgets.QGraphicsScene(self)
|
|
151
|
+
self.setScene(self._scene)
|
|
152
|
+
self.setRenderHints(
|
|
153
|
+
QtGui.QPainter.Antialiasing | QtGui.QPainter.TextAntialiasing
|
|
154
|
+
)
|
|
155
|
+
self.setMinimumSize(160, 160)
|
|
156
|
+
self.positions: list[MapPosition] = []
|
|
157
|
+
self.current: str | None = None
|
|
158
|
+
self.problems: set[str] = set()
|
|
159
|
+
self._colours: dict[str, str] = {}
|
|
160
|
+
self._items: dict[str, QtWidgets.QGraphicsItem] = {}
|
|
161
|
+
|
|
162
|
+
# ------------------------------------------------------------ data
|
|
163
|
+
def colour_of(self, experiment: str) -> str:
|
|
164
|
+
if experiment not in self._colours:
|
|
165
|
+
self._colours[experiment] = PALETTE[len(self._colours) % len(PALETTE)]
|
|
166
|
+
return self._colours[experiment]
|
|
167
|
+
|
|
168
|
+
def set_positions(self, positions: list[MapPosition]):
|
|
169
|
+
self.positions = list(positions)
|
|
170
|
+
self.redraw()
|
|
171
|
+
|
|
172
|
+
def set_current(self, label: str | None):
|
|
173
|
+
if label != self.current:
|
|
174
|
+
self.current = label
|
|
175
|
+
self.redraw()
|
|
176
|
+
|
|
177
|
+
def set_status(self, status: dict | None):
|
|
178
|
+
"""Highlight the current position and mark experiments with acquisition errors."""
|
|
179
|
+
problems = set()
|
|
180
|
+
if status:
|
|
181
|
+
for name, info in status.get("experiments", {}).items():
|
|
182
|
+
if info.get("errors"):
|
|
183
|
+
problems.add(name)
|
|
184
|
+
current = status.get("current_experiment") if status else None
|
|
185
|
+
if problems != self.problems or current != self.current:
|
|
186
|
+
self.problems = problems
|
|
187
|
+
self.current = current
|
|
188
|
+
self.redraw()
|
|
189
|
+
|
|
190
|
+
# --------------------------------------------------------- drawing
|
|
191
|
+
def redraw(self):
|
|
192
|
+
scene = self._scene
|
|
193
|
+
scene.clear()
|
|
194
|
+
self._items = {}
|
|
195
|
+
if not self.positions:
|
|
196
|
+
scene.addText("no positions")
|
|
197
|
+
return
|
|
198
|
+
xs = [p.x for p in self.positions]
|
|
199
|
+
ys = [p.y for p in self.positions]
|
|
200
|
+
span = max(max(xs) - min(xs), max(ys) - min(ys), 1.0)
|
|
201
|
+
marker = span / 40.0 + 1.0
|
|
202
|
+
for p in self.positions:
|
|
203
|
+
colour = QtGui.QColor(self.colour_of(p.experiment))
|
|
204
|
+
pen = QtGui.QPen(colour)
|
|
205
|
+
pen.setCosmetic(True)
|
|
206
|
+
pen.setWidth(3 if p.label == self.current else 1)
|
|
207
|
+
if p.label in self.problems:
|
|
208
|
+
pen.setColor(QtGui.QColor("#d62728"))
|
|
209
|
+
brush = QtGui.QBrush(
|
|
210
|
+
colour if p.label == self.current else QtCore.Qt.NoBrush
|
|
211
|
+
)
|
|
212
|
+
if p.fov_um:
|
|
213
|
+
h, w = p.fov_um
|
|
214
|
+
item = scene.addRect(p.x - w / 2, p.y - h / 2, w, h, pen, brush)
|
|
215
|
+
else:
|
|
216
|
+
item = scene.addEllipse(
|
|
217
|
+
p.x - marker, p.y - marker, 2 * marker, 2 * marker, pen, brush
|
|
218
|
+
)
|
|
219
|
+
item.setToolTip(f"{p.label} x={p.x:.0f} µm y={p.y:.0f} µm")
|
|
220
|
+
item.setData(0, p.label)
|
|
221
|
+
self._items[p.label] = item
|
|
222
|
+
text = scene.addSimpleText(p.label)
|
|
223
|
+
text.setBrush(QtGui.QBrush(colour))
|
|
224
|
+
text.setFlag(QtWidgets.QGraphicsItem.ItemIgnoresTransformations)
|
|
225
|
+
text.setPos(p.x + marker, p.y + marker)
|
|
226
|
+
# a scale bar: 1 mm or 100 µm depending on the span
|
|
227
|
+
bar = 1000.0 if span > 3000 else 100.0
|
|
228
|
+
x0, y0 = min(xs), max(ys) + span * 0.08
|
|
229
|
+
pen = QtGui.QPen(QtGui.QColor("#666666"))
|
|
230
|
+
pen.setCosmetic(True)
|
|
231
|
+
scene.addLine(x0, y0, x0 + bar, y0, pen)
|
|
232
|
+
label = scene.addSimpleText(f"{bar:g} µm")
|
|
233
|
+
label.setFlag(QtWidgets.QGraphicsItem.ItemIgnoresTransformations)
|
|
234
|
+
label.setPos(x0, y0)
|
|
235
|
+
self.fit()
|
|
236
|
+
|
|
237
|
+
def fit(self):
|
|
238
|
+
rect = self._scene.itemsBoundingRect()
|
|
239
|
+
if rect.isValid():
|
|
240
|
+
self.fitInView(
|
|
241
|
+
rect.adjusted(
|
|
242
|
+
-rect.width() * 0.1,
|
|
243
|
+
-rect.height() * 0.1,
|
|
244
|
+
rect.width() * 0.1,
|
|
245
|
+
rect.height() * 0.1,
|
|
246
|
+
),
|
|
247
|
+
QtCore.Qt.KeepAspectRatio,
|
|
248
|
+
)
|
|
249
|
+
|
|
250
|
+
def resizeEvent(self, event):
|
|
251
|
+
super().resizeEvent(event)
|
|
252
|
+
self.fit()
|
|
253
|
+
|
|
254
|
+
def mousePressEvent(self, event):
|
|
255
|
+
item = self.itemAt(event.pos())
|
|
256
|
+
label = item.data(0) if item is not None else None
|
|
257
|
+
if label:
|
|
258
|
+
self.positionClicked.emit(str(label))
|
|
259
|
+
super().mousePressEvent(event)
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
class RunOverview(QtWidgets.QWidget):
|
|
263
|
+
"""The status line above the minimap, refreshed from the experiment directory."""
|
|
264
|
+
|
|
265
|
+
def __init__(self, directory: Path | None = None, parent=None):
|
|
266
|
+
super().__init__(parent)
|
|
267
|
+
self.directory = None if directory is None else Path(directory)
|
|
268
|
+
self.status = StatusLine()
|
|
269
|
+
self.minimap = Minimap()
|
|
270
|
+
layout = QtWidgets.QVBoxLayout(self)
|
|
271
|
+
layout.setContentsMargins(4, 4, 4, 4)
|
|
272
|
+
layout.addWidget(self.status)
|
|
273
|
+
layout.addWidget(self.minimap, stretch=1)
|
|
274
|
+
self._positions_loaded = False
|
|
275
|
+
|
|
276
|
+
def set_directory(self, directory: Path):
|
|
277
|
+
self.directory = Path(directory)
|
|
278
|
+
self._positions_loaded = False
|
|
279
|
+
self.refresh()
|
|
280
|
+
|
|
281
|
+
def refresh(self) -> dict | None:
|
|
282
|
+
if self.directory is None:
|
|
283
|
+
return None
|
|
284
|
+
if not self._positions_loaded:
|
|
285
|
+
positions = positions_from_directory(self.directory)
|
|
286
|
+
if positions:
|
|
287
|
+
self.minimap.set_positions(positions)
|
|
288
|
+
self._positions_loaded = True
|
|
289
|
+
status = read_status(self.directory / "status.json")
|
|
290
|
+
self.status.update_from(status)
|
|
291
|
+
self.minimap.set_status(status)
|
|
292
|
+
return status
|
pyclm/io/__init__.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Read and export PyCLM data without the acquisition pipeline.
|
|
3
|
+
|
|
4
|
+
import pyclm.io
|
|
5
|
+
exp = pyclm.io.open("experiment_dir/bar10.pos1.zarr") # or .hdf5
|
|
6
|
+
pyclm.io.export_imagej(exp) # ImageJ hyperstacks next to the data
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from .export import export_group, export_imagej, pattern_to_camera
|
|
10
|
+
from .readers import (
|
|
11
|
+
ExperimentData,
|
|
12
|
+
GroupData,
|
|
13
|
+
HDF5Experiment,
|
|
14
|
+
ZarrExperiment,
|
|
15
|
+
find_experiments,
|
|
16
|
+
open,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
__all__ = [
|
|
20
|
+
"ExperimentData",
|
|
21
|
+
"GroupData",
|
|
22
|
+
"HDF5Experiment",
|
|
23
|
+
"ZarrExperiment",
|
|
24
|
+
"export_group",
|
|
25
|
+
"export_imagej",
|
|
26
|
+
"find_experiments",
|
|
27
|
+
"open",
|
|
28
|
+
"pattern_to_camera",
|
|
29
|
+
]
|
pyclm/io/export.py
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Export PyCLM experiments to ImageJ hyperstacks: one TIFF per cadence group,
|
|
3
|
+
channels = raw channels, then segmentation labels (if any), then tracked
|
|
4
|
+
labels (if any), then the DMD pattern warped into camera space (if the
|
|
5
|
+
affine transform is known).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import logging
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
import cv2
|
|
14
|
+
import numpy as np
|
|
15
|
+
import tifffile
|
|
16
|
+
from skimage.transform import downscale_local_mean
|
|
17
|
+
|
|
18
|
+
from .readers import ExperimentData, GroupData
|
|
19
|
+
|
|
20
|
+
logger = logging.getLogger(__name__)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _lut(r, g, b):
|
|
24
|
+
ramp = np.arange(256, dtype=np.uint8)
|
|
25
|
+
zero = np.zeros(256, dtype=np.uint8)
|
|
26
|
+
return np.stack([ramp if r else zero, ramp if g else zero, ramp if b else zero])
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
GRAY, YELLOW, CYAN, MAGENTA = _lut(1, 1, 1), _lut(1, 1, 0), _lut(0, 1, 1), _lut(1, 0, 1)
|
|
30
|
+
GREEN, RED, BLUE = _lut(0, 1, 0), _lut(1, 0, 0), _lut(0, 0, 1)
|
|
31
|
+
# one LUT per segmentation table, in the store's order (the default first)
|
|
32
|
+
LABEL_LUTS = (YELLOW, GREEN, RED, BLUE)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def pattern_to_camera(
|
|
36
|
+
pattern: np.ndarray,
|
|
37
|
+
affine: np.ndarray,
|
|
38
|
+
shape: tuple[int, int],
|
|
39
|
+
binning: int,
|
|
40
|
+
roi_offset=(0, 0),
|
|
41
|
+
) -> np.ndarray:
|
|
42
|
+
"""
|
|
43
|
+
Warp a DMD-space pattern back into a (binned) camera frame, values 0-255.
|
|
44
|
+
``roi_offset`` is the camera ROI origin in unbinned pixels (the affine is
|
|
45
|
+
calibrated in the full frame).
|
|
46
|
+
"""
|
|
47
|
+
from pyclm.core.manager import compose_affine
|
|
48
|
+
|
|
49
|
+
h, w = shape
|
|
50
|
+
ati = cv2.invertAffineTransform(compose_affine(affine, roi_offset, 1))
|
|
51
|
+
full = cv2.warpAffine(
|
|
52
|
+
np.round(pattern).astype(np.uint8), ati, (w * binning, h * binning)
|
|
53
|
+
)
|
|
54
|
+
if binning > 1:
|
|
55
|
+
full = downscale_local_mean(full.astype(np.float32), (binning, binning))
|
|
56
|
+
return np.clip(full, 0, 255).astype(np.uint16)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _roi_offset(exp) -> tuple[int, int]:
|
|
60
|
+
roi = getattr(exp, "camera_roi", None)
|
|
61
|
+
return (0, 0) if roi is None else (int(roi[0]), int(roi[1]))
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def pattern_overlay(exp, group, shape: tuple[int, int], t: int) -> np.ndarray | None:
|
|
65
|
+
"""
|
|
66
|
+
The pattern in force at plan timepoint ``t`` as a frame of ``shape``
|
|
67
|
+
(values 0-255): the stored camera-space pattern when the store has one
|
|
68
|
+
(resized if the stimulation binning differs from the group's), else the
|
|
69
|
+
DMD pattern warped back through the affine.
|
|
70
|
+
"""
|
|
71
|
+
cam = exp.camera_pattern_at(t)
|
|
72
|
+
if cam is not None:
|
|
73
|
+
cam = np.asarray(cam)
|
|
74
|
+
if tuple(cam.shape) != tuple(shape):
|
|
75
|
+
cam = cv2.resize(cam, (shape[1], shape[0]), interpolation=cv2.INTER_NEAREST)
|
|
76
|
+
return cam.astype(np.uint16)
|
|
77
|
+
if exp.affine_transform is None:
|
|
78
|
+
return None
|
|
79
|
+
pat = exp.pattern_at(t)
|
|
80
|
+
if pat is None:
|
|
81
|
+
return None
|
|
82
|
+
return pattern_to_camera(
|
|
83
|
+
pat, exp.affine_transform, shape, group.binning, _roi_offset(exp)
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def export_group(
|
|
88
|
+
exp: ExperimentData,
|
|
89
|
+
group: GroupData,
|
|
90
|
+
out_path: Path,
|
|
91
|
+
affine: np.ndarray | None = None,
|
|
92
|
+
overlay_pattern: bool = True,
|
|
93
|
+
include_labels: bool = True,
|
|
94
|
+
) -> Path | None:
|
|
95
|
+
affine = exp.affine_transform if affine is None else affine
|
|
96
|
+
indices = group.acquired()
|
|
97
|
+
if not indices:
|
|
98
|
+
logger.warning(f"{exp.name}/{group.name}: nothing acquired, no export")
|
|
99
|
+
return None
|
|
100
|
+
|
|
101
|
+
shape = group.shape
|
|
102
|
+
label_names = list(group.label_names) if include_labels else []
|
|
103
|
+
use_tracks = include_labels and group.has_tracks
|
|
104
|
+
use_pattern = (
|
|
105
|
+
overlay_pattern
|
|
106
|
+
and affine is not None
|
|
107
|
+
and exp.pattern_at(group.global_t(indices[0])) is not None
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
frames = []
|
|
111
|
+
for i in indices:
|
|
112
|
+
planes = []
|
|
113
|
+
for c in group.channels:
|
|
114
|
+
fr = group.frame(i, c)
|
|
115
|
+
planes.append(
|
|
116
|
+
np.zeros(shape, np.uint16) if fr is None else fr.astype(np.uint16)
|
|
117
|
+
)
|
|
118
|
+
for name in label_names:
|
|
119
|
+
for c in group.channels:
|
|
120
|
+
lb = group.labels(i, c, name)
|
|
121
|
+
planes.append(
|
|
122
|
+
np.zeros(shape, np.uint16) if lb is None else lb.astype(np.uint16)
|
|
123
|
+
)
|
|
124
|
+
if use_tracks:
|
|
125
|
+
for c in group.channels:
|
|
126
|
+
tr = group.tracks(i, c)
|
|
127
|
+
if tr is None:
|
|
128
|
+
planes.append(np.zeros(shape, np.uint16))
|
|
129
|
+
else:
|
|
130
|
+
if tr.max() > np.iinfo(np.uint16).max:
|
|
131
|
+
logger.warning(
|
|
132
|
+
f"{exp.name}/{group.name}: track ids exceed 65535 and are "
|
|
133
|
+
"clipped in the ImageJ export; read the zarr store for exact ids"
|
|
134
|
+
)
|
|
135
|
+
planes.append(
|
|
136
|
+
np.clip(tr, 0, np.iinfo(np.uint16).max).astype(np.uint16)
|
|
137
|
+
)
|
|
138
|
+
if use_pattern:
|
|
139
|
+
pat = exp.pattern_at(group.global_t(i))
|
|
140
|
+
planes.append(
|
|
141
|
+
np.zeros(shape, np.uint16)
|
|
142
|
+
if pat is None
|
|
143
|
+
else pattern_to_camera(
|
|
144
|
+
pat, affine, shape, group.binning, _roi_offset(exp)
|
|
145
|
+
)
|
|
146
|
+
)
|
|
147
|
+
frames.append(np.stack(planes))
|
|
148
|
+
|
|
149
|
+
stack = np.stack(frames) # (T, C, Y, X)
|
|
150
|
+
luts = [GRAY] * len(group.channels)
|
|
151
|
+
ranges = [0, 5000] * len(group.channels)
|
|
152
|
+
for k, _name in enumerate(label_names):
|
|
153
|
+
luts += [LABEL_LUTS[k % len(LABEL_LUTS)]] * len(group.channels)
|
|
154
|
+
ranges += [0, 1] * len(group.channels)
|
|
155
|
+
if use_tracks:
|
|
156
|
+
luts += [MAGENTA] * len(group.channels)
|
|
157
|
+
ranges += [0, 1] * len(group.channels)
|
|
158
|
+
if use_pattern:
|
|
159
|
+
luts.append(CYAN)
|
|
160
|
+
ranges += [0, 1000]
|
|
161
|
+
|
|
162
|
+
metadata = {
|
|
163
|
+
"axes": "TCYX",
|
|
164
|
+
"mode": "composite",
|
|
165
|
+
"LUTs": luts,
|
|
166
|
+
"Ranges": ranges,
|
|
167
|
+
}
|
|
168
|
+
kwargs = {}
|
|
169
|
+
if group.interval_s:
|
|
170
|
+
metadata["finterval"] = float(
|
|
171
|
+
group.every_t * group.interval_s
|
|
172
|
+
) # seconds per frame
|
|
173
|
+
if group.pixel_size_um:
|
|
174
|
+
metadata["unit"] = "um"
|
|
175
|
+
kwargs["resolution"] = (1.0 / group.pixel_size_um, 1.0 / group.pixel_size_um)
|
|
176
|
+
|
|
177
|
+
out_path = Path(out_path)
|
|
178
|
+
tifffile.imwrite(out_path, stack, imagej=True, metadata=metadata, **kwargs)
|
|
179
|
+
logger.info(f"exported {exp.name}/{group.name} -> {out_path} {stack.shape}")
|
|
180
|
+
return out_path
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def export_imagej(
|
|
184
|
+
exp: ExperimentData,
|
|
185
|
+
out_dir: Path | None = None,
|
|
186
|
+
groups: list[str] | None = None,
|
|
187
|
+
affine: np.ndarray | None = None,
|
|
188
|
+
overlay_pattern: bool = True,
|
|
189
|
+
include_labels: bool = True,
|
|
190
|
+
) -> list[Path]:
|
|
191
|
+
"""Write one ImageJ hyperstack per cadence group; returns the paths written."""
|
|
192
|
+
out_dir = Path(out_dir) if out_dir is not None else exp.path.parent
|
|
193
|
+
out_dir.mkdir(parents=True, exist_ok=True)
|
|
194
|
+
written = []
|
|
195
|
+
for name, group in exp.groups.items():
|
|
196
|
+
if groups is not None and name not in groups:
|
|
197
|
+
continue
|
|
198
|
+
path = out_dir / f"{exp.name}_{name}.tif"
|
|
199
|
+
result = export_group(exp, group, path, affine, overlay_pattern, include_labels)
|
|
200
|
+
if result is not None:
|
|
201
|
+
written.append(result)
|
|
202
|
+
return written
|