From 3496739b26ddd003eb628c38add1f7801a45321f Mon Sep 17 00:00:00 2001 From: Richard Barnes Date: Wed, 3 Jan 2018 13:20:27 -0600 Subject: [PATCH 1/4] Added `:outname:` option and `plot_preserve_dir` configuration value Fix bug with adding null string to outname_list --- lib/matplotlib/sphinxext/plot_directive.py | 59 +++++++++++++++++++++- 1 file changed, 57 insertions(+), 2 deletions(-) diff --git a/lib/matplotlib/sphinxext/plot_directive.py b/lib/matplotlib/sphinxext/plot_directive.py index c154baeaf361..617cae6fcf18 100644 --- a/lib/matplotlib/sphinxext/plot_directive.py +++ b/lib/matplotlib/sphinxext/plot_directive.py @@ -77,6 +77,11 @@ If specified, the option's argument will be used as a caption for the figure. This overwrites the caption given in the content, when the plot is generated from a file. + ``:outname:`` : str + If specified, the names of the generated plots will start with the value + of `:outname:`. This is handy for preserving output results if code is + reordered between runs. The value of `:outname:` must be unique across + the generated documentation. Additionally, this directive supports all the options of the `image directive `_, @@ -139,6 +144,11 @@ plot_template Provide a customized template for preparing restructured text. + + plot_preserve_dir + Files with outnames are copied to this directory and files in this + directory are copied back from into the build directory prior to the + build beginning. """ import contextlib @@ -146,6 +156,12 @@ from io import StringIO import itertools import os +import sys +import shutil +import io +import re +import textwrap +import glob from os.path import relpath from pathlib import Path import re @@ -167,6 +183,10 @@ __version__ = 2 +#Outnames must be unique. This variable stores the outnames that +#have been seen so we can guarantee this and warn the user if a +#duplicate is encountered. +outname_list = set() # ----------------------------------------------------------------------------- # Registration hook @@ -245,6 +265,7 @@ class PlotDirective(Directive): 'context': _option_context, 'nofigs': directives.flag, 'caption': directives.unchanged, + 'outname': str } def run(self): @@ -280,6 +301,7 @@ def setup(app): app.add_config_value('plot_apply_rcparams', False, True) app.add_config_value('plot_working_directory', None, True) app.add_config_value('plot_template', None, True) + app.add_config_value('plot_preserve_dir', '', True) app.connect('doctree-read', mark_plot_labels) app.add_css_file('plot_directive.css') app.connect('build-finished', _copy_css_file) @@ -517,7 +539,8 @@ def get_plot_formats(config): def render_figures(code, code_path, output_dir, output_base, context, function_name, config, context_reset=False, close_figs=False, - code_includes=None): + code_includes=None, + outname=''): """ Run a pyplot script and save the images in *output_dir*. @@ -613,6 +636,9 @@ def render_figures(code, code_path, output_dir, output_base, context, for fmt, dpi in formats: try: figman.canvas.figure.savefig(img.filename(fmt), dpi=dpi) + if config.plot_preserve_dir and outname: + print("Preserving '{0}' into '{1}'".format(img.filename(format), config.plot_preserve_dir)) + shutil.copy2(img.filename(format), config.plot_preserve_dir) except Exception as err: raise PlotError(traceback.format_exc()) from err img.formats.append(fmt) @@ -648,6 +674,20 @@ def run(arguments, content, options, state_machine, state, lineno): rst_file = document.attributes['source'] rst_dir = os.path.dirname(rst_file) + #Get output name of the images, if the option was provided + outname = options.get('outname', '') + + #Ensure that the outname is unique, otherwise copied images will + #not be what user expects + if outname and outname in outname_list: + raise Exception("The outname '{0}' is not unique!".format(outname)) + else: + outname_list.add(outname) + + if config.plot_preserve_dir: + #Ensure `preserve_dir` ends with a slash, otherwise `copy2` will misbehave + config.plot_preserve_dir = os.path.join(config.plot_preserve_dir, '') + if len(arguments): if not config.plot_basedir: source_file_name = os.path.join(setup.app.builder.srcdir, @@ -693,6 +733,11 @@ def run(arguments, content, options, state_machine, state, lineno): else: source_ext = '' + #outname, if present, overrides output_base, but preserve + #numbering of multi-figure code snippets + if outname: + output_base = re.sub('^[^-]*', outname, output_base) + # ensure that LaTeX includegraphics doesn't choke in foo.bar.pdf filenames output_base = output_base.replace('.', '-') @@ -753,6 +798,15 @@ def run(arguments, content, options, state_machine, state, lineno): else code, encoding='utf-8') + #If we previously preserved copies of the generated figures + #this copies them into the build directory so that they will + #not be remade + if config.plot_preserve_dir and outname: + outfiles = glob.glob(os.path.join(config.plot_preserve_dir,outname) + '*') + for of in outfiles: + print("Copying preserved copy of '{0}' into '{1}'".format(of, build_dir)) + shutil.copy2(of, build_dir) + # make figures try: results = render_figures(code=code, @@ -764,7 +818,8 @@ def run(arguments, content, options, state_machine, state, lineno): config=config, context_reset=context_opt == 'reset', close_figs=context_opt == 'close-figs', - code_includes=source_file_includes) + code_includes=source_file_includes, + outname= utname) errors = [] except PlotError as err: reporter = state.memo.reporter From c2c50a4a83b976c524dc6288e5d7dcfb2275ffe9 Mon Sep 17 00:00:00 2001 From: Richard Barnes Date: Wed, 3 Jan 2018 13:39:41 -0600 Subject: [PATCH 2/4] Added What's New for plot directive changes Futzing with PEP8 whitespace stuff. Fix grammer Examples of using rst need to be code blocks Use logging instead of print Satisfy PEP8 checks FIX: issue with rebase due to re-naming of local variables STY: fix line length and indentation issues STY: trim whitespace and add trailing comma Fix doc style flake8 fixes plot_preserve_dir > plot_cache_dir Copy edit changelog entry --- .../next_whats_new/sphinx_plot_preserve.rst | 32 +++++++ lib/matplotlib/sphinxext/plot_directive.py | 86 ++++++++++--------- 2 files changed, 77 insertions(+), 41 deletions(-) create mode 100644 doc/users/next_whats_new/sphinx_plot_preserve.rst diff --git a/doc/users/next_whats_new/sphinx_plot_preserve.rst b/doc/users/next_whats_new/sphinx_plot_preserve.rst new file mode 100644 index 000000000000..88d70c86a02c --- /dev/null +++ b/doc/users/next_whats_new/sphinx_plot_preserve.rst @@ -0,0 +1,32 @@ +Caching sphinx directive figure outputs +--------------------------------------- + +The new ``:outname:`` property for the Sphinx plot directive can +be used to cache generated images. It is used like: + +.. code-block:: rst + + .. plot:: + :outname: stinkbug_plot + + import matplotlib.pyplot as plt + import matplotlib.image as mpimg + import numpy as np + img = mpimg.imread('_static/stinkbug.png') + imgplot = plt.imshow(img) + +Without ``:outname:``, the figure generated above would normally be called, +e.g. :file:`docfile3-4-01.png` or something equally mysterious. With +``:outname:`` the figure generated will instead be named +:file:`stinkbug_plot-01.png` or even :file:`stinkbug_plot.png`. This makes it +easy to understand which output image is which and, more importantly, uniquely +keys output images to the code snippets that generated them. + +Configuring the cache directory +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +The directory that images are cached to can be configured using the +``plot_cache_dir`` configuration value in the Sphinx configuration file. + +If an image is already in ``plot_cache_dir`` when documentation is being +generated, this image is copied to the build directory thereby pre-empting +generation and reducing computation time in low-resource environments. diff --git a/lib/matplotlib/sphinxext/plot_directive.py b/lib/matplotlib/sphinxext/plot_directive.py index 617cae6fcf18..983c52bacf41 100644 --- a/lib/matplotlib/sphinxext/plot_directive.py +++ b/lib/matplotlib/sphinxext/plot_directive.py @@ -78,10 +78,10 @@ figure. This overwrites the caption given in the content, when the plot is generated from a file. ``:outname:`` : str - If specified, the names of the generated plots will start with the value - of `:outname:`. This is handy for preserving output results if code is - reordered between runs. The value of `:outname:` must be unique across - the generated documentation. + If specified, the names of the generated plots will start with the + value of ``:outname:``. This is handy for preserving output results if + code is reordered between runs. The value of ``:outname:`` must be + unique across the generated documentation. Additionally, this directive supports all the options of the `image directive `_, @@ -145,10 +145,11 @@ plot_template Provide a customized template for preparing restructured text. - plot_preserve_dir + plot_cache_dir Files with outnames are copied to this directory and files in this - directory are copied back from into the build directory prior to the - build beginning. + directory are copied back into the build directory prior to the build + beginning. + """ import contextlib @@ -158,16 +159,12 @@ import os import sys import shutil -import io import re import textwrap import glob +import logging from os.path import relpath from pathlib import Path -import re -import shutil -import sys -import textwrap import traceback from docutils.parsers.rst import directives, Directive @@ -183,10 +180,12 @@ __version__ = 2 -#Outnames must be unique. This variable stores the outnames that -#have been seen so we can guarantee this and warn the user if a -#duplicate is encountered. -outname_list = set() +_log = logging.getLogger(__name__) + +# Outnames must be unique. This variable stores the outnames that +# have been seen so we can guarantee this and warn the user if a +# duplicate is encountered. +_outname_list = set() # ----------------------------------------------------------------------------- # Registration hook @@ -301,7 +300,7 @@ def setup(app): app.add_config_value('plot_apply_rcparams', False, True) app.add_config_value('plot_working_directory', None, True) app.add_config_value('plot_template', None, True) - app.add_config_value('plot_preserve_dir', '', True) + app.add_config_value('plot_cache_dir', '', True) app.connect('doctree-read', mark_plot_labels) app.add_css_file('plot_directive.css') app.connect('build-finished', _copy_css_file) @@ -636,9 +635,12 @@ def render_figures(code, code_path, output_dir, output_base, context, for fmt, dpi in formats: try: figman.canvas.figure.savefig(img.filename(fmt), dpi=dpi) - if config.plot_preserve_dir and outname: - print("Preserving '{0}' into '{1}'".format(img.filename(format), config.plot_preserve_dir)) - shutil.copy2(img.filename(format), config.plot_preserve_dir) + if config.plot_cache_dir and outname is not None: + _log.info( + "Preserving '{0}' into '{1}'".format( + img.filename(fmt), config.plot_cache_dir)) + shutil.copy2(img.filename(fmt), + config.plot_cache_dir) except Exception as err: raise PlotError(traceback.format_exc()) from err img.formats.append(fmt) @@ -674,19 +676,20 @@ def run(arguments, content, options, state_machine, state, lineno): rst_file = document.attributes['source'] rst_dir = os.path.dirname(rst_file) - #Get output name of the images, if the option was provided + # Get output name of the images, if the option was provided outname = options.get('outname', '') - #Ensure that the outname is unique, otherwise copied images will - #not be what user expects - if outname and outname in outname_list: - raise Exception("The outname '{0}' is not unique!".format(outname)) + # Ensure that the outname is unique, otherwise copied images will + # not be what user expects + if outname and outname in _outname_list: + raise Exception("The outname '{0}' is not unique!".format(outname)) else: - outname_list.add(outname) + _outname_list.add(outname) - if config.plot_preserve_dir: - #Ensure `preserve_dir` ends with a slash, otherwise `copy2` will misbehave - config.plot_preserve_dir = os.path.join(config.plot_preserve_dir, '') + if config.plot_cache_dir: + # Ensure `preserve_dir` ends with a slash, otherwise `copy2` + # will misbehave + config.plot_cache_dir = os.path.join(config.plot_cache_dir, '') if len(arguments): if not config.plot_basedir: @@ -733,10 +736,10 @@ def run(arguments, content, options, state_machine, state, lineno): else: source_ext = '' - #outname, if present, overrides output_base, but preserve - #numbering of multi-figure code snippets + # outname, if present, overrides output_base, but preserve + # numbering of multi-figure code snippets if outname: - output_base = re.sub('^[^-]*', outname, output_base) + output_base = re.sub('^[^-]*', outname, output_base) # ensure that LaTeX includegraphics doesn't choke in foo.bar.pdf filenames output_base = output_base.replace('.', '-') @@ -798,14 +801,15 @@ def run(arguments, content, options, state_machine, state, lineno): else code, encoding='utf-8') - #If we previously preserved copies of the generated figures - #this copies them into the build directory so that they will - #not be remade - if config.plot_preserve_dir and outname: - outfiles = glob.glob(os.path.join(config.plot_preserve_dir,outname) + '*') - for of in outfiles: - print("Copying preserved copy of '{0}' into '{1}'".format(of, build_dir)) - shutil.copy2(of, build_dir) + # If we previously preserved copies of the generated figures this copies + # them into the build directory so that they will not be remade. + if config.plot_cache_dir and outname: + outfiles = glob.glob( + os.path.join(config.plot_cache_dir, outname) + '*') + for of in outfiles: + _log.info("Copying preserved copy of '{0}' into '{1}'".format( + of, build_dir)) + shutil.copy2(of, build_dir) # make figures try: @@ -819,7 +823,7 @@ def run(arguments, content, options, state_machine, state, lineno): context_reset=context_opt == 'reset', close_figs=context_opt == 'close-figs', code_includes=source_file_includes, - outname= utname) + outname=outname) errors = [] except PlotError as err: reporter = state.memo.reporter From 1d3840bc0646dff45be00c6eae49d4154a5363b1 Mon Sep 17 00:00:00 2001 From: Richard Barnes Date: Wed, 3 Jan 2018 15:19:07 -0600 Subject: [PATCH 3/4] Added a test of `:outname:` --- lib/matplotlib/tests/tinypages/some_plots.rst | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/lib/matplotlib/tests/tinypages/some_plots.rst b/lib/matplotlib/tests/tinypages/some_plots.rst index dd1f79892b0e..d707fb004b84 100644 --- a/lib/matplotlib/tests/tinypages/some_plots.rst +++ b/lib/matplotlib/tests/tinypages/some_plots.rst @@ -174,3 +174,12 @@ Plot 21 is generated via an include directive: Plot 22 uses a different specific function in a file with plot commands: .. plot:: range6.py range10 + +Plot 23 has an outname + +.. plot:: + :context: close-figs + :outname: plot23out + + plt.figure() + plt.plot(range(4)) From fca5eb35f7e10bd657367a76b0ef3321ae4d8d97 Mon Sep 17 00:00:00 2001 From: David Stansby Date: Thu, 26 Jan 2023 17:18:43 +0000 Subject: [PATCH 4/4] Use none as default argument --- lib/matplotlib/sphinxext/plot_directive.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/matplotlib/sphinxext/plot_directive.py b/lib/matplotlib/sphinxext/plot_directive.py index 983c52bacf41..a3a9e1bd1fcd 100644 --- a/lib/matplotlib/sphinxext/plot_directive.py +++ b/lib/matplotlib/sphinxext/plot_directive.py @@ -539,7 +539,7 @@ def render_figures(code, code_path, output_dir, output_base, context, function_name, config, context_reset=False, close_figs=False, code_includes=None, - outname=''): + outname=None): """ Run a pyplot script and save the images in *output_dir*.