mathtext.py 4.8 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 LOAD_NO_HINTING
  18. from matplotlib.font_manager import FontProperties
  19. from ._mathtext import ( # noqa: 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
  58. # is mutable; key the cache using an internal copy (see
  59. # text._get_text_metrics_with_cache for a similar case).
  60. prop = prop.copy() if prop is not None else None
  61. antialiased = mpl._val_or_rc(antialiased, 'text.antialiased')
  62. return self._parse_cached(s, dpi, prop, antialiased)
  63. @functools.lru_cache(50)
  64. def _parse_cached(self, s, dpi, prop, antialiased):
  65. from matplotlib.backends import backend_agg
  66. if prop is None:
  67. prop = FontProperties()
  68. fontset_class = _api.check_getitem(
  69. self._font_type_mapping, fontset=prop.get_math_fontfamily())
  70. load_glyph_flags = {
  71. "vector": LOAD_NO_HINTING,
  72. "raster": backend_agg.get_hinting_flag(),
  73. }[self._output_type]
  74. fontset = fontset_class(prop, load_glyph_flags)
  75. fontsize = prop.get_size_in_points()
  76. if self._parser is None: # Cache the parser globally.
  77. self.__class__._parser = _mathtext.Parser()
  78. box = self._parser.parse(s, fontset, fontsize, dpi)
  79. output = _mathtext.ship(box)
  80. if self._output_type == "vector":
  81. return output.to_vector()
  82. elif self._output_type == "raster":
  83. return output.to_raster(antialiased=antialiased)
  84. def math_to_image(s, filename_or_obj, prop=None, dpi=None, format=None,
  85. *, color=None):
  86. """
  87. Given a math expression, renders it in a closely-clipped bounding
  88. box to an image file.
  89. Parameters
  90. ----------
  91. s : str
  92. A math expression. The math portion must be enclosed in dollar signs.
  93. filename_or_obj : str or path-like or file-like
  94. Where to write the image data.
  95. prop : `.FontProperties`, optional
  96. The size and style of the text.
  97. dpi : float, optional
  98. The output dpi. If not set, the dpi is determined as for
  99. `.Figure.savefig`.
  100. format : str, optional
  101. The output format, e.g., 'svg', 'pdf', 'ps' or 'png'. If not set, the
  102. format is determined as for `.Figure.savefig`.
  103. color : str, optional
  104. Foreground color, defaults to :rc:`text.color`.
  105. """
  106. from matplotlib import figure
  107. parser = MathTextParser('path')
  108. width, height, depth, _, _ = parser.parse(s, dpi=72, prop=prop)
  109. fig = figure.Figure(figsize=(width / 72.0, height / 72.0))
  110. fig.text(0, depth/height, s, fontproperties=prop, color=color)
  111. fig.savefig(filename_or_obj, dpi=dpi, format=format)
  112. return depth