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,3069 @@
1
+ # Vendored from matplotlib 3.11 (see licenses/LICENSE_MATPLOTLIB), adapted for matplotlib_rs.
2
+ """
3
+ Matplotlib includes a framework for arbitrary geometric transformations that is used to
4
+ determine the final position of all elements drawn on the canvas.
5
+
6
+ Transforms are composed into trees of `TransformNode` objects
7
+ whose actual value depends on their children. When the contents of
8
+ children change, their parents are automatically invalidated. The
9
+ next time an invalidated transform is accessed, it is recomputed to
10
+ reflect those changes. This invalidation/caching approach prevents
11
+ unnecessary recomputations of transforms, and contributes to better
12
+ interactive performance.
13
+
14
+ For example, here is a graph of the transform tree used to plot data to the figure:
15
+
16
+ .. graphviz:: /api/transforms.dot
17
+ :alt: Diagram of transform tree from data to figure coordinates.
18
+
19
+ The framework can be used for both affine and non-affine
20
+ transformations. However, for speed, we want to use the backend
21
+ renderers to perform affine transformations whenever possible.
22
+ Therefore, it is possible to perform just the affine or non-affine
23
+ part of a transformation on a set of data. The affine is always
24
+ assumed to occur after the non-affine. For any transform::
25
+
26
+ full transform == non-affine part + affine part
27
+
28
+ The backends are not expected to handle non-affine transformations
29
+ themselves.
30
+
31
+ See the tutorial :ref:`transforms_tutorial` for examples
32
+ of how to use transforms.
33
+ """
34
+
35
+ # Note: There are a number of places in the code where we use `np.min` or
36
+ # `np.minimum` instead of the builtin `min`, and likewise for `max`. This is
37
+ # done so that `nan`s are propagated, instead of being silently dropped.
38
+
39
+ import functools
40
+ import itertools
41
+ import textwrap
42
+ import weakref
43
+ import math
44
+
45
+ import numpy as np
46
+ from numpy.linalg import inv
47
+
48
+ from . import _api, _docstring
49
+ from ._path import affine_transform, count_bboxes_overlapping_bbox
50
+ from .path import Path
51
+
52
+ DEBUG = False
53
+
54
+
55
+ def _make_str_method(*args, **kwargs):
56
+ """
57
+ Generate a ``__str__`` method for a `.Transform` subclass.
58
+
59
+ After ::
60
+
61
+ class T:
62
+ __str__ = _make_str_method("attr", key="other")
63
+
64
+ ``str(T(...))`` will be
65
+
66
+ .. code-block:: text
67
+
68
+ {type(T).__name__}(
69
+ {self.attr},
70
+ key={self.other})
71
+ """
72
+ indent = functools.partial(textwrap.indent, prefix=" " * 4)
73
+ def strrepr(x): return repr(x) if isinstance(x, str) else str(x)
74
+ return lambda self: (
75
+ type(self).__name__ + "("
76
+ + ",".join([*(indent("\n" + strrepr(getattr(self, arg)))
77
+ for arg in args),
78
+ *(indent("\n" + k + "=" + strrepr(getattr(self, arg)))
79
+ for k, arg in kwargs.items())])
80
+ + ")")
81
+
82
+
83
+ class TransformNode:
84
+ """
85
+ The base class for anything that participates in the transform tree
86
+ and needs to invalidate its parents or be invalidated. This includes
87
+ classes that are not really transforms, such as bounding boxes, since some
88
+ transforms depend on bounding boxes to compute their values.
89
+ """
90
+
91
+ # Invalidation may affect only the affine part. If the
92
+ # invalidation was "affine-only", the _invalid member is set to
93
+ # INVALID_AFFINE_ONLY
94
+
95
+ # Possible values for the _invalid attribute.
96
+ _VALID, _INVALID_AFFINE_ONLY, _INVALID_FULL = range(3)
97
+
98
+ # matplotlib_rs: nodes whose values live in the Rust model ("live"
99
+ # nodes) and every node depending on them are never cached.
100
+ _live = False
101
+
102
+ @property
103
+ def _invalid(self):
104
+ if self._live:
105
+ return self._INVALID_FULL
106
+ return self.__dict__.get("_invalid_", self._INVALID_FULL)
107
+
108
+ @_invalid.setter
109
+ def _invalid(self, v):
110
+ self.__dict__["_invalid_"] = v
111
+
112
+ # Some metadata about the transform, used to determine whether an
113
+ # invalidation is affine-only
114
+ is_affine = False
115
+
116
+ pass_through = False
117
+ """
118
+ If pass_through is True, all ancestors will always be
119
+ invalidated, even if 'self' is already invalid.
120
+ """
121
+
122
+ def __init__(self, shorthand_name=None):
123
+ """
124
+ Parameters
125
+ ----------
126
+ shorthand_name : str
127
+ A string representing the "name" of the transform. The name carries
128
+ no significance other than to improve the readability of
129
+ ``str(transform)`` when DEBUG=True.
130
+ """
131
+ self._parents = {}
132
+ # Initially invalid, until first computation.
133
+ self._invalid = self._INVALID_FULL
134
+ self._shorthand_name = shorthand_name or ''
135
+
136
+ if DEBUG:
137
+ def __str__(self):
138
+ # either just return the name of this TransformNode, or its repr
139
+ return self._shorthand_name or repr(self)
140
+
141
+ def __getstate__(self):
142
+ # turn the dictionary with weak values into a normal dictionary
143
+ return {**self.__dict__,
144
+ '_parents': {k: v() for k, v in self._parents.items()}}
145
+
146
+ def __setstate__(self, data_dict):
147
+ self.__dict__ = data_dict
148
+ # turn the normal dictionary back into a dictionary with weak values
149
+ # The extra lambda is to provide a callback to remove dead
150
+ # weakrefs from the dictionary when garbage collection is done.
151
+ self._parents = {
152
+ k: weakref.ref(v, lambda _, pop=self._parents.pop, k=k: pop(k))
153
+ for k, v in self._parents.items() if v is not None}
154
+
155
+ def __copy__(self):
156
+ cls = type(self)
157
+ other = cls.__new__(cls)
158
+ other.__dict__.update(self.__dict__)
159
+ # If `c = a + b; a1 = copy(a)`, then modifications to `a1` do not
160
+ # propagate back to `c`, i.e. we need to clear the parents of `a1`.
161
+ other._parents = {}
162
+ # If `c = a + b; c1 = copy(c)`, then modifications to `a` also need to
163
+ # be propagated to `c1`.
164
+ for key, val in vars(self).items():
165
+ if isinstance(val, TransformNode) and id(self) in val._parents:
166
+ other.set_children(val) # val == getattr(other, key)
167
+ return other
168
+
169
+ def invalidate(self):
170
+ """
171
+ Invalidate this `TransformNode` and triggers an invalidation of its
172
+ ancestors. Should be called any time the transform changes.
173
+ """
174
+ self._invalidate_internal(
175
+ level=self._INVALID_AFFINE_ONLY if self.is_affine else self._INVALID_FULL,
176
+ invalidating_node=self)
177
+
178
+ def _invalidate_internal(self, level, invalidating_node):
179
+ """
180
+ Called by :meth:`invalidate` and subsequently ascends the transform
181
+ stack calling each TransformNode's _invalidate_internal method.
182
+ """
183
+ # If we are already more invalid than the currently propagated invalidation,
184
+ # then we don't need to do anything.
185
+ if level <= self._invalid and not self.pass_through:
186
+ return
187
+ self._invalid = level
188
+ for parent in list(self._parents.values()):
189
+ parent = parent() # Dereference the weak reference.
190
+ if parent is not None:
191
+ parent._invalidate_internal(level=level, invalidating_node=self)
192
+
193
+ def set_children(self, *children):
194
+ """
195
+ Set the children of the transform, to let the invalidation
196
+ system know which transforms can invalidate this transform.
197
+ Should be called from the constructor of any transforms that
198
+ depend on other transforms.
199
+ """
200
+ # Parents are stored as weak references, so that if the
201
+ # parents are destroyed, references from the children won't
202
+ # keep them alive.
203
+ id_self = id(self)
204
+ for child in children:
205
+ # Use weak references so this dictionary won't keep obsolete nodes
206
+ # alive; the callback deletes the dictionary entry. This is a
207
+ # performance improvement over using WeakValueDictionary.
208
+ ref = weakref.ref(
209
+ self, lambda _, pop=child._parents.pop, k=id_self: pop(k))
210
+ child._parents[id_self] = ref
211
+ if child._live:
212
+ self._live = True
213
+
214
+ def frozen(self):
215
+ """
216
+ Return a frozen copy of this transform node. The frozen copy will not
217
+ be updated when its children change. Useful for storing a previously
218
+ known state of a transform where ``copy.deepcopy()`` might normally be
219
+ used.
220
+ """
221
+ return self
222
+
223
+
224
+ class BboxBase(TransformNode):
225
+ """
226
+ The base class of all bounding boxes.
227
+
228
+ This class is immutable; `Bbox` is a mutable subclass.
229
+
230
+ The canonical representation is as two points, with no
231
+ restrictions on their ordering. Convenience properties are
232
+ provided to get the left, bottom, right and top edges and width
233
+ and height, but these are not stored explicitly.
234
+ """
235
+
236
+ is_affine = True
237
+
238
+ if DEBUG:
239
+ @staticmethod
240
+ def _check(points):
241
+ if isinstance(points, np.ma.MaskedArray):
242
+ _api.warn_external("Bbox bounds are a masked array.")
243
+ points = np.asarray(points)
244
+ if any((points[1, :] - points[0, :]) == 0):
245
+ _api.warn_external("Singular Bbox.")
246
+
247
+ def frozen(self):
248
+ return Bbox(self.get_points().copy())
249
+ frozen.__doc__ = TransformNode.__doc__
250
+
251
+ def __array__(self, *args, **kwargs):
252
+ return self.get_points()
253
+
254
+ @property
255
+ def x0(self):
256
+ """
257
+ The first of the pair of *x* coordinates that define the bounding box.
258
+
259
+ This is not guaranteed to be less than :attr:`x1` (for that, use
260
+ :attr:`~BboxBase.xmin`).
261
+ """
262
+ return self.get_points()[0, 0]
263
+
264
+ @property
265
+ def y0(self):
266
+ """
267
+ The first of the pair of *y* coordinates that define the bounding box.
268
+
269
+ This is not guaranteed to be less than :attr:`y1` (for that, use
270
+ :attr:`~BboxBase.ymin`).
271
+ """
272
+ return self.get_points()[0, 1]
273
+
274
+ @property
275
+ def x1(self):
276
+ """
277
+ The second of the pair of *x* coordinates that define the bounding box.
278
+
279
+ This is not guaranteed to be greater than :attr:`x0` (for that, use
280
+ :attr:`~BboxBase.xmax`).
281
+ """
282
+ return self.get_points()[1, 0]
283
+
284
+ @property
285
+ def y1(self):
286
+ """
287
+ The second of the pair of *y* coordinates that define the bounding box.
288
+
289
+ This is not guaranteed to be greater than :attr:`y0` (for that, use
290
+ :attr:`~BboxBase.ymax`).
291
+ """
292
+ return self.get_points()[1, 1]
293
+
294
+ @property
295
+ def p0(self):
296
+ """
297
+ The first pair of (*x*, *y*) coordinates that define the bounding box.
298
+
299
+ This is not guaranteed to be the bottom-left corner (for that, use
300
+ :attr:`~BboxBase.min`).
301
+ """
302
+ return self.get_points()[0]
303
+
304
+ @property
305
+ def p1(self):
306
+ """
307
+ The second pair of (*x*, *y*) coordinates that define the bounding box.
308
+
309
+ This is not guaranteed to be the top-right corner (for that, use
310
+ :attr:`~BboxBase.max`).
311
+ """
312
+ return self.get_points()[1]
313
+
314
+ @property
315
+ def xmin(self):
316
+ """The left edge of the bounding box."""
317
+ return np.min(self.get_points()[:, 0])
318
+
319
+ @property
320
+ def ymin(self):
321
+ """The bottom edge of the bounding box."""
322
+ return np.min(self.get_points()[:, 1])
323
+
324
+ @property
325
+ def xmax(self):
326
+ """The right edge of the bounding box."""
327
+ return np.max(self.get_points()[:, 0])
328
+
329
+ @property
330
+ def ymax(self):
331
+ """The top edge of the bounding box."""
332
+ return np.max(self.get_points()[:, 1])
333
+
334
+ @property
335
+ def min(self):
336
+ """The bottom-left corner of the bounding box."""
337
+ return np.min(self.get_points(), axis=0)
338
+
339
+ @property
340
+ def max(self):
341
+ """The top-right corner of the bounding box."""
342
+ return np.max(self.get_points(), axis=0)
343
+
344
+ @property
345
+ def intervalx(self):
346
+ """
347
+ The pair of *x* coordinates that define the bounding box.
348
+
349
+ This is not guaranteed to be sorted from left to right.
350
+ """
351
+ return self.get_points()[:, 0]
352
+
353
+ @property
354
+ def intervaly(self):
355
+ """
356
+ The pair of *y* coordinates that define the bounding box.
357
+
358
+ This is not guaranteed to be sorted from bottom to top.
359
+ """
360
+ return self.get_points()[:, 1]
361
+
362
+ @property
363
+ def width(self):
364
+ """The (signed) width of the bounding box."""
365
+ points = self.get_points()
366
+ return points[1, 0] - points[0, 0]
367
+
368
+ @property
369
+ def height(self):
370
+ """The (signed) height of the bounding box."""
371
+ points = self.get_points()
372
+ return points[1, 1] - points[0, 1]
373
+
374
+ @property
375
+ def size(self):
376
+ """The (signed) width and height of the bounding box."""
377
+ points = self.get_points()
378
+ return points[1] - points[0]
379
+
380
+ @property
381
+ def bounds(self):
382
+ """
383
+ Return (:attr:`x0`, :attr:`y0`, :attr:`~BboxBase.width`,
384
+ :attr:`~BboxBase.height`).
385
+ """
386
+ (x0, y0), (x1, y1) = self.get_points()
387
+ return (x0, y0, x1 - x0, y1 - y0)
388
+
389
+ @property
390
+ def extents(self):
391
+ """Return (:attr:`x0`, :attr:`y0`, :attr:`x1`, :attr:`y1`)."""
392
+ return self.get_points().flatten() # flatten returns a copy.
393
+
394
+ def get_points(self):
395
+ raise NotImplementedError
396
+
397
+ def _is_finite(self):
398
+ """
399
+ Return whether the bounding box is finite and not degenerate to a
400
+ single point.
401
+
402
+ We count the box as finite if neither width nor height are infinite
403
+ and at least one direction is non-zero; i.e. a point is not finite,
404
+ but a horizontal or vertical line is.
405
+
406
+ .. versionadded:: 3.11
407
+
408
+ Notes
409
+ -----
410
+ We keep this private for now because concise naming is hard and
411
+ because we are not sure how universal the concept is. It is
412
+ currently used only for filtering bboxes to be included in
413
+ tightbbox calculation, but I'm unsure whether single points
414
+ should be included there as well.
415
+ """
416
+ width = self.width
417
+ height = self.height
418
+ return (width > 0 or height > 0) and width < np.inf and height < np.inf
419
+
420
+ def containsx(self, x):
421
+ """
422
+ Return whether *x* is in the closed (:attr:`x0`, :attr:`x1`) interval.
423
+ """
424
+ x0, x1 = self.intervalx
425
+ return x0 <= x <= x1 or x0 >= x >= x1
426
+
427
+ def containsy(self, y):
428
+ """
429
+ Return whether *y* is in the closed (:attr:`y0`, :attr:`y1`) interval.
430
+ """
431
+ y0, y1 = self.intervaly
432
+ return y0 <= y <= y1 or y0 >= y >= y1
433
+
434
+ def contains(self, x, y):
435
+ """
436
+ Return whether ``(x, y)`` is in the bounding box or on its edge.
437
+ """
438
+ return self.containsx(x) and self.containsy(y)
439
+
440
+ def overlaps(self, other):
441
+ """
442
+ Return whether this bounding box overlaps with the other bounding box.
443
+
444
+ Parameters
445
+ ----------
446
+ other : `.BboxBase`
447
+ """
448
+ ax1, ay1, ax2, ay2 = self.extents
449
+ bx1, by1, bx2, by2 = other.extents
450
+ if ax2 < ax1:
451
+ ax2, ax1 = ax1, ax2
452
+ if ay2 < ay1:
453
+ ay2, ay1 = ay1, ay2
454
+ if bx2 < bx1:
455
+ bx2, bx1 = bx1, bx2
456
+ if by2 < by1:
457
+ by2, by1 = by1, by2
458
+ return ax1 <= bx2 and bx1 <= ax2 and ay1 <= by2 and by1 <= ay2
459
+
460
+ def fully_containsx(self, x):
461
+ """
462
+ Return whether *x* is in the open (:attr:`x0`, :attr:`x1`) interval.
463
+ """
464
+ x0, x1 = self.intervalx
465
+ return x0 < x < x1 or x0 > x > x1
466
+
467
+ def fully_containsy(self, y):
468
+ """
469
+ Return whether *y* is in the open (:attr:`y0`, :attr:`y1`) interval.
470
+ """
471
+ y0, y1 = self.intervaly
472
+ return y0 < y < y1 or y0 > y > y1
473
+
474
+ def fully_contains(self, x, y):
475
+ """
476
+ Return whether ``x, y`` is in the bounding box, but not on its edge.
477
+ """
478
+ return self.fully_containsx(x) and self.fully_containsy(y)
479
+
480
+ def fully_overlaps(self, other):
481
+ """
482
+ Return whether this bounding box overlaps with the other bounding box,
483
+ not including the edges.
484
+
485
+ Parameters
486
+ ----------
487
+ other : `.BboxBase`
488
+ """
489
+ ax1, ay1, ax2, ay2 = self.extents
490
+ bx1, by1, bx2, by2 = other.extents
491
+ if ax2 < ax1:
492
+ ax2, ax1 = ax1, ax2
493
+ if ay2 < ay1:
494
+ ay2, ay1 = ay1, ay2
495
+ if bx2 < bx1:
496
+ bx2, bx1 = bx1, bx2
497
+ if by2 < by1:
498
+ by2, by1 = by1, by2
499
+ return ax1 < bx2 and bx1 < ax2 and ay1 < by2 and by1 < ay2
500
+
501
+ def transformed(self, transform):
502
+ """
503
+ Construct a `Bbox` by statically transforming this one by *transform*.
504
+ """
505
+ pts = self.get_points()
506
+ ll, ul, lr = transform.transform(np.array(
507
+ [pts[0], [pts[0, 0], pts[1, 1]], [pts[1, 0], pts[0, 1]]]))
508
+ return Bbox([ll, [lr[0], ul[1]]])
509
+
510
+ coefs = {'C': (0.5, 0.5),
511
+ 'SW': (0, 0),
512
+ 'S': (0.5, 0),
513
+ 'SE': (1.0, 0),
514
+ 'E': (1.0, 0.5),
515
+ 'NE': (1.0, 1.0),
516
+ 'N': (0.5, 1.0),
517
+ 'NW': (0, 1.0),
518
+ 'W': (0, 0.5)}
519
+
520
+ def anchored(self, c, container):
521
+ """
522
+ Return a copy of the `Bbox` anchored to *c* within *container*.
523
+
524
+ Parameters
525
+ ----------
526
+ c : (float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', ...}
527
+ Either an (*x*, *y*) pair of relative coordinates (0 is left or
528
+ bottom, 1 is right or top), 'C' (center), or a cardinal direction
529
+ ('SW', southwest, is bottom left, etc.).
530
+ container : `Bbox`
531
+ The box within which the `Bbox` is positioned.
532
+
533
+ See Also
534
+ --------
535
+ .Axes.set_anchor
536
+ """
537
+ l, b, w, h = container.bounds
538
+ L, B, W, H = self.bounds
539
+ cx, cy = self.coefs[c] if isinstance(c, str) else c
540
+ return Bbox(self._points +
541
+ [(l + cx * (w - W)) - L,
542
+ (b + cy * (h - H)) - B])
543
+
544
+ def shrunk(self, mx, my):
545
+ """
546
+ Return a copy of the `Bbox`, shrunk by the factor *mx*
547
+ in the *x* direction and the factor *my* in the *y* direction.
548
+ The lower left corner of the box remains unchanged. Normally
549
+ *mx* and *my* will be less than 1, but this is not enforced.
550
+ """
551
+ w, h = self.size
552
+ return Bbox([self._points[0],
553
+ self._points[0] + [mx * w, my * h]])
554
+
555
+ def shrunk_to_aspect(self, box_aspect, container=None, fig_aspect=1.0):
556
+ """
557
+ Return a copy of the `Bbox`, shrunk so that it is as
558
+ large as it can be while having the desired aspect ratio,
559
+ *box_aspect*. If the box coordinates are relative (i.e.
560
+ fractions of a larger box such as a figure) then the
561
+ physical aspect ratio of that figure is specified with
562
+ *fig_aspect*, so that *box_aspect* can also be given as a
563
+ ratio of the absolute dimensions, not the relative dimensions.
564
+ """
565
+ if box_aspect <= 0 or fig_aspect <= 0:
566
+ raise ValueError("'box_aspect' and 'fig_aspect' must be positive")
567
+ if container is None:
568
+ container = self
569
+ w, h = container.size
570
+ H = w * box_aspect / fig_aspect
571
+ if H <= h:
572
+ W = w
573
+ else:
574
+ W = h * fig_aspect / box_aspect
575
+ H = h
576
+ return Bbox([self._points[0],
577
+ self._points[0] + (W, H)])
578
+
579
+ def splitx(self, *args):
580
+ """
581
+ Return a list of new `Bbox` objects formed by splitting the original
582
+ one with vertical lines at fractional positions given by *args*.
583
+ """
584
+ xf = [0, *args, 1]
585
+ x0, y0, x1, y1 = self.extents
586
+ w = x1 - x0
587
+ return [Bbox([[x0 + xf0 * w, y0], [x0 + xf1 * w, y1]])
588
+ for xf0, xf1 in itertools.pairwise(xf)]
589
+
590
+ def splity(self, *args):
591
+ """
592
+ Return a list of new `Bbox` objects formed by splitting the original
593
+ one with horizontal lines at fractional positions given by *args*.
594
+ """
595
+ yf = [0, *args, 1]
596
+ x0, y0, x1, y1 = self.extents
597
+ h = y1 - y0
598
+ return [Bbox([[x0, y0 + yf0 * h], [x1, y0 + yf1 * h]])
599
+ for yf0, yf1 in itertools.pairwise(yf)]
600
+
601
+ def count_contains(self, vertices):
602
+ """
603
+ Count the number of vertices contained in the `Bbox`.
604
+ Any vertices with a non-finite x or y value are ignored.
605
+
606
+ Parameters
607
+ ----------
608
+ vertices : (N, 2) array
609
+ """
610
+ if len(vertices) == 0:
611
+ return 0
612
+ vertices = np.asarray(vertices)
613
+ with np.errstate(invalid='ignore'):
614
+ return (((self.min < vertices) &
615
+ (vertices < self.max)).all(axis=1).sum())
616
+
617
+ def count_overlaps(self, bboxes):
618
+ """
619
+ Count the number of bounding boxes that overlap this one.
620
+
621
+ Parameters
622
+ ----------
623
+ bboxes : sequence of `.BboxBase`
624
+ """
625
+ return count_bboxes_overlapping_bbox(
626
+ self, np.atleast_3d([np.array(x) for x in bboxes]))
627
+
628
+ def expanded(self, sw, sh):
629
+ """
630
+ Construct a `Bbox` by expanding this one around its center by the
631
+ factors *sw* and *sh*.
632
+ """
633
+ width = self.width
634
+ height = self.height
635
+ deltaw = (sw * width - width) / 2.0
636
+ deltah = (sh * height - height) / 2.0
637
+ a = np.array([[-deltaw, -deltah], [deltaw, deltah]])
638
+ return Bbox(self._points + a)
639
+
640
+ def padded(self, w_pad, h_pad=None):
641
+ """
642
+ Construct a `Bbox` by padding this one on all four sides.
643
+
644
+ Parameters
645
+ ----------
646
+ w_pad : float
647
+ Width pad
648
+ h_pad : float, optional
649
+ Height pad. Defaults to *w_pad*.
650
+
651
+ """
652
+ points = self.get_points()
653
+ if h_pad is None:
654
+ h_pad = w_pad
655
+ return Bbox(points + [[-w_pad, -h_pad], [w_pad, h_pad]])
656
+
657
+ def translated(self, tx, ty):
658
+ """Construct a `Bbox` by translating this one by *tx* and *ty*."""
659
+ return Bbox(self._points + (tx, ty))
660
+
661
+ def corners(self):
662
+ """
663
+ Return the corners of this rectangle as an array of points.
664
+
665
+ Specifically, this returns the array
666
+ ``[[x0, y0], [x0, y1], [x1, y0], [x1, y1]]``.
667
+ """
668
+ (x0, y0), (x1, y1) = self.get_points()
669
+ return np.array([[x0, y0], [x0, y1], [x1, y0], [x1, y1]])
670
+
671
+ def rotated(self, radians):
672
+ """
673
+ Return the axes-aligned bounding box that bounds the result of rotating
674
+ this `Bbox` by an angle of *radians*.
675
+ """
676
+ corners = self.corners()
677
+ corners_rotated = Affine2D().rotate(radians).transform(corners)
678
+ bbox = Bbox.unit()
679
+ bbox.update_from_data_xy(corners_rotated, ignore=True)
680
+ return bbox
681
+
682
+ @staticmethod
683
+ def union(bboxes):
684
+ """Return a `Bbox` that contains all of the given *bboxes*."""
685
+ if not len(bboxes):
686
+ raise ValueError("'bboxes' cannot be empty")
687
+ x0 = np.min([bbox.xmin for bbox in bboxes])
688
+ x1 = np.max([bbox.xmax for bbox in bboxes])
689
+ y0 = np.min([bbox.ymin for bbox in bboxes])
690
+ y1 = np.max([bbox.ymax for bbox in bboxes])
691
+ return Bbox([[x0, y0], [x1, y1]])
692
+
693
+ @staticmethod
694
+ def intersection(bbox1, bbox2):
695
+ """
696
+ Return the intersection of *bbox1* and *bbox2* if they intersect, or
697
+ None if they don't.
698
+ """
699
+ x0 = np.maximum(bbox1.xmin, bbox2.xmin)
700
+ x1 = np.minimum(bbox1.xmax, bbox2.xmax)
701
+ y0 = np.maximum(bbox1.ymin, bbox2.ymin)
702
+ y1 = np.minimum(bbox1.ymax, bbox2.ymax)
703
+ return Bbox([[x0, y0], [x1, y1]]) if x0 <= x1 and y0 <= y1 else None
704
+
705
+
706
+ _default_minpos = np.array([np.inf, np.inf])
707
+
708
+
709
+ class Bbox(BboxBase):
710
+ """
711
+ A mutable bounding box.
712
+
713
+ Examples
714
+ --------
715
+ **Create from known bounds**
716
+
717
+ The default constructor takes the boundary "points" ``[[xmin, ymin],
718
+ [xmax, ymax]]``.
719
+
720
+ >>> Bbox([[1, 1], [3, 7]])
721
+ Bbox([[1.0, 1.0], [3.0, 7.0]])
722
+
723
+ Alternatively, a Bbox can be created from the flattened points array, the
724
+ so-called "extents" ``(xmin, ymin, xmax, ymax)``
725
+
726
+ >>> Bbox.from_extents(1, 1, 3, 7)
727
+ Bbox([[1.0, 1.0], [3.0, 7.0]])
728
+
729
+ or from the "bounds" ``(xmin, ymin, width, height)``.
730
+
731
+ >>> Bbox.from_bounds(1, 1, 2, 6)
732
+ Bbox([[1.0, 1.0], [3.0, 7.0]])
733
+
734
+ **Create from collections of points**
735
+
736
+ The "empty" object for accumulating Bboxs is the null bbox, which is a
737
+ stand-in for the empty set.
738
+
739
+ >>> Bbox.null()
740
+ Bbox([[inf, inf], [-inf, -inf]])
741
+
742
+ Adding points to the null bbox will give you the bbox of those points.
743
+
744
+ >>> box = Bbox.null()
745
+ >>> box.update_from_data_xy([[1, 1]])
746
+ >>> box
747
+ Bbox([[1.0, 1.0], [1.0, 1.0]])
748
+ >>> box.update_from_data_xy([[2, 3], [3, 2]], ignore=False)
749
+ >>> box
750
+ Bbox([[1.0, 1.0], [3.0, 3.0]])
751
+
752
+ Setting ``ignore=True`` is equivalent to starting over from a null bbox.
753
+
754
+ >>> box.update_from_data_xy([[1, 1]], ignore=True)
755
+ >>> box
756
+ Bbox([[1.0, 1.0], [1.0, 1.0]])
757
+
758
+ .. warning::
759
+
760
+ It is recommended to always specify ``ignore`` explicitly. If not, the
761
+ default value of ``ignore`` can be changed at any time by code with
762
+ access to your Bbox, for example using the method `~.Bbox.ignore`.
763
+
764
+ **Properties of the ``null`` bbox**
765
+
766
+ .. note::
767
+
768
+ The current behavior of `Bbox.null()` may be surprising as it does
769
+ not have all of the properties of the "empty set", and as such does
770
+ not behave like a "zero" object in the mathematical sense. We may
771
+ change that in the future (with a deprecation period).
772
+
773
+ The null bbox is the identity for intersections
774
+
775
+ >>> Bbox.intersection(Bbox([[1, 1], [3, 7]]), Bbox.null())
776
+ Bbox([[1.0, 1.0], [3.0, 7.0]])
777
+
778
+ except with itself, where it returns the full space.
779
+
780
+ >>> Bbox.intersection(Bbox.null(), Bbox.null())
781
+ Bbox([[-inf, -inf], [inf, inf]])
782
+
783
+ A union containing null will always return the full space (not the other
784
+ set!)
785
+
786
+ >>> Bbox.union([Bbox([[0, 0], [0, 0]]), Bbox.null()])
787
+ Bbox([[-inf, -inf], [inf, inf]])
788
+ """
789
+
790
+ def __init__(self, points, **kwargs):
791
+ """
792
+ Parameters
793
+ ----------
794
+ points : `~numpy.ndarray`
795
+ A (2, 2) array of the form ``[[x0, y0], [x1, y1]]``.
796
+ """
797
+ super().__init__(**kwargs)
798
+ points = np.asarray(points, float)
799
+ if points.shape != (2, 2):
800
+ raise ValueError('Bbox points must be of the form '
801
+ '"[[x0, y0], [x1, y1]]".')
802
+ self._points = points
803
+ self._minpos = _default_minpos.copy()
804
+ self._ignore = True
805
+ # it is helpful in some contexts to know if the bbox is a
806
+ # default or has been mutated; we store the orig points to
807
+ # support the mutated methods
808
+ self._points_orig = self._points.copy()
809
+ if DEBUG:
810
+ ___init__ = __init__
811
+
812
+ def __init__(self, points, **kwargs):
813
+ self._check(points)
814
+ self.___init__(points, **kwargs)
815
+
816
+ def invalidate(self):
817
+ self._check(self._points)
818
+ super().invalidate()
819
+
820
+ def frozen(self):
821
+ # docstring inherited
822
+ frozen_bbox = super().frozen()
823
+ frozen_bbox._minpos = self.minpos.copy()
824
+ return frozen_bbox
825
+
826
+ @staticmethod
827
+ def unit():
828
+ """Create a new unit `Bbox` from (0, 0) to (1, 1)."""
829
+ return Bbox([[0, 0], [1, 1]])
830
+
831
+ @staticmethod
832
+ def null():
833
+ """Create a new null `Bbox` from (inf, inf) to (-inf, -inf)."""
834
+ return Bbox([[np.inf, np.inf], [-np.inf, -np.inf]])
835
+
836
+ @staticmethod
837
+ def from_bounds(x0, y0, width, height):
838
+ """
839
+ Create a new `Bbox` from *x0*, *y0*, *width* and *height*.
840
+
841
+ *width* and *height* may be negative.
842
+ """
843
+ return Bbox.from_extents(x0, y0, x0 + width, y0 + height)
844
+
845
+ @staticmethod
846
+ def from_extents(*args, minpos=None):
847
+ """
848
+ Create a new Bbox from *left*, *bottom*, *right* and *top*.
849
+
850
+ The *y*-axis increases upwards.
851
+
852
+ Parameters
853
+ ----------
854
+ left, bottom, right, top : float
855
+ The four extents of the bounding box.
856
+ minpos : float or None
857
+ If this is supplied, the Bbox will have a minimum positive value
858
+ set. This is useful when dealing with logarithmic scales and other
859
+ scales where negative bounds result in floating point errors.
860
+ """
861
+ bbox = Bbox(np.asarray(args, dtype=float).reshape((2, 2)))
862
+ if minpos is not None:
863
+ bbox._minpos[:] = minpos
864
+ return bbox
865
+
866
+ def __format__(self, fmt):
867
+ return (
868
+ 'Bbox(x0={0.x0:{1}}, y0={0.y0:{1}}, x1={0.x1:{1}}, y1={0.y1:{1}})'.
869
+ format(self, fmt))
870
+
871
+ def __str__(self):
872
+ return format(self, '')
873
+
874
+ def __repr__(self):
875
+ return 'Bbox([[{0.x0}, {0.y0}], [{0.x1}, {0.y1}]])'.format(self)
876
+
877
+ def ignore(self, value):
878
+ """
879
+ Set whether the existing bounds of the box should be ignored
880
+ by subsequent calls to :meth:`update_from_data_xy`.
881
+
882
+ value : bool
883
+ - When ``True``, subsequent calls to `update_from_data_xy` will
884
+ ignore the existing bounds of the `Bbox`.
885
+ - When ``False``, subsequent calls to `update_from_data_xy` will
886
+ include the existing bounds of the `Bbox`.
887
+ """
888
+ self._ignore = value
889
+
890
+ def update_from_path(self, path, ignore=None, updatex=True, updatey=True):
891
+ """
892
+ Update the bounds of the `Bbox` to contain the vertices of the
893
+ provided path. After updating, the bounds will have positive *width*
894
+ and *height*; *x0* and *y0* will be the minimal values.
895
+
896
+ Parameters
897
+ ----------
898
+ path : `~matplotlib.path.Path`
899
+ ignore : bool, optional
900
+ - When ``True``, ignore the existing bounds of the `Bbox`.
901
+ - When ``False``, include the existing bounds of the `Bbox`.
902
+ - When ``None``, use the last value passed to :meth:`ignore`.
903
+ updatex, updatey : bool, default: True
904
+ When ``True``, update the x/y values.
905
+ """
906
+ if ignore is None:
907
+ ignore = self._ignore
908
+
909
+ if path.vertices.size == 0 or not (updatex or updatey):
910
+ return
911
+
912
+ if ignore:
913
+ points = np.array([[np.inf, np.inf], [-np.inf, -np.inf]])
914
+ minpos = np.array([np.inf, np.inf])
915
+ else:
916
+ points = self._points.copy()
917
+ minpos = self._minpos.copy()
918
+
919
+ valid_points = (np.isfinite(path.vertices[..., 0])
920
+ & np.isfinite(path.vertices[..., 1]))
921
+
922
+ if updatex:
923
+ x = path.vertices[..., 0][valid_points]
924
+ minx = np.min(x, initial=np.inf)
925
+ points[0, 0] = min(points[0, 0], minx)
926
+ points[1, 0] = max(points[1, 0], np.max(x, initial=-np.inf))
927
+ if minx > 0: # Fast path for all-positive x values
928
+ minpos[0] = min(minpos[0], minx)
929
+ else:
930
+ minpos[0] = min(minpos[0], np.min(x[x > 0], initial=np.inf))
931
+ if updatey:
932
+ y = path.vertices[..., 1][valid_points]
933
+ miny = np.min(y, initial=np.inf)
934
+ points[0, 1] = min(points[0, 1], miny)
935
+ points[1, 1] = max(points[1, 1], np.max(y, initial=-np.inf))
936
+ if miny > 0: # Fast path for all-positive y values
937
+ minpos[1] = min(minpos[1], miny)
938
+ else:
939
+ minpos[1] = min(minpos[1], np.min(y[y > 0], initial=np.inf))
940
+
941
+ if np.any(points != self._points) or np.any(minpos != self._minpos):
942
+ self.invalidate()
943
+ if updatex:
944
+ self._points[:, 0] = points[:, 0]
945
+ self._minpos[0] = minpos[0]
946
+ if updatey:
947
+ self._points[:, 1] = points[:, 1]
948
+ self._minpos[1] = minpos[1]
949
+
950
+ def update_from_data_x(self, x, ignore=None):
951
+ """
952
+ Update the x-bounds of the `Bbox` based on the passed in data. After
953
+ updating, the bounds will have positive *width*, and *x0* will be the
954
+ minimal value.
955
+
956
+ Parameters
957
+ ----------
958
+ x : `~numpy.ndarray`
959
+ Array of x-values.
960
+ ignore : bool, optional
961
+ - When ``True``, ignore the existing bounds of the `Bbox`.
962
+ - When ``False``, include the existing bounds of the `Bbox`.
963
+ - When ``None``, use the last value passed to :meth:`ignore`.
964
+ """
965
+ x = np.ravel(x)
966
+ # The y-component in np.array([x, *y*]).T is not used. We simply pass
967
+ # x again to not spend extra time on creating an array of unused data
968
+ self.update_from_data_xy(np.array([x, x]).T, ignore=ignore, updatey=False)
969
+
970
+ def update_from_data_y(self, y, ignore=None):
971
+ """
972
+ Update the y-bounds of the `Bbox` based on the passed in data. After
973
+ updating, the bounds will have positive *height*, and *y0* will be the
974
+ minimal value.
975
+
976
+ Parameters
977
+ ----------
978
+ y : `~numpy.ndarray`
979
+ Array of y-values.
980
+ ignore : bool, optional
981
+ - When ``True``, ignore the existing bounds of the `Bbox`.
982
+ - When ``False``, include the existing bounds of the `Bbox`.
983
+ - When ``None``, use the last value passed to :meth:`ignore`.
984
+ """
985
+ y = np.ravel(y)
986
+ # The x-component in np.array([*x*, y]).T is not used. We simply pass
987
+ # y again to not spend extra time on creating an array of unused data
988
+ self.update_from_data_xy(np.array([y, y]).T, ignore=ignore, updatex=False)
989
+
990
+ def update_from_data_xy(self, xy, ignore=None, updatex=True, updatey=True):
991
+ """
992
+ Update the `Bbox` bounds based on the passed in *xy* coordinates.
993
+
994
+ After updating, the bounds will have positive *width* and *height*;
995
+ *x0* and *y0* will be the minimal values.
996
+
997
+ Parameters
998
+ ----------
999
+ xy : (N, 2) array-like
1000
+ The (x, y) coordinates.
1001
+ ignore : bool, optional
1002
+ - When ``True``, ignore the existing bounds of the `Bbox`.
1003
+ - When ``False``, include the existing bounds of the `Bbox`.
1004
+ - When ``None``, use the last value passed to :meth:`ignore`.
1005
+ updatex, updatey : bool, default: True
1006
+ When ``True``, update the x/y values.
1007
+ """
1008
+ if len(xy) == 0:
1009
+ return
1010
+
1011
+ path = Path(xy)
1012
+ self.update_from_path(path, ignore=ignore,
1013
+ updatex=updatex, updatey=updatey)
1014
+
1015
+ @BboxBase.x0.setter
1016
+ def x0(self, val):
1017
+ self._points[0, 0] = val
1018
+ self.invalidate()
1019
+
1020
+ @BboxBase.y0.setter
1021
+ def y0(self, val):
1022
+ self._points[0, 1] = val
1023
+ self.invalidate()
1024
+
1025
+ @BboxBase.x1.setter
1026
+ def x1(self, val):
1027
+ self._points[1, 0] = val
1028
+ self.invalidate()
1029
+
1030
+ @BboxBase.y1.setter
1031
+ def y1(self, val):
1032
+ self._points[1, 1] = val
1033
+ self.invalidate()
1034
+
1035
+ @BboxBase.p0.setter
1036
+ def p0(self, val):
1037
+ self._points[0] = val
1038
+ self.invalidate()
1039
+
1040
+ @BboxBase.p1.setter
1041
+ def p1(self, val):
1042
+ self._points[1] = val
1043
+ self.invalidate()
1044
+
1045
+ @BboxBase.intervalx.setter
1046
+ def intervalx(self, interval):
1047
+ self._points[:, 0] = interval
1048
+ self.invalidate()
1049
+
1050
+ @BboxBase.intervaly.setter
1051
+ def intervaly(self, interval):
1052
+ self._points[:, 1] = interval
1053
+ self.invalidate()
1054
+
1055
+ @BboxBase.bounds.setter
1056
+ def bounds(self, bounds):
1057
+ l, b, w, h = bounds
1058
+ points = np.array([[l, b], [l + w, b + h]], float)
1059
+ if np.any(self._points != points):
1060
+ self._points = points
1061
+ self.invalidate()
1062
+
1063
+ @property
1064
+ def minpos(self):
1065
+ """
1066
+ The minimum positive value in both directions within the Bbox.
1067
+
1068
+ This is useful when dealing with logarithmic scales and other scales
1069
+ where negative bounds result in floating point errors, and will be used
1070
+ as the minimum extent instead of *p0*.
1071
+ """
1072
+ return self._minpos
1073
+
1074
+ @minpos.setter
1075
+ def minpos(self, val):
1076
+ self._minpos[:] = val
1077
+
1078
+ @property
1079
+ def minposx(self):
1080
+ """
1081
+ The minimum positive value in the *x*-direction within the Bbox.
1082
+
1083
+ This is useful when dealing with logarithmic scales and other scales
1084
+ where negative bounds result in floating point errors, and will be used
1085
+ as the minimum *x*-extent instead of *x0*.
1086
+ """
1087
+ return self._minpos[0]
1088
+
1089
+ @minposx.setter
1090
+ def minposx(self, val):
1091
+ self._minpos[0] = val
1092
+
1093
+ @property
1094
+ def minposy(self):
1095
+ """
1096
+ The minimum positive value in the *y*-direction within the Bbox.
1097
+
1098
+ This is useful when dealing with logarithmic scales and other scales
1099
+ where negative bounds result in floating point errors, and will be used
1100
+ as the minimum *y*-extent instead of *y0*.
1101
+ """
1102
+ return self._minpos[1]
1103
+
1104
+ @minposy.setter
1105
+ def minposy(self, val):
1106
+ self._minpos[1] = val
1107
+
1108
+ def get_points(self):
1109
+ """
1110
+ Get the points of the bounding box as an array of the form
1111
+ ``[[x0, y0], [x1, y1]]``.
1112
+ """
1113
+ self._invalid = 0
1114
+ return self._points
1115
+
1116
+ def set_points(self, points):
1117
+ """
1118
+ Set the points of the bounding box directly from an array of the form
1119
+ ``[[x0, y0], [x1, y1]]``. No error checking is performed, as this
1120
+ method is mainly for internal use.
1121
+ """
1122
+ if np.any(self._points != points):
1123
+ self._points = points
1124
+ self.invalidate()
1125
+
1126
+ def set(self, other):
1127
+ """
1128
+ Set this bounding box from the "frozen" bounds of another `Bbox`.
1129
+ """
1130
+ if np.any(self._points != other.get_points()):
1131
+ self._points = other.get_points()
1132
+ self.invalidate()
1133
+
1134
+ def mutated(self):
1135
+ """Return whether the bbox has changed since init."""
1136
+ return self.mutatedx() or self.mutatedy()
1137
+
1138
+ def mutatedx(self):
1139
+ """Return whether the x-limits have changed since init."""
1140
+ return (self._points[0, 0] != self._points_orig[0, 0] or
1141
+ self._points[1, 0] != self._points_orig[1, 0])
1142
+
1143
+ def mutatedy(self):
1144
+ """Return whether the y-limits have changed since init."""
1145
+ return (self._points[0, 1] != self._points_orig[0, 1] or
1146
+ self._points[1, 1] != self._points_orig[1, 1])
1147
+
1148
+
1149
+ class TransformedBbox(BboxBase):
1150
+ """
1151
+ A `Bbox` that is automatically transformed by a given
1152
+ transform. When either the child bounding box or transform
1153
+ changes, the bounds of this bbox will update accordingly.
1154
+ """
1155
+
1156
+ def __init__(self, bbox, transform, **kwargs):
1157
+ """
1158
+ Parameters
1159
+ ----------
1160
+ bbox : `Bbox`
1161
+ transform : `Transform`
1162
+ """
1163
+ _api.check_isinstance(BboxBase, bbox=bbox)
1164
+ _api.check_isinstance(Transform, transform=transform)
1165
+ if transform.input_dims != 2 or transform.output_dims != 2:
1166
+ raise ValueError(
1167
+ "The input and output dimensions of 'transform' must be 2")
1168
+
1169
+ super().__init__(**kwargs)
1170
+ self._bbox = bbox
1171
+ self._transform = transform
1172
+ self.set_children(bbox, transform)
1173
+ self._points = None
1174
+
1175
+ __str__ = _make_str_method("_bbox", "_transform")
1176
+
1177
+ def get_points(self):
1178
+ # docstring inherited
1179
+ if self._invalid:
1180
+ p = self._bbox.get_points()
1181
+ # Transform all four points, then make a new bounding box
1182
+ # from the result, taking care to make the orientation the
1183
+ # same.
1184
+ points = self._transform.transform(
1185
+ [[p[0, 0], p[0, 1]],
1186
+ [p[1, 0], p[0, 1]],
1187
+ [p[0, 0], p[1, 1]],
1188
+ [p[1, 0], p[1, 1]]])
1189
+ points = np.ma.filled(points, 0.0)
1190
+
1191
+ xs = min(points[:, 0]), max(points[:, 0])
1192
+ if p[0, 0] > p[1, 0]:
1193
+ xs = xs[::-1]
1194
+
1195
+ ys = min(points[:, 1]), max(points[:, 1])
1196
+ if p[0, 1] > p[1, 1]:
1197
+ ys = ys[::-1]
1198
+
1199
+ self._points = np.array([
1200
+ [xs[0], ys[0]],
1201
+ [xs[1], ys[1]]
1202
+ ])
1203
+
1204
+ self._invalid = 0
1205
+ return self._points
1206
+
1207
+ if DEBUG:
1208
+ _get_points = get_points
1209
+
1210
+ def get_points(self):
1211
+ points = self._get_points()
1212
+ self._check(points)
1213
+ return points
1214
+
1215
+ def contains(self, x, y):
1216
+ # Docstring inherited.
1217
+ return self._bbox.contains(*self._transform.inverted().transform((x, y)))
1218
+
1219
+ def fully_contains(self, x, y):
1220
+ # Docstring inherited.
1221
+ return self._bbox.fully_contains(*self._transform.inverted().transform((x, y)))
1222
+
1223
+
1224
+ class LockableBbox(BboxBase):
1225
+ """
1226
+ A `Bbox` where some elements may be locked at certain values.
1227
+
1228
+ When the child bounding box changes, the bounds of this bbox will update
1229
+ accordingly with the exception of the locked elements.
1230
+ """
1231
+ def __init__(self, bbox, x0=None, y0=None, x1=None, y1=None, **kwargs):
1232
+ """
1233
+ Parameters
1234
+ ----------
1235
+ bbox : `Bbox`
1236
+ The child bounding box to wrap.
1237
+
1238
+ x0 : float or None
1239
+ The locked value for x0, or None to leave unlocked.
1240
+
1241
+ y0 : float or None
1242
+ The locked value for y0, or None to leave unlocked.
1243
+
1244
+ x1 : float or None
1245
+ The locked value for x1, or None to leave unlocked.
1246
+
1247
+ y1 : float or None
1248
+ The locked value for y1, or None to leave unlocked.
1249
+
1250
+ """
1251
+ _api.check_isinstance(BboxBase, bbox=bbox)
1252
+ super().__init__(**kwargs)
1253
+ self._bbox = bbox
1254
+ self.set_children(bbox)
1255
+ self._points = None
1256
+ fp = [x0, y0, x1, y1]
1257
+ mask = [val is None for val in fp]
1258
+ self._locked_points = np.ma.array(fp, float, mask=mask).reshape((2, 2))
1259
+
1260
+ __str__ = _make_str_method("_bbox", "_locked_points")
1261
+
1262
+ def get_points(self):
1263
+ # docstring inherited
1264
+ if self._invalid:
1265
+ points = self._bbox.get_points()
1266
+ self._points = np.where(self._locked_points.mask,
1267
+ points,
1268
+ self._locked_points)
1269
+ self._invalid = 0
1270
+ return self._points
1271
+
1272
+ if DEBUG:
1273
+ _get_points = get_points
1274
+
1275
+ def get_points(self):
1276
+ points = self._get_points()
1277
+ self._check(points)
1278
+ return points
1279
+
1280
+ @property
1281
+ def locked_x0(self):
1282
+ """
1283
+ float or None: The value used for the locked x0.
1284
+ """
1285
+ if self._locked_points.mask[0, 0]:
1286
+ return None
1287
+ else:
1288
+ return self._locked_points[0, 0]
1289
+
1290
+ @locked_x0.setter
1291
+ def locked_x0(self, x0):
1292
+ self._locked_points.mask[0, 0] = x0 is None
1293
+ self._locked_points.data[0, 0] = x0
1294
+ self.invalidate()
1295
+
1296
+ @property
1297
+ def locked_y0(self):
1298
+ """
1299
+ float or None: The value used for the locked y0.
1300
+ """
1301
+ if self._locked_points.mask[0, 1]:
1302
+ return None
1303
+ else:
1304
+ return self._locked_points[0, 1]
1305
+
1306
+ @locked_y0.setter
1307
+ def locked_y0(self, y0):
1308
+ self._locked_points.mask[0, 1] = y0 is None
1309
+ self._locked_points.data[0, 1] = y0
1310
+ self.invalidate()
1311
+
1312
+ @property
1313
+ def locked_x1(self):
1314
+ """
1315
+ float or None: The value used for the locked x1.
1316
+ """
1317
+ if self._locked_points.mask[1, 0]:
1318
+ return None
1319
+ else:
1320
+ return self._locked_points[1, 0]
1321
+
1322
+ @locked_x1.setter
1323
+ def locked_x1(self, x1):
1324
+ self._locked_points.mask[1, 0] = x1 is None
1325
+ self._locked_points.data[1, 0] = x1
1326
+ self.invalidate()
1327
+
1328
+ @property
1329
+ def locked_y1(self):
1330
+ """
1331
+ float or None: The value used for the locked y1.
1332
+ """
1333
+ if self._locked_points.mask[1, 1]:
1334
+ return None
1335
+ else:
1336
+ return self._locked_points[1, 1]
1337
+
1338
+ @locked_y1.setter
1339
+ def locked_y1(self, y1):
1340
+ self._locked_points.mask[1, 1] = y1 is None
1341
+ self._locked_points.data[1, 1] = y1
1342
+ self.invalidate()
1343
+
1344
+
1345
+ class Transform(TransformNode):
1346
+ """
1347
+ The base class of all `TransformNode` instances that
1348
+ actually perform a transformation.
1349
+
1350
+ All non-affine transformations should be subclasses of this class.
1351
+ New affine transformations should be subclasses of `Affine2D`.
1352
+
1353
+ Subclasses of this class should override the following members (at
1354
+ minimum):
1355
+
1356
+ - :attr:`input_dims`
1357
+ - :attr:`output_dims`
1358
+ - :meth:`transform`
1359
+ - :meth:`inverted` (if an inverse exists)
1360
+
1361
+ The following attributes may be overridden if the default is unsuitable:
1362
+
1363
+ - :attr:`is_separable` (defaults to True for 1D -> 1D transforms, False
1364
+ otherwise)
1365
+ - :attr:`has_inverse` (defaults to True if :meth:`inverted` is overridden,
1366
+ False otherwise)
1367
+
1368
+ If the transform needs to do something non-standard with
1369
+ `matplotlib.path.Path` objects, such as adding curves
1370
+ where there were once line segments, it should override:
1371
+
1372
+ - :meth:`transform_path`
1373
+ """
1374
+
1375
+ input_dims = None
1376
+ """
1377
+ The number of input dimensions of this transform.
1378
+ Must be overridden (with integers) in the subclass.
1379
+ """
1380
+
1381
+ output_dims = None
1382
+ """
1383
+ The number of output dimensions of this transform.
1384
+ Must be overridden (with integers) in the subclass.
1385
+ """
1386
+
1387
+ is_separable = False
1388
+ """True if this transform is separable in the x- and y- dimensions."""
1389
+
1390
+ has_inverse = False
1391
+ """True if this transform has a corresponding inverse transform."""
1392
+
1393
+ def __init_subclass__(cls):
1394
+ # 1d transforms are always separable; we assume higher-dimensional ones
1395
+ # are not but subclasses can also directly set is_separable -- this is
1396
+ # verified by checking whether "is_separable" appears more than once in
1397
+ # the class's MRO (it appears once in Transform).
1398
+ if (sum("is_separable" in vars(parent) for parent in cls.__mro__) == 1
1399
+ and cls.input_dims == cls.output_dims == 1):
1400
+ cls.is_separable = True
1401
+ # Transform.inverted raises NotImplementedError; we assume that if this
1402
+ # is overridden then the transform is invertible but subclass can also
1403
+ # directly set has_inverse.
1404
+ if (sum("has_inverse" in vars(parent) for parent in cls.__mro__) == 1
1405
+ and hasattr(cls, "inverted")
1406
+ and cls.inverted is not Transform.inverted):
1407
+ cls.has_inverse = True
1408
+
1409
+ def __add__(self, other):
1410
+ """
1411
+ Compose two transforms together so that *self* is followed by *other*.
1412
+
1413
+ ``A + B`` returns a transform ``C`` so that
1414
+ ``C.transform(x) == B.transform(A.transform(x))``.
1415
+ """
1416
+ return (composite_transform_factory(self, other)
1417
+ if isinstance(other, Transform) else
1418
+ NotImplemented)
1419
+
1420
+ # Equality is based on object identity for `Transform`s (so we don't
1421
+ # override `__eq__`), but some subclasses, such as TransformWrapper &
1422
+ # AffineBase, override this behavior.
1423
+
1424
+ def _iter_break_from_left_to_right(self):
1425
+ """
1426
+ Return an iterator breaking down this transform stack from left to
1427
+ right recursively. If self == ((A, N), A) then the result will be an
1428
+ iterator which yields I : ((A, N), A), followed by A : (N, A),
1429
+ followed by (A, N) : (A), but not ((A, N), A) : I.
1430
+
1431
+ This is equivalent to flattening the stack then yielding
1432
+ ``flat_stack[:i], flat_stack[i:]`` where i=0..(n-1).
1433
+ """
1434
+ yield IdentityTransform(), self
1435
+
1436
+ @property
1437
+ def depth(self):
1438
+ """
1439
+ Return the number of transforms which have been chained
1440
+ together to form this Transform instance.
1441
+
1442
+ .. note::
1443
+
1444
+ For the special case of a Composite transform, the maximum depth
1445
+ of the two is returned.
1446
+
1447
+ """
1448
+ return 1
1449
+
1450
+ def contains_branch(self, other):
1451
+ """
1452
+ Return whether the given transform is a sub-tree of this transform.
1453
+
1454
+ This routine uses transform equality to identify sub-trees, therefore
1455
+ in many situations it is object id which will be used.
1456
+
1457
+ For the case where the given transform represents the whole
1458
+ of this transform, returns True.
1459
+ """
1460
+ if self.depth < other.depth:
1461
+ return False
1462
+
1463
+ # check that a subtree is equal to other (starting from self)
1464
+ for _, sub_tree in self._iter_break_from_left_to_right():
1465
+ if sub_tree == other:
1466
+ return True
1467
+ return False
1468
+
1469
+ def contains_branch_separately(self, other_transform):
1470
+ """
1471
+ Return whether the given branch is a sub-tree of this transform on
1472
+ each separate dimension.
1473
+
1474
+ A common use for this method is to identify if a transform is a blended
1475
+ transform containing an Axes' data transform. e.g.::
1476
+
1477
+ x_isdata, y_isdata = trans.contains_branch_separately(ax.transData)
1478
+
1479
+ """
1480
+ if self.output_dims != 2:
1481
+ raise ValueError('contains_branch_separately only supports '
1482
+ 'transforms with 2 output dimensions')
1483
+ # for a non-blended transform each separate dimension is the same, so
1484
+ # just return the appropriate shape.
1485
+ return (self.contains_branch(other_transform), ) * 2
1486
+
1487
+ # Permanent alias for backwards compatibility (historical typo)
1488
+ def contains_branch_seperately(self, other_transform):
1489
+ """:meta private:"""
1490
+ return self.contains_branch_separately(other_transform)
1491
+
1492
+ def __sub__(self, other):
1493
+ """
1494
+ Compose *self* with the inverse of *other*, cancelling identical terms
1495
+ if any::
1496
+
1497
+ # In general:
1498
+ A - B == A + B.inverted()
1499
+ # (but see note regarding frozen transforms below).
1500
+
1501
+ # If A "ends with" B (i.e. A == A' + B for some A') we can cancel
1502
+ # out B:
1503
+ (A' + B) - B == A'
1504
+
1505
+ # Likewise, if B "starts with" A (B = A + B'), we can cancel out A:
1506
+ A - (A + B') == B'.inverted() == B'^-1
1507
+
1508
+ Cancellation (rather than naively returning ``A + B.inverted()``) is
1509
+ important for multiple reasons:
1510
+
1511
+ - It avoids floating-point inaccuracies when computing the inverse of
1512
+ B: ``B - B`` is guaranteed to cancel out exactly (resulting in the
1513
+ identity transform), whereas ``B + B.inverted()`` may differ by a
1514
+ small epsilon.
1515
+ - ``B.inverted()`` always returns a frozen transform: if one computes
1516
+ ``A + B + B.inverted()`` and later mutates ``B``, then
1517
+ ``B.inverted()`` won't be updated and the last two terms won't cancel
1518
+ out anymore; on the other hand, ``A + B - B`` will always be equal to
1519
+ ``A`` even if ``B`` is mutated.
1520
+ """
1521
+ # we only know how to do this operation if other is a Transform.
1522
+ if not isinstance(other, Transform):
1523
+ return NotImplemented
1524
+ for remainder, sub_tree in self._iter_break_from_left_to_right():
1525
+ if sub_tree == other:
1526
+ return remainder
1527
+ for remainder, sub_tree in other._iter_break_from_left_to_right():
1528
+ if sub_tree == self:
1529
+ if not remainder.has_inverse:
1530
+ raise ValueError(
1531
+ "The shortcut cannot be computed since 'other' "
1532
+ "includes a non-invertible component")
1533
+ return remainder.inverted()
1534
+ # if we have got this far, then there was no shortcut possible
1535
+ if other.has_inverse:
1536
+ return self + other.inverted()
1537
+ else:
1538
+ raise ValueError('It is not possible to compute transA - transB '
1539
+ 'since transB cannot be inverted and there is no '
1540
+ 'shortcut possible.')
1541
+
1542
+ def __array__(self, *args, **kwargs):
1543
+ """Array interface to get at this Transform's affine matrix."""
1544
+ return self.get_affine().get_matrix()
1545
+
1546
+ def transform(self, values):
1547
+ """
1548
+ Apply this transformation on the given array of *values*.
1549
+
1550
+ Parameters
1551
+ ----------
1552
+ values : array-like
1553
+ The input values as an array of length :attr:`~Transform.input_dims` or
1554
+ shape (N, :attr:`~Transform.input_dims`).
1555
+
1556
+ Returns
1557
+ -------
1558
+ array
1559
+ The output values as an array of length :attr:`~Transform.output_dims` or
1560
+ shape (N, :attr:`~Transform.output_dims`), depending on the input.
1561
+ """
1562
+ # Ensure that values is a 2d array (but remember whether
1563
+ # we started with a 1d or 2d array).
1564
+ values = np.asanyarray(values)
1565
+ ndim = values.ndim
1566
+ values = values.reshape((-1, self.input_dims))
1567
+
1568
+ # Transform the values
1569
+ res = self.transform_affine(self.transform_non_affine(values))
1570
+
1571
+ # Convert the result back to the shape of the input values.
1572
+ if ndim == 0:
1573
+ assert not np.ma.is_masked(res) # just to be on the safe side
1574
+ return res[0, 0]
1575
+ if ndim == 1:
1576
+ return res.reshape(-1)
1577
+ elif ndim == 2:
1578
+ return res
1579
+ raise ValueError(
1580
+ "Input values must have shape (N, {dims}) or ({dims},)"
1581
+ .format(dims=self.input_dims))
1582
+
1583
+ def transform_affine(self, values):
1584
+ """
1585
+ Apply only the affine part of this transformation on the
1586
+ given array of values.
1587
+
1588
+ ``transform(values)`` is always equivalent to
1589
+ ``transform_affine(transform_non_affine(values))``.
1590
+
1591
+ In non-affine transformations, this is generally a no-op. In
1592
+ affine transformations, this is equivalent to
1593
+ ``transform(values)``.
1594
+
1595
+ Parameters
1596
+ ----------
1597
+ values : array
1598
+ The input values as an array of length :attr:`~Transform.input_dims` or
1599
+ shape (N, :attr:`~Transform.input_dims`).
1600
+
1601
+ Returns
1602
+ -------
1603
+ array
1604
+ The output values as an array of length :attr:`~Transform.output_dims` or
1605
+ shape (N, :attr:`~Transform.output_dims`), depending on the input.
1606
+ """
1607
+ return self.get_affine().transform(values)
1608
+
1609
+ def transform_non_affine(self, values):
1610
+ """
1611
+ Apply only the non-affine part of this transformation.
1612
+
1613
+ ``transform(values)`` is always equivalent to
1614
+ ``transform_affine(transform_non_affine(values))``.
1615
+
1616
+ In non-affine transformations, this is generally equivalent to
1617
+ ``transform(values)``. In affine transformations, this is
1618
+ always a no-op.
1619
+
1620
+ Parameters
1621
+ ----------
1622
+ values : array
1623
+ The input values as an array of length
1624
+ :attr:`~matplotlib.transforms.Transform.input_dims` or
1625
+ shape (N, :attr:`~matplotlib.transforms.Transform.input_dims`).
1626
+
1627
+ Returns
1628
+ -------
1629
+ array
1630
+ The output values as an array of length
1631
+ :attr:`~matplotlib.transforms.Transform.output_dims` or shape
1632
+ (N, :attr:`~matplotlib.transforms.Transform.output_dims`),
1633
+ depending on the input.
1634
+ """
1635
+ return values
1636
+
1637
+ def transform_bbox(self, bbox):
1638
+ """
1639
+ Transform the given bounding box.
1640
+
1641
+ For smarter transforms including caching (a common requirement in
1642
+ Matplotlib), see `TransformedBbox`.
1643
+ """
1644
+ return Bbox(self.transform(bbox.get_points()))
1645
+
1646
+ def get_affine(self):
1647
+ """Get the affine part of this transform."""
1648
+ return IdentityTransform()
1649
+
1650
+ def get_matrix(self):
1651
+ """Get the matrix for the affine part of this transform."""
1652
+ return self.get_affine().get_matrix()
1653
+
1654
+ def transform_point(self, point):
1655
+ """
1656
+ Return a transformed point.
1657
+
1658
+ This function is only kept for backcompatibility; the more general
1659
+ `.transform` method is capable of transforming both a list of points
1660
+ and a single point.
1661
+
1662
+ The point is given as a sequence of length :attr:`input_dims`.
1663
+ The transformed point is returned as a sequence of length
1664
+ :attr:`output_dims`.
1665
+ """
1666
+ if len(point) != self.input_dims:
1667
+ raise ValueError("The length of 'point' must be 'self.input_dims'")
1668
+ return self.transform(point)
1669
+
1670
+ def transform_path(self, path):
1671
+ """
1672
+ Apply the transform to `.Path` *path*, returning a new `.Path`.
1673
+
1674
+ In some cases, this transform may insert curves into the path
1675
+ that began as line segments.
1676
+ """
1677
+ return self.transform_path_affine(self.transform_path_non_affine(path))
1678
+
1679
+ def transform_path_affine(self, path):
1680
+ """
1681
+ Apply the affine part of this transform to `.Path` *path*, returning a
1682
+ new `.Path`.
1683
+
1684
+ ``transform_path(path)`` is equivalent to
1685
+ ``transform_path_affine(transform_path_non_affine(values))``.
1686
+ """
1687
+ return self.get_affine().transform_path_affine(path)
1688
+
1689
+ def transform_path_non_affine(self, path):
1690
+ """
1691
+ Apply the non-affine part of this transform to `.Path` *path*,
1692
+ returning a new `.Path`.
1693
+
1694
+ ``transform_path(path)`` is equivalent to
1695
+ ``transform_path_affine(transform_path_non_affine(values))``.
1696
+ """
1697
+ x = self.transform_non_affine(path.vertices)
1698
+ return Path._fast_from_codes_and_verts(x, path.codes, path)
1699
+
1700
+ def transform_angles(self, angles, pts, radians=False, pushoff=1e-5):
1701
+ """
1702
+ Transform a set of angles anchored at specific locations.
1703
+
1704
+ Parameters
1705
+ ----------
1706
+ angles : (N,) array-like
1707
+ The angles to transform.
1708
+ pts : (N, 2) array-like
1709
+ The points where the angles are anchored.
1710
+ radians : bool, default: False
1711
+ Whether *angles* are radians or degrees.
1712
+ pushoff : float
1713
+ For each point in *pts* and angle in *angles*, the transformed
1714
+ angle is computed by transforming a segment of length *pushoff*
1715
+ starting at that point and making that angle relative to the
1716
+ horizontal axis, and measuring the angle between the horizontal
1717
+ axis and the transformed segment.
1718
+
1719
+ Returns
1720
+ -------
1721
+ (N,) array
1722
+ """
1723
+ # Must be 2D
1724
+ if self.input_dims != 2 or self.output_dims != 2:
1725
+ raise NotImplementedError('Only defined in 2D')
1726
+ angles = np.asarray(angles)
1727
+ pts = np.asarray(pts)
1728
+ _api.check_shape((None, 2), pts=pts)
1729
+ _api.check_shape((None,), angles=angles)
1730
+ if len(angles) != len(pts):
1731
+ raise ValueError("There must be as many 'angles' as 'pts'")
1732
+ # Convert to radians if desired
1733
+ if not radians:
1734
+ angles = np.deg2rad(angles)
1735
+ # Move a short distance away
1736
+ pts2 = pts + pushoff * np.column_stack([np.cos(angles),
1737
+ np.sin(angles)])
1738
+ # Transform both sets of points
1739
+ tpts = self.transform(pts)
1740
+ tpts2 = self.transform(pts2)
1741
+ # Calculate transformed angles
1742
+ d = tpts2 - tpts
1743
+ a = np.arctan2(d[:, 1], d[:, 0])
1744
+ # Convert back to degrees if desired
1745
+ if not radians:
1746
+ a = np.rad2deg(a)
1747
+ return a
1748
+
1749
+ def inverted(self):
1750
+ """
1751
+ Return the corresponding inverse transformation.
1752
+
1753
+ It holds ``x == self.inverted().transform(self.transform(x))``.
1754
+
1755
+ The return value of this method should be treated as
1756
+ temporary. An update to *self* does not cause a corresponding
1757
+ update to its inverted copy.
1758
+ """
1759
+ raise NotImplementedError()
1760
+
1761
+
1762
+ class TransformWrapper(Transform):
1763
+ """
1764
+ A helper class that holds a single child transform and acts
1765
+ equivalently to it.
1766
+
1767
+ This is useful if a node of the transform tree must be replaced at
1768
+ run time with a transform of a different type. This class allows
1769
+ that replacement to correctly trigger invalidation.
1770
+
1771
+ `TransformWrapper` instances must have the same input and output dimensions
1772
+ during their entire lifetime, so the child transform may only be replaced
1773
+ with another child transform of the same dimensions.
1774
+ """
1775
+
1776
+ pass_through = True
1777
+
1778
+ def __init__(self, child):
1779
+ """
1780
+ *child*: A `Transform` instance. This child may later
1781
+ be replaced with :meth:`set`.
1782
+ """
1783
+ _api.check_isinstance(Transform, child=child)
1784
+ super().__init__()
1785
+ self.set(child)
1786
+
1787
+ def __eq__(self, other):
1788
+ return self._child.__eq__(other)
1789
+
1790
+ __str__ = _make_str_method("_child")
1791
+
1792
+ def frozen(self):
1793
+ # docstring inherited
1794
+ return self._child.frozen()
1795
+
1796
+ def set(self, child):
1797
+ """
1798
+ Replace the current child of this transform with another one.
1799
+
1800
+ The new child must have the same number of input and output
1801
+ dimensions as the current child.
1802
+ """
1803
+ if hasattr(self, "_child"): # Absent during init.
1804
+ self.invalidate()
1805
+ new_dims = (child.input_dims, child.output_dims)
1806
+ old_dims = (self._child.input_dims, self._child.output_dims)
1807
+ if new_dims != old_dims:
1808
+ raise ValueError(
1809
+ f"The input and output dims of the new child {new_dims} "
1810
+ f"do not match those of current child {old_dims}")
1811
+ self._child._parents.pop(id(self), None)
1812
+
1813
+ self._child = child
1814
+ self.set_children(child)
1815
+
1816
+ self.transform = child.transform
1817
+ self.transform_affine = child.transform_affine
1818
+ self.transform_non_affine = child.transform_non_affine
1819
+ self.transform_path = child.transform_path
1820
+ self.transform_path_affine = child.transform_path_affine
1821
+ self.transform_path_non_affine = child.transform_path_non_affine
1822
+ self.get_affine = child.get_affine
1823
+ self.inverted = child.inverted
1824
+ self.get_matrix = child.get_matrix
1825
+ # note we do not wrap other properties here since the transform's
1826
+ # child can be changed with WrappedTransform.set and so checking
1827
+ # is_affine and other such properties may be dangerous.
1828
+
1829
+ self._invalid = 0
1830
+ self.invalidate()
1831
+ self._invalid = 0
1832
+
1833
+ input_dims = property(lambda self: self._child.input_dims)
1834
+ output_dims = property(lambda self: self._child.output_dims)
1835
+ is_affine = property(lambda self: self._child.is_affine)
1836
+ is_separable = property(lambda self: self._child.is_separable)
1837
+ has_inverse = property(lambda self: self._child.has_inverse)
1838
+
1839
+
1840
+ class AffineBase(Transform):
1841
+ """
1842
+ The base class of all affine transformations of any number of dimensions.
1843
+ """
1844
+ is_affine = True
1845
+
1846
+ def __init__(self, *args, **kwargs):
1847
+ super().__init__(*args, **kwargs)
1848
+ self._inverted = None
1849
+
1850
+ def __array__(self, *args, **kwargs):
1851
+ # optimises the access of the transform matrix vs. the superclass
1852
+ return self.get_matrix()
1853
+
1854
+ def __eq__(self, other):
1855
+ if getattr(other, "is_affine", False) and hasattr(other, "get_matrix"):
1856
+ return (self.get_matrix() == other.get_matrix()).all()
1857
+ return NotImplemented
1858
+
1859
+ def transform(self, values):
1860
+ # docstring inherited
1861
+ return self.transform_affine(values)
1862
+
1863
+ def transform_affine(self, values):
1864
+ # docstring inherited
1865
+ raise NotImplementedError('Affine subclasses should override this '
1866
+ 'method.')
1867
+
1868
+ def transform_non_affine(self, values):
1869
+ # docstring inherited
1870
+ return values
1871
+
1872
+ def transform_path(self, path):
1873
+ # docstring inherited
1874
+ return self.transform_path_affine(path)
1875
+
1876
+ def transform_path_affine(self, path):
1877
+ # docstring inherited
1878
+ return Path(self.transform_affine(path.vertices),
1879
+ path.codes, path._interpolation_steps)
1880
+
1881
+ def transform_path_non_affine(self, path):
1882
+ # docstring inherited
1883
+ return path
1884
+
1885
+ def get_affine(self):
1886
+ # docstring inherited
1887
+ return self
1888
+
1889
+
1890
+ class Affine2DBase(AffineBase):
1891
+ """
1892
+ The base class of all 2D affine transformations.
1893
+
1894
+ 2D affine transformations are performed using a 3x3 numpy array::
1895
+
1896
+ a c e
1897
+ b d f
1898
+ 0 0 1
1899
+
1900
+ This class provides the read-only interface. For a mutable 2D
1901
+ affine transformation, use `Affine2D`.
1902
+
1903
+ Subclasses of this class will generally only need to override a
1904
+ constructor and `~.Transform.get_matrix` that generates a custom 3x3 matrix.
1905
+ """
1906
+ input_dims = 2
1907
+ output_dims = 2
1908
+
1909
+ def frozen(self):
1910
+ # docstring inherited
1911
+ return Affine2D(self.get_matrix().copy())
1912
+
1913
+ @property
1914
+ def is_separable(self):
1915
+ mtx = self.get_matrix()
1916
+ return mtx[0, 1] == mtx[1, 0] == 0.0
1917
+
1918
+ def to_values(self):
1919
+ """
1920
+ Return the values of the matrix as an ``(a, b, c, d, e, f)`` tuple.
1921
+ """
1922
+ mtx = self.get_matrix()
1923
+ return tuple(mtx[:2].swapaxes(0, 1).flat)
1924
+
1925
+ def transform_affine(self, values):
1926
+ mtx = self.get_matrix()
1927
+ if isinstance(values, np.ma.MaskedArray):
1928
+ tpoints = affine_transform(values.data, mtx)
1929
+ return np.ma.MaskedArray(tpoints, mask=np.ma.getmask(values))
1930
+ return affine_transform(values, mtx)
1931
+
1932
+ if DEBUG:
1933
+ _transform_affine = transform_affine
1934
+
1935
+ def transform_affine(self, values):
1936
+ # docstring inherited
1937
+ # The major speed trap here is just converting to the
1938
+ # points to an array in the first place. If we can use
1939
+ # more arrays upstream, that should help here.
1940
+ if not isinstance(values, np.ndarray):
1941
+ _api.warn_external(
1942
+ f'A non-numpy array of type {type(values)} was passed in '
1943
+ f'for transformation, which results in poor performance.')
1944
+ return self._transform_affine(values)
1945
+
1946
+ def inverted(self):
1947
+ # docstring inherited
1948
+ if self._inverted is None or self._invalid:
1949
+ mtx = self.get_matrix()
1950
+ shorthand_name = None
1951
+ if self._shorthand_name:
1952
+ shorthand_name = '(%s)-1' % self._shorthand_name
1953
+ self._inverted = Affine2D(inv(mtx), shorthand_name=shorthand_name)
1954
+ self._invalid = 0
1955
+ return self._inverted
1956
+
1957
+
1958
+ class Affine2D(Affine2DBase):
1959
+ """
1960
+ A mutable 2D affine transformation.
1961
+ """
1962
+
1963
+ def __init__(self, matrix=None, **kwargs):
1964
+ """
1965
+ Initialize an Affine transform from a 3x3 numpy float array::
1966
+
1967
+ a c e
1968
+ b d f
1969
+ 0 0 1
1970
+
1971
+ If *matrix* is None, initialize with the identity transform.
1972
+ """
1973
+ super().__init__(**kwargs)
1974
+ if matrix is None:
1975
+ # A bit faster than np.identity(3).
1976
+ matrix = IdentityTransform._mtx
1977
+ self._mtx = matrix.copy()
1978
+ self._invalid = 0
1979
+
1980
+ _base_str = _make_str_method("_mtx")
1981
+
1982
+ def __str__(self):
1983
+ return (self._base_str()
1984
+ if (self._mtx != np.diag(np.diag(self._mtx))).any()
1985
+ else f"Affine2D().scale({self._mtx[0, 0]}, {self._mtx[1, 1]})"
1986
+ if self._mtx[0, 0] != self._mtx[1, 1]
1987
+ else f"Affine2D().scale({self._mtx[0, 0]})")
1988
+
1989
+ @staticmethod
1990
+ def from_values(a, b, c, d, e, f):
1991
+ """
1992
+ Create a new Affine2D instance from the given values::
1993
+
1994
+ a c e
1995
+ b d f
1996
+ 0 0 1
1997
+
1998
+ .
1999
+ """
2000
+ return Affine2D(
2001
+ np.array([a, c, e, b, d, f, 0.0, 0.0, 1.0], float).reshape((3, 3)))
2002
+
2003
+ def get_matrix(self):
2004
+ """
2005
+ Get the underlying transformation matrix as a 3x3 array::
2006
+
2007
+ a c e
2008
+ b d f
2009
+ 0 0 1
2010
+
2011
+ .
2012
+ """
2013
+ if self._invalid:
2014
+ self._inverted = None
2015
+ self._invalid = 0
2016
+ return self._mtx
2017
+
2018
+ def set_matrix(self, mtx):
2019
+ """
2020
+ Set the underlying transformation matrix from a 3x3 array::
2021
+
2022
+ a c e
2023
+ b d f
2024
+ 0 0 1
2025
+
2026
+ .
2027
+ """
2028
+ self._mtx = mtx
2029
+ self.invalidate()
2030
+
2031
+ def set(self, other):
2032
+ """
2033
+ Set this transformation from the frozen copy of another
2034
+ `Affine2DBase` object.
2035
+ """
2036
+ _api.check_isinstance(Affine2DBase, other=other)
2037
+ self._mtx = other.get_matrix()
2038
+ self.invalidate()
2039
+
2040
+ def clear(self):
2041
+ """
2042
+ Reset the underlying matrix to the identity transform.
2043
+ """
2044
+ # A bit faster than np.identity(3).
2045
+ self._mtx = IdentityTransform._mtx.copy()
2046
+ self.invalidate()
2047
+ return self
2048
+
2049
+ def rotate(self, theta):
2050
+ """
2051
+ Add a rotation (in radians) to this transform in place.
2052
+
2053
+ Returns *self*, so this method can easily be chained with more
2054
+ calls to :meth:`rotate`, :meth:`rotate_deg`, :meth:`translate`
2055
+ and :meth:`scale`.
2056
+ """
2057
+ a = math.cos(theta)
2058
+ b = math.sin(theta)
2059
+ mtx = self._mtx
2060
+ # Operating and assigning one scalar at a time is much faster.
2061
+ (xx, xy, x0), (yx, yy, y0), _ = mtx.tolist()
2062
+ # mtx = [[a -b 0], [b a 0], [0 0 1]] * mtx
2063
+ mtx[0, 0] = a * xx - b * yx
2064
+ mtx[0, 1] = a * xy - b * yy
2065
+ mtx[0, 2] = a * x0 - b * y0
2066
+ mtx[1, 0] = b * xx + a * yx
2067
+ mtx[1, 1] = b * xy + a * yy
2068
+ mtx[1, 2] = b * x0 + a * y0
2069
+ self.invalidate()
2070
+ return self
2071
+
2072
+ def rotate_deg(self, degrees):
2073
+ """
2074
+ Add a rotation (in degrees) to this transform in place.
2075
+
2076
+ Returns *self*, so this method can easily be chained with more
2077
+ calls to :meth:`rotate`, :meth:`rotate_deg`, :meth:`translate`
2078
+ and :meth:`scale`.
2079
+ """
2080
+ return self.rotate(math.radians(degrees))
2081
+
2082
+ def rotate_around(self, x, y, theta):
2083
+ """
2084
+ Add a rotation (in radians) around the point (x, y) in place.
2085
+
2086
+ Returns *self*, so this method can easily be chained with more
2087
+ calls to :meth:`rotate`, :meth:`rotate_deg`, :meth:`translate`
2088
+ and :meth:`scale`.
2089
+ """
2090
+ return self.translate(-x, -y).rotate(theta).translate(x, y)
2091
+
2092
+ def rotate_deg_around(self, x, y, degrees):
2093
+ """
2094
+ Add a rotation (in degrees) around the point (x, y) in place.
2095
+
2096
+ Returns *self*, so this method can easily be chained with more
2097
+ calls to :meth:`rotate`, :meth:`rotate_deg`, :meth:`translate`
2098
+ and :meth:`scale`.
2099
+ """
2100
+ # Cast to float to avoid wraparound issues with uint8's
2101
+ x, y = float(x), float(y)
2102
+ return self.translate(-x, -y).rotate_deg(degrees).translate(x, y)
2103
+
2104
+ def translate(self, tx, ty):
2105
+ """
2106
+ Add a translation in place.
2107
+
2108
+ Returns *self*, so this method can easily be chained with more
2109
+ calls to :meth:`rotate`, :meth:`rotate_deg`, :meth:`translate`
2110
+ and :meth:`scale`.
2111
+ """
2112
+ self._mtx[0, 2] += tx
2113
+ self._mtx[1, 2] += ty
2114
+ self.invalidate()
2115
+ return self
2116
+
2117
+ def scale(self, sx, sy=None):
2118
+ """
2119
+ Add a scale in place.
2120
+
2121
+ If *sy* is None, the same scale is applied in both the *x*- and
2122
+ *y*-directions.
2123
+
2124
+ Returns *self*, so this method can easily be chained with more
2125
+ calls to :meth:`rotate`, :meth:`rotate_deg`, :meth:`translate`
2126
+ and :meth:`scale`.
2127
+ """
2128
+ if sy is None:
2129
+ sy = sx
2130
+ # explicit element-wise scaling is fastest
2131
+ self._mtx[0, 0] *= sx
2132
+ self._mtx[0, 1] *= sx
2133
+ self._mtx[0, 2] *= sx
2134
+ self._mtx[1, 0] *= sy
2135
+ self._mtx[1, 1] *= sy
2136
+ self._mtx[1, 2] *= sy
2137
+ self.invalidate()
2138
+ return self
2139
+
2140
+ def skew(self, xShear, yShear):
2141
+ """
2142
+ Add a skew in place.
2143
+
2144
+ *xShear* and *yShear* are the shear angles along the *x*- and
2145
+ *y*-axes, respectively, in radians.
2146
+
2147
+ Returns *self*, so this method can easily be chained with more
2148
+ calls to :meth:`rotate`, :meth:`rotate_deg`, :meth:`translate`
2149
+ and :meth:`scale`.
2150
+ """
2151
+ rx = math.tan(xShear)
2152
+ ry = math.tan(yShear)
2153
+ mtx = self._mtx
2154
+ # Operating and assigning one scalar at a time is much faster.
2155
+ (xx, xy, x0), (yx, yy, y0), _ = mtx.tolist()
2156
+ # mtx = [[1 rx 0], [ry 1 0], [0 0 1]] * mtx
2157
+ mtx[0, 0] += rx * yx
2158
+ mtx[0, 1] += rx * yy
2159
+ mtx[0, 2] += rx * y0
2160
+ mtx[1, 0] += ry * xx
2161
+ mtx[1, 1] += ry * xy
2162
+ mtx[1, 2] += ry * x0
2163
+ self.invalidate()
2164
+ return self
2165
+
2166
+ def skew_deg(self, xShear, yShear):
2167
+ """
2168
+ Add a skew in place.
2169
+
2170
+ *xShear* and *yShear* are the shear angles along the *x*- and
2171
+ *y*-axes, respectively, in degrees.
2172
+
2173
+ Returns *self*, so this method can easily be chained with more
2174
+ calls to :meth:`rotate`, :meth:`rotate_deg`, :meth:`translate`
2175
+ and :meth:`scale`.
2176
+ """
2177
+ return self.skew(math.radians(xShear), math.radians(yShear))
2178
+
2179
+
2180
+ class IdentityTransform(Affine2DBase):
2181
+ """
2182
+ A special class that does one thing, the identity transform, in a
2183
+ fast way.
2184
+ """
2185
+ _mtx = np.identity(3)
2186
+
2187
+ def frozen(self):
2188
+ # docstring inherited
2189
+ return self
2190
+
2191
+ __str__ = _make_str_method()
2192
+
2193
+ def get_matrix(self):
2194
+ # docstring inherited
2195
+ return self._mtx
2196
+
2197
+ def transform(self, values):
2198
+ # docstring inherited
2199
+ return np.asanyarray(values)
2200
+
2201
+ def transform_affine(self, values):
2202
+ # docstring inherited
2203
+ return np.asanyarray(values)
2204
+
2205
+ def transform_non_affine(self, values):
2206
+ # docstring inherited
2207
+ return np.asanyarray(values)
2208
+
2209
+ def transform_path(self, path):
2210
+ # docstring inherited
2211
+ return path
2212
+
2213
+ def transform_path_affine(self, path):
2214
+ # docstring inherited
2215
+ return path
2216
+
2217
+ def transform_path_non_affine(self, path):
2218
+ # docstring inherited
2219
+ return path
2220
+
2221
+ def get_affine(self):
2222
+ # docstring inherited
2223
+ return self
2224
+
2225
+ def inverted(self):
2226
+ # docstring inherited
2227
+ return self
2228
+
2229
+
2230
+ class _BlendedMixin:
2231
+ """Common methods for `BlendedGenericTransform` and `BlendedAffine2D`."""
2232
+
2233
+ def __eq__(self, other):
2234
+ if isinstance(other, (BlendedAffine2D, BlendedGenericTransform)):
2235
+ return (self._x == other._x) and (self._y == other._y)
2236
+ elif self._x == self._y:
2237
+ return self._x == other
2238
+ else:
2239
+ return NotImplemented
2240
+
2241
+ def contains_branch_separately(self, transform):
2242
+ return (self._x.contains_branch(transform),
2243
+ self._y.contains_branch(transform))
2244
+
2245
+ __str__ = _make_str_method("_x", "_y")
2246
+
2247
+
2248
+ class BlendedGenericTransform(_BlendedMixin, Transform):
2249
+ """
2250
+ A "blended" transform uses one transform for the *x*-direction, and
2251
+ another transform for the *y*-direction.
2252
+
2253
+ This "generic" version can handle any given child transform in the
2254
+ *x*- and *y*-directions.
2255
+ """
2256
+ input_dims = 2
2257
+ output_dims = 2
2258
+ is_separable = True
2259
+ pass_through = True
2260
+
2261
+ def __init__(self, x_transform, y_transform, **kwargs):
2262
+ """
2263
+ Create a new "blended" transform using *x_transform* to transform the
2264
+ *x*-axis and *y_transform* to transform the *y*-axis.
2265
+
2266
+ You will generally not call this constructor directly but use the
2267
+ `blended_transform_factory` function instead, which can determine
2268
+ automatically which kind of blended transform to create.
2269
+ """
2270
+ Transform.__init__(self, **kwargs)
2271
+ self._x = x_transform
2272
+ self._y = y_transform
2273
+ self.set_children(x_transform, y_transform)
2274
+ self._affine = None
2275
+
2276
+ @property
2277
+ def depth(self):
2278
+ return max(self._x.depth, self._y.depth)
2279
+
2280
+ def contains_branch(self, other):
2281
+ # A blended transform cannot possibly contain a branch from two
2282
+ # different transforms.
2283
+ return False
2284
+
2285
+ is_affine = property(lambda self: self._x.is_affine and self._y.is_affine)
2286
+ has_inverse = property(
2287
+ lambda self: self._x.has_inverse and self._y.has_inverse)
2288
+
2289
+ def frozen(self):
2290
+ # docstring inherited
2291
+ return blended_transform_factory(self._x.frozen(), self._y.frozen())
2292
+
2293
+ def transform_non_affine(self, values):
2294
+ # docstring inherited
2295
+ if self._x.is_affine and self._y.is_affine:
2296
+ return values
2297
+ x = self._x
2298
+ y = self._y
2299
+
2300
+ if x == y and x.input_dims == 2:
2301
+ return x.transform_non_affine(values)
2302
+
2303
+ if x.input_dims == 2:
2304
+ x_points = x.transform_non_affine(values)[:, 0:1]
2305
+ else:
2306
+ x_points = x.transform_non_affine(values[:, 0])
2307
+ x_points = x_points.reshape((len(x_points), 1))
2308
+
2309
+ if y.input_dims == 2:
2310
+ y_points = y.transform_non_affine(values)[:, 1:]
2311
+ else:
2312
+ y_points = y.transform_non_affine(values[:, 1])
2313
+ y_points = y_points.reshape((len(y_points), 1))
2314
+
2315
+ if (isinstance(x_points, np.ma.MaskedArray) or
2316
+ isinstance(y_points, np.ma.MaskedArray)):
2317
+ return np.ma.concatenate((x_points, y_points), 1)
2318
+ else:
2319
+ return np.concatenate((x_points, y_points), 1)
2320
+
2321
+ def inverted(self):
2322
+ # docstring inherited
2323
+ return BlendedGenericTransform(self._x.inverted(), self._y.inverted())
2324
+
2325
+ def get_affine(self):
2326
+ # docstring inherited
2327
+ if self._invalid or self._affine is None:
2328
+ if self._x == self._y:
2329
+ self._affine = self._x.get_affine()
2330
+ else:
2331
+ x_mtx = self._x.get_affine().get_matrix()
2332
+ y_mtx = self._y.get_affine().get_matrix()
2333
+ # We already know the transforms are separable, so we can skip
2334
+ # setting b and c to zero.
2335
+ mtx = np.array([x_mtx[0], y_mtx[1], [0.0, 0.0, 1.0]])
2336
+ self._affine = Affine2D(mtx)
2337
+ self._invalid = 0
2338
+ return self._affine
2339
+
2340
+
2341
+ class BlendedAffine2D(_BlendedMixin, Affine2DBase):
2342
+ """
2343
+ A "blended" transform uses one transform for the *x*-direction, and
2344
+ another transform for the *y*-direction.
2345
+
2346
+ This version is an optimization for the case where both child
2347
+ transforms are of type `Affine2DBase`.
2348
+ """
2349
+
2350
+ is_separable = True
2351
+
2352
+ def __init__(self, x_transform, y_transform, **kwargs):
2353
+ """
2354
+ Create a new "blended" transform using *x_transform* to transform the
2355
+ *x*-axis and *y_transform* to transform the *y*-axis.
2356
+
2357
+ Both *x_transform* and *y_transform* must be 2D affine transforms.
2358
+
2359
+ You will generally not call this constructor directly but use the
2360
+ `blended_transform_factory` function instead, which can determine
2361
+ automatically which kind of blended transform to create.
2362
+ """
2363
+ is_affine = x_transform.is_affine and y_transform.is_affine
2364
+ is_separable = x_transform.is_separable and y_transform.is_separable
2365
+ is_correct = is_affine and is_separable
2366
+ if not is_correct:
2367
+ raise ValueError("Both *x_transform* and *y_transform* must be 2D "
2368
+ "affine transforms")
2369
+
2370
+ Transform.__init__(self, **kwargs)
2371
+ self._x = x_transform
2372
+ self._y = y_transform
2373
+ self.set_children(x_transform, y_transform)
2374
+
2375
+ Affine2DBase.__init__(self)
2376
+ self._mtx = None
2377
+
2378
+ def get_matrix(self):
2379
+ # docstring inherited
2380
+ if self._invalid:
2381
+ if self._x == self._y:
2382
+ self._mtx = self._x.get_matrix()
2383
+ else:
2384
+ x_mtx = self._x.get_matrix()
2385
+ y_mtx = self._y.get_matrix()
2386
+ # We already know the transforms are separable, so we can skip
2387
+ # setting b and c to zero.
2388
+ self._mtx = np.array([x_mtx[0], y_mtx[1], [0.0, 0.0, 1.0]])
2389
+ self._inverted = None
2390
+ self._invalid = 0
2391
+ return self._mtx
2392
+
2393
+
2394
+ def blended_transform_factory(x_transform, y_transform):
2395
+ """
2396
+ Create a new "blended" transform using *x_transform* to transform
2397
+ the *x*-axis and *y_transform* to transform the *y*-axis.
2398
+
2399
+ A faster version of the blended transform is returned for the case
2400
+ where both child transforms are affine.
2401
+ """
2402
+ if (isinstance(x_transform, Affine2DBase) and
2403
+ isinstance(y_transform, Affine2DBase)):
2404
+ return BlendedAffine2D(x_transform, y_transform)
2405
+ return BlendedGenericTransform(x_transform, y_transform)
2406
+
2407
+
2408
+ class CompositeGenericTransform(Transform):
2409
+ """
2410
+ A composite transform formed by applying transform *a* then
2411
+ transform *b*.
2412
+
2413
+ This "generic" version can handle any two arbitrary
2414
+ transformations.
2415
+ """
2416
+ pass_through = True
2417
+
2418
+ def __init__(self, a, b, **kwargs):
2419
+ """
2420
+ Create a new composite transform that is the result of
2421
+ applying transform *a* then transform *b*.
2422
+
2423
+ You will generally not call this constructor directly but write ``a +
2424
+ b`` instead, which will automatically choose the best kind of composite
2425
+ transform instance to create.
2426
+ """
2427
+ if a.output_dims != b.input_dims:
2428
+ raise ValueError("The output dimension of 'a' must be equal to "
2429
+ "the input dimensions of 'b'")
2430
+ self.input_dims = a.input_dims
2431
+ self.output_dims = b.output_dims
2432
+
2433
+ super().__init__(**kwargs)
2434
+ self._a = a
2435
+ self._b = b
2436
+ self.set_children(a, b)
2437
+
2438
+ def frozen(self):
2439
+ # docstring inherited
2440
+ self._invalid = 0
2441
+ frozen = composite_transform_factory(
2442
+ self._a.frozen(), self._b.frozen())
2443
+ if not isinstance(frozen, CompositeGenericTransform):
2444
+ return frozen.frozen()
2445
+ return frozen
2446
+
2447
+ def _invalidate_internal(self, level, invalidating_node):
2448
+ # When the left child is invalidated at AFFINE_ONLY level and the right child is
2449
+ # non-affine, the composite transform is FULLY invalidated.
2450
+ if invalidating_node is self._a and not self._b.is_affine:
2451
+ level = Transform._INVALID_FULL
2452
+ super()._invalidate_internal(level, invalidating_node)
2453
+
2454
+ def __eq__(self, other):
2455
+ if isinstance(other, (CompositeGenericTransform, CompositeAffine2D)):
2456
+ return self is other or (self._a == other._a
2457
+ and self._b == other._b)
2458
+ else:
2459
+ return False
2460
+
2461
+ def _iter_break_from_left_to_right(self):
2462
+ for left, right in self._a._iter_break_from_left_to_right():
2463
+ yield left, right + self._b
2464
+ for left, right in self._b._iter_break_from_left_to_right():
2465
+ yield self._a + left, right
2466
+
2467
+ def contains_branch_separately(self, other_transform):
2468
+ # docstring inherited
2469
+ if self.output_dims != 2:
2470
+ raise ValueError('contains_branch_separately only supports '
2471
+ 'transforms with 2 output dimensions')
2472
+ if self == other_transform:
2473
+ return (True, True)
2474
+ return self._b.contains_branch_separately(other_transform)
2475
+
2476
+ depth = property(lambda self: self._a.depth + self._b.depth)
2477
+ is_affine = property(lambda self: self._a.is_affine and self._b.is_affine)
2478
+ is_separable = property(
2479
+ lambda self: self._a.is_separable and self._b.is_separable)
2480
+ has_inverse = property(
2481
+ lambda self: self._a.has_inverse and self._b.has_inverse)
2482
+
2483
+ __str__ = _make_str_method("_a", "_b")
2484
+
2485
+ def transform_affine(self, values):
2486
+ # docstring inherited
2487
+ return self.get_affine().transform(values)
2488
+
2489
+ def transform_non_affine(self, values):
2490
+ # docstring inherited
2491
+ if self._a.is_affine and self._b.is_affine:
2492
+ return values
2493
+ elif not self._a.is_affine and self._b.is_affine:
2494
+ return self._a.transform_non_affine(values)
2495
+ else:
2496
+ return self._b.transform_non_affine(self._a.transform(values))
2497
+
2498
+ def transform_path_non_affine(self, path):
2499
+ # docstring inherited
2500
+ if self._a.is_affine and self._b.is_affine:
2501
+ return path
2502
+ elif not self._a.is_affine and self._b.is_affine:
2503
+ return self._a.transform_path_non_affine(path)
2504
+ else:
2505
+ return self._b.transform_path_non_affine(
2506
+ self._a.transform_path(path))
2507
+
2508
+ def get_affine(self):
2509
+ # docstring inherited
2510
+ if not self._b.is_affine:
2511
+ return self._b.get_affine()
2512
+ else:
2513
+ return Affine2D(np.dot(self._b.get_affine().get_matrix(),
2514
+ self._a.get_affine().get_matrix()))
2515
+
2516
+ def inverted(self):
2517
+ # docstring inherited
2518
+ return CompositeGenericTransform(
2519
+ self._b.inverted(), self._a.inverted())
2520
+
2521
+
2522
+ class CompositeAffine2D(Affine2DBase):
2523
+ """
2524
+ A composite transform formed by applying transform *a* then transform *b*.
2525
+
2526
+ This version is an optimization that handles the case where both *a*
2527
+ and *b* are 2D affines.
2528
+ """
2529
+ def __init__(self, a, b, **kwargs):
2530
+ """
2531
+ Create a new composite transform that is the result of
2532
+ applying `Affine2DBase` *a* then `Affine2DBase` *b*.
2533
+
2534
+ You will generally not call this constructor directly but write ``a +
2535
+ b`` instead, which will automatically choose the best kind of composite
2536
+ transform instance to create.
2537
+ """
2538
+ if not a.is_affine or not b.is_affine:
2539
+ raise ValueError("'a' and 'b' must be affine transforms")
2540
+ if a.output_dims != b.input_dims:
2541
+ raise ValueError("The output dimension of 'a' must be equal to "
2542
+ "the input dimensions of 'b'")
2543
+ self.input_dims = a.input_dims
2544
+ self.output_dims = b.output_dims
2545
+
2546
+ super().__init__(**kwargs)
2547
+ self._a = a
2548
+ self._b = b
2549
+ self.set_children(a, b)
2550
+ self._mtx = None
2551
+
2552
+ @property
2553
+ def depth(self):
2554
+ return self._a.depth + self._b.depth
2555
+
2556
+ def _iter_break_from_left_to_right(self):
2557
+ for left, right in self._a._iter_break_from_left_to_right():
2558
+ yield left, right + self._b
2559
+ for left, right in self._b._iter_break_from_left_to_right():
2560
+ yield self._a + left, right
2561
+
2562
+ __str__ = _make_str_method("_a", "_b")
2563
+
2564
+ def get_matrix(self):
2565
+ # docstring inherited
2566
+ if self._invalid:
2567
+ self._mtx = np.dot(
2568
+ self._b.get_matrix(),
2569
+ self._a.get_matrix())
2570
+ self._inverted = None
2571
+ self._invalid = 0
2572
+ return self._mtx
2573
+
2574
+
2575
+ def composite_transform_factory(a, b):
2576
+ """
2577
+ Create a new composite transform that is the result of applying
2578
+ transform a then transform b.
2579
+
2580
+ Shortcut versions of the blended transform are provided for the
2581
+ case where both child transforms are affine, or one or the other
2582
+ is the identity transform.
2583
+
2584
+ Composite transforms may also be created using the '+' operator,
2585
+ e.g.::
2586
+
2587
+ c = a + b
2588
+ """
2589
+ # check to see if any of a or b are IdentityTransforms. We use
2590
+ # isinstance here to guarantee that the transforms will *always*
2591
+ # be IdentityTransforms. Since TransformWrappers are mutable,
2592
+ # use of equality here would be wrong.
2593
+ if isinstance(a, IdentityTransform):
2594
+ return b
2595
+ elif isinstance(b, IdentityTransform):
2596
+ return a
2597
+ elif isinstance(a, Affine2D) and isinstance(b, Affine2D):
2598
+ return CompositeAffine2D(a, b)
2599
+ return CompositeGenericTransform(a, b)
2600
+
2601
+
2602
+ class BboxTransform(Affine2DBase):
2603
+ """
2604
+ `BboxTransform` linearly transforms points from one `Bbox` to another.
2605
+ """
2606
+
2607
+ is_separable = True
2608
+
2609
+ def __init__(self, boxin, boxout, **kwargs):
2610
+ """
2611
+ Create a new `BboxTransform` that linearly transforms
2612
+ points from *boxin* to *boxout*.
2613
+ """
2614
+ _api.check_isinstance(BboxBase, boxin=boxin, boxout=boxout)
2615
+
2616
+ super().__init__(**kwargs)
2617
+ self._boxin = boxin
2618
+ self._boxout = boxout
2619
+ self.set_children(boxin, boxout)
2620
+ self._mtx = None
2621
+ self._inverted = None
2622
+
2623
+ __str__ = _make_str_method("_boxin", "_boxout")
2624
+
2625
+ def get_matrix(self):
2626
+ # docstring inherited
2627
+ if self._invalid:
2628
+ inl, inb, inw, inh = self._boxin.bounds
2629
+ outl, outb, outw, outh = self._boxout.bounds
2630
+ x_scale = outw / inw
2631
+ y_scale = outh / inh
2632
+ if DEBUG and (x_scale == 0 or y_scale == 0):
2633
+ raise ValueError(
2634
+ "Transforming from or to a singular bounding box")
2635
+ self._mtx = np.array([[x_scale, 0.0, -inl*x_scale+outl],
2636
+ [ 0.0, y_scale, -inb*y_scale+outb],
2637
+ [ 0.0, 0.0, 1.0]],
2638
+ float)
2639
+ self._inverted = None
2640
+ self._invalid = 0
2641
+ return self._mtx
2642
+
2643
+
2644
+ class BboxTransformTo(Affine2DBase):
2645
+ """
2646
+ `BboxTransformTo` is a transformation that linearly transforms points from
2647
+ the unit bounding box to a given `Bbox`.
2648
+ """
2649
+
2650
+ is_separable = True
2651
+
2652
+ def __init__(self, boxout, **kwargs):
2653
+ """
2654
+ Create a new `BboxTransformTo` that linearly transforms
2655
+ points from the unit bounding box to *boxout*.
2656
+ """
2657
+ _api.check_isinstance(BboxBase, boxout=boxout)
2658
+
2659
+ super().__init__(**kwargs)
2660
+ self._boxout = boxout
2661
+ self.set_children(boxout)
2662
+ self._mtx = None
2663
+ self._inverted = None
2664
+
2665
+ __str__ = _make_str_method("_boxout")
2666
+
2667
+ def get_matrix(self):
2668
+ # docstring inherited
2669
+ if self._invalid:
2670
+ outl, outb, outw, outh = self._boxout.bounds
2671
+ if DEBUG and (outw == 0 or outh == 0):
2672
+ raise ValueError("Transforming to a singular bounding box.")
2673
+ self._mtx = np.array([[outw, 0.0, outl],
2674
+ [ 0.0, outh, outb],
2675
+ [ 0.0, 0.0, 1.0]],
2676
+ float)
2677
+ self._inverted = None
2678
+ self._invalid = 0
2679
+ return self._mtx
2680
+
2681
+
2682
+ class BboxTransformFrom(Affine2DBase):
2683
+ """
2684
+ `BboxTransformFrom` linearly transforms points from a given `Bbox` to the
2685
+ unit bounding box.
2686
+ """
2687
+ is_separable = True
2688
+
2689
+ def __init__(self, boxin, **kwargs):
2690
+ _api.check_isinstance(BboxBase, boxin=boxin)
2691
+
2692
+ super().__init__(**kwargs)
2693
+ self._boxin = boxin
2694
+ self.set_children(boxin)
2695
+ self._mtx = None
2696
+ self._inverted = None
2697
+
2698
+ __str__ = _make_str_method("_boxin")
2699
+
2700
+ def get_matrix(self):
2701
+ # docstring inherited
2702
+ if self._invalid:
2703
+ inl, inb, inw, inh = self._boxin.bounds
2704
+ if DEBUG and (inw == 0 or inh == 0):
2705
+ raise ValueError("Transforming from a singular bounding box.")
2706
+ x_scale = 1.0 / inw
2707
+ y_scale = 1.0 / inh
2708
+ self._mtx = np.array([[x_scale, 0.0, -inl*x_scale],
2709
+ [ 0.0, y_scale, -inb*y_scale],
2710
+ [ 0.0, 0.0, 1.0]],
2711
+ float)
2712
+ self._inverted = None
2713
+ self._invalid = 0
2714
+ return self._mtx
2715
+
2716
+
2717
+ class ScaledTranslation(Affine2DBase):
2718
+ """
2719
+ A transformation that translates by *xt* and *yt*, after *xt* and *yt*
2720
+ have been transformed by *scale_trans*.
2721
+ """
2722
+ def __init__(self, xt, yt, scale_trans, **kwargs):
2723
+ super().__init__(**kwargs)
2724
+ self._t = (xt, yt)
2725
+ self._scale_trans = scale_trans
2726
+ self.set_children(scale_trans)
2727
+ self._mtx = None
2728
+ self._inverted = None
2729
+
2730
+ __str__ = _make_str_method("_t")
2731
+
2732
+ def get_matrix(self):
2733
+ # docstring inherited
2734
+ if self._invalid:
2735
+ # A bit faster than np.identity(3).
2736
+ self._mtx = IdentityTransform._mtx.copy()
2737
+ self._mtx[:2, 2] = self._scale_trans.transform(self._t)
2738
+ self._invalid = 0
2739
+ self._inverted = None
2740
+ return self._mtx
2741
+
2742
+
2743
+ class _ScaledRotation(Affine2DBase):
2744
+ """
2745
+ A transformation that applies rotation by *theta*, after transform by *trans_shift*.
2746
+ """
2747
+ def __init__(self, theta, trans_shift):
2748
+ super().__init__()
2749
+ self._theta = theta
2750
+ self._trans_shift = trans_shift
2751
+ self._mtx = None
2752
+
2753
+ def get_matrix(self):
2754
+ if self._invalid:
2755
+ transformed_coords = self._trans_shift.transform([[self._theta, 0]])[0]
2756
+ adjusted_theta = transformed_coords[0]
2757
+ rotation = Affine2D().rotate(adjusted_theta)
2758
+ self._mtx = rotation.get_matrix()
2759
+ return self._mtx
2760
+
2761
+
2762
+ class AffineDeltaTransform(Affine2DBase):
2763
+ r"""
2764
+ A transform wrapper for transforming displacements between pairs of points.
2765
+
2766
+ This class is intended to be used to transform displacements ("position
2767
+ deltas") between pairs of points (e.g., as the ``offset_transform``
2768
+ of `.Collection`\s): given a transform ``t`` such that ``t =
2769
+ AffineDeltaTransform(t) + offset``, ``AffineDeltaTransform``
2770
+ satisfies ``AffineDeltaTransform(a - b) == AffineDeltaTransform(a) -
2771
+ AffineDeltaTransform(b)``.
2772
+
2773
+ This is implemented by forcing the offset components of the transform
2774
+ matrix to zero.
2775
+
2776
+ This class is experimental as of 3.3, and the API may change.
2777
+ """
2778
+
2779
+ pass_through = True
2780
+
2781
+ def __init__(self, transform, **kwargs):
2782
+ super().__init__(**kwargs)
2783
+ self._base_transform = transform
2784
+ self.set_children(transform)
2785
+
2786
+ __str__ = _make_str_method("_base_transform")
2787
+
2788
+ def get_matrix(self):
2789
+ if self._invalid:
2790
+ self._mtx = self._base_transform.get_matrix().copy()
2791
+ self._mtx[:2, -1] = 0
2792
+ return self._mtx
2793
+
2794
+
2795
+ class TransformedPath(TransformNode):
2796
+ """
2797
+ A `TransformedPath` caches a non-affine transformed copy of the
2798
+ `~.path.Path`. This cached copy is automatically updated when the
2799
+ non-affine part of the transform changes.
2800
+
2801
+ .. note::
2802
+
2803
+ Paths are considered immutable by this class. Any update to the
2804
+ path's vertices/codes will not trigger a transform recomputation.
2805
+
2806
+ """
2807
+ def __init__(self, path, transform):
2808
+ """
2809
+ Parameters
2810
+ ----------
2811
+ path : `~.path.Path`
2812
+ transform : `Transform`
2813
+ """
2814
+ _api.check_isinstance(Transform, transform=transform)
2815
+ super().__init__()
2816
+ self._path = path
2817
+ self._transform = transform
2818
+ self.set_children(transform)
2819
+ self._transformed_path = None
2820
+ self._transformed_points = None
2821
+
2822
+ def _revalidate(self):
2823
+ # only recompute if the invalidation includes the non_affine part of
2824
+ # the transform
2825
+ if (self._invalid == self._INVALID_FULL
2826
+ or self._transformed_path is None):
2827
+ self._transformed_path = \
2828
+ self._transform.transform_path_non_affine(self._path)
2829
+ self._transformed_points = \
2830
+ Path._fast_from_codes_and_verts(
2831
+ self._transform.transform_non_affine(self._path.vertices),
2832
+ None, self._path)
2833
+ self._invalid = 0
2834
+
2835
+ def get_transformed_points_and_affine(self):
2836
+ """
2837
+ Return a copy of the child path, with the non-affine part of
2838
+ the transform already applied, along with the affine part of
2839
+ the path necessary to complete the transformation. Unlike
2840
+ :meth:`get_transformed_path_and_affine`, no interpolation will
2841
+ be performed.
2842
+ """
2843
+ self._revalidate()
2844
+ return self._transformed_points, self.get_affine()
2845
+
2846
+ def get_transformed_path_and_affine(self):
2847
+ """
2848
+ Return a copy of the child path, with the non-affine part of
2849
+ the transform already applied, along with the affine part of
2850
+ the path necessary to complete the transformation.
2851
+ """
2852
+ self._revalidate()
2853
+ return self._transformed_path, self.get_affine()
2854
+
2855
+ def get_fully_transformed_path(self):
2856
+ """
2857
+ Return a fully-transformed copy of the child path.
2858
+ """
2859
+ self._revalidate()
2860
+ return self._transform.transform_path_affine(self._transformed_path)
2861
+
2862
+ def get_affine(self):
2863
+ return self._transform.get_affine()
2864
+
2865
+
2866
+ class TransformedPatchPath(TransformedPath):
2867
+ """
2868
+ A `TransformedPatchPath` caches a non-affine transformed copy of the
2869
+ `~.patches.Patch`. This cached copy is automatically updated when the
2870
+ non-affine part of the transform or the patch changes.
2871
+ """
2872
+
2873
+ def __init__(self, patch):
2874
+ """
2875
+ Parameters
2876
+ ----------
2877
+ patch : `~.patches.Patch`
2878
+ """
2879
+ # Defer to TransformedPath.__init__.
2880
+ super().__init__(patch.get_path(), patch.get_transform())
2881
+ self._patch = patch
2882
+
2883
+ def _revalidate(self):
2884
+ patch_path = self._patch.get_path()
2885
+ # Force invalidation if the patch path changed; otherwise, let base
2886
+ # class check invalidation.
2887
+ if patch_path != self._path:
2888
+ self._path = patch_path
2889
+ self._transformed_path = None
2890
+ super()._revalidate()
2891
+
2892
+
2893
+ def _nonsingular(vmin, vmax, expander=0.001, tiny=1e-15, increasing=True):
2894
+ """
2895
+ Modify the endpoints of a range as needed to avoid singularities.
2896
+
2897
+ Parameters
2898
+ ----------
2899
+ vmin, vmax : float
2900
+ The initial endpoints.
2901
+ expander : float, default: 0.001
2902
+ Fractional amount by which *vmin* and *vmax* are expanded if
2903
+ the original interval is too small, based on *tiny*.
2904
+ tiny : float, default: 1e-15
2905
+ Threshold for the ratio of the interval to the maximum absolute
2906
+ value of its endpoints. If the interval is smaller than
2907
+ this, it will be expanded. This value should be around
2908
+ 1e-15 or larger; otherwise the interval will be approaching
2909
+ the double precision resolution limit.
2910
+ increasing : bool, default: True
2911
+ If True, swap *vmin*, *vmax* if *vmin* > *vmax*.
2912
+
2913
+ Returns
2914
+ -------
2915
+ vmin, vmax : float
2916
+ Endpoints, expanded and/or swapped if necessary.
2917
+ If either input is inf or NaN, or if both inputs are 0 or very
2918
+ close to zero, it returns -*expander*, *expander*.
2919
+ """
2920
+
2921
+ if (not np.isfinite(vmin)) or (not np.isfinite(vmax)):
2922
+ return -expander, expander
2923
+
2924
+ swapped = False
2925
+ if vmax < vmin:
2926
+ vmin, vmax = vmax, vmin
2927
+ swapped = True
2928
+
2929
+ # Expand vmin, vmax to float: if they were integer types, they can wrap
2930
+ # around in abs (abs(np.int8(-128)) == -128) and vmax - vmin can overflow.
2931
+ vmin, vmax = map(float, [vmin, vmax])
2932
+
2933
+ maxabsvalue = max(abs(vmin), abs(vmax))
2934
+ if maxabsvalue < (1e6 / tiny) * np.finfo(float).tiny:
2935
+ vmin = -expander
2936
+ vmax = expander
2937
+
2938
+ elif vmax - vmin <= maxabsvalue * tiny:
2939
+ if vmax == 0 and vmin == 0:
2940
+ vmin = -expander
2941
+ vmax = expander
2942
+ else:
2943
+ vmin -= expander*abs(vmin)
2944
+ vmax += expander*abs(vmax)
2945
+
2946
+ if swapped and not increasing:
2947
+ vmin, vmax = vmax, vmin
2948
+ return vmin, vmax
2949
+
2950
+
2951
+ @_api.deprecated("3.11")
2952
+ @_docstring.copy(_nonsingular)
2953
+ def nonsingular(vmin, vmax, expander=0.001, tiny=1e-15, increasing=True):
2954
+ return _nonsingular(vmin, vmax, expander, tiny, increasing)
2955
+
2956
+
2957
+ def _interval_contains(interval, val):
2958
+ """
2959
+ Check, inclusively, whether an interval includes a given value.
2960
+
2961
+ Parameters
2962
+ ----------
2963
+ interval : (float, float)
2964
+ The endpoints of the interval.
2965
+ val : float
2966
+ Value to check is within interval.
2967
+
2968
+ Returns
2969
+ -------
2970
+ bool
2971
+ Whether *val* is within the *interval*.
2972
+ """
2973
+ a, b = interval
2974
+ if a > b:
2975
+ a, b = b, a
2976
+ return a <= val <= b
2977
+
2978
+
2979
+ @_api.deprecated("3.11")
2980
+ @_docstring.copy(_interval_contains)
2981
+ def interval_contains(interval, val):
2982
+ return _interval_contains(interval, val)
2983
+
2984
+
2985
+ def _interval_contains_close(interval, val, rtol=1e-10):
2986
+ """
2987
+ Check, inclusively, whether an interval includes a given value, with the
2988
+ interval expanded by a small tolerance to admit floating point errors.
2989
+
2990
+ Parameters
2991
+ ----------
2992
+ interval : (float, float)
2993
+ The endpoints of the interval.
2994
+ val : float
2995
+ Value to check is within interval.
2996
+ rtol : float, default: 1e-10
2997
+ Relative tolerance slippage allowed outside of the interval.
2998
+ For an interval ``[a, b]``, values
2999
+ ``a - rtol * (b - a) <= val <= b + rtol * (b - a)`` are considered
3000
+ inside the interval.
3001
+
3002
+ Returns
3003
+ -------
3004
+ bool
3005
+ Whether *val* is within the *interval* (with tolerance).
3006
+ """
3007
+ a, b = interval
3008
+ if a > b:
3009
+ a, b = b, a
3010
+ rtol = (b - a) * rtol
3011
+ return a - rtol <= val <= b + rtol
3012
+
3013
+
3014
+ def _interval_contains_open(interval, val):
3015
+ """
3016
+ Check, excluding endpoints, whether an interval includes a given value.
3017
+
3018
+ Parameters
3019
+ ----------
3020
+ interval : (float, float)
3021
+ The endpoints of the interval.
3022
+ val : float
3023
+ Value to check is within interval.
3024
+
3025
+ Returns
3026
+ -------
3027
+ bool
3028
+ Whether *val* is within the *interval*.
3029
+ """
3030
+ a, b = interval
3031
+ return a < val < b or a > val > b
3032
+
3033
+
3034
+ @_api.deprecated("3.11")
3035
+ @_docstring.copy(_interval_contains_open)
3036
+ def interval_contains_open(interval, val):
3037
+ return _interval_contains_open(interval, val)
3038
+
3039
+
3040
+ def offset_copy(trans, fig=None, x=0.0, y=0.0, units='inches'):
3041
+ """
3042
+ Return a new transform with an added offset.
3043
+
3044
+ Parameters
3045
+ ----------
3046
+ trans : `Transform` subclass
3047
+ Any transform, to which offset will be applied.
3048
+ fig : `~matplotlib.figure.Figure`, default: None
3049
+ Current figure. It can be None if *units* are 'dots'.
3050
+ x, y : float, default: 0.0
3051
+ The offset to apply.
3052
+ units : {'inches', 'points', 'dots'}, default: 'inches'
3053
+ Units of the offset.
3054
+
3055
+ Returns
3056
+ -------
3057
+ `Transform` subclass
3058
+ Transform with applied offset.
3059
+ """
3060
+ _api.check_in_list(['dots', 'points', 'inches'], units=units)
3061
+ if units == 'dots':
3062
+ return trans + Affine2D().translate(x, y)
3063
+ if fig is None:
3064
+ raise ValueError('For units of inches or points a fig kwarg is needed')
3065
+ if units == 'points':
3066
+ x /= 72.0
3067
+ y /= 72.0
3068
+ # Default units are 'inches'
3069
+ return trans + ScaledTranslation(x, y, fig.dpi_scale_trans)