Debian Codegraph @

pyvista/plotting/utilities/sphinx_gallery.py

raw
1 """Utilities for using pyvista with sphinx-gallery."""
2
3 from __future__ import annotations
4
5 from pathlib import Path
6 import shutil
7 from typing import TYPE_CHECKING
8
9 import pyvista as pv
10 from pyvista._deprecate_positional_args import _deprecate_positional_args
11
12 if TYPE_CHECKING:
13 from collections.abc import Iterator
14
15 BUILDING_GALLERY_ERROR_MSG = (
16 'pyvista.BUILDING_GALLERY must be set to True in your conf.py to capture '
17 'images within sphinx_gallery or when building documentation using the '
18 'pyvista-plot directive.'
19 )
20
21
22 def _get_sg_image_scraper():
23 """Return the callable scraper to be used by Sphinx-Gallery.
24
25 It allows PyVista users to just use strings as they already can for
26 'matplotlib' and 'mayavi'. Details on this implementation can be found in
27 `sphinx-gallery/sphinx-gallery/494`_
28
29 This must be imported into the top level namespace of PyVista.
30
31 .. _sphinx-gallery/sphinx-gallery/494: https://github.com/sphinx-gallery/sphinx-gallery/pull/494
32 """
33 return Scraper()
34
35
36 def html_rst(
37 figure_list,
38 sources_dir,
39 srcsetpaths=None,
40 ): # pragma: no cover # numpydoc ignore=PR01,RT01
41 """Generate reST for viewer with exported scene."""
42 from sphinx_gallery.scrapers import _get_srcset_st # noqa: PLC0415
43 from sphinx_gallery.scrapers import figure_rst # noqa: PLC0415
44
45 if srcsetpaths is None:
46 # this should never happen, but figure_rst is public, so
47 # this has to be a kwarg...
48 srcsetpaths = [{0: fl} for fl in figure_list]
49
50 images_rst = ''
51 for i, hinnames in enumerate(srcsetpaths):
52 srcset = _get_srcset_st(sources_dir, hinnames)
53 if srcset[-5:] == 'vtksz':
54 png_file = figure_list[i][:-5] + 'png'
55
56 indented_firgure_rst = '\n'.join(
57 ' ' * 5 + line for line in figure_rst([png_file], sources_dir).split('\n')
58 )
59 images_rst += f"""
60 \n
61 \n
62 .. tab-set::\n
63 \n
64 .. tab-item:: Static Scene\n
65 \n
66 {indented_firgure_rst}
67 \n
68 .. tab-item:: Interactive Scene\n
69 \n
70 .. offlineviewer:: {figure_list[i]}\n\n"""
71
72 else:
73 images_rst += '\n' + figure_rst([figure_list[i]], sources_dir) + '\n\n'
74
75 return images_rst
76
77
78 def _process_events_before_scraping(plotter):
79 """Process events such as changing the camera or an object before scraping."""
80 if plotter.iren is not None and plotter.iren.initialized:
81 # check for pyvistaqt app which can be specifically bound to pyvista plotter
82 # objects in order to interact with qt, then process the events from qt
83 if hasattr(plotter, 'app') and plotter.app is not None:
84 plotter.app.processEvents()
85 plotter.update()
86
87
88 @_deprecate_positional_args(allowed=['image_path_iterator'])
89 def generate_images(image_path_iterator: Iterator[str], dynamic: bool = False) -> list[str]: # noqa: FBT001, FBT002
90 """Generate images from the current plotters.
91
92 The file names are taken from the ``image_path_iterator`` iterator.
93
94 A gif will be created if a plotter has a ``_gif_filename`` attribute.
95 Otherwise, depending on the value of ``dynamic``, either a ``.png`` static image
96 or a ``.vtksz`` file will be created.
97
98 Parameters
99 ----------
100 image_path_iterator : Iterator[str]
101 An iterator that yields the path to the next image to be saved.
102
103 dynamic : bool, default: False
104 Whether to save a static ``.png`` image or a ``.vtksz`` (interactive)
105 file.
106
107 Returns
108 -------
109 list[str]
110 A list of the names of the images that were created.
111
112 """
113 image_names = []
114 figures = pv.plotting.plotter._ALL_PLOTTERS
115 for plotter in figures.values():
116 _process_events_before_scraping(plotter)
117 fname = next(image_path_iterator)
118 # Make sure the extension is "png"
119 path = Path(fname)
120 fname_withoutextension = str(path.parent / path.stem)
121 fname = fname_withoutextension + '.png'
122
123 if (gif_filename := plotter._gif_filename) is not None:
124 # move gif to fname
125 fname = fname[:-3] + 'gif'
126 shutil.move(gif_filename, fname)
127 image_names.append(fname)
128 else:
129 plotter.screenshot(fname)
130 if not dynamic or plotter.last_vtksz is None:
131 image_names.append(fname)
132 else: # pragma: no cover
133 fname = fname[:-3] + 'vtksz'
134 with Path(fname).open('wb') as f:
135 f.write(plotter.last_vtksz) # type: ignore[arg-type]
136 image_names.append(fname)
137
138 pv.close_all() # close and clear all plotters
139 return image_names
140
141
142 class Scraper:
143 """Save ``pyvista.Plotter`` objects.
144
145 Used by sphinx-gallery to generate the plots from the code in the examples.
146
147 Pass an instance of this class to ``sphinx_gallery_conf`` in your
148 ``conf.py`` as the ``"image_scrapers"`` argument.
149
150 Be sure to set ``pyvista.BUILDING_GALLERY = True`` in your ``conf.py``.
151
152 """
153
154 def __repr__(self) -> str:
155 """Return a stable representation of the class instance."""
156 return f'<{type(self).__name__} object>'
157
158 def __call__(self, block, block_vars, gallery_conf): # noqa: ARG002
159 """Save the figures generated after running example code.
160
161 Called by sphinx-gallery.
162
163 """
164 from sphinx_gallery.scrapers import figure_rst # noqa: PLC0415
165
166 if not pv.BUILDING_GALLERY:
167 raise RuntimeError(BUILDING_GALLERY_ERROR_MSG)
168
169 image_path_iterator = block_vars['image_path_iterator']
170 image_names = generate_images(image_path_iterator, dynamic=False)
171 return figure_rst(image_names, gallery_conf['src_dir'])
172
173
174 class DynamicScraper: # pragma: no cover
175 """Save ``pyvista.Plotter`` objects dynamically.
176
177 Used by sphinx-gallery to generate the plots from the code in the examples.
178
179 Pass an instance of this class to ``sphinx_gallery_conf`` in your
180 ``conf.py`` as the ``"image_scrapers"`` argument.
181
182 Be sure to set ``pyvista.BUILDING_GALLERY = True`` in your ``conf.py``.
183
184 If the boolean variable ``PYVISTA_GALLERY_FORCE_STATIC_IN_DOCUMENT = True/False``
185 is set as a global variable in the document then its value will be used as default for the
186 force_static argument of the pyvista-plot command. see also the notes at :func:plot_directive
187
188 To alter the global value behavior just for some plots you may set the
189 boolean variable ``PYVISTA_GALLERY_FORCE_STATIC = True``/
190 ``PYVISTA_GALLERY_FORCE_STATIC = False`` just before the appropriate ``plot`` command.
191
192 The default behavior of this scraper is to create interactive plots.
193
194 """
195
196 def __repr__(self) -> str:
197 """Return a stable representation of the class instance."""
198 return f'<{type(self).__name__} object>'
199
200 def __call__(self, block, block_vars, gallery_conf): # pragma: no cover
201 """Save the figures generated after running example code.
202
203 Called by sphinx-gallery.
204
205 """
206 if not pv.BUILDING_GALLERY:
207 raise RuntimeError(BUILDING_GALLERY_ERROR_MSG)
208
209 # read global option if it exists
210 force_static = block_vars['example_globals'].get(
211 'PYVISTA_GALLERY_FORCE_STATIC_IN_DOCUMENT',
212 False,
213 )
214 # override with block specific value if it exists
215 if 'PYVISTA_GALLERY_FORCE_STATIC = True' in block[1].split('\n'):
216 force_static = True
217 elif 'PYVISTA_GALLERY_FORCE_STATIC = False' in block[1].split('\n'):
218 force_static = False
219
220 if force_static is None:
221 # Just in case force_static is None at this point
222 force_static = False
223
224 dynamic = not force_static
225
226 image_path_iterator = block_vars['image_path_iterator']
227 image_names = generate_images(image_path_iterator, dynamic=dynamic)
228
229 return html_rst(image_names, gallery_conf['src_dir'])