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/core/router.py
ADDED
|
@@ -0,0 +1,422 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Routing of frame-derived data between pipeline processes.
|
|
3
|
+
|
|
4
|
+
Every piece of data the pipeline moves (a raw frame, a segmentation, a
|
|
5
|
+
track table) has a *kind* (:data:`KINDS`) and an identity from the plan
|
|
6
|
+
(``data.event.index``: experiment ``p``, channel ``c``, timepoint ``t``).
|
|
7
|
+
The :class:`Router` holds a table ``(experiment, channel, kind) →
|
|
8
|
+
[consumer, ...]`` built once by :meth:`Router.resolve` from what the
|
|
9
|
+
registered processes want (``subscriptions(plan)``) and can make
|
|
10
|
+
(``produces``), and fans data out with :meth:`Router.publish`. It also
|
|
11
|
+
derives the shutdown fan-in: a consumer receives one
|
|
12
|
+
:class:`~pyclm.core.messages.StreamCloseMessage` on its data inbox when
|
|
13
|
+
every producer feeding it has ended its stream (:meth:`Router.end_stream`).
|
|
14
|
+
|
|
15
|
+
The router is not a thread. ``publish`` runs on the producer's thread and
|
|
16
|
+
costs one ``queue.put`` per delivery; queues pass references, so consumers
|
|
17
|
+
share the object and must not mutate it.
|
|
18
|
+
|
|
19
|
+
A registered process needs ``name`` and ``attach(router, inbox)``, and may
|
|
20
|
+
have ``produces`` (``{kind: (input kinds, ...)}``), ``subscriptions(plan)``,
|
|
21
|
+
``can_produce(kind, experiment, channel)``, ``continuous`` (a producer that
|
|
22
|
+
needs every frame of its inputs once it runs at all, like tracking) and
|
|
23
|
+
``always_active``; see :class:`~pyclm.core.base_process.PipelineProcess`.
|
|
24
|
+
|
|
25
|
+
See docs/stage3-router-design.md.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
from __future__ import annotations
|
|
29
|
+
|
|
30
|
+
import logging
|
|
31
|
+
import threading
|
|
32
|
+
from collections import defaultdict
|
|
33
|
+
from dataclasses import dataclass
|
|
34
|
+
from queue import Queue
|
|
35
|
+
from typing import TYPE_CHECKING, Any
|
|
36
|
+
|
|
37
|
+
from .kinds import base_kind
|
|
38
|
+
from .messages import StreamCloseMessage
|
|
39
|
+
|
|
40
|
+
if TYPE_CHECKING:
|
|
41
|
+
from .plan import AcquisitionPlan
|
|
42
|
+
|
|
43
|
+
logger = logging.getLogger(__name__)
|
|
44
|
+
|
|
45
|
+
# base kinds; a segmentation from a named [segmentation.<name>] table travels
|
|
46
|
+
# as "seg:<name>" and is produced by the "seg" producer (see core/kinds.py)
|
|
47
|
+
# "skipped": a planned frame the microscope did not take (the writer records it)
|
|
48
|
+
KINDS = ("raw", "seg", "tracks", "skipped")
|
|
49
|
+
CADENCES = ("always", "pattern")
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class RoutingError(ValueError):
|
|
53
|
+
"""The registered processes cannot satisfy what the plan and methods ask for."""
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@dataclass(frozen=True)
|
|
57
|
+
class Subscription:
|
|
58
|
+
"""
|
|
59
|
+
One process's interest in one kind of data for one experiment channel.
|
|
60
|
+
|
|
61
|
+
``cadence`` is ``"always"`` (every acquired frame) or ``"pattern"`` (only
|
|
62
|
+
at timepoints where the experiment's pattern is due, i.e.
|
|
63
|
+
``plan.pattern_due``). ``demand=False`` marks a subscription that records
|
|
64
|
+
what is produced anyway without causing a stage to run (the writer's).
|
|
65
|
+
"""
|
|
66
|
+
|
|
67
|
+
consumer: str
|
|
68
|
+
experiment: str
|
|
69
|
+
channel: str
|
|
70
|
+
kind: str
|
|
71
|
+
cadence: str = "always"
|
|
72
|
+
demand: bool = True
|
|
73
|
+
|
|
74
|
+
@property
|
|
75
|
+
def key(self) -> tuple[str, str, str]:
|
|
76
|
+
return (self.experiment, self.channel, self.kind)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
@dataclass
|
|
80
|
+
class _Delivery:
|
|
81
|
+
consumer: str
|
|
82
|
+
cadence: str
|
|
83
|
+
demand: bool
|
|
84
|
+
|
|
85
|
+
def merge(self, cadence: str, demand: bool) -> bool:
|
|
86
|
+
"""Widen this delivery. Returns True if the cadence changed."""
|
|
87
|
+
changed = cadence == "always" and self.cadence != "always"
|
|
88
|
+
if changed:
|
|
89
|
+
self.cadence = "always"
|
|
90
|
+
self.demand = self.demand or demand
|
|
91
|
+
return changed
|
|
92
|
+
|
|
93
|
+
def label(self) -> str:
|
|
94
|
+
out = self.consumer
|
|
95
|
+
if self.cadence != "always":
|
|
96
|
+
out += f"@{self.cadence}"
|
|
97
|
+
if not self.demand:
|
|
98
|
+
out += "(record)"
|
|
99
|
+
return out
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _subscriptions_of(proc: Any, plan: AcquisitionPlan) -> list[Subscription]:
|
|
103
|
+
fn = getattr(proc, "subscriptions", None)
|
|
104
|
+
return list(fn(plan)) if fn is not None else []
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class Router:
|
|
108
|
+
"""See the module docstring. Build with :meth:`add` then :meth:`resolve`."""
|
|
109
|
+
|
|
110
|
+
def __init__(self, plan: AcquisitionPlan):
|
|
111
|
+
self.plan = plan
|
|
112
|
+
self._procs: dict[str, Any] = {}
|
|
113
|
+
self._producers: dict[str, str] = {}
|
|
114
|
+
self._table: dict[tuple[str, str, str], list[_Delivery]] = {}
|
|
115
|
+
self._inboxes: dict[str, Queue] = {}
|
|
116
|
+
self._upstreams: dict[str, set[str]] = {}
|
|
117
|
+
self._ended: dict[str, set[str]] = {}
|
|
118
|
+
self._active: list[str] = []
|
|
119
|
+
self._lock = threading.Lock()
|
|
120
|
+
self._warned: set[tuple] = set()
|
|
121
|
+
self.resolved = False
|
|
122
|
+
# frames published for a key nobody subscribes to (a health counter)
|
|
123
|
+
self.undeliverable = 0
|
|
124
|
+
|
|
125
|
+
# ------------------------------------------------------------ building
|
|
126
|
+
def add(self, proc: Any) -> None:
|
|
127
|
+
"""Register a process (before :meth:`resolve`)."""
|
|
128
|
+
if self.resolved:
|
|
129
|
+
raise RoutingError("cannot add a process after the router is resolved")
|
|
130
|
+
name = proc.name
|
|
131
|
+
if name in self._procs:
|
|
132
|
+
raise RoutingError(f"a process named {name!r} is already registered")
|
|
133
|
+
self._procs[name] = proc
|
|
134
|
+
for kind in getattr(proc, "produces", {}):
|
|
135
|
+
if kind not in KINDS:
|
|
136
|
+
raise RoutingError(f"{name!r} produces unknown kind {kind!r}")
|
|
137
|
+
other = self._producers.get(kind)
|
|
138
|
+
if other is not None:
|
|
139
|
+
raise RoutingError(f"{name!r} and {other!r} both produce {kind!r}")
|
|
140
|
+
self._producers[kind] = name
|
|
141
|
+
|
|
142
|
+
def resolve(self) -> Router:
|
|
143
|
+
"""
|
|
144
|
+
Build the table, derive producer-side subscriptions, validate, attach
|
|
145
|
+
inboxes. Rules (docs/stage3-router-design.md §3.4):
|
|
146
|
+
|
|
147
|
+
1. every ``demand`` subscription pulls in the producer of its kind,
|
|
148
|
+
subscribing that producer to its input kinds at the widest cadence
|
|
149
|
+
any downstream consumer asks for (``"always"`` if the producer is
|
|
150
|
+
``continuous``);
|
|
151
|
+
2. ``demand=False`` subscriptions are honoured only for data that is
|
|
152
|
+
produced anyway;
|
|
153
|
+
3. a demanded kind with no producer, or one whose producer cannot
|
|
154
|
+
serve that experiment, is a :class:`RoutingError`;
|
|
155
|
+
4. a consumer's stream ends after the raw producer's and after each
|
|
156
|
+
producer feeding it; processes receiving nothing are inactive
|
|
157
|
+
unless ``always_active``.
|
|
158
|
+
"""
|
|
159
|
+
if self.resolved:
|
|
160
|
+
raise RoutingError("router already resolved")
|
|
161
|
+
if "raw" not in self._producers:
|
|
162
|
+
raise RoutingError("no registered process produces raw frames")
|
|
163
|
+
|
|
164
|
+
explicit: list[Subscription] = []
|
|
165
|
+
for proc in self._procs.values():
|
|
166
|
+
for sub in _subscriptions_of(proc, self.plan):
|
|
167
|
+
self._check(sub)
|
|
168
|
+
explicit.append(sub)
|
|
169
|
+
|
|
170
|
+
table: dict[tuple, dict[str, _Delivery]] = defaultdict(dict)
|
|
171
|
+
|
|
172
|
+
pending = [s for s in explicit if s.demand]
|
|
173
|
+
for sub in pending:
|
|
174
|
+
self._put(table, sub)
|
|
175
|
+
while pending:
|
|
176
|
+
sub = pending.pop()
|
|
177
|
+
if sub.kind == "raw":
|
|
178
|
+
continue
|
|
179
|
+
producer = self._producer_for(sub)
|
|
180
|
+
proc = self._procs[producer]
|
|
181
|
+
cadence = "always" if getattr(proc, "continuous", False) else sub.cadence
|
|
182
|
+
for kind_in in self._inputs(proc, sub):
|
|
183
|
+
derived = Subscription(
|
|
184
|
+
producer, sub.experiment, sub.channel, kind_in, cadence, True
|
|
185
|
+
)
|
|
186
|
+
if self._put(table, derived):
|
|
187
|
+
pending.append(derived)
|
|
188
|
+
|
|
189
|
+
for sub in explicit:
|
|
190
|
+
if sub.demand:
|
|
191
|
+
continue
|
|
192
|
+
if sub.kind != "raw" and not self._is_produced(table, sub):
|
|
193
|
+
continue
|
|
194
|
+
self._put(table, sub)
|
|
195
|
+
|
|
196
|
+
self._table = {key: list(d.values()) for key, d in table.items()}
|
|
197
|
+
|
|
198
|
+
root = self._producers["raw"]
|
|
199
|
+
upstreams: dict[str, set[str]] = defaultdict(set)
|
|
200
|
+
for (_exp, _ch, kind), deliveries in self._table.items():
|
|
201
|
+
for d in deliveries:
|
|
202
|
+
upstreams[d.consumer].add(self._producers[base_kind(kind)])
|
|
203
|
+
|
|
204
|
+
for name, proc in self._procs.items():
|
|
205
|
+
active = name in upstreams or getattr(proc, "always_active", False)
|
|
206
|
+
if not active:
|
|
207
|
+
continue
|
|
208
|
+
self._active.append(name)
|
|
209
|
+
if name == root:
|
|
210
|
+
self._upstreams[name] = set()
|
|
211
|
+
else:
|
|
212
|
+
self._upstreams[name] = set(upstreams.get(name, ())) | {root}
|
|
213
|
+
self._ended[name] = set()
|
|
214
|
+
inbox: Queue = Queue()
|
|
215
|
+
self._inboxes[name] = inbox
|
|
216
|
+
proc.attach(self, inbox)
|
|
217
|
+
|
|
218
|
+
self.resolved = True
|
|
219
|
+
logger.info(f"routing resolved: {self.as_dict()}")
|
|
220
|
+
return self
|
|
221
|
+
|
|
222
|
+
@staticmethod
|
|
223
|
+
def _put(table, sub: Subscription) -> bool:
|
|
224
|
+
"""Add or widen a delivery. Returns True if the producer must be (re)visited."""
|
|
225
|
+
delivery = table[sub.key].get(sub.consumer)
|
|
226
|
+
if delivery is None:
|
|
227
|
+
table[sub.key][sub.consumer] = _Delivery(
|
|
228
|
+
sub.consumer, sub.cadence, sub.demand
|
|
229
|
+
)
|
|
230
|
+
return True
|
|
231
|
+
return delivery.merge(sub.cadence, sub.demand)
|
|
232
|
+
|
|
233
|
+
def _inputs(self, proc: Any, sub: Subscription) -> tuple[str, ...]:
|
|
234
|
+
"""The kinds ``proc`` consumes to produce ``sub.kind`` for that experiment channel."""
|
|
235
|
+
fn = getattr(proc, "inputs", None)
|
|
236
|
+
if fn is not None:
|
|
237
|
+
experiment = self.plan.schedule.experiments[sub.experiment]
|
|
238
|
+
return tuple(fn(sub.kind, experiment, sub.channel))
|
|
239
|
+
return tuple(proc.produces[base_kind(sub.kind)])
|
|
240
|
+
|
|
241
|
+
def _is_produced(self, table, sub: Subscription) -> bool:
|
|
242
|
+
producer = self._producers.get(base_kind(sub.kind))
|
|
243
|
+
if producer is None:
|
|
244
|
+
return False
|
|
245
|
+
inputs = self._inputs(self._procs[producer], sub)
|
|
246
|
+
return all(
|
|
247
|
+
producer in table.get((sub.experiment, sub.channel, kind_in), {})
|
|
248
|
+
for kind_in in inputs
|
|
249
|
+
)
|
|
250
|
+
|
|
251
|
+
def _producer_for(self, sub: Subscription) -> str:
|
|
252
|
+
where = f"{sub.kind!r} of {sub.experiment}/{sub.channel}"
|
|
253
|
+
name = self._producers.get(base_kind(sub.kind))
|
|
254
|
+
if name is None:
|
|
255
|
+
raise RoutingError(
|
|
256
|
+
f"{sub.consumer!r} needs {where} but no registered process "
|
|
257
|
+
f"produces {sub.kind!r}"
|
|
258
|
+
)
|
|
259
|
+
can = getattr(self._procs[name], "can_produce", None)
|
|
260
|
+
experiment = self.plan.schedule.experiments[sub.experiment]
|
|
261
|
+
if can is not None and not can(sub.kind, experiment, sub.channel):
|
|
262
|
+
raise RoutingError(
|
|
263
|
+
f"{sub.consumer!r} needs {where} but {name!r} has no method "
|
|
264
|
+
f"configured for experiment {sub.experiment!r} "
|
|
265
|
+
"(check the experiment TOML)"
|
|
266
|
+
)
|
|
267
|
+
return name
|
|
268
|
+
|
|
269
|
+
def _check(self, sub: Subscription) -> None:
|
|
270
|
+
plan = self.plan
|
|
271
|
+
if base_kind(sub.kind) not in KINDS:
|
|
272
|
+
raise RoutingError(f"{sub.consumer!r}: unknown data kind {sub.kind!r}")
|
|
273
|
+
if sub.cadence not in CADENCES:
|
|
274
|
+
raise RoutingError(f"{sub.consumer!r}: unknown cadence {sub.cadence!r}")
|
|
275
|
+
if sub.experiment not in plan.experiments:
|
|
276
|
+
raise RoutingError(
|
|
277
|
+
f"{sub.consumer!r}: unknown experiment {sub.experiment!r}"
|
|
278
|
+
)
|
|
279
|
+
if sub.channel not in plan.channels(sub.experiment):
|
|
280
|
+
raise RoutingError(
|
|
281
|
+
f"{sub.consumer!r}: experiment {sub.experiment!r} has no channel "
|
|
282
|
+
f"{sub.channel!r} (channels: {plan.channels(sub.experiment)})"
|
|
283
|
+
)
|
|
284
|
+
if sub.cadence == "pattern":
|
|
285
|
+
for t in range(plan.timepoints):
|
|
286
|
+
if plan.pattern_due(sub.experiment, t) and not plan.is_scheduled(
|
|
287
|
+
sub.experiment, sub.channel, t
|
|
288
|
+
):
|
|
289
|
+
raise RoutingError(
|
|
290
|
+
f"{sub.consumer!r} wants {sub.kind!r} of "
|
|
291
|
+
f"{sub.experiment}/{sub.channel} when the pattern is due, "
|
|
292
|
+
f"but at t={t} the pattern is due and the channel is not "
|
|
293
|
+
"acquired"
|
|
294
|
+
)
|
|
295
|
+
|
|
296
|
+
# ------------------------------------------------------------- running
|
|
297
|
+
def publish(self, data: Any) -> int:
|
|
298
|
+
"""Deliver ``data`` to every subscriber due at its timepoint. Returns the count."""
|
|
299
|
+
if not self.resolved:
|
|
300
|
+
raise RoutingError("publish() before resolve()")
|
|
301
|
+
event = data.event
|
|
302
|
+
key = (event.experiment_name, event.index.get("c"), data.kind)
|
|
303
|
+
deliveries = self._table.get(key)
|
|
304
|
+
if not deliveries:
|
|
305
|
+
self.undeliverable += 1
|
|
306
|
+
if key not in self._warned:
|
|
307
|
+
self._warned.add(key)
|
|
308
|
+
logger.warning(f"no subscriber for {key}; dropping it")
|
|
309
|
+
return 0
|
|
310
|
+
|
|
311
|
+
due = None
|
|
312
|
+
n = 0
|
|
313
|
+
for d in deliveries:
|
|
314
|
+
if d.cadence == "pattern":
|
|
315
|
+
if due is None:
|
|
316
|
+
due = self.plan.pattern_due(key[0], event.t_index)
|
|
317
|
+
if not due:
|
|
318
|
+
continue
|
|
319
|
+
self._inboxes[d.consumer].put(data)
|
|
320
|
+
n += 1
|
|
321
|
+
return n
|
|
322
|
+
|
|
323
|
+
def end_stream(self, producer: str) -> list[str]:
|
|
324
|
+
"""
|
|
325
|
+
Record that ``producer`` will publish nothing more. Every consumer
|
|
326
|
+
whose last upstream this was gets one StreamCloseMessage. Returns the
|
|
327
|
+
consumers closed. Idempotent per producer.
|
|
328
|
+
"""
|
|
329
|
+
closed = []
|
|
330
|
+
with self._lock:
|
|
331
|
+
for consumer, ups in self._upstreams.items():
|
|
332
|
+
if producer not in ups:
|
|
333
|
+
continue
|
|
334
|
+
ended = self._ended[consumer]
|
|
335
|
+
if producer in ended:
|
|
336
|
+
continue
|
|
337
|
+
ended.add(producer)
|
|
338
|
+
if ended == ups:
|
|
339
|
+
closed.append(consumer)
|
|
340
|
+
for consumer in closed:
|
|
341
|
+
self._inboxes[consumer].put(StreamCloseMessage())
|
|
342
|
+
if closed:
|
|
343
|
+
logger.info(f"{producer} ended its stream; closing {closed}")
|
|
344
|
+
return closed
|
|
345
|
+
|
|
346
|
+
# ------------------------------------------------------------- queries
|
|
347
|
+
def is_active(self, name: str) -> bool:
|
|
348
|
+
return name in self._active
|
|
349
|
+
|
|
350
|
+
def active_processes(self) -> list[Any]:
|
|
351
|
+
"""Registered processes that will receive data (or are always active), in registration order."""
|
|
352
|
+
return [self._procs[name] for name in self._active]
|
|
353
|
+
|
|
354
|
+
def inbox(self, name: str) -> Queue:
|
|
355
|
+
return self._inboxes[name]
|
|
356
|
+
|
|
357
|
+
def upstreams(self, name: str) -> set[str]:
|
|
358
|
+
return set(self._upstreams.get(name, ()))
|
|
359
|
+
|
|
360
|
+
def demanded(self, kind: str) -> set[tuple[str, str]]:
|
|
361
|
+
"""``(experiment, channel)`` pairs for which some consumer demands ``kind``."""
|
|
362
|
+
return {
|
|
363
|
+
(exp, ch)
|
|
364
|
+
for (exp, ch, k), deliveries in self._table.items()
|
|
365
|
+
if k == kind and any(d.demand for d in deliveries)
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
def demanded_kinds(self, base: str) -> set[tuple[str, str, str]]:
|
|
369
|
+
"""``(experiment, channel, kind)`` demanded for every kind whose base is ``base`` (e.g. ``seg``, ``seg:nuclei``)."""
|
|
370
|
+
return {
|
|
371
|
+
(exp, ch, k)
|
|
372
|
+
for (exp, ch, k), deliveries in self._table.items()
|
|
373
|
+
if base_kind(k) == base and any(d.demand for d in deliveries)
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
def produced_by(
|
|
377
|
+
self, producer: str
|
|
378
|
+
) -> dict[tuple[str, str], list[tuple[str, str]]]:
|
|
379
|
+
"""
|
|
380
|
+
What ``producer`` must make: ``{(experiment, channel): [(kind, cadence), ...]}``
|
|
381
|
+
where ``cadence`` is ``"always"`` if any *demanding* subscriber wants
|
|
382
|
+
every frame (a record-only subscriber never widens production).
|
|
383
|
+
"""
|
|
384
|
+
out: dict[tuple[str, str], list[tuple[str, str]]] = defaultdict(list)
|
|
385
|
+
for (exp, ch, kind), deliveries in sorted(self._table.items()):
|
|
386
|
+
if self._producers.get(base_kind(kind)) != producer:
|
|
387
|
+
continue
|
|
388
|
+
cadence = (
|
|
389
|
+
"always"
|
|
390
|
+
if any(d.cadence == "always" and d.demand for d in deliveries)
|
|
391
|
+
else "pattern"
|
|
392
|
+
)
|
|
393
|
+
out[(exp, ch)].append((kind, cadence))
|
|
394
|
+
return dict(out)
|
|
395
|
+
|
|
396
|
+
def deliveries_to(self, consumer: str) -> dict[str, set[tuple[str, str]]]:
|
|
397
|
+
"""``{kind: {(experiment, channel), ...}}`` that ``consumer`` will receive."""
|
|
398
|
+
out: dict[str, set[tuple[str, str]]] = defaultdict(set)
|
|
399
|
+
for (exp, ch, kind), deliveries in self._table.items():
|
|
400
|
+
if any(d.consumer == consumer for d in deliveries):
|
|
401
|
+
out[kind].add((exp, ch))
|
|
402
|
+
return dict(out)
|
|
403
|
+
|
|
404
|
+
def receives(self, consumer: str, experiment: str, channel: str, kind: str) -> bool:
|
|
405
|
+
return any(
|
|
406
|
+
d.consumer == consumer
|
|
407
|
+
for d in self._table.get((experiment, channel, kind), ())
|
|
408
|
+
)
|
|
409
|
+
|
|
410
|
+
def as_dict(self) -> dict:
|
|
411
|
+
"""Provenance: producers, the routes per experiment/channel/kind, fan-in, active processes."""
|
|
412
|
+
routes: dict = {}
|
|
413
|
+
for (exp, ch, kind), deliveries in sorted(self._table.items()):
|
|
414
|
+
routes.setdefault(exp, {}).setdefault(ch, {})[kind] = [
|
|
415
|
+
d.label() for d in deliveries
|
|
416
|
+
]
|
|
417
|
+
return {
|
|
418
|
+
"producers": dict(self._producers),
|
|
419
|
+
"routes": routes,
|
|
420
|
+
"upstreams": {k: sorted(v) for k, v in self._upstreams.items()},
|
|
421
|
+
"active": list(self._active),
|
|
422
|
+
}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
|
|
3
|
+
from cv2 import resize
|
|
4
|
+
|
|
5
|
+
from .segmentation import *
|
|
6
|
+
|
|
7
|
+
logger = logging.getLogger(__name__)
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class CellposeResource(SharedSegmentationResource):
|
|
11
|
+
def __init__(self, pretrained_model="cpsam", gpu=True, **kwargs):
|
|
12
|
+
super().__init__()
|
|
13
|
+
|
|
14
|
+
self.pretrained_model = pretrained_model
|
|
15
|
+
self.gpu = gpu
|
|
16
|
+
|
|
17
|
+
logger.info(f"loading cellpose model: {pretrained_model} (gpu={gpu})")
|
|
18
|
+
|
|
19
|
+
from cellpose import models
|
|
20
|
+
|
|
21
|
+
self.model = models.CellposeModel(gpu=gpu, pretrained_model=pretrained_model)
|
|
22
|
+
|
|
23
|
+
def eval(self, data, **cellpose_kwargs):
|
|
24
|
+
from cellpose.transforms import convert_image
|
|
25
|
+
|
|
26
|
+
transformed_data = convert_image(data)
|
|
27
|
+
cellpose_out = self.model.eval(transformed_data, **cellpose_kwargs)
|
|
28
|
+
|
|
29
|
+
return cellpose_out[0]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class CellposeResourceRequest(SharedSegmentationResourceRequest):
|
|
33
|
+
def __init__(self, model_name, use_gpu):
|
|
34
|
+
super().__init__(CellposeResource, pretrained_model=model_name, gpu=use_gpu)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class CellposeSegmentationMethod(SegmentationMethod):
|
|
38
|
+
name = "cellpose"
|
|
39
|
+
|
|
40
|
+
def __init__(
|
|
41
|
+
self,
|
|
42
|
+
experiment_name,
|
|
43
|
+
model="cpsam",
|
|
44
|
+
use_gpu=True,
|
|
45
|
+
normlow=0,
|
|
46
|
+
normhigh=5000,
|
|
47
|
+
**kwargs,
|
|
48
|
+
):
|
|
49
|
+
super().__init__(experiment_name)
|
|
50
|
+
|
|
51
|
+
self.model_name = model
|
|
52
|
+
self.use_gpu = use_gpu
|
|
53
|
+
self.normalization = {"lowhigh": [normlow, normhigh]}
|
|
54
|
+
|
|
55
|
+
self.cellpose_resource = None
|
|
56
|
+
self.initialized = False
|
|
57
|
+
|
|
58
|
+
def request_resource(self) -> Optional[SharedSegmentationResourceRequest]:
|
|
59
|
+
return CellposeResourceRequest(self.model_name, self.use_gpu)
|
|
60
|
+
|
|
61
|
+
def provide_resource(self, resource: SharedSegmentationResource):
|
|
62
|
+
self.cellpose_resource = resource
|
|
63
|
+
self.initialized = True
|
|
64
|
+
|
|
65
|
+
def segment(self, data):
|
|
66
|
+
assert self.initialized, "model was not yet provided a shared CellposeResource"
|
|
67
|
+
|
|
68
|
+
masks = self.cellpose_resource.eval(data, normalize=self.normalization)
|
|
69
|
+
|
|
70
|
+
return masks
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class EmbryoSegmentationMethod(CellposeSegmentationMethod):
|
|
74
|
+
name = "embryo_resizing"
|
|
75
|
+
|
|
76
|
+
def __init__(
|
|
77
|
+
self,
|
|
78
|
+
experiment_name,
|
|
79
|
+
model="embryomodel",
|
|
80
|
+
use_gpu=True,
|
|
81
|
+
normlow=0,
|
|
82
|
+
normhigh=0.15,
|
|
83
|
+
ideal_size=(100, 100),
|
|
84
|
+
cache_result=True,
|
|
85
|
+
**kwargs,
|
|
86
|
+
):
|
|
87
|
+
super().__init__(experiment_name, model, use_gpu, normlow, normhigh)
|
|
88
|
+
|
|
89
|
+
self.ideal_size = ideal_size
|
|
90
|
+
self.cached_result = None
|
|
91
|
+
self.do_cache = cache_result
|
|
92
|
+
|
|
93
|
+
def segment(self, data):
|
|
94
|
+
# use cached result if caching (e.g. because embryo doesn't move)
|
|
95
|
+
if self.do_cache and (self.cached_result is not None):
|
|
96
|
+
return self.cached_result
|
|
97
|
+
|
|
98
|
+
# downscale to make the embryo smaller
|
|
99
|
+
downscaled_frame = resize(data, self.ideal_size)
|
|
100
|
+
|
|
101
|
+
out = super().segment(downscaled_frame)
|
|
102
|
+
mask = out > 0
|
|
103
|
+
|
|
104
|
+
# upscale back to full size
|
|
105
|
+
big_mask = resize(mask.astype(float), data.shape) > 0.5
|
|
106
|
+
|
|
107
|
+
big_mask = np.array(big_mask)
|
|
108
|
+
logger.debug(f"big_mask shape: {big_mask.shape}")
|
|
109
|
+
|
|
110
|
+
if self.do_cache:
|
|
111
|
+
self.cached_result = big_mask
|
|
112
|
+
|
|
113
|
+
return big_mask
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
from typing import Optional
|
|
2
|
+
from uuid import uuid4
|
|
3
|
+
|
|
4
|
+
import numpy as np
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class SharedSegmentationResource:
|
|
8
|
+
def __init__(self, **kwargs):
|
|
9
|
+
pass
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class SharedSegmentationResourceRequest:
|
|
13
|
+
"""
|
|
14
|
+
Used to avoid loading duplicates of large models.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
def __init__(self, resource: type[SharedSegmentationResource], **init_kwargs):
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
:param resource: **class** of shared resource
|
|
21
|
+
:param init_kwargs: kwargs for initializing the shared resource
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
self.resource = resource # this is an uninitialized resource
|
|
25
|
+
self.init_kwargs = init_kwargs
|
|
26
|
+
self.request_id = uuid4()
|
|
27
|
+
|
|
28
|
+
def __eq__(self, other):
|
|
29
|
+
same_resource_type = self.resource == other.resource
|
|
30
|
+
same_kwargs = self.init_kwargs == other.init_kwargs
|
|
31
|
+
|
|
32
|
+
return same_resource_type & same_kwargs
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class SegmentationMethod:
|
|
36
|
+
name = "base_model"
|
|
37
|
+
|
|
38
|
+
def __init__(self, experiment_name, **kwargs):
|
|
39
|
+
self.experiment_name = experiment_name
|
|
40
|
+
|
|
41
|
+
def request_resource(self) -> SharedSegmentationResourceRequest | None:
|
|
42
|
+
pass
|
|
43
|
+
|
|
44
|
+
def provide_resource(self, resource: SharedSegmentationResource):
|
|
45
|
+
pass
|
|
46
|
+
|
|
47
|
+
def segment(self, data: np.ndarray) -> np.ndarray:
|
|
48
|
+
raise NotImplementedError("base_model does not implement segment")
|