matplotlib-rs 0.0.8__cp315-cp315-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (352) hide show
  1. docs/releases/0.0.1.md +268 -0
  2. docs/releases/0.0.2.md +69 -0
  3. docs/releases/0.0.3.md +80 -0
  4. docs/releases/0.0.4.md +73 -0
  5. docs/releases/0.0.5.md +24 -0
  6. docs/releases/0.0.6.md +24 -0
  7. docs/releases/0.0.7.md +24 -0
  8. docs/releases/0.0.8.md +16 -0
  9. licenses/LICENSE_CONTOURPY +29 -0
  10. licenses/LICENSE_CYCLER +27 -0
  11. licenses/LICENSE_DATEUTIL +54 -0
  12. licenses/LICENSE_KIWISOLVER +71 -0
  13. licenses/LICENSE_LIBWEBP +56 -0
  14. licenses/LICENSE_MATPLOTLIB +1253 -0
  15. licenses/LICENSE_PYPARSING +20 -0
  16. licenses/LICENSE_QHULL +39 -0
  17. licenses/LICENSE_SIX +18 -0
  18. matplotlib_rs/__init__.py +1683 -0
  19. matplotlib_rs/__main__.py +27 -0
  20. matplotlib_rs/_afm.py +500 -0
  21. matplotlib_rs/_animation_data.py +263 -0
  22. matplotlib_rs/_api/__init__.py +495 -0
  23. matplotlib_rs/_api/deprecation.py +534 -0
  24. matplotlib_rs/_axis_py.py +2991 -0
  25. matplotlib_rs/_blocking_input.py +31 -0
  26. matplotlib_rs/_cm.py +1500 -0
  27. matplotlib_rs/_cm_bivar.py +1289 -0
  28. matplotlib_rs/_cm_listed.py +2848 -0
  29. matplotlib_rs/_cm_multivar.py +167 -0
  30. matplotlib_rs/_color_data.py +1142 -0
  31. matplotlib_rs/_colormap.py +132 -0
  32. matplotlib_rs/_constrained_layout.py +825 -0
  33. matplotlib_rs/_contour.py +108 -0
  34. matplotlib_rs/_doc_cache.py +12214 -0
  35. matplotlib_rs/_docstring.py +142 -0
  36. matplotlib_rs/_enums.py +178 -0
  37. matplotlib_rs/_figure_rs.py +294 -0
  38. matplotlib_rs/_fontconfig_pattern.py +129 -0
  39. matplotlib_rs/_foreign.py +220 -0
  40. matplotlib_rs/_hook.py +94 -0
  41. matplotlib_rs/_image.py +160 -0
  42. matplotlib_rs/_imageio.py +229 -0
  43. matplotlib_rs/_internal_utils.py +65 -0
  44. matplotlib_rs/_kiwi.py +484 -0
  45. matplotlib_rs/_layoutgrid.py +549 -0
  46. matplotlib_rs/_live.py +192 -0
  47. matplotlib_rs/_mathtext.py +3103 -0
  48. matplotlib_rs/_mathtext_data.py +1811 -0
  49. matplotlib_rs/_mplrs.cp315-win_amd64.pyd +0 -0
  50. matplotlib_rs/_path.py +25 -0
  51. matplotlib_rs/_png.py +162 -0
  52. matplotlib_rs/_pylab_helpers.py +137 -0
  53. matplotlib_rs/_qhull.py +66 -0
  54. matplotlib_rs/_rcpush.py +84 -0
  55. matplotlib_rs/_spines_rs.py +108 -0
  56. matplotlib_rs/_style_helpers.py +52 -0
  57. matplotlib_rs/_text_helpers.py +51 -0
  58. matplotlib_rs/_tight_bbox.py +85 -0
  59. matplotlib_rs/_tight_layout.py +302 -0
  60. matplotlib_rs/_tri.py +140 -0
  61. matplotlib_rs/_type1font.py +1228 -0
  62. matplotlib_rs/_vendor/__init__.py +8 -0
  63. matplotlib_rs/_vendor/cycler.py +574 -0
  64. matplotlib_rs/_vendor/dateutil/__init__.py +27 -0
  65. matplotlib_rs/_vendor/dateutil/_common.py +44 -0
  66. matplotlib_rs/_vendor/dateutil/_tzdata_impl.py +148 -0
  67. matplotlib_rs/_vendor/dateutil/_version.py +5 -0
  68. matplotlib_rs/_vendor/dateutil/easter.py +90 -0
  69. matplotlib_rs/_vendor/dateutil/parser/__init__.py +62 -0
  70. matplotlib_rs/_vendor/dateutil/parser/_parser.py +1614 -0
  71. matplotlib_rs/_vendor/dateutil/parser/isoparser.py +417 -0
  72. matplotlib_rs/_vendor/dateutil/relativedelta.py +597 -0
  73. matplotlib_rs/_vendor/dateutil/rrule.py +1765 -0
  74. matplotlib_rs/_vendor/dateutil/tz/__init__.py +61 -0
  75. matplotlib_rs/_vendor/dateutil/tz/_common.py +420 -0
  76. matplotlib_rs/_vendor/dateutil/tz/_factories.py +81 -0
  77. matplotlib_rs/_vendor/dateutil/tz/_tzfile.py +1429 -0
  78. matplotlib_rs/_vendor/dateutil/tz/_tzpath.py +105 -0
  79. matplotlib_rs/_vendor/dateutil/tz/tz.py +1473 -0
  80. matplotlib_rs/_vendor/dateutil/tz/win.py +371 -0
  81. matplotlib_rs/_vendor/dateutil/tzwin.py +3 -0
  82. matplotlib_rs/_vendor/dateutil/utils.py +72 -0
  83. matplotlib_rs/_vendor/dateutil/zoneinfo/__init__.py +234 -0
  84. matplotlib_rs/_vendor/pyparsing/__init__.py +414 -0
  85. matplotlib_rs/_vendor/pyparsing/actions.py +265 -0
  86. matplotlib_rs/_vendor/pyparsing/common.py +571 -0
  87. matplotlib_rs/_vendor/pyparsing/core.py +6973 -0
  88. matplotlib_rs/_vendor/pyparsing/exceptions.py +354 -0
  89. matplotlib_rs/_vendor/pyparsing/helpers.py +1770 -0
  90. matplotlib_rs/_vendor/pyparsing/results.py +929 -0
  91. matplotlib_rs/_vendor/pyparsing/testing.py +399 -0
  92. matplotlib_rs/_vendor/pyparsing/unicode.py +357 -0
  93. matplotlib_rs/_vendor/pyparsing/util.py +515 -0
  94. matplotlib_rs/_vendor/pyparsing/warnings.py +11 -0
  95. matplotlib_rs/_vendor/six.py +1004 -0
  96. matplotlib_rs/animation.py +1843 -0
  97. matplotlib_rs/artist.py +2302 -0
  98. matplotlib_rs/axes/__init__.py +19 -0
  99. matplotlib_rs/axes/_axes.py +9402 -0
  100. matplotlib_rs/axes/_bar.py +185 -0
  101. matplotlib_rs/axes/_base.py +5236 -0
  102. matplotlib_rs/axes/_base_rs.py +727 -0
  103. matplotlib_rs/axes/_boxplot.py +391 -0
  104. matplotlib_rs/axes/_hist.py +99 -0
  105. matplotlib_rs/axes/_secondary_axes.py +357 -0
  106. matplotlib_rs/axis.py +1963 -0
  107. matplotlib_rs/backend_bases.py +3760 -0
  108. matplotlib_rs/backend_managers.py +388 -0
  109. matplotlib_rs/backend_tools.py +1002 -0
  110. matplotlib_rs/backends/__init__.py +6 -0
  111. matplotlib_rs/backends/_backend_pdf_ps.py +451 -0
  112. matplotlib_rs/backends/backend_agg.py +552 -0
  113. matplotlib_rs/backends/backend_mixed.py +123 -0
  114. matplotlib_rs/backends/backend_pdf.py +2711 -0
  115. matplotlib_rs/backends/backend_pgf.py +1031 -0
  116. matplotlib_rs/backends/backend_ps.py +1491 -0
  117. matplotlib_rs/backends/backend_svg.py +1395 -0
  118. matplotlib_rs/backends/backend_template.py +214 -0
  119. matplotlib_rs/backends/registry.py +423 -0
  120. matplotlib_rs/bezier.py +691 -0
  121. matplotlib_rs/category.py +236 -0
  122. matplotlib_rs/cbook.py +2762 -0
  123. matplotlib_rs/cm.py +251 -0
  124. matplotlib_rs/collections.py +2711 -0
  125. matplotlib_rs/colorbar.py +1586 -0
  126. matplotlib_rs/colorizer.py +909 -0
  127. matplotlib_rs/colors.py +4278 -0
  128. matplotlib_rs/container.py +256 -0
  129. matplotlib_rs/contour.py +1756 -0
  130. matplotlib_rs/dates.py +1847 -0
  131. matplotlib_rs/dviread.py +1386 -0
  132. matplotlib_rs/figure.py +3815 -0
  133. matplotlib_rs/font_manager.py +1855 -0
  134. matplotlib_rs/ft2font.py +515 -0
  135. matplotlib_rs/gridspec.py +808 -0
  136. matplotlib_rs/hatch.py +244 -0
  137. matplotlib_rs/image.py +1863 -0
  138. matplotlib_rs/inset.py +291 -0
  139. matplotlib_rs/layout_engine.py +310 -0
  140. matplotlib_rs/legend.py +1480 -0
  141. matplotlib_rs/legend_handler.py +812 -0
  142. matplotlib_rs/lines.py +1886 -0
  143. matplotlib_rs/markers.py +908 -0
  144. matplotlib_rs/mathtext.py +141 -0
  145. matplotlib_rs/mlab.py +959 -0
  146. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSans-Bold.ttf +0 -0
  147. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSans-BoldOblique.ttf +0 -0
  148. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSans-Oblique.ttf +0 -0
  149. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSans.ttf +0 -0
  150. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSansDisplay.ttf +0 -0
  151. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSansMono-Bold.ttf +0 -0
  152. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSansMono-BoldOblique.ttf +0 -0
  153. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSansMono-Oblique.ttf +0 -0
  154. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSansMono.ttf +0 -0
  155. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSerif-Bold.ttf +0 -0
  156. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSerif-BoldItalic.ttf +0 -0
  157. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSerif-Italic.ttf +0 -0
  158. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSerif.ttf +0 -0
  159. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSerifDisplay.ttf +0 -0
  160. matplotlib_rs/mpl-data/fonts/ttf/LICENSE_DEJAVU +99 -0
  161. matplotlib_rs/mpl-data/fonts/ttf/LICENSE_STIX +124 -0
  162. matplotlib_rs/mpl-data/fonts/ttf/LastResortHE-Regular.ttf +0 -0
  163. matplotlib_rs/mpl-data/fonts/ttf/STIXGeneral.ttf +0 -0
  164. matplotlib_rs/mpl-data/fonts/ttf/STIXGeneralBol.ttf +0 -0
  165. matplotlib_rs/mpl-data/fonts/ttf/STIXGeneralBolIta.ttf +0 -0
  166. matplotlib_rs/mpl-data/fonts/ttf/STIXGeneralItalic.ttf +0 -0
  167. matplotlib_rs/mpl-data/fonts/ttf/STIXNonUni.ttf +0 -0
  168. matplotlib_rs/mpl-data/fonts/ttf/STIXNonUniBol.ttf +0 -0
  169. matplotlib_rs/mpl-data/fonts/ttf/STIXNonUniBolIta.ttf +0 -0
  170. matplotlib_rs/mpl-data/fonts/ttf/STIXNonUniIta.ttf +0 -0
  171. matplotlib_rs/mpl-data/fonts/ttf/STIXSizFiveSymReg.ttf +0 -0
  172. matplotlib_rs/mpl-data/fonts/ttf/STIXSizFourSymBol.ttf +0 -0
  173. matplotlib_rs/mpl-data/fonts/ttf/STIXSizFourSymReg.ttf +0 -0
  174. matplotlib_rs/mpl-data/fonts/ttf/STIXSizOneSymBol.ttf +0 -0
  175. matplotlib_rs/mpl-data/fonts/ttf/STIXSizOneSymReg.ttf +0 -0
  176. matplotlib_rs/mpl-data/fonts/ttf/STIXSizThreeSymBol.ttf +0 -0
  177. matplotlib_rs/mpl-data/fonts/ttf/STIXSizThreeSymReg.ttf +0 -0
  178. matplotlib_rs/mpl-data/fonts/ttf/STIXSizTwoSymBol.ttf +0 -0
  179. matplotlib_rs/mpl-data/fonts/ttf/STIXSizTwoSymReg.ttf +0 -0
  180. matplotlib_rs/mpl-data/fonts/ttf/cmb10.ttf +0 -0
  181. matplotlib_rs/mpl-data/fonts/ttf/cmex10.ttf +0 -0
  182. matplotlib_rs/mpl-data/fonts/ttf/cmmi10.ttf +0 -0
  183. matplotlib_rs/mpl-data/fonts/ttf/cmr10.ttf +0 -0
  184. matplotlib_rs/mpl-data/fonts/ttf/cmss10.ttf +0 -0
  185. matplotlib_rs/mpl-data/fonts/ttf/cmsy10.ttf +0 -0
  186. matplotlib_rs/mpl-data/fonts/ttf/cmti10.ttf +0 -0
  187. matplotlib_rs/mpl-data/fonts/ttf/cmtt10.ttf +0 -0
  188. matplotlib_rs/mpl-data/images/back-symbolic.svg +46 -0
  189. matplotlib_rs/mpl-data/images/back.pdf +0 -0
  190. matplotlib_rs/mpl-data/images/back.png +0 -0
  191. matplotlib_rs/mpl-data/images/back.svg +46 -0
  192. matplotlib_rs/mpl-data/images/back_large.png +0 -0
  193. matplotlib_rs/mpl-data/images/filesave-symbolic.svg +68 -0
  194. matplotlib_rs/mpl-data/images/filesave.pdf +72 -0
  195. matplotlib_rs/mpl-data/images/filesave.png +0 -0
  196. matplotlib_rs/mpl-data/images/filesave.svg +68 -0
  197. matplotlib_rs/mpl-data/images/filesave_large.png +0 -0
  198. matplotlib_rs/mpl-data/images/forward-symbolic.svg +46 -0
  199. matplotlib_rs/mpl-data/images/forward.pdf +0 -0
  200. matplotlib_rs/mpl-data/images/forward.png +0 -0
  201. matplotlib_rs/mpl-data/images/forward.svg +46 -0
  202. matplotlib_rs/mpl-data/images/forward_large.png +0 -0
  203. matplotlib_rs/mpl-data/images/hand.pdf +0 -0
  204. matplotlib_rs/mpl-data/images/hand.png +0 -0
  205. matplotlib_rs/mpl-data/images/hand.svg +130 -0
  206. matplotlib_rs/mpl-data/images/help-symbolic.svg +52 -0
  207. matplotlib_rs/mpl-data/images/help.pdf +71 -0
  208. matplotlib_rs/mpl-data/images/help.png +0 -0
  209. matplotlib_rs/mpl-data/images/help.svg +52 -0
  210. matplotlib_rs/mpl-data/images/help_large.png +0 -0
  211. matplotlib_rs/mpl-data/images/home-symbolic.svg +59 -0
  212. matplotlib_rs/mpl-data/images/home.pdf +0 -0
  213. matplotlib_rs/mpl-data/images/home.png +0 -0
  214. matplotlib_rs/mpl-data/images/home.svg +59 -0
  215. matplotlib_rs/mpl-data/images/home_large.png +0 -0
  216. matplotlib_rs/mpl-data/images/matplotlib.pdf +0 -0
  217. matplotlib_rs/mpl-data/images/matplotlib.png +0 -0
  218. matplotlib_rs/mpl-data/images/matplotlib.svg +3171 -0
  219. matplotlib_rs/mpl-data/images/matplotlib_large.png +0 -0
  220. matplotlib_rs/mpl-data/images/move-symbolic.svg +73 -0
  221. matplotlib_rs/mpl-data/images/move.pdf +0 -0
  222. matplotlib_rs/mpl-data/images/move.png +0 -0
  223. matplotlib_rs/mpl-data/images/move.svg +73 -0
  224. matplotlib_rs/mpl-data/images/move_large.png +0 -0
  225. matplotlib_rs/mpl-data/images/qt4_editor_options.pdf +0 -0
  226. matplotlib_rs/mpl-data/images/qt4_editor_options.png +0 -0
  227. matplotlib_rs/mpl-data/images/qt4_editor_options.svg +48 -0
  228. matplotlib_rs/mpl-data/images/qt4_editor_options_large.png +0 -0
  229. matplotlib_rs/mpl-data/images/subplots-symbolic.svg +81 -0
  230. matplotlib_rs/mpl-data/images/subplots.pdf +0 -0
  231. matplotlib_rs/mpl-data/images/subplots.png +0 -0
  232. matplotlib_rs/mpl-data/images/subplots.svg +81 -0
  233. matplotlib_rs/mpl-data/images/subplots_large.png +0 -0
  234. matplotlib_rs/mpl-data/images/zoom_to_rect-symbolic.svg +40 -0
  235. matplotlib_rs/mpl-data/images/zoom_to_rect.pdf +69 -0
  236. matplotlib_rs/mpl-data/images/zoom_to_rect.png +0 -0
  237. matplotlib_rs/mpl-data/images/zoom_to_rect.svg +40 -0
  238. matplotlib_rs/mpl-data/images/zoom_to_rect_large.png +0 -0
  239. matplotlib_rs/mpl-data/kpsewhich.lua +4 -0
  240. matplotlib_rs/mpl-data/matplotlibrc +849 -0
  241. matplotlib_rs/mpl-data/plot_directive/plot_directive.css +16 -0
  242. matplotlib_rs/mpl-data/sample_data/Minduka_Present_Blue_Pack.png +0 -0
  243. matplotlib_rs/mpl-data/sample_data/README.txt +2 -0
  244. matplotlib_rs/mpl-data/sample_data/Stocks.csv +526 -0
  245. matplotlib_rs/mpl-data/sample_data/axes_grid/bivariate_normal.npy +0 -0
  246. matplotlib_rs/mpl-data/sample_data/data_x_x2_x3.csv +11 -0
  247. matplotlib_rs/mpl-data/sample_data/eeg.dat +0 -0
  248. matplotlib_rs/mpl-data/sample_data/embedding_in_wx3.xrc +65 -0
  249. matplotlib_rs/mpl-data/sample_data/goog.npz +0 -0
  250. matplotlib_rs/mpl-data/sample_data/grace_hopper.jpg +0 -0
  251. matplotlib_rs/mpl-data/sample_data/jacksboro_fault_dem.npz +0 -0
  252. matplotlib_rs/mpl-data/sample_data/logo2.png +0 -0
  253. matplotlib_rs/mpl-data/sample_data/membrane.dat +0 -0
  254. matplotlib_rs/mpl-data/sample_data/msft.csv +66 -0
  255. matplotlib_rs/mpl-data/sample_data/s1045.ima.gz +0 -0
  256. matplotlib_rs/mpl-data/sample_data/topobathy.npz +0 -0
  257. matplotlib_rs/mpl-data/stylelib/Solarize_Light2.mplstyle +53 -0
  258. matplotlib_rs/mpl-data/stylelib/_classic_test_patch.mplstyle +8 -0
  259. matplotlib_rs/mpl-data/stylelib/_mpl-gallery-nogrid.mplstyle +19 -0
  260. matplotlib_rs/mpl-data/stylelib/_mpl-gallery.mplstyle +19 -0
  261. matplotlib_rs/mpl-data/stylelib/bmh.mplstyle +27 -0
  262. matplotlib_rs/mpl-data/stylelib/classic.mplstyle +491 -0
  263. matplotlib_rs/mpl-data/stylelib/dark_background.mplstyle +26 -0
  264. matplotlib_rs/mpl-data/stylelib/fast.mplstyle +11 -0
  265. matplotlib_rs/mpl-data/stylelib/fivethirtyeight.mplstyle +37 -0
  266. matplotlib_rs/mpl-data/stylelib/ggplot.mplstyle +39 -0
  267. matplotlib_rs/mpl-data/stylelib/grayscale.mplstyle +29 -0
  268. matplotlib_rs/mpl-data/stylelib/petroff10.mplstyle +5 -0
  269. matplotlib_rs/mpl-data/stylelib/petroff6.mplstyle +5 -0
  270. matplotlib_rs/mpl-data/stylelib/petroff8.mplstyle +5 -0
  271. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-bright.mplstyle +3 -0
  272. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-colorblind.mplstyle +3 -0
  273. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-dark-palette.mplstyle +3 -0
  274. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-dark.mplstyle +30 -0
  275. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-darkgrid.mplstyle +30 -0
  276. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-deep.mplstyle +3 -0
  277. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-muted.mplstyle +3 -0
  278. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-notebook.mplstyle +21 -0
  279. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-paper.mplstyle +21 -0
  280. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-pastel.mplstyle +3 -0
  281. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-poster.mplstyle +21 -0
  282. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-talk.mplstyle +21 -0
  283. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-ticks.mplstyle +30 -0
  284. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-white.mplstyle +30 -0
  285. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-whitegrid.mplstyle +30 -0
  286. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8.mplstyle +57 -0
  287. matplotlib_rs/mpl-data/stylelib/tableau-colorblind10.mplstyle +3 -0
  288. matplotlib_rs/mpl_toolkits/__init__.py +3 -0
  289. matplotlib_rs/mpl_toolkits/axes_grid1/__init__.py +11 -0
  290. matplotlib_rs/mpl_toolkits/axes_grid1/anchored_artists.py +415 -0
  291. matplotlib_rs/mpl_toolkits/axes_grid1/axes_divider.py +619 -0
  292. matplotlib_rs/mpl_toolkits/axes_grid1/axes_grid.py +565 -0
  293. matplotlib_rs/mpl_toolkits/axes_grid1/axes_rgb.py +158 -0
  294. matplotlib_rs/mpl_toolkits/axes_grid1/axes_size.py +272 -0
  295. matplotlib_rs/mpl_toolkits/axes_grid1/inset_locator.py +525 -0
  296. matplotlib_rs/mpl_toolkits/axes_grid1/mpl_axes.py +129 -0
  297. matplotlib_rs/mpl_toolkits/axes_grid1/parasite_axes.py +261 -0
  298. matplotlib_rs/mpl_toolkits/axisartist/__init__.py +15 -0
  299. matplotlib_rs/mpl_toolkits/axisartist/angle_helper.py +396 -0
  300. matplotlib_rs/mpl_toolkits/axisartist/axes_divider.py +3 -0
  301. matplotlib_rs/mpl_toolkits/axisartist/axis_artist.py +1148 -0
  302. matplotlib_rs/mpl_toolkits/axisartist/axisline_style.py +193 -0
  303. matplotlib_rs/mpl_toolkits/axisartist/axislines.py +475 -0
  304. matplotlib_rs/mpl_toolkits/axisartist/floating_axes.py +265 -0
  305. matplotlib_rs/mpl_toolkits/axisartist/grid_finder.py +329 -0
  306. matplotlib_rs/mpl_toolkits/axisartist/grid_helper_curvelinear.py +353 -0
  307. matplotlib_rs/mpl_toolkits/axisartist/parasite_axes.py +8 -0
  308. matplotlib_rs/mpl_toolkits/mplot3d/__init__.py +4 -0
  309. matplotlib_rs/mpl_toolkits/mplot3d/art3d.py +1758 -0
  310. matplotlib_rs/mpl_toolkits/mplot3d/axes3d.py +4462 -0
  311. matplotlib_rs/mpl_toolkits/mplot3d/axis3d.py +807 -0
  312. matplotlib_rs/mpl_toolkits/mplot3d/proj3d.py +270 -0
  313. matplotlib_rs/offsetbox.py +1726 -0
  314. matplotlib_rs/patches.py +5049 -0
  315. matplotlib_rs/path.py +1147 -0
  316. matplotlib_rs/patheffects.py +512 -0
  317. matplotlib_rs/projections/__init__.py +126 -0
  318. matplotlib_rs/projections/geo.py +512 -0
  319. matplotlib_rs/projections/polar.py +1518 -0
  320. matplotlib_rs/pylab.py +68 -0
  321. matplotlib_rs/pyplot.py +4834 -0
  322. matplotlib_rs/quiver.py +1236 -0
  323. matplotlib_rs/rcsetup.py +3435 -0
  324. matplotlib_rs/sankey.py +815 -0
  325. matplotlib_rs/scale.py +1002 -0
  326. matplotlib_rs/spines.py +618 -0
  327. matplotlib_rs/stackplot.py +144 -0
  328. matplotlib_rs/streamplot.py +768 -0
  329. matplotlib_rs/style/__init__.py +269 -0
  330. matplotlib_rs/style/core.py +28 -0
  331. matplotlib_rs/table.py +860 -0
  332. matplotlib_rs/texmanager.py +375 -0
  333. matplotlib_rs/text.py +2412 -0
  334. matplotlib_rs/textpath.py +377 -0
  335. matplotlib_rs/ticker.py +3111 -0
  336. matplotlib_rs/transforms.py +3069 -0
  337. matplotlib_rs/tri/__init__.py +24 -0
  338. matplotlib_rs/tri/_triangulation.py +248 -0
  339. matplotlib_rs/tri/_tricontour.py +271 -0
  340. matplotlib_rs/tri/_trifinder.py +97 -0
  341. matplotlib_rs/tri/_triinterpolate.py +1575 -0
  342. matplotlib_rs/tri/_tripcolor.py +170 -0
  343. matplotlib_rs/tri/_triplot.py +87 -0
  344. matplotlib_rs/tri/_trirefine.py +308 -0
  345. matplotlib_rs/tri/_tritools.py +264 -0
  346. matplotlib_rs/typing.py +597 -0
  347. matplotlib_rs/units.py +196 -0
  348. matplotlib_rs/widgets.py +4455 -0
  349. matplotlib_rs-0.0.8.dist-info/METADATA +392 -0
  350. matplotlib_rs-0.0.8.dist-info/RECORD +352 -0
  351. matplotlib_rs-0.0.8.dist-info/WHEEL +4 -0
  352. matplotlib_rs-0.0.8.dist-info/sboms/matplotlib-rs.cyclonedx.json +4390 -0
@@ -0,0 +1,1491 @@
1
+ # Vendored from matplotlib 3.11 (see licenses/LICENSE_MATPLOTLIB), adapted for matplotlib_rs.
2
+ """
3
+ A PostScript backend, which can produce both PostScript .ps and .eps.
4
+ """
5
+
6
+ import bisect
7
+ import codecs
8
+ import datetime
9
+ from enum import Enum
10
+ import functools
11
+ from io import StringIO
12
+ import itertools
13
+ import logging
14
+ import math
15
+ import os
16
+ import pathlib
17
+ import shutil
18
+ import struct
19
+ from tempfile import TemporaryDirectory
20
+ import textwrap
21
+ import time
22
+
23
+ import numpy as np
24
+
25
+ import matplotlib_rs as mpl
26
+ from matplotlib_rs import _api, cbook, _path, _text_helpers
27
+ from matplotlib_rs.backend_bases import (
28
+ _Backend, FigureCanvasBase, FigureManagerBase, RendererBase)
29
+ from matplotlib_rs.cbook import is_writable_file_like, file_requires_unicode
30
+ from matplotlib_rs.font_manager import get_font
31
+ from matplotlib_rs.ft2font import LoadFlags
32
+ from matplotlib_rs._mathtext_data import uni2type1
33
+ from matplotlib_rs.path import Path
34
+ from matplotlib_rs.texmanager import TexManager
35
+ from matplotlib_rs.transforms import Affine2D
36
+ from matplotlib_rs.backends.backend_mixed import MixedModeRenderer
37
+ from . import _backend_pdf_ps
38
+
39
+
40
+ _log = logging.getLogger(__name__)
41
+ debugPS = False
42
+
43
+
44
+ papersize = {'letter': (8.5, 11),
45
+ 'legal': (8.5, 14),
46
+ 'ledger': (11, 17),
47
+ 'a0': (33.11, 46.81),
48
+ 'a1': (23.39, 33.11),
49
+ 'a2': (16.54, 23.39),
50
+ 'a3': (11.69, 16.54),
51
+ 'a4': (8.27, 11.69),
52
+ 'a5': (5.83, 8.27),
53
+ 'a6': (4.13, 5.83),
54
+ 'a7': (2.91, 4.13),
55
+ 'a8': (2.05, 2.91),
56
+ 'a9': (1.46, 2.05),
57
+ 'a10': (1.02, 1.46),
58
+ 'b0': (40.55, 57.32),
59
+ 'b1': (28.66, 40.55),
60
+ 'b2': (20.27, 28.66),
61
+ 'b3': (14.33, 20.27),
62
+ 'b4': (10.11, 14.33),
63
+ 'b5': (7.16, 10.11),
64
+ 'b6': (5.04, 7.16),
65
+ 'b7': (3.58, 5.04),
66
+ 'b8': (2.51, 3.58),
67
+ 'b9': (1.76, 2.51),
68
+ 'b10': (1.26, 1.76)}
69
+
70
+
71
+ def _nums_to_str(*args, sep=" "):
72
+ return sep.join(f"{arg:1.3f}".rstrip("0").rstrip(".") for arg in args)
73
+
74
+
75
+ def _move_path_to_path_or_stream(src, dst):
76
+ """
77
+ Move the contents of file at *src* to path-or-filelike *dst*.
78
+
79
+ If *dst* is a path, the metadata of *src* are *not* copied.
80
+ """
81
+ if is_writable_file_like(dst):
82
+ fh = (open(src, encoding='latin-1')
83
+ if file_requires_unicode(dst)
84
+ else open(src, 'rb'))
85
+ with fh:
86
+ shutil.copyfileobj(fh, dst)
87
+ else:
88
+ shutil.move(src, dst, copy_function=shutil.copyfile)
89
+
90
+
91
+ def _font_to_ps_type3(font_path, subset_index, glyph_indices):
92
+ """
93
+ Subset *glyphs_indices* from the font at *font_path* into a Type 3 font.
94
+
95
+ Parameters
96
+ ----------
97
+ font_path : FontPath
98
+ Path to the font to be subsetted.
99
+ subset_index : int
100
+ The subset of the above font being created.
101
+ glyph_indices : set[int]
102
+ The glyphs to include in the subsetted font.
103
+
104
+ Returns
105
+ -------
106
+ str
107
+ The string representation of a Type 3 font, which can be included
108
+ verbatim into a PostScript file.
109
+ """
110
+ font = get_font(font_path)
111
+
112
+ preamble = """\
113
+ %!PS-Adobe-3.0 Resource-Font
114
+ %%Creator: Converted from TrueType to Type 3 by Matplotlib.
115
+ 10 dict begin
116
+ /FontName /{font_name}-{subset} def
117
+ /PaintType 0 def
118
+ /FontMatrix [{inv_units_per_em} 0 0 {inv_units_per_em} 0 0] def
119
+ /FontBBox [{bbox}] def
120
+ /FontType 3 def
121
+ /Encoding [{encoding}] def
122
+ /CharStrings {num_glyphs} dict dup begin
123
+ /.notdef 0 def
124
+ """.format(font_name=font.postscript_name, subset=subset_index,
125
+ inv_units_per_em=1 / font.units_per_EM,
126
+ bbox=" ".join(map(str, font.bbox)),
127
+ encoding=" ".join(f"/{font.get_glyph_name(glyph_index)}"
128
+ for glyph_index in glyph_indices),
129
+ num_glyphs=len(glyph_indices) + 1)
130
+ postamble = """
131
+ end readonly def
132
+
133
+ /BuildGlyph {
134
+ exch begin
135
+ CharStrings exch
136
+ 2 copy known not {pop /.notdef} if
137
+ true 3 1 roll get exec
138
+ end
139
+ } _d
140
+
141
+ /BuildChar {
142
+ 1 index /Encoding get exch get
143
+ 1 index /BuildGlyph get exec
144
+ } _d
145
+
146
+ FontName currentdict end definefont pop
147
+ """
148
+
149
+ entries = []
150
+ for glyph_index in glyph_indices:
151
+ g = font.load_glyph(glyph_index, LoadFlags.NO_SCALE)
152
+ v, c = font.get_path()
153
+ entries.append(
154
+ "/%(name)s{%(bbox)s sc\n" % {
155
+ "name": font.get_glyph_name(glyph_index),
156
+ "bbox": " ".join(map(str, [g.horiAdvance, 0, *g.bbox])),
157
+ }
158
+ + _path.convert_to_string(
159
+ # Convert back to TrueType's internal units (1/64's).
160
+ # (Other dimensions are already in these units.)
161
+ Path(v * 64, c), None, None, False, None, 0,
162
+ # No code for quad Beziers triggers auto-conversion to cubics.
163
+ # Drop intermediate closepolys (relying on the outline
164
+ # decomposer always explicitly moving to the closing point
165
+ # first).
166
+ [b"m", b"l", b"", b"c", b""], True).decode("ascii")
167
+ + "ce} _d"
168
+ )
169
+
170
+ return preamble + "\n".join(entries) + postamble
171
+
172
+
173
+ def _font_to_ps_type42(font_path, subset_index, glyph_indices, fh):
174
+ """
175
+ Subset *glyph_indices* from the font at *font_path* into a Type 42 font at *fh*.
176
+
177
+ Parameters
178
+ ----------
179
+ font_path : FontPath
180
+ Path to the font to be subsetted.
181
+ subset_index : int
182
+ The subset of the above font being created.
183
+ glyph_indices : set[int]
184
+ The glyphs to include in the subsetted font.
185
+ fh : file-like
186
+ Where to write the font.
187
+ """
188
+ _log.debug("SUBSET %s:%d characters: %s", font_path, subset_index, glyph_indices)
189
+ import fontTools.ttLib
190
+ try:
191
+ with (fontTools.ttLib.TTFont(font_path.path,
192
+ fontNumber=font_path.face_index) as font,
193
+ _backend_pdf_ps.get_glyphs_subset(font_path, glyph_indices) as subset):
194
+ new_font = subset.font
195
+ fontdata = _backend_pdf_ps.font_as_file(new_font).getvalue()
196
+ _log.debug(
197
+ "SUBSET %s:%d %d -> %d", font_path, subset_index,
198
+ os.stat(font_path).st_size, len(fontdata)
199
+ )
200
+ fh.write(_serialize_type42(font, subset_index, new_font, fontdata))
201
+ except RuntimeError:
202
+ _log.warning(
203
+ "The PostScript backend does not currently support the selected font (%s).",
204
+ font_path)
205
+ raise
206
+
207
+
208
+ def _serialize_type42(font, subset_index, subset, fontdata):
209
+ """
210
+ Output a PostScript Type-42 format representation of font
211
+
212
+ Parameters
213
+ ----------
214
+ font : fontTools.ttLib.ttFont.TTFont
215
+ The original font object
216
+ subset_index : int
217
+ The subset of the above font to be created.
218
+ subset : fontTools.ttLib.ttFont.TTFont
219
+ The subset font object
220
+ fontdata : bytes
221
+ The raw font data in TTF format
222
+
223
+ Returns
224
+ -------
225
+ str
226
+ The Type-42 formatted font
227
+ """
228
+ version, breakpoints = _version_and_breakpoints(font.get('loca'), fontdata)
229
+ post = font['post']
230
+ name = font['name']
231
+ chars = _generate_charstrings(subset)
232
+ sfnts = _generate_sfnts(fontdata, subset, breakpoints)
233
+ return textwrap.dedent(f"""
234
+ %%!PS-TrueTypeFont-{version[0]}.{version[1]}-{font['head'].fontRevision:.7f}
235
+ 10 dict begin
236
+ /FontType 42 def
237
+ /FontMatrix [1 0 0 1 0 0] def
238
+ /FontName /{name.getDebugName(6)}-{subset_index} def
239
+ /FontInfo 7 dict dup begin
240
+ /FullName ({name.getDebugName(4)}) def
241
+ /FamilyName ({name.getDebugName(1)}) def
242
+ /Version ({name.getDebugName(5)}) def
243
+ /ItalicAngle {post.italicAngle} def
244
+ /isFixedPitch {'true' if post.isFixedPitch else 'false'} def
245
+ /UnderlinePosition {post.underlinePosition} def
246
+ /UnderlineThickness {post.underlineThickness} def
247
+ end readonly def
248
+ /Encoding StandardEncoding def
249
+ /FontBBox [{_nums_to_str(*_bounds(font))}] def
250
+ /PaintType 0 def
251
+ /CIDMap 0 def
252
+ {chars}
253
+ {sfnts}
254
+ FontName currentdict end definefont pop
255
+ """)
256
+
257
+
258
+ def _version_and_breakpoints(loca, fontdata):
259
+ """
260
+ Read the version number of the font and determine sfnts breakpoints.
261
+
262
+ When a TrueType font file is written as a Type 42 font, it has to be
263
+ broken into substrings of at most 65535 bytes. These substrings must
264
+ begin at font table boundaries or glyph boundaries in the glyf table.
265
+ This function determines all possible breakpoints and it is the caller's
266
+ responsibility to do the splitting.
267
+
268
+ Helper function for _font_to_ps_type42.
269
+
270
+ Parameters
271
+ ----------
272
+ loca : fontTools.ttLib._l_o_c_a.table__l_o_c_a or None
273
+ The loca table of the font if available
274
+ fontdata : bytes
275
+ The raw data of the font
276
+
277
+ Returns
278
+ -------
279
+ version : tuple[int, int]
280
+ A 2-tuple of the major version number and minor version number.
281
+ breakpoints : list[int]
282
+ The breakpoints is a sorted list of offsets into fontdata; if loca is not
283
+ available, just the table boundaries.
284
+ """
285
+ v1, v2, numTables = struct.unpack('>3h', fontdata[:6])
286
+ version = (v1, v2)
287
+
288
+ tables = {}
289
+ for i in range(numTables):
290
+ tag, _, offset, _ = struct.unpack('>4sIII', fontdata[12 + i*16:12 + (i+1)*16])
291
+ tables[tag.decode('ascii')] = offset
292
+ if loca is not None:
293
+ glyf_breakpoints = {tables['glyf'] + offset for offset in loca.locations[:-1]}
294
+ else:
295
+ glyf_breakpoints = set()
296
+ breakpoints = sorted({*tables.values(), *glyf_breakpoints, len(fontdata)})
297
+
298
+ return version, breakpoints
299
+
300
+
301
+ def _bounds(font):
302
+ """
303
+ Compute the font bounding box, as if all glyphs were written
304
+ at the same start position.
305
+
306
+ Helper function for _font_to_ps_type42.
307
+
308
+ Parameters
309
+ ----------
310
+ font : fontTools.ttLib.ttFont.TTFont
311
+ The font
312
+
313
+ Returns
314
+ -------
315
+ tuple
316
+ (xMin, yMin, xMax, yMax) of the combined bounding box
317
+ of all the glyphs in the font
318
+ """
319
+ import fontTools.pens.boundsPen
320
+ gs = font.getGlyphSet(False)
321
+ pen = fontTools.pens.boundsPen.BoundsPen(gs)
322
+ for name in gs.keys():
323
+ gs[name].draw(pen)
324
+ return pen.bounds or (0, 0, 0, 0)
325
+
326
+
327
+ def _generate_charstrings(font):
328
+ """
329
+ Transform font glyphs into CharStrings
330
+
331
+ Helper function for _font_to_ps_type42.
332
+
333
+ Parameters
334
+ ----------
335
+ font : fontTools.ttLib.ttFont.TTFont
336
+ The font
337
+
338
+ Returns
339
+ -------
340
+ str
341
+ A definition of the CharStrings dictionary in PostScript
342
+ """
343
+ go = font.getGlyphOrder()
344
+ s = f'/CharStrings {len(go)} dict dup begin\n'
345
+ for i, name in enumerate(go):
346
+ s += f'/{name} {i} def\n'
347
+ s += 'end readonly def'
348
+ return s
349
+
350
+
351
+ def _generate_sfnts(fontdata, font, breakpoints):
352
+ """
353
+ Transform font data into PostScript sfnts format.
354
+
355
+ Helper function for _font_to_ps_type42.
356
+
357
+ Parameters
358
+ ----------
359
+ fontdata : bytes
360
+ The raw data of the font
361
+ font : fontTools.ttLib.ttFont.TTFont
362
+ The fontTools font object
363
+ breakpoints : list
364
+ Sorted offsets of possible breakpoints
365
+
366
+ Returns
367
+ -------
368
+ str
369
+ The sfnts array for the font definition, consisting
370
+ of hex-encoded strings in PostScript format
371
+ """
372
+ s = '/sfnts['
373
+ pos = 0
374
+ while pos < len(fontdata):
375
+ i = bisect.bisect_left(breakpoints, pos + 65534)
376
+ newpos = breakpoints[i-1]
377
+ if newpos <= pos:
378
+ # have to accept a larger string
379
+ newpos = breakpoints[-1]
380
+ s += f'<{fontdata[pos:newpos].hex()}00>' # Always NUL terminate.
381
+ pos = newpos
382
+ s += ']def'
383
+ return '\n'.join(s[i:i+100] for i in range(0, len(s), 100))
384
+
385
+
386
+ def _log_if_debug_on(meth):
387
+ """
388
+ Wrap `RendererPS` method *meth* to emit a PS comment with the method name,
389
+ if the global flag `debugPS` is set.
390
+ """
391
+ @functools.wraps(meth)
392
+ def wrapper(self, *args, **kwargs):
393
+ if debugPS:
394
+ self._pswriter.write(f"% {meth.__name__}\n")
395
+ return meth(self, *args, **kwargs)
396
+
397
+ return wrapper
398
+
399
+
400
+ class RendererPS(_backend_pdf_ps.RendererPDFPSBase):
401
+ """
402
+ The renderer handles all the drawing primitives using a graphics
403
+ context instance that controls the colors/styles.
404
+ """
405
+
406
+ _afm_font_dir = cbook._get_data_path("fonts/afm")
407
+ _use_afm_rc_name = "ps.useafm"
408
+
409
+ def __init__(self, width, height, pswriter, imagedpi=72):
410
+ # Although postscript itself is dpi independent, we need to inform the
411
+ # image code about a requested dpi to generate high resolution images
412
+ # and then scale them before embedding them.
413
+ super().__init__(width, height)
414
+ self._pswriter = pswriter
415
+ if mpl.rcParams['text.usetex']:
416
+ self.textcnt = 0
417
+ self.psfrag = []
418
+ self.imagedpi = imagedpi
419
+
420
+ # current renderer state (None=uninitialised)
421
+ self.color = None
422
+ self.linewidth = None
423
+ self.linejoin = None
424
+ self.linecap = None
425
+ self.linedash = None
426
+ self.fontname = None
427
+ self.fontsize = None
428
+ self._hatches = {}
429
+ self.image_magnification = imagedpi / 72
430
+ self._clip_paths = {}
431
+ # Clip transforms may be temporary affine objects. Keep them alive
432
+ # while their ids are cache keys, so a later transform cannot reuse
433
+ # an address and silently select an unrelated clipping region.
434
+ self._clip_path_transforms = {}
435
+ self._path_collection_id = 0
436
+
437
+ self._character_tracker = _backend_pdf_ps.CharacterTracker(
438
+ _backend_pdf_ps._FONT_MAX_GLYPH.get(mpl.rcParams['ps.fonttype'], 0))
439
+ self._logwarn_once = functools.cache(_log.warning)
440
+
441
+ def _is_transparent(self, rgb_or_rgba):
442
+ if rgb_or_rgba is None:
443
+ return True # Consistent with rgbFace semantics.
444
+ elif len(rgb_or_rgba) == 4:
445
+ if rgb_or_rgba[3] == 0:
446
+ return True
447
+ if rgb_or_rgba[3] != 1:
448
+ self._logwarn_once(
449
+ "The PostScript backend does not support transparency; "
450
+ "partially transparent artists will be rendered opaque.")
451
+ return False
452
+ else: # len() == 3.
453
+ return False
454
+
455
+ def set_color(self, r, g, b, store=True):
456
+ if (r, g, b) != self.color:
457
+ self._pswriter.write(f"{_nums_to_str(r)} setgray\n"
458
+ if r == g == b else
459
+ f"{_nums_to_str(r, g, b)} setrgbcolor\n")
460
+ if store:
461
+ self.color = (r, g, b)
462
+
463
+ def set_linewidth(self, linewidth, store=True):
464
+ linewidth = float(linewidth)
465
+ if linewidth != self.linewidth:
466
+ self._pswriter.write(f"{_nums_to_str(linewidth)} setlinewidth\n")
467
+ if store:
468
+ self.linewidth = linewidth
469
+
470
+ @staticmethod
471
+ def _linejoin_cmd(linejoin):
472
+ # Support for directly passing integer values is for backcompat.
473
+ linejoin = {'miter': 0, 'round': 1, 'bevel': 2, 0: 0, 1: 1, 2: 2}[
474
+ linejoin]
475
+ return f"{linejoin:d} setlinejoin\n"
476
+
477
+ def set_linejoin(self, linejoin, store=True):
478
+ if linejoin != self.linejoin:
479
+ self._pswriter.write(self._linejoin_cmd(linejoin))
480
+ if store:
481
+ self.linejoin = linejoin
482
+
483
+ @staticmethod
484
+ def _linecap_cmd(linecap):
485
+ # Support for directly passing integer values is for backcompat.
486
+ linecap = {'butt': 0, 'round': 1, 'projecting': 2, 0: 0, 1: 1, 2: 2}[
487
+ linecap]
488
+ return f"{linecap:d} setlinecap\n"
489
+
490
+ def set_linecap(self, linecap, store=True):
491
+ if linecap != self.linecap:
492
+ self._pswriter.write(self._linecap_cmd(linecap))
493
+ if store:
494
+ self.linecap = linecap
495
+
496
+ def set_linedash(self, offset, seq, store=True):
497
+ if self.linedash is not None:
498
+ oldo, oldseq = self.linedash
499
+ if np.array_equal(seq, oldseq) and oldo == offset:
500
+ return
501
+
502
+ self._pswriter.write(f"[{_nums_to_str(*seq)}] {_nums_to_str(offset)} setdash\n"
503
+ if seq is not None and len(seq) else
504
+ "[] 0 setdash\n")
505
+ if store:
506
+ self.linedash = (offset, seq)
507
+
508
+ def set_font(self, fontname, fontsize, store=True):
509
+ if (fontname, fontsize) != (self.fontname, self.fontsize):
510
+ self._pswriter.write(f"/{fontname} {fontsize:1.3f} selectfont\n")
511
+ if store:
512
+ self.fontname = fontname
513
+ self.fontsize = fontsize
514
+
515
+ def create_hatch(self, hatch, linewidth):
516
+ sidelen = 72
517
+ if hatch in self._hatches:
518
+ return self._hatches[hatch]
519
+ name = 'H%d' % len(self._hatches)
520
+ pageheight = self.height * 72
521
+ self._pswriter.write(f"""\
522
+ << /PatternType 1
523
+ /PaintType 2
524
+ /TilingType 2
525
+ /BBox[0 0 {sidelen:d} {sidelen:d}]
526
+ /XStep {sidelen:d}
527
+ /YStep {sidelen:d}
528
+
529
+ /PaintProc {{
530
+ pop
531
+ {linewidth:g} setlinewidth
532
+ {self._convert_path(Path.hatch(hatch), Affine2D().scale(sidelen), simplify=False)}
533
+ gsave
534
+ fill
535
+ grestore
536
+ stroke
537
+ }} bind
538
+ >>
539
+ matrix
540
+ 0 {pageheight:g} translate
541
+ makepattern
542
+ /{name} exch def
543
+ """)
544
+ self._hatches[hatch] = name
545
+ return name
546
+
547
+ def get_image_magnification(self):
548
+ """
549
+ Get the factor by which to magnify images passed to draw_image.
550
+ Allows a backend to have images at a different resolution to other
551
+ artists.
552
+ """
553
+ return self.image_magnification
554
+
555
+ def _convert_path(self, path, transform, clip=False, simplify=None):
556
+ if clip:
557
+ clip = (0.0, 0.0, self.width * 72.0, self.height * 72.0)
558
+ else:
559
+ clip = None
560
+ return _path.convert_to_string(
561
+ path, transform, clip, simplify, None,
562
+ 6, [b"m", b"l", b"", b"c", b"cl"], True).decode("ascii")
563
+
564
+ def _get_clip_cmd(self, gc):
565
+ clip = []
566
+ rect = gc.get_clip_rectangle()
567
+ if rect is not None:
568
+ clip.append(f"{_nums_to_str(*rect.p0, *rect.size)} rectclip\n")
569
+ path, trf = gc.get_clip_path()
570
+ if path is not None:
571
+ key = (path, id(trf))
572
+ custom_clip_cmd = self._clip_paths.get(key)
573
+ if custom_clip_cmd is None:
574
+ custom_clip_cmd = "c%d" % len(self._clip_paths)
575
+ self._pswriter.write(f"""\
576
+ /{custom_clip_cmd} {{
577
+ {self._convert_path(path, trf, simplify=False)}
578
+ clip
579
+ newpath
580
+ }} bind def
581
+ """)
582
+ self._clip_paths[key] = custom_clip_cmd
583
+ self._clip_path_transforms[key] = trf
584
+ clip.append(f"{custom_clip_cmd}\n")
585
+ return "".join(clip)
586
+
587
+ @_log_if_debug_on
588
+ def draw_image(self, gc, x, y, im, transform=None):
589
+ # docstring inherited
590
+
591
+ h, w = im.shape[:2]
592
+ imagecmd = "false 3 colorimage"
593
+ data = im[::-1, :, :3] # Vertically flipped rgb values.
594
+ hexdata = data.tobytes().hex("\n", -64) # Linewrap to 128 chars.
595
+
596
+ if transform is None:
597
+ matrix = "1 0 0 1 0 0"
598
+ xscale = w / self.image_magnification
599
+ yscale = h / self.image_magnification
600
+ else:
601
+ matrix = " ".join(map(str, transform.frozen().to_values()))
602
+ xscale = 1.0
603
+ yscale = 1.0
604
+
605
+ self._pswriter.write(f"""\
606
+ gsave
607
+ {self._get_clip_cmd(gc)}
608
+ {x:g} {y:g} translate
609
+ [{matrix}] concat
610
+ {xscale:g} {yscale:g} scale
611
+ /DataString {w:d} string def
612
+ {w:d} {h:d} 8 [ {w:d} 0 0 -{h:d} 0 {h:d} ]
613
+ {{
614
+ currentfile DataString readhexstring pop
615
+ }} bind {imagecmd}
616
+ {hexdata}
617
+ grestore
618
+ """)
619
+
620
+ @_log_if_debug_on
621
+ def draw_path(self, gc, path, transform, rgbFace=None):
622
+ # docstring inherited
623
+ clip = rgbFace is None and gc.get_hatch_path() is None
624
+ simplify = path.should_simplify and clip
625
+ ps = self._convert_path(path, transform, clip=clip, simplify=simplify)
626
+ self._draw_ps(ps, gc, rgbFace)
627
+
628
+ @_log_if_debug_on
629
+ def draw_markers(
630
+ self, gc, marker_path, marker_trans, path, trans, rgbFace=None):
631
+ # docstring inherited
632
+
633
+ ps_color = (
634
+ None
635
+ if self._is_transparent(rgbFace)
636
+ else f'{_nums_to_str(rgbFace[0])} setgray'
637
+ if rgbFace[0] == rgbFace[1] == rgbFace[2]
638
+ else f'{_nums_to_str(*rgbFace[:3])} setrgbcolor')
639
+
640
+ # construct the generic marker command:
641
+
642
+ # don't want the translate to be global
643
+ ps_cmd = ['/o {', 'gsave', 'newpath', 'translate']
644
+
645
+ lw = gc.get_linewidth()
646
+ alpha = (gc.get_alpha()
647
+ if gc.get_forced_alpha() or len(gc.get_rgb()) == 3
648
+ else gc.get_rgb()[3])
649
+ stroke = lw > 0 and alpha > 0
650
+ if stroke:
651
+ ps_cmd.append('%.1f setlinewidth' % lw)
652
+ ps_cmd.append(self._linejoin_cmd(gc.get_joinstyle()))
653
+ ps_cmd.append(self._linecap_cmd(gc.get_capstyle()))
654
+
655
+ ps_cmd.append(self._convert_path(marker_path, marker_trans,
656
+ simplify=False))
657
+
658
+ if rgbFace:
659
+ if stroke:
660
+ ps_cmd.append('gsave')
661
+ if ps_color:
662
+ ps_cmd.extend([ps_color, 'fill'])
663
+ if stroke:
664
+ ps_cmd.append('grestore')
665
+
666
+ if stroke:
667
+ ps_cmd.append('stroke')
668
+ ps_cmd.extend(['grestore', '} bind def'])
669
+
670
+ for vertices, code in path.iter_segments(
671
+ trans,
672
+ clip=(0, 0, self.width*72, self.height*72),
673
+ simplify=False):
674
+ if len(vertices):
675
+ x, y = vertices[-2:]
676
+ ps_cmd.append(f"{x:g} {y:g} o")
677
+
678
+ ps = '\n'.join(ps_cmd)
679
+ self._draw_ps(ps, gc, rgbFace, fill=False, stroke=False)
680
+
681
+ @_log_if_debug_on
682
+ def draw_path_collection(self, gc, master_transform, paths, all_transforms,
683
+ offsets, offset_trans, facecolors, edgecolors,
684
+ linewidths, linestyles, antialiaseds, urls,
685
+ offset_position, *, hatchcolors=None):
686
+ if hatchcolors is None:
687
+ hatchcolors = []
688
+ # Is the optimization worth it? Rough calculation:
689
+ # cost of emitting a path in-line is
690
+ # (len_path + 2) * uses_per_path
691
+ # cost of definition+use is
692
+ # (len_path + 3) + 3 * uses_per_path
693
+ len_path = len(paths[0].vertices) if len(paths) > 0 else 0
694
+ uses_per_path = self._iter_collection_uses_per_path(
695
+ paths, all_transforms, offsets, facecolors, edgecolors)
696
+ should_do_optimization = \
697
+ len_path + 3 * uses_per_path + 3 < (len_path + 2) * uses_per_path
698
+ if not should_do_optimization:
699
+ return RendererBase.draw_path_collection(
700
+ self, gc, master_transform, paths, all_transforms,
701
+ offsets, offset_trans, facecolors, edgecolors,
702
+ linewidths, linestyles, antialiaseds, urls,
703
+ offset_position, hatchcolors=hatchcolors)
704
+
705
+ path_codes = []
706
+ for i, (path, transform) in enumerate(self._iter_collection_raw_paths(
707
+ master_transform, paths, all_transforms)):
708
+ name = 'p%d_%d' % (self._path_collection_id, i)
709
+ path_bytes = self._convert_path(path, transform, simplify=False)
710
+ self._pswriter.write(f"""\
711
+ /{name} {{
712
+ newpath
713
+ translate
714
+ {path_bytes}
715
+ }} bind def
716
+ """)
717
+ path_codes.append(name)
718
+
719
+ for xo, yo, path_id, gc0, rgbFace in self._iter_collection(
720
+ gc, path_codes, offsets, offset_trans,
721
+ facecolors, edgecolors, linewidths, linestyles,
722
+ antialiaseds, urls, offset_position, hatchcolors=hatchcolors):
723
+ ps = f"{xo:g} {yo:g} {path_id}"
724
+ self._draw_ps(ps, gc0, rgbFace)
725
+
726
+ self._path_collection_id += 1
727
+
728
+ @_log_if_debug_on
729
+ def draw_tex(self, gc, x, y, s, prop, angle, *, mtext=None):
730
+ # docstring inherited
731
+ if self._is_transparent(gc.get_rgb()):
732
+ return # Special handling for fully transparent.
733
+
734
+ if not hasattr(self, "psfrag"):
735
+ self._logwarn_once(
736
+ "The PS backend determines usetex status solely based on "
737
+ "rcParams['text.usetex'] and does not support having "
738
+ "usetex=True only for some elements; this element will thus "
739
+ "be rendered as if usetex=False.")
740
+ self.draw_text(gc, x, y, s, prop, angle, False, mtext)
741
+ return
742
+
743
+ w, h, bl = self.get_text_width_height_descent(s, prop, ismath="TeX")
744
+ fontsize = prop.get_size_in_points()
745
+ thetext = 'psmarker%d' % self.textcnt
746
+ color = _nums_to_str(*gc.get_rgb()[:3], sep=',')
747
+ fontcmd = {'sans-serif': r'{\sffamily %s}',
748
+ 'monospace': r'{\ttfamily %s}'}.get(
749
+ mpl.rcParams['font.family'][0], r'{\rmfamily %s}')
750
+ s = fontcmd % s
751
+ tex = r'\color[rgb]{%s} %s' % (color, s)
752
+
753
+ # Stick to bottom-left alignment, so subtract descent from the text-normal
754
+ # direction since text is normally positioned by its baseline.
755
+ rangle = np.radians(angle + 90)
756
+ pos = _nums_to_str(x - bl * np.cos(rangle), y - bl * np.sin(rangle))
757
+ self.psfrag.append(
758
+ r'\psfrag{%s}[bl][bl][1][%f]{\fontsize{%f}{%f}%s}' % (
759
+ thetext, angle, fontsize, fontsize*1.25, tex))
760
+
761
+ self._pswriter.write(f"""\
762
+ gsave
763
+ {pos} moveto
764
+ ({thetext})
765
+ show
766
+ grestore
767
+ """)
768
+ self.textcnt += 1
769
+
770
+ @_log_if_debug_on
771
+ def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
772
+ # docstring inherited
773
+
774
+ if self._is_transparent(gc.get_rgb()):
775
+ return # Special handling for fully transparent.
776
+
777
+ if ismath == 'TeX':
778
+ return self.draw_tex(gc, x, y, s, prop, angle)
779
+
780
+ if ismath:
781
+ return self.draw_mathtext(gc, x, y, s, prop, angle)
782
+
783
+ stream = [] # list of (ps_name, x, y, char_name)
784
+
785
+ if mpl.rcParams['ps.useafm']:
786
+ font = self._get_font_afm(prop)
787
+ ps_name = font.postscript_name.encode("ascii", "replace").decode("ascii")
788
+ scale = 0.001 * prop.get_size_in_points()
789
+ thisx = 0
790
+ last_name = '' # kerns returns 0 for ''.
791
+ for c in s:
792
+ name = uni2type1.get(ord(c), f"uni{ord(c):04X}")
793
+ try:
794
+ width = font.get_width_from_char_name(name)
795
+ except KeyError:
796
+ name = 'question'
797
+ width = font.get_width_char(ord('?'))
798
+ kern = font.get_kern_dist_from_name(last_name, name)
799
+ last_name = name
800
+ thisx += kern * scale
801
+ stream.append((ps_name, thisx, 0, name))
802
+ thisx += width * scale
803
+
804
+ else:
805
+ if mtext is not None:
806
+ features = mtext.get_fontfeatures()
807
+ language = mtext.get_language()
808
+ else:
809
+ features = language = None
810
+ font = self._get_font_ttf(prop)
811
+ for item in _text_helpers.layout(s, font, features=features,
812
+ language=language):
813
+ # NOTE: We ignore the character code in the subset, because PS uses the
814
+ # glyph name to write text. The subset is only used to ensure that each
815
+ # one does not overflow format limits.
816
+ subset, _ = self._character_tracker.track_glyph(
817
+ item.ft_object, item.char, item.glyph_index)
818
+ ps_name = (item.ft_object.postscript_name
819
+ .encode("ascii", "replace").decode("ascii"))
820
+ glyph_name = item.ft_object.get_glyph_name(item.glyph_index)
821
+ stream.append((f'{ps_name}-{subset}', item.x, item.y, glyph_name))
822
+ self.set_color(*gc.get_rgb())
823
+
824
+ for ps_name, group in itertools.groupby(stream, lambda entry: entry[0]):
825
+ self.set_font(ps_name, prop.get_size_in_points(), False)
826
+ thetext = "\n".join(f"{x:g} {y:g} m /{name:s} glyphshow"
827
+ for _, x, y, name in group)
828
+ self._pswriter.write(f"""\
829
+ gsave
830
+ {self._get_clip_cmd(gc)}
831
+ {x:g} {y:g} translate
832
+ {angle:g} rotate
833
+ {thetext}
834
+ grestore
835
+ """)
836
+
837
+ @_log_if_debug_on
838
+ def draw_mathtext(self, gc, x, y, s, prop, angle):
839
+ """Draw the math text using matplotlib.mathtext."""
840
+ width, height, descent, glyphs, rects = \
841
+ self._text2path.mathtext_parser.parse(s, 72, prop)
842
+ self.set_color(*gc.get_rgb())
843
+ self._pswriter.write(
844
+ f"gsave\n"
845
+ f"{x:g} {y:g} translate\n"
846
+ f"{angle:g} rotate\n")
847
+ lastfont = None
848
+ for font, fontsize, ccode, glyph_index, ox, oy in glyphs:
849
+ # NOTE: We ignore the character code in the subset, because PS uses the
850
+ # glyph name to write text. The subset is only used to ensure that each one
851
+ # does not overflow format limits.
852
+ subset, _ = self._character_tracker.track_glyph(
853
+ font, ccode, glyph_index)
854
+ if (font.postscript_name, subset, fontsize) != lastfont:
855
+ lastfont = font.postscript_name, subset, fontsize
856
+ self._pswriter.write(
857
+ f"/{font.postscript_name}-{subset} {fontsize} selectfont\n")
858
+ glyph_name = font.get_glyph_name(glyph_index)
859
+ self._pswriter.write(
860
+ f"{ox:g} {oy:g} moveto\n"
861
+ f"/{glyph_name} glyphshow\n")
862
+ for ox, oy, w, h in rects:
863
+ self._pswriter.write(f"{ox} {oy} {w} {h} rectfill\n")
864
+ self._pswriter.write("grestore\n")
865
+
866
+ @_log_if_debug_on
867
+ def draw_gouraud_triangles(self, gc, points, colors, trans):
868
+ assert len(points) == len(colors)
869
+ if len(points) == 0:
870
+ return
871
+ assert points.ndim == 3
872
+ assert points.shape[1] == 3
873
+ assert points.shape[2] == 2
874
+ assert colors.ndim == 3
875
+ assert colors.shape[1] == 3
876
+ assert colors.shape[2] == 4
877
+
878
+ shape = points.shape
879
+ flat_points = points.reshape((shape[0] * shape[1], 2))
880
+ flat_points = trans.transform(flat_points)
881
+ flat_colors = colors.reshape((shape[0] * shape[1], 4))
882
+ points_min = np.min(flat_points, axis=0) - (1 << 12)
883
+ points_max = np.max(flat_points, axis=0) + (1 << 12)
884
+ factor = np.ceil((2 ** 32 - 1) / (points_max - points_min))
885
+
886
+ xmin, ymin = points_min
887
+ xmax, ymax = points_max
888
+
889
+ data = np.empty(
890
+ shape[0] * shape[1],
891
+ dtype=[('flags', 'u1'), ('points', '2>u4'), ('colors', '3u1')])
892
+ data['flags'] = 0
893
+ data['points'] = (flat_points - points_min) * factor
894
+ data['colors'] = flat_colors[:, :3] * 255.0
895
+ hexdata = data.tobytes().hex("\n", -64) # Linewrap to 128 chars.
896
+
897
+ self._pswriter.write(f"""\
898
+ gsave
899
+ << /ShadingType 4
900
+ /ColorSpace [/DeviceRGB]
901
+ /BitsPerCoordinate 32
902
+ /BitsPerComponent 8
903
+ /BitsPerFlag 8
904
+ /AntiAlias true
905
+ /Decode [ {xmin:g} {xmax:g} {ymin:g} {ymax:g} 0 1 0 1 0 1 ]
906
+ /DataSource <
907
+ {hexdata}
908
+ >
909
+ >>
910
+ shfill
911
+ grestore
912
+ """)
913
+
914
+ def _draw_ps(self, ps, gc, rgbFace, *, fill=True, stroke=True):
915
+ """
916
+ Emit the PostScript snippet *ps* with all the attributes from *gc*
917
+ applied. *ps* must consist of PostScript commands to construct a path.
918
+
919
+ The *fill* and/or *stroke* kwargs can be set to False if the *ps*
920
+ string already includes filling and/or stroking, in which case
921
+ `_draw_ps` is just supplying properties and clipping.
922
+ """
923
+ write = self._pswriter.write
924
+ mightstroke = (gc.get_linewidth() > 0
925
+ and not self._is_transparent(gc.get_rgb()))
926
+ if not mightstroke:
927
+ stroke = False
928
+ if self._is_transparent(rgbFace):
929
+ fill = False
930
+ hatch = gc.get_hatch()
931
+
932
+ if mightstroke:
933
+ self.set_linewidth(gc.get_linewidth())
934
+ self.set_linejoin(gc.get_joinstyle())
935
+ self.set_linecap(gc.get_capstyle())
936
+ self.set_linedash(*gc.get_dashes())
937
+ if mightstroke or hatch:
938
+ self.set_color(*gc.get_rgb()[:3])
939
+ write('gsave\n')
940
+
941
+ write(self._get_clip_cmd(gc))
942
+
943
+ write(ps.strip())
944
+ write("\n")
945
+
946
+ if fill:
947
+ if stroke or hatch:
948
+ write("gsave\n")
949
+ self.set_color(*rgbFace[:3], store=False)
950
+ write("fill\n")
951
+ if stroke or hatch:
952
+ write("grestore\n")
953
+
954
+ if hatch:
955
+ hatch_name = self.create_hatch(hatch, gc.get_hatch_linewidth())
956
+ write("gsave\n")
957
+ write(_nums_to_str(*gc.get_hatch_color()[:3]))
958
+ write(f" {hatch_name} setpattern fill grestore\n")
959
+
960
+ if stroke:
961
+ write("stroke\n")
962
+
963
+ write("grestore\n")
964
+
965
+
966
+ class _Orientation(Enum):
967
+ portrait, landscape = range(2)
968
+
969
+ def swap_if_landscape(self, shape):
970
+ return shape[::-1] if self.name == "landscape" else shape
971
+
972
+
973
+ class FigureCanvasPS(FigureCanvasBase):
974
+ fixed_dpi = 72
975
+ filetypes = {'ps': 'Postscript',
976
+ 'eps': 'Encapsulated Postscript'}
977
+
978
+ def get_default_filetype(self):
979
+ return 'ps'
980
+
981
+ def _print_ps(
982
+ self, fmt, outfile, *,
983
+ metadata=None, papertype=None, orientation='portrait',
984
+ bbox_inches_restore=None, **kwargs):
985
+
986
+ dpi = self.figure.dpi
987
+ self.figure.dpi = 72 # Override the dpi kwarg
988
+
989
+ dsc_comments = {}
990
+ if isinstance(outfile, (str, os.PathLike)):
991
+ filename = pathlib.Path(outfile).name
992
+ dsc_comments["Title"] = \
993
+ filename.encode("ascii", "replace").decode("ascii")
994
+ dsc_comments["Creator"] = (metadata or {}).get(
995
+ "Creator",
996
+ f"Matplotlib v{mpl.__version__}, https://matplotlib.org/")
997
+ # See https://reproducible-builds.org/specs/source-date-epoch/
998
+ source_date_epoch = os.getenv("SOURCE_DATE_EPOCH")
999
+ dsc_comments["CreationDate"] = (
1000
+ datetime.datetime.fromtimestamp(
1001
+ int(source_date_epoch),
1002
+ datetime.timezone.utc).strftime("%a %b %d %H:%M:%S %Y")
1003
+ if source_date_epoch
1004
+ else time.ctime())
1005
+ dsc_comments = "\n".join(
1006
+ f"%%{k}: {v}" for k, v in dsc_comments.items())
1007
+
1008
+ if papertype is None:
1009
+ papertype = mpl.rcParams['ps.papersize']
1010
+ papertype = papertype.lower()
1011
+ _api.check_in_list(['figure', *papersize], papertype=papertype)
1012
+
1013
+ orientation = _api.getitem_checked(
1014
+ _Orientation, orientation=orientation.lower())
1015
+
1016
+ printer = (self._print_figure_tex
1017
+ if mpl.rcParams['text.usetex'] else
1018
+ self._print_figure)
1019
+ printer(fmt, outfile, dpi=dpi, dsc_comments=dsc_comments,
1020
+ orientation=orientation, papertype=papertype,
1021
+ bbox_inches_restore=bbox_inches_restore, **kwargs)
1022
+
1023
+ def _print_figure(
1024
+ self, fmt, outfile, *,
1025
+ dpi, dsc_comments, orientation, papertype,
1026
+ bbox_inches_restore=None):
1027
+ """
1028
+ Render the figure to a filesystem path or a file-like object.
1029
+
1030
+ Parameters are as for `.print_figure`, except that *dsc_comments* is a
1031
+ string containing Document Structuring Convention comments,
1032
+ generated from the *metadata* parameter to `.print_figure`.
1033
+ """
1034
+ is_eps = fmt == 'eps'
1035
+ if not (isinstance(outfile, (str, os.PathLike))
1036
+ or is_writable_file_like(outfile)):
1037
+ raise ValueError("outfile must be a path or a file-like object")
1038
+
1039
+ # find the appropriate papertype
1040
+ width, height = self.figure.get_size_inches()
1041
+ if is_eps or papertype == 'figure':
1042
+ paper_width, paper_height = width, height
1043
+ else:
1044
+ paper_width, paper_height = orientation.swap_if_landscape(
1045
+ papersize[papertype])
1046
+
1047
+ # center the figure on the paper
1048
+ xo = 72 * 0.5 * (paper_width - width)
1049
+ yo = 72 * 0.5 * (paper_height - height)
1050
+
1051
+ llx = xo
1052
+ lly = yo
1053
+ urx = llx + self.figure.bbox.width
1054
+ ury = lly + self.figure.bbox.height
1055
+ rotation = 0
1056
+ if orientation is _Orientation.landscape:
1057
+ llx, lly, urx, ury = lly, llx, ury, urx
1058
+ xo, yo = 72 * paper_height - yo, xo
1059
+ rotation = 90
1060
+ bbox = (llx, lly, urx, ury)
1061
+
1062
+ self._pswriter = StringIO()
1063
+
1064
+ # mixed mode rendering
1065
+ ps_renderer = RendererPS(width, height, self._pswriter, imagedpi=dpi)
1066
+ renderer = MixedModeRenderer(
1067
+ self.figure, width, height, dpi, ps_renderer,
1068
+ bbox_inches_restore=bbox_inches_restore)
1069
+
1070
+ self.figure.draw(renderer)
1071
+
1072
+ def print_figure_impl(fh):
1073
+ # write the PostScript headers
1074
+ if is_eps:
1075
+ print("%!PS-Adobe-3.0 EPSF-3.0", file=fh)
1076
+ else:
1077
+ print("%!PS-Adobe-3.0", file=fh)
1078
+ if papertype != 'figure':
1079
+ print(f"%%DocumentPaperSizes: {papertype}", file=fh)
1080
+ print("%%Pages: 1", file=fh)
1081
+ print(f"%%LanguageLevel: 3\n"
1082
+ f"{dsc_comments}\n"
1083
+ f"%%Orientation: {orientation.name}\n"
1084
+ f"{_get_bbox_header(bbox)}\n"
1085
+ f"%%EndComments\n",
1086
+ end="", file=fh)
1087
+
1088
+ Ndict = len(_psDefs)
1089
+ print("%%BeginProlog", file=fh)
1090
+ if not mpl.rcParams['ps.useafm']:
1091
+ Ndict += sum(map(len, ps_renderer._character_tracker.used.values()))
1092
+ print("/mpldict %d dict def" % Ndict, file=fh)
1093
+ print("mpldict begin", file=fh)
1094
+ print("\n".join(_psDefs), file=fh)
1095
+ if not mpl.rcParams['ps.useafm']:
1096
+ for font, subsets in ps_renderer._character_tracker.used.items():
1097
+ for subset, charmap in enumerate(subsets):
1098
+ if not charmap:
1099
+ continue
1100
+ fonttype = mpl.rcParams['ps.fonttype']
1101
+ fh.flush()
1102
+ if fonttype == 3:
1103
+ fh.write(_font_to_ps_type3(font, subset, charmap.values()))
1104
+ else: # Type 42 only.
1105
+ _font_to_ps_type42(font, subset, charmap.values(), fh)
1106
+ print("end", file=fh)
1107
+ print("%%EndProlog", file=fh)
1108
+
1109
+ if not is_eps:
1110
+ print("%%Page: 1 1", file=fh)
1111
+ print("mpldict begin", file=fh)
1112
+
1113
+ print("%s translate" % _nums_to_str(xo, yo), file=fh)
1114
+ if rotation:
1115
+ print("%d rotate" % rotation, file=fh)
1116
+ print(f"0 0 {_nums_to_str(width*72, height*72)} rectclip", file=fh)
1117
+
1118
+ # write the figure
1119
+ print(self._pswriter.getvalue(), file=fh)
1120
+
1121
+ # write the trailer
1122
+ print("end", file=fh)
1123
+ print("showpage", file=fh)
1124
+ if not is_eps:
1125
+ print("%%EOF", file=fh)
1126
+ fh.flush()
1127
+
1128
+ if mpl.rcParams['ps.usedistiller']:
1129
+ # We are going to use an external program to process the output.
1130
+ # Write to a temporary file.
1131
+ with TemporaryDirectory() as tmpdir:
1132
+ tmpfile = os.path.join(tmpdir, "tmp.ps")
1133
+ with open(tmpfile, 'w', encoding='latin-1') as fh:
1134
+ print_figure_impl(fh)
1135
+ if mpl.rcParams['ps.usedistiller'] == 'ghostscript':
1136
+ _try_distill(gs_distill,
1137
+ tmpfile, is_eps, ptype=papertype, bbox=bbox)
1138
+ elif mpl.rcParams['ps.usedistiller'] == 'xpdf':
1139
+ _try_distill(xpdf_distill,
1140
+ tmpfile, is_eps, ptype=papertype, bbox=bbox)
1141
+ _move_path_to_path_or_stream(tmpfile, outfile)
1142
+
1143
+ else: # Write directly to outfile.
1144
+ with cbook.open_file_cm(outfile, "w", encoding="latin-1") as file:
1145
+ if not file_requires_unicode(file):
1146
+ file = codecs.getwriter("latin-1")(file)
1147
+ print_figure_impl(file)
1148
+
1149
+ def _print_figure_tex(
1150
+ self, fmt, outfile, *,
1151
+ dpi, dsc_comments, orientation, papertype,
1152
+ bbox_inches_restore=None):
1153
+ """
1154
+ If :rc:`text.usetex` is True, a temporary pair of tex/eps files
1155
+ are created to allow tex to manage the text layout via the PSFrags
1156
+ package. These files are processed to yield the final ps or eps file.
1157
+
1158
+ The rest of the behavior is as for `._print_figure`.
1159
+ """
1160
+ is_eps = fmt == 'eps'
1161
+
1162
+ width, height = self.figure.get_size_inches()
1163
+ xo = 0
1164
+ yo = 0
1165
+
1166
+ llx = xo
1167
+ lly = yo
1168
+ urx = llx + self.figure.bbox.width
1169
+ ury = lly + self.figure.bbox.height
1170
+ bbox = (llx, lly, urx, ury)
1171
+
1172
+ self._pswriter = StringIO()
1173
+
1174
+ # mixed mode rendering
1175
+ ps_renderer = RendererPS(width, height, self._pswriter, imagedpi=dpi)
1176
+ renderer = MixedModeRenderer(self.figure,
1177
+ width, height, dpi, ps_renderer,
1178
+ bbox_inches_restore=bbox_inches_restore)
1179
+
1180
+ self.figure.draw(renderer)
1181
+
1182
+ # write to a temp file, we'll move it to outfile when done
1183
+ with TemporaryDirectory() as tmpdir:
1184
+ tmppath = pathlib.Path(tmpdir, "tmp.ps")
1185
+ tmppath.write_text(
1186
+ f"""\
1187
+ %!PS-Adobe-3.0 EPSF-3.0
1188
+ %%LanguageLevel: 3
1189
+ {dsc_comments}
1190
+ {_get_bbox_header(bbox)}
1191
+ %%EndComments
1192
+ %%BeginProlog
1193
+ /mpldict {len(_psDefs)} dict def
1194
+ mpldict begin
1195
+ {"".join(_psDefs)}
1196
+ end
1197
+ %%EndProlog
1198
+ mpldict begin
1199
+ {_nums_to_str(xo, yo)} translate
1200
+ 0 0 {_nums_to_str(width*72, height*72)} rectclip
1201
+ {self._pswriter.getvalue()}
1202
+ end
1203
+ showpage
1204
+ """,
1205
+ encoding="latin-1")
1206
+
1207
+ if orientation is _Orientation.landscape: # now, ready to rotate
1208
+ width, height = height, width
1209
+ bbox = (lly, llx, ury, urx)
1210
+
1211
+ # set the paper size to the figure size if is_eps. The
1212
+ # resulting ps file has the given size with correct bounding
1213
+ # box so that there is no need to call 'pstoeps'
1214
+ if is_eps or papertype == 'figure':
1215
+ paper_width, paper_height = orientation.swap_if_landscape(
1216
+ self.figure.get_size_inches())
1217
+ else:
1218
+ paper_width, paper_height = papersize[papertype]
1219
+
1220
+ psfrag_rotated = _convert_psfrags(
1221
+ tmppath, ps_renderer.psfrag, paper_width, paper_height,
1222
+ orientation.name)
1223
+
1224
+ if (mpl.rcParams['ps.usedistiller'] == 'ghostscript'
1225
+ or mpl.rcParams['text.usetex']):
1226
+ _try_distill(gs_distill,
1227
+ tmppath, is_eps, ptype=papertype, bbox=bbox,
1228
+ rotated=psfrag_rotated)
1229
+ elif mpl.rcParams['ps.usedistiller'] == 'xpdf':
1230
+ _try_distill(xpdf_distill,
1231
+ tmppath, is_eps, ptype=papertype, bbox=bbox,
1232
+ rotated=psfrag_rotated)
1233
+
1234
+ _move_path_to_path_or_stream(tmppath, outfile)
1235
+
1236
+ print_ps = functools.partialmethod(_print_ps, "ps")
1237
+ print_eps = functools.partialmethod(_print_ps, "eps")
1238
+
1239
+ def draw(self):
1240
+ self.figure.draw_without_rendering()
1241
+ return super().draw()
1242
+
1243
+
1244
+ def _convert_psfrags(tmppath, psfrags, paper_width, paper_height, orientation):
1245
+ """
1246
+ When we want to use the LaTeX backend with postscript, we write PSFrag tags
1247
+ to a temporary postscript file, each one marking a position for LaTeX to
1248
+ render some text. convert_psfrags generates a LaTeX document containing the
1249
+ commands to convert those tags to text. LaTeX/dvips produces the postscript
1250
+ file that includes the actual text.
1251
+ """
1252
+ with mpl.rc_context({
1253
+ "text.latex.preamble":
1254
+ mpl.rcParams["text.latex.preamble"] +
1255
+ mpl.texmanager._usepackage_if_not_loaded("color") +
1256
+ mpl.texmanager._usepackage_if_not_loaded("graphicx") +
1257
+ mpl.texmanager._usepackage_if_not_loaded("psfrag") +
1258
+ r"\geometry{papersize={%(width)sin,%(height)sin},margin=0in}"
1259
+ % {"width": paper_width, "height": paper_height}
1260
+ }):
1261
+ dvifile = TexManager().make_dvi(
1262
+ "\n"
1263
+ r"\begin{figure}""\n"
1264
+ r" \centering\leavevmode""\n"
1265
+ r" %(psfrags)s""\n"
1266
+ r" \includegraphics*[angle=%(angle)s]{%(epsfile)s}""\n"
1267
+ r"\end{figure}"
1268
+ % {
1269
+ "psfrags": "\n".join(psfrags),
1270
+ "angle": 90 if orientation == 'landscape' else 0,
1271
+ "epsfile": tmppath.resolve().as_posix(),
1272
+ },
1273
+ fontsize=10) # tex's default fontsize.
1274
+
1275
+ with TemporaryDirectory() as tmpdir:
1276
+ psfile = os.path.join(tmpdir, "tmp.ps")
1277
+ # -R1 is a security flag used to prevent shell command execution
1278
+ cbook._check_and_log_subprocess(
1279
+ ['dvips', '-q', '-R1', '-o', psfile, dvifile], _log)
1280
+ shutil.move(psfile, tmppath)
1281
+
1282
+ # check if the dvips created a ps in landscape paper. Somehow,
1283
+ # above latex+dvips results in a ps file in a landscape mode for a
1284
+ # certain figure sizes (e.g., 8.3in, 5.8in which is a5). And the
1285
+ # bounding box of the final output got messed up. We check see if
1286
+ # the generated ps file is in landscape and return this
1287
+ # information. The return value is used in pstoeps step to recover
1288
+ # the correct bounding box. 2010-06-05 JJL
1289
+ with open(tmppath) as fh:
1290
+ psfrag_rotated = "Landscape" in fh.read(1000)
1291
+ return psfrag_rotated
1292
+
1293
+
1294
+ def _try_distill(func, tmppath, *args, **kwargs):
1295
+ try:
1296
+ func(str(tmppath), *args, **kwargs)
1297
+ except mpl.ExecutableNotFoundError as exc:
1298
+ _log.warning("%s. Distillation step skipped.", exc)
1299
+
1300
+
1301
+ def gs_distill(tmpfile, eps=False, ptype='letter', bbox=None, rotated=False):
1302
+ """
1303
+ Use ghostscript's pswrite or epswrite device to distill a file.
1304
+ This yields smaller files without illegal encapsulated postscript
1305
+ operators. The output is low-level, converting text to outlines.
1306
+ """
1307
+
1308
+ if eps:
1309
+ paper_option = ["-dEPSCrop"]
1310
+ elif ptype == "figure":
1311
+ # The bbox will have its lower-left corner at (0, 0), so upper-right
1312
+ # corner corresponds with paper size.
1313
+ paper_option = [f"-dDEVICEWIDTHPOINTS={bbox[2]}",
1314
+ f"-dDEVICEHEIGHTPOINTS={bbox[3]}"]
1315
+ else:
1316
+ paper_option = [f"-sPAPERSIZE={ptype}"]
1317
+
1318
+ psfile = tmpfile + '.ps'
1319
+ dpi = mpl.rcParams['ps.distiller.res']
1320
+
1321
+ cbook._check_and_log_subprocess(
1322
+ [mpl._get_executable_info("gs").executable,
1323
+ "-dBATCH", "-dNOPAUSE", "-dSAFER", "-r%d" % dpi, "-sDEVICE=ps2write",
1324
+ *paper_option, f"-sOutputFile={psfile}", tmpfile],
1325
+ _log)
1326
+
1327
+ os.remove(tmpfile)
1328
+ shutil.move(psfile, tmpfile)
1329
+
1330
+ # While it is best if above steps preserve the original bounding
1331
+ # box, there seem to be cases when it is not. For those cases,
1332
+ # the original bbox can be restored during the pstoeps step.
1333
+
1334
+ if eps:
1335
+ # For some versions of gs, above steps result in a ps file where the
1336
+ # original bbox is no more correct. Do not adjust bbox for now.
1337
+ pstoeps(tmpfile, bbox, rotated=rotated)
1338
+
1339
+
1340
+ def xpdf_distill(tmpfile, eps=False, ptype='letter', bbox=None, rotated=False):
1341
+ """
1342
+ Use ghostscript's ps2pdf and xpdf's/poppler's pdftops to distill a file.
1343
+ This yields smaller files without illegal encapsulated postscript
1344
+ operators. This distiller is preferred, generating high-level postscript
1345
+ output that treats text as text.
1346
+ """
1347
+ mpl._get_executable_info("gs") # Effectively checks for ps2pdf.
1348
+ mpl._get_executable_info("pdftops")
1349
+
1350
+ if eps:
1351
+ paper_option = ["-dEPSCrop"]
1352
+ elif ptype == "figure":
1353
+ # The bbox will have its lower-left corner at (0, 0), so upper-right
1354
+ # corner corresponds with paper size.
1355
+ paper_option = [f"-dDEVICEWIDTHPOINTS#{bbox[2]}",
1356
+ f"-dDEVICEHEIGHTPOINTS#{bbox[3]}"]
1357
+ else:
1358
+ paper_option = [f"-sPAPERSIZE#{ptype}"]
1359
+
1360
+ with TemporaryDirectory() as tmpdir:
1361
+ tmppdf = pathlib.Path(tmpdir, "tmp.pdf")
1362
+ tmpps = pathlib.Path(tmpdir, "tmp.ps")
1363
+ # Pass options as `-foo#bar` instead of `-foo=bar` to keep Windows
1364
+ # happy (https://ghostscript.com/doc/9.56.1/Use.htm#MS_Windows).
1365
+ cbook._check_and_log_subprocess(
1366
+ ["ps2pdf",
1367
+ "-dSAFER",
1368
+ "-dAutoFilterColorImages#false",
1369
+ "-dAutoFilterGrayImages#false",
1370
+ "-sAutoRotatePages#None",
1371
+ "-sGrayImageFilter#FlateEncode",
1372
+ "-sColorImageFilter#FlateEncode",
1373
+ *paper_option,
1374
+ tmpfile, tmppdf], _log)
1375
+ cbook._check_and_log_subprocess(
1376
+ ["pdftops", "-paper", "match", "-level3", tmppdf, tmpps], _log)
1377
+ shutil.move(tmpps, tmpfile)
1378
+ if eps:
1379
+ pstoeps(tmpfile)
1380
+
1381
+
1382
+ def _get_bbox_header(lbrt):
1383
+ """Return a PostScript header string for bounding box *lbrt*=(l, b, r, t)."""
1384
+ l, b, r, t = lbrt
1385
+ return (f"%%BoundingBox: {int(l)} {int(b)} {math.ceil(r)} {math.ceil(t)}\n"
1386
+ f"%%HiResBoundingBox: {l:.6f} {b:.6f} {r:.6f} {t:.6f}")
1387
+
1388
+
1389
+ def _get_rotate_command(lbrt):
1390
+ """Return a PostScript 90° rotation command for bounding box *lbrt*=(l, b, r, t)."""
1391
+ l, b, r, t = lbrt
1392
+ return f"{l+r:.2f} {0:.2f} translate\n90 rotate"
1393
+
1394
+
1395
+ def pstoeps(tmpfile, bbox=None, rotated=False):
1396
+ """
1397
+ Convert the postscript to encapsulated postscript. The bbox of
1398
+ the eps file will be replaced with the given *bbox* argument. If
1399
+ None, original bbox will be used.
1400
+ """
1401
+
1402
+ epsfile = tmpfile + '.eps'
1403
+ with open(epsfile, 'wb') as epsh, open(tmpfile, 'rb') as tmph:
1404
+ write = epsh.write
1405
+ # Modify the header:
1406
+ for line in tmph:
1407
+ if line.startswith(b'%!PS'):
1408
+ write(b"%!PS-Adobe-3.0 EPSF-3.0\n")
1409
+ if bbox:
1410
+ write(_get_bbox_header(bbox).encode('ascii') + b'\n')
1411
+ elif line.startswith(b'%%EndComments'):
1412
+ write(line)
1413
+ write(b'%%BeginProlog\n'
1414
+ b'save\n'
1415
+ b'countdictstack\n'
1416
+ b'mark\n'
1417
+ b'newpath\n'
1418
+ b'/showpage {} def\n'
1419
+ b'/setpagedevice {pop} def\n'
1420
+ b'%%EndProlog\n'
1421
+ b'%%Page 1 1\n')
1422
+ if rotated: # The output eps file need to be rotated.
1423
+ write(_get_rotate_command(bbox).encode('ascii') + b'\n')
1424
+ break
1425
+ elif bbox and line.startswith((b'%%Bound', b'%%HiResBound',
1426
+ b'%%DocumentMedia', b'%%Pages')):
1427
+ pass
1428
+ else:
1429
+ write(line)
1430
+ # Now rewrite the rest of the file, and modify the trailer.
1431
+ # This is done in a second loop such that the header of the embedded
1432
+ # eps file is not modified.
1433
+ for line in tmph:
1434
+ if line.startswith(b'%%EOF'):
1435
+ write(b'cleartomark\n'
1436
+ b'countdictstack\n'
1437
+ b'exch sub { end } repeat\n'
1438
+ b'restore\n'
1439
+ b'showpage\n'
1440
+ b'%%EOF\n')
1441
+ elif line.startswith(b'%%PageBoundingBox'):
1442
+ pass
1443
+ else:
1444
+ write(line)
1445
+
1446
+ os.remove(tmpfile)
1447
+ shutil.move(epsfile, tmpfile)
1448
+
1449
+
1450
+ FigureManagerPS = FigureManagerBase
1451
+
1452
+
1453
+ # The following Python dictionary psDefs contains the entries for the
1454
+ # PostScript dictionary mpldict. This dictionary implements most of
1455
+ # the matplotlib primitives and some abbreviations.
1456
+ #
1457
+ # References:
1458
+ # https://www.adobe.com/content/dam/acom/en/devnet/actionscript/articles/PLRM.pdf
1459
+ # http://preserve.mactech.com/articles/mactech/Vol.09/09.04/PostscriptTutorial
1460
+ # http://www.math.ubc.ca/people/faculty/cass/graphics/text/www/
1461
+ #
1462
+
1463
+ # The usage comments use the notation of the operator summary
1464
+ # in the PostScript Language reference manual.
1465
+ _psDefs = [
1466
+ # name proc *_d* -
1467
+ # Note that this cannot be bound to /d, because when embedding a Type3 font
1468
+ # we may want to define a "d" glyph using "/d{...} d" which would locally
1469
+ # overwrite the definition.
1470
+ "/_d { bind def } bind def",
1471
+ # x y *m* -
1472
+ "/m { moveto } _d",
1473
+ # x y *l* -
1474
+ "/l { lineto } _d",
1475
+ # x y *r* -
1476
+ "/r { rlineto } _d",
1477
+ # x1 y1 x2 y2 x y *c* -
1478
+ "/c { curveto } _d",
1479
+ # *cl* -
1480
+ "/cl { closepath } _d",
1481
+ # *ce* -
1482
+ "/ce { closepath eofill } _d",
1483
+ # wx wy llx lly urx ury *setcachedevice* -
1484
+ "/sc { setcachedevice } _d",
1485
+ ]
1486
+
1487
+
1488
+ @_Backend.export
1489
+ class _BackendPS(_Backend):
1490
+ backend_version = 'Level II'
1491
+ FigureCanvas = FigureCanvasPS