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
 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
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
        self._reset_timer()

    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 _outputs_connected(
        self, output: SingleOutput | Sequence[SingleOutput] | None
    ) -> ContextManager:
        """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)

        for event in _events:
            # 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)

            output = engine.exec_event(event) or ()  # in case output is None

            for payload in output:
                img, event, meta = payload
                if "PerfCounter" in meta:
                    meta["ElapsedTime-ms"] = (meta["PerfCounter"] - self._t0) * 1000
                meta["Event"] = event
                with exceptions_logged():
                    self._signals.frameReady.emit(img, event, meta)

            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)
        logger.info("MDA Started: %s", sequence)

        self._signals.sequenceStarted.emit(sequence, meta or {})
        self._reset_timer()
        return self._engine

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

    def _time_elapsed(self) -> float:
        return time.perf_counter() - self._t0

    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._time_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._time_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
144
145
146
147
148
149
150
151
152
153
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
103
104
105
106
@property
def engine(self) -> MDAEngine | None:
    """The [`PMDAEngine`][pymmcore_plus.mda.PMDAEngine] that is currently being used."""  # noqa: E501
    return self._engine  # type: ignore

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
108
109
110
111
112
113
114
115
@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
132
133
134
135
136
137
138
139
140
141
142
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
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
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
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

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

Set the PMDAEngine to use for the MDA run.

Source code in pymmcore_plus/mda/_runner.py
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
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
155
156
157
158
159
160
161
162
163
164
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) -> None | Mapping[str, Any] 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.

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 False, in order to avoid unexpected behavior, particularly in testing and demo scenarios. But in many "real world" scenarios, this can be set to True to improve performance.

Source code in pymmcore_plus/mda/_engine.py
 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
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.

    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 `False`, in order to avoid unexpected behavior, particularly
        in testing and demo scenarios.  But in many "real world" scenarios, this can be
        set to `True` to improve performance.
    """

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

        # 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()

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

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

    def setup_sequence(self, sequence: MDASequence) -> Mapping[str, Any]:
        """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()

        # 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()

    def get_summary_metadata(self) -> SummaryMetadata:
        """Get the summary metadata for the sequence."""
        pt = PixelType.for_bytes(
            self._mmc.getBytesPerPixel(), self._mmc.getNumberOfComponents()
        )
        affine = self._mmc.getPixelSizeAffine(True)  # true == cached

        return {
            "DateAndTime": datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f"),
            "PixelType": str(pt),
            "PixelSize_um": self._mmc.getPixelSizeUm(),
            "PixelSizeAffine": ";".join(str(x) for x in affine),
            "Core-XYStage": self._mmc.getXYStageDevice(),
            "Core-Focus": self._mmc.getFocusDevice(),
            "Core-Autofocus": self._mmc.getAutoFocusDevice(),
            "Core-Camera": self._mmc.getCameraDevice(),
            "Core-Galvo": self._mmc.getGalvoDevice(),
            "Core-ImageProcessor": self._mmc.getImageProcessorDevice(),
            "Core-SLM": self._mmc.getSLMDevice(),
            "Core-Shutter": self._mmc.getShutterDevice(),
            "AffineTransform": "Undefined",
        }

    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.channel is not None:
            try:
                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.
        """
        try:
            self._mmc.snapImage()
        except Exception as e:
            logger.warning("Failed to snap image. %s", e)
            return
        if not event.keep_shutter_open:
            self._mmc.setShutterOpen(False)
        yield ImagePayload(self._mmc.getImage(), event, self.get_frame_metadata())

    def get_frame_metadata(
        self, meta: Metadata | None = None, channel_index: int | None = None
    ) -> dict[str, Any]:
        # TODO:

        # this is not a very fast method, and it is called for every frame.
        # Nico Stuurman has suggested that it was a mistake for MM to pull so much
        # metadata for every frame.  So we'll begin with a more conservative approach.

        # while users can now simply re-implement this method,
        # consider coming up with a user-configurable way to specify needed metadata

        # rather than using self._mmc.getTags (which mimics MM) we pull a smaller
        # amount of metadata.
        # If you need more than this, either override or open an issue.

        tags = dict(meta) if meta else {}
        for dev, label, val in self._mmc.getSystemStateCache():
            tags[f"{dev}-{label}"] = val

        # these are added by AcqEngJ
        # yyyy-MM-dd HH:mm:ss.mmmmmm  # NOTE AcqEngJ omits microseconds
        tags["Time"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")
        tags["PixelSizeUm"] = self._mmc.getPixelSizeUm(True)  # true == cached
        with suppress(RuntimeError):
            tags["XPositionUm"] = self._mmc.getXPosition()
            tags["YPositionUm"] = self._mmc.getYPosition()
        with suppress(RuntimeError):
            tags["ZPositionUm"] = self._mmc.getZPosition()

        # used by Runner
        tags["PerfCounter"] = time.perf_counter()
        return tags

    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.
        if not event.keep_shutter_open and self._autoshutter_was_set:
            self._mmc.setAutoShutter(True)

    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:
            core.loadExposureSequence(cam_device, event.exposure_sequence)
        if event.x_sequence:  # y_sequence is implied and will be the same length
            stage = core.getXYStageDevice()
            core.loadXYStageSequence(stage, event.x_sequence, event.y_sequence)
        if event.z_sequence:
            # these notes are from Nico Stuurman in AcqEngJ
            # https://github.com/micro-manager/AcqEngJ/pull/108
            # at least some zStages freak out (in this case, NIDAQ board) when you
            # try to load a sequence while the sequence is still running.  Nothing in
            # the engine stops a stage sequence if all goes well.
            # Stopping a sequence if it is not running hopefully will not harm anyone.
            zstage = core.getFocusDevice()
            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():
                core.loadPropertySequence(dev, prop, value_sequence)

        # TODO: SLM

        # 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.
        """
        # TODO: add support for multiple camera devices
        n_events = len(event.events)

        # 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)

        count = 0
        iter_events = iter(event.events)
        # block until the sequence is done, popping images in the meantime
        while self._mmc.isSequenceRunning():
            if self._mmc.getRemainingImageCount():
                yield self._next_img_payload(next(iter_events))
                count += 1
            else:
                time.sleep(0.001)

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

        while self._mmc.getRemainingImageCount():
            yield self._next_img_payload(next(iter_events))
            count += 1

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

    def _next_img_payload(self, event: MDAEvent) -> PImagePayload:
        """Grab next image from the circular buffer and return it as an ImagePayload."""
        img, meta = self._mmc.popNextImageAndMD()
        tags = self.get_frame_metadata(meta)
        return ImagePayload(img, event, tags)

    # ===================== 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)

use_hardware_sequencing = 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
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
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
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
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
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
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.
    """
    # TODO: add support for multiple camera devices
    n_events = len(event.events)

    # 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)

    count = 0
    iter_events = iter(event.events)
    # block until the sequence is done, popping images in the meantime
    while self._mmc.isSequenceRunning():
        if self._mmc.getRemainingImageCount():
            yield self._next_img_payload(next(iter_events))
            count += 1
        else:
            time.sleep(0.001)

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

    while self._mmc.getRemainingImageCount():
        yield self._next_img_payload(next(iter_events))
        count += 1

    if count != n_events:
        logger.warning(
            "Unexpected number of images returned from sequence. "
            "Expected %s, got %s",
            n_events,
            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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
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.
    """
    try:
        self._mmc.snapImage()
    except Exception as e:
        logger.warning("Failed to snap image. %s", e)
        return
    if not event.keep_shutter_open:
        self._mmc.setShutterOpen(False)
    yield ImagePayload(self._mmc.getImage(), event, self.get_frame_metadata())

get_frame_metadata(meta: Metadata | None = None, channel_index: int | None = None) -> dict[str, Any] #

Source code in pymmcore_plus/mda/_engine.py
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
def get_frame_metadata(
    self, meta: Metadata | None = None, channel_index: int | None = None
) -> dict[str, Any]:
    # TODO:

    # this is not a very fast method, and it is called for every frame.
    # Nico Stuurman has suggested that it was a mistake for MM to pull so much
    # metadata for every frame.  So we'll begin with a more conservative approach.

    # while users can now simply re-implement this method,
    # consider coming up with a user-configurable way to specify needed metadata

    # rather than using self._mmc.getTags (which mimics MM) we pull a smaller
    # amount of metadata.
    # If you need more than this, either override or open an issue.

    tags = dict(meta) if meta else {}
    for dev, label, val in self._mmc.getSystemStateCache():
        tags[f"{dev}-{label}"] = val

    # these are added by AcqEngJ
    # yyyy-MM-dd HH:mm:ss.mmmmmm  # NOTE AcqEngJ omits microseconds
    tags["Time"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")
    tags["PixelSizeUm"] = self._mmc.getPixelSizeUm(True)  # true == cached
    with suppress(RuntimeError):
        tags["XPositionUm"] = self._mmc.getXPosition()
        tags["YPositionUm"] = self._mmc.getYPosition()
    with suppress(RuntimeError):
        tags["ZPositionUm"] = self._mmc.getZPosition()

    # used by Runner
    tags["PerfCounter"] = time.perf_counter()
    return tags

get_summary_metadata() -> SummaryMetadata #

Get the summary metadata for the sequence.

Source code in pymmcore_plus/mda/_engine.py
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
def get_summary_metadata(self) -> SummaryMetadata:
    """Get the summary metadata for the sequence."""
    pt = PixelType.for_bytes(
        self._mmc.getBytesPerPixel(), self._mmc.getNumberOfComponents()
    )
    affine = self._mmc.getPixelSizeAffine(True)  # true == cached

    return {
        "DateAndTime": datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f"),
        "PixelType": str(pt),
        "PixelSize_um": self._mmc.getPixelSizeUm(),
        "PixelSizeAffine": ";".join(str(x) for x in affine),
        "Core-XYStage": self._mmc.getXYStageDevice(),
        "Core-Focus": self._mmc.getFocusDevice(),
        "Core-Autofocus": self._mmc.getAutoFocusDevice(),
        "Core-Camera": self._mmc.getCameraDevice(),
        "Core-Galvo": self._mmc.getGalvoDevice(),
        "Core-ImageProcessor": self._mmc.getImageProcessorDevice(),
        "Core-SLM": self._mmc.getSLMDevice(),
        "Core-Shutter": self._mmc.getShutterDevice(),
        "AffineTransform": "Undefined",
    }

mmcore() -> CMMCorePlus property #

The CMMCorePlus instance to use for hardware control.

Source code in pymmcore_plus/mda/_engine.py
94
95
96
97
@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
407
408
409
410
411
412
413
414
415
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
158
159
160
161
162
163
164
165
166
167
168
169
170
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) -> Mapping[str, Any] #

Setup the hardware for the entire sequence.

Source code in pymmcore_plus/mda/_engine.py
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
def setup_sequence(self, sequence: MDASequence) -> Mapping[str, Any]:
    """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()

    # 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()

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
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
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:
        core.loadExposureSequence(cam_device, event.exposure_sequence)
    if event.x_sequence:  # y_sequence is implied and will be the same length
        stage = core.getXYStageDevice()
        core.loadXYStageSequence(stage, event.x_sequence, event.y_sequence)
    if event.z_sequence:
        # these notes are from Nico Stuurman in AcqEngJ
        # https://github.com/micro-manager/AcqEngJ/pull/108
        # at least some zStages freak out (in this case, NIDAQ board) when you
        # try to load a sequence while the sequence is still running.  Nothing in
        # the engine stops a stage sequence if all goes well.
        # Stopping a sequence if it is not running hopefully will not harm anyone.
        zstage = core.getFocusDevice()
        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():
            core.loadPropertySequence(dev, prop, value_sequence)

    # TODO: SLM

    # 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
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
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.channel is not None:
        try:
            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
325
326
327
328
329
330
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.
    if not event.keep_shutter_open and self._autoshutter_was_set:
        self._mmc.setAutoShutter(True)

teardown_sequence(sequence: MDASequence) -> None #

Perform any teardown required after the sequence has been executed.

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