Coverage for /usr/lib/python3/dist-packages/matplotlib/backends/backend_agg.py: 56%

245 statements  

« prev     ^ index     » next       coverage.py v7.9.1, created at 2025-06-14 15:55 +0200

1""" 

2An `Anti-Grain Geometry`_ (AGG) backend. 

3 

4Features that are implemented: 

5 

6* capstyles and join styles 

7* dashes 

8* linewidth 

9* lines, rectangles, ellipses 

10* clipping to a rectangle 

11* output to RGBA and Pillow-supported image formats 

12* alpha blending 

13* DPI scaling properly - everything scales properly (dashes, linewidths, etc) 

14* draw polygon 

15* freetype2 w/ ft2font 

16 

17Still TODO: 

18 

19* integrate screen dpi w/ ppi and text 

20 

21.. _Anti-Grain Geometry: http://agg.sourceforge.net/antigrain.com 

22""" 

23 

24from contextlib import nullcontext 

25from math import radians, cos, sin 

26import threading 

27 

28import numpy as np 

29 

30import matplotlib as mpl 

31from matplotlib import _api, cbook 

32from matplotlib.backend_bases import ( 

33 _Backend, FigureCanvasBase, FigureManagerBase, RendererBase) 

34from matplotlib.font_manager import fontManager as _fontManager, get_font 

35from matplotlib.ft2font import (LOAD_FORCE_AUTOHINT, LOAD_NO_HINTING, 

36 LOAD_DEFAULT, LOAD_NO_AUTOHINT) 

37from matplotlib.mathtext import MathTextParser 

38from matplotlib.path import Path 

39from matplotlib.transforms import Bbox, BboxBase 

40from matplotlib.backends._backend_agg import RendererAgg as _RendererAgg 

41 

42 

43def get_hinting_flag(): 

44 mapping = { 

45 'default': LOAD_DEFAULT, 

46 'no_autohint': LOAD_NO_AUTOHINT, 

47 'force_autohint': LOAD_FORCE_AUTOHINT, 

48 'no_hinting': LOAD_NO_HINTING, 

49 True: LOAD_FORCE_AUTOHINT, 

50 False: LOAD_NO_HINTING, 

51 'either': LOAD_DEFAULT, 

52 'native': LOAD_NO_AUTOHINT, 

53 'auto': LOAD_FORCE_AUTOHINT, 

54 'none': LOAD_NO_HINTING, 

55 } 

56 return mapping[mpl.rcParams['text.hinting']] 

57 

58 

59class RendererAgg(RendererBase): 

60 """ 

61 The renderer handles all the drawing primitives using a graphics 

62 context instance that controls the colors/styles 

63 """ 

64 

65 # we want to cache the fonts at the class level so that when 

66 # multiple figures are created we can reuse them. This helps with 

67 # a bug on windows where the creation of too many figures leads to 

68 # too many open file handles. However, storing them at the class 

69 # level is not thread safe. The solution here is to let the 

70 # FigureCanvas acquire a lock on the fontd at the start of the 

71 # draw, and release it when it is done. This allows multiple 

72 # renderers to share the cached fonts, but only one figure can 

73 # draw at time and so the font cache is used by only one 

74 # renderer at a time. 

75 

76 lock = threading.RLock() 

77 

78 def __init__(self, width, height, dpi): 

79 super().__init__() 

80 

81 self.dpi = dpi 

82 self.width = width 

83 self.height = height 

84 self._renderer = _RendererAgg(int(width), int(height), dpi) 

85 self._filter_renderers = [] 

86 

87 self._update_methods() 

88 self.mathtext_parser = MathTextParser('Agg') 

89 

90 self.bbox = Bbox.from_bounds(0, 0, self.width, self.height) 

91 

92 def __getstate__(self): 

93 # We only want to preserve the init keywords of the Renderer. 

94 # Anything else can be re-created. 

95 return {'width': self.width, 'height': self.height, 'dpi': self.dpi} 

96 

97 def __setstate__(self, state): 

98 self.__init__(state['width'], state['height'], state['dpi']) 

99 

100 def _update_methods(self): 

101 self.draw_gouraud_triangle = self._renderer.draw_gouraud_triangle 

102 self.draw_gouraud_triangles = self._renderer.draw_gouraud_triangles 

103 self.draw_image = self._renderer.draw_image 

104 self.draw_markers = self._renderer.draw_markers 

105 self.draw_path_collection = self._renderer.draw_path_collection 

106 self.draw_quad_mesh = self._renderer.draw_quad_mesh 

107 self.copy_from_bbox = self._renderer.copy_from_bbox 

108 

109 def draw_path(self, gc, path, transform, rgbFace=None): 

110 # docstring inherited 

111 nmax = mpl.rcParams['agg.path.chunksize'] # here at least for testing 

112 npts = path.vertices.shape[0] 

113 

114 if (npts > nmax > 100 and path.should_simplify and 

115 rgbFace is None and gc.get_hatch() is None): 

116 nch = np.ceil(npts / nmax) 

117 chsize = int(np.ceil(npts / nch)) 

118 i0 = np.arange(0, npts, chsize) 

119 i1 = np.zeros_like(i0) 

120 i1[:-1] = i0[1:] - 1 

121 i1[-1] = npts 

122 for ii0, ii1 in zip(i0, i1): 

123 v = path.vertices[ii0:ii1, :] 

124 c = path.codes 

125 if c is not None: 

126 c = c[ii0:ii1] 

127 c[0] = Path.MOVETO # move to end of last chunk 

128 p = Path(v, c) 

129 p.simplify_threshold = path.simplify_threshold 

130 try: 

131 self._renderer.draw_path(gc, p, transform, rgbFace) 

132 except OverflowError: 

133 msg = ( 

134 "Exceeded cell block limit in Agg.\n\n" 

135 "Please reduce the value of " 

136 f"rcParams['agg.path.chunksize'] (currently {nmax}) " 

137 "or increase the path simplification threshold" 

138 "(rcParams['path.simplify_threshold'] = " 

139 f"{mpl.rcParams['path.simplify_threshold']:.2f} by " 

140 "default and path.simplify_threshold = " 

141 f"{path.simplify_threshold:.2f} on the input)." 

142 ) 

143 raise OverflowError(msg) from None 

144 else: 

145 try: 

146 self._renderer.draw_path(gc, path, transform, rgbFace) 

147 except OverflowError: 

148 cant_chunk = '' 

149 if rgbFace is not None: 

150 cant_chunk += "- can not split filled path\n" 

151 if gc.get_hatch() is not None: 

152 cant_chunk += "- can not split hatched path\n" 

153 if not path.should_simplify: 

154 cant_chunk += "- path.should_simplify is False\n" 

155 if len(cant_chunk): 

156 msg = ( 

157 "Exceeded cell block limit in Agg, however for the " 

158 "following reasons:\n\n" 

159 f"{cant_chunk}\n" 

160 "we can not automatically split up this path to draw." 

161 "\n\nPlease manually simplify your path." 

162 ) 

163 

164 else: 

165 inc_threshold = ( 

166 "or increase the path simplification threshold" 

167 "(rcParams['path.simplify_threshold'] = " 

168 f"{mpl.rcParams['path.simplify_threshold']} " 

169 "by default and path.simplify_threshold " 

170 f"= {path.simplify_threshold} " 

171 "on the input)." 

172 ) 

173 if nmax > 100: 

174 msg = ( 

175 "Exceeded cell block limit in Agg. Please reduce " 

176 "the value of rcParams['agg.path.chunksize'] " 

177 f"(currently {nmax}) {inc_threshold}" 

178 ) 

179 else: 

180 msg = ( 

181 "Exceeded cell block limit in Agg. Please set " 

182 "the value of rcParams['agg.path.chunksize'], " 

183 f"(currently {nmax}) to be greater than 100 " 

184 + inc_threshold 

185 ) 

186 

187 raise OverflowError(msg) from None 

188 

189 def draw_mathtext(self, gc, x, y, s, prop, angle): 

190 """Draw mathtext using :mod:`matplotlib.mathtext`.""" 

191 ox, oy, width, height, descent, font_image = \ 

192 self.mathtext_parser.parse(s, self.dpi, prop) 

193 

194 xd = descent * sin(radians(angle)) 

195 yd = descent * cos(radians(angle)) 

196 x = round(x + ox + xd) 

197 y = round(y - oy + yd) 

198 self._renderer.draw_text_image(font_image, x, y + 1, angle, gc) 

199 

200 def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None): 

201 # docstring inherited 

202 if ismath: 

203 return self.draw_mathtext(gc, x, y, s, prop, angle) 

204 font = self._prepare_font(prop) 

205 # We pass '0' for angle here, since it will be rotated (in raster 

206 # space) in the following call to draw_text_image). 

207 font.set_text(s, 0, flags=get_hinting_flag()) 

208 font.draw_glyphs_to_bitmap( 

209 antialiased=mpl.rcParams['text.antialiased']) 

210 d = font.get_descent() / 64.0 

211 # The descent needs to be adjusted for the angle. 

212 xo, yo = font.get_bitmap_offset() 

213 xo /= 64.0 

214 yo /= 64.0 

215 xd = d * sin(radians(angle)) 

216 yd = d * cos(radians(angle)) 

217 x = round(x + xo + xd) 

218 y = round(y + yo + yd) 

219 self._renderer.draw_text_image(font, x, y + 1, angle, gc) 

220 

221 def get_text_width_height_descent(self, s, prop, ismath): 

222 # docstring inherited 

223 

224 _api.check_in_list(["TeX", True, False], ismath=ismath) 

225 if ismath == "TeX": 

226 # todo: handle props 

227 texmanager = self.get_texmanager() 

228 fontsize = prop.get_size_in_points() 

229 w, h, d = texmanager.get_text_width_height_descent( 

230 s, fontsize, renderer=self) 

231 return w, h, d 

232 

233 if ismath: 

234 ox, oy, width, height, descent, font_image = \ 

235 self.mathtext_parser.parse(s, self.dpi, prop) 

236 return width, height, descent 

237 

238 font = self._prepare_font(prop) 

239 font.set_text(s, 0.0, flags=get_hinting_flag()) 

240 w, h = font.get_width_height() # width and height of unrotated string 

241 d = font.get_descent() 

242 w /= 64.0 # convert from subpixels 

243 h /= 64.0 

244 d /= 64.0 

245 return w, h, d 

246 

247 def draw_tex(self, gc, x, y, s, prop, angle, *, mtext=None): 

248 # docstring inherited 

249 # todo, handle props, angle, origins 

250 size = prop.get_size_in_points() 

251 

252 texmanager = self.get_texmanager() 

253 

254 Z = texmanager.get_grey(s, size, self.dpi) 

255 Z = np.array(Z * 255.0, np.uint8) 

256 

257 w, h, d = self.get_text_width_height_descent(s, prop, ismath="TeX") 

258 xd = d * sin(radians(angle)) 

259 yd = d * cos(radians(angle)) 

260 x = round(x + xd) 

261 y = round(y + yd) 

262 self._renderer.draw_text_image(Z, x, y, angle, gc) 

263 

264 def get_canvas_width_height(self): 

265 # docstring inherited 

266 return self.width, self.height 

267 

268 def _prepare_font(self, font_prop): 

269 """ 

270 Get the `.FT2Font` for *font_prop*, clear its buffer, and set its size. 

271 """ 

272 font = get_font(_fontManager._find_fonts_by_props(font_prop)) 

273 font.clear() 

274 size = font_prop.get_size_in_points() 

275 font.set_size(size, self.dpi) 

276 return font 

277 

278 def points_to_pixels(self, points): 

279 # docstring inherited 

280 return points * self.dpi / 72 

281 

282 def buffer_rgba(self): 

283 return memoryview(self._renderer) 

284 

285 def tostring_argb(self): 

286 return np.asarray(self._renderer).take([3, 0, 1, 2], axis=2).tobytes() 

287 

288 def tostring_rgb(self): 

289 return np.asarray(self._renderer).take([0, 1, 2], axis=2).tobytes() 

290 

291 def clear(self): 

292 self._renderer.clear() 

293 

294 def option_image_nocomposite(self): 

295 # docstring inherited 

296 

297 # It is generally faster to composite each image directly to 

298 # the Figure, and there's no file size benefit to compositing 

299 # with the Agg backend 

300 return True 

301 

302 def option_scale_image(self): 

303 # docstring inherited 

304 return False 

305 

306 def restore_region(self, region, bbox=None, xy=None): 

307 """ 

308 Restore the saved region. If bbox (instance of BboxBase, or 

309 its extents) is given, only the region specified by the bbox 

310 will be restored. *xy* (a pair of floats) optionally 

311 specifies the new position (the LLC of the original region, 

312 not the LLC of the bbox) where the region will be restored. 

313 

314 >>> region = renderer.copy_from_bbox() 

315 >>> x1, y1, x2, y2 = region.get_extents() 

316 >>> renderer.restore_region(region, bbox=(x1+dx, y1, x2, y2), 

317 ... xy=(x1-dx, y1)) 

318 

319 """ 

320 if bbox is not None or xy is not None: 

321 if bbox is None: 

322 x1, y1, x2, y2 = region.get_extents() 

323 elif isinstance(bbox, BboxBase): 

324 x1, y1, x2, y2 = bbox.extents 

325 else: 

326 x1, y1, x2, y2 = bbox 

327 

328 if xy is None: 

329 ox, oy = x1, y1 

330 else: 

331 ox, oy = xy 

332 

333 # The incoming data is float, but the _renderer type-checking wants 

334 # to see integers. 

335 self._renderer.restore_region(region, int(x1), int(y1), 

336 int(x2), int(y2), int(ox), int(oy)) 

337 

338 else: 

339 self._renderer.restore_region(region) 

340 

341 def start_filter(self): 

342 """ 

343 Start filtering. It simply create a new canvas (the old one is saved). 

344 """ 

345 self._filter_renderers.append(self._renderer) 

346 self._renderer = _RendererAgg(int(self.width), int(self.height), 

347 self.dpi) 

348 self._update_methods() 

349 

350 def stop_filter(self, post_processing): 

351 """ 

352 Save the plot in the current canvas as a image and apply 

353 the *post_processing* function. 

354 

355 def post_processing(image, dpi): 

356 # ny, nx, depth = image.shape 

357 # image (numpy array) has RGBA channels and has a depth of 4. 

358 ... 

359 # create a new_image (numpy array of 4 channels, size can be 

360 # different). The resulting image may have offsets from 

361 # lower-left corner of the original image 

362 return new_image, offset_x, offset_y 

363 

364 The saved renderer is restored and the returned image from 

365 post_processing is plotted (using draw_image) on it. 

366 """ 

367 orig_img = np.asarray(self.buffer_rgba()) 

368 slice_y, slice_x = cbook._get_nonzero_slices(orig_img[..., 3]) 

369 cropped_img = orig_img[slice_y, slice_x] 

370 

371 self._renderer = self._filter_renderers.pop() 

372 self._update_methods() 

373 

374 if cropped_img.size: 

375 img, ox, oy = post_processing(cropped_img / 255, self.dpi) 

376 gc = self.new_gc() 

377 if img.dtype.kind == 'f': 

378 img = np.asarray(img * 255., np.uint8) 

379 self._renderer.draw_image( 

380 gc, slice_x.start + ox, int(self.height) - slice_y.stop + oy, 

381 img[::-1]) 

382 

383 

384class FigureCanvasAgg(FigureCanvasBase): 

385 # docstring inherited 

386 

387 _lastKey = None # Overwritten per-instance on the first draw. 

388 

389 def copy_from_bbox(self, bbox): 

390 renderer = self.get_renderer() 

391 return renderer.copy_from_bbox(bbox) 

392 

393 def restore_region(self, region, bbox=None, xy=None): 

394 renderer = self.get_renderer() 

395 return renderer.restore_region(region, bbox, xy) 

396 

397 def draw(self): 

398 # docstring inherited 

399 self.renderer = self.get_renderer() 

400 self.renderer.clear() 

401 # Acquire a lock on the shared font cache. 

402 with RendererAgg.lock, \ 

403 (self.toolbar._wait_cursor_for_draw_cm() if self.toolbar 

404 else nullcontext()): 

405 self.figure.draw(self.renderer) 

406 # A GUI class may be need to update a window using this draw, so 

407 # don't forget to call the superclass. 

408 super().draw() 

409 

410 @_api.delete_parameter("3.6", "cleared", alternative="renderer.clear()") 

411 def get_renderer(self, cleared=False): 

412 w, h = self.figure.bbox.size 

413 key = w, h, self.figure.dpi 

414 reuse_renderer = (self._lastKey == key) 

415 if not reuse_renderer: 

416 self.renderer = RendererAgg(w, h, self.figure.dpi) 

417 self._lastKey = key 

418 elif cleared: 

419 self.renderer.clear() 

420 return self.renderer 

421 

422 def tostring_rgb(self): 

423 """ 

424 Get the image as RGB `bytes`. 

425 

426 `draw` must be called at least once before this function will work and 

427 to update the renderer for any subsequent changes to the Figure. 

428 """ 

429 return self.renderer.tostring_rgb() 

430 

431 def tostring_argb(self): 

432 """ 

433 Get the image as ARGB `bytes`. 

434 

435 `draw` must be called at least once before this function will work and 

436 to update the renderer for any subsequent changes to the Figure. 

437 """ 

438 return self.renderer.tostring_argb() 

439 

440 def buffer_rgba(self): 

441 """ 

442 Get the image as a `memoryview` to the renderer's buffer. 

443 

444 `draw` must be called at least once before this function will work and 

445 to update the renderer for any subsequent changes to the Figure. 

446 """ 

447 return self.renderer.buffer_rgba() 

448 

449 @_api.delete_parameter("3.5", "args") 

450 def print_raw(self, filename_or_obj, *args): 

451 FigureCanvasAgg.draw(self) 

452 renderer = self.get_renderer() 

453 with cbook.open_file_cm(filename_or_obj, "wb") as fh: 

454 fh.write(renderer.buffer_rgba()) 

455 

456 print_rgba = print_raw 

457 

458 def _print_pil(self, filename_or_obj, fmt, pil_kwargs, metadata=None): 

459 """ 

460 Draw the canvas, then save it using `.image.imsave` (to which 

461 *pil_kwargs* and *metadata* are forwarded). 

462 """ 

463 FigureCanvasAgg.draw(self) 

464 mpl.image.imsave( 

465 filename_or_obj, self.buffer_rgba(), format=fmt, origin="upper", 

466 dpi=self.figure.dpi, metadata=metadata, pil_kwargs=pil_kwargs) 

467 

468 @_api.delete_parameter("3.5", "args") 

469 def print_png(self, filename_or_obj, *args, 

470 metadata=None, pil_kwargs=None): 

471 """ 

472 Write the figure to a PNG file. 

473 

474 Parameters 

475 ---------- 

476 filename_or_obj : str or path-like or file-like 

477 The file to write to. 

478 

479 metadata : dict, optional 

480 Metadata in the PNG file as key-value pairs of bytes or latin-1 

481 encodable strings. 

482 According to the PNG specification, keys must be shorter than 79 

483 chars. 

484 

485 The `PNG specification`_ defines some common keywords that may be 

486 used as appropriate: 

487 

488 - Title: Short (one line) title or caption for image. 

489 - Author: Name of image's creator. 

490 - Description: Description of image (possibly long). 

491 - Copyright: Copyright notice. 

492 - Creation Time: Time of original image creation 

493 (usually RFC 1123 format). 

494 - Software: Software used to create the image. 

495 - Disclaimer: Legal disclaimer. 

496 - Warning: Warning of nature of content. 

497 - Source: Device used to create the image. 

498 - Comment: Miscellaneous comment; 

499 conversion from other image format. 

500 

501 Other keywords may be invented for other purposes. 

502 

503 If 'Software' is not given, an autogenerated value for Matplotlib 

504 will be used. This can be removed by setting it to *None*. 

505 

506 For more details see the `PNG specification`_. 

507 

508 .. _PNG specification: \ 

509 https://www.w3.org/TR/2003/REC-PNG-20031110/#11keywords 

510 

511 pil_kwargs : dict, optional 

512 Keyword arguments passed to `PIL.Image.Image.save`. 

513 

514 If the 'pnginfo' key is present, it completely overrides 

515 *metadata*, including the default 'Software' key. 

516 """ 

517 self._print_pil(filename_or_obj, "png", pil_kwargs, metadata) 

518 

519 def print_to_buffer(self): 

520 FigureCanvasAgg.draw(self) 

521 renderer = self.get_renderer() 

522 return (bytes(renderer.buffer_rgba()), 

523 (int(renderer.width), int(renderer.height))) 

524 

525 # Note that these methods should typically be called via savefig() and 

526 # print_figure(), and the latter ensures that `self.figure.dpi` already 

527 # matches the dpi kwarg (if any). 

528 

529 @_api.delete_parameter("3.5", "args") 

530 def print_jpg(self, filename_or_obj, *args, pil_kwargs=None): 

531 # savefig() has already applied savefig.facecolor; we now set it to 

532 # white to make imsave() blend semi-transparent figures against an 

533 # assumed white background. 

534 with mpl.rc_context({"savefig.facecolor": "white"}): 

535 self._print_pil(filename_or_obj, "jpeg", pil_kwargs) 

536 

537 print_jpeg = print_jpg 

538 

539 def print_tif(self, filename_or_obj, *, pil_kwargs=None): 

540 self._print_pil(filename_or_obj, "tiff", pil_kwargs) 

541 

542 print_tiff = print_tif 

543 

544 def print_webp(self, filename_or_obj, *, pil_kwargs=None): 

545 self._print_pil(filename_or_obj, "webp", pil_kwargs) 

546 

547 print_jpg.__doc__, print_tif.__doc__, print_webp.__doc__ = map( 

548 """ 

549 Write the figure to a {} file. 

550 

551 Parameters 

552 ---------- 

553 filename_or_obj : str or path-like or file-like 

554 The file to write to. 

555 pil_kwargs : dict, optional 

556 Additional keyword arguments that are passed to 

557 `PIL.Image.Image.save` when saving the figure. 

558 """.format, ["JPEG", "TIFF", "WebP"]) 

559 

560 

561@_Backend.export 

562class _BackendAgg(_Backend): 

563 backend_version = 'v2.2' 

564 FigureCanvas = FigureCanvasAgg 

565 FigureManager = FigureManagerBase