matplotlib-rs 0.0.8__cp313-cp313-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.cp313-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,1843 @@
1
+ # Vendored from matplotlib 3.11 (see licenses/LICENSE_MATPLOTLIB), adapted for matplotlib_rs.
2
+ import abc
3
+ import base64
4
+ import collections
5
+ import contextlib
6
+ from io import BytesIO, TextIOWrapper
7
+ import itertools
8
+ import logging
9
+ from pathlib import Path
10
+ import shutil
11
+ import subprocess
12
+ import sys
13
+ from tempfile import TemporaryDirectory
14
+ import uuid
15
+ import warnings
16
+
17
+ import numpy as np
18
+
19
+ import matplotlib_rs as mpl
20
+ from matplotlib_rs._animation_data import (
21
+ DISPLAY_TEMPLATE, INCLUDED_FRAMES, JS_INCLUDE, STYLE_INCLUDE)
22
+ from matplotlib_rs import _api, cbook
23
+ import matplotlib_rs.colors as mcolors
24
+
25
+ _log = logging.getLogger(__name__)
26
+
27
+ # Process creation flag for subprocess to prevent it raising a terminal
28
+ # window. See for example https://stackoverflow.com/q/24130623/
29
+ subprocess_creation_flags = (
30
+ subprocess.CREATE_NO_WINDOW if sys.platform == 'win32' else 0)
31
+
32
+
33
+ def adjusted_figsize(w, h, dpi, n):
34
+ """
35
+ Compute figure size so that pixels are a multiple of n.
36
+
37
+ Parameters
38
+ ----------
39
+ w, h : float
40
+ Size in inches.
41
+
42
+ dpi : float
43
+ The dpi.
44
+
45
+ n : int
46
+ The target multiple.
47
+
48
+ Returns
49
+ -------
50
+ wnew, hnew : float
51
+ The new figure size in inches.
52
+ """
53
+
54
+ # this maybe simplified if / when we adopt consistent rounding for
55
+ # pixel size across the whole library
56
+ def correct_roundoff(x, dpi, n):
57
+ if int(x*dpi) % n != 0:
58
+ if int(np.nextafter(x, np.inf)*dpi) % n == 0:
59
+ x = np.nextafter(x, np.inf)
60
+ elif int(np.nextafter(x, -np.inf)*dpi) % n == 0:
61
+ x = np.nextafter(x, -np.inf)
62
+ return x
63
+
64
+ wnew = int(w * dpi / n) * n / dpi
65
+ hnew = int(h * dpi / n) * n / dpi
66
+ return correct_roundoff(wnew, dpi, n), correct_roundoff(hnew, dpi, n)
67
+
68
+
69
+ class MovieWriterRegistry:
70
+ """Registry of available writer classes by human readable name."""
71
+
72
+ def __init__(self):
73
+ self._registered = dict()
74
+
75
+ def register(self, name):
76
+ """
77
+ Decorator for registering a class under a name.
78
+
79
+ Example use::
80
+
81
+ @registry.register(name)
82
+ class Foo:
83
+ pass
84
+ """
85
+ def wrapper(writer_cls):
86
+ self._registered[name] = writer_cls
87
+ return writer_cls
88
+ return wrapper
89
+
90
+ def is_available(self, name):
91
+ """
92
+ Check if given writer is available by name.
93
+
94
+ Parameters
95
+ ----------
96
+ name : str
97
+
98
+ Returns
99
+ -------
100
+ bool
101
+ """
102
+ try:
103
+ cls = self._registered[name]
104
+ except KeyError:
105
+ return False
106
+ return cls.isAvailable()
107
+
108
+ def __iter__(self):
109
+ """Iterate over names of available writer class."""
110
+ for name in self._registered:
111
+ if self.is_available(name):
112
+ yield name
113
+
114
+ def list(self):
115
+ """Get a list of available MovieWriters."""
116
+ return [*self]
117
+
118
+ def __getitem__(self, name):
119
+ """Get an available writer class from its name."""
120
+ _api.check_in_list(self._registered, writer=name)
121
+ if self.is_available(name):
122
+ return self._registered[name]
123
+ raise RuntimeError(f"Requested MovieWriter ({name}) not available")
124
+
125
+
126
+ writers = MovieWriterRegistry()
127
+
128
+
129
+ class AbstractMovieWriter(abc.ABC):
130
+ """
131
+ Abstract base class for writing movies, providing a way to grab frames by
132
+ calling `~AbstractMovieWriter.grab_frame`.
133
+
134
+ `setup` is called to start the process and `finish` is called afterwards.
135
+ `saving` is provided as a context manager to facilitate this process as ::
136
+
137
+ with moviewriter.saving(fig, outfile='myfile.mp4', dpi=100):
138
+ # Iterate over frames
139
+ moviewriter.grab_frame(**savefig_kwargs)
140
+
141
+ The use of the context manager ensures that `setup` and `finish` are
142
+ performed as necessary.
143
+
144
+ An instance of a concrete subclass of this class can be given as the
145
+ ``writer`` argument of `Animation.save()`.
146
+ """
147
+
148
+ def __init__(self, fps=5, metadata=None, codec=None, bitrate=None):
149
+ self.fps = fps
150
+ self.metadata = metadata if metadata is not None else {}
151
+ self.codec = mpl._val_or_rc(codec, 'animation.codec')
152
+ self.bitrate = mpl._val_or_rc(bitrate, 'animation.bitrate')
153
+
154
+ @abc.abstractmethod
155
+ def setup(self, fig, outfile, dpi=None):
156
+ """
157
+ Setup for writing the movie file.
158
+
159
+ Parameters
160
+ ----------
161
+ fig : `~matplotlib.figure.Figure`
162
+ The figure object that contains the information for frames.
163
+ outfile : str
164
+ The filename of the resulting movie file.
165
+ dpi : float, default: ``fig.dpi``
166
+ The DPI (or resolution) for the file. This controls the size
167
+ in pixels of the resulting movie file.
168
+ """
169
+ # Check that path is valid
170
+ Path(outfile).parent.resolve(strict=True)
171
+ self.outfile = outfile
172
+ self.fig = fig
173
+ if dpi is None:
174
+ dpi = self.fig.dpi
175
+ self.dpi = dpi
176
+
177
+ @property
178
+ def frame_size(self):
179
+ """A tuple ``(width, height)`` in pixels of a movie frame."""
180
+ # We cannot query the canvas for width/height because the dpi may be different
181
+ # The tolerance of 1e-8 covers a floating-point tick for even 100,000 pixels
182
+ w, h = self.fig.get_size_inches()
183
+ return int(w * self.dpi + 1e-8), int(h * self.dpi + 1e-8)
184
+
185
+ def _supports_transparency(self):
186
+ """
187
+ Whether this writer supports transparency.
188
+
189
+ Writers may consult output file type and codec to determine this at runtime.
190
+ """
191
+ return False
192
+
193
+ @abc.abstractmethod
194
+ def grab_frame(self, **savefig_kwargs):
195
+ """
196
+ Grab the image information from the figure and save as a movie frame.
197
+
198
+ All keyword arguments in *savefig_kwargs* are passed on to the
199
+ `~.Figure.savefig` call that saves the figure. However, several
200
+ keyword arguments that are supported by `~.Figure.savefig` may not be
201
+ passed as they are controlled by the MovieWriter:
202
+
203
+ - *dpi*, *bbox_inches*: These may not be passed because each frame of the
204
+ animation much be exactly the same size in pixels.
205
+ - *format*: This is controlled by the MovieWriter.
206
+ """
207
+
208
+ @abc.abstractmethod
209
+ def finish(self):
210
+ """Finish any processing for writing the movie."""
211
+
212
+ @contextlib.contextmanager
213
+ def saving(self, fig, outfile, dpi, *args, **kwargs):
214
+ """
215
+ Context manager to facilitate writing the movie file.
216
+
217
+ ``*args, **kw`` are any parameters that should be passed to `setup`.
218
+ """
219
+ if mpl.rcParams['savefig.bbox'] == 'tight':
220
+ _log.info("Disabling savefig.bbox = 'tight', as it may cause "
221
+ "frame size to vary, which is inappropriate for "
222
+ "animation.")
223
+
224
+ # This particular sequence is what contextlib.contextmanager wants
225
+ self.setup(fig, outfile, dpi, *args, **kwargs)
226
+ with mpl.rc_context({'savefig.bbox': None}):
227
+ try:
228
+ yield self
229
+ finally:
230
+ self.finish()
231
+
232
+
233
+ class MovieWriter(AbstractMovieWriter):
234
+ """
235
+ Base class for writing movies.
236
+
237
+ This is a base class for MovieWriter subclasses that write a movie frame
238
+ data to a pipe. You cannot instantiate this class directly.
239
+ See examples for how to use its subclasses.
240
+
241
+ Attributes
242
+ ----------
243
+ frame_format : str
244
+ The format used in writing frame data, defaults to 'rgba'.
245
+ fig : `~matplotlib.figure.Figure`
246
+ The figure to capture data from.
247
+ This must be provided by the subclasses.
248
+ """
249
+
250
+ # Builtin writer subclasses additionally define the _exec_key and _args_key
251
+ # attributes, which indicate the rcParams entries where the path to the
252
+ # executable and additional command-line arguments to the executable are
253
+ # stored. Third-party writers cannot meaningfully set these as they cannot
254
+ # extend rcParams with new keys.
255
+
256
+ # Pipe-based writers only support RGBA, but file-based ones support more
257
+ # formats.
258
+ supported_formats = ["rgba"]
259
+
260
+ def __init__(self, fps=5, codec=None, bitrate=None, extra_args=None,
261
+ metadata=None):
262
+ """
263
+ Parameters
264
+ ----------
265
+ fps : int, default: 5
266
+ Movie frame rate (per second).
267
+ codec : str or None, default: :rc:`animation.codec`
268
+ The codec to use.
269
+ bitrate : int, default: :rc:`animation.bitrate`
270
+ The bitrate of the movie, in kilobits per second. Higher values
271
+ means higher quality movies, but increase the file size. A value
272
+ of -1 lets the underlying movie encoder select the bitrate.
273
+ extra_args : list of str or None, optional
274
+ Extra command-line arguments passed to the underlying movie encoder. These
275
+ arguments are passed last to the encoder, just before the filename. The
276
+ default, None, means to use :rc:`animation.[name-of-encoder]_args` for the
277
+ builtin writers.
278
+ metadata : dict[str, str], default: {}
279
+ A dictionary of keys and values for metadata to include in the
280
+ output file. Some keys that may be of use include:
281
+ title, artist, genre, subject, copyright, srcform, comment.
282
+ """
283
+ if type(self) is MovieWriter:
284
+ # TODO MovieWriter is still an abstract class and needs to be
285
+ # extended with a mixin. This should be clearer in naming
286
+ # and description. For now, just give a reasonable error
287
+ # message to users.
288
+ raise TypeError(
289
+ 'MovieWriter cannot be instantiated directly. Please use one '
290
+ 'of its subclasses.')
291
+
292
+ super().__init__(fps=fps, metadata=metadata, codec=codec,
293
+ bitrate=bitrate)
294
+ self.frame_format = self.supported_formats[0]
295
+ self.extra_args = extra_args
296
+
297
+ def _adjust_frame_size(self):
298
+ wo, ho = self.frame_size # in pixels, so need to convert to inches
299
+ wo /= self.dpi
300
+ ho /= self.dpi
301
+ if self.codec == 'h264':
302
+ w, h = adjusted_figsize(wo, ho, self.dpi, 2)
303
+ if (wo, ho) != (w, h):
304
+ self.fig.set_size_inches(w, h, forward=True)
305
+ _log.info('figure size in inches has been adjusted '
306
+ 'from %s x %s to %s x %s', wo, ho, w, h)
307
+ else:
308
+ w, h = wo, ho
309
+ _log.debug('frame size in pixels is %s x %s', *self.frame_size)
310
+ return w, h
311
+
312
+ def setup(self, fig, outfile, dpi=None):
313
+ # docstring inherited
314
+ super().setup(fig, outfile, dpi=dpi)
315
+ self._w, self._h = self._adjust_frame_size()
316
+ # Run here so that grab_frame() can write the data to a pipe. This
317
+ # eliminates the need for temp files.
318
+ self._run()
319
+
320
+ def _run(self):
321
+ # Uses subprocess to call the program for assembling frames into a
322
+ # movie file. *args* returns the sequence of command line arguments
323
+ # from a few configuration options.
324
+ command = self._args()
325
+ _log.info('MovieWriter._run: running command: %s',
326
+ cbook._pformat_subprocess(command))
327
+ PIPE = subprocess.PIPE
328
+ self._proc = subprocess.Popen(
329
+ command, stdin=PIPE, stdout=PIPE, stderr=PIPE,
330
+ creationflags=subprocess_creation_flags)
331
+
332
+ def finish(self):
333
+ """Finish any processing for writing the movie."""
334
+ out, err = self._proc.communicate()
335
+ # Use the encoding/errors that universal_newlines would use.
336
+ out = TextIOWrapper(BytesIO(out)).read()
337
+ err = TextIOWrapper(BytesIO(err)).read()
338
+ if out:
339
+ _log.log(
340
+ logging.WARNING if self._proc.returncode else logging.DEBUG,
341
+ "MovieWriter stdout:\n%s", out)
342
+ if err:
343
+ _log.log(
344
+ logging.WARNING if self._proc.returncode else logging.DEBUG,
345
+ "MovieWriter stderr:\n%s", err)
346
+ if self._proc.returncode:
347
+ raise subprocess.CalledProcessError(
348
+ self._proc.returncode, self._proc.args, out, err)
349
+
350
+ def grab_frame(self, **savefig_kwargs):
351
+ # docstring inherited
352
+ _validate_grabframe_kwargs(savefig_kwargs)
353
+ _log.debug('MovieWriter.grab_frame: Grabbing frame.')
354
+ # Readjust the figure size in case it has been changed by the user.
355
+ # All frames must have the same size to save the movie correctly.
356
+ self.fig.set_size_inches(self._w, self._h)
357
+ # Save the figure data to the sink, using the frame format and dpi.
358
+ self.fig.savefig(self._proc.stdin, format=self.frame_format,
359
+ dpi=self.dpi, **savefig_kwargs)
360
+
361
+ def _args(self):
362
+ """Assemble list of encoder-specific command-line arguments."""
363
+ return NotImplementedError("args needs to be implemented by subclass.")
364
+
365
+ @classmethod
366
+ def bin_path(cls):
367
+ """
368
+ Return the binary path to the commandline tool used by a specific
369
+ subclass. This is a class method so that the tool can be looked for
370
+ before making a particular MovieWriter subclass available.
371
+ """
372
+ return str(mpl.rcParams[cls._exec_key])
373
+
374
+ @classmethod
375
+ def isAvailable(cls):
376
+ """Return whether a MovieWriter subclass is actually available."""
377
+ if sys.platform == 'emscripten':
378
+ return False
379
+ return shutil.which(cls.bin_path()) is not None
380
+
381
+
382
+ class FileMovieWriter(MovieWriter):
383
+ """
384
+ `MovieWriter` for writing to individual files and stitching at the end.
385
+
386
+ This must be sub-classed to be useful.
387
+ """
388
+ def __init__(self, *args, **kwargs):
389
+ super().__init__(*args, **kwargs)
390
+ self.frame_format = mpl.rcParams['animation.frame_format']
391
+
392
+ def setup(self, fig, outfile, dpi=None, frame_prefix=None):
393
+ """
394
+ Setup for writing the movie file.
395
+
396
+ Parameters
397
+ ----------
398
+ fig : `~matplotlib.figure.Figure`
399
+ The figure to grab the rendered frames from.
400
+ outfile : str
401
+ The filename of the resulting movie file.
402
+ dpi : float, default: ``fig.dpi``
403
+ The dpi of the output file. This, with the figure size,
404
+ controls the size in pixels of the resulting movie file.
405
+ frame_prefix : str, optional
406
+ The filename prefix to use for temporary files. If *None* (the
407
+ default), files are written to a temporary directory which is
408
+ deleted by `finish`; if not *None*, no temporary files are
409
+ deleted.
410
+ """
411
+ # Check that path is valid
412
+ Path(outfile).parent.resolve(strict=True)
413
+ self.fig = fig
414
+ self.outfile = outfile
415
+ if dpi is None:
416
+ dpi = self.fig.dpi
417
+ self.dpi = dpi
418
+ self._adjust_frame_size()
419
+
420
+ if frame_prefix is None:
421
+ self._tmpdir = TemporaryDirectory()
422
+ self.temp_prefix = str(Path(self._tmpdir.name, 'tmp'))
423
+ else:
424
+ self._tmpdir = None
425
+ self.temp_prefix = frame_prefix
426
+ self._frame_counter = 0 # used for generating sequential file names
427
+ self._temp_paths = list()
428
+ self.fname_format_str = '%s%%07d.%s'
429
+
430
+ def __del__(self):
431
+ if hasattr(self, '_tmpdir') and self._tmpdir:
432
+ self._tmpdir.cleanup()
433
+
434
+ @property
435
+ def frame_format(self):
436
+ """
437
+ Format (png, jpeg, etc.) to use for saving the frames, which can be
438
+ decided by the individual subclasses.
439
+ """
440
+ return self._frame_format
441
+
442
+ @frame_format.setter
443
+ def frame_format(self, frame_format):
444
+ if frame_format in self.supported_formats:
445
+ self._frame_format = frame_format
446
+ else:
447
+ _api.warn_external(
448
+ f"Ignoring file format {frame_format!r} which is not "
449
+ f"supported by {type(self).__name__}; using "
450
+ f"{self.supported_formats[0]} instead.")
451
+ self._frame_format = self.supported_formats[0]
452
+
453
+ def _base_temp_name(self):
454
+ # Generates a template name (without number) given the frame format
455
+ # for extension and the prefix.
456
+ return self.fname_format_str % (self.temp_prefix, self.frame_format)
457
+
458
+ def grab_frame(self, **savefig_kwargs):
459
+ # docstring inherited
460
+ # Creates a filename for saving using basename and counter.
461
+ _validate_grabframe_kwargs(savefig_kwargs)
462
+ path = Path(self._base_temp_name() % self._frame_counter)
463
+ self._temp_paths.append(path) # Record the filename for later use.
464
+ self._frame_counter += 1 # Ensures each created name is unique.
465
+ _log.debug('FileMovieWriter.grab_frame: Grabbing frame %d to path=%s',
466
+ self._frame_counter, path)
467
+ with open(path, 'wb') as sink: # Save figure to the sink.
468
+ self.fig.savefig(sink, format=self.frame_format, dpi=self.dpi,
469
+ **savefig_kwargs)
470
+
471
+ def finish(self):
472
+ # Call run here now that all frame grabbing is done. All temp files
473
+ # are available to be assembled.
474
+ try:
475
+ self._run()
476
+ super().finish()
477
+ finally:
478
+ if self._tmpdir:
479
+ _log.debug(
480
+ 'MovieWriter: clearing temporary path=%s', self._tmpdir
481
+ )
482
+ self._tmpdir.cleanup()
483
+
484
+
485
+ @writers.register('pillow')
486
+ class PillowWriter(AbstractMovieWriter):
487
+ """
488
+ Write animated GIF, PNG (APNG) and WebP files, chosen by the extension.
489
+
490
+ The name is matplotlib's; matplotlib_rs encodes the frames with its Rust
491
+ core, as Pillow's ``save(save_all=True)`` would (each frame shown
492
+ ``1000 / fps`` ms, looping forever), without Pillow.
493
+ """
494
+
495
+ def _supports_transparency(self):
496
+ return True
497
+
498
+ @classmethod
499
+ def isAvailable(cls):
500
+ return True
501
+
502
+ def setup(self, fig, outfile, dpi=None):
503
+ super().setup(fig, outfile, dpi=dpi)
504
+ self._frames = []
505
+
506
+ def grab_frame(self, **savefig_kwargs):
507
+ _validate_grabframe_kwargs(savefig_kwargs)
508
+ buf = BytesIO()
509
+ self.fig.savefig(
510
+ buf, **{**savefig_kwargs, "format": "rgba", "dpi": self.dpi})
511
+ width, height = self.frame_size
512
+ self._frames.append(
513
+ np.frombuffer(buf.getbuffer(), np.uint8).reshape(height, width, 4).copy())
514
+
515
+ def finish(self):
516
+ from matplotlib_rs import _imageio
517
+ _imageio.save_animation(self.outfile, self._frames,
518
+ duration=int(1000 / self.fps), loop=0)
519
+
520
+
521
+ # Base class of ffmpeg information. Has the config keys and the common set
522
+ # of arguments that controls the *output* side of things.
523
+ class FFMpegBase:
524
+ """
525
+ Mixin class for FFMpeg output.
526
+
527
+ This is a base class for the concrete `FFMpegWriter` and `FFMpegFileWriter`
528
+ classes.
529
+ """
530
+
531
+ _exec_key = 'animation.ffmpeg_path'
532
+ _args_key = 'animation.ffmpeg_args'
533
+
534
+ def _supports_transparency(self):
535
+ suffix = Path(self.outfile).suffix
536
+ if suffix in {'.apng', '.avif', '.gif', '.webm', '.webp'}:
537
+ return True
538
+ # This list was found by going through `ffmpeg -codecs` for video encoders,
539
+ # running them with _support_transparency() forced to True, and checking that
540
+ # the "Pixel format" in Kdenlive included alpha. Note this is not a guarantee
541
+ # that transparency will work; you may also need to pass `-pix_fmt`, but we
542
+ # trust the user has done so if they are asking for these formats.
543
+ return self.codec in {
544
+ 'apng', 'avrp', 'bmp', 'cfhd', 'dpx', 'ffv1', 'ffvhuff', 'gif', 'huffyuv',
545
+ 'jpeg2000', 'ljpeg', 'png', 'prores', 'prores_aw', 'prores_ks', 'qtrle',
546
+ 'rawvideo', 'targa', 'tiff', 'utvideo', 'v408', }
547
+
548
+ @property
549
+ def output_args(self):
550
+ args = []
551
+ suffix = Path(self.outfile).suffix
552
+ if suffix in {'.apng', '.avif', '.gif', '.webm', '.webp'}:
553
+ self.codec = suffix[1:]
554
+ else:
555
+ args.extend(['-vcodec', self.codec])
556
+ extra_args = (self.extra_args if self.extra_args is not None
557
+ else mpl.rcParams[self._args_key])
558
+ # For h264, the default format is yuv444p, which is not compatible
559
+ # with quicktime (and others). Specifying yuv420p fixes playback on
560
+ # iOS, as well as HTML5 video in firefox and safari (on both Windows and
561
+ # macOS). Also fixes internet explorer. This is as of 2015/10/29.
562
+ if self.codec == 'h264' and '-pix_fmt' not in extra_args:
563
+ args.extend(['-pix_fmt', 'yuv420p'])
564
+ # For GIF, we're telling FFmpeg to split the video stream, to generate
565
+ # a palette, and then use it for encoding.
566
+ elif self.codec == 'gif' and '-filter_complex' not in extra_args:
567
+ args.extend(['-filter_complex',
568
+ 'split [a][b];[a] palettegen [p];[b][p] paletteuse'])
569
+ # For AVIF, we're telling FFmpeg to split the video stream, extract the alpha,
570
+ # in order to place it in a secondary stream, as needed by AVIF-in-FFmpeg.
571
+ elif self.codec == 'avif' and '-filter_complex' not in extra_args:
572
+ args.extend(['-filter_complex',
573
+ 'split [rgb][rgba]; [rgba] alphaextract [alpha]',
574
+ '-map', '[rgb]', '-map', '[alpha]'])
575
+ if self.bitrate > 0:
576
+ args.extend(['-b', '%dk' % self.bitrate]) # %dk: bitrate in kbps.
577
+ for k, v in self.metadata.items():
578
+ args.extend(['-metadata', f'{k}={v}'])
579
+ args.extend(extra_args)
580
+
581
+ return args + ['-y', self.outfile]
582
+
583
+
584
+ # Combine FFMpeg options with pipe-based writing
585
+ @writers.register('ffmpeg')
586
+ class FFMpegWriter(FFMpegBase, MovieWriter):
587
+ """
588
+ Pipe-based ffmpeg writer.
589
+
590
+ Frames are streamed directly to ffmpeg via a pipe and written in a single pass.
591
+
592
+ This effectively works as a slideshow input to ffmpeg with the fps passed as
593
+ ``-framerate``, so see also `their notes on frame rates`_ for further details.
594
+
595
+ .. _their notes on frame rates: https://trac.ffmpeg.org/wiki/Slideshow#Framerates
596
+ """
597
+ def _args(self):
598
+ # Returns the command line parameters for subprocess to use
599
+ # ffmpeg to create a movie using a pipe.
600
+ args = [self.bin_path(), '-f', 'rawvideo', '-vcodec', 'rawvideo',
601
+ '-s', '%dx%d' % self.frame_size, '-pix_fmt', self.frame_format,
602
+ '-framerate', str(self.fps)]
603
+ # Logging is quieted because subprocess.PIPE has limited buffer size.
604
+ # If you have a lot of frames in your animation and set logging to
605
+ # DEBUG, you will have a buffer overrun.
606
+ if _log.getEffectiveLevel() > logging.DEBUG:
607
+ args += ['-loglevel', 'error']
608
+ args += ['-i', 'pipe:'] + self.output_args
609
+ return args
610
+
611
+
612
+ # Combine FFMpeg options with temp file-based writing
613
+ @writers.register('ffmpeg_file')
614
+ class FFMpegFileWriter(FFMpegBase, FileMovieWriter):
615
+ """
616
+ File-based ffmpeg writer.
617
+
618
+ Frames are written to temporary files on disk and then stitched together at the end.
619
+
620
+ This effectively works as a slideshow input to ffmpeg with the fps passed as
621
+ ``-framerate``, so see also `their notes on frame rates`_ for further details.
622
+
623
+ .. _their notes on frame rates: https://trac.ffmpeg.org/wiki/Slideshow#Framerates
624
+
625
+ Parameters
626
+ ----------
627
+ *args, **kwargs
628
+ All arguments are forwarded to `FileMovieWriter`. See
629
+ `FileMovieWriter` for a list of all possible parameters.
630
+ """
631
+ supported_formats = ['png', 'jpeg', 'tiff', 'raw', 'rgba']
632
+
633
+ def _args(self):
634
+ # Returns the command line parameters for subprocess to use
635
+ # ffmpeg to create a movie using a collection of temp images
636
+ args = []
637
+ # For raw frames, we need to explicitly tell ffmpeg the metadata.
638
+ if self.frame_format in {'raw', 'rgba'}:
639
+ args += [
640
+ '-f', 'image2', '-vcodec', 'rawvideo',
641
+ '-video_size', '%dx%d' % self.frame_size,
642
+ '-pixel_format', 'rgba',
643
+ ]
644
+ args += ['-framerate', str(self.fps), '-i', self._base_temp_name()]
645
+ if not self._tmpdir:
646
+ args += ['-frames:v', str(self._frame_counter)]
647
+ # Logging is quieted because subprocess.PIPE has limited buffer size.
648
+ # If you have a lot of frames in your animation and set logging to
649
+ # DEBUG, you will have a buffer overrun.
650
+ if _log.getEffectiveLevel() > logging.DEBUG:
651
+ args += ['-loglevel', 'error']
652
+ return [self.bin_path(), *args, *self.output_args]
653
+
654
+
655
+ # Base class for animated GIFs with ImageMagick
656
+ class ImageMagickBase:
657
+ """
658
+ Mixin class for ImageMagick output.
659
+
660
+ This is a base class for the concrete `ImageMagickWriter` and
661
+ `ImageMagickFileWriter` classes, which define an ``input_names`` attribute
662
+ (or property) specifying the input names passed to ImageMagick.
663
+ """
664
+
665
+ _exec_key = 'animation.convert_path'
666
+ _args_key = 'animation.convert_args'
667
+
668
+ def _supports_transparency(self):
669
+ suffix = Path(self.outfile).suffix
670
+ return suffix in {'.apng', '.avif', '.gif', '.webm', '.webp'}
671
+
672
+ def _args(self):
673
+ # ImageMagick does not recognize "raw".
674
+ fmt = "rgba" if self.frame_format == "raw" else self.frame_format
675
+ extra_args = (self.extra_args if self.extra_args is not None
676
+ else mpl.rcParams[self._args_key])
677
+ return [
678
+ self.bin_path(),
679
+ "-size", "%ix%i" % self.frame_size,
680
+ "-depth", "8",
681
+ "-delay", str(100 / self.fps),
682
+ "-loop", "0",
683
+ f"{fmt}:{self.input_names}",
684
+ *extra_args,
685
+ self.outfile,
686
+ ]
687
+
688
+ @classmethod
689
+ def bin_path(cls):
690
+ binpath = super().bin_path()
691
+ if binpath == 'convert':
692
+ binpath = mpl._get_executable_info('magick').executable
693
+ return binpath
694
+
695
+ @classmethod
696
+ def isAvailable(cls):
697
+ try:
698
+ return super().isAvailable()
699
+ except mpl.ExecutableNotFoundError as _enf:
700
+ # May be raised by get_executable_info.
701
+ _log.debug('ImageMagick unavailable due to: %s', _enf)
702
+ return False
703
+
704
+
705
+ # Combine ImageMagick options with pipe-based writing
706
+ @writers.register('imagemagick')
707
+ class ImageMagickWriter(ImageMagickBase, MovieWriter):
708
+ """
709
+ Pipe-based animated gif writer.
710
+
711
+ Frames are streamed directly to ImageMagick via a pipe and written
712
+ in a single pass.
713
+ """
714
+
715
+ input_names = "-" # stdin
716
+
717
+
718
+ # Combine ImageMagick options with temp file-based writing
719
+ @writers.register('imagemagick_file')
720
+ class ImageMagickFileWriter(ImageMagickBase, FileMovieWriter):
721
+ """
722
+ File-based animated gif writer.
723
+
724
+ Frames are written to temporary files on disk and then stitched
725
+ together at the end.
726
+ """
727
+
728
+ supported_formats = ['png', 'jpeg', 'tiff', 'raw', 'rgba']
729
+ input_names = property(
730
+ lambda self: f'{self.temp_prefix}*.{self.frame_format}')
731
+
732
+
733
+ # Taken directly from jakevdp's JSAnimation package at
734
+ # http://github.com/jakevdp/JSAnimation
735
+ def _included_frames(frame_count, frame_format, frame_dir):
736
+ return INCLUDED_FRAMES.format(Nframes=frame_count,
737
+ frame_dir=frame_dir,
738
+ frame_format=frame_format)
739
+
740
+
741
+ def _embedded_frames(frame_list, frame_format):
742
+ """frame_list should be a list of base64-encoded png files"""
743
+ if frame_format == 'svg':
744
+ # Fix MIME type for svg
745
+ frame_format = 'svg+xml'
746
+ template = ' frames[{0}] = "data:image/{1};base64,{2}"\n'
747
+ return "\n" + "".join(
748
+ template.format(i, frame_format, frame_data.replace('\n', '\\\n'))
749
+ for i, frame_data in enumerate(frame_list))
750
+
751
+
752
+ @writers.register('html')
753
+ class HTMLWriter(FileMovieWriter):
754
+ """Writer for JavaScript-based HTML movies."""
755
+
756
+ supported_formats = ['png', 'jpeg', 'tiff', 'svg']
757
+
758
+ @classmethod
759
+ def isAvailable(cls):
760
+ return True
761
+
762
+ def __init__(self, fps=30, codec=None, bitrate=None, extra_args=None,
763
+ metadata=None, embed_frames=False, default_mode='loop',
764
+ embed_limit=None):
765
+
766
+ if extra_args:
767
+ _log.warning("HTMLWriter ignores 'extra_args'")
768
+ extra_args = () # Don't lookup nonexistent rcParam[args_key].
769
+ self.embed_frames = embed_frames
770
+ self.default_mode = default_mode.lower()
771
+ _api.check_in_list(['loop', 'once', 'reflect'],
772
+ default_mode=self.default_mode)
773
+
774
+ # Save embed limit, which is given in MB
775
+ self._bytes_limit = mpl._val_or_rc(embed_limit, 'animation.embed_limit')
776
+ # Convert from MB to bytes
777
+ self._bytes_limit *= 1024 * 1024
778
+
779
+ super().__init__(fps, codec, bitrate, extra_args, metadata)
780
+
781
+ def setup(self, fig, outfile, dpi=None, frame_dir=None):
782
+ outfile = Path(outfile)
783
+ _api.check_in_list(['.html', '.htm'], outfile_extension=outfile.suffix)
784
+
785
+ self._saved_frames = []
786
+ self._total_bytes = 0
787
+ self._hit_limit = False
788
+
789
+ if not self.embed_frames:
790
+ if frame_dir is None:
791
+ frame_dir = outfile.with_name(outfile.stem + '_frames')
792
+ frame_dir.mkdir(parents=True, exist_ok=True)
793
+ frame_prefix = frame_dir / 'frame'
794
+ else:
795
+ frame_prefix = None
796
+
797
+ super().setup(fig, outfile, dpi, frame_prefix)
798
+ self._clear_temp = False
799
+
800
+ def grab_frame(self, **savefig_kwargs):
801
+ _validate_grabframe_kwargs(savefig_kwargs)
802
+ if self.embed_frames:
803
+ # Just stop processing if we hit the limit
804
+ if self._hit_limit:
805
+ return
806
+ f = BytesIO()
807
+ self.fig.savefig(f, format=self.frame_format,
808
+ dpi=self.dpi, **savefig_kwargs)
809
+ imgdata64 = base64.encodebytes(f.getvalue()).decode('ascii')
810
+ self._total_bytes += len(imgdata64)
811
+ if self._total_bytes >= self._bytes_limit:
812
+ _log.warning(
813
+ "Animation size has reached %s bytes, exceeding the limit "
814
+ "of %s. If you're sure you want a larger animation "
815
+ "embedded, set the animation.embed_limit rc parameter to "
816
+ "a larger value (in MB). This and further frames will be "
817
+ "dropped.", self._total_bytes, self._bytes_limit)
818
+ self._hit_limit = True
819
+ else:
820
+ self._saved_frames.append(imgdata64)
821
+ else:
822
+ return super().grab_frame(**savefig_kwargs)
823
+
824
+ def finish(self):
825
+ # save the frames to an html file
826
+ if self.embed_frames:
827
+ fill_frames = _embedded_frames(self._saved_frames,
828
+ self.frame_format)
829
+ frame_count = len(self._saved_frames)
830
+ else:
831
+ # temp names is filled by FileMovieWriter
832
+ frame_count = len(self._temp_paths)
833
+ fill_frames = _included_frames(
834
+ frame_count, self.frame_format,
835
+ self._temp_paths[0].parent.relative_to(self.outfile.parent))
836
+ mode_dict = dict(once_checked='',
837
+ loop_checked='',
838
+ reflect_checked='')
839
+ mode_dict[self.default_mode + '_checked'] = 'checked'
840
+
841
+ interval = 1000 // self.fps
842
+
843
+ with open(self.outfile, 'w') as of:
844
+ of.write(JS_INCLUDE + STYLE_INCLUDE)
845
+ of.write(DISPLAY_TEMPLATE.format(id=uuid.uuid4().hex,
846
+ Nframes=frame_count,
847
+ fill_frames=fill_frames,
848
+ interval=interval,
849
+ **mode_dict))
850
+
851
+ # Duplicate the temporary file clean up logic from
852
+ # FileMovieWriter.finish. We cannot call the inherited version of
853
+ # finish because it assumes that there is a subprocess that we either
854
+ # need to call to merge many frames together or that there is a
855
+ # subprocess call that we need to clean up.
856
+ if self._tmpdir:
857
+ _log.debug('MovieWriter: clearing temporary path=%s', self._tmpdir)
858
+ self._tmpdir.cleanup()
859
+
860
+
861
+ class Animation:
862
+ """
863
+ Abstract base class for Animations.
864
+
865
+ .. note::
866
+
867
+ You must store the created Animation in a variable that lives as long
868
+ as the animation should run. Otherwise, the Animation object will be
869
+ garbage-collected and the animation stops.
870
+
871
+ Parameters
872
+ ----------
873
+ fig : `~matplotlib.figure.Figure`
874
+ The figure object used to get needed events, such as draw or resize.
875
+
876
+ event_source : object
877
+ A class that can run a callback when desired events
878
+ are generated, as well as be stopped and started.
879
+
880
+ Examples include timers (see `TimedAnimation`) and file
881
+ system notifications.
882
+
883
+ blit : bool, default: False
884
+ Whether blitting is used to optimize drawing. If the backend does not
885
+ support blitting, then this parameter has no effect.
886
+
887
+ See Also
888
+ --------
889
+ FuncAnimation, ArtistAnimation
890
+ """
891
+
892
+ def __init__(self, fig, event_source, blit=False):
893
+ self._draw_was_started = False
894
+
895
+ self._fig = fig
896
+ # Disables blitting for backends that don't support it. This
897
+ # allows users to request it if available, but still have a
898
+ # fallback that works if it is not.
899
+ self._blit = blit and fig.canvas.supports_blit
900
+
901
+ # These are the basics of the animation. The frame sequence represents
902
+ # information for each frame of the animation and depends on how the
903
+ # drawing is handled by the subclasses. The event source fires events
904
+ # that cause the frame sequence to be iterated.
905
+ self.frame_seq = self.new_frame_seq()
906
+ self.event_source = event_source
907
+ self.event_source.add_callback(self._step)
908
+
909
+ # Instead of starting the event source now, we connect to the figure's
910
+ # draw_event, so that we only start once the figure has been drawn.
911
+ self._first_draw_id = fig.canvas.mpl_connect('draw_event', self._start)
912
+
913
+ # Connect to the figure's close_event so that we don't continue to
914
+ # fire events and try to draw to a deleted figure.
915
+ self._close_id = self._fig.canvas.mpl_connect('close_event',
916
+ self._stop)
917
+ if self._blit:
918
+ self._setup_blit()
919
+
920
+ def __del__(self):
921
+ if not getattr(self, '_draw_was_started', True):
922
+ warnings.warn(
923
+ 'Animation was deleted without rendering anything. This is '
924
+ 'most likely not intended. To prevent deletion, assign the '
925
+ 'Animation to a variable, e.g. `anim`, that exists until you '
926
+ 'output the Animation using `plt.show()` or '
927
+ '`anim.save()`.'
928
+ )
929
+
930
+ def _start(self, *args):
931
+ """
932
+ Starts interactive animation. Adds the draw frame command to the GUI
933
+ handler, calls show to start the event loop.
934
+ """
935
+ # Do not start the event source if saving() it.
936
+ if self._fig.canvas.is_saving():
937
+ return
938
+ # First disconnect our draw event handler
939
+ self._fig.canvas.mpl_disconnect(self._first_draw_id)
940
+ # Now do any initial draw
941
+ self._init_draw()
942
+ # Actually start the event_source.
943
+ self.event_source.start()
944
+
945
+ def _stop(self, *args):
946
+ # On stop we disconnect all of our events.
947
+ if self._blit:
948
+ self._fig.canvas.mpl_disconnect(self._resize_id)
949
+ self._fig.canvas.mpl_disconnect(self._close_id)
950
+ self.event_source.remove_callback(self._step)
951
+ self.event_source = None
952
+
953
+ def save(self, filename, writer=None, fps=None, dpi=None, codec=None,
954
+ bitrate=None, extra_args=None, metadata=None, extra_anim=None,
955
+ savefig_kwargs=None, *, progress_callback=None):
956
+ """
957
+ Save the animation as a movie file by drawing every frame.
958
+
959
+ Parameters
960
+ ----------
961
+ filename : str
962
+ The output filename, e.g., :file:`mymovie.mp4`.
963
+
964
+ writer : `AbstractMovieWriter` subclass or str, default: :rc:`animation.writer`
965
+ The writer used to grab the frames and create the movie file.
966
+ This can be an instance of an `AbstractMovieWriter` subclass or a
967
+ string. The builtin writers are
968
+
969
+ ================== ==============================
970
+ str class
971
+ ================== ==============================
972
+ 'ffmpeg' `.FFMpegWriter`
973
+ 'ffmpeg_file' `.FFMpegFileWriter`
974
+ 'imagemagick' `.ImageMagickWriter`
975
+ 'imagemagick_file' `.ImageMagickFileWriter`
976
+ 'pillow' `.PillowWriter`
977
+ 'html' `.HTMLWriter`
978
+ ================== ==============================
979
+
980
+ fps : int, optional
981
+ Movie frame rate (per second). If not set, the frame rate from the
982
+ animation's frame interval.
983
+
984
+ dpi : float, default: :rc:`savefig.dpi`
985
+ Controls the dots per inch for the movie frames. Together with
986
+ the figure's size in inches, this controls the size of the movie.
987
+
988
+ codec : str, default: :rc:`animation.codec`.
989
+ The video codec to use. Not all codecs are supported by a given
990
+ `MovieWriter`.
991
+
992
+ bitrate : int, default: :rc:`animation.bitrate`
993
+ The bitrate of the movie, in kilobits per second. Higher values
994
+ means higher quality movies, but increase the file size. A value
995
+ of -1 lets the underlying movie encoder select the bitrate.
996
+
997
+ extra_args : list of str or None, optional
998
+ Extra command-line arguments passed to the underlying movie encoder. These
999
+ arguments are passed last to the encoder, just before the output filename.
1000
+ The default, None, means to use :rc:`animation.[name-of-encoder]_args` for
1001
+ the builtin writers.
1002
+
1003
+ metadata : dict[str, str], default: {}
1004
+ Dictionary of keys and values for metadata to include in
1005
+ the output file. Some keys that may be of use include:
1006
+ title, artist, genre, subject, copyright, srcform, comment.
1007
+
1008
+ extra_anim : list, default: []
1009
+ Additional `Animation` objects that should be included
1010
+ in the saved movie file. These need to be from the same
1011
+ `.Figure` instance. Also, animation frames will
1012
+ just be simply combined, so there should be a 1:1 correspondence
1013
+ between the frames from the different animations.
1014
+
1015
+ savefig_kwargs : dict, default: {}
1016
+ Keyword arguments passed to each `~.Figure.savefig` call used to
1017
+ save the individual frames.
1018
+
1019
+ progress_callback : function, optional
1020
+ A callback function that will be called for every frame to notify
1021
+ the saving progress. It must have the signature ::
1022
+
1023
+ def func(current_frame: int, total_frames: int) -> Any
1024
+
1025
+ where *current_frame* is the current frame number and *total_frames* is the
1026
+ total number of frames to be saved. *total_frames* is set to None, if the
1027
+ total number of frames cannot be determined. Return values may exist but are
1028
+ ignored.
1029
+
1030
+ Example code to write the progress to stdout::
1031
+
1032
+ progress_callback = lambda i, n: print(f'Saving frame {i}/{n}')
1033
+
1034
+ Notes
1035
+ -----
1036
+ *fps*, *codec*, *bitrate*, *extra_args* and *metadata* are used to
1037
+ construct a `.MovieWriter` instance and can only be passed if
1038
+ *writer* is a string. If they are passed as non-*None* and *writer*
1039
+ is a `.MovieWriter`, a `RuntimeError` will be raised.
1040
+ """
1041
+
1042
+ all_anim = [self]
1043
+ if extra_anim is not None:
1044
+ all_anim.extend(anim for anim in extra_anim
1045
+ if anim._fig is self._fig)
1046
+
1047
+ # Disable "Animation was deleted without rendering" warning.
1048
+ for anim in all_anim:
1049
+ anim._draw_was_started = True
1050
+
1051
+ if writer is None:
1052
+ writer = mpl.rcParams['animation.writer']
1053
+ elif (not isinstance(writer, str) and
1054
+ any(arg is not None
1055
+ for arg in (fps, codec, bitrate, extra_args, metadata))):
1056
+ raise RuntimeError('Passing in values for arguments '
1057
+ 'fps, codec, bitrate, extra_args, or metadata '
1058
+ 'is not supported when writer is an existing '
1059
+ 'MovieWriter instance. These should instead be '
1060
+ 'passed as arguments when creating the '
1061
+ 'MovieWriter instance.')
1062
+
1063
+ if savefig_kwargs is None:
1064
+ savefig_kwargs = {}
1065
+ else:
1066
+ # we are going to mutate this below
1067
+ savefig_kwargs = dict(savefig_kwargs)
1068
+
1069
+ if fps is None and hasattr(self, '_interval'):
1070
+ # Convert interval in ms to frames per second
1071
+ fps = 1000. / self._interval
1072
+
1073
+ # Reuse the savefig DPI for ours if none is given.
1074
+ dpi = mpl._val_or_rc(dpi, 'savefig.dpi')
1075
+ if dpi == 'figure':
1076
+ dpi = self._fig.dpi
1077
+
1078
+ writer_kwargs = {}
1079
+ if codec is not None:
1080
+ writer_kwargs['codec'] = codec
1081
+ if bitrate is not None:
1082
+ writer_kwargs['bitrate'] = bitrate
1083
+ if extra_args is not None:
1084
+ writer_kwargs['extra_args'] = extra_args
1085
+ if metadata is not None:
1086
+ writer_kwargs['metadata'] = metadata
1087
+
1088
+ # If we have the name of a writer, instantiate an instance of the
1089
+ # registered class.
1090
+ if isinstance(writer, str):
1091
+ try:
1092
+ writer_cls = writers[writer]
1093
+ except RuntimeError: # Raised if not available.
1094
+ writer_cls = PillowWriter # Always available.
1095
+ _log.warning("MovieWriter %s unavailable; using Pillow "
1096
+ "instead.", writer)
1097
+ writer = writer_cls(fps, **writer_kwargs)
1098
+ _log.info('Animation.save using %s', type(writer))
1099
+
1100
+ if 'bbox_inches' in savefig_kwargs:
1101
+ _log.warning("Warning: discarding the 'bbox_inches' argument in "
1102
+ "'savefig_kwargs' as it may cause frame size "
1103
+ "to vary, which is inappropriate for animation.")
1104
+ savefig_kwargs.pop('bbox_inches')
1105
+
1106
+ # Create a new sequence of frames for saved data. This is different
1107
+ # from new_frame_seq() to give the ability to save 'live' generated
1108
+ # frame information to be saved later.
1109
+ # TODO: Right now, after closing the figure, saving a movie won't work
1110
+ # since GUI widgets are gone. Either need to remove extra code to
1111
+ # allow for this non-existent use case or find a way to make it work.
1112
+
1113
+ def _pre_composite_to_white(color):
1114
+ r, g, b, a = mcolors.to_rgba(color)
1115
+ return a * np.array([r, g, b]) + 1 - a
1116
+
1117
+ # canvas._is_saving = True makes the draw_event animation-starting
1118
+ # callback a no-op; canvas.manager = None prevents resizing the GUI
1119
+ # widget (both are likewise done in savefig()).
1120
+ with (writer.saving(self._fig, filename, dpi),
1121
+ cbook._setattr_cm(self._fig.canvas, _is_saving=True, manager=None)):
1122
+ if not writer._supports_transparency():
1123
+ facecolor = savefig_kwargs.get('facecolor',
1124
+ mpl.rcParams['savefig.facecolor'])
1125
+ if facecolor == 'auto':
1126
+ facecolor = self._fig.get_facecolor()
1127
+ savefig_kwargs['facecolor'] = _pre_composite_to_white(facecolor)
1128
+ savefig_kwargs['transparent'] = False # just to be safe!
1129
+
1130
+ for anim in all_anim:
1131
+ anim._init_draw() # Clear the initial frame
1132
+ frame_number = 0
1133
+ # TODO: Currently only FuncAnimation has a save_count
1134
+ # attribute. Can we generalize this to all Animations?
1135
+ save_count_list = [getattr(a, '_save_count', None)
1136
+ for a in all_anim]
1137
+ if None in save_count_list:
1138
+ total_frames = None
1139
+ else:
1140
+ total_frames = sum(save_count_list)
1141
+ for data in zip(*[a.new_saved_frame_seq() for a in all_anim]):
1142
+ for anim, d in zip(all_anim, data):
1143
+ # TODO: See if turning off blit is really necessary
1144
+ anim._draw_next_frame(d, blit=False)
1145
+ if progress_callback is not None:
1146
+ progress_callback(frame_number, total_frames)
1147
+ frame_number += 1
1148
+ writer.grab_frame(**savefig_kwargs)
1149
+
1150
+ def _step(self, *args):
1151
+ """
1152
+ Handler for getting events. By default, gets the next frame in the
1153
+ sequence and hands the data off to be drawn.
1154
+ """
1155
+ # Returns True to indicate that the event source should continue to
1156
+ # call _step, until the frame sequence reaches the end of iteration,
1157
+ # at which point False will be returned.
1158
+ try:
1159
+ framedata = next(self.frame_seq)
1160
+ self._draw_next_frame(framedata, self._blit)
1161
+ return True
1162
+ except StopIteration:
1163
+ return False
1164
+
1165
+ def new_frame_seq(self):
1166
+ """Return a new sequence of frame information."""
1167
+ # Default implementation is just an iterator over self._framedata
1168
+ return iter(self._framedata)
1169
+
1170
+ def new_saved_frame_seq(self):
1171
+ """Return a new sequence of saved/cached frame information."""
1172
+ # Default is the same as the regular frame sequence
1173
+ return self.new_frame_seq()
1174
+
1175
+ def _draw_next_frame(self, framedata, blit):
1176
+ # Breaks down the drawing of the next frame into steps of pre- and
1177
+ # post- draw, as well as the drawing of the frame itself.
1178
+ self._pre_draw(framedata, blit)
1179
+ self._draw_frame(framedata)
1180
+ self._post_draw(framedata, blit)
1181
+
1182
+ def _init_draw(self):
1183
+ # Initial draw to clear the frame. Also used by the blitting code
1184
+ # when a clean base is required.
1185
+ self._draw_was_started = True
1186
+
1187
+ def _pre_draw(self, framedata, blit):
1188
+ # Perform any cleaning or whatnot before the drawing of the frame.
1189
+ # This default implementation allows blit to clear the frame.
1190
+ if blit:
1191
+ self._blit_clear(self._drawn_artists)
1192
+
1193
+ def _draw_frame(self, framedata):
1194
+ # Performs actual drawing of the frame.
1195
+ raise NotImplementedError('Needs to be implemented by subclasses to'
1196
+ ' actually make an animation.')
1197
+
1198
+ def _post_draw(self, framedata, blit):
1199
+ # After the frame is rendered, this handles the actual flushing of
1200
+ # the draw, which can be a direct draw_idle() or make use of the
1201
+ # blitting.
1202
+ if blit and self._drawn_artists:
1203
+ self._blit_draw(self._drawn_artists)
1204
+ else:
1205
+ self._fig.canvas.draw_idle()
1206
+
1207
+ # The rest of the code in this class is to facilitate easy blitting
1208
+ def _blit_draw(self, artists):
1209
+ # Handles blitted drawing, which renders only the artists given instead
1210
+ # of the entire figure.
1211
+ updated_ax = {a.axes for a in artists}
1212
+ # Enumerate artists to cache Axes backgrounds. We do not draw
1213
+ # artists yet to not cache foreground from plots with shared Axes
1214
+ for ax in updated_ax:
1215
+ # If we haven't cached the background for the current view of this
1216
+ # Axes object, do so now. This might not always be reliable, but
1217
+ # it's an attempt to automate the process.
1218
+ cur_view = ax._get_view()
1219
+ view, bg = self._blit_cache.get(ax, (object(), None))
1220
+ if cur_view != view:
1221
+ self._blit_cache[ax] = (
1222
+ cur_view, ax.figure.canvas.copy_from_bbox(ax.bbox))
1223
+ # Make a separate pass to draw foreground.
1224
+ for a in artists:
1225
+ a.axes.draw_artist(a)
1226
+ # After rendering all the needed artists, blit each Axes individually.
1227
+ for ax in updated_ax:
1228
+ ax.figure.canvas.blit(ax.bbox)
1229
+
1230
+ def _blit_clear(self, artists):
1231
+ # Get a list of the Axes that need clearing from the artists that
1232
+ # have been drawn. Grab the appropriate saved background from the
1233
+ # cache and restore.
1234
+ axes = {a.axes for a in artists}
1235
+ for ax in axes:
1236
+ try:
1237
+ view, bg = self._blit_cache[ax]
1238
+ except KeyError:
1239
+ continue
1240
+ if ax._get_view() == view:
1241
+ ax.figure.canvas.restore_region(bg)
1242
+ else:
1243
+ self._blit_cache.pop(ax)
1244
+
1245
+ def _setup_blit(self):
1246
+ # Setting up the blit requires: a cache of the background for the Axes
1247
+ self._blit_cache = dict()
1248
+ self._drawn_artists = []
1249
+ # _post_draw needs to be called first to initialize the renderer
1250
+ self._post_draw(None, self._blit)
1251
+ # Then we need to clear the Frame for the initial draw
1252
+ # This is typically handled in _on_resize because QT and Tk
1253
+ # emit a resize event on launch, but the macosx backend does not,
1254
+ # thus we force it here for everyone for consistency
1255
+ self._init_draw()
1256
+ # Connect to future resize events
1257
+ self._resize_id = self._fig.canvas.mpl_connect('resize_event',
1258
+ self._on_resize)
1259
+
1260
+ def _on_resize(self, event):
1261
+ # On resize, we need to disable the resize event handling so we don't
1262
+ # get too many events. Also stop the animation events, so that
1263
+ # we're paused. Reset the cache and re-init. Set up an event handler
1264
+ # to catch once the draw has actually taken place.
1265
+ self._fig.canvas.mpl_disconnect(self._resize_id)
1266
+ self.event_source.stop()
1267
+ self._blit_cache.clear()
1268
+ self._init_draw()
1269
+ self._resize_id = self._fig.canvas.mpl_connect('draw_event',
1270
+ self._end_redraw)
1271
+
1272
+ def _end_redraw(self, event):
1273
+ # Now that the redraw has happened, do the post draw flushing and
1274
+ # blit handling. Then re-enable all of the original events.
1275
+ self._post_draw(None, False)
1276
+ self.event_source.start()
1277
+ self._fig.canvas.mpl_disconnect(self._resize_id)
1278
+ self._resize_id = self._fig.canvas.mpl_connect('resize_event',
1279
+ self._on_resize)
1280
+
1281
+ def to_html5_video(self, embed_limit=None):
1282
+ """
1283
+ Convert the animation to an HTML5 ``<video>`` tag.
1284
+
1285
+ This saves the animation as an h264 video, encoded in base64
1286
+ directly into the HTML5 video tag. This respects :rc:`animation.writer`
1287
+ and :rc:`animation.bitrate`. This also makes use of the
1288
+ *interval* to control the speed, and uses the *repeat*
1289
+ parameter to decide whether to loop.
1290
+
1291
+ Parameters
1292
+ ----------
1293
+ embed_limit : float, optional
1294
+ Limit, in MB, of the returned animation. No animation is created
1295
+ if the limit is exceeded.
1296
+ Defaults to :rc:`animation.embed_limit` = 20.0.
1297
+
1298
+ Returns
1299
+ -------
1300
+ str
1301
+ An HTML5 video tag with the animation embedded as base64 encoded
1302
+ h264 video.
1303
+ If the *embed_limit* is exceeded, this returns the string
1304
+ "Video too large to embed."
1305
+ """
1306
+ VIDEO_TAG = r'''<video {size} {options}>
1307
+ <source type="video/mp4" src="data:video/mp4;base64,{video}">
1308
+ Your browser does not support the video tag.
1309
+ </video>'''
1310
+ # Cache the rendering of the video as HTML
1311
+ if not hasattr(self, '_base64_video'):
1312
+ # Save embed limit, which is given in MB
1313
+ embed_limit = mpl._val_or_rc(embed_limit, 'animation.embed_limit')
1314
+
1315
+ # Convert from MB to bytes
1316
+ embed_limit *= 1024 * 1024
1317
+
1318
+ # Can't open a NamedTemporaryFile twice on Windows, so use a
1319
+ # TemporaryDirectory instead.
1320
+ with TemporaryDirectory() as tmpdir:
1321
+ path = Path(tmpdir, "temp.m4v")
1322
+ # We create a writer manually so that we can get the
1323
+ # appropriate size for the tag
1324
+ Writer = writers[mpl.rcParams['animation.writer']]
1325
+ writer = Writer(codec='h264',
1326
+ bitrate=mpl.rcParams['animation.bitrate'],
1327
+ fps=1000. / self._interval)
1328
+ self.save(str(path), writer=writer)
1329
+ # Now open and base64 encode.
1330
+ vid64 = base64.encodebytes(path.read_bytes())
1331
+
1332
+ vid_len = len(vid64)
1333
+ if vid_len >= embed_limit:
1334
+ _log.warning(
1335
+ "Animation movie is %s bytes, exceeding the limit of %s. "
1336
+ "If you're sure you want a large animation embedded, set "
1337
+ "the animation.embed_limit rc parameter to a larger value "
1338
+ "(in MB).", vid_len, embed_limit)
1339
+ else:
1340
+ self._base64_video = vid64.decode('ascii')
1341
+ self._video_size = 'width="{}" height="{}"'.format(
1342
+ *writer.frame_size)
1343
+
1344
+ # If we exceeded the size, this attribute won't exist
1345
+ if hasattr(self, '_base64_video'):
1346
+ # Default HTML5 options are to autoplay and display video controls
1347
+ options = ['controls', 'autoplay']
1348
+
1349
+ # If we're set to repeat, make it loop
1350
+ if getattr(self, '_repeat', False):
1351
+ options.append('loop')
1352
+
1353
+ return VIDEO_TAG.format(video=self._base64_video,
1354
+ size=self._video_size,
1355
+ options=' '.join(options))
1356
+ else:
1357
+ return 'Video too large to embed.'
1358
+
1359
+ def to_jshtml(self, fps=None, embed_frames=True, default_mode=None):
1360
+ """
1361
+ Generate HTML representation of the animation.
1362
+
1363
+ Parameters
1364
+ ----------
1365
+ fps : int, optional
1366
+ Movie frame rate (per second). If not set, the frame rate from
1367
+ the animation's frame interval.
1368
+ embed_frames : bool, optional
1369
+ default_mode : str, optional
1370
+ What to do when the animation ends. Must be one of ``{'loop',
1371
+ 'once', 'reflect'}``. Defaults to ``'loop'`` if the *repeat*
1372
+ parameter is True, otherwise ``'once'``.
1373
+
1374
+ Returns
1375
+ -------
1376
+ str
1377
+ An HTML representation of the animation embedded as a js object as
1378
+ produced with the `.HTMLWriter`.
1379
+ """
1380
+ if fps is None and hasattr(self, '_interval'):
1381
+ # Convert interval in ms to frames per second
1382
+ fps = 1000 / self._interval
1383
+
1384
+ # If we're not given a default mode, choose one base on the value of
1385
+ # the _repeat attribute
1386
+ if default_mode is None:
1387
+ default_mode = 'loop' if getattr(self, '_repeat',
1388
+ False) else 'once'
1389
+
1390
+ if not hasattr(self, "_html_representation"):
1391
+ # Can't open a NamedTemporaryFile twice on Windows, so use a
1392
+ # TemporaryDirectory instead.
1393
+ with TemporaryDirectory() as tmpdir:
1394
+ path = Path(tmpdir, "temp.html")
1395
+ writer = HTMLWriter(fps=fps,
1396
+ embed_frames=embed_frames,
1397
+ default_mode=default_mode)
1398
+ self.save(str(path), writer=writer)
1399
+ self._html_representation = path.read_text()
1400
+
1401
+ return self._html_representation
1402
+
1403
+ def _repr_html_(self):
1404
+ """IPython display hook for rendering."""
1405
+ fmt = mpl.rcParams['animation.html']
1406
+ if fmt == 'html5':
1407
+ return self.to_html5_video()
1408
+ elif fmt == 'jshtml':
1409
+ return self.to_jshtml()
1410
+
1411
+ def pause(self):
1412
+ """Pause the animation."""
1413
+ self.event_source.stop()
1414
+ if self._blit:
1415
+ for artist in self._drawn_artists:
1416
+ artist.set_animated(False)
1417
+
1418
+ def resume(self):
1419
+ """Resume the animation."""
1420
+ self.event_source.start()
1421
+ if self._blit:
1422
+ for artist in self._drawn_artists:
1423
+ artist.set_animated(True)
1424
+
1425
+
1426
+ class TimedAnimation(Animation):
1427
+ """
1428
+ Abstract `Animation` subclass for time-based animation.
1429
+
1430
+ A new frame is drawn every *interval* milliseconds.
1431
+
1432
+ .. note::
1433
+
1434
+ You must store the created Animation in a variable that lives as long
1435
+ as the animation should run. Otherwise, the Animation object will be
1436
+ garbage-collected and the animation stops.
1437
+
1438
+ Parameters
1439
+ ----------
1440
+ fig : `~matplotlib.figure.Figure`
1441
+ The figure object used to get needed events, such as draw or resize.
1442
+ interval : int, default: 200
1443
+ Delay between frames in milliseconds.
1444
+ repeat_delay : int, default: 0
1445
+ The delay in milliseconds between consecutive animation runs, if
1446
+ *repeat* is True.
1447
+ repeat : bool, default: True
1448
+ Whether the animation repeats when the sequence of frames is completed.
1449
+ blit : bool, default: False
1450
+ Whether blitting is used to optimize drawing.
1451
+ """
1452
+ def __init__(self, fig, interval=200, repeat_delay=0, repeat=True,
1453
+ event_source=None, *args, **kwargs):
1454
+ self._interval = interval
1455
+ # Undocumented support for repeat_delay = None as backcompat.
1456
+ self._repeat_delay = repeat_delay if repeat_delay is not None else 0
1457
+ self._repeat = repeat
1458
+ # If we're not given an event source, create a new timer. This permits
1459
+ # sharing timers between animation objects for syncing animations.
1460
+ if event_source is None:
1461
+ event_source = fig.canvas.new_timer(interval=self._interval)
1462
+ super().__init__(fig, event_source=event_source, *args, **kwargs)
1463
+
1464
+ def _step(self, *args):
1465
+ """Handler for getting events."""
1466
+ # Extends the _step() method for the Animation class. If
1467
+ # Animation._step signals that it reached the end and we want to
1468
+ # repeat, we refresh the frame sequence and return True. If
1469
+ # _repeat_delay is set, change the event_source's interval to our loop
1470
+ # delay and set the callback to one which will then set the interval
1471
+ # back.
1472
+ still_going = super()._step(*args)
1473
+ if not still_going:
1474
+ if self._repeat:
1475
+ # Restart the draw loop
1476
+ self._init_draw()
1477
+ self.frame_seq = self.new_frame_seq()
1478
+ self.event_source.interval = self._repeat_delay
1479
+ return True
1480
+ else:
1481
+ # We are done with the animation. Call pause to remove
1482
+ # animated flags from artists that were using blitting
1483
+ self.pause()
1484
+ if self._blit:
1485
+ # Remove the resize callback if we were blitting
1486
+ self._fig.canvas.mpl_disconnect(self._resize_id)
1487
+ self._fig.canvas.mpl_disconnect(self._close_id)
1488
+ self.event_source = None
1489
+ return False
1490
+
1491
+ self.event_source.interval = self._interval
1492
+ return True
1493
+
1494
+
1495
+ class ArtistAnimation(TimedAnimation):
1496
+ """
1497
+ `TimedAnimation` subclass that creates an animation by using a fixed
1498
+ set of `.Artist` objects.
1499
+
1500
+ Before creating an instance, all plotting should have taken place
1501
+ and the relevant artists saved.
1502
+
1503
+ .. note::
1504
+
1505
+ You must store the created Animation in a variable that lives as long
1506
+ as the animation should run. Otherwise, the Animation object will be
1507
+ garbage-collected and the animation stops.
1508
+
1509
+ Parameters
1510
+ ----------
1511
+ fig : `~matplotlib.figure.Figure`
1512
+ The figure object used to get needed events, such as draw or resize.
1513
+ artists : list
1514
+ Each list entry is a collection of `.Artist` objects that are made
1515
+ visible on the corresponding frame. Other artists are made invisible.
1516
+ interval : int, default: 200
1517
+ Delay between frames in milliseconds.
1518
+ repeat_delay : int, default: 0
1519
+ The delay in milliseconds between consecutive animation runs, if
1520
+ *repeat* is True.
1521
+ repeat : bool, default: True
1522
+ Whether the animation repeats when the sequence of frames is completed.
1523
+ blit : bool, default: False
1524
+ Whether blitting is used to optimize drawing.
1525
+ """
1526
+
1527
+ def __init__(self, fig, artists, *args, **kwargs):
1528
+ # Internal list of artists drawn in the most recent frame.
1529
+ self._drawn_artists = []
1530
+
1531
+ # Use the list of artists as the framedata, which will be iterated
1532
+ # over by the machinery.
1533
+ self._framedata = artists
1534
+ super().__init__(fig, *args, **kwargs)
1535
+
1536
+ def _init_draw(self):
1537
+ super()._init_draw()
1538
+ # Make all the artists involved in *any* frame invisible
1539
+ figs = set()
1540
+ for f in self.new_frame_seq():
1541
+ for artist in f:
1542
+ artist.set_visible(False)
1543
+ artist.set_animated(self._blit)
1544
+ # Assemble a list of unique figures that need flushing
1545
+ if artist.get_figure() not in figs:
1546
+ figs.add(artist.get_figure())
1547
+
1548
+ # Flush the needed figures
1549
+ for fig in figs:
1550
+ fig.canvas.draw_idle()
1551
+
1552
+ def _pre_draw(self, framedata, blit):
1553
+ """Clears artists from the last frame."""
1554
+ if blit:
1555
+ # Let blit handle clearing
1556
+ self._blit_clear(self._drawn_artists)
1557
+ else:
1558
+ # Otherwise, make all the artists from the previous frame invisible
1559
+ for artist in self._drawn_artists:
1560
+ artist.set_visible(False)
1561
+
1562
+ def _draw_frame(self, artists):
1563
+ # Save the artists that were passed in as framedata for the other
1564
+ # steps (esp. blitting) to use.
1565
+ self._drawn_artists = artists
1566
+
1567
+ # Make all the artists from the current frame visible
1568
+ for artist in artists:
1569
+ artist.set_visible(True)
1570
+
1571
+
1572
+ class FuncAnimation(TimedAnimation):
1573
+ """
1574
+ `TimedAnimation` subclass that makes an animation by repeatedly calling
1575
+ a function *func*.
1576
+
1577
+ .. note::
1578
+
1579
+ You must store the created Animation in a variable that lives as long
1580
+ as the animation should run. Otherwise, the Animation object will be
1581
+ garbage-collected and the animation stops.
1582
+
1583
+ Parameters
1584
+ ----------
1585
+ fig : `~matplotlib.figure.Figure`
1586
+ The figure object used to get needed events, such as draw or resize.
1587
+
1588
+ func : callable
1589
+ The function to call at each frame. The first argument will
1590
+ be the next value in *frames*. Any additional positional
1591
+ arguments can be supplied using `functools.partial` or via the *fargs*
1592
+ parameter.
1593
+
1594
+ The required signature is::
1595
+
1596
+ def func(frame, *fargs) -> iterable_of_artists
1597
+
1598
+ It is often more convenient to provide the arguments using
1599
+ `functools.partial`. In this way it is also possible to pass keyword
1600
+ arguments. To pass a function with both positional and keyword
1601
+ arguments, set all arguments as keyword arguments, just leaving the
1602
+ *frame* argument unset::
1603
+
1604
+ def func(frame, art, *, y=None):
1605
+ ...
1606
+
1607
+ ani = FuncAnimation(fig, partial(func, art=ln, y='foo'))
1608
+
1609
+ If ``blit == True``, *func* must return an iterable of all artists
1610
+ that were modified or created. This information is used by the blitting
1611
+ algorithm to determine which parts of the figure have to be updated.
1612
+ The return value is unused if ``blit == False`` and may be omitted in
1613
+ that case.
1614
+
1615
+ frames : iterable, int, generator function, or None, optional
1616
+ Source of data to pass *func* and each frame of the animation
1617
+
1618
+ - If an iterable, then simply use the values provided. If the
1619
+ iterable has a length, it will override the *save_count* kwarg.
1620
+
1621
+ - If an integer, then equivalent to passing ``range(frames)``
1622
+
1623
+ - If a generator function, then must have the signature::
1624
+
1625
+ def gen_function() -> obj
1626
+
1627
+ - If *None*, then equivalent to passing ``itertools.count``.
1628
+
1629
+ In all of these cases, the values in *frames* is simply passed through
1630
+ to the user-supplied *func* and thus can be of any type.
1631
+
1632
+ init_func : callable, optional
1633
+ A function used to draw a clear frame. If not given, the results of
1634
+ drawing from the first item in the frames sequence will be used. This
1635
+ function will be called once before the first frame.
1636
+
1637
+ The required signature is::
1638
+
1639
+ def init_func() -> iterable_of_artists
1640
+
1641
+ If ``blit == True``, *init_func* must return an iterable of artists
1642
+ to be re-drawn. This information is used by the blitting algorithm to
1643
+ determine which parts of the figure have to be updated. The return
1644
+ value is unused if ``blit == False`` and may be omitted in that case.
1645
+
1646
+ fargs : tuple or None, optional
1647
+ Additional arguments to pass to each call to *func*. Note: the use of
1648
+ `functools.partial` is preferred over *fargs*. See *func* for details.
1649
+
1650
+ save_count : int, optional
1651
+ Fallback for the number of values from *frames* to cache. This is
1652
+ only used if the number of frames cannot be inferred from *frames*,
1653
+ i.e. when it's an iterator without length or a generator.
1654
+
1655
+ interval : int, default: 200
1656
+ Delay between frames in milliseconds.
1657
+
1658
+ repeat_delay : int, default: 0
1659
+ The delay in milliseconds between consecutive animation runs, if
1660
+ *repeat* is True.
1661
+
1662
+ repeat : bool, default: True
1663
+ Whether the animation repeats when the sequence of frames is completed.
1664
+
1665
+ blit : bool, default: False
1666
+ Whether blitting is used to optimize drawing. Note: when using
1667
+ blitting, any animated artists will be drawn according to their zorder;
1668
+ however, they will be drawn on top of any previous artists, regardless
1669
+ of their zorder.
1670
+
1671
+ cache_frame_data : bool, default: True
1672
+ Whether frame data is cached. Disabling cache might be helpful when
1673
+ frames contain large objects.
1674
+ """
1675
+ def __init__(self, fig, func, frames=None, init_func=None, fargs=None,
1676
+ save_count=None, *, cache_frame_data=True, **kwargs):
1677
+ if fargs:
1678
+ self._args = fargs
1679
+ else:
1680
+ self._args = ()
1681
+ self._func = func
1682
+ self._init_func = init_func
1683
+
1684
+ # Amount of framedata to keep around for saving movies. This is only
1685
+ # used if we don't know how many frames there will be: in the case
1686
+ # of no generator or in the case of a callable.
1687
+ self._save_count = save_count
1688
+ # Set up a function that creates a new iterable when needed. If nothing
1689
+ # is passed in for frames, just use itertools.count, which will just
1690
+ # keep counting from 0. A callable passed in for frames is assumed to
1691
+ # be a generator. An iterable will be used as is, and anything else
1692
+ # will be treated as a number of frames.
1693
+ if frames is None:
1694
+ self._iter_gen = itertools.count
1695
+ elif callable(frames):
1696
+ self._iter_gen = frames
1697
+ elif np.iterable(frames):
1698
+ if kwargs.get('repeat', True):
1699
+ self._tee_from = frames
1700
+ def iter_frames(frames=frames):
1701
+ this, self._tee_from = itertools.tee(self._tee_from, 2)
1702
+ yield from this
1703
+ self._iter_gen = iter_frames
1704
+ else:
1705
+ self._iter_gen = lambda: iter(frames)
1706
+ if hasattr(frames, '__len__'):
1707
+ self._save_count = len(frames)
1708
+ if save_count is not None:
1709
+ _api.warn_external(
1710
+ f"You passed in an explicit {save_count=} "
1711
+ "which is being ignored in favor of "
1712
+ f"{len(frames)=}."
1713
+ )
1714
+ else:
1715
+ self._iter_gen = lambda: iter(range(frames))
1716
+ self._save_count = frames
1717
+ if save_count is not None:
1718
+ _api.warn_external(
1719
+ f"You passed in an explicit {save_count=} which is being "
1720
+ f"ignored in favor of {frames=}."
1721
+ )
1722
+ if self._save_count is None and cache_frame_data:
1723
+ _api.warn_external(
1724
+ f"{frames=!r} which we can infer the length of, "
1725
+ "did not pass an explicit *save_count* "
1726
+ f"and passed {cache_frame_data=}. To avoid a possibly "
1727
+ "unbounded cache, frame data caching has been disabled. "
1728
+ "To suppress this warning either pass "
1729
+ "`cache_frame_data=False` or `save_count=MAX_FRAMES`."
1730
+ )
1731
+ cache_frame_data = False
1732
+
1733
+ self._cache_frame_data = cache_frame_data
1734
+
1735
+ # Needs to be initialized so the draw functions work without checking
1736
+ self._save_seq = collections.deque([], self._save_count)
1737
+
1738
+ super().__init__(fig, **kwargs)
1739
+
1740
+ # Need to reset the saved seq, since right now it will contain data
1741
+ # for a single frame from init, which is not what we want.
1742
+ self._save_seq.clear()
1743
+
1744
+ def new_frame_seq(self):
1745
+ # Use the generating function to generate a new frame sequence
1746
+ return self._iter_gen()
1747
+
1748
+ def new_saved_frame_seq(self):
1749
+ # Generate an iterator for the sequence of saved data. If there are
1750
+ # no saved frames, generate a new frame sequence and take the first
1751
+ # save_count entries in it.
1752
+ if self._save_seq:
1753
+ # While iterating we are going to update _save_seq
1754
+ # so make a copy to safely iterate over
1755
+ return iter([*self._save_seq])
1756
+ else:
1757
+ if self._save_count is None:
1758
+ frame_seq = self.new_frame_seq()
1759
+
1760
+ def gen():
1761
+ try:
1762
+ while True:
1763
+ yield next(frame_seq)
1764
+ except StopIteration:
1765
+ pass
1766
+ return gen()
1767
+ else:
1768
+ return itertools.islice(self.new_frame_seq(), self._save_count)
1769
+
1770
+ def _init_draw(self):
1771
+ super()._init_draw()
1772
+ # Initialize the drawing either using the given init_func or by
1773
+ # calling the draw function with the first item of the frame sequence.
1774
+ # For blitting, the init_func should return a sequence of modified
1775
+ # artists.
1776
+ if self._init_func is None:
1777
+ try:
1778
+ frame_data = next(self.new_frame_seq())
1779
+ except StopIteration:
1780
+ # we can't start the iteration, it may have already been
1781
+ # exhausted by a previous save or just be 0 length.
1782
+ # warn and bail.
1783
+ warnings.warn(
1784
+ "Can not start iterating the frames for the initial draw. "
1785
+ "This can be caused by passing in a 0 length sequence "
1786
+ "for *frames*.\n\n"
1787
+ "If you passed *frames* as a generator "
1788
+ "it may be exhausted due to a previous display or save."
1789
+ )
1790
+ return
1791
+ self._draw_frame(frame_data)
1792
+ else:
1793
+ self._drawn_artists = self._init_func()
1794
+ if self._blit:
1795
+ if self._drawn_artists is None:
1796
+ raise RuntimeError('When blit=True, the init_func must '
1797
+ 'return a sequence of Artist objects.')
1798
+ for a in self._drawn_artists:
1799
+ a.set_animated(self._blit)
1800
+ self._save_seq.clear()
1801
+
1802
+ def _draw_frame(self, framedata):
1803
+ if self._cache_frame_data:
1804
+ # Save the data for potential saving of movies.
1805
+ self._save_seq.append(framedata)
1806
+
1807
+ # Call the func with framedata and args. If blitting is desired,
1808
+ # func needs to return a sequence of any artists that were modified.
1809
+ self._drawn_artists = self._func(framedata, *self._args)
1810
+
1811
+ if self._blit:
1812
+
1813
+ err = RuntimeError('When blit=True, the animation function must '
1814
+ 'return a sequence of Artist objects.')
1815
+ try:
1816
+ # check if a sequence
1817
+ iter(self._drawn_artists)
1818
+ except TypeError:
1819
+ raise err from None
1820
+
1821
+ # check each item if it's artist
1822
+ for i in self._drawn_artists:
1823
+ if not isinstance(i, mpl.artist.Artist):
1824
+ raise err
1825
+
1826
+ self._drawn_artists = sorted(self._drawn_artists,
1827
+ key=lambda x: x.get_zorder())
1828
+
1829
+ for a in self._drawn_artists:
1830
+ a.set_animated(self._blit)
1831
+
1832
+
1833
+ def _validate_grabframe_kwargs(savefig_kwargs):
1834
+ if mpl.rcParams['savefig.bbox'] == 'tight':
1835
+ raise ValueError(
1836
+ f"{mpl.rcParams['savefig.bbox']=} must not be 'tight' as it "
1837
+ "may cause frame size to vary, which is inappropriate for animation."
1838
+ )
1839
+ for k in ('dpi', 'bbox_inches', 'format'):
1840
+ if k in savefig_kwargs:
1841
+ raise TypeError(
1842
+ f"grab_frame got an unexpected keyword argument {k!r}"
1843
+ )