mathtext.py 5.0 KB

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