closed-loop-microscopy 1.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. closed_loop_microscopy-1.1.0.dist-info/METADATA +118 -0
  2. closed_loop_microscopy-1.1.0.dist-info/RECORD +74 -0
  3. closed_loop_microscopy-1.1.0.dist-info/WHEEL +4 -0
  4. closed_loop_microscopy-1.1.0.dist-info/entry_points.txt +5 -0
  5. closed_loop_microscopy-1.1.0.dist-info/licenses/LICENSE.md +7 -0
  6. pyclm/__init__.py +26 -0
  7. pyclm/__main__.py +8 -0
  8. pyclm/check.py +931 -0
  9. pyclm/cli.py +256 -0
  10. pyclm/commands.py +183 -0
  11. pyclm/controller.py +447 -0
  12. pyclm/convert_hdf5s.py +273 -0
  13. pyclm/core/__init__.py +20 -0
  14. pyclm/core/base_process.py +166 -0
  15. pyclm/core/core_interface.py +47 -0
  16. pyclm/core/datatypes.py +142 -0
  17. pyclm/core/events.py +194 -0
  18. pyclm/core/experiments.py +403 -0
  19. pyclm/core/grid.py +272 -0
  20. pyclm/core/kinds.py +42 -0
  21. pyclm/core/manager.py +861 -0
  22. pyclm/core/measure.py +266 -0
  23. pyclm/core/messages.py +124 -0
  24. pyclm/core/microscope.py +504 -0
  25. pyclm/core/pattern_process.py +282 -0
  26. pyclm/core/patterns/__init__.py +60 -0
  27. pyclm/core/patterns/bar_patterns.py +259 -0
  28. pyclm/core/patterns/cell_intensity_patterns.py +181 -0
  29. pyclm/core/patterns/composite.py +220 -0
  30. pyclm/core/patterns/embryo_patterns.py +90 -0
  31. pyclm/core/patterns/fbc_cell_movement.py +295 -0
  32. pyclm/core/patterns/pattern.py +610 -0
  33. pyclm/core/patterns/pulse_patterns.py +261 -0
  34. pyclm/core/patterns/static_patterns.py +58 -0
  35. pyclm/core/patterns/wave_patterns.py +95 -0
  36. pyclm/core/patterns/zoo.py +231 -0
  37. pyclm/core/plan.py +623 -0
  38. pyclm/core/position_mover.py +185 -0
  39. pyclm/core/queues.py +41 -0
  40. pyclm/core/real_core.py +158 -0
  41. pyclm/core/router.py +422 -0
  42. pyclm/core/segmentation/__init__.py +2 -0
  43. pyclm/core/segmentation/cellpose_segmentation.py +113 -0
  44. pyclm/core/segmentation/segmentation.py +48 -0
  45. pyclm/core/segmentation_process.py +179 -0
  46. pyclm/core/settings.py +120 -0
  47. pyclm/core/storage/__init__.py +37 -0
  48. pyclm/core/storage/base.py +234 -0
  49. pyclm/core/storage/events.py +130 -0
  50. pyclm/core/storage/hdf5_v1.py +337 -0
  51. pyclm/core/storage/ome_zarr.py +861 -0
  52. pyclm/core/tracking/__init__.py +28 -0
  53. pyclm/core/tracking/centroid.py +75 -0
  54. pyclm/core/tracking/tracking.py +124 -0
  55. pyclm/core/tracking_process.py +106 -0
  56. pyclm/core/virtual_microscope/__init__.py +0 -0
  57. pyclm/core/virtual_microscope/simulated_core.py +262 -0
  58. pyclm/core/virtual_microscope/simulated_source.py +206 -0
  59. pyclm/core/writer_process.py +130 -0
  60. pyclm/demo.py +225 -0
  61. pyclm/directories.py +563 -0
  62. pyclm/gui/__init__.py +28 -0
  63. pyclm/gui/debug_viewer.py +41 -0
  64. pyclm/gui/gui_controller.py +551 -0
  65. pyclm/gui/widgets.py +292 -0
  66. pyclm/io/__init__.py +29 -0
  67. pyclm/io/export.py +202 -0
  68. pyclm/io/readers.py +589 -0
  69. pyclm/methods.py +249 -0
  70. pyclm/mmconfig.py +143 -0
  71. pyclm/preview.py +414 -0
  72. pyclm/run_pyclm.py +298 -0
  73. pyclm/schema.py +806 -0
  74. pyclm/templates.py +165 -0
@@ -0,0 +1,282 @@
1
+ import logging
2
+ from threading import Event
3
+
4
+ from .base_process import PipelineProcess
5
+ from .datatypes import AcquisitionData, CameraPattern
6
+ from .experiments import Experiment
7
+ from .messages import (
8
+ Message,
9
+ PatternParamsResultMessage,
10
+ SettingsRequestMessage,
11
+ StreamCloseMessage,
12
+ )
13
+ from .patterns import (
14
+ ROI,
15
+ AcquiredImageRequest,
16
+ CameraProperties,
17
+ DataDock,
18
+ PatternContext,
19
+ PatternMethod,
20
+ known_models,
21
+ )
22
+ from .patterns.pattern import ExperimentState
23
+ from .plan import requirement_kinds
24
+ from .queues import AllQueues
25
+ from .router import Subscription
26
+
27
+ logger = logging.getLogger(__name__)
28
+
29
+
30
+ class PatternProcess(PipelineProcess):
31
+ """
32
+ Generates patterns: the Manager announces each pattern-due timepoint with
33
+ a :class:`RequestPattern`, the Router delivers the required raw / seg /
34
+ tracks data at that cadence, and once the dock for that timepoint is
35
+ complete the experiment's method runs and the result goes to the SLM
36
+ buffer.
37
+ """
38
+
39
+ always_active = True
40
+
41
+ def __init__(self, aq: AllQueues, stop_event: Event | None = None):
42
+ super().__init__(stop_event, name="pattern")
43
+
44
+ # per-instance copy so registrations do not leak between controllers
45
+ self.known_models: dict[str, type[PatternMethod]] = dict(known_models)
46
+
47
+ self.inbox = aq.manager_to_pattern
48
+ self.slm = aq.pattern_to_slm
49
+ self.to_manager = aq.pattern_to_manager
50
+ # experiment name -> MicroscopePosition, for context.position() (set by the Controller)
51
+ self.positions: dict = {}
52
+
53
+ self.camera_properties = None
54
+ # {experiment: GridGeometry} for grid experiments (set by the Controller)
55
+ self.grids: dict = {}
56
+ self.initialized = False
57
+
58
+ self.models = {}
59
+ self.docks = {}
60
+ self.experiments = {}
61
+ # per-experiment memory: histories of deliveries and generated patterns
62
+ self.states: dict[str, ExperimentState] = {}
63
+
64
+ self.register_queue(self.inbox, self.handle_message_wrapper)
65
+
66
+ def initialize(self, camera_properties: CameraProperties):
67
+ self.camera_properties = camera_properties
68
+
69
+ self.initialized = True
70
+
71
+ # ------------------------------------------------------------ routing
72
+ def subscriptions(self, plan) -> list[Subscription]:
73
+ subs = []
74
+ for name in plan.experiments:
75
+ for channel, needs in plan.pattern_requirements(name).items():
76
+ for kind in requirement_kinds(needs):
77
+ subs.append(Subscription(self.name, name, channel, kind, "pattern"))
78
+ return subs
79
+
80
+ # ------------------------------------------------------------ methods
81
+ def request_method(self, experiment: Experiment) -> list[AcquiredImageRequest]:
82
+ method_name = experiment.pattern.method_name
83
+
84
+ model_class: type = self.known_models.get(method_name)
85
+
86
+ assert model_class is not None, (
87
+ f"method {method_name} is not a registered method"
88
+ )
89
+ assert issubclass(model_class, PatternMethod), (
90
+ f"{method_name} is not a PatternMethod"
91
+ )
92
+
93
+ experiment_name = experiment.experiment_name
94
+ method_kwargs = experiment.pattern.kwargs
95
+ logger.debug(f"{experiment_name}: {method_name} kwargs {method_kwargs}")
96
+
97
+ model = model_class(**method_kwargs)
98
+ model.bind_registry(self.known_models)
99
+
100
+ self.models[experiment_name] = model
101
+ self.experiments[experiment_name] = experiment
102
+
103
+ logger.info(f'initializing pattern model "{method_name}"')
104
+
105
+ requirements = model.initialize(experiment)
106
+ self.states[experiment_name] = ExperimentState(
107
+ requirements, pattern_history=getattr(model, "pattern_history", 2)
108
+ )
109
+ return requirements
110
+
111
+ def initialize_models(self):
112
+ for experiment_name in self.models:
113
+ model: PatternMethod = self.models[experiment_name]
114
+ experiment: Experiment = self.experiments[experiment_name]
115
+ props = self.camera_properties
116
+ geom = self.grids.get(experiment_name)
117
+ if geom is not None and props is not None:
118
+ # a grid experiment's method sees, and returns, the stitched frame
119
+ h, w = geom.shape(1)
120
+ props = CameraProperties(ROI(0, 0, int(w), int(h)), props.pixel_size_um)
121
+ model.configure_system(experiment_name, props, experiment)
122
+
123
+ def register_method(self, model: type, name: str | None = None):
124
+ assert issubclass(model, PatternMethod), (
125
+ "model must be a subclass of PatternMethod"
126
+ )
127
+
128
+ model_name = model.name
129
+ if name is not None:
130
+ model_name = name
131
+
132
+ if model_name in self.known_models:
133
+ logger.warning(f"overwriting known model {model_name}")
134
+
135
+ self.known_models[model_name] = model
136
+
137
+ def run_model(self, experiment_name, dockname):
138
+ data_dock = self.docks.pop(dockname)
139
+
140
+ model = self.models.get(experiment_name, None)
141
+
142
+ assert isinstance(model, PatternMethod), (
143
+ f"self.models[{'experiment_name'}] is not a PatternMethod"
144
+ )
145
+
146
+ if model._experiment_ref is None:
147
+ raise RuntimeError(
148
+ f"Model {model.name} for {experiment_name} was not properly configured with an experiment reference."
149
+ )
150
+
151
+ state = self.states.get(experiment_name)
152
+ if state is None:
153
+ state = self.states[experiment_name] = ExperimentState(
154
+ data_dock.requirements
155
+ )
156
+ state.absorb(data_dock, dockname[1])
157
+ context = PatternContext(
158
+ state, model._experiment_ref, position=self.positions.get(experiment_name)
159
+ )
160
+
161
+ pattern = model.generate(context)
162
+ out = CameraPattern(experiment_name, pattern, binning=model.binning)
163
+ state.record_pattern(out.pattern_id, pattern)
164
+ self.slm.put(out)
165
+
166
+ # setting changes the method asked for go to the Manager, which applies
167
+ # them at the next timepoint boundary and records them
168
+ if context.requests:
169
+ self.to_manager.put(
170
+ SettingsRequestMessage(experiment_name, dockname[1], context.requests)
171
+ )
172
+
173
+ def dock_key(self, experiment_name, t) -> tuple[str, int]:
174
+ return (experiment_name, int(t))
175
+
176
+ def check(self, experiment_name, dockname):
177
+ dock: DataDock = self.docks.get(dockname)
178
+
179
+ if dock.check_complete():
180
+ self.run_model(experiment_name, dockname)
181
+
182
+ # ----------------------------------------------------------- messages
183
+ def handle_message(self, message: Message):
184
+ match message.message:
185
+ case "close":
186
+ return False
187
+
188
+ case "update_pattern_params":
189
+ name = message.experiment_name
190
+ model = self.models.get(name)
191
+ if model is None:
192
+ result = PatternParamsResultMessage(
193
+ name, {}, dict.fromkeys(message.parameters, "no pattern method")
194
+ )
195
+ else:
196
+ try:
197
+ applied, refused = model.update(**message.parameters)
198
+ except Exception as e: # a method's own update() may raise
199
+ applied, refused = (
200
+ {},
201
+ dict.fromkeys(message.parameters, repr(e)),
202
+ )
203
+ result = PatternParamsResultMessage(name, applied, refused)
204
+ self.to_manager.put(result)
205
+ return False
206
+
207
+ case "request_pattern":
208
+ assert isinstance(message, RequestPattern)
209
+
210
+ req = message.requirements
211
+ name = message.experiment_name
212
+ t_sec = message.time_sec
213
+ t_index = message.t_index
214
+
215
+ dock = DataDock(t_sec, req)
216
+ dockname = self.dock_key(name, t_index)
217
+
218
+ logger.debug(f"pattern request {dockname}")
219
+
220
+ self.docks[dockname] = dock
221
+
222
+ self.check(name, dockname)
223
+
224
+ return False
225
+
226
+ case _:
227
+ raise NotImplementedError
228
+
229
+ def handle_message_wrapper(self, message):
230
+ if self.handle_message(message):
231
+ return True
232
+ return False
233
+
234
+ def on_stream_end(self) -> bool:
235
+ logger.info("pattern process: stream ended, closing the SLM buffer")
236
+ self.slm.put(StreamCloseMessage())
237
+ return super().on_stream_end()
238
+
239
+ # --------------------------------------------------------------- data
240
+ def handle_data(self, data):
241
+ assert isinstance(data, AcquisitionData), (
242
+ f"pattern process received {type(data)}"
243
+ )
244
+ name = data.event.experiment_name
245
+ t_index = data.event.t_index
246
+
247
+ dockname = self.dock_key(name, t_index)
248
+
249
+ dock = self.docks.get(dockname)
250
+ if dock is None:
251
+ logger.warning(
252
+ f"received {data.kind} data for {dockname} but no pattern was "
253
+ "requested for that timepoint; dropping it"
254
+ )
255
+ return
256
+
257
+ dock.add(data)
258
+
259
+ self.check(name, dockname)
260
+
261
+
262
+ class RequestPattern(Message):
263
+ """
264
+ Used by manager to inform pattern process of upcoming pattern generation
265
+ Pattern process will use this information to collect and store incoming
266
+ raw and segmented data
267
+ """
268
+
269
+ message = "request_pattern"
270
+
271
+ def __init__(
272
+ self,
273
+ t_index,
274
+ time_sec,
275
+ experiment_name: str,
276
+ requirements: list[AcquiredImageRequest],
277
+ ):
278
+ # absolute timepoint, matching AcquisitionEvent.t_index of the data expected
279
+ self.t_index = t_index
280
+ self.time_sec = time_sec
281
+ self.experiment_name = experiment_name
282
+ self.requirements = requirements
@@ -0,0 +1,60 @@
1
+ from .bar_patterns import (
2
+ BarPatternBase,
3
+ BouncingBarPattern,
4
+ RotatingBarPattern,
5
+ SawToothMethod,
6
+ )
7
+ from .cell_intensity_patterns import (
8
+ BinaryNucleusClampModel,
9
+ CenteredImageModel,
10
+ GlobalCycleModel,
11
+ )
12
+ from .composite import SplitPattern
13
+ from .embryo_patterns import InnerPatternMethod, OuterPatternMethod
14
+ from .fbc_cell_movement import (
15
+ BounceModel,
16
+ MoveDownModel,
17
+ MoveInModel,
18
+ MoveOutModel,
19
+ PeriodDirectedPattern,
20
+ RotateCcwModel,
21
+ )
22
+ from .pattern import (
23
+ ROI,
24
+ AcquiredImageRequest,
25
+ CameraProperties,
26
+ DataDock,
27
+ ExperimentState,
28
+ PatternContext,
29
+ PatternMethod,
30
+ )
31
+ from .pulse_patterns import (
32
+ BlinkingBarPattern,
33
+ GlobalPulsePattern,
34
+ PulseSchedulePattern,
35
+ )
36
+ from .static_patterns import CirclePattern, FullOnPattern
37
+
38
+ known_models = {
39
+ "circle": CirclePattern,
40
+ "split": SplitPattern,
41
+ "bar": BarPatternBase,
42
+ "bar_bounce": BouncingBarPattern,
43
+ "blinking_bar": BlinkingBarPattern,
44
+ "global_pulse": GlobalPulsePattern,
45
+ "pulse_schedule": PulseSchedulePattern,
46
+ "full_on": FullOnPattern,
47
+ "rotate_ccw": RotateCcwModel,
48
+ "sawtooth": SawToothMethod,
49
+ "move_out": MoveOutModel,
50
+ "move_in": MoveInModel,
51
+ "move_down": MoveDownModel,
52
+ "fb_bounce": BounceModel,
53
+ "binary_nucleus_clamp": BinaryNucleusClampModel,
54
+ "global_cycle": GlobalCycleModel,
55
+ "centered_image": CenteredImageModel,
56
+ "rotate_bar": RotatingBarPattern,
57
+ "embryo_inner": InnerPatternMethod,
58
+ "embryo_outer": OuterPatternMethod,
59
+ "direction": PeriodDirectedPattern,
60
+ }
@@ -0,0 +1,259 @@
1
+ import numpy as np
2
+
3
+ from .pattern import DataDock, PatternMethod
4
+ from .zoo import ZooMeta
5
+
6
+
7
+ def _stripe_is_on(yy, period_um, duty_cycle, offset_um=0.0):
8
+ """
9
+ Where a stationary periodic bar is lit: stripes of width
10
+ ``duty_cycle * period_um`` along the y-axis, repeating every
11
+ ``period_um``, with the first stripe edge at ``offset_um``.
12
+ """
13
+ return (((yy - offset_um) / period_um) % 1.0) < duty_cycle
14
+
15
+
16
+ def _bar_is_on(yy, t_minutes, bar_speed, period_um, duty_cycle):
17
+ """
18
+ Where a periodic bar is lit at ``t_minutes``: the bar travels along +y at
19
+ ``bar_speed`` µm/min, or along -y when the speed is negative, repeating
20
+ every ``period_um``. The period in time is taken from the speed's
21
+ magnitude so the modulo is always positive.
22
+ """
23
+ period_time = period_um / abs(bar_speed) # minutes
24
+ return ((t_minutes - yy / bar_speed) % period_time) < duty_cycle * period_time
25
+
26
+
27
+ class BarPatternBase(PatternMethod):
28
+ """
29
+ Creates a BarPattern or StationaryBarPattern depending on the requested barspeed
30
+ """
31
+
32
+ def __new__(cls, *args, **kwargs):
33
+ if cls is BarPatternBase: # Check if the base class is being instantiated
34
+ if kwargs.get("bar_speed") != 0:
35
+ return super().__new__(BarPattern)
36
+ else:
37
+ return super().__new__(StationaryBarPattern)
38
+ return super().__new__(cls)
39
+
40
+ def __init__(self, *args, **kwargs):
41
+ super().__init__(*args, **kwargs)
42
+
43
+
44
+ class StationaryBarPattern(BarPatternBase):
45
+ """
46
+ Bar does not move
47
+ """
48
+
49
+ name = "bar (stationary)"
50
+
51
+ def __init__(self, duty_cycle=0.2, bar_speed=0, period=30, **kwargs):
52
+ """
53
+ :param duty_cycle: fraction of time spent on (float 0-1), and consequently fraction of
54
+ vertical axis containing "on" pixels
55
+ :param bar_speed: speed in um/min
56
+ :param period: period in um
57
+ """
58
+ super().__init__(**kwargs)
59
+
60
+ self.duty_cycle = duty_cycle
61
+ self.bar_speed = 0
62
+ self.period_space = period # in um
63
+ self.period_time = 0 # in minutes
64
+
65
+ def generate(self, context):
66
+ _xx, yy = self.get_um_meshgrid()
67
+
68
+ is_on = _stripe_is_on(yy, self.period_space, self.duty_cycle)
69
+
70
+ return is_on.astype(np.float16)
71
+
72
+
73
+ class BarPattern(BarPatternBase):
74
+ """
75
+ moves a bar along the y-axis
76
+ """
77
+
78
+ name = "bar"
79
+ zoo_meta = ZooMeta(
80
+ source="mdck",
81
+ kwargs={"duty_cycle": 0.2, "bar_speed": 1.0, "period": 100},
82
+ title="Moving Bar",
83
+ description="Periodic bar sweeping along the y-axis at constant speed; a negative speed reverses it.",
84
+ )
85
+
86
+ def __init__(self, duty_cycle=0.2, bar_speed=1, period=30, **kwargs):
87
+ """
88
+ :param duty_cycle: fraction of time spent on (float 0-1), and consequently fraction of
89
+ vertical axis containing "on" pixels
90
+ :param bar_speed: speed in um/min; negative moves the bar towards -y
91
+ :param period: period in um
92
+ """
93
+ super().__init__(**kwargs)
94
+
95
+ if bar_speed == 0:
96
+ raise ValueError(
97
+ "bar_speed must be non-zero (0 selects the stationary bar)"
98
+ )
99
+ self.duty_cycle = duty_cycle
100
+ self.bar_speed = bar_speed # um/min; negative moves the bar the other way
101
+ self.period_space = period # in um
102
+
103
+ @property
104
+ def period_time(self) -> float:
105
+ """Minutes for the bar to travel one spatial period (follows bar_speed changes)."""
106
+ return self.period_space / abs(self.bar_speed)
107
+
108
+ def _get_pattern_at_time(self, t_minutes):
109
+ _xx, yy = self.get_um_meshgrid()
110
+ is_on = _bar_is_on(
111
+ yy, t_minutes, self.bar_speed, self.period_space, self.duty_cycle
112
+ )
113
+ return is_on.astype(np.float16)
114
+
115
+ def generate(self, context):
116
+ return self._get_pattern_at_time(context.time / 60)
117
+
118
+
119
+ class SawToothMethod(PatternMethod):
120
+ name = "sawtooth"
121
+
122
+ def __init__(self, duty_cycle=0.2, bar_speed=1, period=30, inverse=False, **kwargs):
123
+ """
124
+ :param duty_cycle: fraction of time spent on (float 0-1), and consequently fraction of
125
+ vertical axis containing "on" pixels
126
+ :param bar_speed: speed in um/min
127
+ :param period: period in um
128
+ """
129
+ super().__init__(**kwargs)
130
+
131
+ if bar_speed == 0:
132
+ raise ValueError("bar_speed must be non-zero")
133
+ self.duty_cycle = duty_cycle
134
+ self.bar_speed = bar_speed # um/min; negative moves the ramp the other way
135
+ self.period_space = period # in um
136
+ self.inverse = inverse
137
+
138
+ @property
139
+ def period_time(self) -> float:
140
+ return self.period_space / abs(self.bar_speed)
141
+
142
+ def generate(self, context):
143
+ t = context.time / 60
144
+
145
+ _xx, yy = self.get_um_meshgrid()
146
+
147
+ is_on = _bar_is_on(yy, t, self.bar_speed, self.period_space, self.duty_cycle)
148
+
149
+ val = ((t - (yy / self.bar_speed)) % self.period_time) / (
150
+ self.duty_cycle * self.period_time
151
+ )
152
+
153
+ if not self.inverse:
154
+ val = 1 - val
155
+
156
+ pattern_out = (is_on * val).astype(np.float16)
157
+
158
+ return pattern_out
159
+
160
+
161
+ class BouncingBarPattern(BarPattern):
162
+ name = "bar_bounce"
163
+
164
+ def __init__(self, duty_cycle=0.2, bar_speed=1, period=30, t_loop=60, **kwargs):
165
+ """
166
+
167
+ :param duty_cycle: fraction of time spent on (float 0-1), and consequently fraction of
168
+ vertical axis containing "on" pixels
169
+ :param bar_speed: speed in um/min
170
+ :param period: period in um
171
+ :param t_loop: period of reversal (there and back) in minutes
172
+ """
173
+ super().__init__(
174
+ duty_cycle=duty_cycle, bar_speed=bar_speed, period=period, **kwargs
175
+ )
176
+ self.t_loop_s = t_loop * 60
177
+
178
+ def generate(self, context):
179
+ t = context.time
180
+ t = t % self.t_loop_s
181
+
182
+ halfway = self.t_loop_s / 2
183
+
184
+ if t > halfway:
185
+ t = halfway - (t - halfway)
186
+
187
+ return self._get_pattern_at_time(t / 60)
188
+
189
+
190
+ class RotatingBarPattern(PatternMethod):
191
+ name = "rotate_bar"
192
+ zoo_meta = ZooMeta(
193
+ source="mdck",
194
+ kwargs={"num_bars": 12, "angular_velocity": 2.0, "bar_width": 20},
195
+ title="Rotating Bar",
196
+ description="Spoke-like bars rotating around the center of the field.",
197
+ )
198
+
199
+ def __init__(
200
+ self,
201
+ num_bars: int = 5,
202
+ angular_velocity: float = 1.0,
203
+ bar_width: float = 20,
204
+ angular_velocity_rad: float | None = None,
205
+ **kwargs,
206
+ ):
207
+ """
208
+ Directs a specified number of bars with fixed width to rotate around the center of the
209
+ camera view at a specified speed. Note that the default speed is in units of um/min. This
210
+ is based on the angular velocity of a point on the bar 100um out from the center. To use rad/min,
211
+ specify angular_velocity_rad
212
+
213
+ :param num_bars: number of bars sticking outwards from the center
214
+ :param angular_velocity: um/min speed of a point on the bar 100um from the center. Can be overwritten
215
+ by angular_velocity_rad
216
+ :param bar_width: um width of the bar
217
+ """
218
+
219
+ super().__init__(**kwargs)
220
+
221
+ self.num_bars = num_bars
222
+ self.angular_velocity = angular_velocity
223
+ self.bar_width = bar_width
224
+ self.angular_velocity_rad = angular_velocity_rad
225
+
226
+ if not self.angular_velocity_rad:
227
+ self.angular_velocity_rad = self.angular_velocity / 100.0
228
+
229
+ def generate(self, context) -> np.ndarray:
230
+ t = context.time / 60.0
231
+
232
+ xx, yy = self.get_um_meshgrid()
233
+ center_x, center_y = self.center_um()
234
+
235
+ xx = xx - center_x
236
+ yy = yy - center_y
237
+
238
+ output = xx * 0.0
239
+
240
+ for spoke_n in range(self.num_bars):
241
+ angles_between = 2 * np.pi / self.num_bars
242
+ spoke_theta = spoke_n * angles_between + self.angular_velocity_rad * t
243
+
244
+ spoke_x = np.cos(spoke_theta)
245
+ spoke_y = np.sin(spoke_theta)
246
+
247
+ projection_mag = xx * spoke_x + yy * spoke_y
248
+ projection_x = projection_mag * spoke_x
249
+ projection_y = projection_mag * spoke_y
250
+
251
+ projection_distance = np.sqrt(
252
+ (xx - projection_x) ** 2 + (yy - projection_y) ** 2
253
+ )
254
+
255
+ output += (projection_mag > 0) & (
256
+ np.abs(projection_distance) < (self.bar_width / 2)
257
+ )
258
+
259
+ return output > 0