Skip to content

Multi-Dimensional Acquisition#

The mda attribute on the CMMCorePlus object provides a high-level interface for running multi-dimensional microscopy experiments.

pymmcore_plus.mda.MDARunner #

Object that executes a multi-dimensional experiment using an MDAEngine.

This object is available at CMMCorePlus.mda.

This is the main object that runs a multi-dimensional experiment; it does so by driving an acquisition engine that implements the PMDAEngine protocol. It emits signals at specific times during the experiment (see PMDASignaler for details on the signals that are available to connect to and when they are emitted).

Source code in pymmcore_plus/mda/_runner.py
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
class MDARunner:
    """Object that executes a multi-dimensional experiment using an MDAEngine.

    This object is available at [`CMMCorePlus.mda`][pymmcore_plus.CMMCorePlus.mda].

    This is the main object that runs a multi-dimensional experiment; it does so by
    driving an acquisition engine that implements the
    [`PMDAEngine`][pymmcore_plus.mda.PMDAEngine] protocol.  It emits signals at specific
    times during the experiment (see
    [`PMDASignaler`][pymmcore_plus.mda.events.PMDASignaler] for details on the signals
    that are available to connect to and when they are emitted).
    """

    def __init__(self) -> None:
        self._engine: PMDAEngine | None = None
        self._signals = _get_auto_MDA_callback_class()()
        self._running = False
        self._paused = False
        self._paused_time: float = 0
        self._pause_interval: float = 0.1  # sec to wait between checking pause state

        self._canceled = False
        self._sequence: MDASequence | None = None
        # timer for the full sequence, reset only once at the beginning of the sequence
        self._sequence_t0: float = 0.0
        # event clock, reset whenever `event.reset_event_timer` is True
        self._t0: float = 0.0

    def set_engine(self, engine: PMDAEngine) -> PMDAEngine | None:
        """Set the [`PMDAEngine`][pymmcore_plus.mda.PMDAEngine] to use for the MDA run."""  # noqa: E501
        # MagicMock on py312 no longer satisfies isinstance ... so we explicitly
        # allow it here just for the sake of testing.
        if not isinstance(engine, (PMDAEngine, MagicMock)):
            raise TypeError("Engine does not conform to the Engine protocol.")

        if self.is_running():  # pragma: no cover
            raise RuntimeError(
                "Cannot register a new engine when the current engine is running "
                "an acquisition. Please cancel the current engine's acquisition "
                "before registering"
            )

        old_engine, self._engine = self._engine, engine
        return old_engine

    # NOTE:
    # this return annotation is a lie, since the user can set it to their own engine.
    # but in MOST cases, this is the engine that will be used by default, so it's
    # convenient for IDEs to point to this rather than the abstract protocol.
    @property
    def engine(self) -> MDAEngine | None:
        """The [`PMDAEngine`][pymmcore_plus.mda.PMDAEngine] that is currently being used."""  # noqa: E501
        return self._engine  # type: ignore

    @property
    def events(self) -> PMDASignaler:
        """Signals that are emitted during the MDA run.

        See [`PMDASignaler`][pymmcore_plus.mda.PMDASignaler] for details on the
        signals that are available to connect to.
        """
        return self._signals

    def is_running(self) -> bool:
        """Return True if an acquisition is currently underway.

        This will return True at any point between the emission of the
        [`sequenceStarted`][pymmcore_plus.mda.PMDASignaler.sequenceStarted] and
        [`sequenceFinished`][pymmcore_plus.mda.PMDASignaler.sequenceFinished] signals,
        including when the acquisition is currently paused.

        Returns
        -------
        bool
            Whether an acquisition is underway.
        """
        return self._running

    def is_paused(self) -> bool:
        """Return True if the acquisition is currently paused.

        Use `toggle_pause` to change the paused state.

        Returns
        -------
        bool
            Whether the current acquisition is paused.
        """
        return self._paused

    def cancel(self) -> None:
        """Cancel the currently running acquisition.

        This is a no-op if no acquisition is currently running.
        If an acquisition is running then this will cancel the acquisition and
        a sequenceCanceled signal, followed by a sequenceFinished signal will
        be emitted.
        """
        self._canceled = True
        self._paused_time = 0

    def toggle_pause(self) -> None:
        """Toggle the paused state of the current acquisition.

        To get whether the acquisition is currently paused use the
        [`is_paused`][pymmcore_plus.mda.MDARunner.is_paused] method. This method is a
        no-op if no acquisition is currently underway.
        """
        if self.is_running():
            self._paused = not self._paused
            self._signals.sequencePauseToggled.emit(self._paused)

    def run(
        self,
        events: Iterable[MDAEvent],
        *,
        output: SingleOutput | Sequence[SingleOutput] | None = None,
    ) -> None:
        """Run the multi-dimensional acquisition defined by `sequence`.

        Most users should not use this directly as it will block further
        execution. Instead, use the
        [`CMMCorePlus.run_mda`][pymmcore_plus.CMMCorePlus.run_mda] method which will
        run on a thread.

        Parameters
        ----------
        events : Iterable[MDAEvent]
            An iterable of `useq.MDAEvents` objects to execute.
        output : SingleOutput | Sequence[SingleOutput] | None, optional
            The output handler(s) to use.  If None, no output will be saved.
            The value may be either a single output or a sequence of outputs,
            where a "single output" can be any of the following:

            - A string or Path to a directory to save images to. A handler will be
                created automatically based on the extension of the path.
                - `.zarr` files will be handled by `OMEZarrWriter`
                - `.ome.tiff` files will be handled by `OMETiffWriter`
                - A directory with no extension will be handled by `ImageSequenceWriter`
            - A handler object that implements the `DataHandler` protocol, currently
                meaning it has a `frameReady` method.  See `mda_listeners_connected`
                for more details.
        """
        error = None
        sequence = events if isinstance(events, MDASequence) else GeneratorMDASequence()
        with self._outputs_connected(output):
            # NOTE: it's important that `_prepare_to_run` and `_finish_run` are
            # called inside the context manager, since the `mda_listeners_connected`
            # context manager expects to see both of those signals.
            try:
                engine = self._prepare_to_run(sequence)
                self._run(engine, events)
            except Exception as e:
                error = e
            with exceptions_logged():
                self._finish_run(sequence)
        if error is not None:
            raise error

    def seconds_elapsed(self) -> float:
        """Return the number of seconds since the start of the acquisition."""
        return time.perf_counter() - self._sequence_t0

    def event_seconds_elapsed(self) -> float:
        """Return the number of seconds on the "event clock".

        This is the time since either the start of the acquisition or the last
        event with `reset_event_timer` set to `True`.
        """
        return time.perf_counter() - self._t0

    def _outputs_connected(
        self, output: SingleOutput | Sequence[SingleOutput] | None
    ) -> AbstractContextManager:
        """Context in which output handlers are connected to the frameReady signal."""
        if output is None:
            return nullcontext()

        if isinstance(output, (str, Path)) or not isinstance(output, Sequence):
            output = [output]

        # convert all items to handler objects
        handlers: list[Any] = []
        for item in output:
            if isinstance(item, (str, Path)):
                handlers.append(self._handler_for_path(item))
            else:
                # TODO: better check for valid handler protocol
                # quick hack for now.
                if not hasattr(item, "frameReady"):
                    raise TypeError(
                        "Output handlers must have a frameReady method. "
                        f"Got {item} with type {type(item)}."
                    )
                handlers.append(item)

        return mda_listeners_connected(*handlers, mda_events=self._signals)

    def _handler_for_path(self, path: str | Path) -> object:
        """Convert a string or Path into a handler object.

        This method picks from the built-in handlers based on the extension of the path.
        """
        path = str(Path(path).expanduser().resolve())
        if path.endswith(".zarr"):
            from pymmcore_plus.mda.handlers import OMEZarrWriter

            return OMEZarrWriter(path)

        if path.endswith((".tiff", ".tif")):
            from pymmcore_plus.mda.handlers import OMETiffWriter

            return OMETiffWriter(path)

        # FIXME: ugly hack for the moment to represent a non-existent directory
        # there are many features that ImageSequenceWriter supports, and it's unclear
        # how to infer them all from a single string.
        if not (Path(path).suffix or Path(path).exists()):
            from pymmcore_plus.mda.handlers import ImageSequenceWriter

            return ImageSequenceWriter(path)

        raise ValueError(f"Could not infer a writer handler for path: '{path}'")

    def _run(self, engine: PMDAEngine, events: Iterable[MDAEvent]) -> None:
        """Main execution of events, inside the try/except block of `run`."""
        teardown_event = getattr(engine, "teardown_event", lambda e: None)
        event_iterator = getattr(engine, "event_iterator", iter)
        _events: Iterator[MDAEvent] = event_iterator(events)
        self._reset_event_timer()
        self._sequence_t0 = self._t0

        for event in _events:
            if event.reset_event_timer:
                self._reset_event_timer()
            # If cancelled break out of the loop
            if self._wait_until_event(event) or not self._running:
                break

            self._signals.eventStarted.emit(event)
            logger.info("%s", event)
            engine.setup_event(event)

            try:
                runner_time_ms = self.seconds_elapsed() * 1000
                # this is a bit of a hack to pass the time into the engine
                # it is used for intra-event time calculations inside the engine.
                # we pop it off after the event is executed.
                event.metadata["runner_t0"] = self._sequence_t0
                output = engine.exec_event(event) or ()  # in case output is None
                for payload in output:
                    img, event, meta = payload
                    event.metadata.pop("runner_t0", None)
                    # if the engine calculated its own time, don't overwrite it
                    if "runner_time_ms" not in meta:
                        meta["runner_time_ms"] = runner_time_ms
                    with exceptions_logged():
                        self._signals.frameReady.emit(img, event, meta)
            finally:
                teardown_event(event)

    def _prepare_to_run(self, sequence: MDASequence) -> PMDAEngine:
        """Set up for the MDA run.

        Parameters
        ----------
        sequence : MDASequence
            The sequence of events to run.
        """
        if not self._engine:  # pragma: no cover
            raise RuntimeError("No MDAEngine set.")

        self._running = True
        self._paused = False
        self._paused_time = 0.0
        self._sequence = sequence

        meta = self._engine.setup_sequence(sequence)
        self._signals.sequenceStarted.emit(sequence, meta or {})
        logger.info("MDA Started: %s", sequence)
        return self._engine

    def _reset_event_timer(self) -> None:
        self._t0 = time.perf_counter()  # reference time, in seconds

    def _check_canceled(self) -> bool:
        """Return True if the cancel method has been called and emit relevant signals.

        If cancelled, this relies on the `self._sequence` being the current sequence
        in order to emit a `sequenceCanceled` signal.

        Returns
        -------
        bool
            Whether the MDA has been canceled.
        """
        if self._canceled:
            logger.warning("MDA Canceled: %s", self._sequence)
            self._signals.sequenceCanceled.emit(self._sequence)
            self._canceled = False
            return True
        return False

    def _wait_until_event(self, event: MDAEvent) -> bool:
        """Wait until the event's min start time, checking for pauses cancellations.

        Parameters
        ----------
        event : MDAEvent
            The event to wait for.

        Returns
        -------
        bool
            Whether the MDA was cancelled while waiting.
        """
        if not self.is_running():
            return False  # pragma: no cover
        if self._check_canceled():
            return True
        while self.is_paused() and not self._canceled:
            self._paused_time += self._pause_interval  # fixme: be more precise
            time.sleep(self._pause_interval)

            if self._check_canceled():
                return True

        # FIXME: this is actually the only place where the runner assumes our event is
        # an MDAevent.  For everything else, the engine is technically the only thing
        # that cares about the event time.
        # So this whole method could potentially be moved to the engine.
        if event.min_start_time:
            go_at = event.min_start_time + self._paused_time
            # We need to enter a loop here checking paused and canceled.
            # otherwise you'll potentially wait a long time to cancel
            remaining_wait_time = go_at - self.event_seconds_elapsed()
            while remaining_wait_time > 0:
                self._signals.awaitingEvent.emit(event, remaining_wait_time)
                while self._paused and not self._canceled:
                    self._paused_time += self._pause_interval  # fixme: be more precise
                    remaining_wait_time += self._pause_interval
                    time.sleep(self._pause_interval)

                if self._canceled:
                    break
                time.sleep(min(remaining_wait_time, 0.5))
                remaining_wait_time = go_at - self.event_seconds_elapsed()

        # check canceled again in case it was canceled
        # during the waiting loop
        return self._check_canceled()

    def _finish_run(self, sequence: MDASequence) -> None:
        """To be called at the end of an acquisition.

        Parameters
        ----------
        sequence : MDASequence
            The sequence that was finished.
        """
        self._running = False
        self._canceled = False

        if hasattr(self._engine, "teardown_sequence"):
            self._engine.teardown_sequence(sequence)  # type: ignore

        logger.info("MDA Finished: %s", sequence)
        self._signals.sequenceFinished.emit(sequence)

cancel() -> None #

Cancel the currently running acquisition.

This is a no-op if no acquisition is currently running. If an acquisition is running then this will cancel the acquisition and a sequenceCanceled signal, followed by a sequenceFinished signal will be emitted.

Source code in pymmcore_plus/mda/_runner.py
140
141
142
143
144
145
146
147
148
149
def cancel(self) -> None:
    """Cancel the currently running acquisition.

    This is a no-op if no acquisition is currently running.
    If an acquisition is running then this will cancel the acquisition and
    a sequenceCanceled signal, followed by a sequenceFinished signal will
    be emitted.
    """
    self._canceled = True
    self._paused_time = 0

engine() -> MDAEngine | None property #

The PMDAEngine that is currently being used.

Source code in pymmcore_plus/mda/_runner.py
 99
100
101
102
@property
def engine(self) -> MDAEngine | None:
    """The [`PMDAEngine`][pymmcore_plus.mda.PMDAEngine] that is currently being used."""  # noqa: E501
    return self._engine  # type: ignore

event_seconds_elapsed() -> float #

Return the number of seconds on the "event clock".

This is the time since either the start of the acquisition or the last event with reset_event_timer set to True.

Source code in pymmcore_plus/mda/_runner.py
213
214
215
216
217
218
219
def event_seconds_elapsed(self) -> float:
    """Return the number of seconds on the "event clock".

    This is the time since either the start of the acquisition or the last
    event with `reset_event_timer` set to `True`.
    """
    return time.perf_counter() - self._t0

events() -> PMDASignaler property #

Signals that are emitted during the MDA run.

See PMDASignaler for details on the signals that are available to connect to.

Source code in pymmcore_plus/mda/_runner.py
104
105
106
107
108
109
110
111
@property
def events(self) -> PMDASignaler:
    """Signals that are emitted during the MDA run.

    See [`PMDASignaler`][pymmcore_plus.mda.PMDASignaler] for details on the
    signals that are available to connect to.
    """
    return self._signals

is_paused() -> bool #

Return True if the acquisition is currently paused.

Use toggle_pause to change the paused state.

Returns:

Type Description
bool

Whether the current acquisition is paused.

Source code in pymmcore_plus/mda/_runner.py
128
129
130
131
132
133
134
135
136
137
138
def is_paused(self) -> bool:
    """Return True if the acquisition is currently paused.

    Use `toggle_pause` to change the paused state.

    Returns
    -------
    bool
        Whether the current acquisition is paused.
    """
    return self._paused

is_running() -> bool #

Return True if an acquisition is currently underway.

This will return True at any point between the emission of the sequenceStarted and sequenceFinished signals, including when the acquisition is currently paused.

Returns:

Type Description
bool

Whether an acquisition is underway.

Source code in pymmcore_plus/mda/_runner.py
113
114
115
116
117
118
119
120
121
122
123
124
125
126
def is_running(self) -> bool:
    """Return True if an acquisition is currently underway.

    This will return True at any point between the emission of the
    [`sequenceStarted`][pymmcore_plus.mda.PMDASignaler.sequenceStarted] and
    [`sequenceFinished`][pymmcore_plus.mda.PMDASignaler.sequenceFinished] signals,
    including when the acquisition is currently paused.

    Returns
    -------
    bool
        Whether an acquisition is underway.
    """
    return self._running

run(events: Iterable[MDAEvent], *, output: SingleOutput | Sequence[SingleOutput] | None = None) -> None #

Run the multi-dimensional acquisition defined by sequence.

Most users should not use this directly as it will block further execution. Instead, use the CMMCorePlus.run_mda method which will run on a thread.

Parameters:

Name Type Description Default
events Iterable[MDAEvent]

An iterable of useq.MDAEvents objects to execute.

required
output SingleOutput | Sequence[SingleOutput] | None, optional

The output handler(s) to use. If None, no output will be saved. The value may be either a single output or a sequence of outputs, where a "single output" can be any of the following:

  • A string or Path to a directory to save images to. A handler will be created automatically based on the extension of the path.
  • .zarr files will be handled by OMEZarrWriter
  • .ome.tiff files will be handled by OMETiffWriter
  • A directory with no extension will be handled by ImageSequenceWriter
  • A handler object that implements the DataHandler protocol, currently meaning it has a frameReady method. See mda_listeners_connected for more details.
None
Source code in pymmcore_plus/mda/_runner.py
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
def run(
    self,
    events: Iterable[MDAEvent],
    *,
    output: SingleOutput | Sequence[SingleOutput] | None = None,
) -> None:
    """Run the multi-dimensional acquisition defined by `sequence`.

    Most users should not use this directly as it will block further
    execution. Instead, use the
    [`CMMCorePlus.run_mda`][pymmcore_plus.CMMCorePlus.run_mda] method which will
    run on a thread.

    Parameters
    ----------
    events : Iterable[MDAEvent]
        An iterable of `useq.MDAEvents` objects to execute.
    output : SingleOutput | Sequence[SingleOutput] | None, optional
        The output handler(s) to use.  If None, no output will be saved.
        The value may be either a single output or a sequence of outputs,
        where a "single output" can be any of the following:

        - A string or Path to a directory to save images to. A handler will be
            created automatically based on the extension of the path.
            - `.zarr` files will be handled by `OMEZarrWriter`
            - `.ome.tiff` files will be handled by `OMETiffWriter`
            - A directory with no extension will be handled by `ImageSequenceWriter`
        - A handler object that implements the `DataHandler` protocol, currently
            meaning it has a `frameReady` method.  See `mda_listeners_connected`
            for more details.
    """
    error = None
    sequence = events if isinstance(events, MDASequence) else GeneratorMDASequence()
    with self._outputs_connected(output):
        # NOTE: it's important that `_prepare_to_run` and `_finish_run` are
        # called inside the context manager, since the `mda_listeners_connected`
        # context manager expects to see both of those signals.
        try:
            engine = self._prepare_to_run(sequence)
            self._run(engine, events)
        except Exception as e:
            error = e
        with exceptions_logged():
            self._finish_run(sequence)
    if error is not None:
        raise error

seconds_elapsed() -> float #

Return the number of seconds since the start of the acquisition.

Source code in pymmcore_plus/mda/_runner.py
209
210
211
def seconds_elapsed(self) -> float:
    """Return the number of seconds since the start of the acquisition."""
    return time.perf_counter() - self._sequence_t0

set_engine(engine: PMDAEngine) -> PMDAEngine | None #

Set the PMDAEngine to use for the MDA run.

Source code in pymmcore_plus/mda/_runner.py
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
def set_engine(self, engine: PMDAEngine) -> PMDAEngine | None:
    """Set the [`PMDAEngine`][pymmcore_plus.mda.PMDAEngine] to use for the MDA run."""  # noqa: E501
    # MagicMock on py312 no longer satisfies isinstance ... so we explicitly
    # allow it here just for the sake of testing.
    if not isinstance(engine, (PMDAEngine, MagicMock)):
        raise TypeError("Engine does not conform to the Engine protocol.")

    if self.is_running():  # pragma: no cover
        raise RuntimeError(
            "Cannot register a new engine when the current engine is running "
            "an acquisition. Please cancel the current engine's acquisition "
            "before registering"
        )

    old_engine, self._engine = self._engine, engine
    return old_engine

toggle_pause() -> None #

Toggle the paused state of the current acquisition.

To get whether the acquisition is currently paused use the is_paused method. This method is a no-op if no acquisition is currently underway.

Source code in pymmcore_plus/mda/_runner.py
151
152
153
154
155
156
157
158
159
160
def toggle_pause(self) -> None:
    """Toggle the paused state of the current acquisition.

    To get whether the acquisition is currently paused use the
    [`is_paused`][pymmcore_plus.mda.MDARunner.is_paused] method. This method is a
    no-op if no acquisition is currently underway.
    """
    if self.is_running():
        self._paused = not self._paused
        self._signals.sequencePauseToggled.emit(self._paused)

pymmcore_plus.mda.PMDAEngine #

Protocol that all MDA engines must implement.

event_iterator(events: Iterable[MDAEvent]) -> Iterator[MDAEvent] #

Wrapper on the event iterator.

Optional.

This can be used to wrap the event iterator to perform any event merging (e.g. if the engine supports HardwareSequencing) or event modification. The default implementation is just iter(events).

Be careful when using this method. It is powerful and can result in unexpected event iteration if used incorrectly.

exec_event(event: MDAEvent) -> Iterable[PImagePayload] abstractmethod #

Execute event.

This method is called after setup_event and is responsible for executing the event. The default assumption is to acquire an image, but more elaborate events will be possible.

The protocol for the returned object is still under development. However, if the returned object has an image attribute, then the MDARunner will emit a frameReady signal

setup_event(event: MDAEvent) -> None abstractmethod #

Prepare state of system (hardware, etc.) for event.

This method is called before each event in the sequence. It is responsible for preparing the state of the system for the event. The engine should be in a state where it can call exec_event without any additional preparation. (This means that the engine should perform any waits or blocks required for system state changes to complete.)

setup_sequence(sequence: MDASequence) -> SummaryMetaV1 | None abstractmethod #

Setup state of system (hardware, etc.) before an MDA is run.

This method is called once at the beginning of a sequence.

teardown_event(event: MDAEvent) -> None #

Teardown state of system (hardware, etc.) after event.

Optional.

If the engine provides this function, it will be called after exec_event to perform any cleanup or teardown required after the event has been executed.

teardown_sequence(sequence: MDASequence) -> None #

Perform any teardown required after the sequence has been executed.

Optional.

If the engine provides this function, it will be called after the last event in the sequence has been executed.

pymmcore_plus.mda.MDAEngine #

The default MDAengine that ships with pymmcore-plus.

This implements the PMDAEngine protocol, and uses a CMMCorePlus instance to control the hardware.

It may be subclassed to provide custom behavior, or to override specific methods. https://pymmcore-plus.github.io/pymmcore-plus/guides/custom_engine/

Attributes:

Name Type Description
mmcore CMMCorePlus

The CMMCorePlus instance to use for hardware control.

use_hardware_sequencing bool

Whether to use hardware sequencing if possible. If True, the engine will attempt to combine MDAEvents into a single SequencedEvent if core.canSequenceEvents() reports that the events can be sequenced. This can be set after instantiation. By default, this is True, however in various testing and demo scenarios, you may wish to set it to False in order to avoid unexpected behavior.

Source code in pymmcore_plus/mda/_engine.py
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
class MDAEngine(PMDAEngine):
    """The default MDAengine that ships with pymmcore-plus.

    This implements the [`PMDAEngine`][pymmcore_plus.mda.PMDAEngine] protocol, and
    uses a [`CMMCorePlus`][pymmcore_plus.CMMCorePlus] instance to control the hardware.

    It may be subclassed to provide custom behavior, or to override specific methods.
    <https://pymmcore-plus.github.io/pymmcore-plus/guides/custom_engine/>

    Attributes
    ----------
    mmcore: CMMCorePlus
        The `CMMCorePlus` instance to use for hardware control.
    use_hardware_sequencing : bool
        Whether to use hardware sequencing if possible. If `True`, the engine will
        attempt to combine MDAEvents into a single `SequencedEvent` if
        [`core.canSequenceEvents()`][pymmcore_plus.CMMCorePlus.canSequenceEvents]
        reports that the events can be sequenced. This can be set after instantiation.
        By default, this is `True`, however in various testing and demo scenarios, you
        may wish to set it to `False` in order to avoid unexpected behavior.
    """

    def __init__(self, mmc: CMMCorePlus, use_hardware_sequencing: bool = True) -> None:
        self._mmc = mmc
        self.use_hardware_sequencing: bool = use_hardware_sequencing

        # whether to include position metadata when fetching on-frame metadata
        # omitted by default when performing triggered acquisition because it's slow.
        self._include_frame_position_metadata: IncludePositionArg = "unsequenced-only"

        # used to check if the hardware autofocus is engaged when the sequence begins.
        # if it is, we will re-engage it after the autofocus action (if successful).
        self._af_was_engaged: bool = False
        # used to store the success of the last _execute_autofocus call
        self._af_succeeded: bool = False

        # used for one_shot autofocus to store the z correction for each position index.
        # map of {position_index: z_correction}
        self._z_correction: dict[int | None, float] = {}

        # This is used to determine whether we need to re-enable autoshutter after
        # the sequence is done (assuming a event.keep_shutter_open was requested)
        # Note: getAutoShutter() is True when no config is loaded at all
        self._autoshutter_was_set: bool = self._mmc.getAutoShutter()

        # -----
        # The following values are stored during setup_sequence simply to speed up
        # retrieval of metadata during each frame.
        # sequence of (device, property) of all properties used in any of the presets
        # in the channel group.
        self._config_device_props: dict[str, Sequence[tuple[str, str]]] = {}

    @property
    def include_frame_position_metadata(self) -> IncludePositionArg:
        return self._include_frame_position_metadata

    @include_frame_position_metadata.setter
    def include_frame_position_metadata(self, value: IncludePositionArg) -> None:
        if value not in (True, False, "unsequenced-only"):  # pragma: no cover
            raise ValueError(
                "include_frame_position_metadata must be True, False, or "
                "'unsequenced-only'"
            )
        self._include_frame_position_metadata = value

    @property
    def mmcore(self) -> CMMCorePlus:
        """The `CMMCorePlus` instance to use for hardware control."""
        return self._mmc

    # ===================== Protocol Implementation =====================

    def setup_sequence(self, sequence: MDASequence) -> SummaryMetaV1 | None:
        """Setup the hardware for the entire sequence."""
        # clear z_correction for new sequence
        self._z_correction.clear()

        if not self._mmc:  # pragma: no cover
            from pymmcore_plus.core import CMMCorePlus

            self._mmc = CMMCorePlus.instance()

        self._update_config_device_props()
        # get if the autofocus is engaged at the start of the sequence
        self._af_was_engaged = self._mmc.isContinuousFocusLocked()

        if px_size := self._mmc.getPixelSizeUm():
            self._update_grid_fov_sizes(px_size, sequence)

        self._autoshutter_was_set = self._mmc.getAutoShutter()
        return self.get_summary_metadata(mda_sequence=sequence)

    def get_summary_metadata(self, mda_sequence: MDASequence | None) -> SummaryMetaV1:
        return summary_metadata(self._mmc, mda_sequence=mda_sequence)

    def _update_grid_fov_sizes(self, px_size: float, sequence: MDASequence) -> None:
        *_, x_size, y_size = self._mmc.getROI()
        fov_width = x_size * px_size
        fov_height = y_size * px_size

        if sequence.grid_plan:
            sequence.grid_plan.fov_width = fov_width
            sequence.grid_plan.fov_height = fov_height

        # set fov to any stage positions sequences
        for p in sequence.stage_positions:
            if p.sequence and p.sequence.grid_plan:
                p.sequence.grid_plan.fov_height = fov_height
                p.sequence.grid_plan.fov_width = fov_width

    def setup_event(self, event: MDAEvent) -> None:
        """Set the system hardware (XY, Z, channel, exposure) as defined in the event.

        Parameters
        ----------
        event : MDAEvent
            The event to use for the Hardware config
        """
        if isinstance(event, SequencedEvent):
            self.setup_sequenced_event(event)
        else:
            self.setup_single_event(event)
        self._mmc.waitForSystem()

    def exec_event(self, event: MDAEvent) -> Iterable[PImagePayload]:
        """Execute an individual event and return the image data."""
        action = getattr(event, "action", None)
        if isinstance(action, HardwareAutofocus):
            # skip if no autofocus device is found
            if not self._mmc.getAutoFocusDevice():
                logger.warning("No autofocus device found. Cannot execute autofocus.")
                return

            try:
                # execute hardware autofocus
                new_correction = self._execute_autofocus(action)
                self._af_succeeded = True
            except RuntimeError as e:
                logger.warning("Hardware autofocus failed. %s", e)
                self._af_succeeded = False
            else:
                # store correction for this position index
                p_idx = event.index.get("p", None)
                self._z_correction[p_idx] = new_correction + self._z_correction.get(
                    p_idx, 0.0
                )
            return

        # if the autofocus was engaged at the start of the sequence AND autofocus action
        # did not fail, re-engage it. NOTE: we need to do that AFTER the runner calls
        # `setup_event`, so we can't do it inside the exec_event autofocus action above.
        if self._af_was_engaged and self._af_succeeded:
            self._mmc.enableContinuousFocus(True)

        if isinstance(event, SequencedEvent):
            yield from self.exec_sequenced_event(event)
        else:
            yield from self.exec_single_event(event)

    def event_iterator(self, events: Iterable[MDAEvent]) -> Iterator[MDAEvent]:
        """Event iterator that merges events for hardware sequencing if possible.

        This wraps `for event in events: ...` inside `MDARunner.run()` and combines
        sequenceable events into an instance of `SequencedEvent` if
        `self.use_hardware_sequencing` is `True`.
        """
        if not self.use_hardware_sequencing:
            yield from events
            return

        seq: list[MDAEvent] = []
        for event in events:
            # if the sequence is empty or the current event can be sequenced with the
            # previous event, add it to the sequence
            if not seq or self._mmc.canSequenceEvents(seq[-1], event, len(seq)):
                seq.append(event)
            else:
                # otherwise, yield a SequencedEvent if the sequence has accumulated
                # more than one event, otherwise yield the single event
                yield seq[0] if len(seq) == 1 else SequencedEvent.create(seq)
                # add this current event and start a new sequence
                seq = [event]
        # yield any remaining events
        if seq:
            yield seq[0] if len(seq) == 1 else SequencedEvent.create(seq)

    # ===================== Regular Events =====================

    def setup_single_event(self, event: MDAEvent) -> None:
        """Setup hardware for a single (non-sequenced) event.

        This method is not part of the PMDAEngine protocol (it is called by
        `setup_event`, which *is* part of the protocol), but it is made public
        in case a user wants to subclass this engine and override this method.
        """
        if event.keep_shutter_open:
            ...

        if event.x_pos is not None or event.y_pos is not None:
            self._set_event_position(event)
        if event.z_pos is not None:
            self._set_event_z(event)
        if event.slm_image is not None:
            self._set_event_slm_image(event)
        if event.channel is not None:
            try:
                # possible speedup by setting manually.
                self._mmc.setConfig(event.channel.group, event.channel.config)
            except Exception as e:
                logger.warning("Failed to set channel. %s", e)
        if event.exposure is not None:
            try:
                self._mmc.setExposure(event.exposure)
            except Exception as e:
                logger.warning("Failed to set exposure. %s", e)

        if (
            # (if autoshutter wasn't set at the beginning of the sequence
            # then it never matters...)
            self._autoshutter_was_set
            # if we want to leave the shutter open after this event, and autoshutter
            # is currently enabled...
            and event.keep_shutter_open
            and self._mmc.getAutoShutter()
        ):
            # we have to disable autoshutter and open the shutter
            self._mmc.setAutoShutter(False)
            self._mmc.setShutterOpen(True)

    def exec_single_event(self, event: MDAEvent) -> Iterator[PImagePayload]:
        """Execute a single (non-triggered) event and return the image data.

        This method is not part of the PMDAEngine protocol (it is called by
        `exec_event`, which *is* part of the protocol), but it is made public
        in case a user wants to subclass this engine and override this method.
        """
        if event.slm_image is not None:
            self._exec_event_slm_image(event.slm_image)

        try:
            self._mmc.snapImage()
            # taking event time after snapImage includes exposure time
            # not sure that's what we want, but it's currently consistent with the
            # timing of the sequenced event runner (where Elapsed_Time_ms is taken after
            # the image is acquired, not before the exposure starts)
            t0 = event.metadata.get("runner_t0") or time.perf_counter()
            event_time_ms = (time.perf_counter() - t0) * 1000
        except Exception as e:
            logger.warning("Failed to snap image. %s", e)
            return
        if not event.keep_shutter_open:
            self._mmc.setShutterOpen(False)

        # most cameras will only have a single channel
        # but Multi-camera may have multiple, and we need to retrieve a buffer for each
        for cam in range(self._mmc.getNumberOfCameraChannels()):
            meta = self.get_frame_metadata(
                event,
                runner_time_ms=event_time_ms,
                camera_device=self._mmc.getPhysicalCameraDevice(cam),
                include_position=self._include_frame_position_metadata is not False,
            )
            # Note, the third element is actually a MutableMapping, but mypy doesn't
            # see TypedDict as a subclass of MutableMapping yet.
            # https://github.com/python/mypy/issues/4976
            yield ImagePayload(self._mmc.getImage(cam), event, meta)  # type: ignore[misc]

    def get_frame_metadata(
        self,
        event: MDAEvent,
        prop_values: tuple[PropertyValue, ...] | None = None,
        runner_time_ms: float = 0.0,
        include_position: bool = True,
        camera_device: str | None = None,
    ) -> FrameMetaV1:
        if prop_values is None and (ch := event.channel):
            prop_values = self._get_current_props(ch.group)
        else:
            prop_values = ()
        return frame_metadata(
            self._mmc,
            cached=True,
            runner_time_ms=runner_time_ms,
            camera_device=camera_device,
            property_values=prop_values,
            mda_event=event,
            include_position=include_position,
        )

    def teardown_event(self, event: MDAEvent) -> None:
        """Teardown state of system (hardware, etc.) after `event`."""
        # autoshutter was set at the beginning of the sequence, and this event
        # doesn't want to leave the shutter open.  Re-enable autoshutter.
        core = self._mmc
        if not event.keep_shutter_open and self._autoshutter_was_set:
            core.setAutoShutter(True)
        # FIXME: this may not be hitting as intended...
        # https://github.com/pymmcore-plus/pymmcore-plus/pull/353#issuecomment-2159176491
        if isinstance(event, SequencedEvent):
            if event.exposure_sequence:
                core.stopExposureSequence(self._mmc.getCameraDevice())
            if event.x_sequence:
                core.stopXYStageSequence(core.getXYStageDevice())
            if event.z_sequence:
                core.stopStageSequence(core.getFocusDevice())
            for dev, prop in event.property_sequences(core):
                core.stopPropertySequence(dev, prop)

    def teardown_sequence(self, sequence: MDASequence) -> None:
        """Perform any teardown required after the sequence has been executed."""
        pass

    # ===================== Sequenced Events =====================

    def setup_sequenced_event(self, event: SequencedEvent) -> None:
        """Setup hardware for a sequenced (triggered) event.

        This method is not part of the PMDAEngine protocol (it is called by
        `setup_event`, which *is* part of the protocol), but it is made public
        in case a user wants to subclass this engine and override this method.
        """
        core = self._mmc
        cam_device = self._mmc.getCameraDevice()

        if event.exposure_sequence:
            with suppress(RuntimeError):
                core.stopExposureSequence(cam_device)
            core.loadExposureSequence(cam_device, event.exposure_sequence)
        if event.x_sequence:  # y_sequence is implied and will be the same length
            stage = core.getXYStageDevice()
            with suppress(RuntimeError):
                core.stopXYStageSequence(stage)
            core.loadXYStageSequence(stage, event.x_sequence, event.y_sequence)
        if event.z_sequence:
            zstage = core.getFocusDevice()
            with suppress(RuntimeError):
                core.stopStageSequence(zstage)
            core.loadStageSequence(zstage, event.z_sequence)
        if prop_seqs := event.property_sequences(core):
            for (dev, prop), value_sequence in prop_seqs.items():
                with suppress(RuntimeError):
                    core.stopPropertySequence(dev, prop)
                core.loadPropertySequence(dev, prop, value_sequence)

        if event.slm_image:
            self._set_event_slm_image(event)

        # preparing a Sequence while another is running is dangerous.
        if core.isSequenceRunning():
            self._await_sequence_acquisition()
        core.prepareSequenceAcquisition(cam_device)

        # start sequences or set non-sequenced values
        if event.x_sequence:
            core.startXYStageSequence(stage)
        elif event.x_pos is not None or event.y_pos is not None:
            self._set_event_position(event)

        if event.z_sequence:
            core.startStageSequence(zstage)
        elif event.z_pos is not None:
            self._set_event_z(event)

        if event.exposure_sequence:
            core.startExposureSequence(cam_device)
        elif event.exposure is not None:
            core.setExposure(event.exposure)

        if prop_seqs:
            for dev, prop in prop_seqs:
                core.startPropertySequence(dev, prop)
        elif event.channel is not None:
            core.setConfig(event.channel.group, event.channel.config)

    def _await_sequence_acquisition(
        self, timeout: float = 5.0, poll_interval: float = 0.2
    ) -> None:
        tot = 0.0
        self._mmc.stopSequenceAcquisition()
        while self._mmc.isSequenceRunning():
            time.sleep(poll_interval)
            tot += poll_interval
            if tot >= timeout:
                raise TimeoutError("Failed to stop running sequence")

    def post_sequence_started(self, event: SequencedEvent) -> None:
        """Perform any actions after startSequenceAcquisition has been called.

        This method is available to subclasses in case they need to perform any
        actions after a hardware-triggered sequence has been started (i.e. after
        core.startSequenceAcquisition has been called).

        The default implementation does nothing.
        """

    def exec_sequenced_event(self, event: SequencedEvent) -> Iterable[PImagePayload]:
        """Execute a sequenced (triggered) event and return the image data.

        This method is not part of the PMDAEngine protocol (it is called by
        `exec_event`, which *is* part of the protocol), but it is made public
        in case a user wants to subclass this engine and override this method.
        """
        n_events = len(event.events)

        t0 = event.metadata.get("runner_t0") or time.perf_counter()
        event_t0_ms = (time.perf_counter() - t0) * 1000

        if event.slm_image is not None:
            self._exec_event_slm_image(event.slm_image)

        # Start sequence
        # Note that the overload of startSequenceAcquisition that takes a camera
        # label does NOT automatically initialize a circular buffer.  So if this call
        # is changed to accept the camera in the future, that should be kept in mind.
        self._mmc.startSequenceAcquisition(
            n_events,
            0,  # intervalMS  # TODO: add support for this
            True,  # stopOnOverflow
        )
        self.post_sequence_started(event)

        n_channels = self._mmc.getNumberOfCameraChannels()
        count = 0
        iter_events = product(event.events, range(n_channels))
        # block until the sequence is done, popping images in the meantime
        while self._mmc.isSequenceRunning():
            if remaining := self._mmc.getRemainingImageCount():
                yield self._next_seqimg_payload(
                    *next(iter_events), remaining=remaining - 1, event_t0=event_t0_ms
                )
                count += 1
            else:
                time.sleep(0.001)

        if self._mmc.isBufferOverflowed():  # pragma: no cover
            raise MemoryError("Buffer overflowed")

        while remaining := self._mmc.getRemainingImageCount():
            yield self._next_seqimg_payload(
                *next(iter_events), remaining=remaining - 1, event_t0=event_t0_ms
            )
            count += 1

        # necessary?
        expected_images = n_events * n_channels
        if count != expected_images:
            logger.warning(
                "Unexpected number of images returned from sequence. "
                "Expected %s, got %s",
                expected_images,
                count,
            )

    def _next_seqimg_payload(
        self,
        event: MDAEvent,
        channel: int = 0,
        *,
        event_t0: float = 0.0,
        remaining: int = 0,
    ) -> PImagePayload:
        """Grab next image from the circular buffer and return it as an ImagePayload."""
        _slice = 0  # ?
        img, mm_meta = self._mmc.popNextImageAndMD(channel, _slice)
        try:
            seq_time = float(mm_meta.get(Keyword.Elapsed_Time_ms))
        except Exception:
            seq_time = 0.0
        try:
            # note, when present in circular buffer meta, this key is called "Camera".
            # It's NOT actually Keyword.CoreCamera (but it's the same value)
            # it is hardcoded in various places in mmCoreAndDevices, see:
            # see: https://github.com/micro-manager/mmCoreAndDevices/pull/468
            camera_device = mm_meta.GetSingleTag("Camera").GetValue()
        except Exception:
            camera_device = self._mmc.getPhysicalCameraDevice(channel)

        # TODO: determine whether we want to try to populate changing property values
        # during the course of a triggered sequence
        meta = self.get_frame_metadata(
            event,
            prop_values=(),
            runner_time_ms=event_t0 + seq_time,
            camera_device=camera_device,
            include_position=self._include_frame_position_metadata is True,
        )
        meta["hardware_triggered"] = True
        meta["images_remaining_in_buffer"] = remaining
        meta["camera_metadata"] = dict(mm_meta)

        # https://github.com/python/mypy/issues/4976
        return ImagePayload(img, event, meta)  # type: ignore[return-value]

    # ===================== EXTRA =====================

    def _execute_autofocus(self, action: HardwareAutofocus) -> float:
        """Perform the hardware autofocus.

        Returns the change in ZPosition that occurred during the autofocus event.
        """
        # switch off autofocus device if it is on
        self._mmc.enableContinuousFocus(False)

        if action.autofocus_motor_offset is not None:
            # set the autofocus device offset
            # if name is given explicitly, use it, otherwise use setAutoFocusOffset
            # (see docs for setAutoFocusOffset for additional details)
            if name := getattr(action, "autofocus_device_name", None):
                self._mmc.setPosition(name, action.autofocus_motor_offset)
            else:
                self._mmc.setAutoFocusOffset(action.autofocus_motor_offset)
            self._mmc.waitForSystem()

        @retry(exceptions=RuntimeError, tries=action.max_retries, logger=logger.warning)
        def _perform_full_focus(previous_z: float) -> float:
            self._mmc.fullFocus()
            self._mmc.waitForSystem()
            return self._mmc.getZPosition() - previous_z

        return _perform_full_focus(self._mmc.getZPosition())

    def _set_event_position(self, event: MDAEvent) -> None:
        # skip if no XY stage device is found
        if not self._mmc.getXYStageDevice():
            logger.warning("No XY stage device found. Cannot set XY position.")
            return

        x = event.x_pos if event.x_pos is not None else self._mmc.getXPosition()
        y = event.y_pos if event.y_pos is not None else self._mmc.getYPosition()
        self._mmc.setXYPosition(x, y)

    def _set_event_z(self, event: MDAEvent) -> None:
        # skip if no Z stage device is found
        if not self._mmc.getFocusDevice():
            logger.warning("No Z stage device found. Cannot set Z position.")
            return

        p_idx = event.index.get("p", None)
        correction = self._z_correction.setdefault(p_idx, 0.0)
        self._mmc.setZPosition(cast("float", event.z_pos) + correction)

    def _set_event_slm_image(self, event: MDAEvent) -> None:
        if not event.slm_image:
            return
        try:
            # Get the SLM device
            if not (
                slm_device := event.slm_image.device or self._mmc.getSLMDevice()
            ):  # pragma: no cover
                raise ValueError("No SLM device found or specified.")

            # cast to numpy array
            slm_array = np.asarray(event.slm_image)
            # if it's a single value, we can just set all pixels to that value
            if slm_array.ndim == 0:
                value = slm_array.item()
                if isinstance(value, bool):
                    dev_name = self._mmc.getDeviceName(slm_device)
                    on_value = _SLM_DEVICES_PIXEL_ON_VALUES.get(dev_name, 1)
                    value = on_value if value else 0
                self._mmc.setSLMPixelsTo(slm_device, int(value))
            elif slm_array.size == 3:
                # if it's a 3-valued array, we assume it's RGB
                r, g, b = slm_array.astype(int)
                self._mmc.setSLMPixelsTo(slm_device, r, g, b)
            elif slm_array.ndim in (2, 3):
                # if it's a 2D/3D array, we assume it's an image
                # where 3D is RGB with shape (h, w, 3)
                if slm_array.ndim == 3 and slm_array.shape[2] != 3:
                    raise ValueError(  # pragma: no cover
                        "SLM image must be 2D or 3D with 3 channels (RGB)."
                    )
                # convert boolean on/off values to pixel values
                if slm_array.dtype == bool:
                    dev_name = self._mmc.getDeviceName(slm_device)
                    on_value = _SLM_DEVICES_PIXEL_ON_VALUES.get(dev_name, 1)
                    slm_array = np.where(slm_array, on_value, 0).astype(np.uint8)
                self._mmc.setSLMImage(slm_device, slm_array)
            if event.slm_image.exposure:
                self._mmc.setSLMExposure(slm_device, event.slm_image.exposure)
        except Exception as e:
            logger.warning("Failed to set SLM Image: %s", e)

    def _exec_event_slm_image(self, img: useq.SLMImage) -> None:
        if slm_device := (img.device or self._mmc.getSLMDevice()):
            try:
                self._mmc.displaySLMImage(slm_device)
            except Exception as e:
                logger.warning("Failed to set SLM Image: %s", e)

    def _update_config_device_props(self) -> None:
        # store devices/props that make up each config group for faster lookup
        self._config_device_props.clear()
        for grp in self._mmc.getAvailableConfigGroups():
            for preset in self._mmc.getAvailableConfigs(grp):
                # ordered/unique list of (device, property) tuples for each group
                self._config_device_props[grp] = tuple(
                    {(i[0], i[1]): None for i in self._mmc.getConfigData(grp, preset)}
                )

    def _get_current_props(self, *groups: str) -> tuple[PropertyValue, ...]:
        """Faster version of core.getConfigGroupState(group).

        MMCore does some excess iteration that we want to avoid here. It calls
        GetAvailableConfigs and then calls getConfigData for *every* preset in the
        group, (not only the one being requested).  We go straight to cached data
        for the group we want.
        """
        return tuple(
            {
                "dev": dev,
                "prop": prop,
                "val": self._mmc.getPropertyFromCache(dev, prop),
            }
            for group in groups
            if (dev_props := self._config_device_props.get(group))
            for dev, prop in dev_props
        )

use_hardware_sequencing: bool = use_hardware_sequencing instance-attribute #

event_iterator(events: Iterable[MDAEvent]) -> Iterator[MDAEvent] #

Event iterator that merges events for hardware sequencing if possible.

This wraps for event in events: ... inside MDARunner.run() and combines sequenceable events into an instance of SequencedEvent if self.use_hardware_sequencing is True.

Source code in pymmcore_plus/mda/_engine.py
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
def event_iterator(self, events: Iterable[MDAEvent]) -> Iterator[MDAEvent]:
    """Event iterator that merges events for hardware sequencing if possible.

    This wraps `for event in events: ...` inside `MDARunner.run()` and combines
    sequenceable events into an instance of `SequencedEvent` if
    `self.use_hardware_sequencing` is `True`.
    """
    if not self.use_hardware_sequencing:
        yield from events
        return

    seq: list[MDAEvent] = []
    for event in events:
        # if the sequence is empty or the current event can be sequenced with the
        # previous event, add it to the sequence
        if not seq or self._mmc.canSequenceEvents(seq[-1], event, len(seq)):
            seq.append(event)
        else:
            # otherwise, yield a SequencedEvent if the sequence has accumulated
            # more than one event, otherwise yield the single event
            yield seq[0] if len(seq) == 1 else SequencedEvent.create(seq)
            # add this current event and start a new sequence
            seq = [event]
    # yield any remaining events
    if seq:
        yield seq[0] if len(seq) == 1 else SequencedEvent.create(seq)

exec_event(event: MDAEvent) -> Iterable[PImagePayload] #

Execute an individual event and return the image data.

Source code in pymmcore_plus/mda/_engine.py
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
def exec_event(self, event: MDAEvent) -> Iterable[PImagePayload]:
    """Execute an individual event and return the image data."""
    action = getattr(event, "action", None)
    if isinstance(action, HardwareAutofocus):
        # skip if no autofocus device is found
        if not self._mmc.getAutoFocusDevice():
            logger.warning("No autofocus device found. Cannot execute autofocus.")
            return

        try:
            # execute hardware autofocus
            new_correction = self._execute_autofocus(action)
            self._af_succeeded = True
        except RuntimeError as e:
            logger.warning("Hardware autofocus failed. %s", e)
            self._af_succeeded = False
        else:
            # store correction for this position index
            p_idx = event.index.get("p", None)
            self._z_correction[p_idx] = new_correction + self._z_correction.get(
                p_idx, 0.0
            )
        return

    # if the autofocus was engaged at the start of the sequence AND autofocus action
    # did not fail, re-engage it. NOTE: we need to do that AFTER the runner calls
    # `setup_event`, so we can't do it inside the exec_event autofocus action above.
    if self._af_was_engaged and self._af_succeeded:
        self._mmc.enableContinuousFocus(True)

    if isinstance(event, SequencedEvent):
        yield from self.exec_sequenced_event(event)
    else:
        yield from self.exec_single_event(event)

exec_sequenced_event(event: SequencedEvent) -> Iterable[PImagePayload] #

Execute a sequenced (triggered) event and return the image data.

This method is not part of the PMDAEngine protocol (it is called by exec_event, which is part of the protocol), but it is made public in case a user wants to subclass this engine and override this method.

Source code in pymmcore_plus/mda/_engine.py
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
def exec_sequenced_event(self, event: SequencedEvent) -> Iterable[PImagePayload]:
    """Execute a sequenced (triggered) event and return the image data.

    This method is not part of the PMDAEngine protocol (it is called by
    `exec_event`, which *is* part of the protocol), but it is made public
    in case a user wants to subclass this engine and override this method.
    """
    n_events = len(event.events)

    t0 = event.metadata.get("runner_t0") or time.perf_counter()
    event_t0_ms = (time.perf_counter() - t0) * 1000

    if event.slm_image is not None:
        self._exec_event_slm_image(event.slm_image)

    # Start sequence
    # Note that the overload of startSequenceAcquisition that takes a camera
    # label does NOT automatically initialize a circular buffer.  So if this call
    # is changed to accept the camera in the future, that should be kept in mind.
    self._mmc.startSequenceAcquisition(
        n_events,
        0,  # intervalMS  # TODO: add support for this
        True,  # stopOnOverflow
    )
    self.post_sequence_started(event)

    n_channels = self._mmc.getNumberOfCameraChannels()
    count = 0
    iter_events = product(event.events, range(n_channels))
    # block until the sequence is done, popping images in the meantime
    while self._mmc.isSequenceRunning():
        if remaining := self._mmc.getRemainingImageCount():
            yield self._next_seqimg_payload(
                *next(iter_events), remaining=remaining - 1, event_t0=event_t0_ms
            )
            count += 1
        else:
            time.sleep(0.001)

    if self._mmc.isBufferOverflowed():  # pragma: no cover
        raise MemoryError("Buffer overflowed")

    while remaining := self._mmc.getRemainingImageCount():
        yield self._next_seqimg_payload(
            *next(iter_events), remaining=remaining - 1, event_t0=event_t0_ms
        )
        count += 1

    # necessary?
    expected_images = n_events * n_channels
    if count != expected_images:
        logger.warning(
            "Unexpected number of images returned from sequence. "
            "Expected %s, got %s",
            expected_images,
            count,
        )

exec_single_event(event: MDAEvent) -> Iterator[PImagePayload] #

Execute a single (non-triggered) event and return the image data.

This method is not part of the PMDAEngine protocol (it is called by exec_event, which is part of the protocol), but it is made public in case a user wants to subclass this engine and override this method.

Source code in pymmcore_plus/mda/_engine.py
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
def exec_single_event(self, event: MDAEvent) -> Iterator[PImagePayload]:
    """Execute a single (non-triggered) event and return the image data.

    This method is not part of the PMDAEngine protocol (it is called by
    `exec_event`, which *is* part of the protocol), but it is made public
    in case a user wants to subclass this engine and override this method.
    """
    if event.slm_image is not None:
        self._exec_event_slm_image(event.slm_image)

    try:
        self._mmc.snapImage()
        # taking event time after snapImage includes exposure time
        # not sure that's what we want, but it's currently consistent with the
        # timing of the sequenced event runner (where Elapsed_Time_ms is taken after
        # the image is acquired, not before the exposure starts)
        t0 = event.metadata.get("runner_t0") or time.perf_counter()
        event_time_ms = (time.perf_counter() - t0) * 1000
    except Exception as e:
        logger.warning("Failed to snap image. %s", e)
        return
    if not event.keep_shutter_open:
        self._mmc.setShutterOpen(False)

    # most cameras will only have a single channel
    # but Multi-camera may have multiple, and we need to retrieve a buffer for each
    for cam in range(self._mmc.getNumberOfCameraChannels()):
        meta = self.get_frame_metadata(
            event,
            runner_time_ms=event_time_ms,
            camera_device=self._mmc.getPhysicalCameraDevice(cam),
            include_position=self._include_frame_position_metadata is not False,
        )
        # Note, the third element is actually a MutableMapping, but mypy doesn't
        # see TypedDict as a subclass of MutableMapping yet.
        # https://github.com/python/mypy/issues/4976
        yield ImagePayload(self._mmc.getImage(cam), event, meta)  # type: ignore[misc]

get_frame_metadata(event: MDAEvent, prop_values: tuple[PropertyValue, ...] | None = None, runner_time_ms: float = 0.0, include_position: bool = True, camera_device: str | None = None) -> FrameMetaV1 #

Source code in pymmcore_plus/mda/_engine.py
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
def get_frame_metadata(
    self,
    event: MDAEvent,
    prop_values: tuple[PropertyValue, ...] | None = None,
    runner_time_ms: float = 0.0,
    include_position: bool = True,
    camera_device: str | None = None,
) -> FrameMetaV1:
    if prop_values is None and (ch := event.channel):
        prop_values = self._get_current_props(ch.group)
    else:
        prop_values = ()
    return frame_metadata(
        self._mmc,
        cached=True,
        runner_time_ms=runner_time_ms,
        camera_device=camera_device,
        property_values=prop_values,
        mda_event=event,
        include_position=include_position,
    )

get_summary_metadata(mda_sequence: MDASequence | None) -> SummaryMetaV1 #

Source code in pymmcore_plus/mda/_engine.py
142
143
def get_summary_metadata(self, mda_sequence: MDASequence | None) -> SummaryMetaV1:
    return summary_metadata(self._mmc, mda_sequence=mda_sequence)

include_frame_position_metadata() -> IncludePositionArg writable property #

Source code in pymmcore_plus/mda/_engine.py
102
103
104
@property
def include_frame_position_metadata(self) -> IncludePositionArg:
    return self._include_frame_position_metadata

mmcore() -> CMMCorePlus property #

The CMMCorePlus instance to use for hardware control.

Source code in pymmcore_plus/mda/_engine.py
115
116
117
118
@property
def mmcore(self) -> CMMCorePlus:
    """The `CMMCorePlus` instance to use for hardware control."""
    return self._mmc

post_sequence_started(event: SequencedEvent) -> None #

Perform any actions after startSequenceAcquisition has been called.

This method is available to subclasses in case they need to perform any actions after a hardware-triggered sequence has been started (i.e. after core.startSequenceAcquisition has been called).

The default implementation does nothing.

Source code in pymmcore_plus/mda/_engine.py
435
436
437
438
439
440
441
442
443
def post_sequence_started(self, event: SequencedEvent) -> None:
    """Perform any actions after startSequenceAcquisition has been called.

    This method is available to subclasses in case they need to perform any
    actions after a hardware-triggered sequence has been started (i.e. after
    core.startSequenceAcquisition has been called).

    The default implementation does nothing.
    """

setup_event(event: MDAEvent) -> None #

Set the system hardware (XY, Z, channel, exposure) as defined in the event.

Parameters:

Name Type Description Default
event MDAEvent

The event to use for the Hardware config

required
Source code in pymmcore_plus/mda/_engine.py
160
161
162
163
164
165
166
167
168
169
170
171
172
def setup_event(self, event: MDAEvent) -> None:
    """Set the system hardware (XY, Z, channel, exposure) as defined in the event.

    Parameters
    ----------
    event : MDAEvent
        The event to use for the Hardware config
    """
    if isinstance(event, SequencedEvent):
        self.setup_sequenced_event(event)
    else:
        self.setup_single_event(event)
    self._mmc.waitForSystem()

setup_sequence(sequence: MDASequence) -> SummaryMetaV1 | None #

Setup the hardware for the entire sequence.

Source code in pymmcore_plus/mda/_engine.py
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
def setup_sequence(self, sequence: MDASequence) -> SummaryMetaV1 | None:
    """Setup the hardware for the entire sequence."""
    # clear z_correction for new sequence
    self._z_correction.clear()

    if not self._mmc:  # pragma: no cover
        from pymmcore_plus.core import CMMCorePlus

        self._mmc = CMMCorePlus.instance()

    self._update_config_device_props()
    # get if the autofocus is engaged at the start of the sequence
    self._af_was_engaged = self._mmc.isContinuousFocusLocked()

    if px_size := self._mmc.getPixelSizeUm():
        self._update_grid_fov_sizes(px_size, sequence)

    self._autoshutter_was_set = self._mmc.getAutoShutter()
    return self.get_summary_metadata(mda_sequence=sequence)

setup_sequenced_event(event: SequencedEvent) -> None #

Setup hardware for a sequenced (triggered) event.

This method is not part of the PMDAEngine protocol (it is called by setup_event, which is part of the protocol), but it is made public in case a user wants to subclass this engine and override this method.

Source code in pymmcore_plus/mda/_engine.py
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
def setup_sequenced_event(self, event: SequencedEvent) -> None:
    """Setup hardware for a sequenced (triggered) event.

    This method is not part of the PMDAEngine protocol (it is called by
    `setup_event`, which *is* part of the protocol), but it is made public
    in case a user wants to subclass this engine and override this method.
    """
    core = self._mmc
    cam_device = self._mmc.getCameraDevice()

    if event.exposure_sequence:
        with suppress(RuntimeError):
            core.stopExposureSequence(cam_device)
        core.loadExposureSequence(cam_device, event.exposure_sequence)
    if event.x_sequence:  # y_sequence is implied and will be the same length
        stage = core.getXYStageDevice()
        with suppress(RuntimeError):
            core.stopXYStageSequence(stage)
        core.loadXYStageSequence(stage, event.x_sequence, event.y_sequence)
    if event.z_sequence:
        zstage = core.getFocusDevice()
        with suppress(RuntimeError):
            core.stopStageSequence(zstage)
        core.loadStageSequence(zstage, event.z_sequence)
    if prop_seqs := event.property_sequences(core):
        for (dev, prop), value_sequence in prop_seqs.items():
            with suppress(RuntimeError):
                core.stopPropertySequence(dev, prop)
            core.loadPropertySequence(dev, prop, value_sequence)

    if event.slm_image:
        self._set_event_slm_image(event)

    # preparing a Sequence while another is running is dangerous.
    if core.isSequenceRunning():
        self._await_sequence_acquisition()
    core.prepareSequenceAcquisition(cam_device)

    # start sequences or set non-sequenced values
    if event.x_sequence:
        core.startXYStageSequence(stage)
    elif event.x_pos is not None or event.y_pos is not None:
        self._set_event_position(event)

    if event.z_sequence:
        core.startStageSequence(zstage)
    elif event.z_pos is not None:
        self._set_event_z(event)

    if event.exposure_sequence:
        core.startExposureSequence(cam_device)
    elif event.exposure is not None:
        core.setExposure(event.exposure)

    if prop_seqs:
        for dev, prop in prop_seqs:
            core.startPropertySequence(dev, prop)
    elif event.channel is not None:
        core.setConfig(event.channel.group, event.channel.config)

setup_single_event(event: MDAEvent) -> None #

Setup hardware for a single (non-sequenced) event.

This method is not part of the PMDAEngine protocol (it is called by setup_event, which is part of the protocol), but it is made public in case a user wants to subclass this engine and override this method.

Source code in pymmcore_plus/mda/_engine.py
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
def setup_single_event(self, event: MDAEvent) -> None:
    """Setup hardware for a single (non-sequenced) event.

    This method is not part of the PMDAEngine protocol (it is called by
    `setup_event`, which *is* part of the protocol), but it is made public
    in case a user wants to subclass this engine and override this method.
    """
    if event.keep_shutter_open:
        ...

    if event.x_pos is not None or event.y_pos is not None:
        self._set_event_position(event)
    if event.z_pos is not None:
        self._set_event_z(event)
    if event.slm_image is not None:
        self._set_event_slm_image(event)
    if event.channel is not None:
        try:
            # possible speedup by setting manually.
            self._mmc.setConfig(event.channel.group, event.channel.config)
        except Exception as e:
            logger.warning("Failed to set channel. %s", e)
    if event.exposure is not None:
        try:
            self._mmc.setExposure(event.exposure)
        except Exception as e:
            logger.warning("Failed to set exposure. %s", e)

    if (
        # (if autoshutter wasn't set at the beginning of the sequence
        # then it never matters...)
        self._autoshutter_was_set
        # if we want to leave the shutter open after this event, and autoshutter
        # is currently enabled...
        and event.keep_shutter_open
        and self._mmc.getAutoShutter()
    ):
        # we have to disable autoshutter and open the shutter
        self._mmc.setAutoShutter(False)
        self._mmc.setShutterOpen(True)

teardown_event(event: MDAEvent) -> None #

Teardown state of system (hardware, etc.) after event.

Source code in pymmcore_plus/mda/_engine.py
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
def teardown_event(self, event: MDAEvent) -> None:
    """Teardown state of system (hardware, etc.) after `event`."""
    # autoshutter was set at the beginning of the sequence, and this event
    # doesn't want to leave the shutter open.  Re-enable autoshutter.
    core = self._mmc
    if not event.keep_shutter_open and self._autoshutter_was_set:
        core.setAutoShutter(True)
    # FIXME: this may not be hitting as intended...
    # https://github.com/pymmcore-plus/pymmcore-plus/pull/353#issuecomment-2159176491
    if isinstance(event, SequencedEvent):
        if event.exposure_sequence:
            core.stopExposureSequence(self._mmc.getCameraDevice())
        if event.x_sequence:
            core.stopXYStageSequence(core.getXYStageDevice())
        if event.z_sequence:
            core.stopStageSequence(core.getFocusDevice())
        for dev, prop in event.property_sequences(core):
            core.stopPropertySequence(dev, prop)

teardown_sequence(sequence: MDASequence) -> None #

Perform any teardown required after the sequence has been executed.

Source code in pymmcore_plus/mda/_engine.py
358
359
360
def teardown_sequence(self, sequence: MDASequence) -> None:
    """Perform any teardown required after the sequence has been executed."""
    pass