backend_agg.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. """
  2. An `Anti-Grain Geometry`_ (AGG) backend.
  3. Features that are implemented:
  4. * capstyles and join styles
  5. * dashes
  6. * linewidth
  7. * lines, rectangles, ellipses
  8. * clipping to a rectangle
  9. * output to RGBA and Pillow-supported image formats
  10. * alpha blending
  11. * DPI scaling properly - everything scales properly (dashes, linewidths, etc)
  12. * draw polygon
  13. * freetype2 w/ ft2font
  14. Still TODO:
  15. * integrate screen dpi w/ ppi and text
  16. .. _Anti-Grain Geometry: http://agg.sourceforge.net/antigrain.com
  17. """
  18. from contextlib import nullcontext
  19. from math import radians, cos, sin
  20. import numpy as np
  21. import matplotlib as mpl
  22. from matplotlib import _api, cbook
  23. from matplotlib.backend_bases import (
  24. _Backend, FigureCanvasBase, FigureManagerBase, RendererBase)
  25. from matplotlib.font_manager import fontManager as _fontManager, get_font
  26. from matplotlib.ft2font import LoadFlags
  27. from matplotlib.mathtext import MathTextParser
  28. from matplotlib.path import Path
  29. from matplotlib.transforms import Bbox, BboxBase
  30. from matplotlib.backends._backend_agg import RendererAgg as _RendererAgg
  31. def get_hinting_flag():
  32. mapping = {
  33. 'default': LoadFlags.DEFAULT,
  34. 'no_autohint': LoadFlags.NO_AUTOHINT,
  35. 'force_autohint': LoadFlags.FORCE_AUTOHINT,
  36. 'no_hinting': LoadFlags.NO_HINTING,
  37. True: LoadFlags.FORCE_AUTOHINT,
  38. False: LoadFlags.NO_HINTING,
  39. 'either': LoadFlags.DEFAULT,
  40. 'native': LoadFlags.NO_AUTOHINT,
  41. 'auto': LoadFlags.FORCE_AUTOHINT,
  42. 'none': LoadFlags.NO_HINTING,
  43. }
  44. return mapping[mpl.rcParams['text.hinting']]
  45. class RendererAgg(RendererBase):
  46. """
  47. The renderer handles all the drawing primitives using a graphics
  48. context instance that controls the colors/styles
  49. """
  50. def __init__(self, width, height, dpi):
  51. super().__init__()
  52. self.dpi = dpi
  53. self.width = width
  54. self.height = height
  55. self._renderer = _RendererAgg(int(width), int(height), dpi)
  56. self._filter_renderers = []
  57. self._update_methods()
  58. self.mathtext_parser = MathTextParser('agg')
  59. self.bbox = Bbox.from_bounds(0, 0, self.width, self.height)
  60. def __getstate__(self):
  61. # We only want to preserve the init keywords of the Renderer.
  62. # Anything else can be re-created.
  63. return {'width': self.width, 'height': self.height, 'dpi': self.dpi}
  64. def __setstate__(self, state):
  65. self.__init__(state['width'], state['height'], state['dpi'])
  66. def _update_methods(self):
  67. self.draw_gouraud_triangles = self._renderer.draw_gouraud_triangles
  68. self.draw_image = self._renderer.draw_image
  69. self.draw_markers = self._renderer.draw_markers
  70. self.draw_path_collection = self._renderer.draw_path_collection
  71. self.draw_quad_mesh = self._renderer.draw_quad_mesh
  72. self.copy_from_bbox = self._renderer.copy_from_bbox
  73. def draw_path(self, gc, path, transform, rgbFace=None):
  74. # docstring inherited
  75. nmax = mpl.rcParams['agg.path.chunksize'] # here at least for testing
  76. npts = path.vertices.shape[0]
  77. if (npts > nmax > 100 and path.should_simplify and
  78. rgbFace is None and gc.get_hatch() is None):
  79. nch = np.ceil(npts / nmax)
  80. chsize = int(np.ceil(npts / nch))
  81. i0 = np.arange(0, npts, chsize)
  82. i1 = np.zeros_like(i0)
  83. i1[:-1] = i0[1:] - 1
  84. i1[-1] = npts
  85. for ii0, ii1 in zip(i0, i1):
  86. v = path.vertices[ii0:ii1, :]
  87. c = path.codes
  88. if c is not None:
  89. c = c[ii0:ii1]
  90. c[0] = Path.MOVETO # move to end of last chunk
  91. p = Path(v, c)
  92. p.simplify_threshold = path.simplify_threshold
  93. try:
  94. self._renderer.draw_path(gc, p, transform, rgbFace)
  95. except OverflowError:
  96. msg = (
  97. "Exceeded cell block limit in Agg.\n\n"
  98. "Please reduce the value of "
  99. f"rcParams['agg.path.chunksize'] (currently {nmax}) "
  100. "or increase the path simplification threshold"
  101. "(rcParams['path.simplify_threshold'] = "
  102. f"{mpl.rcParams['path.simplify_threshold']:.2f} by "
  103. "default and path.simplify_threshold = "
  104. f"{path.simplify_threshold:.2f} on the input)."
  105. )
  106. raise OverflowError(msg) from None
  107. else:
  108. try:
  109. self._renderer.draw_path(gc, path, transform, rgbFace)
  110. except OverflowError:
  111. cant_chunk = ''
  112. if rgbFace is not None:
  113. cant_chunk += "- cannot split filled path\n"
  114. if gc.get_hatch() is not None:
  115. cant_chunk += "- cannot split hatched path\n"
  116. if not path.should_simplify:
  117. cant_chunk += "- path.should_simplify is False\n"
  118. if len(cant_chunk):
  119. msg = (
  120. "Exceeded cell block limit in Agg, however for the "
  121. "following reasons:\n\n"
  122. f"{cant_chunk}\n"
  123. "we cannot automatically split up this path to draw."
  124. "\n\nPlease manually simplify your path."
  125. )
  126. else:
  127. inc_threshold = (
  128. "or increase the path simplification threshold"
  129. "(rcParams['path.simplify_threshold'] = "
  130. f"{mpl.rcParams['path.simplify_threshold']} "
  131. "by default and path.simplify_threshold "
  132. f"= {path.simplify_threshold} "
  133. "on the input)."
  134. )
  135. if nmax > 100:
  136. msg = (
  137. "Exceeded cell block limit in Agg. Please reduce "
  138. "the value of rcParams['agg.path.chunksize'] "
  139. f"(currently {nmax}) {inc_threshold}"
  140. )
  141. else:
  142. msg = (
  143. "Exceeded cell block limit in Agg. Please set "
  144. "the value of rcParams['agg.path.chunksize'], "
  145. f"(currently {nmax}) to be greater than 100 "
  146. + inc_threshold
  147. )
  148. raise OverflowError(msg) from None
  149. def draw_mathtext(self, gc, x, y, s, prop, angle):
  150. """Draw mathtext using :mod:`matplotlib.mathtext`."""
  151. ox, oy, width, height, descent, font_image = \
  152. self.mathtext_parser.parse(s, self.dpi, prop,
  153. antialiased=gc.get_antialiased())
  154. xd = descent * sin(radians(angle))
  155. yd = descent * cos(radians(angle))
  156. x = round(x + ox + xd)
  157. y = round(y - oy + yd)
  158. self._renderer.draw_text_image(font_image, x, y + 1, angle, gc)
  159. def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
  160. # docstring inherited
  161. if ismath:
  162. return self.draw_mathtext(gc, x, y, s, prop, angle)
  163. font = self._prepare_font(prop)
  164. # We pass '0' for angle here, since it will be rotated (in raster
  165. # space) in the following call to draw_text_image).
  166. font.set_text(s, 0, flags=get_hinting_flag())
  167. font.draw_glyphs_to_bitmap(
  168. antialiased=gc.get_antialiased())
  169. d = font.get_descent() / 64.0
  170. # The descent needs to be adjusted for the angle.
  171. xo, yo = font.get_bitmap_offset()
  172. xo /= 64.0
  173. yo /= 64.0
  174. xd = d * sin(radians(angle))
  175. yd = d * cos(radians(angle))
  176. x = round(x + xo + xd)
  177. y = round(y + yo + yd)
  178. self._renderer.draw_text_image(font, x, y + 1, angle, gc)
  179. def get_text_width_height_descent(self, s, prop, ismath):
  180. # docstring inherited
  181. _api.check_in_list(["TeX", True, False], ismath=ismath)
  182. if ismath == "TeX":
  183. return super().get_text_width_height_descent(s, prop, ismath)
  184. if ismath:
  185. ox, oy, width, height, descent, font_image = \
  186. self.mathtext_parser.parse(s, self.dpi, prop)
  187. return width, height, descent
  188. font = self._prepare_font(prop)
  189. font.set_text(s, 0.0, flags=get_hinting_flag())
  190. w, h = font.get_width_height() # width and height of unrotated string
  191. d = font.get_descent()
  192. w /= 64.0 # convert from subpixels
  193. h /= 64.0
  194. d /= 64.0
  195. return w, h, d
  196. def draw_tex(self, gc, x, y, s, prop, angle, *, mtext=None):
  197. # docstring inherited
  198. # todo, handle props, angle, origins
  199. size = prop.get_size_in_points()
  200. texmanager = self.get_texmanager()
  201. Z = texmanager.get_grey(s, size, self.dpi)
  202. Z = np.array(Z * 255.0, np.uint8)
  203. w, h, d = self.get_text_width_height_descent(s, prop, ismath="TeX")
  204. xd = d * sin(radians(angle))
  205. yd = d * cos(radians(angle))
  206. x = round(x + xd)
  207. y = round(y + yd)
  208. self._renderer.draw_text_image(Z, x, y, angle, gc)
  209. def get_canvas_width_height(self):
  210. # docstring inherited
  211. return self.width, self.height
  212. def _prepare_font(self, font_prop):
  213. """
  214. Get the `.FT2Font` for *font_prop*, clear its buffer, and set its size.
  215. """
  216. font = get_font(_fontManager._find_fonts_by_props(font_prop))
  217. font.clear()
  218. size = font_prop.get_size_in_points()
  219. font.set_size(size, self.dpi)
  220. return font
  221. def points_to_pixels(self, points):
  222. # docstring inherited
  223. return points * self.dpi / 72
  224. def buffer_rgba(self):
  225. return memoryview(self._renderer)
  226. def tostring_argb(self):
  227. return np.asarray(self._renderer).take([3, 0, 1, 2], axis=2).tobytes()
  228. def clear(self):
  229. self._renderer.clear()
  230. def option_image_nocomposite(self):
  231. # docstring inherited
  232. # It is generally faster to composite each image directly to
  233. # the Figure, and there's no file size benefit to compositing
  234. # with the Agg backend
  235. return True
  236. def option_scale_image(self):
  237. # docstring inherited
  238. return False
  239. def restore_region(self, region, bbox=None, xy=None):
  240. """
  241. Restore the saved region. If bbox (instance of BboxBase, or
  242. its extents) is given, only the region specified by the bbox
  243. will be restored. *xy* (a pair of floats) optionally
  244. specifies the new position (the LLC of the original region,
  245. not the LLC of the bbox) where the region will be restored.
  246. >>> region = renderer.copy_from_bbox()
  247. >>> x1, y1, x2, y2 = region.get_extents()
  248. >>> renderer.restore_region(region, bbox=(x1+dx, y1, x2, y2),
  249. ... xy=(x1-dx, y1))
  250. """
  251. if bbox is not None or xy is not None:
  252. if bbox is None:
  253. x1, y1, x2, y2 = region.get_extents()
  254. elif isinstance(bbox, BboxBase):
  255. x1, y1, x2, y2 = bbox.extents
  256. else:
  257. x1, y1, x2, y2 = bbox
  258. if xy is None:
  259. ox, oy = x1, y1
  260. else:
  261. ox, oy = xy
  262. # The incoming data is float, but the _renderer type-checking wants
  263. # to see integers.
  264. self._renderer.restore_region(region, int(x1), int(y1),
  265. int(x2), int(y2), int(ox), int(oy))
  266. else:
  267. self._renderer.restore_region(region)
  268. def start_filter(self):
  269. """
  270. Start filtering. It simply creates a new canvas (the old one is saved).
  271. """
  272. self._filter_renderers.append(self._renderer)
  273. self._renderer = _RendererAgg(int(self.width), int(self.height),
  274. self.dpi)
  275. self._update_methods()
  276. def stop_filter(self, post_processing):
  277. """
  278. Save the current canvas as an image and apply post processing.
  279. The *post_processing* function::
  280. def post_processing(image, dpi):
  281. # ny, nx, depth = image.shape
  282. # image (numpy array) has RGBA channels and has a depth of 4.
  283. ...
  284. # create a new_image (numpy array of 4 channels, size can be
  285. # different). The resulting image may have offsets from
  286. # lower-left corner of the original image
  287. return new_image, offset_x, offset_y
  288. The saved renderer is restored and the returned image from
  289. post_processing is plotted (using draw_image) on it.
  290. """
  291. orig_img = np.asarray(self.buffer_rgba())
  292. slice_y, slice_x = cbook._get_nonzero_slices(orig_img[..., 3])
  293. cropped_img = orig_img[slice_y, slice_x]
  294. self._renderer = self._filter_renderers.pop()
  295. self._update_methods()
  296. if cropped_img.size:
  297. img, ox, oy = post_processing(cropped_img / 255, self.dpi)
  298. gc = self.new_gc()
  299. if img.dtype.kind == 'f':
  300. img = np.asarray(img * 255., np.uint8)
  301. self._renderer.draw_image(
  302. gc, slice_x.start + ox, int(self.height) - slice_y.stop + oy,
  303. img[::-1])
  304. class FigureCanvasAgg(FigureCanvasBase):
  305. # docstring inherited
  306. _lastKey = None # Overwritten per-instance on the first draw.
  307. def copy_from_bbox(self, bbox):
  308. renderer = self.get_renderer()
  309. return renderer.copy_from_bbox(bbox)
  310. def restore_region(self, region, bbox=None, xy=None):
  311. renderer = self.get_renderer()
  312. return renderer.restore_region(region, bbox, xy)
  313. def draw(self):
  314. # docstring inherited
  315. self.renderer = self.get_renderer()
  316. self.renderer.clear()
  317. # Acquire a lock on the shared font cache.
  318. with (self.toolbar._wait_cursor_for_draw_cm() if self.toolbar
  319. else nullcontext()):
  320. self.figure.draw(self.renderer)
  321. # A GUI class may be need to update a window using this draw, so
  322. # don't forget to call the superclass.
  323. super().draw()
  324. def get_renderer(self):
  325. w, h = self.figure.bbox.size
  326. key = w, h, self.figure.dpi
  327. reuse_renderer = (self._lastKey == key)
  328. if not reuse_renderer:
  329. self.renderer = RendererAgg(w, h, self.figure.dpi)
  330. self._lastKey = key
  331. return self.renderer
  332. def tostring_argb(self):
  333. """
  334. Get the image as ARGB `bytes`.
  335. `draw` must be called at least once before this function will work and
  336. to update the renderer for any subsequent changes to the Figure.
  337. """
  338. return self.renderer.tostring_argb()
  339. def buffer_rgba(self):
  340. """
  341. Get the image as a `memoryview` to the renderer's buffer.
  342. `draw` must be called at least once before this function will work and
  343. to update the renderer for any subsequent changes to the Figure.
  344. """
  345. return self.renderer.buffer_rgba()
  346. def print_raw(self, filename_or_obj, *, metadata=None):
  347. if metadata is not None:
  348. raise ValueError("metadata not supported for raw/rgba")
  349. FigureCanvasAgg.draw(self)
  350. renderer = self.get_renderer()
  351. with cbook.open_file_cm(filename_or_obj, "wb") as fh:
  352. fh.write(renderer.buffer_rgba())
  353. print_rgba = print_raw
  354. def _print_pil(self, filename_or_obj, fmt, pil_kwargs, metadata=None):
  355. """
  356. Draw the canvas, then save it using `.image.imsave` (to which
  357. *pil_kwargs* and *metadata* are forwarded).
  358. """
  359. FigureCanvasAgg.draw(self)
  360. mpl.image.imsave(
  361. filename_or_obj, self.buffer_rgba(), format=fmt, origin="upper",
  362. dpi=self.figure.dpi, metadata=metadata, pil_kwargs=pil_kwargs)
  363. def print_png(self, filename_or_obj, *, metadata=None, pil_kwargs=None):
  364. """
  365. Write the figure to a PNG file.
  366. Parameters
  367. ----------
  368. filename_or_obj : str or path-like or file-like
  369. The file to write to.
  370. metadata : dict, optional
  371. Metadata in the PNG file as key-value pairs of bytes or latin-1
  372. encodable strings.
  373. According to the PNG specification, keys must be shorter than 79
  374. chars.
  375. The `PNG specification`_ defines some common keywords that may be
  376. used as appropriate:
  377. - Title: Short (one line) title or caption for image.
  378. - Author: Name of image's creator.
  379. - Description: Description of image (possibly long).
  380. - Copyright: Copyright notice.
  381. - Creation Time: Time of original image creation
  382. (usually RFC 1123 format).
  383. - Software: Software used to create the image.
  384. - Disclaimer: Legal disclaimer.
  385. - Warning: Warning of nature of content.
  386. - Source: Device used to create the image.
  387. - Comment: Miscellaneous comment;
  388. conversion from other image format.
  389. Other keywords may be invented for other purposes.
  390. If 'Software' is not given, an autogenerated value for Matplotlib
  391. will be used. This can be removed by setting it to *None*.
  392. For more details see the `PNG specification`_.
  393. .. _PNG specification: \
  394. https://www.w3.org/TR/2003/REC-PNG-20031110/#11keywords
  395. pil_kwargs : dict, optional
  396. Keyword arguments passed to `PIL.Image.Image.save`.
  397. If the 'pnginfo' key is present, it completely overrides
  398. *metadata*, including the default 'Software' key.
  399. """
  400. self._print_pil(filename_or_obj, "png", pil_kwargs, metadata)
  401. def print_to_buffer(self):
  402. FigureCanvasAgg.draw(self)
  403. renderer = self.get_renderer()
  404. return (bytes(renderer.buffer_rgba()),
  405. (int(renderer.width), int(renderer.height)))
  406. # Note that these methods should typically be called via savefig() and
  407. # print_figure(), and the latter ensures that `self.figure.dpi` already
  408. # matches the dpi kwarg (if any).
  409. def print_jpg(self, filename_or_obj, *, metadata=None, pil_kwargs=None):
  410. # savefig() has already applied savefig.facecolor; we now set it to
  411. # white to make imsave() blend semi-transparent figures against an
  412. # assumed white background.
  413. with mpl.rc_context({"savefig.facecolor": "white"}):
  414. self._print_pil(filename_or_obj, "jpeg", pil_kwargs, metadata)
  415. print_jpeg = print_jpg
  416. def print_tif(self, filename_or_obj, *, metadata=None, pil_kwargs=None):
  417. self._print_pil(filename_or_obj, "tiff", pil_kwargs, metadata)
  418. print_tiff = print_tif
  419. def print_webp(self, filename_or_obj, *, metadata=None, pil_kwargs=None):
  420. self._print_pil(filename_or_obj, "webp", pil_kwargs, metadata)
  421. print_jpg.__doc__, print_tif.__doc__, print_webp.__doc__ = map(
  422. """
  423. Write the figure to a {} file.
  424. Parameters
  425. ----------
  426. filename_or_obj : str or path-like or file-like
  427. The file to write to.
  428. pil_kwargs : dict, optional
  429. Additional keyword arguments that are passed to
  430. `PIL.Image.Image.save` when saving the figure.
  431. """.format, ["JPEG", "TIFF", "WebP"])
  432. @_Backend.export
  433. class _BackendAgg(_Backend):
  434. backend_version = 'v2.2'
  435. FigureCanvas = FigureCanvasAgg
  436. FigureManager = FigureManagerBase