Debian Codegraph @

pyvista/jupyter/__init__.py

raw
1 """Jupyter notebook plotting module."""
2
3 from __future__ import annotations
4
5 # noqa-reason: ``Callable`` is used in the ``JupyterBackendRegistration``
6 # NamedTuple field annotations and must be available at runtime so that
7 # ``typing.get_type_hints`` (called by Sphinx autodoc) can resolve them.
8 from collections.abc import Callable # noqa: TC003
9 from importlib.metadata import entry_points
10 import importlib.util
11 from typing import Literal
12 from typing import NamedTuple
13 from typing import get_args
14
15 from typing_extensions import TypeIs
16
17 import pyvista as pv
18 from pyvista._warn_external import warn_external
19 from pyvista.core.errors import PyVistaDeprecationWarning as PyVistaDeprecationWarning
20 from pyvista.core.utilities._registry_helpers import handler_source
21
22 JupyterBackendOptions = Literal['static', 'client', 'server', 'trame', 'html', 'none']
23 ALLOWED_BACKENDS = get_args(JupyterBackendOptions)
24
25 JUPYTER_BACKEND_ENTRY_POINT_GROUP = 'pyvista.jupyter_backends'
26
27 _custom_backends: dict[str, Callable[..., object]] = {}
28 _custom_backend_sources: dict[str, str] = {}
29 _entry_points_loaded: bool = False
30
31
32 class JupyterBackendRegistration(NamedTuple):
33 """Describe one registered custom Jupyter backend.
34
35 Returned by :func:`~pyvista.registered_jupyter_backends`.
36
37 .. versionadded:: 0.48.0
38
39 Attributes
40 ----------
41 name : str
42 Backend name.
43 handler : callable
44 The backend handler callable.
45 source : str
46 Human-readable origin in the form ``'module.qualname'`` for
47 explicit registrations or the entry-point ``value`` for
48 plugin-discovered registrations.
49
50 """
51
52 name: str
53 handler: Callable[..., object]
54 source: str
55
56
57 def register_jupyter_backend(
58 name: str,
59 handler: Callable[..., object],
60 *,
61 override: bool = False,
62 ) -> None:
63 """Register a custom Jupyter backend handler.
64
65 .. versionadded:: 0.48.0
66
67 Parameters
68 ----------
69 name : str
70 Name of the backend (e.g. ``'custom'``). Must not collide with
71 a built-in backend name unless ``override=True`` is passed.
72 handler : callable
73 A callable with signature ``handler(plotter, **kwargs)`` that
74 returns an IPython-displayable object.
75 override : bool, default: False
76 If ``True``, allow registering a name that collides with a
77 built-in backend. Also silences the warning emitted when
78 replacing an existing custom registration.
79
80 Raises
81 ------
82 ValueError
83 If ``name`` collides with a built-in backend and ``override``
84 is ``False``.
85
86 Warns
87 -----
88 UserWarning
89 If ``name`` already refers to a registered custom backend. The
90 new registration replaces the old one (last wins); pass
91 ``override=True`` to silence the warning.
92
93 Examples
94 --------
95 >>> import pyvista as pv
96 >>> def my_handler(plotter, **kwargs): ...
97 >>> pv.register_jupyter_backend('my_backend', my_handler) # doctest: +SKIP
98
99 """
100 name = name.lower()
101 if not override and name in ALLOWED_BACKENDS:
102 msg = (
103 f'Cannot register custom backend "{name}": collides with built-in backend. '
104 'Use override=True to replace it.'
105 )
106 raise ValueError(msg)
107 if not override and name in _custom_backends:
108 existing_source = _custom_backend_sources.get(name, '<unknown>')
109 warn_external(
110 f'Registering Jupyter backend "{name}" replaces an existing custom '
111 f'registration from {existing_source}.',
112 )
113 _custom_backends[name] = handler
114 _custom_backend_sources[name] = handler_source(handler)
115
116
117 def registered_jupyter_backends() -> tuple[JupyterBackendRegistration, ...]:
118 """Return every custom Jupyter backend currently registered.
119
120 Forces discovery of any pending entry-point plugins so the returned
121 list reflects every backend visible to PyVista. A plugin that fails
122 to import emits a ``UserWarning`` and is skipped; the rest still
123 appear in the result.
124
125 .. versionadded:: 0.48.0
126
127 Returns
128 -------
129 tuple[JupyterBackendRegistration, ...]
130 One record per registered backend. Each record exposes
131 ``name``, ``handler``, and ``source``. Built-in backends are
132 not included; only custom registrations.
133
134 """
135 _ensure_entry_points()
136 return tuple(
137 JupyterBackendRegistration(
138 name=name,
139 handler=handler,
140 source=_custom_backend_sources.get(name, '<unknown>'),
141 )
142 for name, handler in _custom_backends.items()
143 )
144
145
146 def _get_custom_backend_handler(name: str) -> Callable[..., object] | None:
147 """Look up a custom backend handler by name.
148
149 Checks the registry first, then discovers entry points lazily.
150
151 Parameters
152 ----------
153 name : str
154 Backend name to look up.
155
156 Returns
157 -------
158 callable or None
159 The handler if found, otherwise ``None``.
160
161 """
162 handler = _custom_backends.get(name)
163 if handler is not None:
164 return handler
165 _ensure_entry_points()
166 return _custom_backends.get(name)
167
168
169 def _ensure_entry_points() -> None:
170 """Scan ``pyvista.jupyter_backends`` entry point group and load handlers."""
171 global _entry_points_loaded # noqa: PLW0603
172 if _entry_points_loaded:
173 return
174 _entry_points_loaded = True
175
176 eps = entry_points(group=JUPYTER_BACKEND_ENTRY_POINT_GROUP)
177 for ep in eps:
178 name = ep.name.lower()
179 if name in ALLOWED_BACKENDS or name in _custom_backends:
180 continue
181 try:
182 # ep.load() runs third-party import machinery — it can raise
183 # literally anything. Convert to a warning so one broken
184 # plugin cannot take down the Jupyter integration.
185 handler = ep.load()
186 except Exception as err: # noqa: BLE001
187 warn_external(
188 f'Failed to load {JUPYTER_BACKEND_ENTRY_POINT_GROUP} entry point '
189 f'"{ep.value}" for "{name}": {err}',
190 )
191 continue
192 _custom_backends[name] = handler
193 _custom_backend_sources[name] = ep.value
194
195
196 def _resolve_backend() -> str:
197 """Auto-detect the best available Jupyter backend.
198
199 Priority: registered custom backends > trame > static.
200
201 Returns
202 -------
203 str
204 Name of the best available backend.
205
206 """
207 _ensure_entry_points()
208 if _custom_backends:
209 return next(iter(_custom_backends))
210
211 try:
212 from pyvista.trame.jupyter import show_trame as show_trame # noqa: PLC0415
213 except ImportError:
214 pass
215 else:
216 return 'trame'
217
218 return 'static'
219
220
221 def _is_jupyter_backend(backend: str) -> TypeIs[JupyterBackendOptions]:
222 """Return True if backend is allowed jupyter backend."""
223 return backend in ALLOWED_BACKENDS
224
225
226 def _validate_jupyter_backend(
227 backend: str | None,
228 ) -> str | None:
229 """Validate that a jupyter backend is valid.
230
231 Returns the normalized name of the backend, or ``None`` to indicate that
232 the backend should be auto-detected at display time. Raises if the backend
233 is invalid.
234
235 """
236 # ``None`` is the auto-detect sentinel; preserve it
237 if backend is None:
238 return None
239 backend = backend.lower()
240
241 if not importlib.util.find_spec('IPython'):
242 msg = 'Install IPython to display with pyvista in a notebook.'
243 raise ImportError(msg)
244
245 if _is_jupyter_backend(backend):
246 if backend in ['server', 'client', 'trame', 'html']:
247 try:
248 from pyvista.trame.jupyter import show_trame as show_trame # noqa: PLC0415
249 except ImportError: # pragma: no cover
250 msg = 'Please install trame dependencies: pip install "pyvista[jupyter]"'
251 raise ImportError(msg)
252 return backend
253
254 # Check custom backends (registry + entry points)
255 if _get_custom_backend_handler(backend) is not None:
256 return backend
257
258 all_backends = list(ALLOWED_BACKENDS) + sorted(_custom_backends.keys())
259 backend_list_str = ', '.join([f'"{item}"' for item in all_backends])
260 msg = (
261 f'Invalid Jupyter notebook plotting backend "{backend}".\n'
262 f'Use one of the following:\n{backend_list_str}'
263 )
264 raise ValueError(msg)
265
266
267 def set_jupyter_backend(backend: JupyterBackendOptions | str, name=None, **kwargs): # noqa: ARG001
268 """Set the plotting backend for a jupyter notebook.
269
270 Parameters
271 ----------
272 backend : str
273 Jupyter backend to use when plotting. Must be one of the following:
274
275 * ``'static'`` : Display a single static image within the
276 Jupyterlab environment. Still requires that a virtual
277 framebuffer be set up when displaying on a headless server,
278 but does not require any additional modules to be installed.
279
280 * ``'client'`` : Export/serialize the scene graph to be rendered
281 with VTK.js client-side through ``trame``. Requires ``trame``
282 and ``jupyter-server-proxy`` to be installed.
283
284 * ``'server'``: Render remotely and stream the resulting VTK
285 images back to the client using ``trame``. This replaces the
286 ``'ipyvtklink'`` backend with better performance.
287 Supports the most VTK features, but suffers from minor lag due
288 to remote rendering. Requires that a virtual framebuffer be set
289 up when displaying on a headless server. Must have at least ``trame``
290 and ``jupyter-server-proxy`` installed for cloud/remote Jupyter
291 instances. This mode is also aliased by ``'trame'``.
292
293 * ``'trame'``: The full Trame-based backend that combines both
294 ``'server'`` and ``'client'`` into one backend. This requires a
295 virtual frame buffer.
296
297 * ``'html'`` : Export/serialize the scene graph to be rendered
298 with the Trame client backend but in a static HTML file.
299
300 * ``'none'`` : Do not display any plots within jupyterlab,
301 instead display using dedicated VTK render windows. This
302 will generate nothing on headless servers even with a
303 virtual framebuffer.
304
305 Custom backends registered via :func:`~pyvista.register_jupyter_backend`
306 are also accepted. Pass ``None`` to reset to auto-detection at display
307 time.
308
309 name : str, optional
310 The unique name identifier for the server.
311 **kwargs : dict, optional
312 Any additional keyword arguments to pass to the server launch.
313
314 Examples
315 --------
316 Enable the trame Trame backend.
317
318 >>> pv.set_jupyter_backend('trame') # doctest:+SKIP
319
320 Just show static images.
321
322 >>> pv.set_jupyter_backend('static') # doctest:+SKIP
323
324 Disable all plotting within JupyterLab and display using a
325 standard desktop VTK render window.
326
327 >>> pv.set_jupyter_backend('none') # doctest:+SKIP
328
329 Reset to auto-detect the best available backend.
330
331 >>> pv.set_jupyter_backend(None) # doctest:+SKIP
332
333 """
334 pv.global_theme._jupyter_backend = _validate_jupyter_backend(backend)