Skip to content

Commit 8ab6ec7

Browse files
committed
Fixes for Sphinx 7.3 and sphinx-gallery 0.16
1 parent 990aa7c commit 8ab6ec7

File tree

3 files changed

+50
-61
lines changed

3 files changed

+50
-61
lines changed

docs/source/conf.py

+3-7
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,6 @@
2424
sys.path.insert(0, os.path.abspath('.'))
2525
sys.path.insert(0, os.path.abspath('../../'))
2626

27-
from doc_extensions import gallery_scraper, reset_numpy_random_seed
28-
from sphinx_gallery.sorting import FileNameSortKey
2927
import plotly.io as pio
3028
pio.renderers.default = 'sphinx_gallery'
3129

@@ -66,14 +64,14 @@
6664
'examples_dirs': ['../tutorials', '../examples', '../demos'],
6765
'gallery_dirs': ['auto_tutorials', 'auto_examples', 'auto_demos'],
6866
'filename_pattern': re.escape(os.sep),
69-
'image_scrapers': (gallery_scraper(),),
70-
'reset_modules': ('matplotlib', 'seaborn', reset_numpy_random_seed()),
67+
'image_scrapers': ('doc_extensions.gallery_scraper',),
68+
'reset_modules': ('matplotlib', 'seaborn', 'doc_extensions.reset_numpy_random_seed'),
7169
'reset_modules_order': 'both',
7270
'abort_on_example_error': False,
7371
'reference_url': {'stonesoup': None},
7472
'remove_config_comments': True,
7573
'ignore_repr_types': r'matplotlib\.(?:figure|animation|legend)',
76-
'within_subsection_order': FileNameSortKey,
74+
'within_subsection_order': "FileNameSortKey",
7775
'matplotlib_animations': True,
7876
'notebook_images':
7977
f'https://stonesoup.rtfd.io/en/{os.environ.get("READTHEDOCS_VERSION", "latest")}/',
@@ -162,8 +160,6 @@
162160
# If true, keep warnings as "system message" paragraphs in the built documents.
163161
# keep_warnings = False
164162

165-
suppress_warnings = ["config.cache"]
166-
167163
# If true, `todo` and `todoList` produce output, else they produce nothing.
168164
todo_include_todos = False
169165

docs/source/doc_extensions.py

+46-53
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,27 @@
11
import re
22
from collections.abc import Sequence
3+
from pathlib import PurePosixPath
4+
from textwrap import indent
5+
6+
import numpy as np
7+
import matplotlib
8+
import matplotlib.pyplot as plt
9+
from matplotlib.animation import Animation
10+
from matplotlib.figure import Figure
11+
from sphinx_gallery.scrapers import (
12+
figure_rst, _anim_rst, _matplotlib_fig_titles, HLIST_HEADER,
13+
HLIST_IMAGE_MATPLOTLIB)
14+
import plotly.graph_objects as go
15+
try:
16+
import kaleido # noqa: F401
17+
except ImportError:
18+
write_plotly_image = None
19+
else:
20+
from plotly.io import write_image as write_plotly_image
321

422
from stonesoup.base import Base
523

24+
625
STONESOUP_TYPE_REGEX = re.compile(r'stonesoup\.(\w+\.)*')
726

827

@@ -70,25 +89,7 @@ def setup(app):
7089
app.connect('autodoc-process-signature', shorten_type_hints)
7190

7291

73-
import os
74-
import matplotlib
75-
import matplotlib.pyplot as plt
76-
from textwrap import indent
77-
78-
from sphinx_gallery.scrapers import (
79-
figure_rst, _anim_rst, _matplotlib_fig_titles, HLIST_HEADER,
80-
HLIST_IMAGE_MATPLOTLIB)
81-
82-
import plotly.graph_objects as go
83-
try:
84-
import kaleido
85-
except ImportError:
86-
write_plotly_image = None
87-
else:
88-
from plotly.io import write_image as write_plotly_image
89-
90-
91-
class gallery_scraper():
92+
class GalleryScraper():
9293
def __init__(self):
9394
self.plotted_figures = set()
9495
self.current_src_file = None
@@ -124,18 +125,15 @@ def __call__(self, block, block_vars, gallery_conf, **kwargs):
124125
self.plotted_figures = set()
125126
self.current_src_file = block_vars['src_file']
126127

127-
from matplotlib.animation import Animation
128-
from matplotlib.figure import Figure
129128
image_path_iterator = block_vars['image_path_iterator']
130129
image_rsts = []
131130

132131
# Check for animations
133-
anims = list()
134-
if gallery_conf.get('matplotlib_animations', False):
132+
anims = {}
133+
if gallery_conf['matplotlib_animations']:
135134
for ani in block_vars['example_globals'].values():
136135
if isinstance(ani, Animation):
137-
anims.append(ani)
138-
136+
anims[ani._fig] = ani
139137
# Then standard images
140138
new_figures = set(plt.get_fignums()) - self.plotted_figures
141139
last_line = block[1].strip().split('\n')[-1]
@@ -149,30 +147,22 @@ def __call__(self, block, block_vars, gallery_conf, **kwargs):
149147
else:
150148
if isinstance(output, Figure):
151149
new_figures.add(output.number)
152-
elif isinstance(output, go.Figure):
153-
if write_plotly_image is not None:
154-
image_path = next(image_path_iterator)
155-
if 'format' in kwargs:
156-
image_path = '%s.%s' % (os.path.splitext(image_path)[0],
157-
kwargs['format'])
158-
write_plotly_image(output, image_path, kwargs.get('format'))
150+
elif isinstance(output, go.Figure) and write_plotly_image is not None:
151+
image_path = PurePosixPath(next(image_path_iterator))
152+
if "format" in kwargs:
153+
image_path = image_path.with_suffix("." + kwargs["format"])
154+
write_plotly_image(output, str(image_path), kwargs.get('format'))
159155

160156
for fig_num, image_path in zip(new_figures, image_path_iterator):
161-
if 'format' in kwargs:
162-
image_path = '%s.%s' % (os.path.splitext(image_path)[0],
163-
kwargs['format'])
164-
# Set the fig_num figure as the current figure as we can't
165-
# save a figure that's not the current figure.
157+
image_path = PurePosixPath(image_path)
158+
if "format" in kwargs:
159+
image_path = image_path.with_suffix("." + kwargs["format"])
160+
# Convert figure number to Figure.
166161
fig = plt.figure(fig_num)
167162
self.plotted_figures.add(fig_num)
168163
# Deal with animations
169-
cont = False
170-
for anim in anims:
171-
if anim._fig is fig:
172-
image_rsts.append(_anim_rst(anim, image_path, gallery_conf))
173-
cont = True
174-
break
175-
if cont:
164+
if anim := anims.get(fig):
165+
image_rsts.append(_anim_rst(anim, image_path, gallery_conf))
176166
continue
177167
# get fig titles
178168
fig_titles = _matplotlib_fig_titles(fig)
@@ -183,8 +173,7 @@ def __call__(self, block, block_vars, gallery_conf, **kwargs):
183173
for attr in ['facecolor', 'edgecolor']:
184174
fig_attr = getattr(fig, 'get_' + attr)()
185175
default_attr = matplotlib.rcParams['figure.' + attr]
186-
if to_rgba(fig_attr) != to_rgba(default_attr) and \
187-
attr not in kwargs:
176+
if to_rgba(fig_attr) != to_rgba(default_attr) and attr not in kwargs:
188177
these_kwargs[attr] = fig_attr
189178
these_kwargs['bbox_inches'] = "tight"
190179
fig.savefig(image_path, **these_kwargs)
@@ -194,24 +183,28 @@ def __call__(self, block, block_vars, gallery_conf, **kwargs):
194183
if len(image_rsts) == 1:
195184
rst = image_rsts[0]
196185
elif len(image_rsts) > 1:
197-
image_rsts = [re.sub(r':class: sphx-glr-single-img',
198-
':class: sphx-glr-multi-img',
199-
image) for image in image_rsts]
200-
image_rsts = [HLIST_IMAGE_MATPLOTLIB + indent(image, u' ' * 6)
201-
for image in image_rsts]
186+
image_rsts = [
187+
re.sub(r':class: sphx-glr-single-img', ':class: sphx-glr-multi-img', image)
188+
for image in image_rsts]
189+
image_rsts = [
190+
HLIST_IMAGE_MATPLOTLIB + indent(image, ' ' * 6) for image in image_rsts
191+
]
202192
rst = HLIST_HEADER + ''.join(image_rsts)
203193
return rst
204194

205195

206-
class reset_numpy_random_seed:
196+
class ResetNumPyRandomSeed:
207197

208198
def __init__(self):
209199
self.state = None
210200

211201
def __call__(self, gallery_conf, fname, when):
212-
import numpy as np
213202
if when == 'before':
214203
self.state = np.random.get_state()
215204
elif when == 'after':
216205
# Set state attribute back to `None`
217206
self.state = np.random.set_state(self.state)
207+
208+
209+
gallery_scraper = GalleryScraper()
210+
reset_numpy_random_seed = ResetNumPyRandomSeed()

setup.cfg

+1-1
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ dev =
4444
pytest-skip-slow
4545
Sphinx
4646
sphinx_rtd_theme>=1.2
47-
sphinx-gallery>=0.10.1
47+
sphinx-gallery>=0.16
4848
video =
4949
ffmpeg-python
5050
moviepy

0 commit comments

Comments
 (0)