| 1 |
"""Plot directive module. |
| 2 |
|
| 3 |
A directive for including a PyVista plot in a Sphinx document. |
| 4 |
|
| 5 |
The ``.. pyvista-plot::`` sphinx directive will include an inline |
| 6 |
``.png`` image. |
| 7 |
|
| 8 |
The source code for the plot may be included in one of two ways: |
| 9 |
|
| 10 |
1. Using **doctest** syntax:: |
| 11 |
|
| 12 |
.. pyvista-plot:: |
| 13 |
|
| 14 |
>>> import pyvista as pv |
| 15 |
>>> sphere = pv.Sphere() |
| 16 |
>>> out = sphere.plot() |
| 17 |
|
| 18 |
2. **A path to a source file** as the argument to the directive:: |
| 19 |
|
| 20 |
.. pyvista-plot:: path/to/plot.py |
| 21 |
|
| 22 |
When a path to a source file is given, the content of the |
| 23 |
directive may optionally contain a caption for the plot:: |
| 24 |
|
| 25 |
.. pyvista-plot:: path/to/plot.py |
| 26 |
|
| 27 |
The plot's caption. |
| 28 |
|
| 29 |
Additionally, one may specify the name of a function to call (with |
| 30 |
no arguments) immediately after importing the module:: |
| 31 |
|
| 32 |
.. pyvista-plot:: path/to/plot.py plot_function1 |
| 33 |
|
| 34 |
.. note:: |
| 35 |
Code blocks containing ``doctest:+SKIP`` will be skipped. |
| 36 |
|
| 37 |
.. note:: |
| 38 |
Animations will not be saved, only the last frame will be shown. |
| 39 |
|
| 40 |
|
| 41 |
**Options** |
| 42 |
The ``pyvista-plot`` directive supports the following options: |
| 43 |
|
| 44 |
include-source : bool |
| 45 |
Whether to display the source code. The default can be changed |
| 46 |
using the ``pyvista_plot_include_source`` variable in :file:`conf.py`. |
| 47 |
|
| 48 |
encoding : str |
| 49 |
If this source file is in a non-UTF8 or non-ASCII encoding, the |
| 50 |
encoding must be specified using the ``:encoding:`` option. The |
| 51 |
encoding will not be inferred using the ``-*- coding -*-`` metacomment. |
| 52 |
|
| 53 |
context : None |
| 54 |
If provided, the code will be run in the context of all previous plot |
| 55 |
directives for which the ``:context:`` option was specified. This only |
| 56 |
applies to inline code plot directives, not those run from files. |
| 57 |
|
| 58 |
nofigs : None |
| 59 |
When setting this flag, the code block will be run but no figures will be |
| 60 |
inserted. This is usually useful with the ``:context:`` option. |
| 61 |
|
| 62 |
caption : str |
| 63 |
If specified, the option's argument will be used as a caption for the |
| 64 |
figure. This overwrites the caption given in the content, when the plot |
| 65 |
is generated from a file. |
| 66 |
|
| 67 |
force_static : None |
| 68 |
When setting this flag, static images will be used instead of an |
| 69 |
interactive scene. |
| 70 |
|
| 71 |
skip : bool, default: True |
| 72 |
Whether to skip execution of this directive. If no argument is provided |
| 73 |
i.e., ``:skip:``, then it defaults to ``:skip: true``. Default |
| 74 |
behaviour is controlled by the ``plot_skip`` boolean variable in |
| 75 |
:file:`conf.py`. Note that, if specified, this option overrides the |
| 76 |
``plot_skip`` configuration. |
| 77 |
|
| 78 |
optional : None |
| 79 |
This flag marks the directive for *conditional* execution. Whether the |
| 80 |
directive is executed is controlled by the ``plot_skip_optional`` |
| 81 |
boolean variable in :file:`conf.py`. |
| 82 |
|
| 83 |
Additionally, this directive supports all the options of the `image` |
| 84 |
directive, except for *target* (since plot will add its own target). These |
| 85 |
include *alt*, *height*, *width*, *scale*, *align*. |
| 86 |
|
| 87 |
|
| 88 |
**Configuration options** |
| 89 |
|
| 90 |
.. versionchanged:: 0.45 |
| 91 |
Prior to v0.45, these directives conflicted with ``matplotlib``. All |
| 92 |
directives have been prepended with ``pyvista_``. |
| 93 |
|
| 94 |
The plot directive has the following configuration options: |
| 95 |
|
| 96 |
pyvista_plot_include_source : bool, default: True |
| 97 |
Default value for the ``include-source`` directive option. |
| 98 |
Default is ``True``. |
| 99 |
|
| 100 |
pyvista_plot_basedir : str |
| 101 |
Base directory, to which ``plot::`` file names are relative |
| 102 |
to. If ``None`` or unset, file names are relative to the |
| 103 |
directory where the file containing the directive is. |
| 104 |
|
| 105 |
pyvista_plot_html_show_formats : bool, default: True |
| 106 |
Whether to show links to the files in HTML. Default ``True``. |
| 107 |
|
| 108 |
pyvista_plot_template : str |
| 109 |
Provide a customized Jinja2 template for preparing restructured text. |
| 110 |
|
| 111 |
pyvista_plot_setup : str |
| 112 |
Python code to be run before every plot directive block. |
| 113 |
|
| 114 |
pyvista_plot_cleanup : str |
| 115 |
Python code to be run after every plot directive block. |
| 116 |
|
| 117 |
pyvista_plot_skip : bool, default: False |
| 118 |
Default value for the ``skip`` directive option. |
| 119 |
|
| 120 |
pyvista_plot_skip_optional : bool, default: False |
| 121 |
Whether to skip execution of ``optional`` directives. |
| 122 |
|
| 123 |
These options can be set by defining global variables of the same name in |
| 124 |
:file:`conf.py`. |
| 125 |
|
| 126 |
|
| 127 |
**Directive Configuration Settings** |
| 128 |
|
| 129 |
Globally, you can set if the file names should be either: |
| 130 |
|
| 131 |
* Deterministic, based on directive source hash: |
| 132 |
``<BASENAME>-<HASH>_<INDEX>_<SUBINDEX>.<EXT>`` (Default) |
| 133 |
* Indexed, based on location in document: |
| 134 |
``<BASENAME>-<DOC-INDEX>_<INDEX>_<SUBINDEX>.<EXT>`` |
| 135 |
|
| 136 |
Enable indexed naming this by setting ``pyvista_plot_use_counter=True``. Note |
| 137 |
that indexed is incompatible with parallel builds due to race conditions. |
| 138 |
|
| 139 |
.. versionchanged:: 0.47 |
| 140 |
Hash-based image naming is now used by default. |
| 141 |
""" |
| 142 |
|
| 143 |
from __future__ import annotations |
| 144 |
|
| 145 |
import doctest |
| 146 |
import hashlib |
| 147 |
import os |
| 148 |
from os.path import relpath |
| 149 |
from pathlib import Path |
| 150 |
import re |
| 151 |
import shutil |
| 152 |
import textwrap |
| 153 |
import traceback |
| 154 |
from typing import TYPE_CHECKING |
| 155 |
from typing import ClassVar |
| 156 |
|
| 157 |
from docutils.parsers.rst import Directive |
| 158 |
from docutils.parsers.rst import directives |
| 159 |
from docutils.parsers.rst.directives.images import Image |
| 160 |
import jinja2 # Sphinx dependency. |
| 161 |
|
| 162 |
# must enable BUILDING_GALLERY to keep windows active |
| 163 |
# enable offscreen to hide figures when generating them. |
| 164 |
import pyvista as pv |
| 165 |
|
| 166 |
if TYPE_CHECKING: |
| 167 |
from collections.abc import Callable |
| 168 |
|
| 169 |
from sphinx.application import Sphinx |
| 170 |
from sphinx.config import Config |
| 171 |
|
| 172 |
|
| 173 |
pv.BUILDING_GALLERY = True |
| 174 |
pv.OFF_SCREEN = True |
| 175 |
|
| 176 |
# ----------------------------------------------------------------------------- |
| 177 |
# Registration hook |
| 178 |
# ----------------------------------------------------------------------------- |
| 179 |
|
| 180 |
|
| 181 |
def _option_boolean(arg) -> bool: |
| 182 |
if not arg or not arg.strip(): |
| 183 |
# no argument given, assume used as a flag |
| 184 |
return True |
| 185 |
elif arg.strip().lower() in ('no', '0', 'false'): |
| 186 |
return False |
| 187 |
elif arg.strip().lower() in ('yes', '1', 'true'): |
| 188 |
return True |
| 189 |
else: # pragma: no cover |
| 190 |
msg = f'"{arg}" unknown boolean' |
| 191 |
raise ValueError(msg) |
| 192 |
|
| 193 |
|
| 194 |
def _option_context(arg): |
| 195 |
if arg is not None: # pragma: no cover |
| 196 |
msg = 'No arguments allowed for ``:context:``' |
| 197 |
raise ValueError(msg) |
| 198 |
|
| 199 |
|
| 200 |
def _option_format(arg): |
| 201 |
return directives.choice(arg, ('python', 'doctest')) |
| 202 |
|
| 203 |
|
| 204 |
class PlotDirective(Directive): |
| 205 |
"""The ``.. pyvista-plot::`` directive, as documented in the module's docstring.""" |
| 206 |
|
| 207 |
has_content = True |
| 208 |
required_arguments = 0 |
| 209 |
optional_arguments = 2 |
| 210 |
final_argument_whitespace = False |
| 211 |
option_spec: ClassVar[dict[str, Callable]] = { |
| 212 |
'alt': directives.unchanged, |
| 213 |
'height': directives.length_or_unitless, |
| 214 |
'width': directives.length_or_percentage_or_unitless, |
| 215 |
'scale': directives.nonnegative_int, |
| 216 |
'align': Image.align, |
| 217 |
'include-source': _option_boolean, |
| 218 |
'format': _option_format, |
| 219 |
'context': _option_context, |
| 220 |
'nofigs': directives.flag, |
| 221 |
'encoding': directives.encoding, |
| 222 |
'caption': directives.unchanged, |
| 223 |
'force_static': directives.flag, |
| 224 |
'skip': _option_boolean, |
| 225 |
'optional': directives.flag, |
| 226 |
} |
| 227 |
|
| 228 |
def run(self): |
| 229 |
"""Run the plot directive.""" |
| 230 |
try: |
| 231 |
return run( |
| 232 |
self.arguments, |
| 233 |
self.content, |
| 234 |
self.options, |
| 235 |
self.state_machine, |
| 236 |
self.state, |
| 237 |
self.lineno, |
| 238 |
) |
| 239 |
except Exception as e: # noqa: BLE001 # pragma: no cover |
| 240 |
raise self.error(str(e)) |
| 241 |
|
| 242 |
|
| 243 |
def setup(app: Sphinx): |
| 244 |
"""Set up the plot directive.""" |
| 245 |
setup.app = app |
| 246 |
setup.config = app.config |
| 247 |
setup.confdir = app.confdir |
| 248 |
app.add_directive('pyvista-plot', PlotDirective) |
| 249 |
|
| 250 |
legacy_keys = [ |
| 251 |
'plot_include_source', |
| 252 |
'plot_basedir', |
| 253 |
'plot_html_show_formats', |
| 254 |
'plot_template', |
| 255 |
'plot_setup', |
| 256 |
'plot_cleanup', |
| 257 |
'plot_skip', |
| 258 |
'plot_skip_optional', |
| 259 |
] |
| 260 |
|
| 261 |
def raise_on_legacy_config(app: Sphinx, config: Config) -> None: |
| 262 |
"""Raise a RuntimeError when using legacy configuration parameters. |
| 263 |
|
| 264 |
These parameters conflict with matplotlib's ``plot_directive``. |
| 265 |
|
| 266 |
""" |
| 267 |
uses_matplotlib = 'matplotlib.sphinxext.plot_directive' in app.extensions |
| 268 |
|
| 269 |
if not uses_matplotlib: # pragma: no cover |
| 270 |
for key in legacy_keys: |
| 271 |
if getattr(config, key, None) is not None: |
| 272 |
msg = ( |
| 273 |
f"Sphinx config uses deprecated '{key}' without 'pyvista_' prefix. " |
| 274 |
f"Rename it to 'pyvista_{key}" |
| 275 |
) |
| 276 |
raise RuntimeError(msg) |
| 277 |
|
| 278 |
app.connect('config-inited', raise_on_legacy_config) |
| 279 |
|
| 280 |
def check_counter_for_parallel_build(app: Sphinx, config: Config) -> None: |
| 281 |
if config.pyvista_plot_use_counter and app.parallel > 1: |
| 282 |
msg = ( |
| 283 |
"The 'pyvista_plot_use_counter' option cannot be enabled for parallel builds." |
| 284 |
" Set 'pyvista_plot_use_counter = False' in your conf.py" |
| 285 |
' or disable parallel builds.' |
| 286 |
) |
| 287 |
raise RuntimeError(msg) |
| 288 |
|
| 289 |
# Connect the new function to the 'config-inited' event |
| 290 |
app.connect('config-inited', check_counter_for_parallel_build) |
| 291 |
|
| 292 |
app.add_config_value('pyvista_plot_use_counter', False, 'env') |
| 293 |
app.add_config_value('pyvista_plot_include_source', True, False) |
| 294 |
app.add_config_value('pyvista_plot_basedir', None, True) |
| 295 |
app.add_config_value('pyvista_plot_html_show_formats', True, True) |
| 296 |
app.add_config_value('pyvista_plot_template', None, True) |
| 297 |
app.add_config_value('pyvista_plot_setup', None, True) |
| 298 |
app.add_config_value('pyvista_plot_cleanup', None, True) |
| 299 |
app.add_config_value(name='pyvista_plot_skip', default=False, rebuild='html') |
| 300 |
app.add_config_value(name='pyvista_plot_skip_optional', default=False, rebuild='html') |
| 301 |
return { |
| 302 |
'parallel_read_safe': True, |
| 303 |
'parallel_write_safe': True, |
| 304 |
'version': pv.__version__, |
| 305 |
} |
| 306 |
|
| 307 |
|
| 308 |
# ----------------------------------------------------------------------------- |
| 309 |
# Doctest handling |
| 310 |
# ----------------------------------------------------------------------------- |
| 311 |
def _contains_doctest(text): |
| 312 |
try: |
| 313 |
# check if it's valid Python as-is |
| 314 |
compile(text, '<string>', 'exec') |
| 315 |
except SyntaxError: |
| 316 |
pass |
| 317 |
else: |
| 318 |
return False |
| 319 |
r = re.compile(r'^\s*>>>', re.MULTILINE) |
| 320 |
m = r.search(text) |
| 321 |
return bool(m) |
| 322 |
|
| 323 |
|
| 324 |
def _contains_pyvista_plot(text) -> bool: |
| 325 |
return '.. pyvista-plot::' in text |
| 326 |
|
| 327 |
|
| 328 |
def _strip_comments(code): |
| 329 |
"""Remove comments from a line of python code.""" |
| 330 |
return re.sub(r'(?m)^ *#.*\n?', '', code) |
| 331 |
|
| 332 |
|
| 333 |
def _split_code_at_show(text): |
| 334 |
"""Split code at plt.show() or plt.plot(). |
| 335 |
|
| 336 |
Includes logic to deal with edge cases like: |
| 337 |
|
| 338 |
>>> import pyvista as pv |
| 339 |
>>> pv.Sphere().plot(color='blue', cpos='xy') |
| 340 |
|
| 341 |
>>> pv.Sphere().plot(color='red', cpos='xy') |
| 342 |
|
| 343 |
""" |
| 344 |
parts = [] |
| 345 |
is_doctest = _contains_doctest(text) |
| 346 |
part = [] |
| 347 |
|
| 348 |
within_plot = False |
| 349 |
for line in text.split('\n'): |
| 350 |
part.append(line) |
| 351 |
|
| 352 |
# check if show(...) or plot(...) is within the line |
| 353 |
line_no_comments = _strip_comments(line) |
| 354 |
if within_plot: # allow for multi-line plot(... |
| 355 |
if line_no_comments.endswith(')'): |
| 356 |
parts.append('\n'.join(part)) |
| 357 |
part = [] |
| 358 |
within_plot = False |
| 359 |
|
| 360 |
elif _show_or_plot_in_string(line_no_comments): |
| 361 |
if line_no_comments.endswith(')'): |
| 362 |
parts.append('\n'.join(part)) |
| 363 |
part = [] |
| 364 |
else: # allow for multi-line plot(... |
| 365 |
within_plot = True |
| 366 |
|
| 367 |
if '\n'.join(part).strip(): |
| 368 |
parts.append('\n'.join(part)) |
| 369 |
return is_doctest, parts |
| 370 |
|
| 371 |
|
| 372 |
def _show_or_plot_in_string(string): |
| 373 |
# string contains `.show(`, `.plot(`, or `plot_xyz(` where `xyz` is one |
| 374 |
# or more lower-case letters or underscore, e.g. `plot_cell(`, `plot_datasets(` |
| 375 |
pattern = r'(?:\.plot\(|\.show\(|(?:[ \t\n.]plot_[a-z_]+?)\()' |
| 376 |
return bool(re.search(pattern, string)) |
| 377 |
|
| 378 |
|
| 379 |
# ----------------------------------------------------------------------------- |
| 380 |
# Template |
| 381 |
# ----------------------------------------------------------------------------- |
| 382 |
|
| 383 |
TEMPLATE = """ |
| 384 |
{{ source_code }} |
| 385 |
|
| 386 |
.. only:: html |
| 387 |
|
| 388 |
{% for img in images %} |
| 389 |
{% if img.extension == 'vtksz' %} |
| 390 |
|
| 391 |
.. tab-set:: |
| 392 |
|
| 393 |
.. tab-item:: Static Scene |
| 394 |
|
| 395 |
.. figure:: {{ build_dir }}/{{ img.stem }}.png |
| 396 |
{% for option in options -%} |
| 397 |
{{ option }} |
| 398 |
{% endfor %} |
| 399 |
|
| 400 |
|
| 401 |
.. tab-item:: Interactive Scene |
| 402 |
|
| 403 |
.. offlineviewer:: {{ build_dir }}/{{ img.stem }}.vtksz |
| 404 |
|
| 405 |
{{ caption }} {# appropriate leading whitespace added beforehand #} |
| 406 |
{% else %} |
| 407 |
.. figure:: {{ build_dir }}/{{ img.basename }} |
| 408 |
{% for option in options -%} |
| 409 |
{{ option }} |
| 410 |
{% endfor %} |
| 411 |
|
| 412 |
{{ caption }} {# appropriate leading whitespace added beforehand #} |
| 413 |
{% endif %} |
| 414 |
{% endfor %} |
| 415 |
|
| 416 |
""" |
| 417 |
|
| 418 |
exception_template = """ |
| 419 |
.. only:: html |
| 420 |
|
| 421 |
[`source code <%(linkdir)s/%(basename)s.py>`__] |
| 422 |
|
| 423 |
Exception occurred rendering plot. |
| 424 |
|
| 425 |
""" |
| 426 |
|
| 427 |
# the context of the plot for all directives specified with the |
| 428 |
# :context: option |
| 429 |
plot_context = {} |
| 430 |
|
| 431 |
|
| 432 |
class ImageFile: |
| 433 |
"""Simple representation of an image file path.""" |
| 434 |
|
| 435 |
def __init__(self, dirname, basename): |
| 436 |
"""Construct ImageFile.""" |
| 437 |
self.basename = basename |
| 438 |
self.dirname = dirname |
| 439 |
self.extension = Path(basename).suffix[1:] |
| 440 |
|
| 441 |
@property |
| 442 |
def filename(self): |
| 443 |
"""Return the filename of this image.""" |
| 444 |
return str(Path(self.dirname) / self.basename) |
| 445 |
|
| 446 |
@property |
| 447 |
def stem(self): |
| 448 |
"""Return the basename without the suffix.""" |
| 449 |
return Path(self.basename).stem |
| 450 |
|
| 451 |
def __repr__(self) -> str: # pragma no cover |
| 452 |
return self.filename |
| 453 |
|
| 454 |
|
| 455 |
class PlotError(RuntimeError): |
| 456 |
"""More descriptive plot error.""" |
| 457 |
|
| 458 |
|
| 459 |
def _run_code(*, code, code_path, ns=None, function_name=None): # noqa: ARG001 |
| 460 |
"""Run a docstring example. |
| 461 |
|
| 462 |
Run the example if it does not contain ``'doctest:+SKIP'``, or a |
| 463 |
```pyvista-plot::`` directive. In the later case, the doctest parser will |
| 464 |
present the code-block again with the ```pyvista-plot::`` directive |
| 465 |
and its options removed. |
| 466 |
|
| 467 |
Import a Python module from a path, and run the function given by |
| 468 |
name, if function_name is not None. |
| 469 |
""" |
| 470 |
# do not execute code containing any SKIP directives |
| 471 |
if 'doctest:+SKIP' in code: |
| 472 |
return ns |
| 473 |
|
| 474 |
if 'pyvista-plot::' in code: |
| 475 |
return ns |
| 476 |
|
| 477 |
try: |
| 478 |
if pv.PLOT_DIRECTIVE_THEME is not None: |
| 479 |
pv.set_plot_theme(pv.PLOT_DIRECTIVE_THEME) # pragma: no cover |
| 480 |
exec(code, ns) # noqa: S102 |
| 481 |
except (Exception, SystemExit) as err: # pragma: no cover |
| 482 |
# Annotate traceback with source file and line |
| 483 |
tb = traceback.format_exc() |
| 484 |
msg = f'Error in {code_path}:\n{tb}' |
| 485 |
raise PlotError(msg) from err |
| 486 |
|
| 487 |
return ns |
| 488 |
|
| 489 |
|
| 490 |
def render_figures( |
| 491 |
*, |
| 492 |
code, |
| 493 |
code_path, |
| 494 |
output_dir, |
| 495 |
output_base, |
| 496 |
context, |
| 497 |
function_name, |
| 498 |
config, |
| 499 |
force_static, |
| 500 |
): |
| 501 |
"""Run a pyplot script and save the images in *output_dir*. |
| 502 |
|
| 503 |
Save the images under *output_dir* with file names derived from |
| 504 |
*output_base*. Closed plotters are ignored if they were never |
| 505 |
rendered. |
| 506 |
""" |
| 507 |
# We skip snippets that contain the ```pyvista-plot::`` directive as part of their code. |
| 508 |
# The doctest parser will present the code-block once again with the ```pyvista-plot::`` |
| 509 |
# directive and its options properly parsed. |
| 510 |
if _contains_pyvista_plot(code): |
| 511 |
is_doctest = True |
| 512 |
code_pieces = [code] |
| 513 |
else: |
| 514 |
# Try to determine if all images already exist |
| 515 |
is_doctest, code_pieces = _split_code_at_show(code) |
| 516 |
|
| 517 |
# Otherwise, we didn't find the files, so build them |
| 518 |
results = [] |
| 519 |
ns = plot_context if context else {} |
| 520 |
|
| 521 |
# Check for setup and teardown code for plots |
| 522 |
code_setup = config.pyvista_plot_setup |
| 523 |
code_cleanup = config.pyvista_plot_cleanup |
| 524 |
|
| 525 |
if code_setup: |
| 526 |
_run_code(code=code_setup, code_path=code_path, ns=ns, function_name=function_name) |
| 527 |
|
| 528 |
try: |
| 529 |
for i, code_piece in enumerate(code_pieces): |
| 530 |
# generate the plot |
| 531 |
_run_code( |
| 532 |
code=doctest.script_from_examples(code_piece) if is_doctest else code_piece, |
| 533 |
code_path=code_path, |
| 534 |
ns=ns, |
| 535 |
function_name=function_name, |
| 536 |
) |
| 537 |
|
| 538 |
images = [] |
| 539 |
|
| 540 |
if ( |
| 541 |
_show_or_plot_in_string(code_piece) |
| 542 |
or '.open_gif' in code_piece |
| 543 |
or 'plot=True' in code_piece |
| 544 |
): |
| 545 |
figures = pv.plotting.plotter._ALL_PLOTTERS |
| 546 |
|
| 547 |
for j, (_, plotter) in enumerate(figures.items()): |
| 548 |
if plotter._gif_filename is not None: |
| 549 |
image_file = ImageFile(output_dir, f'{output_base}_{i:02d}_{j:02d}.gif') |
| 550 |
shutil.move(plotter._gif_filename, image_file.filename) |
| 551 |
else: |
| 552 |
image_file = ImageFile(output_dir, f'{output_base}_{i:02d}_{j:02d}.png') |
| 553 |
try: |
| 554 |
plotter.screenshot(image_file.filename) |
| 555 |
except RuntimeError: # pragma no cover |
| 556 |
# ignore closed, unrendered plotters |
| 557 |
continue |
| 558 |
if force_static or (plotter.last_vtksz is None): |
| 559 |
images.append(image_file) |
| 560 |
continue |
| 561 |
else: |
| 562 |
image_file = ImageFile( |
| 563 |
output_dir, f'{output_base}_{i:02d}_{j:02d}.vtksz' |
| 564 |
) |
| 565 |
with Path(image_file.filename).open('wb') as f: |
| 566 |
f.write(plotter.last_vtksz) |
| 567 |
images.append(image_file) |
| 568 |
|
| 569 |
pv.close_all() # close and clear all plotters |
| 570 |
|
| 571 |
results.append((code_piece, images)) |
| 572 |
finally: |
| 573 |
if code_cleanup: |
| 574 |
_run_code(code=code_cleanup, code_path=code_path, ns=ns, function_name=function_name) |
| 575 |
|
| 576 |
return results |
| 577 |
|
| 578 |
|
| 579 |
def _contains_doctest(text: str) -> bool: |
| 580 |
"""Check if the text contains doctest markers.""" |
| 581 |
r = re.compile(r'^\s*>>>', re.MULTILINE) |
| 582 |
m = r.search(text) |
| 583 |
return bool(m) |
| 584 |
|
| 585 |
|
| 586 |
def hash_plot_code(code: str, options: dict) -> str: |
| 587 |
"""Generate a hash of the plot code.""" |
| 588 |
# convert to plain script if doctest code |
| 589 |
script = doctest.script_from_examples(code) if _contains_doctest(code) else code |
| 590 |
|
| 591 |
lines = [] |
| 592 |
for line in script.splitlines(): |
| 593 |
line_without_comments = re.sub(r'(?<!["\'])#.*', '', line).strip() |
| 594 |
if line_without_comments: |
| 595 |
lines.append(line_without_comments) |
| 596 |
clean_script = textwrap.dedent('\n'.join(lines)) |
| 597 |
|
| 598 |
parts = [ |
| 599 |
'ctx=' + str('context' in options), |
| 600 |
clean_script, |
| 601 |
] |
| 602 |
|
| 603 |
# first 16 char should be sufficient |
| 604 |
return hashlib.sha256(''.join(parts).encode('utf-8')).hexdigest()[:16] |
| 605 |
|
| 606 |
|
| 607 |
def run(arguments, content, options, state_machine, state, lineno): # noqa: PLR0917 |
| 608 |
"""Run the plot directive.""" |
| 609 |
document = state_machine.document |
| 610 |
config = document.settings.env.config |
| 611 |
nofigs = 'nofigs' in options |
| 612 |
optional = 'optional' in options |
| 613 |
force_static = 'force_static' in options |
| 614 |
use_counter = config.pyvista_plot_use_counter |
| 615 |
|
| 616 |
default_fmt = 'png' |
| 617 |
|
| 618 |
options.setdefault('include-source', config.pyvista_plot_include_source) |
| 619 |
options.setdefault('skip', config.pyvista_plot_skip) |
| 620 |
|
| 621 |
skip = options['skip'] or (optional and config.pyvista_plot_skip_optional) |
| 622 |
|
| 623 |
keep_context = 'context' in options |
| 624 |
_ = None if not keep_context else options['context'] |
| 625 |
|
| 626 |
rst_file = document.attributes['source'] |
| 627 |
rst_dir = str(Path(rst_file).parent) |
| 628 |
|
| 629 |
if len(arguments): |
| 630 |
if not config.pyvista_plot_basedir: |
| 631 |
source_file_name = str(Path(setup.app.builder.srcdir) / directives.uri(arguments[0])) |
| 632 |
else: |
| 633 |
source_file_name = str( |
| 634 |
Path(setup.confdir) / config.pyvista_plot_basedir / directives.uri(arguments[0]), |
| 635 |
) |
| 636 |
|
| 637 |
# If there is content, it will be passed as a caption. |
| 638 |
caption = '\n'.join(content) |
| 639 |
|
| 640 |
# Enforce unambiguous use of captions. |
| 641 |
if 'caption' in options: |
| 642 |
if caption: # pragma: no cover |
| 643 |
msg = 'Caption specified in both content and options. Please remove ambiguity.' |
| 644 |
raise ValueError(msg) |
| 645 |
# Use caption option |
| 646 |
caption = options['caption'] |
| 647 |
|
| 648 |
# If the optional function name is provided, use it |
| 649 |
function_name = arguments[1] if len(arguments) == 2 else None |
| 650 |
|
| 651 |
code = Path(source_file_name).read_text(encoding='utf-8') |
| 652 |
output_base = Path(source_file_name).name |
| 653 |
else: |
| 654 |
source_file_name = rst_file |
| 655 |
code = textwrap.dedent('\n'.join(map(str, content))) |
| 656 |
|
| 657 |
base = Path(source_file_name).stem |
| 658 |
ext = Path(source_file_name).suffix |
| 659 |
function_name = None |
| 660 |
caption = options.get('caption', '') |
| 661 |
|
| 662 |
if use_counter: |
| 663 |
counter = document.attributes.get('_plot_counter', 0) + 1 |
| 664 |
document.attributes['_plot_counter'] = counter |
| 665 |
output_base = f'{base}-{counter}{ext}' |
| 666 |
else: |
| 667 |
code_hash = hash_plot_code(code, options) |
| 668 |
output_base = f'{base}-{code_hash}{ext}' |
| 669 |
|
| 670 |
base = Path(output_base).stem |
| 671 |
source_ext = Path(output_base).suffix |
| 672 |
if source_ext in ('.py', '.rst', '.txt'): |
| 673 |
output_base = base |
| 674 |
else: |
| 675 |
source_ext = '' |
| 676 |
|
| 677 |
# ensure that LaTeX includegraphics doesn't choke in foo.bar.pdf filenames |
| 678 |
output_base = output_base.replace('.', '-') |
| 679 |
|
| 680 |
# is it in doctest format? |
| 681 |
is_doctest = _contains_doctest(code) |
| 682 |
if 'format' in options: |
| 683 |
is_doctest = options['format'] != 'python' |
| 684 |
|
| 685 |
# determine output directory name fragment |
| 686 |
source_rel_name = relpath(source_file_name, setup.confdir) |
| 687 |
source_rel_dir = str(Path(source_rel_name).parent).lstrip(os.path.sep) |
| 688 |
|
| 689 |
# build_dir: where to place output files (temporarily) |
| 690 |
build_dir = str(Path(setup.app.doctreedir).parent / 'plot_directive' / source_rel_dir) |
| 691 |
# get rid of .. in paths, also changes pathsep |
| 692 |
# see note in Python docs for warning about symbolic links on Windows. |
| 693 |
# need to compare source and dest paths at end |
| 694 |
build_dir = os.path.normpath(build_dir) |
| 695 |
Path(build_dir).mkdir(parents=True, exist_ok=True) |
| 696 |
|
| 697 |
# output_dir: final location in the builder's directory |
| 698 |
dest_dir = str((Path(setup.app.builder.outdir) / source_rel_dir).resolve()) |
| 699 |
Path(dest_dir).mkdir(parents=True, exist_ok=True) |
| 700 |
|
| 701 |
# how to link to files from the RST file |
| 702 |
dest_dir_link = os.path.join( # noqa: PTH118 |
| 703 |
relpath(setup.confdir, rst_dir), |
| 704 |
source_rel_dir, |
| 705 |
).replace(os.path.sep, '/') |
| 706 |
try: |
| 707 |
build_dir_link = relpath(build_dir, rst_dir).replace(os.path.sep, '/') |
| 708 |
except ValueError: # pragma: no cover |
| 709 |
# on Windows, relpath raises ValueError when path and start are on |
| 710 |
# different mounts/drives |
| 711 |
build_dir_link = build_dir |
| 712 |
_ = dest_dir_link + '/' + output_base + source_ext |
| 713 |
|
| 714 |
# make figures |
| 715 |
errors = [] |
| 716 |
if skip: |
| 717 |
results = [(code, [])] |
| 718 |
else: |
| 719 |
try: |
| 720 |
results = render_figures( |
| 721 |
code=code, |
| 722 |
code_path=source_file_name, |
| 723 |
output_dir=build_dir, |
| 724 |
output_base=output_base, |
| 725 |
context=keep_context, |
| 726 |
function_name=function_name, |
| 727 |
config=config, |
| 728 |
force_static=force_static, |
| 729 |
) |
| 730 |
except PlotError as err: # pragma: no cover |
| 731 |
reporter = state.memo.reporter |
| 732 |
sm = reporter.system_message( |
| 733 |
2, |
| 734 |
f'Exception occurred in plotting {output_base}\n from {source_file_name}:\n{err}', |
| 735 |
line=lineno, |
| 736 |
) |
| 737 |
results = [(code, [])] |
| 738 |
errors.append(sm) |
| 739 |
|
| 740 |
# Properly indent the caption |
| 741 |
caption = ( |
| 742 |
'' if skip else '\n' + '\n'.join(' ' + line.strip() for line in caption.split('\n')) |
| 743 |
) |
| 744 |
|
| 745 |
# generate output restructuredtext |
| 746 |
total_lines = [] |
| 747 |
for _, (code_piece, images) in enumerate(results): |
| 748 |
if options['include-source']: |
| 749 |
if is_doctest: |
| 750 |
lines = ['', *code_piece.splitlines()] |
| 751 |
else: |
| 752 |
lines = [ |
| 753 |
'.. code-block:: python', |
| 754 |
'', |
| 755 |
*textwrap.indent(code_piece, ' ').splitlines(), |
| 756 |
] |
| 757 |
source_code = '\n'.join(lines) |
| 758 |
else: |
| 759 |
source_code = '' |
| 760 |
|
| 761 |
images_input = [] if nofigs else images |
| 762 |
|
| 763 |
opts = [ |
| 764 |
f':{key}: {val}' |
| 765 |
for key, val in options.items() |
| 766 |
if key in ('alt', 'height', 'width', 'scale', 'align') |
| 767 |
] |
| 768 |
|
| 769 |
result = jinja2.Template(config.pyvista_plot_template or TEMPLATE).render( |
| 770 |
default_fmt=default_fmt, |
| 771 |
dest_dir=dest_dir_link, |
| 772 |
build_dir=build_dir_link, |
| 773 |
source_link=None, |
| 774 |
multi_image=len(images_input) > 1, |
| 775 |
options=opts, |
| 776 |
images=images_input, |
| 777 |
source_code=source_code, |
| 778 |
html_show_formats=config.pyvista_plot_html_show_formats and len(images_input), |
| 779 |
caption=caption, |
| 780 |
) |
| 781 |
|
| 782 |
total_lines.extend(result.split('\n')) |
| 783 |
total_lines.extend('\n') |
| 784 |
|
| 785 |
# If there were errors, return the Node objects to Sphinx now. |
| 786 |
if errors: # pragma: no cover |
| 787 |
return errors |
| 788 |
|
| 789 |
if total_lines: |
| 790 |
state_machine.insert_input(total_lines, source=source_file_name) |
| 791 |
|
| 792 |
# copy image files to builder's output directory, if necessary |
| 793 |
Path(dest_dir).mkdir(parents=True, exist_ok=True) |
| 794 |
|
| 795 |
for _, images in results: |
| 796 |
for image in images: |
| 797 |
destimg = str(Path(dest_dir) / image.basename) |
| 798 |
if image.filename != destimg: |
| 799 |
shutil.copyfile(image.filename, destimg) |
| 800 |
|
| 801 |
# copy script (if necessary) |
| 802 |
Path(dest_dir, output_base + source_ext).write_text( |
| 803 |
doctest.script_from_examples(code) |
| 804 |
if source_file_name == rst_file and is_doctest |
| 805 |
else code, |
| 806 |
encoding='utf-8', |
| 807 |
) |
| 808 |
|
| 809 |
return errors |