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,1575 @@
1
+ # Vendored from matplotlib 3.11 (see licenses/LICENSE_MATPLOTLIB), adapted for matplotlib_rs.
2
+ """
3
+ Interpolation inside triangular grids.
4
+ """
5
+
6
+ import numpy as np
7
+
8
+ from matplotlib_rs import _api
9
+ from matplotlib_rs.tri import Triangulation
10
+ from matplotlib_rs.tri._trifinder import TriFinder
11
+ from matplotlib_rs.tri._tritools import TriAnalyzer
12
+
13
+ __all__ = ('TriInterpolator', 'LinearTriInterpolator', 'CubicTriInterpolator')
14
+
15
+
16
+ class TriInterpolator:
17
+ """
18
+ Abstract base class for classes used to interpolate on a triangular grid.
19
+
20
+ Derived classes implement the following methods:
21
+
22
+ - ``__call__(x, y)``,
23
+ where x, y are array-like point coordinates of the same shape, and
24
+ that returns a masked array of the same shape containing the
25
+ interpolated z-values.
26
+
27
+ - ``gradient(x, y)``,
28
+ where x, y are array-like point coordinates of the same
29
+ shape, and that returns a list of 2 masked arrays of the same shape
30
+ containing the 2 derivatives of the interpolator (derivatives of
31
+ interpolated z values with respect to x and y).
32
+ """
33
+
34
+ def __init__(self, triangulation, z, trifinder=None):
35
+ _api.check_isinstance(Triangulation, triangulation=triangulation)
36
+ self._triangulation = triangulation
37
+
38
+ self._z = np.asarray(z)
39
+ if self._z.shape != self._triangulation.x.shape:
40
+ raise ValueError("z array must have same length as triangulation x"
41
+ " and y arrays")
42
+
43
+ _api.check_isinstance((TriFinder, None), trifinder=trifinder)
44
+ self._trifinder = trifinder or self._triangulation.get_trifinder()
45
+
46
+ # Default scaling factors : 1.0 (= no scaling)
47
+ # Scaling may be used for interpolations for which the order of
48
+ # magnitude of x, y has an impact on the interpolant definition.
49
+ # Please refer to :meth:`_interpolate_multikeys` for details.
50
+ self._unit_x = 1.0
51
+ self._unit_y = 1.0
52
+
53
+ # Default triangle renumbering: None (= no renumbering)
54
+ # Renumbering may be used to avoid unnecessary computations
55
+ # if complex calculations are done inside the Interpolator.
56
+ # Please refer to :meth:`_interpolate_multikeys` for details.
57
+ self._tri_renum = None
58
+
59
+ # __call__ and gradient docstrings are shared by all subclasses
60
+ # (except, if needed, relevant additions).
61
+ # However these methods are only implemented in subclasses to avoid
62
+ # confusion in the documentation.
63
+ _docstring__call__ = """
64
+ Returns a masked array containing interpolated values at the specified
65
+ (x, y) points.
66
+
67
+ Parameters
68
+ ----------
69
+ x, y : array-like
70
+ x and y coordinates of the same shape and any number of
71
+ dimensions.
72
+
73
+ Returns
74
+ -------
75
+ np.ma.array
76
+ Masked array of the same shape as *x* and *y*; values corresponding
77
+ to (*x*, *y*) points outside of the triangulation are masked out.
78
+
79
+ """
80
+
81
+ _docstringgradient = r"""
82
+ Returns a list of 2 masked arrays containing interpolated derivatives
83
+ at the specified (x, y) points.
84
+
85
+ Parameters
86
+ ----------
87
+ x, y : array-like
88
+ x and y coordinates of the same shape and any number of
89
+ dimensions.
90
+
91
+ Returns
92
+ -------
93
+ dzdx, dzdy : np.ma.array
94
+ 2 masked arrays of the same shape as *x* and *y*; values
95
+ corresponding to (x, y) points outside of the triangulation
96
+ are masked out.
97
+ The first returned array contains the values of
98
+ :math:`\frac{\partial z}{\partial x}` and the second those of
99
+ :math:`\frac{\partial z}{\partial y}`.
100
+
101
+ """
102
+
103
+ def _interpolate_multikeys(self, x, y, tri_index=None,
104
+ return_keys=('z',)):
105
+ """
106
+ Versatile (private) method defined for all TriInterpolators.
107
+
108
+ :meth:`_interpolate_multikeys` is a wrapper around method
109
+ :meth:`_interpolate_single_key` (to be defined in the child
110
+ subclasses).
111
+ :meth:`_interpolate_single_key actually performs the interpolation,
112
+ but only for 1-dimensional inputs and at valid locations (inside
113
+ unmasked triangles of the triangulation).
114
+
115
+ The purpose of :meth:`_interpolate_multikeys` is to implement the
116
+ following common tasks needed in all subclasses implementations:
117
+
118
+ - calculation of containing triangles
119
+ - dealing with more than one interpolation request at the same
120
+ location (e.g., if the 2 derivatives are requested, it is
121
+ unnecessary to compute the containing triangles twice)
122
+ - scaling according to self._unit_x, self._unit_y
123
+ - dealing with points outside of the grid (with fill value np.nan)
124
+ - dealing with multi-dimensional *x*, *y* arrays: flattening for
125
+ :meth:`_interpolate_params` call and final reshaping.
126
+
127
+ (Note that np.vectorize could do most of those things very well for
128
+ you, but it does it by function evaluations over successive tuples of
129
+ the input arrays. Therefore, this tends to be more time-consuming than
130
+ using optimized numpy functions - e.g., np.dot - which can be used
131
+ easily on the flattened inputs, in the child-subclass methods
132
+ :meth:`_interpolate_single_key`.)
133
+
134
+ It is guaranteed that the calls to :meth:`_interpolate_single_key`
135
+ will be done with flattened (1-d) array-like input parameters *x*, *y*
136
+ and with flattened, valid `tri_index` arrays (no -1 index allowed).
137
+
138
+ Parameters
139
+ ----------
140
+ x, y : array-like
141
+ x and y coordinates where interpolated values are requested.
142
+ tri_index : array-like of int, optional
143
+ Array of the containing triangle indices, same shape as
144
+ *x* and *y*. Defaults to None. If None, these indices
145
+ will be computed by a TriFinder instance.
146
+ (Note: For point outside the grid, tri_index[ipt] shall be -1).
147
+ return_keys : tuple of keys from {'z', 'dzdx', 'dzdy'}
148
+ Defines the interpolation arrays to return, and in which order.
149
+
150
+ Returns
151
+ -------
152
+ list of arrays
153
+ Each array-like contains the expected interpolated values in the
154
+ order defined by *return_keys* parameter.
155
+ """
156
+ # Flattening and rescaling inputs arrays x, y
157
+ # (initial shape is stored for output)
158
+ x = np.asarray(x, dtype=np.float64)
159
+ y = np.asarray(y, dtype=np.float64)
160
+ sh_ret = x.shape
161
+ if x.shape != y.shape:
162
+ raise ValueError("x and y shall have same shapes."
163
+ f" Given: {x.shape} and {y.shape}")
164
+ x = np.ravel(x)
165
+ y = np.ravel(y)
166
+ x_scaled = x/self._unit_x
167
+ y_scaled = y/self._unit_y
168
+ size_ret = np.size(x_scaled)
169
+
170
+ # Computes & ravels the element indexes, extract the valid ones.
171
+ if tri_index is None:
172
+ tri_index = self._trifinder(x, y)
173
+ else:
174
+ if tri_index.shape != sh_ret:
175
+ raise ValueError(
176
+ "tri_index array is provided and shall"
177
+ " have same shape as x and y. Given: "
178
+ f"{tri_index.shape} and {sh_ret}")
179
+ tri_index = np.ravel(tri_index)
180
+
181
+ mask_in = (tri_index != -1)
182
+ if self._tri_renum is None:
183
+ valid_tri_index = tri_index[mask_in]
184
+ else:
185
+ valid_tri_index = self._tri_renum[tri_index[mask_in]]
186
+ valid_x = x_scaled[mask_in]
187
+ valid_y = y_scaled[mask_in]
188
+
189
+ ret = []
190
+ for return_key in return_keys:
191
+ # Find the return index associated with the key.
192
+ try:
193
+ return_index = {'z': 0, 'dzdx': 1, 'dzdy': 2}[return_key]
194
+ except KeyError as err:
195
+ raise ValueError("return_keys items shall take values in"
196
+ " {'z', 'dzdx', 'dzdy'}") from err
197
+
198
+ # Sets the scale factor for f & df components
199
+ scale = [1., 1./self._unit_x, 1./self._unit_y][return_index]
200
+
201
+ # Computes the interpolation
202
+ ret_loc = np.empty(size_ret, dtype=np.float64)
203
+ ret_loc[~mask_in] = np.nan
204
+ ret_loc[mask_in] = self._interpolate_single_key(
205
+ return_key, valid_tri_index, valid_x, valid_y) * scale
206
+ ret += [np.ma.masked_invalid(ret_loc.reshape(sh_ret), copy=False)]
207
+
208
+ return ret
209
+
210
+ def _interpolate_single_key(self, return_key, tri_index, x, y):
211
+ """
212
+ Interpolate at points belonging to the triangulation
213
+ (inside an unmasked triangles).
214
+
215
+ Parameters
216
+ ----------
217
+ return_key : {'z', 'dzdx', 'dzdy'}
218
+ The requested values (z or its derivatives).
219
+ tri_index : 1D int array
220
+ Valid triangle index (cannot be -1).
221
+ x, y : 1D arrays, same shape as `tri_index`
222
+ Valid locations where interpolation is requested.
223
+
224
+ Returns
225
+ -------
226
+ 1-d array
227
+ Returned array of the same size as *tri_index*
228
+ """
229
+ raise NotImplementedError("TriInterpolator subclasses" +
230
+ "should implement _interpolate_single_key!")
231
+
232
+
233
+ class LinearTriInterpolator(TriInterpolator):
234
+ """
235
+ Linear interpolator on a triangular grid.
236
+
237
+ Each triangle is represented by a plane so that an interpolated value at
238
+ point (x, y) lies on the plane of the triangle containing (x, y).
239
+ Interpolated values are therefore continuous across the triangulation, but
240
+ their first derivatives are discontinuous at edges between triangles.
241
+
242
+ Parameters
243
+ ----------
244
+ triangulation : `~matplotlib.tri.Triangulation`
245
+ The triangulation to interpolate over.
246
+ z : (npoints,) array-like
247
+ Array of values, defined at grid points, to interpolate between.
248
+ trifinder : `~matplotlib.tri.TriFinder`, optional
249
+ If this is not specified, the Triangulation's default TriFinder will
250
+ be used by calling `.Triangulation.get_trifinder`.
251
+
252
+ Methods
253
+ -------
254
+ `__call__` (x, y) : Returns interpolated values at (x, y) points.
255
+ `gradient` (x, y) : Returns interpolated derivatives at (x, y) points.
256
+
257
+ """
258
+ def __init__(self, triangulation, z, trifinder=None):
259
+ super().__init__(triangulation, z, trifinder)
260
+
261
+ # Store plane coefficients for fast interpolation calculations.
262
+ self._plane_coefficients = \
263
+ self._triangulation.calculate_plane_coefficients(self._z)
264
+
265
+ def __call__(self, x, y):
266
+ return self._interpolate_multikeys(x, y, tri_index=None,
267
+ return_keys=('z',))[0]
268
+ __call__.__doc__ = TriInterpolator._docstring__call__
269
+
270
+ def gradient(self, x, y):
271
+ return self._interpolate_multikeys(x, y, tri_index=None,
272
+ return_keys=('dzdx', 'dzdy'))
273
+ gradient.__doc__ = TriInterpolator._docstringgradient
274
+
275
+ def _interpolate_single_key(self, return_key, tri_index, x, y):
276
+ _api.check_in_list(['z', 'dzdx', 'dzdy'], return_key=return_key)
277
+ if return_key == 'z':
278
+ return (self._plane_coefficients[tri_index, 0]*x +
279
+ self._plane_coefficients[tri_index, 1]*y +
280
+ self._plane_coefficients[tri_index, 2])
281
+ elif return_key == 'dzdx':
282
+ return self._plane_coefficients[tri_index, 0]
283
+ else: # 'dzdy'
284
+ return self._plane_coefficients[tri_index, 1]
285
+
286
+
287
+ class CubicTriInterpolator(TriInterpolator):
288
+ r"""
289
+ Cubic interpolator on a triangular grid.
290
+
291
+ In one-dimension - on a segment - a cubic interpolating function is
292
+ defined by the values of the function and its derivative at both ends.
293
+ This is almost the same in 2D inside a triangle, except that the values
294
+ of the function and its 2 derivatives have to be defined at each triangle
295
+ node.
296
+
297
+ The CubicTriInterpolator takes the value of the function at each node -
298
+ provided by the user - and internally computes the value of the
299
+ derivatives, resulting in a smooth interpolation.
300
+ (As a special feature, the user can also impose the value of the
301
+ derivatives at each node, but this is not supposed to be the common
302
+ usage.)
303
+
304
+ Parameters
305
+ ----------
306
+ triangulation : `~matplotlib.tri.Triangulation`
307
+ The triangulation to interpolate over.
308
+ z : (npoints,) array-like
309
+ Array of values, defined at grid points, to interpolate between.
310
+ kind : {'min_E', 'geom', 'user'}, optional
311
+ Choice of the smoothing algorithm, in order to compute
312
+ the interpolant derivatives (defaults to 'min_E'):
313
+
314
+ - if 'min_E': (default) The derivatives at each node is computed
315
+ to minimize a bending energy.
316
+ - if 'geom': The derivatives at each node is computed as a
317
+ weighted average of relevant triangle normals. To be used for
318
+ speed optimization (large grids).
319
+ - if 'user': The user provides the argument *dz*, no computation
320
+ is hence needed.
321
+
322
+ trifinder : `~matplotlib.tri.TriFinder`, optional
323
+ If not specified, the Triangulation's default TriFinder will
324
+ be used by calling `.Triangulation.get_trifinder`.
325
+ dz : tuple of array-likes (dzdx, dzdy), optional
326
+ Used only if *kind* ='user'. In this case *dz* must be provided as
327
+ (dzdx, dzdy) where dzdx, dzdy are arrays of the same shape as *z* and
328
+ are the interpolant first derivatives at the *triangulation* points.
329
+
330
+ Methods
331
+ -------
332
+ `__call__` (x, y) : Returns interpolated values at (x, y) points.
333
+ `gradient` (x, y) : Returns interpolated derivatives at (x, y) points.
334
+
335
+ Notes
336
+ -----
337
+ This note is a bit technical and details how the cubic interpolation is
338
+ computed.
339
+
340
+ The interpolation is based on a Clough-Tocher subdivision scheme of
341
+ the *triangulation* mesh (to make it clearer, each triangle of the
342
+ grid will be divided in 3 child-triangles, and on each child triangle
343
+ the interpolated function is a cubic polynomial of the 2 coordinates).
344
+ This technique originates from FEM (Finite Element Method) analysis;
345
+ the element used is a reduced Hsieh-Clough-Tocher (HCT)
346
+ element. Its shape functions are described in [1]_.
347
+ The assembled function is guaranteed to be C1-smooth, i.e. it is
348
+ continuous and its first derivatives are also continuous (this
349
+ is easy to show inside the triangles but is also true when crossing the
350
+ edges).
351
+
352
+ In the default case (*kind* ='min_E'), the interpolant minimizes a
353
+ curvature energy on the functional space generated by the HCT element
354
+ shape functions - with imposed values but arbitrary derivatives at each
355
+ node. The minimized functional is the integral of the so-called total
356
+ curvature (implementation based on an algorithm from [2]_ - PCG sparse
357
+ solver):
358
+
359
+ .. math::
360
+
361
+ E(z) = \frac{1}{2} \int_{\Omega} \left(
362
+ \left( \frac{\partial^2{z}}{\partial{x}^2} \right)^2 +
363
+ \left( \frac{\partial^2{z}}{\partial{y}^2} \right)^2 +
364
+ 2\left( \frac{\partial^2{z}}{\partial{y}\partial{x}} \right)^2
365
+ \right) dx\,dy
366
+
367
+ If the case *kind* ='geom' is chosen by the user, a simple geometric
368
+ approximation is used (weighted average of the triangle normal
369
+ vectors), which could improve speed on very large grids.
370
+
371
+ References
372
+ ----------
373
+ .. [1] Michel Bernadou, Kamal Hassan, "Basis functions for general
374
+ Hsieh-Clough-Tocher triangles, complete or reduced.",
375
+ International Journal for Numerical Methods in Engineering,
376
+ 17(5):784 - 789. 2.01.
377
+ .. [2] C.T. Kelley, "Iterative Methods for Optimization".
378
+
379
+ """
380
+ def __init__(self, triangulation, z, kind='min_E', trifinder=None,
381
+ dz=None):
382
+ super().__init__(triangulation, z, trifinder)
383
+
384
+ # Loads the underlying c++ _triangulation.
385
+ # (During loading, reordering of triangulation._triangles may occur so
386
+ # that all final triangles are now anti-clockwise)
387
+ self._triangulation.get_cpp_triangulation()
388
+
389
+ # To build the stiffness matrix and avoid zero-energy spurious modes
390
+ # we will only store internally the valid (unmasked) triangles and
391
+ # the necessary (used) points coordinates.
392
+ # 2 renumbering tables need to be computed and stored:
393
+ # - a triangle renum table in order to translate the result from a
394
+ # TriFinder instance into the internal stored triangle number.
395
+ # - a node renum table to overwrite the self._z values into the new
396
+ # (used) node numbering.
397
+ tri_analyzer = TriAnalyzer(self._triangulation)
398
+ (compressed_triangles, compressed_x, compressed_y, tri_renum,
399
+ node_renum) = tri_analyzer._get_compressed_triangulation()
400
+ self._triangles = compressed_triangles
401
+ self._tri_renum = tri_renum
402
+ # Taking into account the node renumbering in self._z:
403
+ valid_node = (node_renum != -1)
404
+ self._z[node_renum[valid_node]] = self._z[valid_node]
405
+
406
+ # Computing scale factors
407
+ self._unit_x = np.ptp(compressed_x)
408
+ self._unit_y = np.ptp(compressed_y)
409
+ self._pts = np.column_stack([compressed_x / self._unit_x,
410
+ compressed_y / self._unit_y])
411
+ # Computing triangle points
412
+ self._tris_pts = self._pts[self._triangles]
413
+ # Computing eccentricities
414
+ self._eccs = self._compute_tri_eccentricities(self._tris_pts)
415
+ # Computing dof estimations for HCT triangle shape function
416
+ _api.check_in_list(['user', 'geom', 'min_E'], kind=kind)
417
+ self._dof = self._compute_dof(kind, dz=dz)
418
+ # Loading HCT element
419
+ self._ReferenceElement = _ReducedHCT_Element()
420
+
421
+ def __call__(self, x, y):
422
+ return self._interpolate_multikeys(x, y, tri_index=None,
423
+ return_keys=('z',))[0]
424
+ __call__.__doc__ = TriInterpolator._docstring__call__
425
+
426
+ def gradient(self, x, y):
427
+ return self._interpolate_multikeys(x, y, tri_index=None,
428
+ return_keys=('dzdx', 'dzdy'))
429
+ gradient.__doc__ = TriInterpolator._docstringgradient
430
+
431
+ def _interpolate_single_key(self, return_key, tri_index, x, y):
432
+ _api.check_in_list(['z', 'dzdx', 'dzdy'], return_key=return_key)
433
+ tris_pts = self._tris_pts[tri_index]
434
+ alpha = self._get_alpha_vec(x, y, tris_pts)
435
+ ecc = self._eccs[tri_index]
436
+ dof = np.expand_dims(self._dof[tri_index], axis=1)
437
+ if return_key == 'z':
438
+ return self._ReferenceElement.get_function_values(
439
+ alpha, ecc, dof)
440
+ else: # 'dzdx', 'dzdy'
441
+ J = self._get_jacobian(tris_pts)
442
+ dzdx = self._ReferenceElement.get_function_derivatives(
443
+ alpha, J, ecc, dof)
444
+ if return_key == 'dzdx':
445
+ return dzdx[:, 0, 0]
446
+ else:
447
+ return dzdx[:, 1, 0]
448
+
449
+ def _compute_dof(self, kind, dz=None):
450
+ """
451
+ Compute and return nodal dofs according to kind.
452
+
453
+ Parameters
454
+ ----------
455
+ kind : {'min_E', 'geom', 'user'}
456
+ Choice of the _DOF_estimator subclass to estimate the gradient.
457
+ dz : tuple of array-likes (dzdx, dzdy), optional
458
+ Used only if *kind*=user; in this case passed to the
459
+ :class:`_DOF_estimator_user`.
460
+
461
+ Returns
462
+ -------
463
+ array-like, shape (npts, 2)
464
+ Estimation of the gradient at triangulation nodes (stored as
465
+ degree of freedoms of reduced-HCT triangle elements).
466
+ """
467
+ if kind == 'user':
468
+ if dz is None:
469
+ raise ValueError("For a CubicTriInterpolator with "
470
+ "*kind*='user', a valid *dz* "
471
+ "argument is expected.")
472
+ TE = _DOF_estimator_user(self, dz=dz)
473
+ elif kind == 'geom':
474
+ TE = _DOF_estimator_geom(self)
475
+ else: # 'min_E', checked in __init__
476
+ TE = _DOF_estimator_min_E(self)
477
+ return TE.compute_dof_from_df()
478
+
479
+ @staticmethod
480
+ def _get_alpha_vec(x, y, tris_pts):
481
+ """
482
+ Fast (vectorized) function to compute barycentric coordinates alpha.
483
+
484
+ Parameters
485
+ ----------
486
+ x, y : array-like of dim 1 (shape (nx,))
487
+ Coordinates of the points whose points barycentric coordinates are
488
+ requested.
489
+ tris_pts : array like of dim 3 (shape: (nx, 3, 2))
490
+ Coordinates of the containing triangles apexes.
491
+
492
+ Returns
493
+ -------
494
+ array of dim 2 (shape (nx, 3))
495
+ Barycentric coordinates of the points inside the containing
496
+ triangles.
497
+ """
498
+ ndim = tris_pts.ndim-2
499
+
500
+ a = tris_pts[:, 1, :] - tris_pts[:, 0, :]
501
+ b = tris_pts[:, 2, :] - tris_pts[:, 0, :]
502
+ abT = np.stack([a, b], axis=-1)
503
+ ab = _transpose_vectorized(abT)
504
+ OM = np.stack([x, y], axis=1) - tris_pts[:, 0, :]
505
+
506
+ metric = ab @ abT
507
+ # Here we try to deal with the colinear cases.
508
+ # metric_inv is in this case set to the Moore-Penrose pseudo-inverse
509
+ # meaning that we will still return a set of valid barycentric
510
+ # coordinates.
511
+ metric_inv = _pseudo_inv22sym_vectorized(metric)
512
+ Covar = ab @ _transpose_vectorized(np.expand_dims(OM, ndim))
513
+ ksi = metric_inv @ Covar
514
+ alpha = _to_matrix_vectorized([
515
+ [1-ksi[:, 0, 0]-ksi[:, 1, 0]], [ksi[:, 0, 0]], [ksi[:, 1, 0]]])
516
+ return alpha
517
+
518
+ @staticmethod
519
+ def _get_jacobian(tris_pts):
520
+ """
521
+ Fast (vectorized) function to compute triangle jacobian matrix.
522
+
523
+ Parameters
524
+ ----------
525
+ tris_pts : array like of dim 3 (shape: (nx, 3, 2))
526
+ Coordinates of the containing triangles apexes.
527
+
528
+ Returns
529
+ -------
530
+ array of dim 3 (shape (nx, 2, 2))
531
+ Barycentric coordinates of the points inside the containing
532
+ triangles.
533
+ J[itri, :, :] is the jacobian matrix at apex 0 of the triangle
534
+ itri, so that the following (matrix) relationship holds:
535
+ [dz/dksi] = [J] x [dz/dx]
536
+ with x: global coordinates
537
+ ksi: element parametric coordinates in triangle first apex
538
+ local basis.
539
+ """
540
+ a = np.array(tris_pts[:, 1, :] - tris_pts[:, 0, :])
541
+ b = np.array(tris_pts[:, 2, :] - tris_pts[:, 0, :])
542
+ J = _to_matrix_vectorized([[a[:, 0], a[:, 1]],
543
+ [b[:, 0], b[:, 1]]])
544
+ return J
545
+
546
+ @staticmethod
547
+ def _compute_tri_eccentricities(tris_pts):
548
+ """
549
+ Compute triangle eccentricities.
550
+
551
+ Parameters
552
+ ----------
553
+ tris_pts : array like of dim 3 (shape: (nx, 3, 2))
554
+ Coordinates of the triangles apexes.
555
+
556
+ Returns
557
+ -------
558
+ array like of dim 2 (shape: (nx, 3))
559
+ The so-called eccentricity parameters [1] needed for HCT triangular
560
+ element.
561
+ """
562
+ a = np.expand_dims(tris_pts[:, 2, :] - tris_pts[:, 1, :], axis=2)
563
+ b = np.expand_dims(tris_pts[:, 0, :] - tris_pts[:, 2, :], axis=2)
564
+ c = np.expand_dims(tris_pts[:, 1, :] - tris_pts[:, 0, :], axis=2)
565
+ # Do not use np.squeeze, this is dangerous if only one triangle
566
+ # in the triangulation...
567
+ dot_a = (_transpose_vectorized(a) @ a)[:, 0, 0]
568
+ dot_b = (_transpose_vectorized(b) @ b)[:, 0, 0]
569
+ dot_c = (_transpose_vectorized(c) @ c)[:, 0, 0]
570
+ # Note that this line will raise a warning for dot_a, dot_b or dot_c
571
+ # zeros, but we choose not to support triangles with duplicate points.
572
+ return _to_matrix_vectorized([[(dot_c-dot_b) / dot_a],
573
+ [(dot_a-dot_c) / dot_b],
574
+ [(dot_b-dot_a) / dot_c]])
575
+
576
+
577
+ # FEM element used for interpolation and for solving minimisation
578
+ # problem (Reduced HCT element)
579
+ class _ReducedHCT_Element:
580
+ """
581
+ Implementation of reduced HCT triangular element with explicit shape
582
+ functions.
583
+
584
+ Computes z, dz, d2z and the element stiffness matrix for bending energy:
585
+ E(f) = integral( (d2z/dx2 + d2z/dy2)**2 dA)
586
+
587
+ *** Reference for the shape functions: ***
588
+ [1] Basis functions for general Hsieh-Clough-Tocher _triangles, complete or
589
+ reduced.
590
+ Michel Bernadou, Kamal Hassan
591
+ International Journal for Numerical Methods in Engineering.
592
+ 17(5):784 - 789. 2.01
593
+
594
+ *** Element description: ***
595
+ 9 dofs: z and dz given at 3 apex
596
+ C1 (conform)
597
+
598
+ """
599
+ # 1) Loads matrices to generate shape functions as a function of
600
+ # triangle eccentricities - based on [1] p.11 '''
601
+ M = np.array([
602
+ [ 0.00, 0.00, 0.00, 4.50, 4.50, 0.00, 0.00, 0.00, 0.00, 0.00],
603
+ [-0.25, 0.00, 0.00, 0.50, 1.25, 0.00, 0.00, 0.00, 0.00, 0.00],
604
+ [-0.25, 0.00, 0.00, 1.25, 0.50, 0.00, 0.00, 0.00, 0.00, 0.00],
605
+ [ 0.50, 1.00, 0.00, -1.50, 0.00, 3.00, 3.00, 0.00, 0.00, 3.00],
606
+ [ 0.00, 0.00, 0.00, -0.25, 0.25, 0.00, 1.00, 0.00, 0.00, 0.50],
607
+ [ 0.25, 0.00, 0.00, -0.50, -0.25, 1.00, 0.00, 0.00, 0.00, 1.00],
608
+ [ 0.50, 0.00, 1.00, 0.00, -1.50, 0.00, 0.00, 3.00, 3.00, 3.00],
609
+ [ 0.25, 0.00, 0.00, -0.25, -0.50, 0.00, 0.00, 0.00, 1.00, 1.00],
610
+ [ 0.00, 0.00, 0.00, 0.25, -0.25, 0.00, 0.00, 1.00, 0.00, 0.50]])
611
+ M0 = np.array([
612
+ [ 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],
613
+ [ 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],
614
+ [ 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],
615
+ [-1.00, 0.00, 0.00, 1.50, 1.50, 0.00, 0.00, 0.00, 0.00, -3.00],
616
+ [-0.50, 0.00, 0.00, 0.75, 0.75, 0.00, 0.00, 0.00, 0.00, -1.50],
617
+ [ 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],
618
+ [ 1.00, 0.00, 0.00, -1.50, -1.50, 0.00, 0.00, 0.00, 0.00, 3.00],
619
+ [ 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],
620
+ [ 0.50, 0.00, 0.00, -0.75, -0.75, 0.00, 0.00, 0.00, 0.00, 1.50]])
621
+ M1 = np.array([
622
+ [-0.50, 0.00, 0.00, 1.50, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],
623
+ [ 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],
624
+ [-0.25, 0.00, 0.00, 0.75, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],
625
+ [ 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],
626
+ [ 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],
627
+ [ 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],
628
+ [ 0.50, 0.00, 0.00, -1.50, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],
629
+ [ 0.25, 0.00, 0.00, -0.75, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],
630
+ [ 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00]])
631
+ M2 = np.array([
632
+ [ 0.50, 0.00, 0.00, 0.00, -1.50, 0.00, 0.00, 0.00, 0.00, 0.00],
633
+ [ 0.25, 0.00, 0.00, 0.00, -0.75, 0.00, 0.00, 0.00, 0.00, 0.00],
634
+ [ 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],
635
+ [-0.50, 0.00, 0.00, 0.00, 1.50, 0.00, 0.00, 0.00, 0.00, 0.00],
636
+ [ 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],
637
+ [-0.25, 0.00, 0.00, 0.00, 0.75, 0.00, 0.00, 0.00, 0.00, 0.00],
638
+ [ 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],
639
+ [ 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],
640
+ [ 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00]])
641
+
642
+ # 2) Loads matrices to rotate components of gradient & Hessian
643
+ # vectors in the reference basis of triangle first apex (a0)
644
+ rotate_dV = np.array([[ 1., 0.], [ 0., 1.],
645
+ [ 0., 1.], [-1., -1.],
646
+ [-1., -1.], [ 1., 0.]])
647
+
648
+ rotate_d2V = np.array([[1., 0., 0.], [0., 1., 0.], [ 0., 0., 1.],
649
+ [0., 1., 0.], [1., 1., 1.], [ 0., -2., -1.],
650
+ [1., 1., 1.], [1., 0., 0.], [-2., 0., -1.]])
651
+
652
+ # 3) Loads Gauss points & weights on the 3 sub-_triangles for P2
653
+ # exact integral - 3 points on each subtriangles.
654
+ # NOTE: as the 2nd derivative is discontinuous , we really need those 9
655
+ # points!
656
+ n_gauss = 9
657
+ gauss_pts = np.array([[13./18., 4./18., 1./18.],
658
+ [ 4./18., 13./18., 1./18.],
659
+ [ 7./18., 7./18., 4./18.],
660
+ [ 1./18., 13./18., 4./18.],
661
+ [ 1./18., 4./18., 13./18.],
662
+ [ 4./18., 7./18., 7./18.],
663
+ [ 4./18., 1./18., 13./18.],
664
+ [13./18., 1./18., 4./18.],
665
+ [ 7./18., 4./18., 7./18.]], dtype=np.float64)
666
+ gauss_w = np.ones([9], dtype=np.float64) / 9.
667
+
668
+ # 4) Stiffness matrix for curvature energy
669
+ E = np.array([[1., 0., 0.], [0., 1., 0.], [0., 0., 2.]])
670
+
671
+ # 5) Loads the matrix to compute DOF_rot from tri_J at apex 0
672
+ J0_to_J1 = np.array([[-1., 1.], [-1., 0.]])
673
+ J0_to_J2 = np.array([[ 0., -1.], [ 1., -1.]])
674
+
675
+ def get_function_values(self, alpha, ecc, dofs):
676
+ """
677
+ Parameters
678
+ ----------
679
+ alpha : is a (N x 3 x 1) array (array of column-matrices) of
680
+ barycentric coordinates,
681
+ ecc : is a (N x 3 x 1) array (array of column-matrices) of triangle
682
+ eccentricities,
683
+ dofs : is a (N x 1 x 9) arrays (arrays of row-matrices) of computed
684
+ degrees of freedom.
685
+
686
+ Returns
687
+ -------
688
+ Returns the N-array of interpolated function values.
689
+ """
690
+ subtri = np.argmin(alpha, axis=1)[:, 0]
691
+ ksi = _roll_vectorized(alpha, -subtri, axis=0)
692
+ E = _roll_vectorized(ecc, -subtri, axis=0)
693
+ x = ksi[:, 0, 0]
694
+ y = ksi[:, 1, 0]
695
+ z = ksi[:, 2, 0]
696
+ x_sq = x*x
697
+ y_sq = y*y
698
+ z_sq = z*z
699
+ V = _to_matrix_vectorized([
700
+ [x_sq*x], [y_sq*y], [z_sq*z], [x_sq*z], [x_sq*y], [y_sq*x],
701
+ [y_sq*z], [z_sq*y], [z_sq*x], [x*y*z]])
702
+ prod = self.M @ V
703
+ prod += _scalar_vectorized(E[:, 0, 0], self.M0 @ V)
704
+ prod += _scalar_vectorized(E[:, 1, 0], self.M1 @ V)
705
+ prod += _scalar_vectorized(E[:, 2, 0], self.M2 @ V)
706
+ s = _roll_vectorized(prod, 3*subtri, axis=0)
707
+ return (dofs @ s)[:, 0, 0]
708
+
709
+ def get_function_derivatives(self, alpha, J, ecc, dofs):
710
+ """
711
+ Parameters
712
+ ----------
713
+ *alpha* is a (N x 3 x 1) array (array of column-matrices of
714
+ barycentric coordinates)
715
+ *J* is a (N x 2 x 2) array of jacobian matrices (jacobian matrix at
716
+ triangle first apex)
717
+ *ecc* is a (N x 3 x 1) array (array of column-matrices of triangle
718
+ eccentricities)
719
+ *dofs* is a (N x 1 x 9) arrays (arrays of row-matrices) of computed
720
+ degrees of freedom.
721
+
722
+ Returns
723
+ -------
724
+ Returns the values of interpolated function derivatives [dz/dx, dz/dy]
725
+ in global coordinates at locations alpha, as a column-matrices of
726
+ shape (N x 2 x 1).
727
+ """
728
+ subtri = np.argmin(alpha, axis=1)[:, 0]
729
+ ksi = _roll_vectorized(alpha, -subtri, axis=0)
730
+ E = _roll_vectorized(ecc, -subtri, axis=0)
731
+ x = ksi[:, 0, 0]
732
+ y = ksi[:, 1, 0]
733
+ z = ksi[:, 2, 0]
734
+ x_sq = x*x
735
+ y_sq = y*y
736
+ z_sq = z*z
737
+ dV = _to_matrix_vectorized([
738
+ [ -3.*x_sq, -3.*x_sq],
739
+ [ 3.*y_sq, 0.],
740
+ [ 0., 3.*z_sq],
741
+ [ -2.*x*z, -2.*x*z+x_sq],
742
+ [-2.*x*y+x_sq, -2.*x*y],
743
+ [ 2.*x*y-y_sq, -y_sq],
744
+ [ 2.*y*z, y_sq],
745
+ [ z_sq, 2.*y*z],
746
+ [ -z_sq, 2.*x*z-z_sq],
747
+ [ x*z-y*z, x*y-y*z]])
748
+ # Puts back dV in first apex basis
749
+ dV = dV @ _extract_submatrices(
750
+ self.rotate_dV, subtri, block_size=2, axis=0)
751
+
752
+ prod = self.M @ dV
753
+ prod += _scalar_vectorized(E[:, 0, 0], self.M0 @ dV)
754
+ prod += _scalar_vectorized(E[:, 1, 0], self.M1 @ dV)
755
+ prod += _scalar_vectorized(E[:, 2, 0], self.M2 @ dV)
756
+ dsdksi = _roll_vectorized(prod, 3*subtri, axis=0)
757
+ dfdksi = dofs @ dsdksi
758
+ # In global coordinates:
759
+ # Here we try to deal with the simplest colinear cases, returning a
760
+ # null matrix.
761
+ J_inv = _safe_inv22_vectorized(J)
762
+ dfdx = J_inv @ _transpose_vectorized(dfdksi)
763
+ return dfdx
764
+
765
+ def get_function_hessians(self, alpha, J, ecc, dofs):
766
+ """
767
+ Parameters
768
+ ----------
769
+ *alpha* is a (N x 3 x 1) array (array of column-matrices) of
770
+ barycentric coordinates
771
+ *J* is a (N x 2 x 2) array of jacobian matrices (jacobian matrix at
772
+ triangle first apex)
773
+ *ecc* is a (N x 3 x 1) array (array of column-matrices) of triangle
774
+ eccentricities
775
+ *dofs* is a (N x 1 x 9) arrays (arrays of row-matrices) of computed
776
+ degrees of freedom.
777
+
778
+ Returns
779
+ -------
780
+ Returns the values of interpolated function 2nd-derivatives
781
+ [d2z/dx2, d2z/dy2, d2z/dxdy] in global coordinates at locations alpha,
782
+ as a column-matrices of shape (N x 3 x 1).
783
+ """
784
+ d2sdksi2 = self.get_d2Sidksij2(alpha, ecc)
785
+ d2fdksi2 = dofs @ d2sdksi2
786
+ H_rot = self.get_Hrot_from_J(J)
787
+ d2fdx2 = d2fdksi2 @ H_rot
788
+ return _transpose_vectorized(d2fdx2)
789
+
790
+ def get_d2Sidksij2(self, alpha, ecc):
791
+ """
792
+ Parameters
793
+ ----------
794
+ *alpha* is a (N x 3 x 1) array (array of column-matrices) of
795
+ barycentric coordinates
796
+ *ecc* is a (N x 3 x 1) array (array of column-matrices) of triangle
797
+ eccentricities
798
+
799
+ Returns
800
+ -------
801
+ Returns the arrays d2sdksi2 (N x 3 x 1) Hessian of shape functions
802
+ expressed in covariant coordinates in first apex basis.
803
+ """
804
+ subtri = np.argmin(alpha, axis=1)[:, 0]
805
+ ksi = _roll_vectorized(alpha, -subtri, axis=0)
806
+ E = _roll_vectorized(ecc, -subtri, axis=0)
807
+ x = ksi[:, 0, 0]
808
+ y = ksi[:, 1, 0]
809
+ z = ksi[:, 2, 0]
810
+ d2V = _to_matrix_vectorized([
811
+ [ 6.*x, 6.*x, 6.*x],
812
+ [ 6.*y, 0., 0.],
813
+ [ 0., 6.*z, 0.],
814
+ [ 2.*z, 2.*z-4.*x, 2.*z-2.*x],
815
+ [2.*y-4.*x, 2.*y, 2.*y-2.*x],
816
+ [2.*x-4.*y, 0., -2.*y],
817
+ [ 2.*z, 0., 2.*y],
818
+ [ 0., 2.*y, 2.*z],
819
+ [ 0., 2.*x-4.*z, -2.*z],
820
+ [ -2.*z, -2.*y, x-y-z]])
821
+ # Puts back d2V in first apex basis
822
+ d2V = d2V @ _extract_submatrices(
823
+ self.rotate_d2V, subtri, block_size=3, axis=0)
824
+ prod = self.M @ d2V
825
+ prod += _scalar_vectorized(E[:, 0, 0], self.M0 @ d2V)
826
+ prod += _scalar_vectorized(E[:, 1, 0], self.M1 @ d2V)
827
+ prod += _scalar_vectorized(E[:, 2, 0], self.M2 @ d2V)
828
+ d2sdksi2 = _roll_vectorized(prod, 3*subtri, axis=0)
829
+ return d2sdksi2
830
+
831
+ def get_bending_matrices(self, J, ecc):
832
+ """
833
+ Parameters
834
+ ----------
835
+ *J* is a (N x 2 x 2) array of jacobian matrices (jacobian matrix at
836
+ triangle first apex)
837
+ *ecc* is a (N x 3 x 1) array (array of column-matrices) of triangle
838
+ eccentricities
839
+
840
+ Returns
841
+ -------
842
+ Returns the element K matrices for bending energy expressed in
843
+ GLOBAL nodal coordinates.
844
+ K_ij = integral [ (d2zi/dx2 + d2zi/dy2) * (d2zj/dx2 + d2zj/dy2) dA]
845
+ tri_J is needed to rotate dofs from local basis to global basis
846
+ """
847
+ n = np.size(ecc, 0)
848
+
849
+ # 1) matrix to rotate dofs in global coordinates
850
+ J1 = self.J0_to_J1 @ J
851
+ J2 = self.J0_to_J2 @ J
852
+ DOF_rot = np.zeros([n, 9, 9], dtype=np.float64)
853
+ DOF_rot[:, 0, 0] = 1
854
+ DOF_rot[:, 3, 3] = 1
855
+ DOF_rot[:, 6, 6] = 1
856
+ DOF_rot[:, 1:3, 1:3] = J
857
+ DOF_rot[:, 4:6, 4:6] = J1
858
+ DOF_rot[:, 7:9, 7:9] = J2
859
+
860
+ # 2) matrix to rotate Hessian in global coordinates.
861
+ H_rot, area = self.get_Hrot_from_J(J, return_area=True)
862
+
863
+ # 3) Computes stiffness matrix
864
+ # Gauss quadrature.
865
+ K = np.zeros([n, 9, 9], dtype=np.float64)
866
+ weights = self.gauss_w
867
+ pts = self.gauss_pts
868
+ for igauss in range(self.n_gauss):
869
+ alpha = np.tile(pts[igauss, :], n).reshape(n, 3)
870
+ alpha = np.expand_dims(alpha, 2)
871
+ weight = weights[igauss]
872
+ d2Skdksi2 = self.get_d2Sidksij2(alpha, ecc)
873
+ d2Skdx2 = d2Skdksi2 @ H_rot
874
+ K += weight * (d2Skdx2 @ self.E @ _transpose_vectorized(d2Skdx2))
875
+
876
+ # 4) With nodal (not elem) dofs
877
+ K = _transpose_vectorized(DOF_rot) @ K @ DOF_rot
878
+
879
+ # 5) Need the area to compute total element energy
880
+ return _scalar_vectorized(area, K)
881
+
882
+ def get_Hrot_from_J(self, J, return_area=False):
883
+ """
884
+ Parameters
885
+ ----------
886
+ *J* is a (N x 2 x 2) array of jacobian matrices (jacobian matrix at
887
+ triangle first apex)
888
+
889
+ Returns
890
+ -------
891
+ Returns H_rot used to rotate Hessian from local basis of first apex,
892
+ to global coordinates.
893
+ if *return_area* is True, returns also the triangle area (0.5*det(J))
894
+ """
895
+ # Here we try to deal with the simplest colinear cases; a null
896
+ # energy and area is imposed.
897
+ J_inv = _safe_inv22_vectorized(J)
898
+ Ji00 = J_inv[:, 0, 0]
899
+ Ji11 = J_inv[:, 1, 1]
900
+ Ji10 = J_inv[:, 1, 0]
901
+ Ji01 = J_inv[:, 0, 1]
902
+ H_rot = _to_matrix_vectorized([
903
+ [Ji00*Ji00, Ji10*Ji10, Ji00*Ji10],
904
+ [Ji01*Ji01, Ji11*Ji11, Ji01*Ji11],
905
+ [2*Ji00*Ji01, 2*Ji11*Ji10, Ji00*Ji11+Ji10*Ji01]])
906
+ if not return_area:
907
+ return H_rot
908
+ else:
909
+ area = 0.5 * (J[:, 0, 0]*J[:, 1, 1] - J[:, 0, 1]*J[:, 1, 0])
910
+ return H_rot, area
911
+
912
+ def get_Kff_and_Ff(self, J, ecc, triangles, Uc):
913
+ """
914
+ Build K and F for the following elliptic formulation:
915
+ minimization of curvature energy with value of function at node
916
+ imposed and derivatives 'free'.
917
+
918
+ Build the global Kff matrix in cco format.
919
+ Build the full Ff vec Ff = - Kfc x Uc.
920
+
921
+ Parameters
922
+ ----------
923
+ *J* is a (N x 2 x 2) array of jacobian matrices (jacobian matrix at
924
+ triangle first apex)
925
+ *ecc* is a (N x 3 x 1) array (array of column-matrices) of triangle
926
+ eccentricities
927
+ *triangles* is a (N x 3) array of nodes indexes.
928
+ *Uc* is (N x 3) array of imposed displacements at nodes
929
+
930
+ Returns
931
+ -------
932
+ (Kff_rows, Kff_cols, Kff_vals) Kff matrix in COO format - Duplicate
933
+ (row, col) entries must be summed.
934
+ Ff: force vector - dim npts * 3
935
+ """
936
+ ntri = np.size(ecc, 0)
937
+ vec_range = np.arange(ntri, dtype=np.int32)
938
+ c_indices = np.full(ntri, -1, dtype=np.int32) # for unused dofs, -1
939
+ f_dof = [1, 2, 4, 5, 7, 8]
940
+ c_dof = [0, 3, 6]
941
+
942
+ # vals, rows and cols indices in global dof numbering
943
+ f_dof_indices = _to_matrix_vectorized([[
944
+ c_indices, triangles[:, 0]*2, triangles[:, 0]*2+1,
945
+ c_indices, triangles[:, 1]*2, triangles[:, 1]*2+1,
946
+ c_indices, triangles[:, 2]*2, triangles[:, 2]*2+1]])
947
+
948
+ expand_indices = np.ones([ntri, 9, 1], dtype=np.int32)
949
+ f_row_indices = _transpose_vectorized(expand_indices @ f_dof_indices)
950
+ f_col_indices = expand_indices @ f_dof_indices
951
+ K_elem = self.get_bending_matrices(J, ecc)
952
+
953
+ # Extracting sub-matrices
954
+ # Explanation & notations:
955
+ # * Subscript f denotes 'free' degrees of freedom (i.e. dz/dx, dz/dx)
956
+ # * Subscript c denotes 'condensated' (imposed) degrees of freedom
957
+ # (i.e. z at all nodes)
958
+ # * F = [Ff, Fc] is the force vector
959
+ # * U = [Uf, Uc] is the imposed dof vector
960
+ # [ Kff Kfc ]
961
+ # * K = [ ] is the laplacian stiffness matrix
962
+ # [ Kcf Kff ]
963
+ # * As F = K x U one gets straightforwardly: Ff = - Kfc x Uc
964
+
965
+ # Computing Kff stiffness matrix in sparse COO format
966
+ Kff_vals = np.ravel(K_elem[np.ix_(vec_range, f_dof, f_dof)])
967
+ Kff_rows = np.ravel(f_row_indices[np.ix_(vec_range, f_dof, f_dof)])
968
+ Kff_cols = np.ravel(f_col_indices[np.ix_(vec_range, f_dof, f_dof)])
969
+
970
+ # Computing Ff force vector in sparse COO format
971
+ Kfc_elem = K_elem[np.ix_(vec_range, f_dof, c_dof)]
972
+ Uc_elem = np.expand_dims(Uc, axis=2)
973
+ Ff_elem = -(Kfc_elem @ Uc_elem)[:, :, 0]
974
+ Ff_indices = f_dof_indices[np.ix_(vec_range, [0], f_dof)][:, 0, :]
975
+
976
+ # Extracting Ff force vector in dense format
977
+ # We have to sum duplicate indices - using bincount
978
+ Ff = np.bincount(np.ravel(Ff_indices), weights=np.ravel(Ff_elem))
979
+ return Kff_rows, Kff_cols, Kff_vals, Ff
980
+
981
+
982
+ # :class:_DOF_estimator, _DOF_estimator_user, _DOF_estimator_geom,
983
+ # _DOF_estimator_min_E
984
+ # Private classes used to compute the degree of freedom of each triangular
985
+ # element for the TriCubicInterpolator.
986
+ class _DOF_estimator:
987
+ """
988
+ Abstract base class for classes used to estimate a function's first
989
+ derivatives, and deduce the dofs for a CubicTriInterpolator using a
990
+ reduced HCT element formulation.
991
+
992
+ Derived classes implement ``compute_df(self, **kwargs)``, returning
993
+ ``np.vstack([dfx, dfy]).T`` where ``dfx, dfy`` are the estimation of the 2
994
+ gradient coordinates.
995
+ """
996
+ def __init__(self, interpolator, **kwargs):
997
+ _api.check_isinstance(CubicTriInterpolator, interpolator=interpolator)
998
+ self._pts = interpolator._pts
999
+ self._tris_pts = interpolator._tris_pts
1000
+ self.z = interpolator._z
1001
+ self._triangles = interpolator._triangles
1002
+ (self._unit_x, self._unit_y) = (interpolator._unit_x,
1003
+ interpolator._unit_y)
1004
+ self.dz = self.compute_dz(**kwargs)
1005
+ self.compute_dof_from_df()
1006
+
1007
+ def compute_dz(self, **kwargs):
1008
+ raise NotImplementedError
1009
+
1010
+ def compute_dof_from_df(self):
1011
+ """
1012
+ Compute reduced-HCT elements degrees of freedom, from the gradient.
1013
+ """
1014
+ J = CubicTriInterpolator._get_jacobian(self._tris_pts)
1015
+ tri_z = self.z[self._triangles]
1016
+ tri_dz = self.dz[self._triangles]
1017
+ tri_dof = self.get_dof_vec(tri_z, tri_dz, J)
1018
+ return tri_dof
1019
+
1020
+ @staticmethod
1021
+ def get_dof_vec(tri_z, tri_dz, J):
1022
+ """
1023
+ Compute the dof vector of a triangle, from the value of f, df and
1024
+ of the local Jacobian at each node.
1025
+
1026
+ Parameters
1027
+ ----------
1028
+ tri_z : shape (3,) array
1029
+ f nodal values.
1030
+ tri_dz : shape (3, 2) array
1031
+ df/dx, df/dy nodal values.
1032
+ J
1033
+ Jacobian matrix in local basis of apex 0.
1034
+
1035
+ Returns
1036
+ -------
1037
+ dof : shape (9,) array
1038
+ For each apex ``iapex``::
1039
+
1040
+ dof[iapex*3+0] = f(Ai)
1041
+ dof[iapex*3+1] = df(Ai).(AiAi+)
1042
+ dof[iapex*3+2] = df(Ai).(AiAi-)
1043
+ """
1044
+ npt = tri_z.shape[0]
1045
+ dof = np.zeros([npt, 9], dtype=np.float64)
1046
+ J1 = _ReducedHCT_Element.J0_to_J1 @ J
1047
+ J2 = _ReducedHCT_Element.J0_to_J2 @ J
1048
+
1049
+ col0 = J @ np.expand_dims(tri_dz[:, 0, :], axis=2)
1050
+ col1 = J1 @ np.expand_dims(tri_dz[:, 1, :], axis=2)
1051
+ col2 = J2 @ np.expand_dims(tri_dz[:, 2, :], axis=2)
1052
+
1053
+ dfdksi = _to_matrix_vectorized([
1054
+ [col0[:, 0, 0], col1[:, 0, 0], col2[:, 0, 0]],
1055
+ [col0[:, 1, 0], col1[:, 1, 0], col2[:, 1, 0]]])
1056
+ dof[:, 0:7:3] = tri_z
1057
+ dof[:, 1:8:3] = dfdksi[:, 0]
1058
+ dof[:, 2:9:3] = dfdksi[:, 1]
1059
+ return dof
1060
+
1061
+
1062
+ class _DOF_estimator_user(_DOF_estimator):
1063
+ """dz is imposed by user; accounts for scaling if any."""
1064
+
1065
+ def compute_dz(self, dz):
1066
+ (dzdx, dzdy) = dz
1067
+ dzdx = dzdx * self._unit_x
1068
+ dzdy = dzdy * self._unit_y
1069
+ return np.vstack([dzdx, dzdy]).T
1070
+
1071
+
1072
+ class _DOF_estimator_geom(_DOF_estimator):
1073
+ """Fast 'geometric' approximation, recommended for large arrays."""
1074
+
1075
+ def compute_dz(self):
1076
+ """
1077
+ self.df is computed as weighted average of _triangles sharing a common
1078
+ node. On each triangle itri f is first assumed linear (= ~f), which
1079
+ allows to compute d~f[itri]
1080
+ Then the following approximation of df nodal values is then proposed:
1081
+ f[ipt] = SUM ( w[itri] x d~f[itri] , for itri sharing apex ipt)
1082
+ The weighted coeff. w[itri] are proportional to the angle of the
1083
+ triangle itri at apex ipt
1084
+ """
1085
+ el_geom_w = self.compute_geom_weights()
1086
+ el_geom_grad = self.compute_geom_grads()
1087
+
1088
+ # Sum of weights coeffs
1089
+ w_node_sum = np.bincount(np.ravel(self._triangles),
1090
+ weights=np.ravel(el_geom_w))
1091
+
1092
+ # Sum of weighted df = (dfx, dfy)
1093
+ dfx_el_w = np.empty_like(el_geom_w)
1094
+ dfy_el_w = np.empty_like(el_geom_w)
1095
+ for iapex in range(3):
1096
+ dfx_el_w[:, iapex] = el_geom_w[:, iapex]*el_geom_grad[:, 0]
1097
+ dfy_el_w[:, iapex] = el_geom_w[:, iapex]*el_geom_grad[:, 1]
1098
+ dfx_node_sum = np.bincount(np.ravel(self._triangles),
1099
+ weights=np.ravel(dfx_el_w))
1100
+ dfy_node_sum = np.bincount(np.ravel(self._triangles),
1101
+ weights=np.ravel(dfy_el_w))
1102
+
1103
+ # Estimation of df
1104
+ dfx_estim = dfx_node_sum/w_node_sum
1105
+ dfy_estim = dfy_node_sum/w_node_sum
1106
+ return np.vstack([dfx_estim, dfy_estim]).T
1107
+
1108
+ def compute_geom_weights(self):
1109
+ """
1110
+ Build the (nelems, 3) weights coeffs of _triangles angles,
1111
+ renormalized so that np.sum(weights, axis=1) == np.ones(nelems)
1112
+ """
1113
+ weights = np.zeros([np.size(self._triangles, 0), 3])
1114
+ tris_pts = self._tris_pts
1115
+ for ipt in range(3):
1116
+ p0 = tris_pts[:, ipt % 3, :]
1117
+ p1 = tris_pts[:, (ipt+1) % 3, :]
1118
+ p2 = tris_pts[:, (ipt-1) % 3, :]
1119
+ alpha1 = np.arctan2(p1[:, 1]-p0[:, 1], p1[:, 0]-p0[:, 0])
1120
+ alpha2 = np.arctan2(p2[:, 1]-p0[:, 1], p2[:, 0]-p0[:, 0])
1121
+ # In the below formula we could take modulo 2. but
1122
+ # modulo 1. is safer regarding round-off errors (flat triangles).
1123
+ angle = np.abs(((alpha2-alpha1) / np.pi) % 1)
1124
+ # Weight proportional to angle up np.pi/2; null weight for
1125
+ # degenerated cases 0 and np.pi (note that *angle* is normalized
1126
+ # by np.pi).
1127
+ weights[:, ipt] = 0.5 - np.abs(angle-0.5)
1128
+ return weights
1129
+
1130
+ def compute_geom_grads(self):
1131
+ """
1132
+ Compute the (global) gradient component of f assumed linear (~f).
1133
+ returns array df of shape (nelems, 2)
1134
+ df[ielem].dM[ielem] = dz[ielem] i.e. df = dz x dM = dM.T^-1 x dz
1135
+ """
1136
+ tris_pts = self._tris_pts
1137
+ tris_f = self.z[self._triangles]
1138
+
1139
+ dM1 = tris_pts[:, 1, :] - tris_pts[:, 0, :]
1140
+ dM2 = tris_pts[:, 2, :] - tris_pts[:, 0, :]
1141
+ dM = np.dstack([dM1, dM2])
1142
+ # Here we try to deal with the simplest colinear cases: a null
1143
+ # gradient is assumed in this case.
1144
+ dM_inv = _safe_inv22_vectorized(dM)
1145
+
1146
+ dZ1 = tris_f[:, 1] - tris_f[:, 0]
1147
+ dZ2 = tris_f[:, 2] - tris_f[:, 0]
1148
+ dZ = np.vstack([dZ1, dZ2]).T
1149
+ df = np.empty_like(dZ)
1150
+
1151
+ # With np.einsum: could be ej,eji -> ej
1152
+ df[:, 0] = dZ[:, 0]*dM_inv[:, 0, 0] + dZ[:, 1]*dM_inv[:, 1, 0]
1153
+ df[:, 1] = dZ[:, 0]*dM_inv[:, 0, 1] + dZ[:, 1]*dM_inv[:, 1, 1]
1154
+ return df
1155
+
1156
+
1157
+ class _DOF_estimator_min_E(_DOF_estimator_geom):
1158
+ """
1159
+ The 'smoothest' approximation, df is computed through global minimization
1160
+ of the bending energy:
1161
+ E(f) = integral[(d2z/dx2 + d2z/dy2 + 2 d2z/dxdy)**2 dA]
1162
+ """
1163
+ def __init__(self, Interpolator):
1164
+ self._eccs = Interpolator._eccs
1165
+ super().__init__(Interpolator)
1166
+
1167
+ def compute_dz(self):
1168
+ """
1169
+ Elliptic solver for bending energy minimization.
1170
+ Uses a dedicated 'toy' sparse Jacobi PCG solver.
1171
+ """
1172
+ # Initial guess for iterative PCG solver.
1173
+ dz_init = super().compute_dz()
1174
+ Uf0 = np.ravel(dz_init)
1175
+
1176
+ reference_element = _ReducedHCT_Element()
1177
+ J = CubicTriInterpolator._get_jacobian(self._tris_pts)
1178
+ eccs = self._eccs
1179
+ triangles = self._triangles
1180
+ Uc = self.z[self._triangles]
1181
+
1182
+ # Building stiffness matrix and force vector in COO format
1183
+ Kff_rows, Kff_cols, Kff_vals, Ff = reference_element.get_Kff_and_Ff(
1184
+ J, eccs, triangles, Uc)
1185
+
1186
+ # Building sparse matrix and solving minimization problem
1187
+ # We could use scipy.sparse direct solver; however to avoid this
1188
+ # external dependency an implementation of a simple PCG solver with
1189
+ # a simple diagonal Jacobi preconditioner is implemented.
1190
+ tol = 1.e-10
1191
+ n_dof = Ff.shape[0]
1192
+ Kff_coo = _Sparse_Matrix_coo(Kff_vals, Kff_rows, Kff_cols,
1193
+ shape=(n_dof, n_dof))
1194
+ Kff_coo.compress_csc()
1195
+ Uf, err = _cg(A=Kff_coo, b=Ff, x0=Uf0, tol=tol)
1196
+ # If the PCG did not converge, we return the best guess between Uf0
1197
+ # and Uf.
1198
+ err0 = np.linalg.norm(Kff_coo.dot(Uf0) - Ff)
1199
+ if err0 < err:
1200
+ # Maybe a good occasion to raise a warning here ?
1201
+ _api.warn_external("In TriCubicInterpolator initialization, "
1202
+ "PCG sparse solver did not converge after "
1203
+ "1000 iterations. `geom` approximation is "
1204
+ "used instead of `min_E`")
1205
+ Uf = Uf0
1206
+
1207
+ # Building dz from Uf
1208
+ dz = np.empty([self._pts.shape[0], 2], dtype=np.float64)
1209
+ dz[:, 0] = Uf[::2]
1210
+ dz[:, 1] = Uf[1::2]
1211
+ return dz
1212
+
1213
+
1214
+ # The following private :class:_Sparse_Matrix_coo and :func:_cg provide
1215
+ # a PCG sparse solver for (symmetric) elliptic problems.
1216
+ class _Sparse_Matrix_coo:
1217
+ def __init__(self, vals, rows, cols, shape):
1218
+ """
1219
+ Create a sparse matrix in COO format.
1220
+ *vals*: arrays of values of non-null entries of the matrix
1221
+ *rows*: int arrays of rows of non-null entries of the matrix
1222
+ *cols*: int arrays of cols of non-null entries of the matrix
1223
+ *shape*: 2-tuple (n, m) of matrix shape
1224
+ """
1225
+ self.n, self.m = shape
1226
+ self.vals = np.asarray(vals, dtype=np.float64)
1227
+ self.rows = np.asarray(rows, dtype=np.int32)
1228
+ self.cols = np.asarray(cols, dtype=np.int32)
1229
+
1230
+ def dot(self, V):
1231
+ """
1232
+ Dot product of self by a vector *V* in sparse-dense to dense format
1233
+ *V* dense vector of shape (self.m,).
1234
+ """
1235
+ assert V.shape == (self.m,)
1236
+ return np.bincount(self.rows,
1237
+ weights=self.vals*V[self.cols],
1238
+ minlength=self.m)
1239
+
1240
+ def compress_csc(self):
1241
+ """
1242
+ Compress rows, cols, vals / summing duplicates. Sort for csc format.
1243
+ """
1244
+ _, unique, indices = np.unique(
1245
+ self.rows + self.n*self.cols,
1246
+ return_index=True, return_inverse=True)
1247
+ self.rows = self.rows[unique]
1248
+ self.cols = self.cols[unique]
1249
+ self.vals = np.bincount(indices, weights=self.vals)
1250
+
1251
+ def compress_csr(self):
1252
+ """
1253
+ Compress rows, cols, vals / summing duplicates. Sort for csr format.
1254
+ """
1255
+ _, unique, indices = np.unique(
1256
+ self.m*self.rows + self.cols,
1257
+ return_index=True, return_inverse=True)
1258
+ self.rows = self.rows[unique]
1259
+ self.cols = self.cols[unique]
1260
+ self.vals = np.bincount(indices, weights=self.vals)
1261
+
1262
+ def to_dense(self):
1263
+ """
1264
+ Return a dense matrix representing self, mainly for debugging purposes.
1265
+ """
1266
+ ret = np.zeros([self.n, self.m], dtype=np.float64)
1267
+ nvals = self.vals.size
1268
+ for i in range(nvals):
1269
+ ret[self.rows[i], self.cols[i]] += self.vals[i]
1270
+ return ret
1271
+
1272
+ def __str__(self):
1273
+ return self.to_dense().__str__()
1274
+
1275
+ @property
1276
+ def diag(self):
1277
+ """Return the (dense) vector of the diagonal elements."""
1278
+ in_diag = (self.rows == self.cols)
1279
+ diag = np.zeros(min(self.n, self.n), dtype=np.float64) # default 0.
1280
+ diag[self.rows[in_diag]] = self.vals[in_diag]
1281
+ return diag
1282
+
1283
+
1284
+ def _cg(A, b, x0=None, tol=1.e-10, maxiter=1000):
1285
+ """
1286
+ Use Preconditioned Conjugate Gradient iteration to solve A x = b
1287
+ A simple Jacobi (diagonal) preconditioner is used.
1288
+
1289
+ Parameters
1290
+ ----------
1291
+ A : _Sparse_Matrix_coo
1292
+ *A* must have been compressed before by compress_csc or
1293
+ compress_csr method.
1294
+ b : array
1295
+ Right hand side of the linear system.
1296
+ x0 : array, optional
1297
+ Starting guess for the solution. Defaults to the zero vector.
1298
+ tol : float, optional
1299
+ Tolerance to achieve. The algorithm terminates when the relative
1300
+ residual is below tol. Default is 1e-10.
1301
+ maxiter : int, optional
1302
+ Maximum number of iterations. Iteration will stop after *maxiter*
1303
+ steps even if the specified tolerance has not been achieved. Defaults
1304
+ to 1000.
1305
+
1306
+ Returns
1307
+ -------
1308
+ x : array
1309
+ The converged solution.
1310
+ err : float
1311
+ The absolute error np.linalg.norm(A.dot(x) - b)
1312
+ """
1313
+ n = b.size
1314
+ assert A.n == n
1315
+ assert A.m == n
1316
+ b_norm = np.linalg.norm(b)
1317
+
1318
+ # Jacobi pre-conditioner
1319
+ kvec = A.diag
1320
+ # For diag elem < 1e-6 we keep 1e-6.
1321
+ kvec = np.maximum(kvec, 1e-6)
1322
+
1323
+ # Initial guess
1324
+ if x0 is None:
1325
+ x = np.zeros(n)
1326
+ else:
1327
+ x = x0
1328
+
1329
+ r = b - A.dot(x)
1330
+ w = r/kvec
1331
+
1332
+ p = np.zeros(n)
1333
+ beta = 0.0
1334
+ rho = np.dot(r, w)
1335
+ k = 0
1336
+
1337
+ # Following C. T. Kelley
1338
+ while (np.sqrt(abs(rho)) > tol*b_norm) and (k < maxiter):
1339
+ p = w + beta*p
1340
+ z = A.dot(p)
1341
+ alpha = rho/np.dot(p, z)
1342
+ r = r - alpha*z
1343
+ w = r/kvec
1344
+ rhoold = rho
1345
+ rho = np.dot(r, w)
1346
+ x = x + alpha*p
1347
+ beta = rho/rhoold
1348
+ # err = np.linalg.norm(A.dot(x) - b) # absolute accuracy - not used
1349
+ k += 1
1350
+ err = np.linalg.norm(A.dot(x) - b)
1351
+ return x, err
1352
+
1353
+
1354
+ # The following private functions:
1355
+ # :func:`_safe_inv22_vectorized`
1356
+ # :func:`_pseudo_inv22sym_vectorized`
1357
+ # :func:`_scalar_vectorized`
1358
+ # :func:`_transpose_vectorized`
1359
+ # :func:`_roll_vectorized`
1360
+ # :func:`_to_matrix_vectorized`
1361
+ # :func:`_extract_submatrices`
1362
+ # provide fast numpy implementation of some standard operations on arrays of
1363
+ # matrices - stored as (:, n_rows, n_cols)-shaped np.arrays.
1364
+
1365
+ # Development note: Dealing with pathologic 'flat' triangles in the
1366
+ # CubicTriInterpolator code and impact on (2, 2)-matrix inversion functions
1367
+ # :func:`_safe_inv22_vectorized` and :func:`_pseudo_inv22sym_vectorized`.
1368
+ #
1369
+ # Goals:
1370
+ # 1) The CubicTriInterpolator should be able to handle flat or almost flat
1371
+ # triangles without raising an error,
1372
+ # 2) These degenerated triangles should have no impact on the automatic dof
1373
+ # calculation (associated with null weight for the _DOF_estimator_geom and
1374
+ # with null energy for the _DOF_estimator_min_E),
1375
+ # 3) Linear patch test should be passed exactly on degenerated meshes,
1376
+ # 4) Interpolation (with :meth:`_interpolate_single_key` or
1377
+ # :meth:`_interpolate_multi_key`) shall be correctly handled even *inside*
1378
+ # the pathologic triangles, to interact correctly with a TriRefiner class.
1379
+ #
1380
+ # Difficulties:
1381
+ # Flat triangles have rank-deficient *J* (so-called jacobian matrix) and
1382
+ # *metric* (the metric tensor = J x J.T). Computation of the local
1383
+ # tangent plane is also problematic.
1384
+ #
1385
+ # Implementation:
1386
+ # Most of the time, when computing the inverse of a rank-deficient matrix it
1387
+ # is safe to simply return the null matrix (which is the implementation in
1388
+ # :func:`_safe_inv22_vectorized`). This is because of point 2), itself
1389
+ # enforced by:
1390
+ # - null area hence null energy in :class:`_DOF_estimator_min_E`
1391
+ # - angles close or equal to 0 or np.pi hence null weight in
1392
+ # :class:`_DOF_estimator_geom`.
1393
+ # Note that the function angle -> weight is continuous and maximum for an
1394
+ # angle np.pi/2 (refer to :meth:`compute_geom_weights`)
1395
+ # The exception is the computation of barycentric coordinates, which is done
1396
+ # by inversion of the *metric* matrix. In this case, we need to compute a set
1397
+ # of valid coordinates (1 among numerous possibilities), to ensure point 4).
1398
+ # We benefit here from the symmetry of metric = J x J.T, which makes it easier
1399
+ # to compute a pseudo-inverse in :func:`_pseudo_inv22sym_vectorized`
1400
+ def _safe_inv22_vectorized(M):
1401
+ """
1402
+ Inversion of arrays of (2, 2) matrices, returns 0 for rank-deficient
1403
+ matrices.
1404
+
1405
+ *M* : array of (2, 2) matrices to inverse, shape (n, 2, 2)
1406
+ """
1407
+ _api.check_shape((None, 2, 2), M=M)
1408
+ M_inv = np.empty_like(M)
1409
+ prod1 = M[:, 0, 0]*M[:, 1, 1]
1410
+ delta = prod1 - M[:, 0, 1]*M[:, 1, 0]
1411
+
1412
+ # We set delta_inv to 0. in case of a rank deficient matrix; a
1413
+ # rank-deficient input matrix *M* will lead to a null matrix in output
1414
+ rank2 = (np.abs(delta) > 1e-8*np.abs(prod1))
1415
+ if np.all(rank2):
1416
+ # Normal 'optimized' flow.
1417
+ delta_inv = 1./delta
1418
+ else:
1419
+ # 'Pathologic' flow.
1420
+ delta_inv = np.zeros(M.shape[0])
1421
+ delta_inv[rank2] = 1./delta[rank2]
1422
+
1423
+ M_inv[:, 0, 0] = M[:, 1, 1]*delta_inv
1424
+ M_inv[:, 0, 1] = -M[:, 0, 1]*delta_inv
1425
+ M_inv[:, 1, 0] = -M[:, 1, 0]*delta_inv
1426
+ M_inv[:, 1, 1] = M[:, 0, 0]*delta_inv
1427
+ return M_inv
1428
+
1429
+
1430
+ def _pseudo_inv22sym_vectorized(M):
1431
+ """
1432
+ Inversion of arrays of (2, 2) SYMMETRIC matrices; returns the
1433
+ (Moore-Penrose) pseudo-inverse for rank-deficient matrices.
1434
+
1435
+ In case M is of rank 1, we have M = trace(M) x P where P is the orthogonal
1436
+ projection on Im(M), and we return trace(M)^-1 x P == M / trace(M)**2
1437
+ In case M is of rank 0, we return the null matrix.
1438
+
1439
+ *M* : array of (2, 2) matrices to inverse, shape (n, 2, 2)
1440
+ """
1441
+ _api.check_shape((None, 2, 2), M=M)
1442
+ M_inv = np.empty_like(M)
1443
+ prod1 = M[:, 0, 0]*M[:, 1, 1]
1444
+ delta = prod1 - M[:, 0, 1]*M[:, 1, 0]
1445
+ rank2 = (np.abs(delta) > 1e-8*np.abs(prod1))
1446
+
1447
+ if np.all(rank2):
1448
+ # Normal 'optimized' flow.
1449
+ M_inv[:, 0, 0] = M[:, 1, 1] / delta
1450
+ M_inv[:, 0, 1] = -M[:, 0, 1] / delta
1451
+ M_inv[:, 1, 0] = -M[:, 1, 0] / delta
1452
+ M_inv[:, 1, 1] = M[:, 0, 0] / delta
1453
+ else:
1454
+ # 'Pathologic' flow.
1455
+ # Here we have to deal with 2 sub-cases
1456
+ # 1) First sub-case: matrices of rank 2:
1457
+ delta = delta[rank2]
1458
+ M_inv[rank2, 0, 0] = M[rank2, 1, 1] / delta
1459
+ M_inv[rank2, 0, 1] = -M[rank2, 0, 1] / delta
1460
+ M_inv[rank2, 1, 0] = -M[rank2, 1, 0] / delta
1461
+ M_inv[rank2, 1, 1] = M[rank2, 0, 0] / delta
1462
+ # 2) Second sub-case: rank-deficient matrices of rank 0 and 1:
1463
+ rank01 = ~rank2
1464
+ tr = M[rank01, 0, 0] + M[rank01, 1, 1]
1465
+ tr_zeros = (np.abs(tr) < 1.e-8)
1466
+ sq_tr_inv = (1.-tr_zeros) / (tr**2+tr_zeros)
1467
+ # sq_tr_inv = 1. / tr**2
1468
+ M_inv[rank01, 0, 0] = M[rank01, 0, 0] * sq_tr_inv
1469
+ M_inv[rank01, 0, 1] = M[rank01, 0, 1] * sq_tr_inv
1470
+ M_inv[rank01, 1, 0] = M[rank01, 1, 0] * sq_tr_inv
1471
+ M_inv[rank01, 1, 1] = M[rank01, 1, 1] * sq_tr_inv
1472
+
1473
+ return M_inv
1474
+
1475
+
1476
+ def _scalar_vectorized(scalar, M):
1477
+ """
1478
+ Scalar product between scalars and matrices.
1479
+ """
1480
+ return scalar[:, np.newaxis, np.newaxis]*M
1481
+
1482
+
1483
+ def _transpose_vectorized(M):
1484
+ """
1485
+ Transposition of an array of matrices *M*.
1486
+ """
1487
+ return np.transpose(M, [0, 2, 1])
1488
+
1489
+
1490
+ def _roll_vectorized(M, roll_indices, axis):
1491
+ """
1492
+ Roll an array of matrices along *axis* (0: rows, 1: columns) according to
1493
+ an array of indices *roll_indices*.
1494
+ """
1495
+ assert axis in [0, 1]
1496
+ ndim = M.ndim
1497
+ assert ndim == 3
1498
+ ndim_roll = roll_indices.ndim
1499
+ assert ndim_roll == 1
1500
+ sh = M.shape
1501
+ r, c = sh[-2:]
1502
+ assert sh[0] == roll_indices.shape[0]
1503
+ vec_indices = np.arange(sh[0], dtype=np.int32)
1504
+
1505
+ # Builds the rolled matrix
1506
+ M_roll = np.empty_like(M)
1507
+ if axis == 0:
1508
+ for ir in range(r):
1509
+ for ic in range(c):
1510
+ M_roll[:, ir, ic] = M[vec_indices, (-roll_indices+ir) % r, ic]
1511
+ else: # 1
1512
+ for ir in range(r):
1513
+ for ic in range(c):
1514
+ M_roll[:, ir, ic] = M[vec_indices, ir, (-roll_indices+ic) % c]
1515
+ return M_roll
1516
+
1517
+
1518
+ def _to_matrix_vectorized(M):
1519
+ """
1520
+ Build an array of matrices from individuals np.arrays of identical shapes.
1521
+
1522
+ Parameters
1523
+ ----------
1524
+ M
1525
+ ncols-list of nrows-lists of shape sh.
1526
+
1527
+ Returns
1528
+ -------
1529
+ M_res : np.array of shape (sh, nrow, ncols)
1530
+ *M_res* satisfies ``M_res[..., i, j] = M[i][j]``.
1531
+ """
1532
+ assert isinstance(M, (tuple, list))
1533
+ assert all(isinstance(item, (tuple, list)) for item in M)
1534
+ c_vec = np.asarray([len(item) for item in M])
1535
+ assert np.all(c_vec-c_vec[0] == 0)
1536
+ r = len(M)
1537
+ c = c_vec[0]
1538
+ M00 = np.asarray(M[0][0])
1539
+ dt = M00.dtype
1540
+ sh = [M00.shape[0], r, c]
1541
+ M_ret = np.empty(sh, dtype=dt)
1542
+ for irow in range(r):
1543
+ for icol in range(c):
1544
+ M_ret[:, irow, icol] = np.asarray(M[irow][icol])
1545
+ return M_ret
1546
+
1547
+
1548
+ def _extract_submatrices(M, block_indices, block_size, axis):
1549
+ """
1550
+ Extract selected blocks of a matrices *M* depending on parameters
1551
+ *block_indices* and *block_size*.
1552
+
1553
+ Returns the array of extracted matrices *Mres* so that ::
1554
+
1555
+ M_res[..., ir, :] = M[(block_indices*block_size+ir), :]
1556
+ """
1557
+ assert block_indices.ndim == 1
1558
+ assert axis in [0, 1]
1559
+
1560
+ r, c = M.shape
1561
+ if axis == 0:
1562
+ sh = [block_indices.shape[0], block_size, c]
1563
+ else: # 1
1564
+ sh = [block_indices.shape[0], r, block_size]
1565
+
1566
+ dt = M.dtype
1567
+ M_res = np.empty(sh, dtype=dt)
1568
+ if axis == 0:
1569
+ for ir in range(block_size):
1570
+ M_res[:, ir, :] = M[(block_indices*block_size+ir), :]
1571
+ else: # 1
1572
+ for ic in range(block_size):
1573
+ M_res[:, :, ic] = M[:, (block_indices*block_size+ic)]
1574
+
1575
+ return M_res