texmanager.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. r"""
  2. This module supports embedded TeX expressions in matplotlib via dvipng
  3. and dvips for the raster and postscript backends. The tex and
  4. dvipng/dvips information is cached in ~/.matplotlib/tex.cache for reuse between
  5. sessions
  6. Requirements:
  7. * latex
  8. * \*Agg backends: dvipng>=1.6
  9. * PS backend: psfrag, dvips, and Ghostscript>=8.60
  10. Backends:
  11. * \*Agg
  12. * PS
  13. * PDF
  14. For raster output, you can get RGBA numpy arrays from TeX expressions
  15. as follows::
  16. texmanager = TexManager()
  17. s = ('\TeX\ is Number '
  18. '$\displaystyle\sum_{n=1}^\infty\frac{-e^{i\pi}}{2^n}$!')
  19. Z = texmanager.get_rgba(s, fontsize=12, dpi=80, rgb=(1, 0, 0))
  20. To enable tex rendering of all text in your matplotlib figure, set
  21. :rc:`text.usetex` to True.
  22. """
  23. import copy
  24. import functools
  25. import glob
  26. import hashlib
  27. import logging
  28. import os
  29. from pathlib import Path
  30. import re
  31. import subprocess
  32. import numpy as np
  33. import matplotlib as mpl
  34. from matplotlib import cbook, dviread, rcParams
  35. _log = logging.getLogger(__name__)
  36. class TexManager:
  37. """
  38. Convert strings to dvi files using TeX, caching the results to a directory.
  39. Repeated calls to this constructor always return the same instance.
  40. """
  41. cachedir = mpl.get_cachedir()
  42. if cachedir is not None:
  43. texcache = os.path.join(cachedir, 'tex.cache')
  44. Path(texcache).mkdir(parents=True, exist_ok=True)
  45. else:
  46. # Should only happen in a restricted environment (such as Google App
  47. # Engine). Deal with this gracefully by not creating a cache directory.
  48. texcache = None
  49. # Caches.
  50. rgba_arrayd = {}
  51. grey_arrayd = {}
  52. serif = ('cmr', '')
  53. sans_serif = ('cmss', '')
  54. monospace = ('cmtt', '')
  55. cursive = ('pzc', r'\usepackage{chancery}')
  56. font_family = 'serif'
  57. font_families = ('serif', 'sans-serif', 'cursive', 'monospace')
  58. font_info = {
  59. 'new century schoolbook': ('pnc', r'\renewcommand{\rmdefault}{pnc}'),
  60. 'bookman': ('pbk', r'\renewcommand{\rmdefault}{pbk}'),
  61. 'times': ('ptm', r'\usepackage{mathptmx}'),
  62. 'palatino': ('ppl', r'\usepackage{mathpazo}'),
  63. 'zapf chancery': ('pzc', r'\usepackage{chancery}'),
  64. 'cursive': ('pzc', r'\usepackage{chancery}'),
  65. 'charter': ('pch', r'\usepackage{charter}'),
  66. 'serif': ('cmr', ''),
  67. 'sans-serif': ('cmss', ''),
  68. 'helvetica': ('phv', r'\usepackage{helvet}'),
  69. 'avant garde': ('pag', r'\usepackage{avant}'),
  70. 'courier': ('pcr', r'\usepackage{courier}'),
  71. # Loading the type1ec package ensures that cm-super is installed, which
  72. # is necessary for unicode computer modern. (It also allows the use of
  73. # computer modern at arbitrary sizes, but that's just a side effect.)
  74. 'monospace': ('cmtt', r'\usepackage{type1ec}'),
  75. 'computer modern roman': ('cmr', r'\usepackage{type1ec}'),
  76. 'computer modern sans serif': ('cmss', r'\usepackage{type1ec}'),
  77. 'computer modern typewriter': ('cmtt', r'\usepackage{type1ec}')}
  78. _rc_cache = None
  79. _rc_cache_keys = (
  80. ('text.latex.preamble', 'text.latex.unicode', 'text.latex.preview',
  81. 'font.family') + tuple('font.' + n for n in font_families))
  82. @functools.lru_cache() # Always return the same instance.
  83. def __new__(cls):
  84. self = object.__new__(cls)
  85. self._reinit()
  86. return self
  87. def _reinit(self):
  88. if self.texcache is None:
  89. raise RuntimeError('Cannot create TexManager, as there is no '
  90. 'cache directory available')
  91. Path(self.texcache).mkdir(parents=True, exist_ok=True)
  92. ff = rcParams['font.family']
  93. if len(ff) == 1 and ff[0].lower() in self.font_families:
  94. self.font_family = ff[0].lower()
  95. elif isinstance(ff, str) and ff.lower() in self.font_families:
  96. self.font_family = ff.lower()
  97. else:
  98. _log.info('font.family must be one of (%s) when text.usetex is '
  99. 'True. serif will be used by default.',
  100. ', '.join(self.font_families))
  101. self.font_family = 'serif'
  102. fontconfig = [self.font_family]
  103. for font_family in self.font_families:
  104. font_family_attr = font_family.replace('-', '_')
  105. for font in rcParams['font.' + font_family]:
  106. if font.lower() in self.font_info:
  107. setattr(self, font_family_attr,
  108. self.font_info[font.lower()])
  109. _log.debug('family: %s, font: %s, info: %s',
  110. font_family, font, self.font_info[font.lower()])
  111. break
  112. else:
  113. _log.debug('%s font is not compatible with usetex.',
  114. font_family)
  115. else:
  116. _log.info('No LaTeX-compatible font found for the %s font '
  117. 'family in rcParams. Using default.', font_family)
  118. setattr(self, font_family_attr, self.font_info[font_family])
  119. fontconfig.append(getattr(self, font_family_attr)[0])
  120. # Add a hash of the latex preamble to self._fontconfig so that the
  121. # correct png is selected for strings rendered with same font and dpi
  122. # even if the latex preamble changes within the session
  123. preamble_bytes = self.get_custom_preamble().encode('utf-8')
  124. fontconfig.append(hashlib.md5(preamble_bytes).hexdigest())
  125. self._fontconfig = ''.join(fontconfig)
  126. # The following packages and commands need to be included in the latex
  127. # file's preamble:
  128. cmd = [self.serif[1], self.sans_serif[1], self.monospace[1]]
  129. if self.font_family == 'cursive':
  130. cmd.append(self.cursive[1])
  131. self._font_preamble = '\n'.join(
  132. [r'\usepackage{type1cm}'] + cmd + [r'\usepackage{textcomp}'])
  133. def get_basefile(self, tex, fontsize, dpi=None):
  134. """
  135. Return a filename based on a hash of the string, fontsize, and dpi.
  136. """
  137. s = ''.join([tex, self.get_font_config(), '%f' % fontsize,
  138. self.get_custom_preamble(), str(dpi or '')])
  139. return os.path.join(
  140. self.texcache, hashlib.md5(s.encode('utf-8')).hexdigest())
  141. def get_font_config(self):
  142. """Reinitializes self if relevant rcParams on have changed."""
  143. if self._rc_cache is None:
  144. self._rc_cache = dict.fromkeys(self._rc_cache_keys)
  145. changed = [par for par in self._rc_cache_keys
  146. if rcParams[par] != self._rc_cache[par]]
  147. if changed:
  148. _log.debug('following keys changed: %s', changed)
  149. for k in changed:
  150. _log.debug('%-20s: %-10s -> %-10s',
  151. k, self._rc_cache[k], rcParams[k])
  152. # deepcopy may not be necessary, but feels more future-proof
  153. self._rc_cache[k] = copy.deepcopy(rcParams[k])
  154. _log.debug('RE-INIT\nold fontconfig: %s', self._fontconfig)
  155. self._reinit()
  156. _log.debug('fontconfig: %s', self._fontconfig)
  157. return self._fontconfig
  158. def get_font_preamble(self):
  159. """
  160. Return a string containing font configuration for the tex preamble.
  161. """
  162. return self._font_preamble
  163. def get_custom_preamble(self):
  164. """Return a string containing user additions to the tex preamble."""
  165. return rcParams['text.latex.preamble']
  166. def make_tex(self, tex, fontsize):
  167. """
  168. Generate a tex file to render the tex string at a specific font size.
  169. Return the file name.
  170. """
  171. basefile = self.get_basefile(tex, fontsize)
  172. texfile = '%s.tex' % basefile
  173. custom_preamble = self.get_custom_preamble()
  174. fontcmd = {'sans-serif': r'{\sffamily %s}',
  175. 'monospace': r'{\ttfamily %s}'}.get(self.font_family,
  176. r'{\rmfamily %s}')
  177. tex = fontcmd % tex
  178. unicode_preamble = "\n".join([
  179. r"\usepackage[utf8]{inputenc}",
  180. r"\DeclareUnicodeCharacter{2212}{\ensuremath{-}}",
  181. ]) if rcParams["text.latex.unicode"] else ""
  182. s = r"""
  183. \documentclass{article}
  184. %s
  185. %s
  186. %s
  187. \usepackage[papersize={72in,72in},body={70in,70in},margin={1in,1in}]{geometry}
  188. \pagestyle{empty}
  189. \begin{document}
  190. \fontsize{%f}{%f}%s
  191. \end{document}
  192. """ % (self._font_preamble, unicode_preamble, custom_preamble,
  193. fontsize, fontsize * 1.25, tex)
  194. with open(texfile, 'wb') as fh:
  195. if rcParams['text.latex.unicode']:
  196. fh.write(s.encode('utf8'))
  197. else:
  198. try:
  199. fh.write(s.encode('ascii'))
  200. except UnicodeEncodeError:
  201. _log.info("You are using unicode and latex, but have not "
  202. "enabled the 'text.latex.unicode' rcParam.")
  203. raise
  204. return texfile
  205. _re_vbox = re.compile(
  206. r"MatplotlibBox:\(([\d.]+)pt\+([\d.]+)pt\)x([\d.]+)pt")
  207. def make_tex_preview(self, tex, fontsize):
  208. """
  209. Generate a tex file to render the tex string at a specific font size.
  210. It uses the preview.sty to determine the dimension (width, height,
  211. descent) of the output.
  212. Return the file name.
  213. """
  214. basefile = self.get_basefile(tex, fontsize)
  215. texfile = '%s.tex' % basefile
  216. custom_preamble = self.get_custom_preamble()
  217. fontcmd = {'sans-serif': r'{\sffamily %s}',
  218. 'monospace': r'{\ttfamily %s}'}.get(self.font_family,
  219. r'{\rmfamily %s}')
  220. tex = fontcmd % tex
  221. unicode_preamble = "\n".join([
  222. r"\usepackage[utf8]{inputenc}",
  223. r"\DeclareUnicodeCharacter{2212}{\ensuremath{-}}",
  224. ]) if rcParams["text.latex.unicode"] else ""
  225. # newbox, setbox, immediate, etc. are used to find the box
  226. # extent of the rendered text.
  227. s = r"""
  228. \documentclass{article}
  229. %s
  230. %s
  231. %s
  232. \usepackage[active,showbox,tightpage]{preview}
  233. \usepackage[papersize={72in,72in},body={70in,70in},margin={1in,1in}]{geometry}
  234. %% we override the default showbox as it is treated as an error and makes
  235. %% the exit status not zero
  236. \def\showbox#1%%
  237. {\immediate\write16{MatplotlibBox:(\the\ht#1+\the\dp#1)x\the\wd#1}}
  238. \begin{document}
  239. \begin{preview}
  240. {\fontsize{%f}{%f}%s}
  241. \end{preview}
  242. \end{document}
  243. """ % (self._font_preamble, unicode_preamble, custom_preamble,
  244. fontsize, fontsize * 1.25, tex)
  245. with open(texfile, 'wb') as fh:
  246. if rcParams['text.latex.unicode']:
  247. fh.write(s.encode('utf8'))
  248. else:
  249. try:
  250. fh.write(s.encode('ascii'))
  251. except UnicodeEncodeError:
  252. _log.info("You are using unicode and latex, but have not "
  253. "enabled the 'text.latex.unicode' rcParam.")
  254. raise
  255. return texfile
  256. def _run_checked_subprocess(self, command, tex):
  257. _log.debug(cbook._pformat_subprocess(command))
  258. try:
  259. report = subprocess.check_output(command,
  260. cwd=self.texcache,
  261. stderr=subprocess.STDOUT)
  262. except FileNotFoundError as exc:
  263. raise RuntimeError(
  264. 'Failed to process string with tex because {} could not be '
  265. 'found'.format(command[0])) from exc
  266. except subprocess.CalledProcessError as exc:
  267. raise RuntimeError(
  268. '{prog} was not able to process the following string:\n'
  269. '{tex!r}\n\n'
  270. 'Here is the full report generated by {prog}:\n'
  271. '{exc}\n\n'.format(
  272. prog=command[0],
  273. tex=tex.encode('unicode_escape'),
  274. exc=exc.output.decode('utf-8'))) from exc
  275. _log.debug(report)
  276. return report
  277. def make_dvi(self, tex, fontsize):
  278. """
  279. Generate a dvi file containing latex's layout of tex string.
  280. Return the file name.
  281. """
  282. if rcParams['text.latex.preview']:
  283. return self.make_dvi_preview(tex, fontsize)
  284. basefile = self.get_basefile(tex, fontsize)
  285. dvifile = '%s.dvi' % basefile
  286. if not os.path.exists(dvifile):
  287. texfile = self.make_tex(tex, fontsize)
  288. with cbook._lock_path(texfile):
  289. self._run_checked_subprocess(
  290. ["latex", "-interaction=nonstopmode", "--halt-on-error",
  291. texfile], tex)
  292. for fname in glob.glob(basefile + '*'):
  293. if not fname.endswith(('dvi', 'tex')):
  294. try:
  295. os.remove(fname)
  296. except OSError:
  297. pass
  298. return dvifile
  299. def make_dvi_preview(self, tex, fontsize):
  300. """
  301. Generate a dvi file containing latex's layout of tex string.
  302. It calls make_tex_preview() method and store the size information
  303. (width, height, descent) in a separate file.
  304. Return the file name.
  305. """
  306. basefile = self.get_basefile(tex, fontsize)
  307. dvifile = '%s.dvi' % basefile
  308. baselinefile = '%s.baseline' % basefile
  309. if not os.path.exists(dvifile) or not os.path.exists(baselinefile):
  310. texfile = self.make_tex_preview(tex, fontsize)
  311. report = self._run_checked_subprocess(
  312. ["latex", "-interaction=nonstopmode", "--halt-on-error",
  313. texfile], tex)
  314. # find the box extent information in the latex output
  315. # file and store them in ".baseline" file
  316. m = TexManager._re_vbox.search(report.decode("utf-8"))
  317. with open(basefile + '.baseline', "w") as fh:
  318. fh.write(" ".join(m.groups()))
  319. for fname in glob.glob(basefile + '*'):
  320. if not fname.endswith(('dvi', 'tex', 'baseline')):
  321. try:
  322. os.remove(fname)
  323. except OSError:
  324. pass
  325. return dvifile
  326. def make_png(self, tex, fontsize, dpi):
  327. """
  328. Generate a png file containing latex's rendering of tex string.
  329. Return the file name.
  330. """
  331. basefile = self.get_basefile(tex, fontsize, dpi)
  332. pngfile = '%s.png' % basefile
  333. # see get_rgba for a discussion of the background
  334. if not os.path.exists(pngfile):
  335. dvifile = self.make_dvi(tex, fontsize)
  336. self._run_checked_subprocess(
  337. ["dvipng", "-bg", "Transparent", "-D", str(dpi),
  338. "-T", "tight", "-o", pngfile, dvifile], tex)
  339. return pngfile
  340. def get_grey(self, tex, fontsize=None, dpi=None):
  341. """Return the alpha channel."""
  342. from matplotlib import _png
  343. key = tex, self.get_font_config(), fontsize, dpi
  344. alpha = self.grey_arrayd.get(key)
  345. if alpha is None:
  346. pngfile = self.make_png(tex, fontsize, dpi)
  347. with open(os.path.join(self.texcache, pngfile), "rb") as file:
  348. X = _png.read_png(file)
  349. self.grey_arrayd[key] = alpha = X[:, :, -1]
  350. return alpha
  351. def get_rgba(self, tex, fontsize=None, dpi=None, rgb=(0, 0, 0)):
  352. """Return latex's rendering of the tex string as an rgba array."""
  353. if not fontsize:
  354. fontsize = rcParams['font.size']
  355. if not dpi:
  356. dpi = rcParams['savefig.dpi']
  357. r, g, b = rgb
  358. key = tex, self.get_font_config(), fontsize, dpi, tuple(rgb)
  359. Z = self.rgba_arrayd.get(key)
  360. if Z is None:
  361. alpha = self.get_grey(tex, fontsize, dpi)
  362. Z = np.dstack([r, g, b, alpha])
  363. self.rgba_arrayd[key] = Z
  364. return Z
  365. def get_text_width_height_descent(self, tex, fontsize, renderer=None):
  366. """Return width, height and descent of the text."""
  367. if tex.strip() == '':
  368. return 0, 0, 0
  369. dpi_fraction = renderer.points_to_pixels(1.) if renderer else 1
  370. if rcParams['text.latex.preview']:
  371. # use preview.sty
  372. basefile = self.get_basefile(tex, fontsize)
  373. baselinefile = '%s.baseline' % basefile
  374. if not os.path.exists(baselinefile):
  375. dvifile = self.make_dvi_preview(tex, fontsize)
  376. with open(baselinefile) as fh:
  377. l = fh.read().split()
  378. height, depth, width = [float(l1) * dpi_fraction for l1 in l]
  379. return width, height + depth, depth
  380. else:
  381. # use dviread. It sometimes returns a wrong descent.
  382. dvifile = self.make_dvi(tex, fontsize)
  383. with dviread.Dvi(dvifile, 72 * dpi_fraction) as dvi:
  384. page, = dvi
  385. # A total height (including the descent) needs to be returned.
  386. return page.width, page.height + page.descent, page.descent