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,181 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
import tifffile
|
|
3
|
+
from skimage.measure import regionprops
|
|
4
|
+
|
|
5
|
+
from .pattern import AcquiredImageRequest, DataDock, PatternMethod
|
|
6
|
+
from .zoo import ZooMeta
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class NucleusControlMethod(PatternMethod):
|
|
10
|
+
name = "nucleus_control_base"
|
|
11
|
+
zoo_meta = ZooMeta(
|
|
12
|
+
source="mcf10a",
|
|
13
|
+
title="Generic Nucleus Control",
|
|
14
|
+
kwargs={"_channel": ""},
|
|
15
|
+
description="Subclass this method to apply per-cell intensity",
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
def __init__(self, channel=None, tracks=False, **kwargs):
|
|
19
|
+
super().__init__(**kwargs)
|
|
20
|
+
|
|
21
|
+
if channel is None:
|
|
22
|
+
raise AttributeError(
|
|
23
|
+
"NucleusControlMethod must be provided a "
|
|
24
|
+
'segmentation channel in the .toml: e.g. nuc_channel = "545"'
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
self.channel = channel
|
|
28
|
+
# with tracks = true the per-cell loop runs on tracked labels, so
|
|
29
|
+
# prop.label is a track id that persists across timepoints
|
|
30
|
+
self.use_tracks = bool(tracks)
|
|
31
|
+
self.add_requirement(
|
|
32
|
+
channel, raw=True, seg=not self.use_tracks, tracks=self.use_tracks
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
def process_prop(self, prop):
|
|
36
|
+
return prop.image
|
|
37
|
+
|
|
38
|
+
def cell_labels(self, context) -> np.ndarray:
|
|
39
|
+
"""The label image the per-cell loop runs on: tracked labels with ``tracks = true``, else the segmentation."""
|
|
40
|
+
if self.use_tracks:
|
|
41
|
+
return context.tracks(self.channel).labels
|
|
42
|
+
return context.segmentation(self.channel)
|
|
43
|
+
|
|
44
|
+
def generate(self, context) -> np.ndarray:
|
|
45
|
+
seg = self.cell_labels(context)
|
|
46
|
+
raw = context.raw(self.channel)
|
|
47
|
+
|
|
48
|
+
h, w = self.pattern_shape
|
|
49
|
+
|
|
50
|
+
new_img = np.zeros((int(h), int(w)), dtype=np.float16)
|
|
51
|
+
|
|
52
|
+
for prop in regionprops(seg, intensity_image=raw):
|
|
53
|
+
cell_stim = self.process_prop(prop)
|
|
54
|
+
|
|
55
|
+
new_img[prop.bbox[0] : prop.bbox[2], prop.bbox[1] : prop.bbox[3]] += (
|
|
56
|
+
cell_stim
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
new_img_clamped = np.clip(new_img, 0, 1).astype(np.float16)
|
|
60
|
+
|
|
61
|
+
return new_img_clamped
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class BinaryNucleusClampModel(NucleusControlMethod):
|
|
65
|
+
name = "binary_nucleus_clamp"
|
|
66
|
+
|
|
67
|
+
def __init__(self, channel="545", clamp_target=10000, **kwargs):
|
|
68
|
+
super().__init__(channel=channel, **kwargs)
|
|
69
|
+
|
|
70
|
+
self.clamp_target = clamp_target
|
|
71
|
+
|
|
72
|
+
zoo_meta = ZooMeta(
|
|
73
|
+
source="mcf10a",
|
|
74
|
+
title="Bang-Bang Controller",
|
|
75
|
+
kwargs={"_channel": "", "clamp_target": 75},
|
|
76
|
+
description="Applies light if nucleus is below target intensity",
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
def process_prop(self, prop):
|
|
80
|
+
if prop.intensity_mean > self.clamp_target:
|
|
81
|
+
return prop.image * 0
|
|
82
|
+
|
|
83
|
+
return prop.image
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class CenteredImageModel(NucleusControlMethod):
|
|
87
|
+
name = "centered_image"
|
|
88
|
+
|
|
89
|
+
def __init__(
|
|
90
|
+
self,
|
|
91
|
+
channel="545",
|
|
92
|
+
tif_path=None,
|
|
93
|
+
min_intensity=2000,
|
|
94
|
+
max_intensity=5000,
|
|
95
|
+
**kwargs,
|
|
96
|
+
):
|
|
97
|
+
super().__init__(channel=channel, **kwargs)
|
|
98
|
+
|
|
99
|
+
self.img = tifffile.imread(tif_path)
|
|
100
|
+
self.min_intensity = min_intensity
|
|
101
|
+
self.max_intensity = max_intensity
|
|
102
|
+
|
|
103
|
+
self.target_image = None
|
|
104
|
+
|
|
105
|
+
def make_target_image(self):
|
|
106
|
+
img = self.img
|
|
107
|
+
|
|
108
|
+
h, w = self.pattern_shape
|
|
109
|
+
|
|
110
|
+
h = int(h)
|
|
111
|
+
w = int(w)
|
|
112
|
+
|
|
113
|
+
padding_h_up = (h - img.shape[0]) // 2
|
|
114
|
+
padding_h_down = h - (padding_h_up + img.shape[0])
|
|
115
|
+
padding_w_left = (w - img.shape[1]) // 2
|
|
116
|
+
padding_w_right = w - (padding_w_left + img.shape[1])
|
|
117
|
+
|
|
118
|
+
padded_img = np.pad(
|
|
119
|
+
img, ((padding_h_up, padding_h_down), (padding_w_left, padding_w_right))
|
|
120
|
+
)
|
|
121
|
+
padded_img = np.array(padded_img, dtype=np.float16)
|
|
122
|
+
|
|
123
|
+
max_v = np.max(img)
|
|
124
|
+
min_v = np.min(img)
|
|
125
|
+
|
|
126
|
+
padded_img = (padded_img - min_v) / (max_v - min_v)
|
|
127
|
+
padded_img = np.clip(padded_img, 0, 1)
|
|
128
|
+
|
|
129
|
+
padded_img = (
|
|
130
|
+
padded_img * (self.max_intensity - self.min_intensity)
|
|
131
|
+
) + self.min_intensity
|
|
132
|
+
|
|
133
|
+
self.target_image = padded_img
|
|
134
|
+
|
|
135
|
+
def get_target_intensity(self, prop):
|
|
136
|
+
y, x = prop.centroid
|
|
137
|
+
|
|
138
|
+
y = round(y)
|
|
139
|
+
x = round(x)
|
|
140
|
+
|
|
141
|
+
return self.target_image[y, x]
|
|
142
|
+
|
|
143
|
+
def process_prop(self, prop):
|
|
144
|
+
target = self.get_target_intensity(prop)
|
|
145
|
+
|
|
146
|
+
if prop.intensity_mean > target:
|
|
147
|
+
return prop.image * 0
|
|
148
|
+
|
|
149
|
+
return prop.image
|
|
150
|
+
|
|
151
|
+
def generate(self, context) -> np.ndarray:
|
|
152
|
+
if self.target_image is None:
|
|
153
|
+
self.make_target_image()
|
|
154
|
+
|
|
155
|
+
return super().generate(context)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
class GlobalCycleModel(NucleusControlMethod):
|
|
159
|
+
name = "global_cycle"
|
|
160
|
+
|
|
161
|
+
zoo_meta = ZooMeta(
|
|
162
|
+
source="mcf10a",
|
|
163
|
+
title="Open loop intensity cycle",
|
|
164
|
+
kwargs={"_channel": "gfp"},
|
|
165
|
+
time_seconds=5,
|
|
166
|
+
description="Applies light for a given period with a 50% duty cycle",
|
|
167
|
+
)
|
|
168
|
+
|
|
169
|
+
def __init__(self, channel="545", period_m=10, **kwargs):
|
|
170
|
+
super().__init__(channel=channel, **kwargs)
|
|
171
|
+
|
|
172
|
+
self.period_s = period_m * 60
|
|
173
|
+
|
|
174
|
+
def generate(self, context) -> np.ndarray:
|
|
175
|
+
t = context.time
|
|
176
|
+
|
|
177
|
+
is_on = ((t // self.period_s) % 2) == 0
|
|
178
|
+
|
|
179
|
+
h, w = self.pattern_shape
|
|
180
|
+
|
|
181
|
+
return np.ones((int(h), int(w))) * is_on
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Pattern methods built from other pattern methods.
|
|
3
|
+
|
|
4
|
+
:class:`SplitPattern` (``method = "split"``) runs one method on each half of
|
|
5
|
+
the field, the halves being ``left`` / ``right`` or ``top`` / ``bottom``
|
|
6
|
+
sub-tables of ``[pattern]``::
|
|
7
|
+
|
|
8
|
+
[pattern]
|
|
9
|
+
method = "split"
|
|
10
|
+
boundary = 0.5 # where the halves meet, as a fraction of the width (or height)
|
|
11
|
+
feather = 0 # pixels of linear blend across the boundary
|
|
12
|
+
|
|
13
|
+
[pattern.left]
|
|
14
|
+
method = "move_in"
|
|
15
|
+
channel = "545"
|
|
16
|
+
|
|
17
|
+
[pattern.right]
|
|
18
|
+
method = "move_out"
|
|
19
|
+
channel = "545"
|
|
20
|
+
|
|
21
|
+
Each half's method is an ordinary registered pattern method (built in or
|
|
22
|
+
custom) with its own arguments; it sees the whole field and the composite
|
|
23
|
+
keeps its pattern on its side of the boundary. Requirements are the union
|
|
24
|
+
of the halves', so the frames and segmentations each half asks for arrive
|
|
25
|
+
once and are shared.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
from __future__ import annotations
|
|
29
|
+
|
|
30
|
+
import logging
|
|
31
|
+
|
|
32
|
+
import numpy as np
|
|
33
|
+
|
|
34
|
+
from ..experiments import Experiment
|
|
35
|
+
from .pattern import AcquiredImageRequest, CameraProperties, PatternMethod
|
|
36
|
+
|
|
37
|
+
logger = logging.getLogger(__name__)
|
|
38
|
+
|
|
39
|
+
HORIZONTAL = ("left", "right") # the boundary is vertical: halves side by side
|
|
40
|
+
VERTICAL = ("top", "bottom") # the boundary is horizontal: halves one above the other
|
|
41
|
+
REGIONS = HORIZONTAL + VERTICAL
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class SplitPattern(PatternMethod):
|
|
45
|
+
"""One pattern method per half of the field; see the module docstring."""
|
|
46
|
+
|
|
47
|
+
name = "split"
|
|
48
|
+
|
|
49
|
+
def __init__(
|
|
50
|
+
self,
|
|
51
|
+
left=None,
|
|
52
|
+
right=None,
|
|
53
|
+
top=None,
|
|
54
|
+
bottom=None,
|
|
55
|
+
boundary: float = 0.5,
|
|
56
|
+
feather: int = 0,
|
|
57
|
+
**kwargs,
|
|
58
|
+
):
|
|
59
|
+
super().__init__(**kwargs)
|
|
60
|
+
specs = {
|
|
61
|
+
"left": left,
|
|
62
|
+
"right": right,
|
|
63
|
+
"top": top,
|
|
64
|
+
"bottom": bottom,
|
|
65
|
+
}
|
|
66
|
+
given = tuple(r for r in REGIONS if specs[r] is not None)
|
|
67
|
+
if given == HORIZONTAL:
|
|
68
|
+
self.axis = 1
|
|
69
|
+
elif given == VERTICAL:
|
|
70
|
+
self.axis = 0
|
|
71
|
+
else:
|
|
72
|
+
raise ValueError(
|
|
73
|
+
"split needs exactly [pattern.left] and [pattern.right], or "
|
|
74
|
+
f"[pattern.top] and [pattern.bottom]; got {list(given) or 'none'}"
|
|
75
|
+
)
|
|
76
|
+
self.regions = given
|
|
77
|
+
for region in given:
|
|
78
|
+
spec = specs[region]
|
|
79
|
+
if not isinstance(spec, dict) or "method" not in spec:
|
|
80
|
+
raise ValueError(
|
|
81
|
+
f"[pattern.{region}] must be a table with a 'method' key"
|
|
82
|
+
)
|
|
83
|
+
self.specs = {r: dict(specs[r]) for r in given}
|
|
84
|
+
if not 0.0 < float(boundary) < 1.0:
|
|
85
|
+
raise ValueError(f"boundary must be between 0 and 1, got {boundary}")
|
|
86
|
+
self.boundary = float(boundary)
|
|
87
|
+
self.feather = max(0, int(feather))
|
|
88
|
+
# built by bind_registry, which the pattern process calls before initialize
|
|
89
|
+
self.children: dict[str, PatternMethod] = {}
|
|
90
|
+
|
|
91
|
+
# ------------------------------------------------------------ construction
|
|
92
|
+
@classmethod
|
|
93
|
+
def nested_methods(cls, kwargs: dict) -> list[tuple[str, str, dict]]:
|
|
94
|
+
out = []
|
|
95
|
+
for region in REGIONS:
|
|
96
|
+
spec = kwargs.get(region)
|
|
97
|
+
if isinstance(spec, dict) and "method" in spec:
|
|
98
|
+
rest = {k: v for k, v in spec.items() if k != "method"}
|
|
99
|
+
out.append((region, str(spec["method"]), rest))
|
|
100
|
+
return out
|
|
101
|
+
|
|
102
|
+
def bind_registry(self, registry: dict[str, type]) -> None:
|
|
103
|
+
for region, spec in self.specs.items():
|
|
104
|
+
method = spec["method"]
|
|
105
|
+
cls = registry.get(method)
|
|
106
|
+
if cls is None:
|
|
107
|
+
raise ValueError(
|
|
108
|
+
f"[pattern.{region}]: unknown pattern method {method!r} "
|
|
109
|
+
f"(registered: {', '.join(sorted(registry))})"
|
|
110
|
+
)
|
|
111
|
+
child_kwargs = {k: v for k, v in spec.items() if k != "method"}
|
|
112
|
+
child = cls(**child_kwargs)
|
|
113
|
+
child.bind_registry(registry)
|
|
114
|
+
self.children[region] = child
|
|
115
|
+
# mirror the halves' declared needs so tools that read them off the
|
|
116
|
+
# method (pyclm check) see the union
|
|
117
|
+
self._requirements_list = [
|
|
118
|
+
req for c in self.children.values() for req in c._requirements_list
|
|
119
|
+
]
|
|
120
|
+
stim = [c for c in self.children.values() if c._stim_requested]
|
|
121
|
+
self._stim_requested = bool(stim)
|
|
122
|
+
self._stim_request_raw = any(c._stim_request_raw for c in stim)
|
|
123
|
+
self._stim_request_seg = any(c._stim_request_seg for c in stim)
|
|
124
|
+
self._stim_request_history = max(
|
|
125
|
+
(c._stim_request_history for c in stim), default=1
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
def _require_children(self) -> None:
|
|
129
|
+
if len(self.children) != len(self.regions):
|
|
130
|
+
raise RuntimeError(
|
|
131
|
+
"split's halves are not built: the pattern process binds the "
|
|
132
|
+
"method registry before initialize (bind_registry)"
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
# ------------------------------------------------------------ lifecycle
|
|
136
|
+
def initialize(self, experiment: Experiment) -> list[AcquiredImageRequest]:
|
|
137
|
+
self._require_children()
|
|
138
|
+
merged: dict = {}
|
|
139
|
+
for child in self.children.values():
|
|
140
|
+
for req in child.initialize(experiment):
|
|
141
|
+
have = merged.get(req.id)
|
|
142
|
+
if have is None:
|
|
143
|
+
merged[req.id] = req
|
|
144
|
+
continue
|
|
145
|
+
merged[req.id] = AcquiredImageRequest(
|
|
146
|
+
req.id,
|
|
147
|
+
have.needs_raw or req.needs_raw,
|
|
148
|
+
have.needs_seg or req.needs_seg,
|
|
149
|
+
have.needs_tracks or req.needs_tracks,
|
|
150
|
+
max(have.history, req.history),
|
|
151
|
+
tuple(dict.fromkeys((*have.segmentations, *req.segmentations))),
|
|
152
|
+
)
|
|
153
|
+
return list(merged.values())
|
|
154
|
+
|
|
155
|
+
def configure_system(
|
|
156
|
+
self,
|
|
157
|
+
experiment_name: str,
|
|
158
|
+
camera_properties: CameraProperties,
|
|
159
|
+
experiment: Experiment,
|
|
160
|
+
):
|
|
161
|
+
super().configure_system(experiment_name, camera_properties, experiment)
|
|
162
|
+
for child in self.children.values():
|
|
163
|
+
child.configure_system(experiment_name, camera_properties, experiment)
|
|
164
|
+
|
|
165
|
+
def update_binning(self, binning: int):
|
|
166
|
+
super().update_binning(binning)
|
|
167
|
+
for child in self.children.values():
|
|
168
|
+
if child.binning != int(binning):
|
|
169
|
+
child.update_binning(binning)
|
|
170
|
+
|
|
171
|
+
def update(self, **parameters) -> tuple[dict, dict]:
|
|
172
|
+
"""``boundary`` / ``feather`` here; ``left.<name>`` and the like go to that half."""
|
|
173
|
+
own, forwarded = {}, {}
|
|
174
|
+
for key, value in parameters.items():
|
|
175
|
+
region, dot, rest = key.partition(".")
|
|
176
|
+
if dot and region in self.children:
|
|
177
|
+
forwarded.setdefault(region, {})[rest] = value
|
|
178
|
+
else:
|
|
179
|
+
own[key] = value
|
|
180
|
+
applied, refused = super().update(**own)
|
|
181
|
+
for region, params in forwarded.items():
|
|
182
|
+
a, r = self.children[region].update(**params)
|
|
183
|
+
applied.update({f"{region}.{k}": v for k, v in a.items()})
|
|
184
|
+
refused.update({f"{region}.{k}": v for k, v in r.items()})
|
|
185
|
+
return applied, refused
|
|
186
|
+
|
|
187
|
+
# ------------------------------------------------------------ the pattern
|
|
188
|
+
def masks(self) -> dict[str, np.ndarray]:
|
|
189
|
+
"""The weight of each half at every pixel (they sum to 1)."""
|
|
190
|
+
h, w = self.pattern_shape
|
|
191
|
+
n = w if self.axis == 1 else h
|
|
192
|
+
coords = np.arange(n, dtype=np.float32) + 0.5
|
|
193
|
+
edge = self.boundary * n
|
|
194
|
+
if self.feather > 0:
|
|
195
|
+
first = np.clip((edge - coords) / self.feather + 0.5, 0.0, 1.0)
|
|
196
|
+
else:
|
|
197
|
+
first = (coords < edge).astype(np.float32)
|
|
198
|
+
first = first[np.newaxis, :] if self.axis == 1 else first[:, np.newaxis]
|
|
199
|
+
first = np.broadcast_to(first, (h, w)).astype(np.float32)
|
|
200
|
+
return {self.regions[0]: first, self.regions[1]: 1.0 - first}
|
|
201
|
+
|
|
202
|
+
def generate(self, context) -> np.ndarray:
|
|
203
|
+
self._require_children()
|
|
204
|
+
masks = self.masks()
|
|
205
|
+
out = np.zeros(self.pattern_shape, np.float32)
|
|
206
|
+
for region, child in self.children.items():
|
|
207
|
+
pattern = np.asarray(child.generate(context), dtype=np.float32)
|
|
208
|
+
if pattern.shape != out.shape:
|
|
209
|
+
pattern = _fit(pattern, out.shape)
|
|
210
|
+
out += masks[region] * np.clip(pattern, 0.0, 1.0)
|
|
211
|
+
return np.clip(out, 0.0, 1.0)
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _fit(pattern: np.ndarray, shape: tuple[int, int]) -> np.ndarray:
|
|
215
|
+
"""Crop or zero-pad a half's pattern to the composite's shape."""
|
|
216
|
+
out = np.zeros(shape, np.float32)
|
|
217
|
+
h = min(shape[0], pattern.shape[0])
|
|
218
|
+
w = min(shape[1], pattern.shape[1])
|
|
219
|
+
out[:h, :w] = pattern[:h, :w]
|
|
220
|
+
return out
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
from skimage.measure import label, regionprops
|
|
5
|
+
|
|
6
|
+
from .pattern import PatternContext, PatternMethod
|
|
7
|
+
from .zoo import ZooMeta
|
|
8
|
+
|
|
9
|
+
logger = logging.getLogger(__name__)
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class PatternAlongAxis(PatternMethod):
|
|
13
|
+
def __init__(self, channel="638", **kwargs):
|
|
14
|
+
super().__init__(**kwargs)
|
|
15
|
+
|
|
16
|
+
self.channel = channel
|
|
17
|
+
self.add_requirement(channel, raw=False, seg=True)
|
|
18
|
+
|
|
19
|
+
def apply_magnitude(self, mag) -> np.ndarray:
|
|
20
|
+
raise NotImplementedError
|
|
21
|
+
|
|
22
|
+
def generate(self, context: PatternContext):
|
|
23
|
+
mask = context.segmentation(self.channel)
|
|
24
|
+
|
|
25
|
+
labeled_mask = label(mask)
|
|
26
|
+
props = regionprops(labeled_mask)
|
|
27
|
+
|
|
28
|
+
if len(props) == 0:
|
|
29
|
+
logger.warning(f"No props segmented: {self.experiment_name}")
|
|
30
|
+
return np.zeros_like(mask)
|
|
31
|
+
|
|
32
|
+
biggest_prop_area = 0
|
|
33
|
+
for prop in props:
|
|
34
|
+
if prop.area > biggest_prop_area:
|
|
35
|
+
mask = labeled_mask == prop.label
|
|
36
|
+
centroid = prop.centroid
|
|
37
|
+
long_axis = (np.sin(prop.orientation), np.cos(prop.orientation))
|
|
38
|
+
axis_length = prop.axis_major_length
|
|
39
|
+
|
|
40
|
+
biggest_prop_area = prop.area
|
|
41
|
+
|
|
42
|
+
y_arange = np.arange(self.pattern_shape[0])
|
|
43
|
+
x_arange = np.arange(self.pattern_shape[1])
|
|
44
|
+
|
|
45
|
+
yy, xx = np.meshgrid(y_arange, x_arange)
|
|
46
|
+
|
|
47
|
+
mag = (yy - centroid[1]) * long_axis[0] + (xx - centroid[0]) * long_axis[1]
|
|
48
|
+
mag = np.abs(mag) / (axis_length / 2)
|
|
49
|
+
|
|
50
|
+
included = self.apply_magnitude(mag)
|
|
51
|
+
|
|
52
|
+
return included * mask
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class InnerPatternMethod(PatternAlongAxis):
|
|
56
|
+
zoo_meta = ZooMeta(
|
|
57
|
+
source="fly",
|
|
58
|
+
title="Inner fraction",
|
|
59
|
+
description="Applies a bar to the center of the long axis",
|
|
60
|
+
kwargs={"fraction_length": 0.1},
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
name = "embryo_inner"
|
|
64
|
+
|
|
65
|
+
def __init__(self, fraction_length=0.1, **kwargs):
|
|
66
|
+
super().__init__(**kwargs)
|
|
67
|
+
|
|
68
|
+
self.fraction_length = fraction_length
|
|
69
|
+
|
|
70
|
+
def apply_magnitude(self, mag) -> np.ndarray:
|
|
71
|
+
return mag < self.fraction_length
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class OuterPatternMethod(PatternAlongAxis):
|
|
75
|
+
zoo_meta = ZooMeta(
|
|
76
|
+
source="fly",
|
|
77
|
+
title="Outer fraction",
|
|
78
|
+
description="Applies a bar to the poles of the long axis",
|
|
79
|
+
kwargs={"fraction_length": 0.1},
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
name = "embryo_outer"
|
|
83
|
+
|
|
84
|
+
def __init__(self, fraction_length=0.1, **kwargs):
|
|
85
|
+
super().__init__(**kwargs)
|
|
86
|
+
|
|
87
|
+
self.fraction_length = fraction_length
|
|
88
|
+
|
|
89
|
+
def apply_magnitude(self, mag) -> np.ndarray:
|
|
90
|
+
return mag > (1 - self.fraction_length)
|