1r"""
2A module for parsing a subset of the TeX math syntax and rendering it to a
3Matplotlib backend.
4
5For a tutorial of its usage, see :ref:`mathtext`. This
6document is primarily concerned with implementation details.
7
8The module uses pyparsing_ to parse the TeX expression.
9
10.. _pyparsing: https://pypi.org/project/pyparsing/
11
12The Bakoma distribution of the TeX Computer Modern fonts, and STIX
13fonts are supported. There is experimental support for using
14arbitrary fonts, but results may vary without proper tweaking and
15metrics for those fonts.
16"""
17
18import functools
19import logging
20
21import matplotlib as mpl
22from matplotlib import _api, _mathtext
23from matplotlib.ft2font import LOAD_NO_HINTING
24from matplotlib.font_manager import FontProperties
25from ._mathtext import ( # noqa: reexported API
26 RasterParse, VectorParse, get_unicode_index)
27
28_log = logging.getLogger(__name__)
29
30
31get_unicode_index.__module__ = __name__
32
33##############################################################################
34# MAIN
35
36
37class MathTextParser:
38 _parser = None
39 _font_type_mapping = {
40 'cm': _mathtext.BakomaFonts,
41 'dejavuserif': _mathtext.DejaVuSerifFonts,
42 'dejavusans': _mathtext.DejaVuSansFonts,
43 'stix': _mathtext.StixFonts,
44 'stixsans': _mathtext.StixSansFonts,
45 'custom': _mathtext.UnicodeFonts,
46 }
47
48 def __init__(self, output):
49 """
50 Create a MathTextParser for the given backend *output*.
51
52 Parameters
53 ----------
54 output : {"path", "agg"}
55 Whether to return a `VectorParse` ("path") or a
56 `RasterParse` ("agg", or its synonym "macosx").
57 """
58 self._output_type = _api.check_getitem(
59 {"path": "vector", "agg": "raster", "macosx": "raster"},
60 output=output.lower())
61
62 def parse(self, s, dpi=72, prop=None, *, antialiased=None):
63 """
64 Parse the given math expression *s* at the given *dpi*. If *prop* is
65 provided, it is a `.FontProperties` object specifying the "default"
66 font to use in the math expression, used for all non-math text.
67
68 The results are cached, so multiple calls to `parse`
69 with the same expression should be fast.
70
71 Depending on the *output* type, this returns either a `VectorParse` or
72 a `RasterParse`.
73 """
74 # lru_cache can't decorate parse() directly because prop
75 # is mutable; key the cache using an internal copy (see
76 # text._get_text_metrics_with_cache for a similar case).
77 prop = prop.copy() if prop is not None else None
78 antialiased = mpl._val_or_rc(antialiased, 'text.antialiased')
79 return self._parse_cached(s, dpi, prop, antialiased)
80
81 @functools.lru_cache(50)
82 def _parse_cached(self, s, dpi, prop, antialiased):
83 from matplotlib.backends import backend_agg
84
85 if prop is None:
86 prop = FontProperties()
87 fontset_class = _api.check_getitem(
88 self._font_type_mapping, fontset=prop.get_math_fontfamily())
89 load_glyph_flags = {
90 "vector": LOAD_NO_HINTING,
91 "raster": backend_agg.get_hinting_flag(),
92 }[self._output_type]
93 fontset = fontset_class(prop, load_glyph_flags)
94
95 fontsize = prop.get_size_in_points()
96
97 if self._parser is None: # Cache the parser globally.
98 self.__class__._parser = _mathtext.Parser()
99
100 box = self._parser.parse(s, fontset, fontsize, dpi)
101 output = _mathtext.ship(box)
102 if self._output_type == "vector":
103 return output.to_vector()
104 elif self._output_type == "raster":
105 return output.to_raster(antialiased=antialiased)
106
107
108def math_to_image(s, filename_or_obj, prop=None, dpi=None, format=None,
109 *, color=None):
110 """
111 Given a math expression, renders it in a closely-clipped bounding
112 box to an image file.
113
114 Parameters
115 ----------
116 s : str
117 A math expression. The math portion must be enclosed in dollar signs.
118 filename_or_obj : str or path-like or file-like
119 Where to write the image data.
120 prop : `.FontProperties`, optional
121 The size and style of the text.
122 dpi : float, optional
123 The output dpi. If not set, the dpi is determined as for
124 `.Figure.savefig`.
125 format : str, optional
126 The output format, e.g., 'svg', 'pdf', 'ps' or 'png'. If not set, the
127 format is determined as for `.Figure.savefig`.
128 color : str, optional
129 Foreground color, defaults to :rc:`text.color`.
130 """
131 from matplotlib import figure
132
133 parser = MathTextParser('path')
134 width, height, depth, _, _ = parser.parse(s, dpi=72, prop=prop)
135
136 fig = figure.Figure(figsize=(width / 72.0, height / 72.0))
137 fig.text(0, depth/height, s, fontproperties=prop, color=color)
138 fig.savefig(filename_or_obj, dpi=dpi, format=format)
139
140 return depth