Skip to content

Commit 78df724

Browse files
committed
Create tiny mathtext baseline images using svg with non-embedded fonts.
... and using non-integer bases sqrt as example use case.
1 parent 4345d23 commit 78df724

File tree

4 files changed

+113
-7
lines changed

4 files changed

+113
-7
lines changed

lib/matplotlib/_mathtext.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -2158,7 +2158,8 @@ def __init__(self):
21582158

21592159
p.sqrt <<= Group(
21602160
Suppress(Literal(r"\sqrt"))
2161-
- ((Optional(p.lbracket + p.int_literal + p.rbracket, default=None)
2161+
- ((Group(Optional(
2162+
p.lbracket + OneOrMore(~p.rbracket + p.token) + p.rbracket))
21622163
+ p.required_group)
21632164
| Error("Expected \\sqrt{value}"))
21642165
)
@@ -2864,10 +2865,10 @@ def sqrt(self, s, loc, toks):
28642865

28652866
# Add the root and shift it upward so it is above the tick.
28662867
# The value of 0.6 is a hard-coded hack ;)
2867-
if root is None:
2868+
if not root:
28682869
root = Box(check.width * 0.5, 0., 0.)
28692870
else:
2870-
root = Hlist([Char(x, state) for x in root])
2871+
root = Hlist(root)
28712872
root.shrink()
28722873
root.shrink()
28732874

lib/matplotlib/testing/compare.py

+17-2
Original file line numberDiff line numberDiff line change
@@ -181,7 +181,7 @@ def __call__(self, orig, dest):
181181
# just be reported as a regular exception below).
182182
"DISPLAY": "",
183183
# Do not load any user options.
184-
"INKSCAPE_PROFILE_DIR": os.devnull,
184+
"INKSCAPE_PROFILE_DIR": self._tmpdir.name,
185185
}
186186
# Old versions of Inkscape (e.g. 0.48.3.1) seem to sometimes
187187
# deadlock when stderr is redirected to a pipe, so we redirect it
@@ -233,6 +233,15 @@ def __del__(self):
233233
self._tmpdir.cleanup()
234234

235235

236+
class _SVGWithMatplotlibFontsConverter(_SVGConverter):
237+
def __call__(self, orig, dest):
238+
if not hasattr(self, "_tmpdir"):
239+
self._tmpdir = TemporaryDirectory()
240+
shutil.copytree(cbook._get_data_path("fonts/ttf"),
241+
Path(self._tmpdir.name, "fonts"))
242+
return super().__call__(orig, dest)
243+
244+
236245
def _update_converter():
237246
try:
238247
mpl._get_executable_info("gs")
@@ -254,6 +263,7 @@ def _update_converter():
254263
#: extension to png format.
255264
converter = {}
256265
_update_converter()
266+
_svg_with_matplotlib_fonts_converter = _SVGWithMatplotlibFontsConverter()
257267

258268

259269
def comparable_formats():
@@ -303,7 +313,12 @@ def convert(filename, cache):
303313
return str(newpath)
304314

305315
_log.debug("For %s: converting to png.", filename)
306-
converter[path.suffix[1:]](path, newpath)
316+
convert = converter[path.suffix[1:]]
317+
if path.suffix == ".svg":
318+
contents = path.read_text()
319+
if 'style="font:' in contents: # for svg.fonttype = none.
320+
convert = _svg_with_matplotlib_fonts_converter
321+
convert(path, newpath)
307322

308323
if cache_dir is not None:
309324
_log.debug("For %s: caching conversion result.", filename)

lib/matplotlib/tests/test_mathtext.py

+29-2
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,9 @@
112112
r'$\left(X\right)_{a}^{b}$', # github issue 7615
113113
r'$\dfrac{\$100.00}{y}$', # github issue #1888
114114
]
115+
svg_only_math_tests = [
116+
r'$\sqrt[ab]{123}$', # github issue #8665
117+
]
115118

116119
digits = "0123456789"
117120
uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
@@ -167,8 +170,6 @@
167170
for set in chars:
168171
font_tests.append(wrapper % set)
169172

170-
font_tests = list(filter(lambda x: x[1] is not None, enumerate(font_tests)))
171-
172173

173174
@pytest.fixture
174175
def baseline_images(request, fontset, index):
@@ -192,6 +193,32 @@ def test_mathtext_rendering(baseline_images, fontset, index, test):
192193
horizontalalignment='center', verticalalignment='center')
193194

194195

196+
cur_svg_only_math_tests = list(
197+
filter(lambda x: x[1] is not None, enumerate(svg_only_math_tests)))
198+
199+
200+
@pytest.mark.parametrize('index, test', cur_svg_only_math_tests,
201+
ids=[str(idx) for idx, _ in cur_svg_only_math_tests])
202+
@pytest.mark.parametrize('fontset', ['all'])
203+
@pytest.mark.parametrize('baseline_images', ['mathtext1'], indirect=True)
204+
@image_comparison(
205+
baseline_images=None, extensions=['svg'],
206+
savefig_kwarg={
207+
'metadata': { # Minimize svg size.
208+
'Creator': None, 'Date': None, 'Format': None, 'Type': None}})
209+
def test_mathtext_rendering_svg_only(baseline_images, fontset, index, test):
210+
mpl.rcParams['svg.fonttype'] = 'none'
211+
fig = plt.figure(figsize=(5.25, 5.25))
212+
fig.patch.set_visible(False) # Minimize svg size.
213+
fontsets = ['cm', 'stix', 'stixsans', 'dejavusans', 'dejavuserif']
214+
for i, fontset in enumerate(fontsets):
215+
fig.text(0.5, (i + .5) / len(fontsets), test, math_fontfamily=fontset,
216+
horizontalalignment='center', verticalalignment='center')
217+
218+
219+
font_tests = list(filter(lambda x: x[1] is not None, enumerate(font_tests)))
220+
221+
195222
@pytest.mark.parametrize('index, test', font_tests,
196223
ids=[str(index) for index, _ in font_tests])
197224
@pytest.mark.parametrize('fontset',

0 commit comments

Comments
 (0)