Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/changes/dev/newfeature.1.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Add the ``offscreen`` 3D backend, selected with ``mne.viz.set_3d_backend("offscreen")``, to produce :class:`mne.viz.Brain` screenshots and movies without a window, e.g., on headless servers and in documentation builds, by `Christian Brodbeck`_.
9 changes: 9 additions & 0 deletions doc/install/advanced.rst
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,15 @@ system package manager or with:

$ conda install -c conda-forge mesalib

To render 3D figures without any window, for example to save
:meth:`mne.viz.Brain.screenshot` images from a script or a report, select the
``offscreen`` 3D backend, which needs neither Qt nor the notebook packages:

.. code-block:: ipython

In [1]: import mne
In [2]: mne.viz.set_3d_backend("offscreen")

Using the development version
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Expand Down
39 changes: 26 additions & 13 deletions mne/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -735,6 +735,7 @@ def browser_backend(request, garbage_collect, monkeypatch):
@pytest.fixture(
params=[
pytest.param("pyvistaqt", marks=pytest.mark.pvtest),
pytest.param("offscreen", marks=pytest.mark.pvtest),
pytest.param("jupyterlite_notebook", marks=pytest.mark.pvtest),
]
)
Expand All @@ -751,6 +752,13 @@ def renderer_pyvistaqt(request, options_3d, garbage_collect):
yield renderer


@pytest.fixture(params=[pytest.param("offscreen", marks=pytest.mark.pvtest)])
def renderer_offscreen(request, options_3d, garbage_collect):
"""Yield the offscreen PyVista backend."""
with _use_backend(request.param, interactive=False) as renderer:
yield renderer


@pytest.fixture(params=[pytest.param("notebook", marks=pytest.mark.pvtest)])
def renderer_notebook(request, options_3d):
"""Yield the 3D notebook renderer."""
Expand Down Expand Up @@ -828,6 +836,8 @@ def _check_skip_backend(name):
pytest.importorskip("pyvistaqt")
if not _check_qt_version():
pytest.skip("Test skipped, requires Qt.")
elif name == "offscreen":
pass # draws with a plain pyvista.Plotter: nothing else to need
else:
assert name == "notebook", name
pytest.importorskip("jupyter")
Expand Down Expand Up @@ -1123,14 +1133,15 @@ def brain_gc(request):
"renderer",
"renderer_pyvistaqt",
"renderer_notebook",
"renderer_offscreen",
)
assert set(request.fixturenames) & set(keys) != set()
for key in keys:
if key in request.fixturenames:
is_pv = request.getfixturevalue(key)._get_3d_backend() == "pyvistaqt"
backend_name = request.getfixturevalue(key)._get_3d_backend()
close_func = request.getfixturevalue(key).backend._close_all
break
if not is_pv:
if backend_name not in ("pyvistaqt", "offscreen"):
yield
return
from mne.viz import Brain
Expand All @@ -1144,17 +1155,19 @@ def brain_gc(request):
try:
yield
close_func()
# pyvistaqt >= 0.11.3 schedules the plotter's window for deferred deletion
# (deleteLater) on close; until Qt processes it, the C++ window object
# keeps its Python wrapper (and thereby the whole plotter graph) alive.
from qtpy.QtCore import QEvent
from qtpy.QtWidgets import QApplication

app = QApplication.instance()
if app is not None:
for _ in range(2):
app.processEvents()
app.sendPostedEvents(None, QEvent.DeferredDelete)
if backend_name == "pyvistaqt":
# pyvistaqt >= 0.11.3 schedules the plotter's window for deferred
# deletion (deleteLater) on close; until Qt processes it, the C++ window
# object keeps its Python wrapper (and thereby the whole plotter graph)
# alive.
from qtpy.QtCore import QEvent
from qtpy.QtWidgets import QApplication

app = QApplication.instance()
if app is not None:
for _ in range(2):
app.processEvents()
app.sendPostedEvents(None, QEvent.DeferredDelete)
if not _test_passed(request):
return
# The collect must happen *before* list(Brain._instances) is evaluated:
Expand Down
18 changes: 13 additions & 5 deletions mne/viz/_3d.py
Original file line number Diff line number Diff line change
Expand Up @@ -2763,11 +2763,19 @@ def _check_st_tv(show_traces, time_viewer, times):
("auto", "separate", "vertex", "label"),
extra="when a string",
)
if time_viewer == "auto":
from .backends.renderer import _get_3d_backend
from .backends._utils import _check_time_viewer_backend
from .backends.renderer import _get_3d_backend

# the browser backend writes a static scene, so there is no slider to show
time_viewer = _get_3d_backend() != "jupyterlite_notebook"
backend = _get_3d_backend()
if time_viewer == "auto":
# the browser backend writes a static scene and the offscreen backend
# has no window, so there is no slider to show
time_viewer = backend not in ("jupyterlite_notebook", "offscreen")
asked = show_traces != "auto" and show_traces # traces need the time viewer
else:
asked = time_viewer
if asked: # before a figure exists that the error would leave open
_check_time_viewer_backend(backend)
if show_traces == "auto":
show_traces = time_viewer and times is not None and len(times) > 1
if show_traces and not time_viewer:
Expand Down Expand Up @@ -3309,7 +3317,7 @@ def _check_views(surf, views, hemi, stc=None, backend=None):
stc, SourceEstimate, "stc", "SourceEstimate when a flatmap is used"
)
if backend is not None:
if backend not in ("pyvistaqt", "notebook"):
if backend not in ("pyvistaqt", "notebook", "offscreen"):
raise RuntimeError(
"The PyVista 3D backend must be used to plot a flatmap"
)
Expand Down
6 changes: 4 additions & 2 deletions mne/viz/_brain/_brain.py
Original file line number Diff line number Diff line change
Expand Up @@ -540,7 +540,8 @@ def _clean(self):
renderer.RemoveAllLights()
# app_window cannot be set to None because it is used in __del__
for key in ("lighting", "interactor", "_RenderWindow"):
setattr(self.plotter, key, None)
if hasattr(self.plotter, key): # a plain pyvista.Plotter has none
setattr(self.plotter, key, None)
# Qt LeaveEvent requires _Iren so we use _FakeIren instead of None
# to resolve the ref to vtkGenericRenderWindowInteractor
self.plotter._Iren = _FakeIren()
Expand Down Expand Up @@ -1603,7 +1604,8 @@ def add_annotation(
name=name,
)

if hover:
# only a Qt plotter is an interactor that delivers mouse events
if hover and hasattr(self.plotter, "AddObserver"):

@_auto_weakref
def on_annotation_hover(iren, event):
Expand Down
2 changes: 2 additions & 0 deletions mne/viz/_brain/_time_viewer.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
_validate_type,
fill_doc_static,
)
from ..backends._utils import _check_time_viewer_backend
from ..ui_events import (
PlaybackSpeed,
VertexSelect,
Expand Down Expand Up @@ -67,6 +68,7 @@ def setup_time_viewer(self, time_viewer=True, show_traces=True):
an entry from that menu switches which overlay's ``fmin`` / ``fmid``
/ ``fmax`` sliders and smoothing control are active.
"""
_check_time_viewer_backend(self._renderer._kind)
if self.time_viewer:
return
if not self._all_data:
Expand Down
26 changes: 25 additions & 1 deletion mne/viz/_brain/tests/test_brain.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
from mne.source_estimate import _BaseSourceEstimate
from mne.source_space import read_source_spaces, setup_volume_source_space
from mne.utils import catch_logging, check_version
from mne.viz import ui_events
from mne.viz import close_3d_figure, ui_events
from mne.viz._brain import Brain, LayeredMesh, _BrainScraper, _LinkViewer
from mne.viz._brain._brain import _auto_scalar_bar_fmt
from mne.viz._brain.colormap import calculate_lut
Expand Down Expand Up @@ -223,6 +223,30 @@ def test_brain_data_gc(renderer_interactive_pyvistaqt, brain_gc):
brain.close()


@testing.requires_testing_data
def test_brain_offscreen(renderer_offscreen, brain_gc):
"""Test what is specific to the offscreen backend: no window, no time viewer."""
stc = read_source_estimate(fname_stc, subject=subject)
kwargs = dict(subjects_dir=subjects_dir, hemi="lh", size=(300, 250))
# asking for the time viewer fails before a Brain is created
brains = set(Brain._instances)
for bad in (dict(time_viewer=True), dict(show_traces=True)):
with pytest.raises(RuntimeError, match="time viewer is not available"):
stc.plot(**kwargs, **bad)
assert set(Brain._instances) == brains
brain = stc.plot(**kwargs) # time_viewer="auto" resolves to no time viewer
assert not brain.time_viewer
with pytest.raises(RuntimeError, match="time viewer is not available"):
brain.setup_time_viewer()
brain.add_annotation("aparc") # without the hover labels
assert brain.screenshot().shape == (250, 300, 3)
# closing the figure rather than the Brain cleans up the Brain too
close_3d_figure(brain._renderer.figure)
assert brain._cleaned
stc.subject = "fsaverage" # wrong, but it has the patch files a flat map needs
stc.plot(surface="flat", **kwargs).close()


@testing.requires_testing_data
def test_brain_routines(renderer_pyvistaqt, brain_gc):
"""Test backend agnostic Brain routines."""
Expand Down
38 changes: 14 additions & 24 deletions mne/viz/backends/_lite.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
# License: BSD-3-Clause
# Copyright the MNE-Python contributors.

import inspect
import weakref
from contextlib import nullcontext

Expand All @@ -35,7 +34,14 @@
)
from ...utils import _check_option, _validate_type
from ._abstract import Figure3D, _AbstractRenderer
from ._utils import ALLOWED_QUIVER_MODES, LIGHTS, _to_pos, _vtk_faces
from ._utils import (
ALLOWED_QUIVER_MODES,
LIGHTS,
_CloseCallbackMixin,
_run_close_callbacks,
_to_pos,
_vtk_faces,
)

# vtk.js places text in normalized window coordinates; PyVista takes these names
_TITLE_POSITIONS = {
Expand Down Expand Up @@ -185,7 +191,7 @@ def _init(self, plotter):
return self


class _LiteRenderer(_AbstractRenderer):
class _LiteRenderer(_CloseCallbackMixin, _AbstractRenderer):
"""MNE 3D renderer backed by pyvista-js."""

# not "notebook": that backend has VTK, a filesystem and OS threads
Expand Down Expand Up @@ -586,32 +592,16 @@ def subplot(self, x, y):
def _update(self):
pass # the page paints after the cell finishes

def _window_close_connect(self, func, *, after=True):
# an output cell has no close event, so close() runs these; ui_events
# drops its channel here, without which its subscribers pin the figure.
# Weak for bound methods (Brain._clean) so a figure dropped without
# close() still dies by refcount rather than waiting on the collector
if inspect.ismethod(func):
func = weakref.WeakMethod(func)
self._close_callbacks[after].append(func)

def _window_close_disconnect(self, after=True):
self._close_callbacks[after].clear()

def _run_close_callbacks(self, after):
for func in list(self._close_callbacks[after]): # Brain._clean disconnects
if isinstance(func, weakref.WeakMethod):
func = func()
if func is not None:
func()

def text3d(self, x, y, z, text, font_size, color="white", *, shadow=False):
pass # no camera-facing 3D text, so sensors go unlabeled

def close(self):
self._run_close_callbacks(after=False)
# an output cell has no close event, so this runs the close callbacks;
# ui_events drops its channel there, without which its subscribers pin
# the figure
_run_close_callbacks(self._close_callbacks, after=False)
_lite_release_plotter(self.plotter)
self._run_close_callbacks(after=True)
_run_close_callbacks(self._close_callbacks, after=True)

# -- things pyvista-js cannot do ----------------------------------------
def contour(self, *args, **kwargs):
Expand Down
72 changes: 72 additions & 0 deletions mne/viz/backends/_offscreen.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
"""An off-screen PyVista backend for MNE's 3D renderer.

Draws with a plain :class:`pyvista.Plotter` in off-screen mode: no Qt, no
notebook widgets and no window. Figures are consumed through
:meth:`~mne.viz.Brain.screenshot` and :meth:`~mne.viz.Brain.save_movie`, which
is what reports, documentation builds and headless servers need. Selected with
``mne.viz.set_3d_backend("offscreen")``.

Everything that draws works, including :class:`mne.viz.Brain`; only the
interactive widgets do not, so :meth:`mne.viz.Brain.setup_time_viewer` raises.
"""

# Authors: The MNE-Python contributors.
# License: BSD-3-Clause
# Copyright the MNE-Python contributors.

from contextlib import nullcontext
from functools import cached_property

import pyvista

from ._pyvista import (
_check_3d_figure, # noqa: F401
_clear_3d_figure, # noqa: F401
_close_3d_figure, # noqa: F401
_close_all, # noqa: F401
_PyVistaRenderer,
_set_3d_title, # noqa: F401
_set_3d_view, # noqa: F401
_take_3d_screenshot, # noqa: F401
)
from ._utils import _CloseCallbackMixin, _run_close_callbacks


class _Plotter(pyvista.Plotter):
"""A plain Plotter that runs close callbacks, as a Qt window does on closing.

The plotter runs them rather than the renderer because ``close_3d_figure``
and ``close_all_3d_figures`` close the plotter without going through one.
"""

@cached_property
def _close_callbacks(self):
return {False: [], True: []} # keyed by ``after``

def close(self):
first = not self._closed
if first:
_run_close_callbacks(self._close_callbacks, after=False)
super().close()
if first:
_run_close_callbacks(self._close_callbacks, after=True)


class _Renderer(_CloseCallbackMixin, _PyVistaRenderer):
_kind = "offscreen"
_plotter_class = _Plotter

@property
def _close_callbacks(self):
return self.plotter._close_callbacks

def show(self):
# pyvista.Plotter.show() renders once and then closes the plotter,
# which would leave nothing to screenshot; just render
self._update()

def _window_set_theme(self, theme):
pass # there is no window


_testing_context = nullcontext # the plotter is always off screen
Loading
Loading