backend_agg.py 20 KB

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