diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_agg_filter.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_agg_filter.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7e512948d38257e10ec6bad944ac589d1576ef2a Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_agg_filter.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_animation.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_animation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..115aab3f99cbac3a5693c72acb73e55b71a339a2 Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_animation.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_axis.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_axis.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dff1153eb23641cd4bc74873b34d2b1b8c6f3938 Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_axis.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_backend_bases.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_backend_bases.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..87f1dea86f958df5dd02bdd4e42f4e7f27245e17 Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_backend_bases.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_backend_cairo.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_backend_cairo.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..70012beaa1fc581699370e90b988b0524a2dfe1b Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_backend_cairo.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_backend_gtk3.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_backend_gtk3.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5a76a6a9ccd5b9bb94a6e2e01efcd431ec69a211 Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_backend_gtk3.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_backend_macosx.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_backend_macosx.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e43bad1bde69607ae1301dd18a738016ac06c0f3 Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_backend_macosx.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_backend_pdf.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_backend_pdf.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a9c1512aa0641d41cebaa2866474c1a6e8180fa5 Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_backend_pdf.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_backend_pgf.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_backend_pgf.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..50a3fe7df9ea52fca3e2c0c203d25a018421221d Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_backend_pgf.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_backend_ps.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_backend_ps.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1f9998d9a2daf10181d4392e7ea18a41e8b55c19 Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_backend_ps.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_backend_svg.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_backend_svg.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..29c31e87d418361b6507a7d64ff38f0cccc6706b Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_backend_svg.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_backend_template.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_backend_template.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..13b4f061de74634064b688d54cb46f0a7016cda7 Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_backend_template.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_backend_tk.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_backend_tk.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fc9122dd85369881cacb51a3d3cdce0aaa81f86b Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_backend_tk.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_backend_tools.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_backend_tools.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..719640a98668f20d23df44bf7cff354aacfd8a22 Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_backend_tools.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_backend_webagg.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_backend_webagg.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bb3edcad49759ccdda48086f61c6954edb062597 Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_backend_webagg.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_backends_interactive.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_backends_interactive.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e4de6794047a0858401f806c43ab648906270ed0 Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_backends_interactive.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_basic.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_basic.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..10e3e964e45acb6b2cd4a7d783870f700e9bb632 Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_basic.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_bbox_tight.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_bbox_tight.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..87c793e1de34c3d4e07400a48ab6ce07bc6f49c9 Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_bbox_tight.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_collections.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_collections.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..31a4736577b7e58418c6e4688b616d2a5ec72c47 Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_collections.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_colorbar.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_colorbar.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c92815b6ae76852c7ae8e79386cead0d417e534e Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_colorbar.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_container.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_container.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..24b177ef949c3b6a41ccc2d3d4ee73d17003cdf0 Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_container.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_contour.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_contour.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2e4ad65d1988660fe931c037c9f306063a756f8b Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_contour.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_dates.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_dates.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e2a4bfa45b016f68383b09fcfaf320884d0b47ed Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_dates.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_doc.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_doc.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7634d3de6496c6d1d37c560a389e02e88055b8d0 Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_doc.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_dviread.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_dviread.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..94c80970c6f0ba4cc8fddb38cb521777226c216a Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_dviread.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_figure.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_figure.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a8a35f24b87a030cfb9321ee9415cccfeca0b70b Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_figure.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_ft2font.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_ft2font.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..53aa1f8c954083d912b148ccd2f22e9e83098e38 Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_ft2font.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_gridspec.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_gridspec.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2128a97d3c8039f73b70743811c183e8e9c9154f Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_gridspec.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_legend.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_legend.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..618a1a495c5ff1d2f7f390460199c4567531f770 Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_legend.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_lines.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_lines.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a1d1a1f8c51e2ebcec5a158af022fe21d9fbd35d Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_lines.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_marker.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_marker.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..82d7679304dd790d57894ef02a678c9a8c7d1435 Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_marker.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_matplotlib.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_matplotlib.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..31a756665d4c4378af748e4fab873971f2efbfd3 Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_matplotlib.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_mlab.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_mlab.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..789d1dae8e148dd94ee64314f8af5485104abe32 Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_mlab.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_offsetbox.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_offsetbox.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..22670e3bcfcd88b718304d510cc797c54faaa052 Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_offsetbox.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_patches.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_patches.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8dd985afa73ab8278a88bc96548eec4dfcf109d8 Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_patches.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_path.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_path.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9da5a3d8510ffa1ec220bd6847a7c99b75e8ee0e Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_path.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_patheffects.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_patheffects.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3253cb1bb220e0f4b21940fefb02f0da251044e7 Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_patheffects.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_pickle.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_pickle.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..682349a25eb84c3e260c993c34b64f6f6bb74dd4 Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_pickle.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_polar.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_polar.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fb9fd1cdceda799ae99787038c0f4dd2b9d3c83f Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_polar.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_preprocess_data.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_preprocess_data.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f368d7e29ee229bb49eb2b849841701e95a86eb7 Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_preprocess_data.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_pyplot.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_pyplot.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e90e3c88f77485fc7fedb036332be90761338c02 Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_pyplot.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_rcparams.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_rcparams.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cd82c23c284348c442a2896c3e068a5c4085caef Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_rcparams.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_sankey.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_sankey.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c693dc5e2e40cece67cd9841e43c6e0f1f827227 Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_sankey.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_scale.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_scale.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..385427b8c3568f499cab1dfe54547f2edd187072 Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_scale.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_simplification.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_simplification.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7899b3b8c0ed2cd326e13b186bde1a0d29408004 Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_simplification.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_skew.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_skew.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..df1f1dd12a5a1678f15b5abf9bd30102a759e7f6 Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_skew.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_sphinxext.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_sphinxext.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0813b8216d867e9d52d25ba95c0652ffcef74385 Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_sphinxext.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_spines.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_spines.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..43964a820d0a919991679d46e0fe00b8118af89c Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_spines.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_streamplot.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_streamplot.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ebbdaabf1a1e280ca22c67a99db7b1e8b0d062a7 Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_streamplot.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_style.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_style.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..55776904c79e35192555c0e7966abd1bd4393e75 Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_style.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_subplots.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_subplots.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a6a59ef7bb9090d799f6df25c732e839052d9feb Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_subplots.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_table.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_table.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c9fbfbaa55eba724ecce687e116f0806b1405a9e Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_table.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_testing.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_testing.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..67af8070232c1a8b051c4facded7f56498d16a1a Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_testing.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_texmanager.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_texmanager.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fdc03cf79097faf569719974fbc4f3afb3bff9a5 Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_texmanager.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_text.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_text.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8ba4cfbd8faa809a32072676f817d3d8e7adcd96 Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_text.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_ticker.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_ticker.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f61ab13b5b505e13729b35108ebe2d8c83f8f226 Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_ticker.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_transforms.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_transforms.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e7612a730b1d7a87dd2c533627b02b8f4eb6c522 Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_transforms.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_triangulation.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_triangulation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b6eb9b1f923d8eb34f41c32b934bdf06a7e28427 Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_triangulation.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_units.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_units.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4ae82bdd87fb4d1e50b5ee3c101e2115878f6f46 Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_units.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_widgets.cpython-310.pyc b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_widgets.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d430da647ff3629ca2958bdd13454a57dfcfd607 Binary files /dev/null and b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_widgets.cpython-310.pyc differ diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/test_afm.py b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/test_afm.py new file mode 100644 index 0000000000000000000000000000000000000000..e5c6a83937cd68e3ae20a14d8babb9a99bd5a4f5 --- /dev/null +++ b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/test_afm.py @@ -0,0 +1,137 @@ +from io import BytesIO +import pytest +import logging + +from matplotlib import _afm +from matplotlib import font_manager as fm + + +# See note in afm.py re: use of comma as decimal separator in the +# UnderlineThickness field and re: use of non-ASCII characters in the Notice +# field. +AFM_TEST_DATA = b"""StartFontMetrics 2.0 +Comment Comments are ignored. +Comment Creation Date:Mon Nov 13 12:34:11 GMT 2017 +FontName MyFont-Bold +EncodingScheme FontSpecific +FullName My Font Bold +FamilyName Test Fonts +Weight Bold +ItalicAngle 0.0 +IsFixedPitch false +UnderlinePosition -100 +UnderlineThickness 56,789 +Version 001.000 +Notice Copyright \xa9 2017 No one. +FontBBox 0 -321 1234 369 +StartCharMetrics 3 +C 0 ; WX 250 ; N space ; B 0 0 0 0 ; +C 42 ; WX 1141 ; N foo ; B 40 60 800 360 ; +C 99 ; WX 583 ; N bar ; B 40 -10 543 210 ; +EndCharMetrics +EndFontMetrics +""" + + +def test_nonascii_str(): + # This tests that we also decode bytes as utf-8 properly. + # Else, font files with non ascii characters fail to load. + inp_str = "привет" + byte_str = inp_str.encode("utf8") + + ret = _afm._to_str(byte_str) + assert ret == inp_str + + +def test_parse_header(): + fh = BytesIO(AFM_TEST_DATA) + header = _afm._parse_header(fh) + assert header == { + b'StartFontMetrics': 2.0, + b'FontName': 'MyFont-Bold', + b'EncodingScheme': 'FontSpecific', + b'FullName': 'My Font Bold', + b'FamilyName': 'Test Fonts', + b'Weight': 'Bold', + b'ItalicAngle': 0.0, + b'IsFixedPitch': False, + b'UnderlinePosition': -100, + b'UnderlineThickness': 56.789, + b'Version': '001.000', + b'Notice': b'Copyright \xa9 2017 No one.', + b'FontBBox': [0, -321, 1234, 369], + b'StartCharMetrics': 3, + } + + +def test_parse_char_metrics(): + fh = BytesIO(AFM_TEST_DATA) + _afm._parse_header(fh) # position + metrics = _afm._parse_char_metrics(fh) + assert metrics == ( + {0: (250.0, 'space', [0, 0, 0, 0]), + 42: (1141.0, 'foo', [40, 60, 800, 360]), + 99: (583.0, 'bar', [40, -10, 543, 210]), + }, + {'space': (250.0, 'space', [0, 0, 0, 0]), + 'foo': (1141.0, 'foo', [40, 60, 800, 360]), + 'bar': (583.0, 'bar', [40, -10, 543, 210]), + }) + + +def test_get_familyname_guessed(): + fh = BytesIO(AFM_TEST_DATA) + font = _afm.AFM(fh) + del font._header[b'FamilyName'] # remove FamilyName, so we have to guess + assert font.get_familyname() == 'My Font' + + +def test_font_manager_weight_normalization(): + font = _afm.AFM(BytesIO( + AFM_TEST_DATA.replace(b"Weight Bold\n", b"Weight Custom\n"))) + assert fm.afmFontProperty("", font).weight == "normal" + + +@pytest.mark.parametrize( + "afm_data", + [ + b"""nope +really nope""", + b"""StartFontMetrics 2.0 +Comment Comments are ignored. +Comment Creation Date:Mon Nov 13 12:34:11 GMT 2017 +FontName MyFont-Bold +EncodingScheme FontSpecific""", + ], +) +def test_bad_afm(afm_data): + fh = BytesIO(afm_data) + with pytest.raises(RuntimeError): + _afm._parse_header(fh) + + +@pytest.mark.parametrize( + "afm_data", + [ + b"""StartFontMetrics 2.0 +Comment Comments are ignored. +Comment Creation Date:Mon Nov 13 12:34:11 GMT 2017 +Aardvark bob +FontName MyFont-Bold +EncodingScheme FontSpecific +StartCharMetrics 3""", + b"""StartFontMetrics 2.0 +Comment Comments are ignored. +Comment Creation Date:Mon Nov 13 12:34:11 GMT 2017 +ItalicAngle zero degrees +FontName MyFont-Bold +EncodingScheme FontSpecific +StartCharMetrics 3""", + ], +) +def test_malformed_header(afm_data, caplog): + fh = BytesIO(afm_data) + with caplog.at_level(logging.ERROR): + _afm._parse_header(fh) + + assert len(caplog.records) == 1 diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/test_axis.py b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/test_axis.py new file mode 100644 index 0000000000000000000000000000000000000000..97b5f88dede17ebde9aa828b55a2d1707981865e --- /dev/null +++ b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/test_axis.py @@ -0,0 +1,10 @@ +import numpy as np + +import matplotlib.pyplot as plt +from matplotlib.axis import XTick + + +def test_tick_labelcolor_array(): + # Smoke test that we can instantiate a Tick with labelcolor as array. + ax = plt.axes() + XTick(ax, 0, labelcolor=np.array([1, 0, 0, 1])) diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/test_backend_nbagg.py b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/test_backend_nbagg.py new file mode 100644 index 0000000000000000000000000000000000000000..4ebf3e1f56d117895388e709cbdefec4f98bd5e6 --- /dev/null +++ b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/test_backend_nbagg.py @@ -0,0 +1,30 @@ +import os +from pathlib import Path +import subprocess +from tempfile import TemporaryDirectory + +import pytest + +nbformat = pytest.importorskip('nbformat') +pytest.importorskip('nbconvert') +pytest.importorskip('ipykernel') + +# From https://blog.thedataincubator.com/2016/06/testing-jupyter-notebooks/ + + +def test_ipynb(): + nb_path = Path(__file__).parent / 'test_nbagg_01.ipynb' + + with TemporaryDirectory() as tmpdir: + out_path = Path(tmpdir, "out.ipynb") + subprocess.check_call( + ["jupyter", "nbconvert", "--to", "notebook", + "--execute", "--ExecutePreprocessor.timeout=500", + "--output", str(out_path), str(nb_path)], + env={**os.environ, "IPYTHONDIR": tmpdir}) + with out_path.open() as out: + nb = nbformat.read(out, nbformat.current_nbformat) + + errors = [output for cell in nb.cells for output in cell.get("outputs", []) + if output.output_type == "error"] + assert not errors diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/test_backend_pdf.py b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/test_backend_pdf.py new file mode 100644 index 0000000000000000000000000000000000000000..6fc02806240ba80e9a660f8f46e74559fa919b42 --- /dev/null +++ b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/test_backend_pdf.py @@ -0,0 +1,437 @@ +import datetime +import decimal +import io +import os +from pathlib import Path +from tempfile import NamedTemporaryFile + +import numpy as np +import pytest + +import matplotlib as mpl +from matplotlib import ( + pyplot as plt, rcParams, font_manager as fm +) +from matplotlib.cbook import _get_data_path +from matplotlib.ft2font import FT2Font +from matplotlib.font_manager import findfont, FontProperties +from matplotlib.backends._backend_pdf_ps import get_glyphs_subset +from matplotlib.backends.backend_pdf import PdfPages +from matplotlib.patches import Rectangle +from matplotlib.testing.decorators import check_figures_equal, image_comparison +from matplotlib.testing._markers import needs_usetex + + +@image_comparison(['pdf_use14corefonts.pdf']) +def test_use14corefonts(): + rcParams['pdf.use14corefonts'] = True + rcParams['font.family'] = 'sans-serif' + rcParams['font.size'] = 8 + rcParams['font.sans-serif'] = ['Helvetica'] + rcParams['pdf.compression'] = 0 + + text = '''A three-line text positioned just above a blue line +and containing some French characters and the euro symbol: +"Merci pépé pour les 10 €"''' + + fig, ax = plt.subplots() + ax.set_title('Test PDF backend with option use14corefonts=True') + ax.text(0.5, 0.5, text, horizontalalignment='center', + verticalalignment='bottom', + fontsize=14) + ax.axhline(0.5, linewidth=0.5) + + +@pytest.mark.parametrize('fontname, fontfile', [ + ('DejaVu Sans', 'DejaVuSans.ttf'), + ('WenQuanYi Zen Hei', 'wqy-zenhei.ttc'), +]) +@pytest.mark.parametrize('fonttype', [3, 42]) +def test_embed_fonts(fontname, fontfile, fonttype): + if Path(findfont(FontProperties(family=[fontname]))).name != fontfile: + pytest.skip(f'Font {fontname!r} may be missing') + + rcParams['pdf.fonttype'] = fonttype + fig, ax = plt.subplots() + ax.plot([1, 2, 3]) + ax.set_title('Axes Title', font=fontname) + fig.savefig(io.BytesIO(), format='pdf') + + +def test_multipage_pagecount(): + with PdfPages(io.BytesIO()) as pdf: + assert pdf.get_pagecount() == 0 + fig, ax = plt.subplots() + ax.plot([1, 2, 3]) + fig.savefig(pdf, format="pdf") + assert pdf.get_pagecount() == 1 + pdf.savefig() + assert pdf.get_pagecount() == 2 + + +def test_multipage_properfinalize(): + pdfio = io.BytesIO() + with PdfPages(pdfio) as pdf: + for i in range(10): + fig, ax = plt.subplots() + ax.set_title('This is a long title') + fig.savefig(pdf, format="pdf") + s = pdfio.getvalue() + assert s.count(b'startxref') == 1 + assert len(s) < 40000 + + +def test_multipage_keep_empty(): + # test empty pdf files + # test that an empty pdf is left behind with keep_empty=True (default) + with NamedTemporaryFile(delete=False) as tmp: + with PdfPages(tmp) as pdf: + filename = pdf._file.fh.name + assert os.path.exists(filename) + os.remove(filename) + # test if an empty pdf is deleting itself afterwards with keep_empty=False + with PdfPages(filename, keep_empty=False) as pdf: + pass + assert not os.path.exists(filename) + # test pdf files with content, they should never be deleted + fig, ax = plt.subplots() + ax.plot([1, 2, 3]) + # test that a non-empty pdf is left behind with keep_empty=True (default) + with NamedTemporaryFile(delete=False) as tmp: + with PdfPages(tmp) as pdf: + filename = pdf._file.fh.name + pdf.savefig() + assert os.path.exists(filename) + os.remove(filename) + # test that a non-empty pdf is left behind with keep_empty=False + with NamedTemporaryFile(delete=False) as tmp: + with PdfPages(tmp, keep_empty=False) as pdf: + filename = pdf._file.fh.name + pdf.savefig() + assert os.path.exists(filename) + os.remove(filename) + + +def test_composite_image(): + # Test that figures can be saved with and without combining multiple images + # (on a single set of axes) into a single composite image. + X, Y = np.meshgrid(np.arange(-5, 5, 1), np.arange(-5, 5, 1)) + Z = np.sin(Y ** 2) + fig, ax = plt.subplots() + ax.set_xlim(0, 3) + ax.imshow(Z, extent=[0, 1, 0, 1]) + ax.imshow(Z[::-1], extent=[2, 3, 0, 1]) + plt.rcParams['image.composite_image'] = True + with PdfPages(io.BytesIO()) as pdf: + fig.savefig(pdf, format="pdf") + assert len(pdf._file._images) == 1 + plt.rcParams['image.composite_image'] = False + with PdfPages(io.BytesIO()) as pdf: + fig.savefig(pdf, format="pdf") + assert len(pdf._file._images) == 2 + + +def test_indexed_image(): + # An image with low color count should compress to a palette-indexed format. + pikepdf = pytest.importorskip('pikepdf') + + data = np.zeros((256, 1, 3), dtype=np.uint8) + data[:, 0, 0] = np.arange(256) # Maximum unique colours for an indexed image. + + rcParams['pdf.compression'] = True + fig = plt.figure() + fig.figimage(data, resize=True) + buf = io.BytesIO() + fig.savefig(buf, format='pdf', dpi='figure') + + with pikepdf.Pdf.open(buf) as pdf: + page, = pdf.pages + image, = page.images.values() + pdf_image = pikepdf.PdfImage(image) + assert pdf_image.indexed + pil_image = pdf_image.as_pil_image() + rgb = np.asarray(pil_image.convert('RGB')) + + np.testing.assert_array_equal(data, rgb) + + +def test_savefig_metadata(monkeypatch): + pikepdf = pytest.importorskip('pikepdf') + monkeypatch.setenv('SOURCE_DATE_EPOCH', '0') + + fig, ax = plt.subplots() + ax.plot(range(5)) + + md = { + 'Author': 'me', + 'Title': 'Multipage PDF', + 'Subject': 'Test page', + 'Keywords': 'test,pdf,multipage', + 'ModDate': datetime.datetime( + 1968, 8, 1, tzinfo=datetime.timezone(datetime.timedelta(0))), + 'Trapped': 'True' + } + buf = io.BytesIO() + fig.savefig(buf, metadata=md, format='pdf') + + with pikepdf.Pdf.open(buf) as pdf: + info = {k: str(v) for k, v in pdf.docinfo.items()} + + assert info == { + '/Author': 'me', + '/CreationDate': 'D:19700101000000Z', + '/Creator': f'Matplotlib v{mpl.__version__}, https://matplotlib.org', + '/Keywords': 'test,pdf,multipage', + '/ModDate': 'D:19680801000000Z', + '/Producer': f'Matplotlib pdf backend v{mpl.__version__}', + '/Subject': 'Test page', + '/Title': 'Multipage PDF', + '/Trapped': '/True', + } + + +def test_invalid_metadata(): + fig, ax = plt.subplots() + + with pytest.warns(UserWarning, + match="Unknown infodict keyword: 'foobar'."): + fig.savefig(io.BytesIO(), format='pdf', metadata={'foobar': 'invalid'}) + + with pytest.warns(UserWarning, + match='not an instance of datetime.datetime.'): + fig.savefig(io.BytesIO(), format='pdf', + metadata={'ModDate': '1968-08-01'}) + + with pytest.warns(UserWarning, + match='not one of {"True", "False", "Unknown"}'): + fig.savefig(io.BytesIO(), format='pdf', metadata={'Trapped': 'foo'}) + + with pytest.warns(UserWarning, match='not an instance of str.'): + fig.savefig(io.BytesIO(), format='pdf', metadata={'Title': 1234}) + + +def test_multipage_metadata(monkeypatch): + pikepdf = pytest.importorskip('pikepdf') + monkeypatch.setenv('SOURCE_DATE_EPOCH', '0') + + fig, ax = plt.subplots() + ax.plot(range(5)) + + md = { + 'Author': 'me', + 'Title': 'Multipage PDF', + 'Subject': 'Test page', + 'Keywords': 'test,pdf,multipage', + 'ModDate': datetime.datetime( + 1968, 8, 1, tzinfo=datetime.timezone(datetime.timedelta(0))), + 'Trapped': 'True' + } + buf = io.BytesIO() + with PdfPages(buf, metadata=md) as pdf: + pdf.savefig(fig) + pdf.savefig(fig) + + with pikepdf.Pdf.open(buf) as pdf: + info = {k: str(v) for k, v in pdf.docinfo.items()} + + assert info == { + '/Author': 'me', + '/CreationDate': 'D:19700101000000Z', + '/Creator': f'Matplotlib v{mpl.__version__}, https://matplotlib.org', + '/Keywords': 'test,pdf,multipage', + '/ModDate': 'D:19680801000000Z', + '/Producer': f'Matplotlib pdf backend v{mpl.__version__}', + '/Subject': 'Test page', + '/Title': 'Multipage PDF', + '/Trapped': '/True', + } + + +def test_text_urls(): + pikepdf = pytest.importorskip('pikepdf') + + test_url = 'https://test_text_urls.matplotlib.org/' + + fig = plt.figure(figsize=(2, 1)) + fig.text(0.1, 0.1, 'test plain 123', url=f'{test_url}plain') + fig.text(0.1, 0.4, 'test mathtext $123$', url=f'{test_url}mathtext') + + with io.BytesIO() as fd: + fig.savefig(fd, format='pdf') + + with pikepdf.Pdf.open(fd) as pdf: + annots = pdf.pages[0].Annots + + # Iteration over Annots must occur within the context manager, + # otherwise it may fail depending on the pdf structure. + for y, fragment in [('0.1', 'plain'), ('0.4', 'mathtext')]: + annot = next( + (a for a in annots if a.A.URI == f'{test_url}{fragment}'), + None) + assert annot is not None + assert getattr(annot, 'QuadPoints', None) is None + # Positions in points (72 per inch.) + assert annot.Rect[1] == decimal.Decimal(y) * 72 + + +def test_text_rotated_urls(): + pikepdf = pytest.importorskip('pikepdf') + + test_url = 'https://test_text_urls.matplotlib.org/' + + fig = plt.figure(figsize=(1, 1)) + fig.text(0.1, 0.1, 'N', rotation=45, url=f'{test_url}') + + with io.BytesIO() as fd: + fig.savefig(fd, format='pdf') + + with pikepdf.Pdf.open(fd) as pdf: + annots = pdf.pages[0].Annots + + # Iteration over Annots must occur within the context manager, + # otherwise it may fail depending on the pdf structure. + annot = next( + (a for a in annots if a.A.URI == f'{test_url}'), + None) + assert annot is not None + assert getattr(annot, 'QuadPoints', None) is not None + # Positions in points (72 per inch) + assert annot.Rect[0] == \ + annot.QuadPoints[6] - decimal.Decimal('0.00001') + + +@needs_usetex +def test_text_urls_tex(): + pikepdf = pytest.importorskip('pikepdf') + + test_url = 'https://test_text_urls.matplotlib.org/' + + fig = plt.figure(figsize=(2, 1)) + fig.text(0.1, 0.7, 'test tex $123$', usetex=True, url=f'{test_url}tex') + + with io.BytesIO() as fd: + fig.savefig(fd, format='pdf') + + with pikepdf.Pdf.open(fd) as pdf: + annots = pdf.pages[0].Annots + + # Iteration over Annots must occur within the context manager, + # otherwise it may fail depending on the pdf structure. + annot = next( + (a for a in annots if a.A.URI == f'{test_url}tex'), + None) + assert annot is not None + # Positions in points (72 per inch.) + assert annot.Rect[1] == decimal.Decimal('0.7') * 72 + + +def test_pdfpages_fspath(): + with PdfPages(Path(os.devnull)) as pdf: + pdf.savefig(plt.figure()) + + +@image_comparison(['hatching_legend.pdf']) +def test_hatching_legend(): + """Test for correct hatching on patches in legend""" + fig = plt.figure(figsize=(1, 2)) + + a = Rectangle([0, 0], 0, 0, facecolor="green", hatch="XXXX") + b = Rectangle([0, 0], 0, 0, facecolor="blue", hatch="XXXX") + + fig.legend([a, b, a, b], ["", "", "", ""]) + + +@image_comparison(['grayscale_alpha.pdf']) +def test_grayscale_alpha(): + """Masking images with NaN did not work for grayscale images""" + x, y = np.ogrid[-2:2:.1, -2:2:.1] + dd = np.exp(-(x**2 + y**2)) + dd[dd < .1] = np.nan + fig, ax = plt.subplots() + ax.imshow(dd, interpolation='none', cmap='gray_r') + ax.set_xticks([]) + ax.set_yticks([]) + + +@mpl.style.context('default') +@check_figures_equal(extensions=["pdf", "eps"]) +def test_pdf_eps_savefig_when_color_is_none(fig_test, fig_ref): + ax_test = fig_test.add_subplot() + ax_test.set_axis_off() + ax_test.plot(np.sin(np.linspace(-5, 5, 100)), "v", c="none") + ax_ref = fig_ref.add_subplot() + ax_ref.set_axis_off() + + +@needs_usetex +def test_failing_latex(): + """Test failing latex subprocess call""" + plt.xlabel("$22_2_2$", usetex=True) # This fails with "Double subscript" + with pytest.raises(RuntimeError): + plt.savefig(io.BytesIO(), format="pdf") + + +def test_empty_rasterized(): + # Check that empty figures that are rasterised save to pdf files fine + fig, ax = plt.subplots() + ax.plot([], [], rasterized=True) + fig.savefig(io.BytesIO(), format="pdf") + + +@image_comparison(['kerning.pdf']) +def test_kerning(): + fig = plt.figure() + s = "AVAVAVAVAVAVAVAV€AAVV" + fig.text(0, .25, s, size=5) + fig.text(0, .75, s, size=20) + + +def test_glyphs_subset(): + fpath = str(_get_data_path("fonts/ttf/DejaVuSerif.ttf")) + chars = "these should be subsetted! 1234567890" + + # non-subsetted FT2Font + nosubfont = FT2Font(fpath) + nosubfont.set_text(chars) + + # subsetted FT2Font + subfont = FT2Font(get_glyphs_subset(fpath, chars)) + subfont.set_text(chars) + + nosubcmap = nosubfont.get_charmap() + subcmap = subfont.get_charmap() + + # all unique chars must be available in subsetted font + assert set(chars) == set(chr(key) for key in subcmap.keys()) + + # subsetted font's charmap should have less entries + assert len(subcmap) < len(nosubcmap) + + # since both objects are assigned same characters + assert subfont.get_num_glyphs() == nosubfont.get_num_glyphs() + + +@image_comparison(["multi_font_type3.pdf"], tol=4.6) +def test_multi_font_type3(): + fp = fm.FontProperties(family=["WenQuanYi Zen Hei"]) + if Path(fm.findfont(fp)).name != "wqy-zenhei.ttc": + pytest.skip("Font may be missing") + + plt.rc('font', family=['DejaVu Sans', 'WenQuanYi Zen Hei'], size=27) + plt.rc('pdf', fonttype=3) + + fig = plt.figure() + fig.text(0.15, 0.475, "There are 几个汉字 in between!") + + +@image_comparison(["multi_font_type42.pdf"], tol=2.2) +def test_multi_font_type42(): + fp = fm.FontProperties(family=["WenQuanYi Zen Hei"]) + if Path(fm.findfont(fp)).name != "wqy-zenhei.ttc": + pytest.skip("Font may be missing") + + plt.rc('font', family=['DejaVu Sans', 'WenQuanYi Zen Hei'], size=27) + plt.rc('pdf', fonttype=42) + + fig = plt.figure() + fig.text(0.15, 0.475, "There are 几个汉字 in between!") diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/test_collections.py b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/test_collections.py new file mode 100644 index 0000000000000000000000000000000000000000..ac1faa3c1cdce865607a6dc913c82efd06cb8e4b --- /dev/null +++ b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/test_collections.py @@ -0,0 +1,1193 @@ +from datetime import datetime +import io +import re +from types import SimpleNamespace + +import numpy as np +from numpy.testing import assert_array_equal, assert_array_almost_equal +import pytest + +import matplotlib as mpl +import matplotlib.pyplot as plt +import matplotlib.collections as mcollections +import matplotlib.colors as mcolors +import matplotlib.path as mpath +import matplotlib.transforms as mtransforms +from matplotlib.collections import (Collection, LineCollection, + EventCollection, PolyCollection) +from matplotlib.testing.decorators import check_figures_equal, image_comparison + + +def generate_EventCollection_plot(): + """Generate the initial collection and plot it.""" + positions = np.array([0., 1., 2., 3., 5., 8., 13., 21.]) + extra_positions = np.array([34., 55., 89.]) + orientation = 'horizontal' + lineoffset = 1 + linelength = .5 + linewidth = 2 + color = [1, 0, 0, 1] + linestyle = 'solid' + antialiased = True + + coll = EventCollection(positions, + orientation=orientation, + lineoffset=lineoffset, + linelength=linelength, + linewidth=linewidth, + color=color, + linestyle=linestyle, + antialiased=antialiased + ) + + fig, ax = plt.subplots() + ax.add_collection(coll) + ax.set_title('EventCollection: default') + props = {'positions': positions, + 'extra_positions': extra_positions, + 'orientation': orientation, + 'lineoffset': lineoffset, + 'linelength': linelength, + 'linewidth': linewidth, + 'color': color, + 'linestyle': linestyle, + 'antialiased': antialiased + } + ax.set_xlim(-1, 22) + ax.set_ylim(0, 2) + return ax, coll, props + + +@image_comparison(['EventCollection_plot__default']) +def test__EventCollection__get_props(): + _, coll, props = generate_EventCollection_plot() + # check that the default segments have the correct coordinates + check_segments(coll, + props['positions'], + props['linelength'], + props['lineoffset'], + props['orientation']) + # check that the default positions match the input positions + np.testing.assert_array_equal(props['positions'], coll.get_positions()) + # check that the default orientation matches the input orientation + assert props['orientation'] == coll.get_orientation() + # check that the default orientation matches the input orientation + assert coll.is_horizontal() + # check that the default linelength matches the input linelength + assert props['linelength'] == coll.get_linelength() + # check that the default lineoffset matches the input lineoffset + assert props['lineoffset'] == coll.get_lineoffset() + # check that the default linestyle matches the input linestyle + assert coll.get_linestyle() == [(0, None)] + # check that the default color matches the input color + for color in [coll.get_color(), *coll.get_colors()]: + np.testing.assert_array_equal(color, props['color']) + + +@image_comparison(['EventCollection_plot__set_positions']) +def test__EventCollection__set_positions(): + splt, coll, props = generate_EventCollection_plot() + new_positions = np.hstack([props['positions'], props['extra_positions']]) + coll.set_positions(new_positions) + np.testing.assert_array_equal(new_positions, coll.get_positions()) + check_segments(coll, new_positions, + props['linelength'], + props['lineoffset'], + props['orientation']) + splt.set_title('EventCollection: set_positions') + splt.set_xlim(-1, 90) + + +@image_comparison(['EventCollection_plot__add_positions']) +def test__EventCollection__add_positions(): + splt, coll, props = generate_EventCollection_plot() + new_positions = np.hstack([props['positions'], + props['extra_positions'][0]]) + coll.switch_orientation() # Test adding in the vertical orientation, too. + coll.add_positions(props['extra_positions'][0]) + coll.switch_orientation() + np.testing.assert_array_equal(new_positions, coll.get_positions()) + check_segments(coll, + new_positions, + props['linelength'], + props['lineoffset'], + props['orientation']) + splt.set_title('EventCollection: add_positions') + splt.set_xlim(-1, 35) + + +@image_comparison(['EventCollection_plot__append_positions']) +def test__EventCollection__append_positions(): + splt, coll, props = generate_EventCollection_plot() + new_positions = np.hstack([props['positions'], + props['extra_positions'][2]]) + coll.append_positions(props['extra_positions'][2]) + np.testing.assert_array_equal(new_positions, coll.get_positions()) + check_segments(coll, + new_positions, + props['linelength'], + props['lineoffset'], + props['orientation']) + splt.set_title('EventCollection: append_positions') + splt.set_xlim(-1, 90) + + +@image_comparison(['EventCollection_plot__extend_positions']) +def test__EventCollection__extend_positions(): + splt, coll, props = generate_EventCollection_plot() + new_positions = np.hstack([props['positions'], + props['extra_positions'][1:]]) + coll.extend_positions(props['extra_positions'][1:]) + np.testing.assert_array_equal(new_positions, coll.get_positions()) + check_segments(coll, + new_positions, + props['linelength'], + props['lineoffset'], + props['orientation']) + splt.set_title('EventCollection: extend_positions') + splt.set_xlim(-1, 90) + + +@image_comparison(['EventCollection_plot__switch_orientation']) +def test__EventCollection__switch_orientation(): + splt, coll, props = generate_EventCollection_plot() + new_orientation = 'vertical' + coll.switch_orientation() + assert new_orientation == coll.get_orientation() + assert not coll.is_horizontal() + new_positions = coll.get_positions() + check_segments(coll, + new_positions, + props['linelength'], + props['lineoffset'], new_orientation) + splt.set_title('EventCollection: switch_orientation') + splt.set_ylim(-1, 22) + splt.set_xlim(0, 2) + + +@image_comparison(['EventCollection_plot__switch_orientation__2x']) +def test__EventCollection__switch_orientation_2x(): + """ + Check that calling switch_orientation twice sets the orientation back to + the default. + """ + splt, coll, props = generate_EventCollection_plot() + coll.switch_orientation() + coll.switch_orientation() + new_positions = coll.get_positions() + assert props['orientation'] == coll.get_orientation() + assert coll.is_horizontal() + np.testing.assert_array_equal(props['positions'], new_positions) + check_segments(coll, + new_positions, + props['linelength'], + props['lineoffset'], + props['orientation']) + splt.set_title('EventCollection: switch_orientation 2x') + + +@image_comparison(['EventCollection_plot__set_orientation']) +def test__EventCollection__set_orientation(): + splt, coll, props = generate_EventCollection_plot() + new_orientation = 'vertical' + coll.set_orientation(new_orientation) + assert new_orientation == coll.get_orientation() + assert not coll.is_horizontal() + check_segments(coll, + props['positions'], + props['linelength'], + props['lineoffset'], + new_orientation) + splt.set_title('EventCollection: set_orientation') + splt.set_ylim(-1, 22) + splt.set_xlim(0, 2) + + +@image_comparison(['EventCollection_plot__set_linelength']) +def test__EventCollection__set_linelength(): + splt, coll, props = generate_EventCollection_plot() + new_linelength = 15 + coll.set_linelength(new_linelength) + assert new_linelength == coll.get_linelength() + check_segments(coll, + props['positions'], + new_linelength, + props['lineoffset'], + props['orientation']) + splt.set_title('EventCollection: set_linelength') + splt.set_ylim(-20, 20) + + +@image_comparison(['EventCollection_plot__set_lineoffset']) +def test__EventCollection__set_lineoffset(): + splt, coll, props = generate_EventCollection_plot() + new_lineoffset = -5. + coll.set_lineoffset(new_lineoffset) + assert new_lineoffset == coll.get_lineoffset() + check_segments(coll, + props['positions'], + props['linelength'], + new_lineoffset, + props['orientation']) + splt.set_title('EventCollection: set_lineoffset') + splt.set_ylim(-6, -4) + + +@image_comparison([ + 'EventCollection_plot__set_linestyle', + 'EventCollection_plot__set_linestyle', + 'EventCollection_plot__set_linewidth', +]) +def test__EventCollection__set_prop(): + for prop, value, expected in [ + ('linestyle', 'dashed', [(0, (6.0, 6.0))]), + ('linestyle', (0, (6., 6.)), [(0, (6.0, 6.0))]), + ('linewidth', 5, 5), + ]: + splt, coll, _ = generate_EventCollection_plot() + coll.set(**{prop: value}) + assert plt.getp(coll, prop) == expected + splt.set_title(f'EventCollection: set_{prop}') + + +@image_comparison(['EventCollection_plot__set_color']) +def test__EventCollection__set_color(): + splt, coll, _ = generate_EventCollection_plot() + new_color = np.array([0, 1, 1, 1]) + coll.set_color(new_color) + for color in [coll.get_color(), *coll.get_colors()]: + np.testing.assert_array_equal(color, new_color) + splt.set_title('EventCollection: set_color') + + +def check_segments(coll, positions, linelength, lineoffset, orientation): + """ + Test helper checking that all values in the segment are correct, given a + particular set of inputs. + """ + segments = coll.get_segments() + if (orientation.lower() == 'horizontal' + or orientation.lower() == 'none' or orientation is None): + # if horizontal, the position in is in the y-axis + pos1 = 1 + pos2 = 0 + elif orientation.lower() == 'vertical': + # if vertical, the position in is in the x-axis + pos1 = 0 + pos2 = 1 + else: + raise ValueError("orientation must be 'horizontal' or 'vertical'") + + # test to make sure each segment is correct + for i, segment in enumerate(segments): + assert segment[0, pos1] == lineoffset + linelength / 2 + assert segment[1, pos1] == lineoffset - linelength / 2 + assert segment[0, pos2] == positions[i] + assert segment[1, pos2] == positions[i] + + +def test_null_collection_datalim(): + col = mcollections.PathCollection([]) + col_data_lim = col.get_datalim(mtransforms.IdentityTransform()) + assert_array_equal(col_data_lim.get_points(), + mtransforms.Bbox.null().get_points()) + + +def test_no_offsets_datalim(): + # A collection with no offsets and a non transData + # transform should return a null bbox + ax = plt.axes() + coll = mcollections.PathCollection([mpath.Path([(0, 0), (1, 0)])]) + ax.add_collection(coll) + coll_data_lim = coll.get_datalim(mtransforms.IdentityTransform()) + assert_array_equal(coll_data_lim.get_points(), + mtransforms.Bbox.null().get_points()) + + +def test_add_collection(): + # Test if data limits are unchanged by adding an empty collection. + # GitHub issue #1490, pull #1497. + plt.figure() + ax = plt.axes() + ax.scatter([0, 1], [0, 1]) + bounds = ax.dataLim.bounds + ax.scatter([], []) + assert ax.dataLim.bounds == bounds + + +@mpl.style.context('mpl20') +@check_figures_equal(extensions=['png']) +def test_collection_log_datalim(fig_test, fig_ref): + # Data limits should respect the minimum x/y when using log scale. + x_vals = [4.38462e-6, 5.54929e-6, 7.02332e-6, 8.88889e-6, 1.12500e-5, + 1.42383e-5, 1.80203e-5, 2.28070e-5, 2.88651e-5, 3.65324e-5, + 4.62363e-5, 5.85178e-5, 7.40616e-5, 9.37342e-5, 1.18632e-4] + y_vals = [0.0, 0.1, 0.182, 0.332, 0.604, 1.1, 2.0, 3.64, 6.64, 12.1, 22.0, + 39.6, 71.3] + + x, y = np.meshgrid(x_vals, y_vals) + x = x.flatten() + y = y.flatten() + + ax_test = fig_test.subplots() + ax_test.set_xscale('log') + ax_test.set_yscale('log') + ax_test.margins = 0 + ax_test.scatter(x, y) + + ax_ref = fig_ref.subplots() + ax_ref.set_xscale('log') + ax_ref.set_yscale('log') + ax_ref.plot(x, y, marker="o", ls="") + + +def test_quiver_limits(): + ax = plt.axes() + x, y = np.arange(8), np.arange(10) + u = v = np.linspace(0, 10, 80).reshape(10, 8) + q = plt.quiver(x, y, u, v) + assert q.get_datalim(ax.transData).bounds == (0., 0., 7., 9.) + + plt.figure() + ax = plt.axes() + x = np.linspace(-5, 10, 20) + y = np.linspace(-2, 4, 10) + y, x = np.meshgrid(y, x) + trans = mtransforms.Affine2D().translate(25, 32) + ax.transData + plt.quiver(x, y, np.sin(x), np.cos(y), transform=trans) + assert ax.dataLim.bounds == (20.0, 30.0, 15.0, 6.0) + + +def test_barb_limits(): + ax = plt.axes() + x = np.linspace(-5, 10, 20) + y = np.linspace(-2, 4, 10) + y, x = np.meshgrid(y, x) + trans = mtransforms.Affine2D().translate(25, 32) + ax.transData + plt.barbs(x, y, np.sin(x), np.cos(y), transform=trans) + # The calculated bounds are approximately the bounds of the original data, + # this is because the entire path is taken into account when updating the + # datalim. + assert_array_almost_equal(ax.dataLim.bounds, (20, 30, 15, 6), + decimal=1) + + +@image_comparison(['EllipseCollection_test_image.png'], remove_text=True) +def test_EllipseCollection(): + # Test basic functionality + fig, ax = plt.subplots() + x = np.arange(4) + y = np.arange(3) + X, Y = np.meshgrid(x, y) + XY = np.vstack((X.ravel(), Y.ravel())).T + + ww = X / x[-1] + hh = Y / y[-1] + aa = np.ones_like(ww) * 20 # first axis is 20 degrees CCW from x axis + + ec = mcollections.EllipseCollection( + ww, hh, aa, units='x', offsets=XY, offset_transform=ax.transData, + facecolors='none') + ax.add_collection(ec) + ax.autoscale_view() + + +@image_comparison(['polycollection_close.png'], remove_text=True) +def test_polycollection_close(): + from mpl_toolkits.mplot3d import Axes3D + + vertsQuad = [ + [[0., 0.], [0., 1.], [1., 1.], [1., 0.]], + [[0., 1.], [2., 3.], [2., 2.], [1., 1.]], + [[2., 2.], [2., 3.], [4., 1.], [3., 1.]], + [[3., 0.], [3., 1.], [4., 1.], [4., 0.]]] + + fig = plt.figure() + ax = fig.add_axes(Axes3D(fig)) + + colors = ['r', 'g', 'b', 'y', 'k'] + zpos = list(range(5)) + + poly = mcollections.PolyCollection( + vertsQuad * len(zpos), linewidth=0.25) + poly.set_alpha(0.7) + + # need to have a z-value for *each* polygon = element! + zs = [] + cs = [] + for z, c in zip(zpos, colors): + zs.extend([z] * len(vertsQuad)) + cs.extend([c] * len(vertsQuad)) + + poly.set_color(cs) + + ax.add_collection3d(poly, zs=zs, zdir='y') + + # axis limit settings: + ax.set_xlim3d(0, 4) + ax.set_zlim3d(0, 3) + ax.set_ylim3d(0, 4) + + +@image_comparison(['regularpolycollection_rotate.png'], remove_text=True) +def test_regularpolycollection_rotate(): + xx, yy = np.mgrid[:10, :10] + xy_points = np.transpose([xx.flatten(), yy.flatten()]) + rotations = np.linspace(0, 2*np.pi, len(xy_points)) + + fig, ax = plt.subplots() + for xy, alpha in zip(xy_points, rotations): + col = mcollections.RegularPolyCollection( + 4, sizes=(100,), rotation=alpha, + offsets=[xy], offset_transform=ax.transData) + ax.add_collection(col, autolim=True) + ax.autoscale_view() + + +@image_comparison(['regularpolycollection_scale.png'], remove_text=True) +def test_regularpolycollection_scale(): + # See issue #3860 + + class SquareCollection(mcollections.RegularPolyCollection): + def __init__(self, **kwargs): + super().__init__(4, rotation=np.pi/4., **kwargs) + + def get_transform(self): + """Return transform scaling circle areas to data space.""" + ax = self.axes + + pts2pixels = 72.0 / ax.figure.dpi + + scale_x = pts2pixels * ax.bbox.width / ax.viewLim.width + scale_y = pts2pixels * ax.bbox.height / ax.viewLim.height + return mtransforms.Affine2D().scale(scale_x, scale_y) + + fig, ax = plt.subplots() + + xy = [(0, 0)] + # Unit square has a half-diagonal of `1/sqrt(2)`, so `pi * r**2` equals... + circle_areas = [np.pi / 2] + squares = SquareCollection( + sizes=circle_areas, offsets=xy, offset_transform=ax.transData) + ax.add_collection(squares, autolim=True) + ax.axis([-1, 1, -1, 1]) + + +def test_picking(): + fig, ax = plt.subplots() + col = ax.scatter([0], [0], [1000], picker=True) + fig.savefig(io.BytesIO(), dpi=fig.dpi) + mouse_event = SimpleNamespace(x=325, y=240) + found, indices = col.contains(mouse_event) + assert found + assert_array_equal(indices['ind'], [0]) + + +def test_quadmesh_contains(): + x = np.arange(4) + X = x[:, None] * x[None, :] + + fig, ax = plt.subplots() + mesh = ax.pcolormesh(X) + fig.draw_without_rendering() + xdata, ydata = 0.5, 0.5 + x, y = mesh.get_transform().transform((xdata, ydata)) + mouse_event = SimpleNamespace(xdata=xdata, ydata=ydata, x=x, y=y) + found, indices = mesh.contains(mouse_event) + assert found + assert_array_equal(indices['ind'], [0]) + + xdata, ydata = 1.5, 1.5 + x, y = mesh.get_transform().transform((xdata, ydata)) + mouse_event = SimpleNamespace(xdata=xdata, ydata=ydata, x=x, y=y) + found, indices = mesh.contains(mouse_event) + assert found + assert_array_equal(indices['ind'], [5]) + + +def test_quadmesh_contains_concave(): + # Test a concave polygon, V-like shape + x = [[0, -1], [1, 0]] + y = [[0, 1], [1, -1]] + fig, ax = plt.subplots() + mesh = ax.pcolormesh(x, y, [[0]]) + fig.draw_without_rendering() + # xdata, ydata, expected + points = [(-0.5, 0.25, True), # left wing + (0, 0.25, False), # between the two wings + (0.5, 0.25, True), # right wing + (0, -0.25, True), # main body + ] + for point in points: + xdata, ydata, expected = point + x, y = mesh.get_transform().transform((xdata, ydata)) + mouse_event = SimpleNamespace(xdata=xdata, ydata=ydata, x=x, y=y) + found, indices = mesh.contains(mouse_event) + assert found is expected + + +def test_quadmesh_cursor_data(): + x = np.arange(4) + X = x[:, None] * x[None, :] + + fig, ax = plt.subplots() + mesh = ax.pcolormesh(X) + # Empty array data + mesh._A = None + fig.draw_without_rendering() + xdata, ydata = 0.5, 0.5 + x, y = mesh.get_transform().transform((xdata, ydata)) + mouse_event = SimpleNamespace(xdata=xdata, ydata=ydata, x=x, y=y) + # Empty collection should return None + assert mesh.get_cursor_data(mouse_event) is None + + # Now test adding the array data, to make sure we do get a value + mesh.set_array(np.ones((X.shape))) + assert_array_equal(mesh.get_cursor_data(mouse_event), [1]) + + +def test_quadmesh_cursor_data_multiple_points(): + x = [1, 2, 1, 2] + fig, ax = plt.subplots() + mesh = ax.pcolormesh(x, x, np.ones((3, 3))) + fig.draw_without_rendering() + xdata, ydata = 1.5, 1.5 + x, y = mesh.get_transform().transform((xdata, ydata)) + mouse_event = SimpleNamespace(xdata=xdata, ydata=ydata, x=x, y=y) + # All quads are covering the same square + assert_array_equal(mesh.get_cursor_data(mouse_event), np.ones(9)) + + +def test_linestyle_single_dashes(): + plt.scatter([0, 1, 2], [0, 1, 2], linestyle=(0., [2., 2.])) + plt.draw() + + +@image_comparison(['size_in_xy.png'], remove_text=True) +def test_size_in_xy(): + fig, ax = plt.subplots() + + widths, heights, angles = (10, 10), 10, 0 + widths = 10, 10 + coords = [(10, 10), (15, 15)] + e = mcollections.EllipseCollection( + widths, heights, angles, units='xy', + offsets=coords, offset_transform=ax.transData) + + ax.add_collection(e) + + ax.set_xlim(0, 30) + ax.set_ylim(0, 30) + + +def test_pandas_indexing(pd): + + # Should not fail break when faced with a + # non-zero indexed series + index = [11, 12, 13] + ec = fc = pd.Series(['red', 'blue', 'green'], index=index) + lw = pd.Series([1, 2, 3], index=index) + ls = pd.Series(['solid', 'dashed', 'dashdot'], index=index) + aa = pd.Series([True, False, True], index=index) + + Collection(edgecolors=ec) + Collection(facecolors=fc) + Collection(linewidths=lw) + Collection(linestyles=ls) + Collection(antialiaseds=aa) + + +@mpl.style.context('default') +def test_lslw_bcast(): + col = mcollections.PathCollection([]) + col.set_linestyles(['-', '-']) + col.set_linewidths([1, 2, 3]) + + assert col.get_linestyles() == [(0, None)] * 6 + assert col.get_linewidths() == [1, 2, 3] * 2 + + col.set_linestyles(['-', '-', '-']) + assert col.get_linestyles() == [(0, None)] * 3 + assert (col.get_linewidths() == [1, 2, 3]).all() + + +def test_set_wrong_linestyle(): + c = Collection() + with pytest.raises(ValueError, match="Do not know how to convert 'fuzzy'"): + c.set_linestyle('fuzzy') + + +@mpl.style.context('default') +def test_capstyle(): + col = mcollections.PathCollection([], capstyle='round') + assert col.get_capstyle() == 'round' + col.set_capstyle('butt') + assert col.get_capstyle() == 'butt' + + +@mpl.style.context('default') +def test_joinstyle(): + col = mcollections.PathCollection([], joinstyle='round') + assert col.get_joinstyle() == 'round' + col.set_joinstyle('miter') + assert col.get_joinstyle() == 'miter' + + +@image_comparison(['cap_and_joinstyle.png']) +def test_cap_and_joinstyle_image(): + fig, ax = plt.subplots() + ax.set_xlim([-0.5, 1.5]) + ax.set_ylim([-0.5, 2.5]) + + x = np.array([0.0, 1.0, 0.5]) + ys = np.array([[0.0], [0.5], [1.0]]) + np.array([[0.0, 0.0, 1.0]]) + + segs = np.zeros((3, 3, 2)) + segs[:, :, 0] = x + segs[:, :, 1] = ys + line_segments = LineCollection(segs, linewidth=[10, 15, 20]) + line_segments.set_capstyle("round") + line_segments.set_joinstyle("miter") + + ax.add_collection(line_segments) + ax.set_title('Line collection with customized caps and joinstyle') + + +@image_comparison(['scatter_post_alpha.png'], + remove_text=True, style='default') +def test_scatter_post_alpha(): + fig, ax = plt.subplots() + sc = ax.scatter(range(5), range(5), c=range(5)) + sc.set_alpha(.1) + + +def test_scatter_alpha_array(): + x = np.arange(5) + alpha = x / 5 + # With colormapping. + fig, (ax0, ax1) = plt.subplots(2) + sc0 = ax0.scatter(x, x, c=x, alpha=alpha) + sc1 = ax1.scatter(x, x, c=x) + sc1.set_alpha(alpha) + plt.draw() + assert_array_equal(sc0.get_facecolors()[:, -1], alpha) + assert_array_equal(sc1.get_facecolors()[:, -1], alpha) + # Without colormapping. + fig, (ax0, ax1) = plt.subplots(2) + sc0 = ax0.scatter(x, x, color=['r', 'g', 'b', 'c', 'm'], alpha=alpha) + sc1 = ax1.scatter(x, x, color='r', alpha=alpha) + plt.draw() + assert_array_equal(sc0.get_facecolors()[:, -1], alpha) + assert_array_equal(sc1.get_facecolors()[:, -1], alpha) + # Without colormapping, and set alpha afterward. + fig, (ax0, ax1) = plt.subplots(2) + sc0 = ax0.scatter(x, x, color=['r', 'g', 'b', 'c', 'm']) + sc0.set_alpha(alpha) + sc1 = ax1.scatter(x, x, color='r') + sc1.set_alpha(alpha) + plt.draw() + assert_array_equal(sc0.get_facecolors()[:, -1], alpha) + assert_array_equal(sc1.get_facecolors()[:, -1], alpha) + + +def test_pathcollection_legend_elements(): + np.random.seed(19680801) + x, y = np.random.rand(2, 10) + y = np.random.rand(10) + c = np.random.randint(0, 5, size=10) + s = np.random.randint(10, 300, size=10) + + fig, ax = plt.subplots() + sc = ax.scatter(x, y, c=c, s=s, cmap="jet", marker="o", linewidths=0) + + h, l = sc.legend_elements(fmt="{x:g}") + assert len(h) == 5 + assert l == ["0", "1", "2", "3", "4"] + colors = np.array([line.get_color() for line in h]) + colors2 = sc.cmap(np.arange(5)/4) + assert_array_equal(colors, colors2) + l1 = ax.legend(h, l, loc=1) + + h2, lab2 = sc.legend_elements(num=9) + assert len(h2) == 9 + l2 = ax.legend(h2, lab2, loc=2) + + h, l = sc.legend_elements(prop="sizes", alpha=0.5, color="red") + assert all(line.get_alpha() == 0.5 for line in h) + assert all(line.get_markerfacecolor() == "red" for line in h) + l3 = ax.legend(h, l, loc=4) + + h, l = sc.legend_elements(prop="sizes", num=4, fmt="{x:.2f}", + func=lambda x: 2*x) + actsizes = [line.get_markersize() for line in h] + labeledsizes = np.sqrt(np.array(l, float) / 2) + assert_array_almost_equal(actsizes, labeledsizes) + l4 = ax.legend(h, l, loc=3) + + loc = mpl.ticker.MaxNLocator(nbins=9, min_n_ticks=9-1, + steps=[1, 2, 2.5, 3, 5, 6, 8, 10]) + h5, lab5 = sc.legend_elements(num=loc) + assert len(h2) == len(h5) + + levels = [-1, 0, 55.4, 260] + h6, lab6 = sc.legend_elements(num=levels, prop="sizes", fmt="{x:g}") + assert [float(l) for l in lab6] == levels[2:] + + for l in [l1, l2, l3, l4]: + ax.add_artist(l) + + fig.canvas.draw() + + +def test_EventCollection_nosort(): + # Check that EventCollection doesn't modify input in place + arr = np.array([3, 2, 1, 10]) + coll = EventCollection(arr) + np.testing.assert_array_equal(arr, np.array([3, 2, 1, 10])) + + +def test_collection_set_verts_array(): + verts = np.arange(80, dtype=np.double).reshape(10, 4, 2) + col_arr = PolyCollection(verts) + col_list = PolyCollection(list(verts)) + assert len(col_arr._paths) == len(col_list._paths) + for ap, lp in zip(col_arr._paths, col_list._paths): + assert np.array_equal(ap._vertices, lp._vertices) + assert np.array_equal(ap._codes, lp._codes) + + verts_tuple = np.empty(10, dtype=object) + verts_tuple[:] = [tuple(tuple(y) for y in x) for x in verts] + col_arr_tuple = PolyCollection(verts_tuple) + assert len(col_arr._paths) == len(col_arr_tuple._paths) + for ap, atp in zip(col_arr._paths, col_arr_tuple._paths): + assert np.array_equal(ap._vertices, atp._vertices) + assert np.array_equal(ap._codes, atp._codes) + + +def test_collection_set_array(): + vals = [*range(10)] + + # Test set_array with list + c = Collection() + c.set_array(vals) + + # Test set_array with wrong dtype + with pytest.raises(TypeError, match="^Image data of dtype"): + c.set_array("wrong_input") + + # Test if array kwarg is copied + vals[5] = 45 + assert np.not_equal(vals, c.get_array()).any() + + +def test_blended_collection_autolim(): + a = [1, 2, 4] + height = .2 + + xy_pairs = np.column_stack([np.repeat(a, 2), np.tile([0, height], len(a))]) + line_segs = xy_pairs.reshape([len(a), 2, 2]) + + f, ax = plt.subplots() + trans = mtransforms.blended_transform_factory(ax.transData, ax.transAxes) + ax.add_collection(LineCollection(line_segs, transform=trans)) + ax.autoscale_view(scalex=True, scaley=False) + np.testing.assert_allclose(ax.get_xlim(), [1., 4.]) + + +def test_singleton_autolim(): + fig, ax = plt.subplots() + ax.scatter(0, 0) + np.testing.assert_allclose(ax.get_ylim(), [-0.06, 0.06]) + np.testing.assert_allclose(ax.get_xlim(), [-0.06, 0.06]) + + +@pytest.mark.parametrize("transform, expected", [ + ("transData", (-0.5, 3.5)), + ("transAxes", (2.8, 3.2)), +]) +def test_autolim_with_zeros(transform, expected): + # 1) Test that a scatter at (0, 0) data coordinates contributes to + # autoscaling even though any(offsets) would be False in that situation. + # 2) Test that specifying transAxes for the transform does not contribute + # to the autoscaling. + fig, ax = plt.subplots() + ax.scatter(0, 0, transform=getattr(ax, transform)) + ax.scatter(3, 3) + np.testing.assert_allclose(ax.get_ylim(), expected) + np.testing.assert_allclose(ax.get_xlim(), expected) + + +def test_quadmesh_set_array_validation(): + x = np.arange(11) + y = np.arange(8) + z = np.random.random((7, 10)) + fig, ax = plt.subplots() + coll = ax.pcolormesh(x, y, z) + + with pytest.raises(ValueError, match=re.escape( + "For X (11) and Y (8) with flat shading, A should have shape " + "(7, 10, 3) or (7, 10, 4) or (7, 10) or (70,), not (10, 7)")): + coll.set_array(z.reshape(10, 7)) + + z = np.arange(54).reshape((6, 9)) + with pytest.raises(ValueError, match=re.escape( + "For X (11) and Y (8) with flat shading, A should have shape " + "(7, 10, 3) or (7, 10, 4) or (7, 10) or (70,), not (6, 9)")): + coll.set_array(z) + with pytest.raises(ValueError, match=re.escape( + "For X (11) and Y (8) with flat shading, A should have shape " + "(7, 10, 3) or (7, 10, 4) or (7, 10) or (70,), not (54,)")): + coll.set_array(z.ravel()) + + # RGB(A) tests + z = np.ones((9, 6, 3)) # RGB with wrong X/Y dims + with pytest.raises(ValueError, match=re.escape( + "For X (11) and Y (8) with flat shading, A should have shape " + "(7, 10, 3) or (7, 10, 4) or (7, 10) or (70,), not (9, 6, 3)")): + coll.set_array(z) + + z = np.ones((9, 6, 4)) # RGBA with wrong X/Y dims + with pytest.raises(ValueError, match=re.escape( + "For X (11) and Y (8) with flat shading, A should have shape " + "(7, 10, 3) or (7, 10, 4) or (7, 10) or (70,), not (9, 6, 4)")): + coll.set_array(z) + + z = np.ones((7, 10, 2)) # Right X/Y dims, bad 3rd dim + with pytest.raises(ValueError, match=re.escape( + "For X (11) and Y (8) with flat shading, A should have shape " + "(7, 10, 3) or (7, 10, 4) or (7, 10) or (70,), not (7, 10, 2)")): + coll.set_array(z) + + x = np.arange(10) + y = np.arange(7) + z = np.random.random((7, 10)) + fig, ax = plt.subplots() + coll = ax.pcolormesh(x, y, z, shading='gouraud') + + +def test_quadmesh_get_coordinates(): + x = [0, 1, 2] + y = [2, 4, 6] + z = np.ones(shape=(2, 2)) + xx, yy = np.meshgrid(x, y) + coll = plt.pcolormesh(xx, yy, z) + + # shape (3, 3, 2) + coords = np.stack([xx.T, yy.T]).T + assert_array_equal(coll.get_coordinates(), coords) + + +def test_quadmesh_set_array(): + x = np.arange(4) + y = np.arange(4) + z = np.arange(9).reshape((3, 3)) + fig, ax = plt.subplots() + coll = ax.pcolormesh(x, y, np.ones(z.shape)) + # Test that the collection is able to update with a 2d array + coll.set_array(z) + fig.canvas.draw() + assert np.array_equal(coll.get_array(), z) + + # Check that pre-flattened arrays work too + coll.set_array(np.ones(9)) + fig.canvas.draw() + assert np.array_equal(coll.get_array(), np.ones(9)) + + z = np.arange(16).reshape((4, 4)) + fig, ax = plt.subplots() + coll = ax.pcolormesh(x, y, np.ones(z.shape), shading='gouraud') + # Test that the collection is able to update with a 2d array + coll.set_array(z) + fig.canvas.draw() + assert np.array_equal(coll.get_array(), z) + + # Check that pre-flattened arrays work too + coll.set_array(np.ones(16)) + fig.canvas.draw() + assert np.array_equal(coll.get_array(), np.ones(16)) + + +def test_quadmesh_vmin_vmax(): + # test when vmin/vmax on the norm changes, the quadmesh gets updated + fig, ax = plt.subplots() + cmap = mpl.colormaps['plasma'] + norm = mpl.colors.Normalize(vmin=0, vmax=1) + coll = ax.pcolormesh([[1]], cmap=cmap, norm=norm) + fig.canvas.draw() + assert np.array_equal(coll.get_facecolors()[0, :], cmap(norm(1))) + + # Change the vmin/vmax of the norm so that the color is from + # the bottom of the colormap now + norm.vmin, norm.vmax = 1, 2 + fig.canvas.draw() + assert np.array_equal(coll.get_facecolors()[0, :], cmap(norm(1))) + + +def test_quadmesh_alpha_array(): + x = np.arange(4) + y = np.arange(4) + z = np.arange(9).reshape((3, 3)) + alpha = z / z.max() + alpha_flat = alpha.ravel() + # Provide 2-D alpha: + fig, (ax0, ax1) = plt.subplots(2) + coll1 = ax0.pcolormesh(x, y, z, alpha=alpha) + coll2 = ax1.pcolormesh(x, y, z) + coll2.set_alpha(alpha) + plt.draw() + assert_array_equal(coll1.get_facecolors()[:, -1], alpha_flat) + assert_array_equal(coll2.get_facecolors()[:, -1], alpha_flat) + # Or provide 1-D alpha: + fig, (ax0, ax1) = plt.subplots(2) + coll1 = ax0.pcolormesh(x, y, z, alpha=alpha_flat) + coll2 = ax1.pcolormesh(x, y, z) + coll2.set_alpha(alpha_flat) + plt.draw() + assert_array_equal(coll1.get_facecolors()[:, -1], alpha_flat) + assert_array_equal(coll2.get_facecolors()[:, -1], alpha_flat) + + +def test_alpha_validation(): + # Most of the relevant testing is in test_artist and test_colors. + fig, ax = plt.subplots() + pc = ax.pcolormesh(np.arange(12).reshape((3, 4))) + with pytest.raises(ValueError, match="^Data array shape"): + pc.set_alpha([0.5, 0.6]) + pc.update_scalarmappable() + + +def test_legend_inverse_size_label_relationship(): + """ + Ensure legend markers scale appropriately when label and size are + inversely related. + Here label = 5 / size + """ + + np.random.seed(19680801) + X = np.random.random(50) + Y = np.random.random(50) + C = 1 - np.random.random(50) + S = 5 / C + + legend_sizes = [0.2, 0.4, 0.6, 0.8] + fig, ax = plt.subplots() + sc = ax.scatter(X, Y, s=S) + handles, labels = sc.legend_elements( + prop='sizes', num=legend_sizes, func=lambda s: 5 / s + ) + + # Convert markersize scale to 's' scale + handle_sizes = [x.get_markersize() for x in handles] + handle_sizes = [5 / x**2 for x in handle_sizes] + + assert_array_almost_equal(handle_sizes, legend_sizes, decimal=1) + + +@mpl.style.context('default') +@pytest.mark.parametrize('pcfunc', [plt.pcolor, plt.pcolormesh]) +def test_color_logic(pcfunc): + z = np.arange(12).reshape(3, 4) + # Explicitly set an edgecolor. + pc = pcfunc(z, edgecolors='red', facecolors='none') + pc.update_scalarmappable() # This is called in draw(). + # Define 2 reference "colors" here for multiple use. + face_default = mcolors.to_rgba_array(pc._get_default_facecolor()) + mapped = pc.get_cmap()(pc.norm((z.ravel()))) + # GitHub issue #1302: + assert mcolors.same_color(pc.get_edgecolor(), 'red') + # Check setting attributes after initialization: + pc = pcfunc(z) + pc.set_facecolor('none') + pc.set_edgecolor('red') + pc.update_scalarmappable() + assert mcolors.same_color(pc.get_facecolor(), 'none') + assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 1]]) + pc.set_alpha(0.5) + pc.update_scalarmappable() + assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 0.5]]) + pc.set_alpha(None) # restore default alpha + pc.update_scalarmappable() + assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 1]]) + # Reset edgecolor to default. + pc.set_edgecolor(None) + pc.update_scalarmappable() + assert mcolors.same_color(pc.get_edgecolor(), mapped) + pc.set_facecolor(None) # restore default for facecolor + pc.update_scalarmappable() + assert mcolors.same_color(pc.get_facecolor(), mapped) + assert mcolors.same_color(pc.get_edgecolor(), 'none') + # Turn off colormapping entirely: + pc.set_array(None) + pc.update_scalarmappable() + assert mcolors.same_color(pc.get_edgecolor(), 'none') + assert mcolors.same_color(pc.get_facecolor(), face_default) # not mapped + # Turn it back on by restoring the array (must be 1D!): + pc.set_array(z.ravel()) + pc.update_scalarmappable() + assert mcolors.same_color(pc.get_facecolor(), mapped) + assert mcolors.same_color(pc.get_edgecolor(), 'none') + # Give color via tuple rather than string. + pc = pcfunc(z, edgecolors=(1, 0, 0), facecolors=(0, 1, 0)) + pc.update_scalarmappable() + assert mcolors.same_color(pc.get_facecolor(), mapped) + assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 1]]) + # Provide an RGB array; mapping overrides it. + pc = pcfunc(z, edgecolors=(1, 0, 0), facecolors=np.ones((12, 3))) + pc.update_scalarmappable() + assert mcolors.same_color(pc.get_facecolor(), mapped) + assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 1]]) + # Turn off the mapping. + pc.set_array(None) + pc.update_scalarmappable() + assert mcolors.same_color(pc.get_facecolor(), np.ones((12, 3))) + assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 1]]) + # And an RGBA array. + pc = pcfunc(z, edgecolors=(1, 0, 0), facecolors=np.ones((12, 4))) + pc.update_scalarmappable() + assert mcolors.same_color(pc.get_facecolor(), mapped) + assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 1]]) + # Turn off the mapping. + pc.set_array(None) + pc.update_scalarmappable() + assert mcolors.same_color(pc.get_facecolor(), np.ones((12, 4))) + assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 1]]) + + +def test_LineCollection_args(): + lc = LineCollection(None, linewidth=2.2, edgecolor='r', + zorder=3, facecolors=[0, 1, 0, 1]) + assert lc.get_linewidth()[0] == 2.2 + assert mcolors.same_color(lc.get_edgecolor(), 'r') + assert lc.get_zorder() == 3 + assert mcolors.same_color(lc.get_facecolor(), [[0, 1, 0, 1]]) + # To avoid breaking mplot3d, LineCollection internally sets the facecolor + # kwarg if it has not been specified. Hence we need the following test + # for LineCollection._set_default(). + lc = LineCollection(None, facecolor=None) + assert mcolors.same_color(lc.get_facecolor(), 'none') + + +def test_array_wrong_dimensions(): + z = np.arange(12).reshape(3, 4) + pc = plt.pcolor(z) + with pytest.raises(ValueError, match="^Collections can only map"): + pc.set_array(z) + pc.update_scalarmappable() + pc = plt.pcolormesh(z) + pc.set_array(z) # 2D is OK for Quadmesh + pc.update_scalarmappable() + # 3D RGB is OK as well + z = np.arange(36).reshape(3, 4, 3) + pc.set_array(z) + + +def test_get_segments(): + segments = np.tile(np.linspace(0, 1, 256), (2, 1)).T + lc = LineCollection([segments]) + + readback, = lc.get_segments() + # these should comeback un-changed! + assert np.all(segments == readback) + + +def test_set_offsets_late(): + identity = mtransforms.IdentityTransform() + sizes = [2] + + null = mcollections.CircleCollection(sizes=sizes) + + init = mcollections.CircleCollection(sizes=sizes, offsets=(10, 10)) + + late = mcollections.CircleCollection(sizes=sizes) + late.set_offsets((10, 10)) + + # Bbox.__eq__ doesn't compare bounds + null_bounds = null.get_datalim(identity).bounds + init_bounds = init.get_datalim(identity).bounds + late_bounds = late.get_datalim(identity).bounds + + # offsets and transform are applied when set after initialization + assert null_bounds != init_bounds + assert init_bounds == late_bounds + + +def test_set_offset_transform(): + skew = mtransforms.Affine2D().skew(2, 2) + init = mcollections.Collection(offset_transform=skew) + + late = mcollections.Collection() + late.set_offset_transform(skew) + + assert skew == init.get_offset_transform() == late.get_offset_transform() + + +def test_set_offset_units(): + # passing the offsets in initially (i.e. via scatter) + # should yield the same results as `set_offsets` + x = np.linspace(0, 10, 5) + y = np.sin(x) + d = x * np.timedelta64(24, 'h') + np.datetime64('2021-11-29') + + sc = plt.scatter(d, y) + off0 = sc.get_offsets() + sc.set_offsets(list(zip(d, y))) + np.testing.assert_allclose(off0, sc.get_offsets()) + + # try the other way around + fig, ax = plt.subplots() + sc = ax.scatter(y, d) + off0 = sc.get_offsets() + sc.set_offsets(list(zip(y, d))) + np.testing.assert_allclose(off0, sc.get_offsets()) + + +@image_comparison(baseline_images=["test_check_masked_offsets"], + extensions=["png"], remove_text=True, style="mpl20") +def test_check_masked_offsets(): + # Check if masked data is respected by scatter + # Ref: Issue #24545 + unmasked_x = [ + datetime(2022, 12, 15, 4, 49, 52), + datetime(2022, 12, 15, 4, 49, 53), + datetime(2022, 12, 15, 4, 49, 54), + datetime(2022, 12, 15, 4, 49, 55), + datetime(2022, 12, 15, 4, 49, 56), + ] + + masked_y = np.ma.array([1, 2, 3, 4, 5], mask=[0, 1, 1, 0, 0]) + + fig, ax = plt.subplots() + ax.scatter(unmasked_x, masked_y) + + +@check_figures_equal(extensions=["png"]) +def test_masked_set_offsets(fig_ref, fig_test): + x = np.ma.array([1, 2, 3, 4, 5], mask=[0, 0, 1, 1, 0]) + y = np.arange(1, 6) + + ax_test = fig_test.add_subplot() + scat = ax_test.scatter(x, y) + scat.set_offsets(np.ma.column_stack([x, y])) + ax_test.set_xticks([]) + ax_test.set_yticks([]) + + ax_ref = fig_ref.add_subplot() + ax_ref.scatter([1, 2, 5], [1, 2, 5]) + ax_ref.set_xticks([]) + ax_ref.set_yticks([]) + + +def test_check_offsets_dtype(): + # Check that setting offsets doesn't change dtype + x = np.ma.array([1, 2, 3, 4, 5], mask=[0, 0, 1, 1, 0]) + y = np.arange(1, 6) + + fig, ax = plt.subplots() + scat = ax.scatter(x, y) + masked_offsets = np.ma.column_stack([x, y]) + scat.set_offsets(masked_offsets) + assert isinstance(scat.get_offsets(), type(masked_offsets)) + + unmasked_offsets = np.column_stack([x, y]) + scat.set_offsets(unmasked_offsets) + assert isinstance(scat.get_offsets(), type(unmasked_offsets)) diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/test_colors.py b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/test_colors.py new file mode 100644 index 0000000000000000000000000000000000000000..367fd6ce567f21b3c160fb7fa68996930149c47e --- /dev/null +++ b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/test_colors.py @@ -0,0 +1,1599 @@ +import copy +import itertools +import unittest.mock + +from io import BytesIO +import numpy as np +from PIL import Image +import pytest +import base64 + +from numpy.testing import assert_array_equal, assert_array_almost_equal + +from matplotlib import cbook, cm, cycler +import matplotlib +import matplotlib as mpl +import matplotlib.colors as mcolors +import matplotlib.colorbar as mcolorbar +import matplotlib.pyplot as plt +import matplotlib.scale as mscale +from matplotlib.testing.decorators import image_comparison, check_figures_equal + + +@pytest.mark.parametrize('N, result', [ + (5, [1, .6, .2, .1, 0]), + (2, [1, 0]), + (1, [0]), +]) +def test_create_lookup_table(N, result): + data = [(0.0, 1.0, 1.0), (0.5, 0.2, 0.2), (1.0, 0.0, 0.0)] + assert_array_almost_equal(mcolors._create_lookup_table(N, data), result) + + +@pytest.mark.parametrize("dtype", [np.uint8, int, np.float16, float]) +def test_index_dtype(dtype): + # We use subtraction in the indexing, so need to verify that uint8 works + cm = mpl.colormaps["viridis"] + assert_array_equal(cm(dtype(0)), cm(0)) + + +def test_resampled(): + """ + GitHub issue #6025 pointed to incorrect ListedColormap.resampled; + here we test the method for LinearSegmentedColormap as well. + """ + n = 101 + colorlist = np.empty((n, 4), float) + colorlist[:, 0] = np.linspace(0, 1, n) + colorlist[:, 1] = 0.2 + colorlist[:, 2] = np.linspace(1, 0, n) + colorlist[:, 3] = 0.7 + lsc = mcolors.LinearSegmentedColormap.from_list('lsc', colorlist) + lc = mcolors.ListedColormap(colorlist) + # Set some bad values for testing too + for cmap in [lsc, lc]: + cmap.set_under('r') + cmap.set_over('g') + cmap.set_bad('b') + lsc3 = lsc.resampled(3) + lc3 = lc.resampled(3) + expected = np.array([[0.0, 0.2, 1.0, 0.7], + [0.5, 0.2, 0.5, 0.7], + [1.0, 0.2, 0.0, 0.7]], float) + assert_array_almost_equal(lsc3([0, 0.5, 1]), expected) + assert_array_almost_equal(lc3([0, 0.5, 1]), expected) + # Test over/under was copied properly + assert_array_almost_equal(lsc(np.inf), lsc3(np.inf)) + assert_array_almost_equal(lsc(-np.inf), lsc3(-np.inf)) + assert_array_almost_equal(lsc(np.nan), lsc3(np.nan)) + assert_array_almost_equal(lc(np.inf), lc3(np.inf)) + assert_array_almost_equal(lc(-np.inf), lc3(-np.inf)) + assert_array_almost_equal(lc(np.nan), lc3(np.nan)) + + +def test_register_cmap(): + new_cm = mpl.colormaps["viridis"] + target = "viridis2" + with pytest.warns( + mpl.MatplotlibDeprecationWarning, + match=r"matplotlib\.colormaps\.register\(name\)" + ): + cm.register_cmap(target, new_cm) + assert mpl.colormaps[target] == new_cm + + with pytest.raises(ValueError, + match="Arguments must include a name or a Colormap"): + with pytest.warns( + mpl.MatplotlibDeprecationWarning, + match=r"matplotlib\.colormaps\.register\(name\)" + ): + cm.register_cmap() + + with pytest.warns( + mpl.MatplotlibDeprecationWarning, + match=r"matplotlib\.colormaps\.unregister\(name\)" + ): + cm.unregister_cmap(target) + with pytest.raises(ValueError, + match=f'{target!r} is not a valid value for name;'): + with pytest.warns( + mpl.MatplotlibDeprecationWarning, + match=r"matplotlib\.colormaps\[name\]" + ): + cm.get_cmap(target) + with pytest.warns( + mpl.MatplotlibDeprecationWarning, + match=r"matplotlib\.colormaps\.unregister\(name\)" + ): + # test that second time is error free + cm.unregister_cmap(target) + + with pytest.raises(TypeError, match="'cmap' must be"): + with pytest.warns( + mpl.MatplotlibDeprecationWarning, + match=r"matplotlib\.colormaps\.register\(name\)" + ): + cm.register_cmap('nome', cmap='not a cmap') + + +def test_colormaps_get_cmap(): + cr = mpl.colormaps + + # check str, and Colormap pass + assert cr.get_cmap('plasma') == cr["plasma"] + assert cr.get_cmap(cr["magma"]) == cr["magma"] + + # check default + assert cr.get_cmap(None) == cr[mpl.rcParams['image.cmap']] + + # check ValueError on bad name + bad_cmap = 'AardvarksAreAwkward' + with pytest.raises(ValueError, match=bad_cmap): + cr.get_cmap(bad_cmap) + + # check TypeError on bad type + with pytest.raises(TypeError, match='object'): + cr.get_cmap(object()) + + +def test_double_register_builtin_cmap(): + name = "viridis" + match = f"Re-registering the builtin cmap {name!r}." + with pytest.raises(ValueError, match=match): + matplotlib.colormaps.register( + mpl.colormaps[name], name=name, force=True + ) + with pytest.raises(ValueError, match='A colormap named "viridis"'): + with pytest.warns(mpl.MatplotlibDeprecationWarning): + cm.register_cmap(name, mpl.colormaps[name]) + with pytest.warns(UserWarning): + # TODO is warning more than once! + cm.register_cmap(name, mpl.colormaps[name], override_builtin=True) + + +def test_unregister_builtin_cmap(): + name = "viridis" + match = f'cannot unregister {name!r} which is a builtin colormap.' + with pytest.raises(ValueError, match=match): + with pytest.warns(mpl.MatplotlibDeprecationWarning): + cm.unregister_cmap(name) + + +def test_colormap_copy(): + cmap = plt.cm.Reds + copied_cmap = copy.copy(cmap) + with np.errstate(invalid='ignore'): + ret1 = copied_cmap([-1, 0, .5, 1, np.nan, np.inf]) + cmap2 = copy.copy(copied_cmap) + cmap2.set_bad('g') + with np.errstate(invalid='ignore'): + ret2 = copied_cmap([-1, 0, .5, 1, np.nan, np.inf]) + assert_array_equal(ret1, ret2) + # again with the .copy method: + cmap = plt.cm.Reds + copied_cmap = cmap.copy() + with np.errstate(invalid='ignore'): + ret1 = copied_cmap([-1, 0, .5, 1, np.nan, np.inf]) + cmap2 = copy.copy(copied_cmap) + cmap2.set_bad('g') + with np.errstate(invalid='ignore'): + ret2 = copied_cmap([-1, 0, .5, 1, np.nan, np.inf]) + assert_array_equal(ret1, ret2) + + +def test_colormap_equals(): + cmap = mpl.colormaps["plasma"] + cm_copy = cmap.copy() + # different object id's + assert cm_copy is not cmap + # But the same data should be equal + assert cm_copy == cmap + # Change the copy + cm_copy.set_bad('y') + assert cm_copy != cmap + # Make sure we can compare different sizes without failure + cm_copy._lut = cm_copy._lut[:10, :] + assert cm_copy != cmap + # Test different names are not equal + cm_copy = cmap.copy() + cm_copy.name = "Test" + assert cm_copy != cmap + # Test colorbar extends + cm_copy = cmap.copy() + cm_copy.colorbar_extend = not cmap.colorbar_extend + assert cm_copy != cmap + + +def test_colormap_endian(): + """ + GitHub issue #1005: a bug in putmask caused erroneous + mapping of 1.0 when input from a non-native-byteorder + array. + """ + cmap = mpl.colormaps["jet"] + # Test under, over, and invalid along with values 0 and 1. + a = [-0.5, 0, 0.5, 1, 1.5, np.nan] + for dt in ["f2", "f4", "f8"]: + anative = np.ma.masked_invalid(np.array(a, dtype=dt)) + aforeign = anative.byteswap().newbyteorder() + assert_array_equal(cmap(anative), cmap(aforeign)) + + +def test_colormap_invalid(): + """ + GitHub issue #9892: Handling of nan's were getting mapped to under + rather than bad. This tests to make sure all invalid values + (-inf, nan, inf) are mapped respectively to (under, bad, over). + """ + cmap = mpl.colormaps["plasma"] + x = np.array([-np.inf, -1, 0, np.nan, .7, 2, np.inf]) + + expected = np.array([[0.050383, 0.029803, 0.527975, 1.], + [0.050383, 0.029803, 0.527975, 1.], + [0.050383, 0.029803, 0.527975, 1.], + [0., 0., 0., 0.], + [0.949217, 0.517763, 0.295662, 1.], + [0.940015, 0.975158, 0.131326, 1.], + [0.940015, 0.975158, 0.131326, 1.]]) + assert_array_equal(cmap(x), expected) + + # Test masked representation (-inf, inf) are now masked + expected = np.array([[0., 0., 0., 0.], + [0.050383, 0.029803, 0.527975, 1.], + [0.050383, 0.029803, 0.527975, 1.], + [0., 0., 0., 0.], + [0.949217, 0.517763, 0.295662, 1.], + [0.940015, 0.975158, 0.131326, 1.], + [0., 0., 0., 0.]]) + assert_array_equal(cmap(np.ma.masked_invalid(x)), expected) + + # Test scalar representations + assert_array_equal(cmap(-np.inf), cmap(0)) + assert_array_equal(cmap(np.inf), cmap(1.0)) + assert_array_equal(cmap(np.nan), [0., 0., 0., 0.]) + + +def test_colormap_return_types(): + """ + Make sure that tuples are returned for scalar input and + that the proper shapes are returned for ndarrays. + """ + cmap = mpl.colormaps["plasma"] + # Test return types and shapes + # scalar input needs to return a tuple of length 4 + assert isinstance(cmap(0.5), tuple) + assert len(cmap(0.5)) == 4 + + # input array returns an ndarray of shape x.shape + (4,) + x = np.ones(4) + assert cmap(x).shape == x.shape + (4,) + + # multi-dimensional array input + x2d = np.zeros((2, 2)) + assert cmap(x2d).shape == x2d.shape + (4,) + + +def test_BoundaryNorm(): + """ + GitHub issue #1258: interpolation was failing with numpy + 1.7 pre-release. + """ + + boundaries = [0, 1.1, 2.2] + vals = [-1, 0, 1, 2, 2.2, 4] + + # Without interpolation + expected = [-1, 0, 0, 1, 2, 2] + ncolors = len(boundaries) - 1 + bn = mcolors.BoundaryNorm(boundaries, ncolors) + assert_array_equal(bn(vals), expected) + + # ncolors != len(boundaries) - 1 triggers interpolation + expected = [-1, 0, 0, 2, 3, 3] + ncolors = len(boundaries) + bn = mcolors.BoundaryNorm(boundaries, ncolors) + assert_array_equal(bn(vals), expected) + + # with a single region and interpolation + expected = [-1, 1, 1, 1, 3, 3] + bn = mcolors.BoundaryNorm([0, 2.2], ncolors) + assert_array_equal(bn(vals), expected) + + # more boundaries for a third color + boundaries = [0, 1, 2, 3] + vals = [-1, 0.1, 1.1, 2.2, 4] + ncolors = 5 + expected = [-1, 0, 2, 4, 5] + bn = mcolors.BoundaryNorm(boundaries, ncolors) + assert_array_equal(bn(vals), expected) + + # a scalar as input should not trigger an error and should return a scalar + boundaries = [0, 1, 2] + vals = [-1, 0.1, 1.1, 2.2] + bn = mcolors.BoundaryNorm(boundaries, 2) + expected = [-1, 0, 1, 2] + for v, ex in zip(vals, expected): + ret = bn(v) + assert isinstance(ret, int) + assert_array_equal(ret, ex) + assert_array_equal(bn([v]), ex) + + # same with interp + bn = mcolors.BoundaryNorm(boundaries, 3) + expected = [-1, 0, 2, 3] + for v, ex in zip(vals, expected): + ret = bn(v) + assert isinstance(ret, int) + assert_array_equal(ret, ex) + assert_array_equal(bn([v]), ex) + + # Clipping + bn = mcolors.BoundaryNorm(boundaries, 3, clip=True) + expected = [0, 0, 2, 2] + for v, ex in zip(vals, expected): + ret = bn(v) + assert isinstance(ret, int) + assert_array_equal(ret, ex) + assert_array_equal(bn([v]), ex) + + # Masked arrays + boundaries = [0, 1.1, 2.2] + vals = np.ma.masked_invalid([-1., np.nan, 0, 1.4, 9]) + + # Without interpolation + ncolors = len(boundaries) - 1 + bn = mcolors.BoundaryNorm(boundaries, ncolors) + expected = np.ma.masked_array([-1, -99, 0, 1, 2], mask=[0, 1, 0, 0, 0]) + assert_array_equal(bn(vals), expected) + + # With interpolation + bn = mcolors.BoundaryNorm(boundaries, len(boundaries)) + expected = np.ma.masked_array([-1, -99, 0, 2, 3], mask=[0, 1, 0, 0, 0]) + assert_array_equal(bn(vals), expected) + + # Non-trivial masked arrays + vals = np.ma.masked_invalid([np.inf, np.nan]) + assert np.all(bn(vals).mask) + vals = np.ma.masked_invalid([np.inf]) + assert np.all(bn(vals).mask) + + # Incompatible extend and clip + with pytest.raises(ValueError, match="not compatible"): + mcolors.BoundaryNorm(np.arange(4), 5, extend='both', clip=True) + + # Too small ncolors argument + with pytest.raises(ValueError, match="ncolors must equal or exceed"): + mcolors.BoundaryNorm(np.arange(4), 2) + + with pytest.raises(ValueError, match="ncolors must equal or exceed"): + mcolors.BoundaryNorm(np.arange(4), 3, extend='min') + + with pytest.raises(ValueError, match="ncolors must equal or exceed"): + mcolors.BoundaryNorm(np.arange(4), 4, extend='both') + + # Testing extend keyword, with interpolation (large cmap) + bounds = [1, 2, 3] + cmap = mpl.colormaps['viridis'] + mynorm = mcolors.BoundaryNorm(bounds, cmap.N, extend='both') + refnorm = mcolors.BoundaryNorm([0] + bounds + [4], cmap.N) + x = np.random.randn(100) * 10 + 2 + ref = refnorm(x) + ref[ref == 0] = -1 + ref[ref == cmap.N - 1] = cmap.N + assert_array_equal(mynorm(x), ref) + + # Without interpolation + cmref = mcolors.ListedColormap(['blue', 'red']) + cmref.set_over('black') + cmref.set_under('white') + cmshould = mcolors.ListedColormap(['white', 'blue', 'red', 'black']) + + assert mcolors.same_color(cmref.get_over(), 'black') + assert mcolors.same_color(cmref.get_under(), 'white') + + refnorm = mcolors.BoundaryNorm(bounds, cmref.N) + mynorm = mcolors.BoundaryNorm(bounds, cmshould.N, extend='both') + assert mynorm.vmin == refnorm.vmin + assert mynorm.vmax == refnorm.vmax + + assert mynorm(bounds[0] - 0.1) == -1 # under + assert mynorm(bounds[0] + 0.1) == 1 # first bin -> second color + assert mynorm(bounds[-1] - 0.1) == cmshould.N - 2 # next-to-last color + assert mynorm(bounds[-1] + 0.1) == cmshould.N # over + + x = [-1, 1.2, 2.3, 9.6] + assert_array_equal(cmshould(mynorm(x)), cmshould([0, 1, 2, 3])) + x = np.random.randn(100) * 10 + 2 + assert_array_equal(cmshould(mynorm(x)), cmref(refnorm(x))) + + # Just min + cmref = mcolors.ListedColormap(['blue', 'red']) + cmref.set_under('white') + cmshould = mcolors.ListedColormap(['white', 'blue', 'red']) + + assert mcolors.same_color(cmref.get_under(), 'white') + + assert cmref.N == 2 + assert cmshould.N == 3 + refnorm = mcolors.BoundaryNorm(bounds, cmref.N) + mynorm = mcolors.BoundaryNorm(bounds, cmshould.N, extend='min') + assert mynorm.vmin == refnorm.vmin + assert mynorm.vmax == refnorm.vmax + x = [-1, 1.2, 2.3] + assert_array_equal(cmshould(mynorm(x)), cmshould([0, 1, 2])) + x = np.random.randn(100) * 10 + 2 + assert_array_equal(cmshould(mynorm(x)), cmref(refnorm(x))) + + # Just max + cmref = mcolors.ListedColormap(['blue', 'red']) + cmref.set_over('black') + cmshould = mcolors.ListedColormap(['blue', 'red', 'black']) + + assert mcolors.same_color(cmref.get_over(), 'black') + + assert cmref.N == 2 + assert cmshould.N == 3 + refnorm = mcolors.BoundaryNorm(bounds, cmref.N) + mynorm = mcolors.BoundaryNorm(bounds, cmshould.N, extend='max') + assert mynorm.vmin == refnorm.vmin + assert mynorm.vmax == refnorm.vmax + x = [1.2, 2.3, 4] + assert_array_equal(cmshould(mynorm(x)), cmshould([0, 1, 2])) + x = np.random.randn(100) * 10 + 2 + assert_array_equal(cmshould(mynorm(x)), cmref(refnorm(x))) + + +def test_CenteredNorm(): + np.random.seed(0) + + # Assert equivalence to symmetrical Normalize. + x = np.random.normal(size=100) + x_maxabs = np.max(np.abs(x)) + norm_ref = mcolors.Normalize(vmin=-x_maxabs, vmax=x_maxabs) + norm = mcolors.CenteredNorm() + assert_array_almost_equal(norm_ref(x), norm(x)) + + # Check that vcenter is in the center of vmin and vmax + # when vcenter is set. + vcenter = int(np.random.normal(scale=50)) + norm = mcolors.CenteredNorm(vcenter=vcenter) + norm.autoscale_None([1, 2]) + assert norm.vmax + norm.vmin == 2 * vcenter + + # Check that halfrange can be set without setting vcenter and that it is + # not reset through autoscale_None. + norm = mcolors.CenteredNorm(halfrange=1.0) + norm.autoscale_None([1, 3000]) + assert norm.halfrange == 1.0 + + # Check that halfrange input works correctly. + x = np.random.normal(size=10) + norm = mcolors.CenteredNorm(vcenter=0.5, halfrange=0.5) + assert_array_almost_equal(x, norm(x)) + norm = mcolors.CenteredNorm(vcenter=1, halfrange=1) + assert_array_almost_equal(x, 2 * norm(x)) + + # Check that halfrange input works correctly and use setters. + norm = mcolors.CenteredNorm() + norm.vcenter = 2 + norm.halfrange = 2 + assert_array_almost_equal(x, 4 * norm(x)) + + # Check that prior to adding data, setting halfrange first has same effect. + norm = mcolors.CenteredNorm() + norm.halfrange = 2 + norm.vcenter = 2 + assert_array_almost_equal(x, 4 * norm(x)) + + # Check that manual change of vcenter adjusts halfrange accordingly. + norm = mcolors.CenteredNorm() + assert norm.vcenter == 0 + # add data + norm(np.linspace(-1.0, 0.0, 10)) + assert norm.vmax == 1.0 + assert norm.halfrange == 1.0 + # set vcenter to 1, which should move the center but leave the + # halfrange unchanged + norm.vcenter = 1 + assert norm.vmin == 0 + assert norm.vmax == 2 + assert norm.halfrange == 1 + + # Check setting vmin directly updates the halfrange and vmax, but + # leaves vcenter alone + norm.vmin = -1 + assert norm.halfrange == 2 + assert norm.vmax == 3 + assert norm.vcenter == 1 + + # also check vmax updates + norm.vmax = 2 + assert norm.halfrange == 1 + assert norm.vmin == 0 + assert norm.vcenter == 1 + + +@pytest.mark.parametrize("vmin,vmax", [[-1, 2], [3, 1]]) +def test_lognorm_invalid(vmin, vmax): + # Check that invalid limits in LogNorm error + norm = mcolors.LogNorm(vmin=vmin, vmax=vmax) + with pytest.raises(ValueError): + norm(1) + with pytest.raises(ValueError): + norm.inverse(1) + + +def test_LogNorm(): + """ + LogNorm ignored clip, now it has the same + behavior as Normalize, e.g., values > vmax are bigger than 1 + without clip, with clip they are 1. + """ + ln = mcolors.LogNorm(clip=True, vmax=5) + assert_array_equal(ln([1, 6]), [0, 1.0]) + + +def test_LogNorm_inverse(): + """ + Test that lists work, and that the inverse works + """ + norm = mcolors.LogNorm(vmin=0.1, vmax=10) + assert_array_almost_equal(norm([0.5, 0.4]), [0.349485, 0.30103]) + assert_array_almost_equal([0.5, 0.4], norm.inverse([0.349485, 0.30103])) + assert_array_almost_equal(norm(0.4), [0.30103]) + assert_array_almost_equal([0.4], norm.inverse([0.30103])) + + +def test_PowerNorm(): + a = np.array([0, 0.5, 1, 1.5], dtype=float) + pnorm = mcolors.PowerNorm(1) + norm = mcolors.Normalize() + assert_array_almost_equal(norm(a), pnorm(a)) + + a = np.array([-0.5, 0, 2, 4, 8], dtype=float) + expected = [0, 0, 1/16, 1/4, 1] + pnorm = mcolors.PowerNorm(2, vmin=0, vmax=8) + assert_array_almost_equal(pnorm(a), expected) + assert pnorm(a[0]) == expected[0] + assert pnorm(a[2]) == expected[2] + assert_array_almost_equal(a[1:], pnorm.inverse(pnorm(a))[1:]) + + # Clip = True + a = np.array([-0.5, 0, 1, 8, 16], dtype=float) + expected = [0, 0, 0, 1, 1] + pnorm = mcolors.PowerNorm(2, vmin=2, vmax=8, clip=True) + assert_array_almost_equal(pnorm(a), expected) + assert pnorm(a[0]) == expected[0] + assert pnorm(a[-1]) == expected[-1] + + # Clip = True at call time + a = np.array([-0.5, 0, 1, 8, 16], dtype=float) + expected = [0, 0, 0, 1, 1] + pnorm = mcolors.PowerNorm(2, vmin=2, vmax=8, clip=False) + assert_array_almost_equal(pnorm(a, clip=True), expected) + assert pnorm(a[0], clip=True) == expected[0] + assert pnorm(a[-1], clip=True) == expected[-1] + + +def test_PowerNorm_translation_invariance(): + a = np.array([0, 1/2, 1], dtype=float) + expected = [0, 1/8, 1] + pnorm = mcolors.PowerNorm(vmin=0, vmax=1, gamma=3) + assert_array_almost_equal(pnorm(a), expected) + pnorm = mcolors.PowerNorm(vmin=-2, vmax=-1, gamma=3) + assert_array_almost_equal(pnorm(a - 2), expected) + + +def test_Normalize(): + norm = mcolors.Normalize() + vals = np.arange(-10, 10, 1, dtype=float) + _inverse_tester(norm, vals) + _scalar_tester(norm, vals) + _mask_tester(norm, vals) + + # Handle integer input correctly (don't overflow when computing max-min, + # i.e. 127-(-128) here). + vals = np.array([-128, 127], dtype=np.int8) + norm = mcolors.Normalize(vals.min(), vals.max()) + assert_array_equal(norm(vals), [0, 1]) + + # Don't lose precision on longdoubles (float128 on Linux): + # for array inputs... + vals = np.array([1.2345678901, 9.8765432109], dtype=np.longdouble) + norm = mcolors.Normalize(vals[0], vals[1]) + assert norm(vals).dtype == np.longdouble + assert_array_equal(norm(vals), [0, 1]) + # and for scalar ones. + eps = np.finfo(np.longdouble).resolution + norm = plt.Normalize(1, 1 + 100 * eps) + # This returns exactly 0.5 when longdouble is extended precision (80-bit), + # but only a value close to it when it is quadruple precision (128-bit). + assert_array_almost_equal(norm(1 + 50 * eps), 0.5, decimal=3) + + +def test_FuncNorm(): + def forward(x): + return (x**2) + def inverse(x): + return np.sqrt(x) + + norm = mcolors.FuncNorm((forward, inverse), vmin=0, vmax=10) + expected = np.array([0, 0.25, 1]) + input = np.array([0, 5, 10]) + assert_array_almost_equal(norm(input), expected) + assert_array_almost_equal(norm.inverse(expected), input) + + def forward(x): + return np.log10(x) + def inverse(x): + return 10**x + norm = mcolors.FuncNorm((forward, inverse), vmin=0.1, vmax=10) + lognorm = mcolors.LogNorm(vmin=0.1, vmax=10) + assert_array_almost_equal(norm([0.2, 5, 10]), lognorm([0.2, 5, 10])) + assert_array_almost_equal(norm.inverse([0.2, 5, 10]), + lognorm.inverse([0.2, 5, 10])) + + +def test_TwoSlopeNorm_autoscale(): + norm = mcolors.TwoSlopeNorm(vcenter=20) + norm.autoscale([10, 20, 30, 40]) + assert norm.vmin == 10. + assert norm.vmax == 40. + + +def test_TwoSlopeNorm_autoscale_None_vmin(): + norm = mcolors.TwoSlopeNorm(2, vmin=0, vmax=None) + norm.autoscale_None([1, 2, 3, 4, 5]) + assert norm(5) == 1 + assert norm.vmax == 5 + + +def test_TwoSlopeNorm_autoscale_None_vmax(): + norm = mcolors.TwoSlopeNorm(2, vmin=None, vmax=10) + norm.autoscale_None([1, 2, 3, 4, 5]) + assert norm(1) == 0 + assert norm.vmin == 1 + + +def test_TwoSlopeNorm_scale(): + norm = mcolors.TwoSlopeNorm(2) + assert norm.scaled() is False + norm([1, 2, 3, 4]) + assert norm.scaled() is True + + +def test_TwoSlopeNorm_scaleout_center(): + # test the vmin never goes above vcenter + norm = mcolors.TwoSlopeNorm(vcenter=0) + norm([1, 2, 3, 5]) + assert norm.vmin == 0 + assert norm.vmax == 5 + + +def test_TwoSlopeNorm_scaleout_center_max(): + # test the vmax never goes below vcenter + norm = mcolors.TwoSlopeNorm(vcenter=0) + norm([-1, -2, -3, -5]) + assert norm.vmax == 0 + assert norm.vmin == -5 + + +def test_TwoSlopeNorm_Even(): + norm = mcolors.TwoSlopeNorm(vmin=-1, vcenter=0, vmax=4) + vals = np.array([-1.0, -0.5, 0.0, 1.0, 2.0, 3.0, 4.0]) + expected = np.array([0.0, 0.25, 0.5, 0.625, 0.75, 0.875, 1.0]) + assert_array_equal(norm(vals), expected) + + +def test_TwoSlopeNorm_Odd(): + norm = mcolors.TwoSlopeNorm(vmin=-2, vcenter=0, vmax=5) + vals = np.array([-2.0, -1.0, 0.0, 1.0, 2.0, 3.0, 4.0, 5.0]) + expected = np.array([0.0, 0.25, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]) + assert_array_equal(norm(vals), expected) + + +def test_TwoSlopeNorm_VminEqualsVcenter(): + with pytest.raises(ValueError): + mcolors.TwoSlopeNorm(vmin=-2, vcenter=-2, vmax=2) + + +def test_TwoSlopeNorm_VmaxEqualsVcenter(): + with pytest.raises(ValueError): + mcolors.TwoSlopeNorm(vmin=-2, vcenter=2, vmax=2) + + +def test_TwoSlopeNorm_VminGTVcenter(): + with pytest.raises(ValueError): + mcolors.TwoSlopeNorm(vmin=10, vcenter=0, vmax=20) + + +def test_TwoSlopeNorm_TwoSlopeNorm_VminGTVmax(): + with pytest.raises(ValueError): + mcolors.TwoSlopeNorm(vmin=10, vcenter=0, vmax=5) + + +def test_TwoSlopeNorm_VcenterGTVmax(): + with pytest.raises(ValueError): + mcolors.TwoSlopeNorm(vmin=10, vcenter=25, vmax=20) + + +def test_TwoSlopeNorm_premature_scaling(): + norm = mcolors.TwoSlopeNorm(vcenter=2) + with pytest.raises(ValueError): + norm.inverse(np.array([0.1, 0.5, 0.9])) + + +def test_SymLogNorm(): + """ + Test SymLogNorm behavior + """ + norm = mcolors.SymLogNorm(3, vmax=5, linscale=1.2, base=np.e) + vals = np.array([-30, -1, 2, 6], dtype=float) + normed_vals = norm(vals) + expected = [0., 0.53980074, 0.826991, 1.02758204] + assert_array_almost_equal(normed_vals, expected) + _inverse_tester(norm, vals) + _scalar_tester(norm, vals) + _mask_tester(norm, vals) + + # Ensure that specifying vmin returns the same result as above + norm = mcolors.SymLogNorm(3, vmin=-30, vmax=5, linscale=1.2, base=np.e) + normed_vals = norm(vals) + assert_array_almost_equal(normed_vals, expected) + + # test something more easily checked. + norm = mcolors.SymLogNorm(1, vmin=-np.e**3, vmax=np.e**3, base=np.e) + nn = norm([-np.e**3, -np.e**2, -np.e**1, -1, + 0, 1, np.e**1, np.e**2, np.e**3]) + xx = np.array([0., 0.109123, 0.218246, 0.32737, 0.5, 0.67263, + 0.781754, 0.890877, 1.]) + assert_array_almost_equal(nn, xx) + norm = mcolors.SymLogNorm(1, vmin=-10**3, vmax=10**3, base=10) + nn = norm([-10**3, -10**2, -10**1, -1, + 0, 1, 10**1, 10**2, 10**3]) + xx = np.array([0., 0.121622, 0.243243, 0.364865, 0.5, 0.635135, + 0.756757, 0.878378, 1.]) + assert_array_almost_equal(nn, xx) + + +def test_SymLogNorm_colorbar(): + """ + Test un-called SymLogNorm in a colorbar. + """ + norm = mcolors.SymLogNorm(0.1, vmin=-1, vmax=1, linscale=1, base=np.e) + fig = plt.figure() + mcolorbar.ColorbarBase(fig.add_subplot(), norm=norm) + plt.close(fig) + + +def test_SymLogNorm_single_zero(): + """ + Test SymLogNorm to ensure it is not adding sub-ticks to zero label + """ + fig = plt.figure() + norm = mcolors.SymLogNorm(1e-5, vmin=-1, vmax=1, base=np.e) + cbar = mcolorbar.ColorbarBase(fig.add_subplot(), norm=norm) + ticks = cbar.get_ticks() + assert np.count_nonzero(ticks == 0) <= 1 + plt.close(fig) + + +class TestAsinhNorm: + """ + Tests for `~.colors.AsinhNorm` + """ + + def test_init(self): + norm0 = mcolors.AsinhNorm() + assert norm0.linear_width == 1 + + norm5 = mcolors.AsinhNorm(linear_width=5) + assert norm5.linear_width == 5 + + def test_norm(self): + norm = mcolors.AsinhNorm(2, vmin=-4, vmax=4) + vals = np.arange(-3.5, 3.5, 10) + normed_vals = norm(vals) + asinh2 = np.arcsinh(2) + + expected = (2 * np.arcsinh(vals / 2) + 2 * asinh2) / (4 * asinh2) + assert_array_almost_equal(normed_vals, expected) + + +def _inverse_tester(norm_instance, vals): + """ + Checks if the inverse of the given normalization is working. + """ + assert_array_almost_equal(norm_instance.inverse(norm_instance(vals)), vals) + + +def _scalar_tester(norm_instance, vals): + """ + Checks if scalars and arrays are handled the same way. + Tests only for float. + """ + scalar_result = [norm_instance(float(v)) for v in vals] + assert_array_almost_equal(scalar_result, norm_instance(vals)) + + +def _mask_tester(norm_instance, vals): + """ + Checks mask handling + """ + masked_array = np.ma.array(vals) + masked_array[0] = np.ma.masked + assert_array_equal(masked_array.mask, norm_instance(masked_array).mask) + + +@image_comparison(['levels_and_colors.png']) +def test_cmap_and_norm_from_levels_and_colors(): + # Remove this line when this test image is regenerated. + plt.rcParams['pcolormesh.snap'] = False + + data = np.linspace(-2, 4, 49).reshape(7, 7) + levels = [-1, 2, 2.5, 3] + colors = ['red', 'green', 'blue', 'yellow', 'black'] + extend = 'both' + cmap, norm = mcolors.from_levels_and_colors(levels, colors, extend=extend) + + ax = plt.axes() + m = plt.pcolormesh(data, cmap=cmap, norm=norm) + plt.colorbar(m) + + # Hide the axes labels (but not the colorbar ones, as they are useful) + ax.tick_params(labelleft=False, labelbottom=False) + + +@image_comparison(baseline_images=['boundarynorm_and_colorbar'], + extensions=['png'], tol=1.0) +def test_boundarynorm_and_colorbarbase(): + # Remove this line when this test image is regenerated. + plt.rcParams['pcolormesh.snap'] = False + + # Make a figure and axes with dimensions as desired. + fig = plt.figure() + ax1 = fig.add_axes([0.05, 0.80, 0.9, 0.15]) + ax2 = fig.add_axes([0.05, 0.475, 0.9, 0.15]) + ax3 = fig.add_axes([0.05, 0.15, 0.9, 0.15]) + + # Set the colormap and bounds + bounds = [-1, 2, 5, 7, 12, 15] + cmap = mpl.colormaps['viridis'] + + # Default behavior + norm = mcolors.BoundaryNorm(bounds, cmap.N) + cb1 = mcolorbar.ColorbarBase(ax1, cmap=cmap, norm=norm, extend='both', + orientation='horizontal', spacing='uniform') + # New behavior + norm = mcolors.BoundaryNorm(bounds, cmap.N, extend='both') + cb2 = mcolorbar.ColorbarBase(ax2, cmap=cmap, norm=norm, + orientation='horizontal') + + # User can still force to any extend='' if really needed + norm = mcolors.BoundaryNorm(bounds, cmap.N, extend='both') + cb3 = mcolorbar.ColorbarBase(ax3, cmap=cmap, norm=norm, + extend='neither', orientation='horizontal') + + +def test_cmap_and_norm_from_levels_and_colors2(): + levels = [-1, 2, 2.5, 3] + colors = ['red', (0, 1, 0), 'blue', (0.5, 0.5, 0.5), (0.0, 0.0, 0.0, 1.0)] + clr = mcolors.to_rgba_array(colors) + bad = (0.1, 0.1, 0.1, 0.1) + no_color = (0.0, 0.0, 0.0, 0.0) + masked_value = 'masked_value' + + # Define the test values which are of interest. + # Note: levels are lev[i] <= v < lev[i+1] + tests = [('both', None, {-2: clr[0], + -1: clr[1], + 2: clr[2], + 2.25: clr[2], + 3: clr[4], + 3.5: clr[4], + masked_value: bad}), + + ('min', -1, {-2: clr[0], + -1: clr[1], + 2: clr[2], + 2.25: clr[2], + 3: no_color, + 3.5: no_color, + masked_value: bad}), + + ('max', -1, {-2: no_color, + -1: clr[0], + 2: clr[1], + 2.25: clr[1], + 3: clr[3], + 3.5: clr[3], + masked_value: bad}), + + ('neither', -2, {-2: no_color, + -1: clr[0], + 2: clr[1], + 2.25: clr[1], + 3: no_color, + 3.5: no_color, + masked_value: bad}), + ] + + for extend, i1, cases in tests: + cmap, norm = mcolors.from_levels_and_colors(levels, colors[0:i1], + extend=extend) + cmap.set_bad(bad) + for d_val, expected_color in cases.items(): + if d_val == masked_value: + d_val = np.ma.array([1], mask=True) + else: + d_val = [d_val] + assert_array_equal(expected_color, cmap(norm(d_val))[0], + 'Wih extend={0!r} and data ' + 'value={1!r}'.format(extend, d_val)) + + with pytest.raises(ValueError): + mcolors.from_levels_and_colors(levels, colors) + + +def test_rgb_hsv_round_trip(): + for a_shape in [(500, 500, 3), (500, 3), (1, 3), (3,)]: + np.random.seed(0) + tt = np.random.random(a_shape) + assert_array_almost_equal( + tt, mcolors.hsv_to_rgb(mcolors.rgb_to_hsv(tt))) + assert_array_almost_equal( + tt, mcolors.rgb_to_hsv(mcolors.hsv_to_rgb(tt))) + + +def test_autoscale_masked(): + # Test for #2336. Previously fully masked data would trigger a ValueError. + data = np.ma.masked_all((12, 20)) + plt.pcolor(data) + plt.draw() + + +@image_comparison(['light_source_shading_topo.png']) +def test_light_source_topo_surface(): + """Shades a DEM using different v.e.'s and blend modes.""" + dem = cbook.get_sample_data('jacksboro_fault_dem.npz', np_load=True) + elev = dem['elevation'] + dx, dy = dem['dx'], dem['dy'] + # Get the true cellsize in meters for accurate vertical exaggeration + # Convert from decimal degrees to meters + dx = 111320.0 * dx * np.cos(dem['ymin']) + dy = 111320.0 * dy + + ls = mcolors.LightSource(315, 45) + cmap = cm.gist_earth + + fig, axs = plt.subplots(nrows=3, ncols=3) + for row, mode in zip(axs, ['hsv', 'overlay', 'soft']): + for ax, ve in zip(row, [0.1, 1, 10]): + rgb = ls.shade(elev, cmap, vert_exag=ve, dx=dx, dy=dy, + blend_mode=mode) + ax.imshow(rgb) + ax.set(xticks=[], yticks=[]) + + +def test_light_source_shading_default(): + """ + Array comparison test for the default "hsv" blend mode. Ensure the + default result doesn't change without warning. + """ + y, x = np.mgrid[-1.2:1.2:8j, -1.2:1.2:8j] + z = 10 * np.cos(x**2 + y**2) + + cmap = plt.cm.copper + ls = mcolors.LightSource(315, 45) + rgb = ls.shade(z, cmap) + + # Result stored transposed and rounded for more compact display... + expect = np.array( + [[[0.00, 0.45, 0.90, 0.90, 0.82, 0.62, 0.28, 0.00], + [0.45, 0.94, 0.99, 1.00, 1.00, 0.96, 0.65, 0.17], + [0.90, 0.99, 1.00, 1.00, 1.00, 1.00, 0.94, 0.35], + [0.90, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 0.49], + [0.82, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 0.41], + [0.62, 0.96, 1.00, 1.00, 1.00, 1.00, 0.90, 0.07], + [0.28, 0.65, 0.94, 1.00, 1.00, 0.90, 0.35, 0.01], + [0.00, 0.17, 0.35, 0.49, 0.41, 0.07, 0.01, 0.00]], + + [[0.00, 0.28, 0.59, 0.72, 0.62, 0.40, 0.18, 0.00], + [0.28, 0.78, 0.93, 0.92, 0.83, 0.66, 0.39, 0.11], + [0.59, 0.93, 0.99, 1.00, 0.92, 0.75, 0.50, 0.21], + [0.72, 0.92, 1.00, 0.99, 0.93, 0.76, 0.51, 0.18], + [0.62, 0.83, 0.92, 0.93, 0.87, 0.68, 0.42, 0.08], + [0.40, 0.66, 0.75, 0.76, 0.68, 0.52, 0.23, 0.02], + [0.18, 0.39, 0.50, 0.51, 0.42, 0.23, 0.00, 0.00], + [0.00, 0.11, 0.21, 0.18, 0.08, 0.02, 0.00, 0.00]], + + [[0.00, 0.18, 0.38, 0.46, 0.39, 0.26, 0.11, 0.00], + [0.18, 0.50, 0.70, 0.75, 0.64, 0.44, 0.25, 0.07], + [0.38, 0.70, 0.91, 0.98, 0.81, 0.51, 0.29, 0.13], + [0.46, 0.75, 0.98, 0.96, 0.84, 0.48, 0.22, 0.12], + [0.39, 0.64, 0.81, 0.84, 0.71, 0.31, 0.11, 0.05], + [0.26, 0.44, 0.51, 0.48, 0.31, 0.10, 0.03, 0.01], + [0.11, 0.25, 0.29, 0.22, 0.11, 0.03, 0.00, 0.00], + [0.00, 0.07, 0.13, 0.12, 0.05, 0.01, 0.00, 0.00]], + + [[1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00], + [1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00], + [1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00], + [1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00], + [1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00], + [1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00], + [1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00], + [1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00]] + ]).T + + assert_array_almost_equal(rgb, expect, decimal=2) + + +def test_light_source_shading_empty_mask(): + y, x = np.mgrid[-1.2:1.2:8j, -1.2:1.2:8j] + z0 = 10 * np.cos(x**2 + y**2) + z1 = np.ma.array(z0) + + cmap = plt.cm.copper + ls = mcolors.LightSource(315, 45) + rgb0 = ls.shade(z0, cmap) + rgb1 = ls.shade(z1, cmap) + + assert_array_almost_equal(rgb0, rgb1) + + +# Numpy 1.9.1 fixed a bug in masked arrays which resulted in +# additional elements being masked when calculating the gradient thus +# the output is different with earlier numpy versions. +def test_light_source_masked_shading(): + """ + Array comparison test for a surface with a masked portion. Ensures that + we don't wind up with "fringes" of odd colors around masked regions. + """ + y, x = np.mgrid[-1.2:1.2:8j, -1.2:1.2:8j] + z = 10 * np.cos(x**2 + y**2) + + z = np.ma.masked_greater(z, 9.9) + + cmap = plt.cm.copper + ls = mcolors.LightSource(315, 45) + rgb = ls.shade(z, cmap) + + # Result stored transposed and rounded for more compact display... + expect = np.array( + [[[0.00, 0.46, 0.91, 0.91, 0.84, 0.64, 0.29, 0.00], + [0.46, 0.96, 1.00, 1.00, 1.00, 0.97, 0.67, 0.18], + [0.91, 1.00, 1.00, 1.00, 1.00, 1.00, 0.96, 0.36], + [0.91, 1.00, 1.00, 0.00, 0.00, 1.00, 1.00, 0.51], + [0.84, 1.00, 1.00, 0.00, 0.00, 1.00, 1.00, 0.44], + [0.64, 0.97, 1.00, 1.00, 1.00, 1.00, 0.94, 0.09], + [0.29, 0.67, 0.96, 1.00, 1.00, 0.94, 0.38, 0.01], + [0.00, 0.18, 0.36, 0.51, 0.44, 0.09, 0.01, 0.00]], + + [[0.00, 0.29, 0.61, 0.75, 0.64, 0.41, 0.18, 0.00], + [0.29, 0.81, 0.95, 0.93, 0.85, 0.68, 0.40, 0.11], + [0.61, 0.95, 1.00, 0.78, 0.78, 0.77, 0.52, 0.22], + [0.75, 0.93, 0.78, 0.00, 0.00, 0.78, 0.54, 0.19], + [0.64, 0.85, 0.78, 0.00, 0.00, 0.78, 0.45, 0.08], + [0.41, 0.68, 0.77, 0.78, 0.78, 0.55, 0.25, 0.02], + [0.18, 0.40, 0.52, 0.54, 0.45, 0.25, 0.00, 0.00], + [0.00, 0.11, 0.22, 0.19, 0.08, 0.02, 0.00, 0.00]], + + [[0.00, 0.19, 0.39, 0.48, 0.41, 0.26, 0.12, 0.00], + [0.19, 0.52, 0.73, 0.78, 0.66, 0.46, 0.26, 0.07], + [0.39, 0.73, 0.95, 0.50, 0.50, 0.53, 0.30, 0.14], + [0.48, 0.78, 0.50, 0.00, 0.00, 0.50, 0.23, 0.12], + [0.41, 0.66, 0.50, 0.00, 0.00, 0.50, 0.11, 0.05], + [0.26, 0.46, 0.53, 0.50, 0.50, 0.11, 0.03, 0.01], + [0.12, 0.26, 0.30, 0.23, 0.11, 0.03, 0.00, 0.00], + [0.00, 0.07, 0.14, 0.12, 0.05, 0.01, 0.00, 0.00]], + + [[1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00], + [1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00], + [1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00], + [1.00, 1.00, 1.00, 0.00, 0.00, 1.00, 1.00, 1.00], + [1.00, 1.00, 1.00, 0.00, 0.00, 1.00, 1.00, 1.00], + [1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00], + [1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00], + [1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00]], + ]).T + + assert_array_almost_equal(rgb, expect, decimal=2) + + +def test_light_source_hillshading(): + """ + Compare the current hillshading method against one that should be + mathematically equivalent. Illuminates a cone from a range of angles. + """ + + def alternative_hillshade(azimuth, elev, z): + illum = _sph2cart(*_azimuth2math(azimuth, elev)) + illum = np.array(illum) + + dy, dx = np.gradient(-z) + dy = -dy + dz = np.ones_like(dy) + normals = np.dstack([dx, dy, dz]) + normals /= np.linalg.norm(normals, axis=2)[..., None] + + intensity = np.tensordot(normals, illum, axes=(2, 0)) + intensity -= intensity.min() + intensity /= intensity.ptp() + return intensity + + y, x = np.mgrid[5:0:-1, :5] + z = -np.hypot(x - x.mean(), y - y.mean()) + + for az, elev in itertools.product(range(0, 390, 30), range(0, 105, 15)): + ls = mcolors.LightSource(az, elev) + h1 = ls.hillshade(z) + h2 = alternative_hillshade(az, elev, z) + assert_array_almost_equal(h1, h2) + + +def test_light_source_planar_hillshading(): + """ + Ensure that the illumination intensity is correct for planar surfaces. + """ + + def plane(azimuth, elevation, x, y): + """ + Create a plane whose normal vector is at the given azimuth and + elevation. + """ + theta, phi = _azimuth2math(azimuth, elevation) + a, b, c = _sph2cart(theta, phi) + z = -(a*x + b*y) / c + return z + + def angled_plane(azimuth, elevation, angle, x, y): + """ + Create a plane whose normal vector is at an angle from the given + azimuth and elevation. + """ + elevation = elevation + angle + if elevation > 90: + azimuth = (azimuth + 180) % 360 + elevation = (90 - elevation) % 90 + return plane(azimuth, elevation, x, y) + + y, x = np.mgrid[5:0:-1, :5] + for az, elev in itertools.product(range(0, 390, 30), range(0, 105, 15)): + ls = mcolors.LightSource(az, elev) + + # Make a plane at a range of angles to the illumination + for angle in range(0, 105, 15): + z = angled_plane(az, elev, angle, x, y) + h = ls.hillshade(z) + assert_array_almost_equal(h, np.cos(np.radians(angle))) + + +def test_color_names(): + assert mcolors.to_hex("blue") == "#0000ff" + assert mcolors.to_hex("xkcd:blue") == "#0343df" + assert mcolors.to_hex("tab:blue") == "#1f77b4" + + +def _sph2cart(theta, phi): + x = np.cos(theta) * np.sin(phi) + y = np.sin(theta) * np.sin(phi) + z = np.cos(phi) + return x, y, z + + +def _azimuth2math(azimuth, elevation): + """ + Convert from clockwise-from-north and up-from-horizontal to mathematical + conventions. + """ + theta = np.radians((90 - azimuth) % 360) + phi = np.radians(90 - elevation) + return theta, phi + + +def test_pandas_iterable(pd): + # Using a list or series yields equivalent + # colormaps, i.e the series isn't seen as + # a single color + lst = ['red', 'blue', 'green'] + s = pd.Series(lst) + cm1 = mcolors.ListedColormap(lst, N=5) + cm2 = mcolors.ListedColormap(s, N=5) + assert_array_equal(cm1.colors, cm2.colors) + + +@pytest.mark.parametrize('name', sorted(mpl.colormaps())) +def test_colormap_reversing(name): + """ + Check the generated _lut data of a colormap and corresponding reversed + colormap if they are almost the same. + """ + cmap = mpl.colormaps[name] + cmap_r = cmap.reversed() + if not cmap_r._isinit: + cmap._init() + cmap_r._init() + assert_array_almost_equal(cmap._lut[:-3], cmap_r._lut[-4::-1]) + # Test the bad, over, under values too + assert_array_almost_equal(cmap(-np.inf), cmap_r(np.inf)) + assert_array_almost_equal(cmap(np.inf), cmap_r(-np.inf)) + assert_array_almost_equal(cmap(np.nan), cmap_r(np.nan)) + + +def test_has_alpha_channel(): + assert mcolors._has_alpha_channel((0, 0, 0, 0)) + assert mcolors._has_alpha_channel([1, 1, 1, 1]) + assert not mcolors._has_alpha_channel('blue') # 4-char string! + assert not mcolors._has_alpha_channel('0.25') + assert not mcolors._has_alpha_channel('r') + assert not mcolors._has_alpha_channel((1, 0, 0)) + + +def test_cn(): + matplotlib.rcParams['axes.prop_cycle'] = cycler('color', + ['blue', 'r']) + assert mcolors.to_hex("C0") == '#0000ff' + assert mcolors.to_hex("C1") == '#ff0000' + + matplotlib.rcParams['axes.prop_cycle'] = cycler('color', + ['xkcd:blue', 'r']) + assert mcolors.to_hex("C0") == '#0343df' + assert mcolors.to_hex("C1") == '#ff0000' + assert mcolors.to_hex("C10") == '#0343df' + assert mcolors.to_hex("C11") == '#ff0000' + + matplotlib.rcParams['axes.prop_cycle'] = cycler('color', ['8e4585', 'r']) + + assert mcolors.to_hex("C0") == '#8e4585' + # if '8e4585' gets parsed as a float before it gets detected as a hex + # colour it will be interpreted as a very large number. + # this mustn't happen. + assert mcolors.to_rgb("C0")[0] != np.inf + + +def test_conversions(): + # to_rgba_array("none") returns a (0, 4) array. + assert_array_equal(mcolors.to_rgba_array("none"), np.zeros((0, 4))) + assert_array_equal(mcolors.to_rgba_array([]), np.zeros((0, 4))) + # a list of grayscale levels, not a single color. + assert_array_equal( + mcolors.to_rgba_array([".2", ".5", ".8"]), + np.vstack([mcolors.to_rgba(c) for c in [".2", ".5", ".8"]])) + # alpha is properly set. + assert mcolors.to_rgba((1, 1, 1), .5) == (1, 1, 1, .5) + assert mcolors.to_rgba(".1", .5) == (.1, .1, .1, .5) + # builtin round differs between py2 and py3. + assert mcolors.to_hex((.7, .7, .7)) == "#b2b2b2" + # hex roundtrip. + hex_color = "#1234abcd" + assert mcolors.to_hex(mcolors.to_rgba(hex_color), keep_alpha=True) == \ + hex_color + + +def test_conversions_masked(): + x1 = np.ma.array(['k', 'b'], mask=[True, False]) + x2 = np.ma.array([[0, 0, 0, 1], [0, 0, 1, 1]]) + x2[0] = np.ma.masked + assert mcolors.to_rgba(x1[0]) == (0, 0, 0, 0) + assert_array_equal(mcolors.to_rgba_array(x1), + [[0, 0, 0, 0], [0, 0, 1, 1]]) + assert_array_equal(mcolors.to_rgba_array(x2), mcolors.to_rgba_array(x1)) + + +def test_to_rgba_array_single_str(): + # single color name is valid + assert_array_equal(mcolors.to_rgba_array("red"), [(1, 0, 0, 1)]) + + # single char color sequence is invalid + with pytest.raises(ValueError, + match="'rgb' is not a valid color value."): + array = mcolors.to_rgba_array("rgb") + + +def test_to_rgba_array_alpha_array(): + with pytest.raises(ValueError, match="The number of colors must match"): + mcolors.to_rgba_array(np.ones((5, 3), float), alpha=np.ones((2,))) + alpha = [0.5, 0.6] + c = mcolors.to_rgba_array(np.ones((2, 3), float), alpha=alpha) + assert_array_equal(c[:, 3], alpha) + c = mcolors.to_rgba_array(['r', 'g'], alpha=alpha) + assert_array_equal(c[:, 3], alpha) + + +def test_failed_conversions(): + with pytest.raises(ValueError): + mcolors.to_rgba('5') + with pytest.raises(ValueError): + mcolors.to_rgba('-1') + with pytest.raises(ValueError): + mcolors.to_rgba('nan') + with pytest.raises(ValueError): + mcolors.to_rgba('unknown_color') + with pytest.raises(ValueError): + # Gray must be a string to distinguish 3-4 grays from RGB or RGBA. + mcolors.to_rgba(0.4) + + +def test_grey_gray(): + color_mapping = mcolors._colors_full_map + for k in color_mapping.keys(): + if 'grey' in k: + assert color_mapping[k] == color_mapping[k.replace('grey', 'gray')] + if 'gray' in k: + assert color_mapping[k] == color_mapping[k.replace('gray', 'grey')] + + +def test_tableau_order(): + dflt_cycle = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', + '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', + '#bcbd22', '#17becf'] + + assert list(mcolors.TABLEAU_COLORS.values()) == dflt_cycle + + +def test_ndarray_subclass_norm(): + # Emulate an ndarray subclass that handles units + # which objects when adding or subtracting with other + # arrays. See #6622 and #8696 + class MyArray(np.ndarray): + def __isub__(self, other): + raise RuntimeError + + def __add__(self, other): + raise RuntimeError + + data = np.arange(-10, 10, 1, dtype=float).reshape((10, 2)) + mydata = data.view(MyArray) + + for norm in [mcolors.Normalize(), mcolors.LogNorm(), + mcolors.SymLogNorm(3, vmax=5, linscale=1, base=np.e), + mcolors.Normalize(vmin=mydata.min(), vmax=mydata.max()), + mcolors.SymLogNorm(3, vmin=mydata.min(), vmax=mydata.max(), + base=np.e), + mcolors.PowerNorm(1)]: + assert_array_equal(norm(mydata), norm(data)) + fig, ax = plt.subplots() + ax.imshow(mydata, norm=norm) + fig.canvas.draw() # Check that no warning is emitted. + + +def test_same_color(): + assert mcolors.same_color('k', (0, 0, 0)) + assert not mcolors.same_color('w', (1, 1, 0)) + assert mcolors.same_color(['red', 'blue'], ['r', 'b']) + assert mcolors.same_color('none', 'none') + assert not mcolors.same_color('none', 'red') + with pytest.raises(ValueError): + mcolors.same_color(['r', 'g', 'b'], ['r']) + with pytest.raises(ValueError): + mcolors.same_color(['red', 'green'], 'none') + + +def test_hex_shorthand_notation(): + assert mcolors.same_color("#123", "#112233") + assert mcolors.same_color("#123a", "#112233aa") + + +def test_repr_png(): + cmap = mpl.colormaps['viridis'] + png = cmap._repr_png_() + assert len(png) > 0 + img = Image.open(BytesIO(png)) + assert img.width > 0 + assert img.height > 0 + assert 'Title' in img.text + assert 'Description' in img.text + assert 'Author' in img.text + assert 'Software' in img.text + + +def test_repr_html(): + cmap = mpl.colormaps['viridis'] + html = cmap._repr_html_() + assert len(html) > 0 + png = cmap._repr_png_() + assert base64.b64encode(png).decode('ascii') in html + assert cmap.name in html + assert html.startswith('') + + +def test_get_under_over_bad(): + cmap = mpl.colormaps['viridis'] + assert_array_equal(cmap.get_under(), cmap(-np.inf)) + assert_array_equal(cmap.get_over(), cmap(np.inf)) + assert_array_equal(cmap.get_bad(), cmap(np.nan)) + + +@pytest.mark.parametrize('kind', ('over', 'under', 'bad')) +def test_non_mutable_get_values(kind): + cmap = copy.copy(mpl.colormaps['viridis']) + init_value = getattr(cmap, f'get_{kind}')() + getattr(cmap, f'set_{kind}')('k') + black_value = getattr(cmap, f'get_{kind}')() + assert np.all(black_value == [0, 0, 0, 1]) + assert not np.all(init_value == black_value) + + +def test_colormap_alpha_array(): + cmap = mpl.colormaps['viridis'] + vals = [-1, 0.5, 2] # under, valid, over + with pytest.raises(ValueError, match="alpha is array-like but"): + cmap(vals, alpha=[1, 1, 1, 1]) + alpha = np.array([0.1, 0.2, 0.3]) + c = cmap(vals, alpha=alpha) + assert_array_equal(c[:, -1], alpha) + c = cmap(vals, alpha=alpha, bytes=True) + assert_array_equal(c[:, -1], (alpha * 255).astype(np.uint8)) + + +def test_colormap_bad_data_with_alpha(): + cmap = mpl.colormaps['viridis'] + c = cmap(np.nan, alpha=0.5) + assert c == (0, 0, 0, 0) + c = cmap([0.5, np.nan], alpha=0.5) + assert_array_equal(c[1], (0, 0, 0, 0)) + c = cmap([0.5, np.nan], alpha=[0.1, 0.2]) + assert_array_equal(c[1], (0, 0, 0, 0)) + c = cmap([[np.nan, 0.5], [0, 0]], alpha=0.5) + assert_array_equal(c[0, 0], (0, 0, 0, 0)) + c = cmap([[np.nan, 0.5], [0, 0]], alpha=np.full((2, 2), 0.5)) + assert_array_equal(c[0, 0], (0, 0, 0, 0)) + + +def test_2d_to_rgba(): + color = np.array([0.1, 0.2, 0.3]) + rgba_1d = mcolors.to_rgba(color.reshape(-1)) + rgba_2d = mcolors.to_rgba(color.reshape((1, -1))) + assert rgba_1d == rgba_2d + + +def test_set_dict_to_rgba(): + # downstream libraries do this... + # note we can't test this because it is not well-ordered + # so just smoketest: + colors = set([(0, .5, 1), (1, .2, .5), (.4, 1, .2)]) + res = mcolors.to_rgba_array(colors) + palette = {"red": (1, 0, 0), "green": (0, 1, 0), "blue": (0, 0, 1)} + res = mcolors.to_rgba_array(palette.values()) + exp = np.eye(3) + np.testing.assert_array_almost_equal(res[:, :-1], exp) + + +def test_norm_deepcopy(): + norm = mcolors.LogNorm() + norm.vmin = 0.0002 + norm2 = copy.deepcopy(norm) + assert norm2.vmin == norm.vmin + assert isinstance(norm2._scale, mscale.LogScale) + norm = mcolors.Normalize() + norm.vmin = 0.0002 + norm2 = copy.deepcopy(norm) + assert norm2._scale is None + assert norm2.vmin == norm.vmin + + +def test_norm_callback(): + increment = unittest.mock.Mock(return_value=None) + + norm = mcolors.Normalize() + norm.callbacks.connect('changed', increment) + # Haven't updated anything, so call count should be 0 + assert increment.call_count == 0 + + # Now change vmin and vmax to test callbacks + norm.vmin = 1 + assert increment.call_count == 1 + norm.vmax = 5 + assert increment.call_count == 2 + # callback shouldn't be called if setting to the same value + norm.vmin = 1 + assert increment.call_count == 2 + norm.vmax = 5 + assert increment.call_count == 2 + + # We only want autoscale() calls to send out one update signal + increment.call_count = 0 + norm.autoscale([0, 1, 2]) + assert increment.call_count == 1 + + +def test_scalarmappable_norm_update(): + norm = mcolors.Normalize() + sm = matplotlib.cm.ScalarMappable(norm=norm, cmap='plasma') + # sm doesn't have a stale attribute at first, set it to False + sm.stale = False + # The mappable should be stale after updating vmin/vmax + norm.vmin = 5 + assert sm.stale + sm.stale = False + norm.vmax = 5 + assert sm.stale + sm.stale = False + norm.clip = True + assert sm.stale + # change to the CenteredNorm and TwoSlopeNorm to test those + # Also make sure that updating the norm directly and with + # set_norm both update the Norm callback + norm = mcolors.CenteredNorm() + sm.norm = norm + sm.stale = False + norm.vcenter = 1 + assert sm.stale + norm = mcolors.TwoSlopeNorm(vcenter=0, vmin=-1, vmax=1) + sm.set_norm(norm) + sm.stale = False + norm.vcenter = 1 + assert sm.stale + + +@check_figures_equal() +def test_norm_update_figs(fig_test, fig_ref): + ax_ref = fig_ref.add_subplot() + ax_test = fig_test.add_subplot() + + z = np.arange(100).reshape((10, 10)) + ax_ref.imshow(z, norm=mcolors.Normalize(10, 90)) + + # Create the norm beforehand with different limits and then update + # after adding to the plot + norm = mcolors.Normalize(0, 1) + ax_test.imshow(z, norm=norm) + # Force initial draw to make sure it isn't already stale + fig_test.canvas.draw() + norm.vmin, norm.vmax = 10, 90 + + +def test_make_norm_from_scale_name(): + logitnorm = mcolors.make_norm_from_scale( + mscale.LogitScale, mcolors.Normalize) + assert logitnorm.__name__ == logitnorm.__qualname__ == "LogitScaleNorm" + + +def test_color_sequences(): + # basic access + assert plt.color_sequences is matplotlib.color_sequences # same registry + assert list(plt.color_sequences) == [ + 'tab10', 'tab20', 'tab20b', 'tab20c', 'Pastel1', 'Pastel2', 'Paired', + 'Accent', 'Dark2', 'Set1', 'Set2', 'Set3'] + assert len(plt.color_sequences['tab10']) == 10 + assert len(plt.color_sequences['tab20']) == 20 + + tab_colors = [ + 'tab:blue', 'tab:orange', 'tab:green', 'tab:red', 'tab:purple', + 'tab:brown', 'tab:pink', 'tab:gray', 'tab:olive', 'tab:cyan'] + for seq_color, tab_color in zip(plt.color_sequences['tab10'], tab_colors): + assert mcolors.same_color(seq_color, tab_color) + + # registering + with pytest.raises(ValueError, match="reserved name"): + plt.color_sequences.register('tab10', ['r', 'g', 'b']) + with pytest.raises(ValueError, match="not a valid color specification"): + plt.color_sequences.register('invalid', ['not a color']) + + rgb_colors = ['r', 'g', 'b'] + plt.color_sequences.register('rgb', rgb_colors) + assert plt.color_sequences['rgb'] == ['r', 'g', 'b'] + # should not affect the registered sequence because input is copied + rgb_colors.append('c') + assert plt.color_sequences['rgb'] == ['r', 'g', 'b'] + # should not affect the registered sequence because returned list is a copy + plt.color_sequences['rgb'].append('c') + assert plt.color_sequences['rgb'] == ['r', 'g', 'b'] + + # unregister + plt.color_sequences.unregister('rgb') + with pytest.raises(KeyError): + plt.color_sequences['rgb'] # rgb is gone + plt.color_sequences.unregister('rgb') # multiple unregisters are ok + with pytest.raises(ValueError, match="Cannot unregister builtin"): + plt.color_sequences.unregister('tab10') + + +def test_cm_set_cmap_error(): + sm = cm.ScalarMappable() + # Pick a name we are pretty sure will never be a colormap name + bad_cmap = 'AardvarksAreAwkward' + with pytest.raises(ValueError, match=bad_cmap): + sm.set_cmap(bad_cmap) diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/test_cycles.py b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/test_cycles.py new file mode 100644 index 0000000000000000000000000000000000000000..2cf086ba345a81f4003570bfbc6ac1353f50c8ea --- /dev/null +++ b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/test_cycles.py @@ -0,0 +1,160 @@ +import matplotlib as mpl +import matplotlib.pyplot as plt +import numpy as np +import pytest + +from cycler import cycler + + +def test_colorcycle_basic(): + fig, ax = plt.subplots() + ax.set_prop_cycle(cycler('color', ['r', 'g', 'y'])) + for _ in range(4): + ax.plot(range(10), range(10)) + assert [l.get_color() for l in ax.lines] == ['r', 'g', 'y', 'r'] + + +def test_marker_cycle(): + fig, ax = plt.subplots() + ax.set_prop_cycle(cycler('c', ['r', 'g', 'y']) + + cycler('marker', ['.', '*', 'x'])) + for _ in range(4): + ax.plot(range(10), range(10)) + assert [l.get_color() for l in ax.lines] == ['r', 'g', 'y', 'r'] + assert [l.get_marker() for l in ax.lines] == ['.', '*', 'x', '.'] + + +def test_marker_cycle_kwargs_arrays_iterators(): + fig, ax = plt.subplots() + ax.set_prop_cycle(c=np.array(['r', 'g', 'y']), + marker=iter(['.', '*', 'x'])) + for _ in range(4): + ax.plot(range(10), range(10)) + assert [l.get_color() for l in ax.lines] == ['r', 'g', 'y', 'r'] + assert [l.get_marker() for l in ax.lines] == ['.', '*', 'x', '.'] + + +def test_linestylecycle_basic(): + fig, ax = plt.subplots() + ax.set_prop_cycle(cycler('ls', ['-', '--', ':'])) + for _ in range(4): + ax.plot(range(10), range(10)) + assert [l.get_linestyle() for l in ax.lines] == ['-', '--', ':', '-'] + + +def test_fillcycle_basic(): + fig, ax = plt.subplots() + ax.set_prop_cycle(cycler('c', ['r', 'g', 'y']) + + cycler('hatch', ['xx', 'O', '|-']) + + cycler('linestyle', ['-', '--', ':'])) + for _ in range(4): + ax.fill(range(10), range(10)) + assert ([p.get_facecolor() for p in ax.patches] + == [mpl.colors.to_rgba(c) for c in ['r', 'g', 'y', 'r']]) + assert [p.get_hatch() for p in ax.patches] == ['xx', 'O', '|-', 'xx'] + assert [p.get_linestyle() for p in ax.patches] == ['-', '--', ':', '-'] + + +def test_fillcycle_ignore(): + fig, ax = plt.subplots() + ax.set_prop_cycle(cycler('color', ['r', 'g', 'y']) + + cycler('hatch', ['xx', 'O', '|-']) + + cycler('marker', ['.', '*', 'D'])) + t = range(10) + # Should not advance the cycler, even though there is an + # unspecified property in the cycler "marker". + # "marker" is not a Polygon property, and should be ignored. + ax.fill(t, t, 'r', hatch='xx') + # Allow the cycler to advance, but specify some properties + ax.fill(t, t, hatch='O') + ax.fill(t, t) + ax.fill(t, t) + assert ([p.get_facecolor() for p in ax.patches] + == [mpl.colors.to_rgba(c) for c in ['r', 'r', 'g', 'y']]) + assert [p.get_hatch() for p in ax.patches] == ['xx', 'O', 'O', '|-'] + + +def test_property_collision_plot(): + fig, ax = plt.subplots() + ax.set_prop_cycle('linewidth', [2, 4]) + t = range(10) + for c in range(1, 4): + ax.plot(t, t, lw=0.1) + ax.plot(t, t) + ax.plot(t, t) + assert [l.get_linewidth() for l in ax.lines] == [0.1, 0.1, 0.1, 2, 4] + + +def test_property_collision_fill(): + fig, ax = plt.subplots() + ax.set_prop_cycle(linewidth=[2, 3, 4, 5, 6], facecolor='bgcmy') + t = range(10) + for c in range(1, 4): + ax.fill(t, t, lw=0.1) + ax.fill(t, t) + ax.fill(t, t) + assert ([p.get_facecolor() for p in ax.patches] + == [mpl.colors.to_rgba(c) for c in 'bgcmy']) + assert [p.get_linewidth() for p in ax.patches] == [0.1, 0.1, 0.1, 5, 6] + + +def test_valid_input_forms(): + fig, ax = plt.subplots() + # These should not raise an error. + ax.set_prop_cycle(None) + ax.set_prop_cycle(cycler('linewidth', [1, 2])) + ax.set_prop_cycle('color', 'rgywkbcm') + ax.set_prop_cycle('lw', (1, 2)) + ax.set_prop_cycle('linewidth', [1, 2]) + ax.set_prop_cycle('linewidth', iter([1, 2])) + ax.set_prop_cycle('linewidth', np.array([1, 2])) + ax.set_prop_cycle('color', np.array([[1, 0, 0], + [0, 1, 0], + [0, 0, 1]])) + ax.set_prop_cycle('dashes', [[], [13, 2], [8, 3, 1, 3]]) + ax.set_prop_cycle(lw=[1, 2], color=['k', 'w'], ls=['-', '--']) + ax.set_prop_cycle(lw=np.array([1, 2]), + color=np.array(['k', 'w']), + ls=np.array(['-', '--'])) + + +def test_cycle_reset(): + fig, ax = plt.subplots() + + # Can't really test a reset because only a cycle object is stored + # but we can test the first item of the cycle. + prop = next(ax._get_lines.prop_cycler) + ax.set_prop_cycle(linewidth=[10, 9, 4]) + assert prop != next(ax._get_lines.prop_cycler) + ax.set_prop_cycle(None) + got = next(ax._get_lines.prop_cycler) + assert prop == got + + +def test_invalid_input_forms(): + fig, ax = plt.subplots() + + with pytest.raises((TypeError, ValueError)): + ax.set_prop_cycle(1) + with pytest.raises((TypeError, ValueError)): + ax.set_prop_cycle([1, 2]) + + with pytest.raises((TypeError, ValueError)): + ax.set_prop_cycle('color', 'fish') + + with pytest.raises((TypeError, ValueError)): + ax.set_prop_cycle('linewidth', 1) + with pytest.raises((TypeError, ValueError)): + ax.set_prop_cycle('linewidth', {1, 2}) + with pytest.raises((TypeError, ValueError)): + ax.set_prop_cycle(linewidth=1, color='r') + + with pytest.raises((TypeError, ValueError)): + ax.set_prop_cycle('foobar', [1, 2]) + with pytest.raises((TypeError, ValueError)): + ax.set_prop_cycle(foobar=[1, 2]) + + with pytest.raises((TypeError, ValueError)): + ax.set_prop_cycle(cycler(foobar=[1, 2])) + with pytest.raises(ValueError): + ax.set_prop_cycle(cycler(color='rgb', c='cmy')) diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/test_dviread.py b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/test_dviread.py new file mode 100644 index 0000000000000000000000000000000000000000..7e10975f44d5c868acf6a65b46a1c15c4a43f503 --- /dev/null +++ b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/test_dviread.py @@ -0,0 +1,77 @@ +import json +from pathlib import Path +import shutil + +import matplotlib.dviread as dr +import pytest + + +def test_PsfontsMap(monkeypatch): + monkeypatch.setattr(dr, '_find_tex_file', lambda x: x) + + filename = str(Path(__file__).parent / 'baseline_images/dviread/test.map') + fontmap = dr.PsfontsMap(filename) + # Check all properties of a few fonts + for n in [1, 2, 3, 4, 5]: + key = b'TeXfont%d' % n + entry = fontmap[key] + assert entry.texname == key + assert entry.psname == b'PSfont%d' % n + if n not in [3, 5]: + assert entry.encoding == b'font%d.enc' % n + elif n == 3: + assert entry.encoding == b'enc3.foo' + # We don't care about the encoding of TeXfont5, which specifies + # multiple encodings. + if n not in [1, 5]: + assert entry.filename == b'font%d.pfa' % n + else: + assert entry.filename == b'font%d.pfb' % n + if n == 4: + assert entry.effects == {'slant': -0.1, 'extend': 1.2} + else: + assert entry.effects == {} + # Some special cases + entry = fontmap[b'TeXfont6'] + assert entry.filename is None + assert entry.encoding is None + entry = fontmap[b'TeXfont7'] + assert entry.filename is None + assert entry.encoding == b'font7.enc' + entry = fontmap[b'TeXfont8'] + assert entry.filename == b'font8.pfb' + assert entry.encoding is None + entry = fontmap[b'TeXfont9'] + assert entry.psname == b'TeXfont9' + assert entry.filename == b'/absolute/font9.pfb' + # First of duplicates only. + entry = fontmap[b'TeXfontA'] + assert entry.psname == b'PSfontA1' + # Slant/Extend only works for T1 fonts. + entry = fontmap[b'TeXfontB'] + assert entry.psname == b'PSfontB6' + # Subsetted TrueType must have encoding. + entry = fontmap[b'TeXfontC'] + assert entry.psname == b'PSfontC3' + # Missing font + with pytest.raises(LookupError, match='no-such-font'): + fontmap[b'no-such-font'] + with pytest.raises(LookupError, match='%'): + fontmap[b'%'] + + +@pytest.mark.skipif(shutil.which("kpsewhich") is None, + reason="kpsewhich is not available") +def test_dviread(): + dirpath = Path(__file__).parent / 'baseline_images/dviread' + with (dirpath / 'test.json').open() as f: + correct = json.load(f) + with dr.Dvi(str(dirpath / 'test.dvi'), None) as dvi: + data = [{'text': [[t.x, t.y, + chr(t.glyph), + t.font.texname.decode('ascii'), + round(t.font.size, 2)] + for t in page.text], + 'boxes': [[b.x, b.y, b.height, b.width] for b in page.boxes]} + for page in dvi] + assert data == correct diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/test_lines.py b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/test_lines.py new file mode 100644 index 0000000000000000000000000000000000000000..5d31172a96f1dc5aa934a366df146a5bcea5eb9f --- /dev/null +++ b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/test_lines.py @@ -0,0 +1,410 @@ +""" +Tests specific to the lines module. +""" + +import itertools +import platform +import timeit +from types import SimpleNamespace + +from cycler import cycler +import numpy as np +from numpy.testing import assert_array_equal +import pytest + +import matplotlib +import matplotlib as mpl +from matplotlib import _path +import matplotlib.lines as mlines +from matplotlib.markers import MarkerStyle +from matplotlib.path import Path +import matplotlib.pyplot as plt +import matplotlib.transforms as mtransforms +from matplotlib.testing.decorators import image_comparison, check_figures_equal +from matplotlib._api.deprecation import MatplotlibDeprecationWarning + + +def test_segment_hits(): + """Test a problematic case.""" + cx, cy = 553, 902 + x, y = np.array([553., 553.]), np.array([95., 947.]) + radius = 6.94 + assert_array_equal(mlines.segment_hits(cx, cy, x, y, radius), [0]) + + +# Runtimes on a loaded system are inherently flaky. Not so much that a rerun +# won't help, hopefully. +@pytest.mark.flaky(reruns=3) +def test_invisible_Line_rendering(): + """ + GitHub issue #1256 identified a bug in Line.draw method + + Despite visibility attribute set to False, the draw method was not + returning early enough and some pre-rendering code was executed + though not necessary. + + Consequence was an excessive draw time for invisible Line instances + holding a large number of points (Npts> 10**6) + """ + # Creates big x and y data: + N = 10**7 + x = np.linspace(0, 1, N) + y = np.random.normal(size=N) + + # Create a plot figure: + fig = plt.figure() + ax = plt.subplot() + + # Create a "big" Line instance: + l = mlines.Line2D(x, y) + l.set_visible(False) + # but don't add it to the Axis instance `ax` + + # [here Interactive panning and zooming is pretty responsive] + # Time the canvas drawing: + t_no_line = min(timeit.repeat(fig.canvas.draw, number=1, repeat=3)) + # (gives about 25 ms) + + # Add the big invisible Line: + ax.add_line(l) + + # [Now interactive panning and zooming is very slow] + # Time the canvas drawing: + t_invisible_line = min(timeit.repeat(fig.canvas.draw, number=1, repeat=3)) + # gives about 290 ms for N = 10**7 pts + + slowdown_factor = t_invisible_line / t_no_line + slowdown_threshold = 2 # trying to avoid false positive failures + assert slowdown_factor < slowdown_threshold + + +def test_set_line_coll_dash(): + fig, ax = plt.subplots() + np.random.seed(0) + # Testing setting linestyles for line collections. + # This should not produce an error. + ax.contour(np.random.randn(20, 30), linestyles=[(0, (3, 3))]) + + +def test_invalid_line_data(): + with pytest.raises(RuntimeError, match='xdata must be'): + mlines.Line2D(0, []) + with pytest.raises(RuntimeError, match='ydata must be'): + mlines.Line2D([], 1) + + line = mlines.Line2D([], []) + # when deprecation cycle is completed + # with pytest.raises(RuntimeError, match='x must be'): + with pytest.warns(MatplotlibDeprecationWarning): + line.set_xdata(0) + # with pytest.raises(RuntimeError, match='y must be'): + with pytest.warns(MatplotlibDeprecationWarning): + line.set_ydata(0) + + +@image_comparison(['line_dashes'], remove_text=True) +def test_line_dashes(): + fig, ax = plt.subplots() + + ax.plot(range(10), linestyle=(0, (3, 3)), lw=5) + + +def test_line_colors(): + fig, ax = plt.subplots() + ax.plot(range(10), color='none') + ax.plot(range(10), color='r') + ax.plot(range(10), color='.3') + ax.plot(range(10), color=(1, 0, 0, 1)) + ax.plot(range(10), color=(1, 0, 0)) + fig.canvas.draw() + + +def test_valid_colors(): + line = mlines.Line2D([], []) + with pytest.raises(ValueError): + line.set_color("foobar") + + +def test_linestyle_variants(): + fig, ax = plt.subplots() + for ls in ["-", "solid", "--", "dashed", + "-.", "dashdot", ":", "dotted", + (0, None), (0, ()), (0, []), # gh-22930 + ]: + ax.plot(range(10), linestyle=ls) + fig.canvas.draw() + + +def test_valid_linestyles(): + line = mlines.Line2D([], []) + with pytest.raises(ValueError): + line.set_linestyle('aardvark') + + +@image_comparison(['drawstyle_variants.png'], remove_text=True) +def test_drawstyle_variants(): + fig, axs = plt.subplots(6) + dss = ["default", "steps-mid", "steps-pre", "steps-post", "steps", None] + # We want to check that drawstyles are properly handled even for very long + # lines (for which the subslice optimization is on); however, we need + # to zoom in so that the difference between the drawstyles is actually + # visible. + for ax, ds in zip(axs.flat, dss): + ax.plot(range(2000), drawstyle=ds) + ax.set(xlim=(0, 2), ylim=(0, 2)) + + +@check_figures_equal(extensions=('png',)) +def test_no_subslice_with_transform(fig_ref, fig_test): + ax = fig_ref.add_subplot() + x = np.arange(2000) + ax.plot(x + 2000, x) + + ax = fig_test.add_subplot() + t = mtransforms.Affine2D().translate(2000.0, 0.0) + ax.plot(x, x, transform=t+ax.transData) + + +def test_valid_drawstyles(): + line = mlines.Line2D([], []) + with pytest.raises(ValueError): + line.set_drawstyle('foobar') + + +def test_set_drawstyle(): + x = np.linspace(0, 2*np.pi, 10) + y = np.sin(x) + + fig, ax = plt.subplots() + line, = ax.plot(x, y) + line.set_drawstyle("steps-pre") + assert len(line.get_path().vertices) == 2*len(x)-1 + + line.set_drawstyle("default") + assert len(line.get_path().vertices) == len(x) + + +@image_comparison( + ['line_collection_dashes'], remove_text=True, style='mpl20', + tol=0.65 if platform.machine() in ('aarch64', 'ppc64le', 's390x') else 0) +def test_set_line_coll_dash_image(): + fig, ax = plt.subplots() + np.random.seed(0) + ax.contour(np.random.randn(20, 30), linestyles=[(0, (3, 3))]) + + +@image_comparison(['marker_fill_styles.png'], remove_text=True) +def test_marker_fill_styles(): + colors = itertools.cycle([[0, 0, 1], 'g', '#ff0000', 'c', 'm', 'y', + np.array([0, 0, 0])]) + altcolor = 'lightgreen' + + y = np.array([1, 1]) + x = np.array([0, 9]) + fig, ax = plt.subplots() + + # This hard-coded list of markers correspond to an earlier iteration of + # MarkerStyle.filled_markers; the value of that attribute has changed but + # we kept the old value here to not regenerate the baseline image. + # Replace with mlines.Line2D.filled_markers when the image is regenerated. + for j, marker in enumerate("ov^<>8sp*hHDdPX"): + for i, fs in enumerate(mlines.Line2D.fillStyles): + color = next(colors) + ax.plot(j * 10 + x, y + i + .5 * (j % 2), + marker=marker, + markersize=20, + markerfacecoloralt=altcolor, + fillstyle=fs, + label=fs, + linewidth=5, + color=color, + markeredgecolor=color, + markeredgewidth=2) + + ax.set_ylim([0, 7.5]) + ax.set_xlim([-5, 155]) + + +def test_markerfacecolor_fillstyle(): + """Test that markerfacecolor does not override fillstyle='none'.""" + l, = plt.plot([1, 3, 2], marker=MarkerStyle('o', fillstyle='none'), + markerfacecolor='red') + assert l.get_fillstyle() == 'none' + assert l.get_markerfacecolor() == 'none' + + +@image_comparison(['scaled_lines'], style='default') +def test_lw_scaling(): + th = np.linspace(0, 32) + fig, ax = plt.subplots() + lins_styles = ['dashed', 'dotted', 'dashdot'] + cy = cycler(matplotlib.rcParams['axes.prop_cycle']) + for j, (ls, sty) in enumerate(zip(lins_styles, cy)): + for lw in np.linspace(.5, 10, 10): + ax.plot(th, j*np.ones(50) + .1 * lw, linestyle=ls, lw=lw, **sty) + + +def test_is_sorted_and_has_non_nan(): + assert _path.is_sorted_and_has_non_nan(np.array([1, 2, 3])) + assert _path.is_sorted_and_has_non_nan(np.array([1, np.nan, 3])) + assert not _path.is_sorted_and_has_non_nan([3, 5] + [np.nan] * 100 + [0, 2]) + n = 2 * mlines.Line2D._subslice_optim_min_size + plt.plot([np.nan] * n, range(n)) + + +@check_figures_equal() +def test_step_markers(fig_test, fig_ref): + fig_test.subplots().step([0, 1], "-o") + fig_ref.subplots().plot([0, 0, 1], [0, 1, 1], "-o", markevery=[0, 2]) + + +@pytest.mark.parametrize("parent", ["figure", "axes"]) +@check_figures_equal(extensions=('png',)) +def test_markevery(fig_test, fig_ref, parent): + np.random.seed(42) + x = np.linspace(0, 1, 14) + y = np.random.rand(len(x)) + + cases_test = [None, 4, (2, 5), [1, 5, 11], + [0, -1], slice(5, 10, 2), + np.arange(len(x))[y > 0.5], + 0.3, (0.3, 0.4)] + cases_ref = ["11111111111111", "10001000100010", "00100001000010", + "01000100000100", "10000000000001", "00000101010000", + "01110001110110", "11011011011110", "01010011011101"] + + if parent == "figure": + # float markevery ("relative to axes size") is not supported. + cases_test = cases_test[:-2] + cases_ref = cases_ref[:-2] + + def add_test(x, y, *, markevery): + fig_test.add_artist( + mlines.Line2D(x, y, marker="o", markevery=markevery)) + + def add_ref(x, y, *, markevery): + fig_ref.add_artist( + mlines.Line2D(x, y, marker="o", markevery=markevery)) + + elif parent == "axes": + axs_test = iter(fig_test.subplots(3, 3).flat) + axs_ref = iter(fig_ref.subplots(3, 3).flat) + + def add_test(x, y, *, markevery): + next(axs_test).plot(x, y, "-gD", markevery=markevery) + + def add_ref(x, y, *, markevery): + next(axs_ref).plot(x, y, "-gD", markevery=markevery) + + for case in cases_test: + add_test(x, y, markevery=case) + + for case in cases_ref: + me = np.array(list(case)).astype(int).astype(bool) + add_ref(x, y, markevery=me) + + +def test_markevery_figure_line_unsupported_relsize(): + fig = plt.figure() + fig.add_artist(mlines.Line2D([0, 1], [0, 1], marker="o", markevery=.5)) + with pytest.raises(ValueError): + fig.canvas.draw() + + +def test_marker_as_markerstyle(): + fig, ax = plt.subplots() + line, = ax.plot([2, 4, 3], marker=MarkerStyle("D")) + fig.canvas.draw() + assert line.get_marker() == "D" + + # continue with smoke tests: + line.set_marker("s") + fig.canvas.draw() + line.set_marker(MarkerStyle("o")) + fig.canvas.draw() + # test Path roundtrip + triangle1 = Path._create_closed([[-1, -1], [1, -1], [0, 2]]) + line2, = ax.plot([1, 3, 2], marker=MarkerStyle(triangle1), ms=22) + line3, = ax.plot([0, 2, 1], marker=triangle1, ms=22) + + assert_array_equal(line2.get_marker().vertices, triangle1.vertices) + assert_array_equal(line3.get_marker().vertices, triangle1.vertices) + + +@image_comparison(['striped_line.png'], remove_text=True, style='mpl20') +def test_striped_lines(): + rng = np.random.default_rng(19680801) + _, ax = plt.subplots() + ax.plot(rng.uniform(size=12), color='orange', gapcolor='blue', + linestyle='--', lw=5, label=' ') + ax.plot(rng.uniform(size=12), color='red', gapcolor='black', + linestyle=(0, (2, 5, 4, 2)), lw=5, label=' ', alpha=0.5) + ax.legend(handlelength=5) + + +@check_figures_equal() +def test_odd_dashes(fig_test, fig_ref): + fig_test.add_subplot().plot([1, 2], dashes=[1, 2, 3]) + fig_ref.add_subplot().plot([1, 2], dashes=[1, 2, 3, 1, 2, 3]) + + +def test_picking(): + fig, ax = plt.subplots() + mouse_event = SimpleNamespace(x=fig.bbox.width // 2, + y=fig.bbox.height // 2 + 15) + + # Default pickradius is 5, so event should not pick this line. + l0, = ax.plot([0, 1], [0, 1], picker=True) + found, indices = l0.contains(mouse_event) + assert not found + + # But with a larger pickradius, this should be picked. + l1, = ax.plot([0, 1], [0, 1], picker=True, pickradius=20) + found, indices = l1.contains(mouse_event) + assert found + assert_array_equal(indices['ind'], [0]) + + # And if we modify the pickradius after creation, it should work as well. + l2, = ax.plot([0, 1], [0, 1], picker=True) + found, indices = l2.contains(mouse_event) + assert not found + l2.set_pickradius(20) + found, indices = l2.contains(mouse_event) + assert found + assert_array_equal(indices['ind'], [0]) + + +@check_figures_equal() +def test_input_copy(fig_test, fig_ref): + + t = np.arange(0, 6, 2) + l, = fig_test.add_subplot().plot(t, t, ".-") + t[:] = range(3) + # Trigger cache invalidation + l.set_drawstyle("steps") + fig_ref.add_subplot().plot([0, 2, 4], [0, 2, 4], ".-", drawstyle="steps") + + +@check_figures_equal(extensions=["png"]) +def test_markevery_prop_cycle(fig_test, fig_ref): + """Test that we can set markevery prop_cycle.""" + cases = [None, 8, (30, 8), [16, 24, 30], [0, -1], + slice(100, 200, 3), 0.1, 0.3, 1.5, + (0.0, 0.1), (0.45, 0.1)] + + cmap = mpl.colormaps['jet'] + colors = cmap(np.linspace(0.2, 0.8, len(cases))) + + x = np.linspace(-1, 1) + y = 5 * x**2 + + axs = fig_ref.add_subplot() + for i, markevery in enumerate(cases): + axs.plot(y - i, 'o-', markevery=markevery, color=colors[i]) + + matplotlib.rcParams['axes.prop_cycle'] = cycler(markevery=cases, + color=colors) + + ax = fig_test.add_subplot() + for i, _ in enumerate(cases): + ax.plot(y - i, 'o-') diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/test_pyplot.py b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/test_pyplot.py new file mode 100644 index 0000000000000000000000000000000000000000..95e3174d8ae82baa45f39c2583b4034fe3bfd07c --- /dev/null +++ b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/test_pyplot.py @@ -0,0 +1,457 @@ +import difflib + +import numpy as np +import subprocess +import sys +from pathlib import Path + +import pytest + +import matplotlib as mpl +from matplotlib import pyplot as plt +from matplotlib._api import MatplotlibDeprecationWarning + + +def test_pyplot_up_to_date(tmpdir): + gen_script = Path(mpl.__file__).parents[2] / "tools/boilerplate.py" + if not gen_script.exists(): + pytest.skip("boilerplate.py not found") + orig_contents = Path(plt.__file__).read_text() + plt_file = tmpdir.join('pyplot.py') + plt_file.write_text(orig_contents, 'utf-8') + + subprocess.run([sys.executable, str(gen_script), str(plt_file)], + check=True) + new_contents = plt_file.read_text('utf-8') + + if orig_contents != new_contents: + diff_msg = '\n'.join( + difflib.unified_diff( + orig_contents.split('\n'), new_contents.split('\n'), + fromfile='found pyplot.py', + tofile='expected pyplot.py', + n=0, lineterm='')) + pytest.fail( + "pyplot.py is not up-to-date. Please run " + "'python tools/boilerplate.py' to update pyplot.py. " + "This needs to be done from an environment where your " + "current working copy is installed (e.g. 'pip install -e'd). " + "Here is a diff of unexpected differences:\n%s" % diff_msg + ) + + +def test_copy_docstring_and_deprecators(recwarn): + @mpl._api.rename_parameter("(version)", "old", "new") + @mpl._api.make_keyword_only("(version)", "kwo") + def func(new, kwo=None): + pass + + @plt._copy_docstring_and_deprecators(func) + def wrapper_func(new, kwo=None): + pass + + wrapper_func(None) + wrapper_func(new=None) + wrapper_func(None, kwo=None) + wrapper_func(new=None, kwo=None) + assert not recwarn + with pytest.warns(MatplotlibDeprecationWarning): + wrapper_func(old=None) + with pytest.warns(MatplotlibDeprecationWarning): + wrapper_func(None, None) + + +def test_pyplot_box(): + fig, ax = plt.subplots() + plt.box(False) + assert not ax.get_frame_on() + plt.box(True) + assert ax.get_frame_on() + plt.box() + assert not ax.get_frame_on() + plt.box() + assert ax.get_frame_on() + + +def test_stackplot_smoke(): + # Small smoke test for stackplot (see #12405) + plt.stackplot([1, 2, 3], [1, 2, 3]) + + +def test_nrows_error(): + with pytest.raises(TypeError): + plt.subplot(nrows=1) + with pytest.raises(TypeError): + plt.subplot(ncols=1) + + +def test_ioff(): + plt.ion() + assert mpl.is_interactive() + with plt.ioff(): + assert not mpl.is_interactive() + assert mpl.is_interactive() + + plt.ioff() + assert not mpl.is_interactive() + with plt.ioff(): + assert not mpl.is_interactive() + assert not mpl.is_interactive() + + +def test_ion(): + plt.ioff() + assert not mpl.is_interactive() + with plt.ion(): + assert mpl.is_interactive() + assert not mpl.is_interactive() + + plt.ion() + assert mpl.is_interactive() + with plt.ion(): + assert mpl.is_interactive() + assert mpl.is_interactive() + + +def test_nested_ion_ioff(): + # initial state is interactive + plt.ion() + + # mixed ioff/ion + with plt.ioff(): + assert not mpl.is_interactive() + with plt.ion(): + assert mpl.is_interactive() + assert not mpl.is_interactive() + assert mpl.is_interactive() + + # redundant contexts + with plt.ioff(): + with plt.ioff(): + assert not mpl.is_interactive() + assert mpl.is_interactive() + + with plt.ion(): + plt.ioff() + assert mpl.is_interactive() + + # initial state is not interactive + plt.ioff() + + # mixed ioff/ion + with plt.ion(): + assert mpl.is_interactive() + with plt.ioff(): + assert not mpl.is_interactive() + assert mpl.is_interactive() + assert not mpl.is_interactive() + + # redundant contexts + with plt.ion(): + with plt.ion(): + assert mpl.is_interactive() + assert not mpl.is_interactive() + + with plt.ioff(): + plt.ion() + assert not mpl.is_interactive() + + +def test_close(): + try: + plt.close(1.1) + except TypeError as e: + assert str(e) == "close() argument must be a Figure, an int, " \ + "a string, or None, not " + + +def test_subplot_reuse(): + ax1 = plt.subplot(121) + assert ax1 is plt.gca() + ax2 = plt.subplot(122) + assert ax2 is plt.gca() + ax3 = plt.subplot(121) + assert ax1 is plt.gca() + assert ax1 is ax3 + + +def test_axes_kwargs(): + # plt.axes() always creates new axes, even if axes kwargs differ. + plt.figure() + ax = plt.axes() + ax1 = plt.axes() + assert ax is not None + assert ax1 is not ax + plt.close() + + plt.figure() + ax = plt.axes(projection='polar') + ax1 = plt.axes(projection='polar') + assert ax is not None + assert ax1 is not ax + plt.close() + + plt.figure() + ax = plt.axes(projection='polar') + ax1 = plt.axes() + assert ax is not None + assert ax1.name == 'rectilinear' + assert ax1 is not ax + plt.close() + + +def test_subplot_replace_projection(): + # plt.subplot() searches for axes with the same subplot spec, and if one + # exists, and the kwargs match returns it, create a new one if they do not + fig = plt.figure() + ax = plt.subplot(1, 2, 1) + ax1 = plt.subplot(1, 2, 1) + ax2 = plt.subplot(1, 2, 2) + with pytest.warns(MatplotlibDeprecationWarning): + ax3 = plt.subplot(1, 2, 1, projection='polar') + ax4 = plt.subplot(1, 2, 1, projection='polar') + assert ax is not None + assert ax1 is ax + assert ax2 is not ax + assert ax3 is not ax + assert ax3 is ax4 + + assert ax not in fig.axes + assert ax2 in fig.axes + assert ax3 in fig.axes + + assert ax.name == 'rectilinear' + assert ax2.name == 'rectilinear' + assert ax3.name == 'polar' + + +def test_subplot_kwarg_collision(): + ax1 = plt.subplot(projection='polar', theta_offset=0) + ax2 = plt.subplot(projection='polar', theta_offset=0) + assert ax1 is ax2 + ax1.remove() + ax3 = plt.subplot(projection='polar', theta_offset=1) + assert ax1 is not ax3 + assert ax1 not in plt.gcf().axes + + +def test_gca(): + # plt.gca() returns an existing axes, unless there were no axes. + plt.figure() + ax = plt.gca() + ax1 = plt.gca() + assert ax is not None + assert ax1 is ax + plt.close() + + +def test_subplot_projection_reuse(): + # create an Axes + ax1 = plt.subplot(111) + # check that it is current + assert ax1 is plt.gca() + # make sure we get it back if we ask again + assert ax1 is plt.subplot(111) + # remove it + ax1.remove() + # create a polar plot + ax2 = plt.subplot(111, projection='polar') + assert ax2 is plt.gca() + # this should have deleted the first axes + assert ax1 not in plt.gcf().axes + # assert we get it back if no extra parameters passed + assert ax2 is plt.subplot(111) + ax2.remove() + # now check explicitly setting the projection to rectilinear + # makes a new axes + ax3 = plt.subplot(111, projection='rectilinear') + assert ax3 is plt.gca() + assert ax3 is not ax2 + assert ax2 not in plt.gcf().axes + + +def test_subplot_polar_normalization(): + ax1 = plt.subplot(111, projection='polar') + ax2 = plt.subplot(111, polar=True) + ax3 = plt.subplot(111, polar=True, projection='polar') + assert ax1 is ax2 + assert ax1 is ax3 + + with pytest.raises(ValueError, + match="polar=True, yet projection='3d'"): + ax2 = plt.subplot(111, polar=True, projection='3d') + + +def test_subplot_change_projection(): + created_axes = set() + ax = plt.subplot() + created_axes.add(ax) + projections = ('aitoff', 'hammer', 'lambert', 'mollweide', + 'polar', 'rectilinear', '3d') + for proj in projections: + ax.remove() + ax = plt.subplot(projection=proj) + assert ax is plt.subplot() + assert ax.name == proj + created_axes.add(ax) + # Check that each call created a new Axes. + assert len(created_axes) == 1 + len(projections) + + +def test_polar_second_call(): + # the first call creates the axes with polar projection + ln1, = plt.polar(0., 1., 'ro') + assert isinstance(ln1, mpl.lines.Line2D) + # the second call should reuse the existing axes + ln2, = plt.polar(1.57, .5, 'bo') + assert isinstance(ln2, mpl.lines.Line2D) + assert ln1.axes is ln2.axes + + +def test_fallback_position(): + # check that position kwarg works if rect not supplied + axref = plt.axes([0.2, 0.2, 0.5, 0.5]) + axtest = plt.axes(position=[0.2, 0.2, 0.5, 0.5]) + np.testing.assert_allclose(axtest.bbox.get_points(), + axref.bbox.get_points()) + + # check that position kwarg ignored if rect is supplied + axref = plt.axes([0.2, 0.2, 0.5, 0.5]) + axtest = plt.axes([0.2, 0.2, 0.5, 0.5], position=[0.1, 0.1, 0.8, 0.8]) + np.testing.assert_allclose(axtest.bbox.get_points(), + axref.bbox.get_points()) + + +def test_set_current_figure_via_subfigure(): + fig1 = plt.figure() + subfigs = fig1.subfigures(2) + + plt.figure() + assert plt.gcf() != fig1 + + current = plt.figure(subfigs[1]) + assert plt.gcf() == fig1 + assert current == fig1 + + +def test_set_current_axes_on_subfigure(): + fig = plt.figure() + subfigs = fig.subfigures(2) + + ax = subfigs[0].subplots(1, squeeze=True) + subfigs[1].subplots(1, squeeze=True) + + assert plt.gca() != ax + plt.sca(ax) + assert plt.gca() == ax + + +def test_pylab_integration(): + IPython = pytest.importorskip("IPython") + mpl.testing.subprocess_run_helper( + IPython.start_ipython, + "--pylab", + "-c", + ";".join(( + "import matplotlib.pyplot as plt", + "assert plt._REPL_DISPLAYHOOK == plt._ReplDisplayHook.IPYTHON", + )), + timeout=60, + ) + + +def test_doc_pyplot_summary(): + """Test that pyplot_summary lists all the plot functions.""" + pyplot_docs = Path(__file__).parent / '../../../doc/api/pyplot_summary.rst' + if not pyplot_docs.exists(): + pytest.skip("Documentation sources not available") + + def extract_documented_functions(lines): + """ + Return a list of all the functions that are mentioned in the + autosummary blocks contained in *lines*. + + An autosummary block looks like this:: + + .. autosummary:: + :toctree: _as_gen + :template: autosummary.rst + :nosignatures: + + plot + plot_date + + """ + functions = [] + in_autosummary = False + for line in lines: + if not in_autosummary: + if line.startswith(".. autosummary::"): + in_autosummary = True + else: + if not line or line.startswith(" :"): + # empty line or autosummary parameter + continue + if not line[0].isspace(): + # no more indentation: end of autosummary block + in_autosummary = False + continue + functions.append(line.strip()) + return functions + + lines = pyplot_docs.read_text().split("\n") + doc_functions = set(extract_documented_functions(lines)) + plot_commands = set(plt._get_pyplot_commands()) + missing = plot_commands.difference(doc_functions) + if missing: + raise AssertionError( + f"The following pyplot functions are not listed in the " + f"documentation. Please add them to doc/api/pyplot_summary.rst: " + f"{missing!r}") + extra = doc_functions.difference(plot_commands) + if extra: + raise AssertionError( + f"The following functions are listed in the pyplot documentation, " + f"but they do not exist in pyplot. " + f"Please remove them from doc/api/pyplot_summary.rst: {extra!r}") + + +def test_minor_ticks(): + plt.figure() + plt.plot(np.arange(1, 10)) + tick_pos, tick_labels = plt.xticks(minor=True) + assert np.all(tick_labels == np.array([], dtype=np.float64)) + assert tick_labels == [] + + plt.yticks(ticks=[3.5, 6.5], labels=["a", "b"], minor=True) + ax = plt.gca() + tick_pos = ax.get_yticks(minor=True) + tick_labels = ax.get_yticklabels(minor=True) + assert np.all(tick_pos == np.array([3.5, 6.5])) + assert [l.get_text() for l in tick_labels] == ['a', 'b'] + + +def test_switch_backend_no_close(): + plt.switch_backend('agg') + fig = plt.figure() + fig = plt.figure() + assert len(plt.get_fignums()) == 2 + plt.switch_backend('agg') + assert len(plt.get_fignums()) == 2 + plt.switch_backend('svg') + assert len(plt.get_fignums()) == 0 + + +def figure_hook_example(figure): + figure._test_was_here = True + + +def test_figure_hook(): + + test_rc = { + 'figure.hooks': ['matplotlib.tests.test_pyplot:figure_hook_example'] + } + with mpl.rc_context(test_rc): + fig = plt.figure() + + assert fig._test_was_here diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/test_sphinxext.py b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/test_sphinxext.py new file mode 100644 index 0000000000000000000000000000000000000000..41575d3a3ce1a78a3082effe0ba4822fe1dd2b76 --- /dev/null +++ b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/test_sphinxext.py @@ -0,0 +1,180 @@ +"""Tests for tinypages build using sphinx extensions.""" + +import filecmp +import os +from pathlib import Path +import shutil +from subprocess import Popen, PIPE +import sys + +import pytest + + +pytest.importorskip('sphinx', + minversion=None if sys.version_info < (3, 10) else '4.1.3') + + +def build_sphinx_html(source_dir, doctree_dir, html_dir, extra_args=None): + # Build the pages with warnings turned into errors + extra_args = [] if extra_args is None else extra_args + cmd = [sys.executable, '-msphinx', '-W', '-b', 'html', + '-d', str(doctree_dir), str(source_dir), str(html_dir), *extra_args] + proc = Popen(cmd, stdout=PIPE, stderr=PIPE, universal_newlines=True, + env={**os.environ, "MPLBACKEND": ""}) + out, err = proc.communicate() + + assert proc.returncode == 0, \ + f"sphinx build failed with stdout:\n{out}\nstderr:\n{err}\n" + if err: + pytest.fail(f"sphinx build emitted the following warnings:\n{err}") + + assert html_dir.is_dir() + + +def test_tinypages(tmp_path): + shutil.copytree(Path(__file__).parent / 'tinypages', tmp_path, + dirs_exist_ok=True) + html_dir = tmp_path / '_build' / 'html' + img_dir = html_dir / '_images' + doctree_dir = tmp_path / 'doctrees' + # Build the pages with warnings turned into errors + cmd = [sys.executable, '-msphinx', '-W', '-b', 'html', + '-d', str(doctree_dir), + str(Path(__file__).parent / 'tinypages'), str(html_dir)] + # On CI, gcov emits warnings (due to agg headers being included with the + # same name in multiple extension modules -- but we don't care about their + # coverage anyways); hide them using GCOV_ERROR_FILE. + proc = Popen( + cmd, stdout=PIPE, stderr=PIPE, universal_newlines=True, + env={**os.environ, "MPLBACKEND": "", "GCOV_ERROR_FILE": os.devnull}) + out, err = proc.communicate() + + # Build the pages with warnings turned into errors + build_sphinx_html(tmp_path, doctree_dir, html_dir) + + def plot_file(num): + return img_dir / f'some_plots-{num}.png' + + def plot_directive_file(num): + # This is always next to the doctree dir. + return doctree_dir.parent / 'plot_directive' / f'some_plots-{num}.png' + + range_10, range_6, range_4 = [plot_file(i) for i in range(1, 4)] + # Plot 5 is range(6) plot + assert filecmp.cmp(range_6, plot_file(5)) + # Plot 7 is range(4) plot + assert filecmp.cmp(range_4, plot_file(7)) + # Plot 11 is range(10) plot + assert filecmp.cmp(range_10, plot_file(11)) + # Plot 12 uses the old range(10) figure and the new range(6) figure + assert filecmp.cmp(range_10, plot_file('12_00')) + assert filecmp.cmp(range_6, plot_file('12_01')) + # Plot 13 shows close-figs in action + assert filecmp.cmp(range_4, plot_file(13)) + # Plot 14 has included source + html_contents = (html_dir / 'some_plots.html').read_bytes() + + assert b'# Only a comment' in html_contents + # check plot defined in external file. + assert filecmp.cmp(range_4, img_dir / 'range4.png') + assert filecmp.cmp(range_6, img_dir / 'range6_range6.png') + # check if figure caption made it into html file + assert b'This is the caption for plot 15.' in html_contents + # check if figure caption using :caption: made it into html file + assert b'Plot 17 uses the caption option.' in html_contents + # check if figure caption made it into html file + assert b'This is the caption for plot 18.' in html_contents + # check if the custom classes made it into the html file + assert b'plot-directive my-class my-other-class' in html_contents + # check that the multi-image caption is applied twice + assert html_contents.count(b'This caption applies to both plots.') == 2 + # Plot 21 is range(6) plot via an include directive. But because some of + # the previous plots are repeated, the argument to plot_file() is only 17. + assert filecmp.cmp(range_6, plot_file(17)) + # plot 22 is from the range6.py file again, but a different function + assert filecmp.cmp(range_10, img_dir / 'range6_range10.png') + + # Modify the included plot + contents = (tmp_path / 'included_plot_21.rst').read_bytes() + contents = contents.replace(b'plt.plot(range(6))', b'plt.plot(range(4))') + (tmp_path / 'included_plot_21.rst').write_bytes(contents) + # Build the pages again and check that the modified file was updated + modification_times = [plot_directive_file(i).stat().st_mtime + for i in (1, 2, 3, 5)] + build_sphinx_html(tmp_path, doctree_dir, html_dir) + assert filecmp.cmp(range_4, plot_file(17)) + # Check that the plots in the plot_directive folder weren't changed. + # (plot_directive_file(1) won't be modified, but it will be copied to html/ + # upon compilation, so plot_file(1) will be modified) + assert plot_directive_file(1).stat().st_mtime == modification_times[0] + assert plot_directive_file(2).stat().st_mtime == modification_times[1] + assert plot_directive_file(3).stat().st_mtime == modification_times[2] + assert filecmp.cmp(range_10, plot_file(1)) + assert filecmp.cmp(range_6, plot_file(2)) + assert filecmp.cmp(range_4, plot_file(3)) + # Make sure that figures marked with context are re-created (but that the + # contents are the same) + assert plot_directive_file(5).stat().st_mtime > modification_times[3] + assert filecmp.cmp(range_6, plot_file(5)) + + +def test_plot_html_show_source_link(tmp_path): + parent = Path(__file__).parent + shutil.copyfile(parent / 'tinypages/conf.py', tmp_path / 'conf.py') + shutil.copytree(parent / 'tinypages/_static', tmp_path / '_static') + doctree_dir = tmp_path / 'doctrees' + (tmp_path / 'index.rst').write_text(""" +.. plot:: + + plt.plot(range(2)) +""") + # Make sure source scripts are created by default + html_dir1 = tmp_path / '_build' / 'html1' + build_sphinx_html(tmp_path, doctree_dir, html_dir1) + assert len(list(html_dir1.glob("**/index-1.py"))) == 1 + # Make sure source scripts are NOT created when + # plot_html_show_source_link` is False + html_dir2 = tmp_path / '_build' / 'html2' + build_sphinx_html(tmp_path, doctree_dir, html_dir2, + extra_args=['-D', 'plot_html_show_source_link=0']) + assert len(list(html_dir2.glob("**/index-1.py"))) == 0 + + +@pytest.mark.parametrize('plot_html_show_source_link', [0, 1]) +def test_show_source_link_true(tmp_path, plot_html_show_source_link): + # Test that a source link is generated if :show-source-link: is true, + # whether or not plot_html_show_source_link is true. + parent = Path(__file__).parent + shutil.copyfile(parent / 'tinypages/conf.py', tmp_path / 'conf.py') + shutil.copytree(parent / 'tinypages/_static', tmp_path / '_static') + doctree_dir = tmp_path / 'doctrees' + (tmp_path / 'index.rst').write_text(""" +.. plot:: + :show-source-link: true + + plt.plot(range(2)) +""") + html_dir = tmp_path / '_build' / 'html' + build_sphinx_html(tmp_path, doctree_dir, html_dir, extra_args=[ + '-D', f'plot_html_show_source_link={plot_html_show_source_link}']) + assert len(list(html_dir.glob("**/index-1.py"))) == 1 + + +@pytest.mark.parametrize('plot_html_show_source_link', [0, 1]) +def test_show_source_link_false(tmp_path, plot_html_show_source_link): + # Test that a source link is NOT generated if :show-source-link: is false, + # whether or not plot_html_show_source_link is true. + parent = Path(__file__).parent + shutil.copyfile(parent / 'tinypages/conf.py', tmp_path / 'conf.py') + shutil.copytree(parent / 'tinypages/_static', tmp_path / '_static') + doctree_dir = tmp_path / 'doctrees' + (tmp_path / 'index.rst').write_text(""" +.. plot:: + :show-source-link: false + + plt.plot(range(2)) +""") + html_dir = tmp_path / '_build' / 'html' + build_sphinx_html(tmp_path, doctree_dir, html_dir, extra_args=[ + '-D', f'plot_html_show_source_link={plot_html_show_source_link}']) + assert len(list(html_dir.glob("**/index-1.py"))) == 0 diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/test_ticker.py b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/test_ticker.py new file mode 100644 index 0000000000000000000000000000000000000000..2bea8c9990677f599bcc42d5e82eb346dd73ecff --- /dev/null +++ b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/test_ticker.py @@ -0,0 +1,1563 @@ +from contextlib import nullcontext +import itertools +import locale +import logging +import re + +import numpy as np +from numpy.testing import assert_almost_equal, assert_array_equal +import pytest + +import matplotlib as mpl +import matplotlib.pyplot as plt +import matplotlib.ticker as mticker + + +class TestMaxNLocator: + basic_data = [ + (20, 100, np.array([20., 40., 60., 80., 100.])), + (0.001, 0.0001, np.array([0., 0.0002, 0.0004, 0.0006, 0.0008, 0.001])), + (-1e15, 1e15, np.array([-1.0e+15, -5.0e+14, 0e+00, 5e+14, 1.0e+15])), + (0, 0.85e-50, np.arange(6) * 2e-51), + (-0.85e-50, 0, np.arange(-5, 1) * 2e-51), + ] + + integer_data = [ + (-0.1, 1.1, None, np.array([-1, 0, 1, 2])), + (-0.1, 0.95, None, np.array([-0.25, 0, 0.25, 0.5, 0.75, 1.0])), + (1, 55, [1, 1.5, 5, 6, 10], np.array([0, 15, 30, 45, 60])), + ] + + @pytest.mark.parametrize('vmin, vmax, expected', basic_data) + def test_basic(self, vmin, vmax, expected): + loc = mticker.MaxNLocator(nbins=5) + assert_almost_equal(loc.tick_values(vmin, vmax), expected) + + @pytest.mark.parametrize('vmin, vmax, steps, expected', integer_data) + def test_integer(self, vmin, vmax, steps, expected): + loc = mticker.MaxNLocator(nbins=5, integer=True, steps=steps) + assert_almost_equal(loc.tick_values(vmin, vmax), expected) + + +class TestLinearLocator: + def test_basic(self): + loc = mticker.LinearLocator(numticks=3) + test_value = np.array([-0.8, -0.3, 0.2]) + assert_almost_equal(loc.tick_values(-0.8, 0.2), test_value) + + def test_set_params(self): + """ + Create linear locator with presets={}, numticks=2 and change it to + something else. See if change was successful. Should not exception. + """ + loc = mticker.LinearLocator(numticks=2) + loc.set_params(numticks=8, presets={(0, 1): []}) + assert loc.numticks == 8 + assert loc.presets == {(0, 1): []} + + +class TestMultipleLocator: + def test_basic(self): + loc = mticker.MultipleLocator(base=3.147) + test_value = np.array([-9.441, -6.294, -3.147, 0., 3.147, 6.294, + 9.441, 12.588]) + assert_almost_equal(loc.tick_values(-7, 10), test_value) + + def test_view_limits(self): + """ + Test basic behavior of view limits. + """ + with mpl.rc_context({'axes.autolimit_mode': 'data'}): + loc = mticker.MultipleLocator(base=3.147) + assert_almost_equal(loc.view_limits(-5, 5), (-5, 5)) + + def test_view_limits_round_numbers(self): + """ + Test that everything works properly with 'round_numbers' for auto + limit. + """ + with mpl.rc_context({'axes.autolimit_mode': 'round_numbers'}): + loc = mticker.MultipleLocator(base=3.147) + assert_almost_equal(loc.view_limits(-4, 4), (-6.294, 6.294)) + + def test_set_params(self): + """ + Create multiple locator with 0.7 base, and change it to something else. + See if change was successful. + """ + mult = mticker.MultipleLocator(base=0.7) + mult.set_params(base=1.7) + assert mult._edge.step == 1.7 + + +class TestAutoMinorLocator: + def test_basic(self): + fig, ax = plt.subplots() + ax.set_xlim(0, 1.39) + ax.minorticks_on() + test_value = np.array([0.05, 0.1, 0.15, 0.25, 0.3, 0.35, 0.45, + 0.5, 0.55, 0.65, 0.7, 0.75, 0.85, 0.9, + 0.95, 1.05, 1.1, 1.15, 1.25, 1.3, 1.35]) + assert_almost_equal(ax.xaxis.get_ticklocs(minor=True), test_value) + + # NB: the following values are assuming that *xlim* is [0, 5] + params = [ + (0, 0), # no major tick => no minor tick either + (1, 0) # a single major tick => no minor tick + ] + + @pytest.mark.parametrize('nb_majorticks, expected_nb_minorticks', params) + def test_low_number_of_majorticks( + self, nb_majorticks, expected_nb_minorticks): + # This test is related to issue #8804 + fig, ax = plt.subplots() + xlims = (0, 5) # easier to test the different code paths + ax.set_xlim(*xlims) + ax.set_xticks(np.linspace(xlims[0], xlims[1], nb_majorticks)) + ax.minorticks_on() + ax.xaxis.set_minor_locator(mticker.AutoMinorLocator()) + assert len(ax.xaxis.get_minorticklocs()) == expected_nb_minorticks + + majorstep_minordivisions = [(1, 5), + (2, 4), + (2.5, 5), + (5, 5), + (10, 5)] + + # This test is meant to verify the parameterization for + # test_number_of_minor_ticks + def test_using_all_default_major_steps(self): + with mpl.rc_context({'_internal.classic_mode': False}): + majorsteps = [x[0] for x in self.majorstep_minordivisions] + np.testing.assert_allclose(majorsteps, + mticker.AutoLocator()._steps) + + @pytest.mark.parametrize('major_step, expected_nb_minordivisions', + majorstep_minordivisions) + def test_number_of_minor_ticks( + self, major_step, expected_nb_minordivisions): + fig, ax = plt.subplots() + xlims = (0, major_step) + ax.set_xlim(*xlims) + ax.set_xticks(xlims) + ax.minorticks_on() + ax.xaxis.set_minor_locator(mticker.AutoMinorLocator()) + nb_minor_divisions = len(ax.xaxis.get_minorticklocs()) + 1 + assert nb_minor_divisions == expected_nb_minordivisions + + limits = [(0, 1.39), (0, 0.139), + (0, 0.11e-19), (0, 0.112e-12), + (-2.0e-07, -3.3e-08), (1.20e-06, 1.42e-06), + (-1.34e-06, -1.44e-06), (-8.76e-07, -1.51e-06)] + + reference = [ + [0.05, 0.1, 0.15, 0.25, 0.3, 0.35, 0.45, 0.5, 0.55, 0.65, 0.7, + 0.75, 0.85, 0.9, 0.95, 1.05, 1.1, 1.15, 1.25, 1.3, 1.35], + [0.005, 0.01, 0.015, 0.025, 0.03, 0.035, 0.045, 0.05, 0.055, 0.065, + 0.07, 0.075, 0.085, 0.09, 0.095, 0.105, 0.11, 0.115, 0.125, 0.13, + 0.135], + [5.00e-22, 1.00e-21, 1.50e-21, 2.50e-21, 3.00e-21, 3.50e-21, 4.50e-21, + 5.00e-21, 5.50e-21, 6.50e-21, 7.00e-21, 7.50e-21, 8.50e-21, 9.00e-21, + 9.50e-21, 1.05e-20, 1.10e-20], + [5.00e-15, 1.00e-14, 1.50e-14, 2.50e-14, 3.00e-14, 3.50e-14, 4.50e-14, + 5.00e-14, 5.50e-14, 6.50e-14, 7.00e-14, 7.50e-14, 8.50e-14, 9.00e-14, + 9.50e-14, 1.05e-13, 1.10e-13], + [-1.95e-07, -1.90e-07, -1.85e-07, -1.75e-07, -1.70e-07, -1.65e-07, + -1.55e-07, -1.50e-07, -1.45e-07, -1.35e-07, -1.30e-07, -1.25e-07, + -1.15e-07, -1.10e-07, -1.05e-07, -9.50e-08, -9.00e-08, -8.50e-08, + -7.50e-08, -7.00e-08, -6.50e-08, -5.50e-08, -5.00e-08, -4.50e-08, + -3.50e-08], + [1.21e-06, 1.22e-06, 1.23e-06, 1.24e-06, 1.26e-06, 1.27e-06, 1.28e-06, + 1.29e-06, 1.31e-06, 1.32e-06, 1.33e-06, 1.34e-06, 1.36e-06, 1.37e-06, + 1.38e-06, 1.39e-06, 1.41e-06, 1.42e-06], + [-1.435e-06, -1.430e-06, -1.425e-06, -1.415e-06, -1.410e-06, + -1.405e-06, -1.395e-06, -1.390e-06, -1.385e-06, -1.375e-06, + -1.370e-06, -1.365e-06, -1.355e-06, -1.350e-06, -1.345e-06], + [-1.48e-06, -1.46e-06, -1.44e-06, -1.42e-06, -1.38e-06, -1.36e-06, + -1.34e-06, -1.32e-06, -1.28e-06, -1.26e-06, -1.24e-06, -1.22e-06, + -1.18e-06, -1.16e-06, -1.14e-06, -1.12e-06, -1.08e-06, -1.06e-06, + -1.04e-06, -1.02e-06, -9.80e-07, -9.60e-07, -9.40e-07, -9.20e-07, + -8.80e-07]] + + additional_data = list(zip(limits, reference)) + + @pytest.mark.parametrize('lim, ref', additional_data) + def test_additional(self, lim, ref): + fig, ax = plt.subplots() + + ax.minorticks_on() + ax.grid(True, 'minor', 'y', linewidth=1) + ax.grid(True, 'major', color='k', linewidth=1) + ax.set_ylim(lim) + + assert_almost_equal(ax.yaxis.get_ticklocs(minor=True), ref) + + +class TestLogLocator: + def test_basic(self): + loc = mticker.LogLocator(numticks=5) + with pytest.raises(ValueError): + loc.tick_values(0, 1000) + + test_value = np.array([1.00000000e-05, 1.00000000e-03, 1.00000000e-01, + 1.00000000e+01, 1.00000000e+03, 1.00000000e+05, + 1.00000000e+07, 1.000000000e+09]) + assert_almost_equal(loc.tick_values(0.001, 1.1e5), test_value) + + loc = mticker.LogLocator(base=2) + test_value = np.array([0.5, 1., 2., 4., 8., 16., 32., 64., 128., 256.]) + assert_almost_equal(loc.tick_values(1, 100), test_value) + + def test_polar_axes(self): + """ + Polar axes have a different ticking logic. + """ + fig, ax = plt.subplots(subplot_kw={'projection': 'polar'}) + ax.set_yscale('log') + ax.set_ylim(1, 100) + assert_array_equal(ax.get_yticks(), [10, 100, 1000]) + + def test_switch_to_autolocator(self): + loc = mticker.LogLocator(subs="all") + assert_array_equal(loc.tick_values(0.45, 0.55), + [0.44, 0.46, 0.48, 0.5, 0.52, 0.54, 0.56]) + # check that we *skip* 1.0, and 10, because this is a minor locator + loc = mticker.LogLocator(subs=np.arange(2, 10)) + assert 1.0 not in loc.tick_values(0.9, 20.) + assert 10.0 not in loc.tick_values(0.9, 20.) + + def test_set_params(self): + """ + Create log locator with default value, base=10.0, subs=[1.0], + numdecs=4, numticks=15 and change it to something else. + See if change was successful. Should not raise exception. + """ + loc = mticker.LogLocator() + loc.set_params(numticks=7, numdecs=8, subs=[2.0], base=4) + assert loc.numticks == 7 + assert loc.numdecs == 8 + assert loc._base == 4 + assert list(loc._subs) == [2.0] + + +class TestNullLocator: + def test_set_params(self): + """ + Create null locator, and attempt to call set_params() on it. + Should not exception, and should raise a warning. + """ + loc = mticker.NullLocator() + with pytest.warns(UserWarning): + loc.set_params() + + +class _LogitHelper: + @staticmethod + def isclose(x, y): + return (np.isclose(-np.log(1/x-1), -np.log(1/y-1)) + if 0 < x < 1 and 0 < y < 1 else False) + + @staticmethod + def assert_almost_equal(x, y): + ax = np.array(x) + ay = np.array(y) + assert np.all(ax > 0) and np.all(ax < 1) + assert np.all(ay > 0) and np.all(ay < 1) + lx = -np.log(1/ax-1) + ly = -np.log(1/ay-1) + assert_almost_equal(lx, ly) + + +class TestLogitLocator: + ref_basic_limits = [ + (5e-2, 1 - 5e-2), + (5e-3, 1 - 5e-3), + (5e-4, 1 - 5e-4), + (5e-5, 1 - 5e-5), + (5e-6, 1 - 5e-6), + (5e-7, 1 - 5e-7), + (5e-8, 1 - 5e-8), + (5e-9, 1 - 5e-9), + ] + + ref_basic_major_ticks = [ + 1 / (10 ** np.arange(1, 3)), + 1 / (10 ** np.arange(1, 4)), + 1 / (10 ** np.arange(1, 5)), + 1 / (10 ** np.arange(1, 6)), + 1 / (10 ** np.arange(1, 7)), + 1 / (10 ** np.arange(1, 8)), + 1 / (10 ** np.arange(1, 9)), + 1 / (10 ** np.arange(1, 10)), + ] + + ref_maxn_limits = [(0.4, 0.6), (5e-2, 2e-1), (1 - 2e-1, 1 - 5e-2)] + + @pytest.mark.parametrize( + "lims, expected_low_ticks", + zip(ref_basic_limits, ref_basic_major_ticks), + ) + def test_basic_major(self, lims, expected_low_ticks): + """ + Create logit locator with huge number of major, and tests ticks. + """ + expected_ticks = sorted( + [*expected_low_ticks, 0.5, *(1 - expected_low_ticks)] + ) + loc = mticker.LogitLocator(nbins=100) + _LogitHelper.assert_almost_equal( + loc.tick_values(*lims), + expected_ticks + ) + + @pytest.mark.parametrize("lims", ref_maxn_limits) + def test_maxn_major(self, lims): + """ + When the axis is zoomed, the locator must have the same behavior as + MaxNLocator. + """ + loc = mticker.LogitLocator(nbins=100) + maxn_loc = mticker.MaxNLocator(nbins=100, steps=[1, 2, 5, 10]) + for nbins in (4, 8, 16): + loc.set_params(nbins=nbins) + maxn_loc.set_params(nbins=nbins) + ticks = loc.tick_values(*lims) + maxn_ticks = maxn_loc.tick_values(*lims) + assert ticks.shape == maxn_ticks.shape + assert (ticks == maxn_ticks).all() + + @pytest.mark.parametrize("lims", ref_basic_limits + ref_maxn_limits) + def test_nbins_major(self, lims): + """ + Assert logit locator for respecting nbins param. + """ + + basic_needed = int(-np.floor(np.log10(lims[0]))) * 2 + 1 + loc = mticker.LogitLocator(nbins=100) + for nbins in range(basic_needed, 2, -1): + loc.set_params(nbins=nbins) + assert len(loc.tick_values(*lims)) <= nbins + 2 + + @pytest.mark.parametrize( + "lims, expected_low_ticks", + zip(ref_basic_limits, ref_basic_major_ticks), + ) + def test_minor(self, lims, expected_low_ticks): + """ + In large scale, test the presence of minor, + and assert no minor when major are subsampled. + """ + + expected_ticks = sorted( + [*expected_low_ticks, 0.5, *(1 - expected_low_ticks)] + ) + basic_needed = len(expected_ticks) + loc = mticker.LogitLocator(nbins=100) + minor_loc = mticker.LogitLocator(nbins=100, minor=True) + for nbins in range(basic_needed, 2, -1): + loc.set_params(nbins=nbins) + minor_loc.set_params(nbins=nbins) + major_ticks = loc.tick_values(*lims) + minor_ticks = minor_loc.tick_values(*lims) + if len(major_ticks) >= len(expected_ticks): + # no subsample, we must have a lot of minors ticks + assert (len(major_ticks) - 1) * 5 < len(minor_ticks) + else: + # subsample + _LogitHelper.assert_almost_equal( + sorted([*major_ticks, *minor_ticks]), expected_ticks) + + def test_minor_attr(self): + loc = mticker.LogitLocator(nbins=100) + assert not loc.minor + loc.minor = True + assert loc.minor + loc.set_params(minor=False) + assert not loc.minor + + acceptable_vmin_vmax = [ + *(2.5 ** np.arange(-3, 0)), + *(1 - 2.5 ** np.arange(-3, 0)), + ] + + @pytest.mark.parametrize( + "lims", + [ + (a, b) + for (a, b) in itertools.product(acceptable_vmin_vmax, repeat=2) + if a != b + ], + ) + def test_nonsingular_ok(self, lims): + """ + Create logit locator, and test the nonsingular method for acceptable + value + """ + loc = mticker.LogitLocator() + lims2 = loc.nonsingular(*lims) + assert sorted(lims) == sorted(lims2) + + @pytest.mark.parametrize("okval", acceptable_vmin_vmax) + def test_nonsingular_nok(self, okval): + """ + Create logit locator, and test the nonsingular method for non + acceptable value + """ + loc = mticker.LogitLocator() + vmin, vmax = (-1, okval) + vmin2, vmax2 = loc.nonsingular(vmin, vmax) + assert vmax2 == vmax + assert 0 < vmin2 < vmax2 + vmin, vmax = (okval, 2) + vmin2, vmax2 = loc.nonsingular(vmin, vmax) + assert vmin2 == vmin + assert vmin2 < vmax2 < 1 + + +class TestFixedLocator: + def test_set_params(self): + """ + Create fixed locator with 5 nbins, and change it to something else. + See if change was successful. + Should not exception. + """ + fixed = mticker.FixedLocator(range(0, 24), nbins=5) + fixed.set_params(nbins=7) + assert fixed.nbins == 7 + + +class TestIndexLocator: + def test_set_params(self): + """ + Create index locator with 3 base, 4 offset. and change it to something + else. See if change was successful. + Should not exception. + """ + index = mticker.IndexLocator(base=3, offset=4) + index.set_params(base=7, offset=7) + assert index._base == 7 + assert index.offset == 7 + + +class TestSymmetricalLogLocator: + def test_set_params(self): + """ + Create symmetrical log locator with default subs =[1.0] numticks = 15, + and change it to something else. + See if change was successful. + Should not exception. + """ + sym = mticker.SymmetricalLogLocator(base=10, linthresh=1) + sym.set_params(subs=[2.0], numticks=8) + assert sym._subs == [2.0] + assert sym.numticks == 8 + + +class TestAsinhLocator: + def test_init(self): + lctr = mticker.AsinhLocator(linear_width=2.718, numticks=19) + assert lctr.linear_width == 2.718 + assert lctr.numticks == 19 + assert lctr.base == 10 + + def test_set_params(self): + lctr = mticker.AsinhLocator(linear_width=5, + numticks=17, symthresh=0.125, + base=4, subs=(2.5, 3.25)) + assert lctr.numticks == 17 + assert lctr.symthresh == 0.125 + assert lctr.base == 4 + assert lctr.subs == (2.5, 3.25) + + lctr.set_params(numticks=23) + assert lctr.numticks == 23 + lctr.set_params(None) + assert lctr.numticks == 23 + + lctr.set_params(symthresh=0.5) + assert lctr.symthresh == 0.5 + lctr.set_params(symthresh=None) + assert lctr.symthresh == 0.5 + + lctr.set_params(base=7) + assert lctr.base == 7 + lctr.set_params(base=None) + assert lctr.base == 7 + + lctr.set_params(subs=(2, 4.125)) + assert lctr.subs == (2, 4.125) + lctr.set_params(subs=None) + assert lctr.subs == (2, 4.125) + lctr.set_params(subs=[]) + assert lctr.subs is None + + def test_linear_values(self): + lctr = mticker.AsinhLocator(linear_width=100, numticks=11, base=0) + + assert_almost_equal(lctr.tick_values(-1, 1), + np.arange(-1, 1.01, 0.2)) + assert_almost_equal(lctr.tick_values(-0.1, 0.1), + np.arange(-0.1, 0.101, 0.02)) + assert_almost_equal(lctr.tick_values(-0.01, 0.01), + np.arange(-0.01, 0.0101, 0.002)) + + def test_wide_values(self): + lctr = mticker.AsinhLocator(linear_width=0.1, numticks=11, base=0) + + assert_almost_equal(lctr.tick_values(-100, 100), + [-100, -20, -5, -1, -0.2, + 0, 0.2, 1, 5, 20, 100]) + assert_almost_equal(lctr.tick_values(-1000, 1000), + [-1000, -100, -20, -3, -0.4, + 0, 0.4, 3, 20, 100, 1000]) + + def test_near_zero(self): + """Check that manually injected zero will supersede nearby tick""" + lctr = mticker.AsinhLocator(linear_width=100, numticks=3, base=0) + + assert_almost_equal(lctr.tick_values(-1.1, 0.9), [-1.0, 0.0, 0.9]) + + def test_fallback(self): + lctr = mticker.AsinhLocator(1.0, numticks=11) + + assert_almost_equal(lctr.tick_values(101, 102), + np.arange(101, 102.01, 0.1)) + + def test_symmetrizing(self): + class DummyAxis: + bounds = (-1, 1) + @classmethod + def get_view_interval(cls): return cls.bounds + + lctr = mticker.AsinhLocator(linear_width=1, numticks=3, + symthresh=0.25, base=0) + lctr.axis = DummyAxis + + DummyAxis.bounds = (-1, 2) + assert_almost_equal(lctr(), [-1, 0, 2]) + + DummyAxis.bounds = (-1, 0.9) + assert_almost_equal(lctr(), [-1, 0, 1]) + + DummyAxis.bounds = (-0.85, 1.05) + assert_almost_equal(lctr(), [-1, 0, 1]) + + DummyAxis.bounds = (1, 1.1) + assert_almost_equal(lctr(), [1, 1.05, 1.1]) + + def test_base_rounding(self): + lctr10 = mticker.AsinhLocator(linear_width=1, numticks=8, + base=10, subs=(1, 3, 5)) + assert_almost_equal(lctr10.tick_values(-110, 110), + [-500, -300, -100, -50, -30, -10, -5, -3, -1, + -0.5, -0.3, -0.1, 0, 0.1, 0.3, 0.5, + 1, 3, 5, 10, 30, 50, 100, 300, 500]) + + lctr5 = mticker.AsinhLocator(linear_width=1, numticks=20, base=5) + assert_almost_equal(lctr5.tick_values(-1050, 1050), + [-625, -125, -25, -5, -1, -0.2, 0, + 0.2, 1, 5, 25, 125, 625]) + + +class TestScalarFormatter: + offset_data = [ + (123, 189, 0), + (-189, -123, 0), + (12341, 12349, 12340), + (-12349, -12341, -12340), + (99999.5, 100010.5, 100000), + (-100010.5, -99999.5, -100000), + (99990.5, 100000.5, 100000), + (-100000.5, -99990.5, -100000), + (1233999, 1234001, 1234000), + (-1234001, -1233999, -1234000), + (1, 1, 1), + (123, 123, 0), + # Test cases courtesy of @WeatherGod + (.4538, .4578, .45), + (3789.12, 3783.1, 3780), + (45124.3, 45831.75, 45000), + (0.000721, 0.0007243, 0.00072), + (12592.82, 12591.43, 12590), + (9., 12., 0), + (900., 1200., 0), + (1900., 1200., 0), + (0.99, 1.01, 1), + (9.99, 10.01, 10), + (99.99, 100.01, 100), + (5.99, 6.01, 6), + (15.99, 16.01, 16), + (-0.452, 0.492, 0), + (-0.492, 0.492, 0), + (12331.4, 12350.5, 12300), + (-12335.3, 12335.3, 0), + ] + + use_offset_data = [True, False] + + useMathText_data = [True, False] + + # (sci_type, scilimits, lim, orderOfMag, fewticks) + scilimits_data = [ + (False, (0, 0), (10.0, 20.0), 0, False), + (True, (-2, 2), (-10, 20), 0, False), + (True, (-2, 2), (-20, 10), 0, False), + (True, (-2, 2), (-110, 120), 2, False), + (True, (-2, 2), (-120, 110), 2, False), + (True, (-2, 2), (-.001, 0.002), -3, False), + (True, (-7, 7), (0.18e10, 0.83e10), 9, True), + (True, (0, 0), (-1e5, 1e5), 5, False), + (True, (6, 6), (-1e5, 1e5), 6, False), + ] + + cursor_data = [ + [0., "0.000"], + [0.0123, "0.012"], + [0.123, "0.123"], + [1.23, "1.230"], + [12.3, "12.300"], + ] + + format_data = [ + (.1, "1e-1"), + (.11, "1.1e-1"), + (1e8, "1e8"), + (1.1e8, "1.1e8"), + ] + + @pytest.mark.parametrize('unicode_minus, result', + [(True, "\N{MINUS SIGN}1"), (False, "-1")]) + def test_unicode_minus(self, unicode_minus, result): + mpl.rcParams['axes.unicode_minus'] = unicode_minus + assert ( + plt.gca().xaxis.get_major_formatter().format_data_short(-1).strip() + == result) + + @pytest.mark.parametrize('left, right, offset', offset_data) + def test_offset_value(self, left, right, offset): + fig, ax = plt.subplots() + formatter = ax.xaxis.get_major_formatter() + + with (pytest.warns(UserWarning, match='Attempting to set identical') + if left == right else nullcontext()): + ax.set_xlim(left, right) + ax.xaxis._update_ticks() + assert formatter.offset == offset + + with (pytest.warns(UserWarning, match='Attempting to set identical') + if left == right else nullcontext()): + ax.set_xlim(right, left) + ax.xaxis._update_ticks() + assert formatter.offset == offset + + @pytest.mark.parametrize('use_offset', use_offset_data) + def test_use_offset(self, use_offset): + with mpl.rc_context({'axes.formatter.useoffset': use_offset}): + tmp_form = mticker.ScalarFormatter() + assert use_offset == tmp_form.get_useOffset() + assert tmp_form.offset == 0 + + @pytest.mark.parametrize('use_math_text', useMathText_data) + def test_useMathText(self, use_math_text): + with mpl.rc_context({'axes.formatter.use_mathtext': use_math_text}): + tmp_form = mticker.ScalarFormatter() + assert use_math_text == tmp_form.get_useMathText() + + def test_set_use_offset_float(self): + tmp_form = mticker.ScalarFormatter() + tmp_form.set_useOffset(0.5) + assert not tmp_form.get_useOffset() + assert tmp_form.offset == 0.5 + + def test_use_locale(self): + conv = locale.localeconv() + sep = conv['thousands_sep'] + if not sep or conv['grouping'][-1:] in ([], [locale.CHAR_MAX]): + pytest.skip('Locale does not apply grouping') # pragma: no cover + + with mpl.rc_context({'axes.formatter.use_locale': True}): + tmp_form = mticker.ScalarFormatter() + assert tmp_form.get_useLocale() + + tmp_form.create_dummy_axis() + tmp_form.axis.set_data_interval(0, 10) + tmp_form.set_locs([1, 2, 3]) + assert sep in tmp_form(1e9) + + @pytest.mark.parametrize( + 'sci_type, scilimits, lim, orderOfMag, fewticks', scilimits_data) + def test_scilimits(self, sci_type, scilimits, lim, orderOfMag, fewticks): + tmp_form = mticker.ScalarFormatter() + tmp_form.set_scientific(sci_type) + tmp_form.set_powerlimits(scilimits) + fig, ax = plt.subplots() + ax.yaxis.set_major_formatter(tmp_form) + ax.set_ylim(*lim) + if fewticks: + ax.yaxis.set_major_locator(mticker.MaxNLocator(4)) + + tmp_form.set_locs(ax.yaxis.get_majorticklocs()) + assert orderOfMag == tmp_form.orderOfMagnitude + + @pytest.mark.parametrize('value, expected', format_data) + def test_format_data(self, value, expected): + mpl.rcParams['axes.unicode_minus'] = False + sf = mticker.ScalarFormatter() + assert sf.format_data(value) == expected + + @pytest.mark.parametrize('data, expected', cursor_data) + def test_cursor_precision(self, data, expected): + fig, ax = plt.subplots() + ax.set_xlim(-1, 1) # Pointing precision of 0.001. + fmt = ax.xaxis.get_major_formatter().format_data_short + assert fmt(data) == expected + + @pytest.mark.parametrize('data, expected', cursor_data) + def test_cursor_dummy_axis(self, data, expected): + # Issue #17624 + sf = mticker.ScalarFormatter() + sf.create_dummy_axis() + sf.axis.set_view_interval(0, 10) + fmt = sf.format_data_short + assert fmt(data) == expected + assert sf.axis.get_tick_space() == 9 + assert sf.axis.get_minpos() == 0 + + def test_mathtext_ticks(self): + mpl.rcParams.update({ + 'font.family': 'serif', + 'font.serif': 'cmr10', + 'axes.formatter.use_mathtext': False + }) + + with pytest.warns(UserWarning, match='cmr10 font should ideally'): + fig, ax = plt.subplots() + ax.set_xticks([-1, 0, 1]) + fig.canvas.draw() + + def test_cmr10_substitutions(self, caplog): + mpl.rcParams.update({ + 'font.family': 'cmr10', + 'mathtext.fontset': 'cm', + 'axes.formatter.use_mathtext': True, + }) + + # Test that it does not log a warning about missing glyphs. + with caplog.at_level(logging.WARNING, logger='matplotlib.mathtext'): + fig, ax = plt.subplots() + ax.plot([-0.03, 0.05], [40, 0.05]) + ax.set_yscale('log') + yticks = [0.02, 0.3, 4, 50] + formatter = mticker.LogFormatterSciNotation() + ax.set_yticks(yticks, map(formatter, yticks)) + fig.canvas.draw() + assert not caplog.text + + def test_empty_locs(self): + sf = mticker.ScalarFormatter() + sf.set_locs([]) + assert sf(0.5) == '' + + +class FakeAxis: + """Allow Formatter to be called without having a "full" plot set up.""" + def __init__(self, vmin=1, vmax=10): + self.vmin = vmin + self.vmax = vmax + + def get_view_interval(self): + return self.vmin, self.vmax + + +class TestLogFormatterExponent: + param_data = [ + (True, 4, np.arange(-3, 4.0), np.arange(-3, 4.0), + ['-3', '-2', '-1', '0', '1', '2', '3']), + # With labelOnlyBase=False, non-integer powers should be nicely + # formatted. + (False, 10, np.array([0.1, 0.00001, np.pi, 0.2, -0.2, -0.00001]), + range(6), ['0.1', '1e-05', '3.14', '0.2', '-0.2', '-1e-05']), + (False, 50, np.array([3, 5, 12, 42], dtype=float), range(6), + ['3', '5', '12', '42']), + ] + + base_data = [2.0, 5.0, 10.0, np.pi, np.e] + + @pytest.mark.parametrize( + 'labelOnlyBase, exponent, locs, positions, expected', param_data) + @pytest.mark.parametrize('base', base_data) + def test_basic(self, labelOnlyBase, base, exponent, locs, positions, + expected): + formatter = mticker.LogFormatterExponent(base=base, + labelOnlyBase=labelOnlyBase) + formatter.axis = FakeAxis(1, base**exponent) + vals = base**locs + labels = [formatter(x, pos) for (x, pos) in zip(vals, positions)] + expected = [label.replace('-', '\N{Minus Sign}') for label in expected] + assert labels == expected + + def test_blank(self): + # Should be a blank string for non-integer powers if labelOnlyBase=True + formatter = mticker.LogFormatterExponent(base=10, labelOnlyBase=True) + formatter.axis = FakeAxis() + assert formatter(10**0.1) == '' + + +class TestLogFormatterMathtext: + fmt = mticker.LogFormatterMathtext() + test_data = [ + (0, 1, '$\\mathdefault{10^{0}}$'), + (0, 1e-2, '$\\mathdefault{10^{-2}}$'), + (0, 1e2, '$\\mathdefault{10^{2}}$'), + (3, 1, '$\\mathdefault{1}$'), + (3, 1e-2, '$\\mathdefault{0.01}$'), + (3, 1e2, '$\\mathdefault{100}$'), + (3, 1e-3, '$\\mathdefault{10^{-3}}$'), + (3, 1e3, '$\\mathdefault{10^{3}}$'), + ] + + @pytest.mark.parametrize('min_exponent, value, expected', test_data) + def test_min_exponent(self, min_exponent, value, expected): + with mpl.rc_context({'axes.formatter.min_exponent': min_exponent}): + assert self.fmt(value) == expected + + +class TestLogFormatterSciNotation: + test_data = [ + (2, 0.03125, '$\\mathdefault{2^{-5}}$'), + (2, 1, '$\\mathdefault{2^{0}}$'), + (2, 32, '$\\mathdefault{2^{5}}$'), + (2, 0.0375, '$\\mathdefault{1.2\\times2^{-5}}$'), + (2, 1.2, '$\\mathdefault{1.2\\times2^{0}}$'), + (2, 38.4, '$\\mathdefault{1.2\\times2^{5}}$'), + (10, -1, '$\\mathdefault{-10^{0}}$'), + (10, 1e-05, '$\\mathdefault{10^{-5}}$'), + (10, 1, '$\\mathdefault{10^{0}}$'), + (10, 100000, '$\\mathdefault{10^{5}}$'), + (10, 2e-05, '$\\mathdefault{2\\times10^{-5}}$'), + (10, 2, '$\\mathdefault{2\\times10^{0}}$'), + (10, 200000, '$\\mathdefault{2\\times10^{5}}$'), + (10, 5e-05, '$\\mathdefault{5\\times10^{-5}}$'), + (10, 5, '$\\mathdefault{5\\times10^{0}}$'), + (10, 500000, '$\\mathdefault{5\\times10^{5}}$'), + ] + + @mpl.style.context('default') + @pytest.mark.parametrize('base, value, expected', test_data) + def test_basic(self, base, value, expected): + formatter = mticker.LogFormatterSciNotation(base=base) + formatter.sublabel = {1, 2, 5, 1.2} + with mpl.rc_context({'text.usetex': False}): + assert formatter(value) == expected + + +class TestLogFormatter: + pprint_data = [ + (3.141592654e-05, 0.001, '3.142e-5'), + (0.0003141592654, 0.001, '3.142e-4'), + (0.003141592654, 0.001, '3.142e-3'), + (0.03141592654, 0.001, '3.142e-2'), + (0.3141592654, 0.001, '3.142e-1'), + (3.141592654, 0.001, '3.142'), + (31.41592654, 0.001, '3.142e1'), + (314.1592654, 0.001, '3.142e2'), + (3141.592654, 0.001, '3.142e3'), + (31415.92654, 0.001, '3.142e4'), + (314159.2654, 0.001, '3.142e5'), + (1e-05, 0.001, '1e-5'), + (0.0001, 0.001, '1e-4'), + (0.001, 0.001, '1e-3'), + (0.01, 0.001, '1e-2'), + (0.1, 0.001, '1e-1'), + (1, 0.001, '1'), + (10, 0.001, '10'), + (100, 0.001, '100'), + (1000, 0.001, '1000'), + (10000, 0.001, '1e4'), + (100000, 0.001, '1e5'), + (3.141592654e-05, 0.015, '0'), + (0.0003141592654, 0.015, '0'), + (0.003141592654, 0.015, '0.003'), + (0.03141592654, 0.015, '0.031'), + (0.3141592654, 0.015, '0.314'), + (3.141592654, 0.015, '3.142'), + (31.41592654, 0.015, '31.416'), + (314.1592654, 0.015, '314.159'), + (3141.592654, 0.015, '3141.593'), + (31415.92654, 0.015, '31415.927'), + (314159.2654, 0.015, '314159.265'), + (1e-05, 0.015, '0'), + (0.0001, 0.015, '0'), + (0.001, 0.015, '0.001'), + (0.01, 0.015, '0.01'), + (0.1, 0.015, '0.1'), + (1, 0.015, '1'), + (10, 0.015, '10'), + (100, 0.015, '100'), + (1000, 0.015, '1000'), + (10000, 0.015, '10000'), + (100000, 0.015, '100000'), + (3.141592654e-05, 0.5, '0'), + (0.0003141592654, 0.5, '0'), + (0.003141592654, 0.5, '0.003'), + (0.03141592654, 0.5, '0.031'), + (0.3141592654, 0.5, '0.314'), + (3.141592654, 0.5, '3.142'), + (31.41592654, 0.5, '31.416'), + (314.1592654, 0.5, '314.159'), + (3141.592654, 0.5, '3141.593'), + (31415.92654, 0.5, '31415.927'), + (314159.2654, 0.5, '314159.265'), + (1e-05, 0.5, '0'), + (0.0001, 0.5, '0'), + (0.001, 0.5, '0.001'), + (0.01, 0.5, '0.01'), + (0.1, 0.5, '0.1'), + (1, 0.5, '1'), + (10, 0.5, '10'), + (100, 0.5, '100'), + (1000, 0.5, '1000'), + (10000, 0.5, '10000'), + (100000, 0.5, '100000'), + (3.141592654e-05, 5, '0'), + (0.0003141592654, 5, '0'), + (0.003141592654, 5, '0'), + (0.03141592654, 5, '0.03'), + (0.3141592654, 5, '0.31'), + (3.141592654, 5, '3.14'), + (31.41592654, 5, '31.42'), + (314.1592654, 5, '314.16'), + (3141.592654, 5, '3141.59'), + (31415.92654, 5, '31415.93'), + (314159.2654, 5, '314159.27'), + (1e-05, 5, '0'), + (0.0001, 5, '0'), + (0.001, 5, '0'), + (0.01, 5, '0.01'), + (0.1, 5, '0.1'), + (1, 5, '1'), + (10, 5, '10'), + (100, 5, '100'), + (1000, 5, '1000'), + (10000, 5, '10000'), + (100000, 5, '100000'), + (3.141592654e-05, 100, '0'), + (0.0003141592654, 100, '0'), + (0.003141592654, 100, '0'), + (0.03141592654, 100, '0'), + (0.3141592654, 100, '0.3'), + (3.141592654, 100, '3.1'), + (31.41592654, 100, '31.4'), + (314.1592654, 100, '314.2'), + (3141.592654, 100, '3141.6'), + (31415.92654, 100, '31415.9'), + (314159.2654, 100, '314159.3'), + (1e-05, 100, '0'), + (0.0001, 100, '0'), + (0.001, 100, '0'), + (0.01, 100, '0'), + (0.1, 100, '0.1'), + (1, 100, '1'), + (10, 100, '10'), + (100, 100, '100'), + (1000, 100, '1000'), + (10000, 100, '10000'), + (100000, 100, '100000'), + (3.141592654e-05, 1000000.0, '3.1e-5'), + (0.0003141592654, 1000000.0, '3.1e-4'), + (0.003141592654, 1000000.0, '3.1e-3'), + (0.03141592654, 1000000.0, '3.1e-2'), + (0.3141592654, 1000000.0, '3.1e-1'), + (3.141592654, 1000000.0, '3.1'), + (31.41592654, 1000000.0, '3.1e1'), + (314.1592654, 1000000.0, '3.1e2'), + (3141.592654, 1000000.0, '3.1e3'), + (31415.92654, 1000000.0, '3.1e4'), + (314159.2654, 1000000.0, '3.1e5'), + (1e-05, 1000000.0, '1e-5'), + (0.0001, 1000000.0, '1e-4'), + (0.001, 1000000.0, '1e-3'), + (0.01, 1000000.0, '1e-2'), + (0.1, 1000000.0, '1e-1'), + (1, 1000000.0, '1'), + (10, 1000000.0, '10'), + (100, 1000000.0, '100'), + (1000, 1000000.0, '1000'), + (10000, 1000000.0, '1e4'), + (100000, 1000000.0, '1e5'), + ] + + @pytest.mark.parametrize('value, domain, expected', pprint_data) + def test_pprint(self, value, domain, expected): + fmt = mticker.LogFormatter() + label = fmt._pprint_val(value, domain) + assert label == expected + + def _sub_labels(self, axis, subs=()): + """Test whether locator marks subs to be labeled.""" + fmt = axis.get_minor_formatter() + minor_tlocs = axis.get_minorticklocs() + fmt.set_locs(minor_tlocs) + coefs = minor_tlocs / 10**(np.floor(np.log10(minor_tlocs))) + label_expected = [round(c) in subs for c in coefs] + label_test = [fmt(x) != '' for x in minor_tlocs] + assert label_test == label_expected + + @mpl.style.context('default') + def test_sublabel(self): + # test label locator + fig, ax = plt.subplots() + ax.set_xscale('log') + ax.xaxis.set_major_locator(mticker.LogLocator(base=10, subs=[])) + ax.xaxis.set_minor_locator(mticker.LogLocator(base=10, + subs=np.arange(2, 10))) + ax.xaxis.set_major_formatter(mticker.LogFormatter(labelOnlyBase=True)) + ax.xaxis.set_minor_formatter(mticker.LogFormatter(labelOnlyBase=False)) + # axis range above 3 decades, only bases are labeled + ax.set_xlim(1, 1e4) + fmt = ax.xaxis.get_major_formatter() + fmt.set_locs(ax.xaxis.get_majorticklocs()) + show_major_labels = [fmt(x) != '' + for x in ax.xaxis.get_majorticklocs()] + assert np.all(show_major_labels) + self._sub_labels(ax.xaxis, subs=[]) + + # For the next two, if the numdec threshold in LogFormatter.set_locs + # were 3, then the label sub would be 3 for 2-3 decades and (2, 5) + # for 1-2 decades. With a threshold of 1, subs are not labeled. + # axis range at 2 to 3 decades + ax.set_xlim(1, 800) + self._sub_labels(ax.xaxis, subs=[]) + + # axis range at 1 to 2 decades + ax.set_xlim(1, 80) + self._sub_labels(ax.xaxis, subs=[]) + + # axis range at 0.4 to 1 decades, label subs 2, 3, 4, 6 + ax.set_xlim(1, 8) + self._sub_labels(ax.xaxis, subs=[2, 3, 4, 6]) + + # axis range at 0 to 0.4 decades, label all + ax.set_xlim(0.5, 0.9) + self._sub_labels(ax.xaxis, subs=np.arange(2, 10, dtype=int)) + + @pytest.mark.parametrize('val', [1, 10, 100, 1000]) + def test_LogFormatter_call(self, val): + # test _num_to_string method used in __call__ + temp_lf = mticker.LogFormatter() + temp_lf.axis = FakeAxis() + assert temp_lf(val) == str(val) + + @pytest.mark.parametrize('val', [1e-323, 2e-323, 10e-323, 11e-323]) + def test_LogFormatter_call_tiny(self, val): + # test coeff computation in __call__ + temp_lf = mticker.LogFormatter() + temp_lf.axis = FakeAxis() + temp_lf(val) + + +class TestLogitFormatter: + @staticmethod + def logit_deformatter(string): + r""" + Parser to convert string as r'$\mathdefault{1.41\cdot10^{-4}}$' in + float 1.41e-4, as '0.5' or as r'$\mathdefault{\frac{1}{2}}$' in float + 0.5, + """ + match = re.match( + r"[^\d]*" + r"(?P1-)?" + r"(?P\d*\.?\d*)?" + r"(?:\\cdot)?" + r"(?:10\^\{(?P-?\d*)})?" + r"[^\d]*$", + string, + ) + if match: + comp = match["comp"] is not None + mantissa = float(match["mant"]) if match["mant"] else 1 + expo = int(match["expo"]) if match["expo"] is not None else 0 + value = mantissa * 10 ** expo + if match["mant"] or match["expo"] is not None: + if comp: + return 1 - value + return value + match = re.match( + r"[^\d]*\\frac\{(?P\d+)\}\{(?P\d+)\}[^\d]*$", string + ) + if match: + num, deno = float(match["num"]), float(match["deno"]) + return num / deno + raise ValueError("Not formatted by LogitFormatter") + + @pytest.mark.parametrize( + "fx, x", + [ + (r"STUFF0.41OTHERSTUFF", 0.41), + (r"STUFF1.41\cdot10^{-2}OTHERSTUFF", 1.41e-2), + (r"STUFF1-0.41OTHERSTUFF", 1 - 0.41), + (r"STUFF1-1.41\cdot10^{-2}OTHERSTUFF", 1 - 1.41e-2), + (r"STUFF", None), + (r"STUFF12.4e-3OTHERSTUFF", None), + ], + ) + def test_logit_deformater(self, fx, x): + if x is None: + with pytest.raises(ValueError): + TestLogitFormatter.logit_deformatter(fx) + else: + y = TestLogitFormatter.logit_deformatter(fx) + assert _LogitHelper.isclose(x, y) + + decade_test = sorted( + [10 ** (-i) for i in range(1, 10)] + + [1 - 10 ** (-i) for i in range(1, 10)] + + [1 / 2] + ) + + @pytest.mark.parametrize("x", decade_test) + def test_basic(self, x): + """ + Test the formatted value correspond to the value for ideal ticks in + logit space. + """ + formatter = mticker.LogitFormatter(use_overline=False) + formatter.set_locs(self.decade_test) + s = formatter(x) + x2 = TestLogitFormatter.logit_deformatter(s) + assert _LogitHelper.isclose(x, x2) + + @pytest.mark.parametrize("x", (-1, -0.5, -0.1, 1.1, 1.5, 2)) + def test_invalid(self, x): + """ + Test that invalid value are formatted with empty string without + raising exception. + """ + formatter = mticker.LogitFormatter(use_overline=False) + formatter.set_locs(self.decade_test) + s = formatter(x) + assert s == "" + + @pytest.mark.parametrize("x", 1 / (1 + np.exp(-np.linspace(-7, 7, 10)))) + def test_variablelength(self, x): + """ + The format length should change depending on the neighbor labels. + """ + formatter = mticker.LogitFormatter(use_overline=False) + for N in (10, 20, 50, 100, 200, 1000, 2000, 5000, 10000): + if x + 1 / N < 1: + formatter.set_locs([x - 1 / N, x, x + 1 / N]) + sx = formatter(x) + sx1 = formatter(x + 1 / N) + d = ( + TestLogitFormatter.logit_deformatter(sx1) + - TestLogitFormatter.logit_deformatter(sx) + ) + assert 0 < d < 2 / N + + lims_minor_major = [ + (True, (5e-8, 1 - 5e-8), ((25, False), (75, False))), + (True, (5e-5, 1 - 5e-5), ((25, False), (75, True))), + (True, (5e-2, 1 - 5e-2), ((25, True), (75, True))), + (False, (0.75, 0.76, 0.77), ((7, True), (25, True), (75, True))), + ] + + @pytest.mark.parametrize("method, lims, cases", lims_minor_major) + def test_minor_vs_major(self, method, lims, cases): + """ + Test minor/major displays. + """ + + if method: + min_loc = mticker.LogitLocator(minor=True) + ticks = min_loc.tick_values(*lims) + else: + ticks = np.array(lims) + min_form = mticker.LogitFormatter(minor=True) + for threshold, has_minor in cases: + min_form.set_minor_threshold(threshold) + formatted = min_form.format_ticks(ticks) + labelled = [f for f in formatted if len(f) > 0] + if has_minor: + assert len(labelled) > 0, (threshold, has_minor) + else: + assert len(labelled) == 0, (threshold, has_minor) + + def test_minor_number(self): + """ + Test the parameter minor_number + """ + min_loc = mticker.LogitLocator(minor=True) + min_form = mticker.LogitFormatter(minor=True) + ticks = min_loc.tick_values(5e-2, 1 - 5e-2) + for minor_number in (2, 4, 8, 16): + min_form.set_minor_number(minor_number) + formatted = min_form.format_ticks(ticks) + labelled = [f for f in formatted if len(f) > 0] + assert len(labelled) == minor_number + + def test_use_overline(self): + """ + Test the parameter use_overline + """ + x = 1 - 1e-2 + fx1 = r"$\mathdefault{1-10^{-2}}$" + fx2 = r"$\mathdefault{\overline{10^{-2}}}$" + form = mticker.LogitFormatter(use_overline=False) + assert form(x) == fx1 + form.use_overline(True) + assert form(x) == fx2 + form.use_overline(False) + assert form(x) == fx1 + + def test_one_half(self): + """ + Test the parameter one_half + """ + form = mticker.LogitFormatter() + assert r"\frac{1}{2}" in form(1/2) + form.set_one_half("1/2") + assert "1/2" in form(1/2) + form.set_one_half("one half") + assert "one half" in form(1/2) + + @pytest.mark.parametrize("N", (100, 253, 754)) + def test_format_data_short(self, N): + locs = np.linspace(0, 1, N)[1:-1] + form = mticker.LogitFormatter() + for x in locs: + fx = form.format_data_short(x) + if fx.startswith("1-"): + x2 = 1 - float(fx[2:]) + else: + x2 = float(fx) + assert abs(x - x2) < 1 / N + + +class TestFormatStrFormatter: + def test_basic(self): + # test % style formatter + tmp_form = mticker.FormatStrFormatter('%05d') + assert '00002' == tmp_form(2) + + +class TestStrMethodFormatter: + test_data = [ + ('{x:05d}', (2,), '00002'), + ('{x:03d}-{pos:02d}', (2, 1), '002-01'), + ] + + @pytest.mark.parametrize('format, input, expected', test_data) + def test_basic(self, format, input, expected): + fmt = mticker.StrMethodFormatter(format) + assert fmt(*input) == expected + + +class TestEngFormatter: + # (unicode_minus, input, expected) where ''expected'' corresponds to the + # outputs respectively returned when (places=None, places=0, places=2) + # unicode_minus is a boolean value for the rcParam['axes.unicode_minus'] + raw_format_data = [ + (False, -1234.56789, ('-1.23457 k', '-1 k', '-1.23 k')), + (True, -1234.56789, ('\N{MINUS SIGN}1.23457 k', '\N{MINUS SIGN}1 k', + '\N{MINUS SIGN}1.23 k')), + (False, -1.23456789, ('-1.23457', '-1', '-1.23')), + (True, -1.23456789, ('\N{MINUS SIGN}1.23457', '\N{MINUS SIGN}1', + '\N{MINUS SIGN}1.23')), + (False, -0.123456789, ('-123.457 m', '-123 m', '-123.46 m')), + (True, -0.123456789, ('\N{MINUS SIGN}123.457 m', '\N{MINUS SIGN}123 m', + '\N{MINUS SIGN}123.46 m')), + (False, -0.00123456789, ('-1.23457 m', '-1 m', '-1.23 m')), + (True, -0.00123456789, ('\N{MINUS SIGN}1.23457 m', '\N{MINUS SIGN}1 m', + '\N{MINUS SIGN}1.23 m')), + (True, -0.0, ('0', '0', '0.00')), + (True, -0, ('0', '0', '0.00')), + (True, 0, ('0', '0', '0.00')), + (True, 1.23456789e-6, ('1.23457 µ', '1 µ', '1.23 µ')), + (True, 0.123456789, ('123.457 m', '123 m', '123.46 m')), + (True, 0.1, ('100 m', '100 m', '100.00 m')), + (True, 1, ('1', '1', '1.00')), + (True, 1.23456789, ('1.23457', '1', '1.23')), + # places=0: corner-case rounding + (True, 999.9, ('999.9', '1 k', '999.90')), + # corner-case rounding for all + (True, 999.9999, ('1 k', '1 k', '1.00 k')), + # negative corner-case + (False, -999.9999, ('-1 k', '-1 k', '-1.00 k')), + (True, -999.9999, ('\N{MINUS SIGN}1 k', '\N{MINUS SIGN}1 k', + '\N{MINUS SIGN}1.00 k')), + (True, 1000, ('1 k', '1 k', '1.00 k')), + (True, 1001, ('1.001 k', '1 k', '1.00 k')), + (True, 100001, ('100.001 k', '100 k', '100.00 k')), + (True, 987654.321, ('987.654 k', '988 k', '987.65 k')), + # OoR value (> 1000 Y) + (True, 1.23e27, ('1230 Y', '1230 Y', '1230.00 Y')) + ] + + @pytest.mark.parametrize('unicode_minus, input, expected', raw_format_data) + def test_params(self, unicode_minus, input, expected): + """ + Test the formatting of EngFormatter for various values of the 'places' + argument, in several cases: + + 0. without a unit symbol but with a (default) space separator; + 1. with both a unit symbol and a (default) space separator; + 2. with both a unit symbol and some non default separators; + 3. without a unit symbol but with some non default separators. + + Note that cases 2. and 3. are looped over several separator strings. + """ + + plt.rcParams['axes.unicode_minus'] = unicode_minus + UNIT = 's' # seconds + DIGITS = '0123456789' # %timeit showed 10-20% faster search than set + + # Case 0: unit='' (default) and sep=' ' (default). + # 'expected' already corresponds to this reference case. + exp_outputs = expected + formatters = ( + mticker.EngFormatter(), # places=None (default) + mticker.EngFormatter(places=0), + mticker.EngFormatter(places=2) + ) + for _formatter, _exp_output in zip(formatters, exp_outputs): + assert _formatter(input) == _exp_output + + # Case 1: unit=UNIT and sep=' ' (default). + # Append a unit symbol to the reference case. + # Beware of the values in [1, 1000), where there is no prefix! + exp_outputs = (_s + " " + UNIT if _s[-1] in DIGITS # case w/o prefix + else _s + UNIT for _s in expected) + formatters = ( + mticker.EngFormatter(unit=UNIT), # places=None (default) + mticker.EngFormatter(unit=UNIT, places=0), + mticker.EngFormatter(unit=UNIT, places=2) + ) + for _formatter, _exp_output in zip(formatters, exp_outputs): + assert _formatter(input) == _exp_output + + # Test several non default separators: no separator, a narrow + # no-break space (Unicode character) and an extravagant string. + for _sep in ("", "\N{NARROW NO-BREAK SPACE}", "@_@"): + # Case 2: unit=UNIT and sep=_sep. + # Replace the default space separator from the reference case + # with the tested one `_sep` and append a unit symbol to it. + exp_outputs = (_s + _sep + UNIT if _s[-1] in DIGITS # no prefix + else _s.replace(" ", _sep) + UNIT + for _s in expected) + formatters = ( + mticker.EngFormatter(unit=UNIT, sep=_sep), # places=None + mticker.EngFormatter(unit=UNIT, places=0, sep=_sep), + mticker.EngFormatter(unit=UNIT, places=2, sep=_sep) + ) + for _formatter, _exp_output in zip(formatters, exp_outputs): + assert _formatter(input) == _exp_output + + # Case 3: unit='' (default) and sep=_sep. + # Replace the default space separator from the reference case + # with the tested one `_sep`. Reference case is already unitless. + exp_outputs = (_s.replace(" ", _sep) for _s in expected) + formatters = ( + mticker.EngFormatter(sep=_sep), # places=None (default) + mticker.EngFormatter(places=0, sep=_sep), + mticker.EngFormatter(places=2, sep=_sep) + ) + for _formatter, _exp_output in zip(formatters, exp_outputs): + assert _formatter(input) == _exp_output + + +def test_engformatter_usetex_useMathText(): + fig, ax = plt.subplots() + ax.plot([0, 500, 1000], [0, 500, 1000]) + ax.set_xticks([0, 500, 1000]) + for formatter in (mticker.EngFormatter(usetex=True), + mticker.EngFormatter(useMathText=True)): + ax.xaxis.set_major_formatter(formatter) + fig.canvas.draw() + x_tick_label_text = [labl.get_text() for labl in ax.get_xticklabels()] + # Checking if the dollar `$` signs have been inserted around numbers + # in tick labels. + assert x_tick_label_text == ['$0$', '$500$', '$1$ k'] + + +class TestPercentFormatter: + percent_data = [ + # Check explicitly set decimals over different intervals and values + (100, 0, '%', 120, 100, '120%'), + (100, 0, '%', 100, 90, '100%'), + (100, 0, '%', 90, 50, '90%'), + (100, 0, '%', -1.7, 40, '-2%'), + (100, 1, '%', 90.0, 100, '90.0%'), + (100, 1, '%', 80.1, 90, '80.1%'), + (100, 1, '%', 70.23, 50, '70.2%'), + # 60.554 instead of 60.55: see https://bugs.python.org/issue5118 + (100, 1, '%', -60.554, 40, '-60.6%'), + # Check auto decimals over different intervals and values + (100, None, '%', 95, 1, '95.00%'), + (1.0, None, '%', 3, 6, '300%'), + (17.0, None, '%', 1, 8.5, '6%'), + (17.0, None, '%', 1, 8.4, '5.9%'), + (5, None, '%', -100, 0.000001, '-2000.00000%'), + # Check percent symbol + (1.0, 2, None, 1.2, 100, '120.00'), + (75, 3, '', 50, 100, '66.667'), + (42, None, '^^Foobar$$', 21, 12, '50.0^^Foobar$$'), + ] + + percent_ids = [ + # Check explicitly set decimals over different intervals and values + 'decimals=0, x>100%', + 'decimals=0, x=100%', + 'decimals=0, x<100%', + 'decimals=0, x<0%', + 'decimals=1, x>100%', + 'decimals=1, x=100%', + 'decimals=1, x<100%', + 'decimals=1, x<0%', + # Check auto decimals over different intervals and values + 'autodecimal, x<100%, display_range=1', + 'autodecimal, x>100%, display_range=6 (custom xmax test)', + 'autodecimal, x<100%, display_range=8.5 (autodecimal test 1)', + 'autodecimal, x<100%, display_range=8.4 (autodecimal test 2)', + 'autodecimal, x<-100%, display_range=1e-6 (tiny display range)', + # Check percent symbol + 'None as percent symbol', + 'Empty percent symbol', + 'Custom percent symbol', + ] + + latex_data = [ + (False, False, r'50\{t}%'), + (False, True, r'50\\\{t\}\%'), + (True, False, r'50\{t}%'), + (True, True, r'50\{t}%'), + ] + + @pytest.mark.parametrize( + 'xmax, decimals, symbol, x, display_range, expected', + percent_data, ids=percent_ids) + def test_basic(self, xmax, decimals, symbol, + x, display_range, expected): + formatter = mticker.PercentFormatter(xmax, decimals, symbol) + with mpl.rc_context(rc={'text.usetex': False}): + assert formatter.format_pct(x, display_range) == expected + + @pytest.mark.parametrize('is_latex, usetex, expected', latex_data) + def test_latex(self, is_latex, usetex, expected): + fmt = mticker.PercentFormatter(symbol='\\{t}%', is_latex=is_latex) + with mpl.rc_context(rc={'text.usetex': usetex}): + assert fmt.format_pct(50, 100) == expected + + +def test_majformatter_type(): + fig, ax = plt.subplots() + with pytest.raises(TypeError): + ax.xaxis.set_major_formatter(mticker.LogLocator()) + + +def test_minformatter_type(): + fig, ax = plt.subplots() + with pytest.raises(TypeError): + ax.xaxis.set_minor_formatter(mticker.LogLocator()) + + +def test_majlocator_type(): + fig, ax = plt.subplots() + with pytest.raises(TypeError): + ax.xaxis.set_major_locator(mticker.LogFormatter()) + + +def test_minlocator_type(): + fig, ax = plt.subplots() + with pytest.raises(TypeError): + ax.xaxis.set_minor_locator(mticker.LogFormatter()) + + +def test_minorticks_rc(): + fig = plt.figure() + + def minorticksubplot(xminor, yminor, i): + rc = {'xtick.minor.visible': xminor, + 'ytick.minor.visible': yminor} + with plt.rc_context(rc=rc): + ax = fig.add_subplot(2, 2, i) + + assert (len(ax.xaxis.get_minor_ticks()) > 0) == xminor + assert (len(ax.yaxis.get_minor_ticks()) > 0) == yminor + + minorticksubplot(False, False, 1) + minorticksubplot(True, False, 2) + minorticksubplot(False, True, 3) + minorticksubplot(True, True, 4) + + +@pytest.mark.parametrize('remove_overlapping_locs, expected_num', + ((True, 6), + (None, 6), # this tests the default + (False, 9))) +def test_remove_overlap(remove_overlapping_locs, expected_num): + t = np.arange("2018-11-03", "2018-11-06", dtype="datetime64") + x = np.ones(len(t)) + + fig, ax = plt.subplots() + ax.plot(t, x) + + ax.xaxis.set_major_locator(mpl.dates.DayLocator()) + ax.xaxis.set_major_formatter(mpl.dates.DateFormatter('\n%a')) + + ax.xaxis.set_minor_locator(mpl.dates.HourLocator((0, 6, 12, 18))) + ax.xaxis.set_minor_formatter(mpl.dates.DateFormatter('%H:%M')) + # force there to be extra ticks + ax.xaxis.get_minor_ticks(15) + if remove_overlapping_locs is not None: + ax.xaxis.remove_overlapping_locs = remove_overlapping_locs + + # check that getter/setter exists + current = ax.xaxis.remove_overlapping_locs + assert (current == ax.xaxis.get_remove_overlapping_locs()) + plt.setp(ax.xaxis, remove_overlapping_locs=current) + new = ax.xaxis.remove_overlapping_locs + assert (new == ax.xaxis.remove_overlapping_locs) + + # check that the accessors filter correctly + # this is the method that does the actual filtering + assert len(ax.xaxis.get_minorticklocs()) == expected_num + # these three are derivative + assert len(ax.xaxis.get_minor_ticks()) == expected_num + assert len(ax.xaxis.get_minorticklabels()) == expected_num + assert len(ax.xaxis.get_minorticklines()) == expected_num*2 + + +@pytest.mark.parametrize('sub', [ + ['hi', 'aardvark'], + np.zeros((2, 2))]) +def test_bad_locator_subs(sub): + ll = mticker.LogLocator() + with pytest.raises(ValueError): + ll.set_params(subs=sub) + + +@pytest.mark.parametrize('numticks', [1, 2, 3, 9]) +@mpl.style.context('default') +def test_small_range_loglocator(numticks): + ll = mticker.LogLocator() + ll.set_params(numticks=numticks) + for top in [5, 7, 9, 11, 15, 50, 100, 1000]: + ticks = ll.tick_values(.5, top) + assert (np.diff(np.log10(ll.tick_values(6, 150))) == 1).all() + + +def test_NullFormatter(): + formatter = mticker.NullFormatter() + assert formatter(1.0) == '' + assert formatter.format_data(1.0) == '' + assert formatter.format_data_short(1.0) == '' + + +@pytest.mark.parametrize('formatter', ( + mticker.FuncFormatter(lambda a: f'val: {a}'), + mticker.FixedFormatter(('foo', 'bar')))) +def test_set_offset_string(formatter): + assert formatter.get_offset() == '' + formatter.set_offset_string('mpl') + assert formatter.get_offset() == 'mpl' diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/test_units.py b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/test_units.py new file mode 100644 index 0000000000000000000000000000000000000000..d3b8c5a71643c0a95c7fcee0041ce9eb35822c2e --- /dev/null +++ b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/test_units.py @@ -0,0 +1,285 @@ +from datetime import datetime, timezone, timedelta +import platform +from unittest.mock import MagicMock + +import matplotlib.pyplot as plt +from matplotlib.testing.decorators import check_figures_equal, image_comparison +import matplotlib.units as munits +from matplotlib.category import UnitData +import numpy as np +import pytest + + +# Basic class that wraps numpy array and has units +class Quantity: + def __init__(self, data, units): + self.magnitude = data + self.units = units + + def to(self, new_units): + factors = {('hours', 'seconds'): 3600, ('minutes', 'hours'): 1 / 60, + ('minutes', 'seconds'): 60, ('feet', 'miles'): 1 / 5280., + ('feet', 'inches'): 12, ('miles', 'inches'): 12 * 5280} + if self.units != new_units: + mult = factors[self.units, new_units] + return Quantity(mult * self.magnitude, new_units) + else: + return Quantity(self.magnitude, self.units) + + def __copy__(self): + return Quantity(self.magnitude, self.units) + + def __getattr__(self, attr): + return getattr(self.magnitude, attr) + + def __getitem__(self, item): + if np.iterable(self.magnitude): + return Quantity(self.magnitude[item], self.units) + else: + return Quantity(self.magnitude, self.units) + + def __array__(self): + return np.asarray(self.magnitude) + + +@pytest.fixture +def quantity_converter(): + # Create an instance of the conversion interface and + # mock so we can check methods called + qc = munits.ConversionInterface() + + def convert(value, unit, axis): + if hasattr(value, 'units'): + return value.to(unit).magnitude + elif np.iterable(value): + try: + return [v.to(unit).magnitude for v in value] + except AttributeError: + return [Quantity(v, axis.get_units()).to(unit).magnitude + for v in value] + else: + return Quantity(value, axis.get_units()).to(unit).magnitude + + def default_units(value, axis): + if hasattr(value, 'units'): + return value.units + elif np.iterable(value): + for v in value: + if hasattr(v, 'units'): + return v.units + return None + + qc.convert = MagicMock(side_effect=convert) + qc.axisinfo = MagicMock(side_effect=lambda u, a: + munits.AxisInfo(label=u, default_limits=(0, 100))) + qc.default_units = MagicMock(side_effect=default_units) + return qc + + +# Tests that the conversion machinery works properly for classes that +# work as a facade over numpy arrays (like pint) +@image_comparison(['plot_pint.png'], style='mpl20', + tol=0 if platform.machine() == 'x86_64' else 0.01) +def test_numpy_facade(quantity_converter): + # use former defaults to match existing baseline image + plt.rcParams['axes.formatter.limits'] = -7, 7 + + # Register the class + munits.registry[Quantity] = quantity_converter + + # Simple test + y = Quantity(np.linspace(0, 30), 'miles') + x = Quantity(np.linspace(0, 5), 'hours') + + fig, ax = plt.subplots() + fig.subplots_adjust(left=0.15) # Make space for label + ax.plot(x, y, 'tab:blue') + ax.axhline(Quantity(26400, 'feet'), color='tab:red') + ax.axvline(Quantity(120, 'minutes'), color='tab:green') + ax.yaxis.set_units('inches') + ax.xaxis.set_units('seconds') + + assert quantity_converter.convert.called + assert quantity_converter.axisinfo.called + assert quantity_converter.default_units.called + + +# Tests gh-8908 +@image_comparison(['plot_masked_units.png'], remove_text=True, style='mpl20', + tol=0 if platform.machine() == 'x86_64' else 0.01) +def test_plot_masked_units(): + data = np.linspace(-5, 5) + data_masked = np.ma.array(data, mask=(data > -2) & (data < 2)) + data_masked_units = Quantity(data_masked, 'meters') + + fig, ax = plt.subplots() + ax.plot(data_masked_units) + + +def test_empty_set_limits_with_units(quantity_converter): + # Register the class + munits.registry[Quantity] = quantity_converter + + fig, ax = plt.subplots() + ax.set_xlim(Quantity(-1, 'meters'), Quantity(6, 'meters')) + ax.set_ylim(Quantity(-1, 'hours'), Quantity(16, 'hours')) + + +@image_comparison(['jpl_bar_units.png'], + savefig_kwarg={'dpi': 120}, style='mpl20') +def test_jpl_bar_units(): + import matplotlib.testing.jpl_units as units + units.register() + + day = units.Duration("ET", 24.0 * 60.0 * 60.0) + x = [0 * units.km, 1 * units.km, 2 * units.km] + w = [1 * day, 2 * day, 3 * day] + b = units.Epoch("ET", dt=datetime(2009, 4, 25)) + fig, ax = plt.subplots() + ax.bar(x, w, bottom=b) + ax.set_ylim([b - 1 * day, b + w[-1] + (1.001) * day]) + + +@image_comparison(['jpl_barh_units.png'], + savefig_kwarg={'dpi': 120}, style='mpl20') +def test_jpl_barh_units(): + import matplotlib.testing.jpl_units as units + units.register() + + day = units.Duration("ET", 24.0 * 60.0 * 60.0) + x = [0 * units.km, 1 * units.km, 2 * units.km] + w = [1 * day, 2 * day, 3 * day] + b = units.Epoch("ET", dt=datetime(2009, 4, 25)) + + fig, ax = plt.subplots() + ax.barh(x, w, left=b) + ax.set_xlim([b - 1 * day, b + w[-1] + (1.001) * day]) + + +def test_empty_arrays(): + # Check that plotting an empty array with a dtype works + plt.scatter(np.array([], dtype='datetime64[ns]'), np.array([])) + + +def test_scatter_element0_masked(): + times = np.arange('2005-02', '2005-03', dtype='datetime64[D]') + y = np.arange(len(times), dtype=float) + y[0] = np.nan + fig, ax = plt.subplots() + ax.scatter(times, y) + fig.canvas.draw() + + +def test_errorbar_mixed_units(): + x = np.arange(10) + y = [datetime(2020, 5, i * 2 + 1) for i in x] + fig, ax = plt.subplots() + ax.errorbar(x, y, timedelta(days=0.5)) + fig.canvas.draw() + + +@check_figures_equal(extensions=["png"]) +def test_subclass(fig_test, fig_ref): + class subdate(datetime): + pass + + fig_test.subplots().plot(subdate(2000, 1, 1), 0, "o") + fig_ref.subplots().plot(datetime(2000, 1, 1), 0, "o") + + +def test_shared_axis_quantity(quantity_converter): + munits.registry[Quantity] = quantity_converter + x = Quantity(np.linspace(0, 1, 10), "hours") + y1 = Quantity(np.linspace(1, 2, 10), "feet") + y2 = Quantity(np.linspace(3, 4, 10), "feet") + fig, (ax1, ax2) = plt.subplots(2, 1, sharex='all', sharey='all') + ax1.plot(x, y1) + ax2.plot(x, y2) + assert ax1.xaxis.get_units() == ax2.xaxis.get_units() == "hours" + assert ax2.yaxis.get_units() == ax2.yaxis.get_units() == "feet" + ax1.xaxis.set_units("seconds") + ax2.yaxis.set_units("inches") + assert ax1.xaxis.get_units() == ax2.xaxis.get_units() == "seconds" + assert ax1.yaxis.get_units() == ax2.yaxis.get_units() == "inches" + + +def test_shared_axis_datetime(): + # datetime uses dates.DateConverter + y1 = [datetime(2020, i, 1, tzinfo=timezone.utc) for i in range(1, 13)] + y2 = [datetime(2021, i, 1, tzinfo=timezone.utc) for i in range(1, 13)] + fig, (ax1, ax2) = plt.subplots(1, 2, sharey=True) + ax1.plot(y1) + ax2.plot(y2) + ax1.yaxis.set_units(timezone(timedelta(hours=5))) + assert ax2.yaxis.units == timezone(timedelta(hours=5)) + + +def test_shared_axis_categorical(): + # str uses category.StrCategoryConverter + d1 = {"a": 1, "b": 2} + d2 = {"a": 3, "b": 4} + fig, (ax1, ax2) = plt.subplots(1, 2, sharex=True, sharey=True) + ax1.plot(d1.keys(), d1.values()) + ax2.plot(d2.keys(), d2.values()) + ax1.xaxis.set_units(UnitData(["c", "d"])) + assert "c" in ax2.xaxis.get_units()._mapping.keys() + + +def test_empty_default_limits(quantity_converter): + munits.registry[Quantity] = quantity_converter + fig, ax1 = plt.subplots() + ax1.xaxis.update_units(Quantity([10], "miles")) + fig.draw_without_rendering() + assert ax1.get_xlim() == (0, 100) + ax1.yaxis.update_units(Quantity([10], "miles")) + fig.draw_without_rendering() + assert ax1.get_ylim() == (0, 100) + + fig, ax = plt.subplots() + ax.axhline(30) + ax.plot(Quantity(np.arange(0, 3), "miles"), + Quantity(np.arange(0, 6, 2), "feet")) + fig.draw_without_rendering() + assert ax.get_xlim() == (0, 2) + assert ax.get_ylim() == (0, 30) + + fig, ax = plt.subplots() + ax.axvline(30) + ax.plot(Quantity(np.arange(0, 3), "miles"), + Quantity(np.arange(0, 6, 2), "feet")) + fig.draw_without_rendering() + assert ax.get_xlim() == (0, 30) + assert ax.get_ylim() == (0, 4) + + fig, ax = plt.subplots() + ax.xaxis.update_units(Quantity([10], "miles")) + ax.axhline(30) + fig.draw_without_rendering() + assert ax.get_xlim() == (0, 100) + assert ax.get_ylim() == (28.5, 31.5) + + fig, ax = plt.subplots() + ax.yaxis.update_units(Quantity([10], "miles")) + ax.axvline(30) + fig.draw_without_rendering() + assert ax.get_ylim() == (0, 100) + assert ax.get_xlim() == (28.5, 31.5) + + +# test array-like objects... +class Kernel: + def __init__(self, array): + self._array = np.asanyarray(array) + + def __array__(self): + return self._array + + @property + def shape(self): + return self._array.shape + + +def test_plot_kernel(): + # just a smoketest that fail + kernel = Kernel([1, 2, 3, 4, 5]) + plt.plot(kernel) diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/test_usetex.py b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/test_usetex.py new file mode 100644 index 0000000000000000000000000000000000000000..0f01ebaffb56f2f5110c777c474e640f06e2b631 --- /dev/null +++ b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/test_usetex.py @@ -0,0 +1,155 @@ +from tempfile import TemporaryFile + +import numpy as np +import pytest + +import matplotlib as mpl +from matplotlib import dviread +from matplotlib.testing import _has_tex_package +from matplotlib.testing.decorators import check_figures_equal, image_comparison +from matplotlib.testing._markers import needs_usetex +import matplotlib.pyplot as plt + + +pytestmark = needs_usetex + + +@image_comparison( + baseline_images=['test_usetex'], + extensions=['pdf', 'png'], + style="mpl20") +def test_usetex(): + mpl.rcParams['text.usetex'] = True + fig, ax = plt.subplots() + kwargs = {"verticalalignment": "baseline", "size": 24, + "bbox": dict(pad=0, edgecolor="k", facecolor="none")} + ax.text(0.2, 0.7, + # the \LaTeX macro exercises character sizing and placement, + # \left[ ... \right\} draw some variable-height characters, + # \sqrt and \frac draw horizontal rules, \mathrm changes the font + r'\LaTeX\ $\left[\int\limits_e^{2e}' + r'\sqrt\frac{\log^3 x}{x}\,\mathrm{d}x \right\}$', + **kwargs) + ax.text(0.2, 0.3, "lg", **kwargs) + ax.text(0.4, 0.3, r"$\frac{1}{2}\pi$", **kwargs) + ax.text(0.6, 0.3, "$p^{3^A}$", **kwargs) + ax.text(0.8, 0.3, "$p_{3_2}$", **kwargs) + for x in {t.get_position()[0] for t in ax.texts}: + ax.axvline(x) + for y in {t.get_position()[1] for t in ax.texts}: + ax.axhline(y) + ax.set_axis_off() + + +@check_figures_equal() +def test_empty(fig_test, fig_ref): + mpl.rcParams['text.usetex'] = True + fig_test.text(.5, .5, "% a comment") + + +@check_figures_equal() +def test_unicode_minus(fig_test, fig_ref): + mpl.rcParams['text.usetex'] = True + fig_test.text(.5, .5, "$-$") + fig_ref.text(.5, .5, "\N{MINUS SIGN}") + + +def test_mathdefault(): + plt.rcParams["axes.formatter.use_mathtext"] = True + fig = plt.figure() + fig.add_subplot().set_xlim(-1, 1) + # Check that \mathdefault commands generated by tickers don't cause + # problems when later switching usetex on. + mpl.rcParams['text.usetex'] = True + fig.canvas.draw() + + +@image_comparison(['eqnarray.png']) +def test_multiline_eqnarray(): + text = ( + r'\begin{eqnarray*}' + r'foo\\' + r'bar\\' + r'baz\\' + r'\end{eqnarray*}' + ) + + fig = plt.figure(figsize=(1, 1)) + fig.text(0.5, 0.5, text, usetex=True, + horizontalalignment='center', verticalalignment='center') + + +@pytest.mark.parametrize("fontsize", [8, 10, 12]) +def test_minus_no_descent(fontsize): + # Test special-casing of minus descent in DviFont._height_depth_of, by + # checking that overdrawing a 1 and a -1 results in an overall height + # equivalent to drawing either of them separately. + mpl.style.use("mpl20") + mpl.rcParams['font.size'] = fontsize + heights = {} + fig = plt.figure() + for vals in [(1,), (-1,), (-1, 1)]: + fig.clear() + for x in vals: + fig.text(.5, .5, f"${x}$", usetex=True) + fig.canvas.draw() + # The following counts the number of non-fully-blank pixel rows. + heights[vals] = ((np.array(fig.canvas.buffer_rgba())[..., 0] != 255) + .any(axis=1).sum()) + assert len({*heights.values()}) == 1 + + +@pytest.mark.parametrize('pkg', ['xcolor', 'chemformula']) +def test_usetex_packages(pkg): + if not _has_tex_package(pkg): + pytest.skip(f'{pkg} is not available') + mpl.rcParams['text.usetex'] = True + + fig = plt.figure() + text = fig.text(0.5, 0.5, "Some text 0123456789") + fig.canvas.draw() + + mpl.rcParams['text.latex.preamble'] = ( + r'\PassOptionsToPackage{dvipsnames}{xcolor}\usepackage{%s}' % pkg) + fig = plt.figure() + text2 = fig.text(0.5, 0.5, "Some text 0123456789") + fig.canvas.draw() + np.testing.assert_array_equal(text2.get_window_extent(), + text.get_window_extent()) + + +@pytest.mark.parametrize( + "preamble", + [r"\usepackage[full]{textcomp}", r"\usepackage{underscore}"], +) +def test_latex_pkg_already_loaded(preamble): + plt.rcParams["text.latex.preamble"] = preamble + fig = plt.figure() + fig.text(.5, .5, "hello, world", usetex=True) + fig.canvas.draw() + + +def test_usetex_with_underscore(): + plt.rcParams["text.usetex"] = True + df = {"a_b": range(5)[::-1], "c": range(5)} + fig, ax = plt.subplots() + ax.plot("c", "a_b", data=df) + ax.legend() + ax.text(0, 0, "foo_bar", usetex=True) + plt.draw() + + +@pytest.mark.flaky(reruns=3) # Tends to hit a TeX cache lock on AppVeyor. +@pytest.mark.parametrize("fmt", ["pdf", "svg"]) +def test_missing_psfont(fmt, monkeypatch): + """An error is raised if a TeX font lacks a Type-1 equivalent""" + monkeypatch.setattr( + dviread.PsfontsMap, '__getitem__', + lambda self, k: dviread.PsFont( + texname=b'texfont', psname=b'Some Font', + effects=None, encoding=None, filename=None)) + mpl.rcParams['text.usetex'] = True + fig, ax = plt.subplots() + ax.text(0.5, 0.5, 'hello') + with TemporaryFile() as tmpfile, pytest.raises(ValueError): + fig.savefig(tmpfile, format=fmt) diff --git a/omnilmm/lib/python3.10/site-packages/matplotlib/tests/test_widgets.py b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/test_widgets.py new file mode 100644 index 0000000000000000000000000000000000000000..2f9572822f64b9bee385731e266fe8d1ab1931ce --- /dev/null +++ b/omnilmm/lib/python3.10/site-packages/matplotlib/tests/test_widgets.py @@ -0,0 +1,1729 @@ +import functools +import io +from unittest import mock + +from matplotlib._api.deprecation import MatplotlibDeprecationWarning +from matplotlib.backend_bases import MouseEvent +import matplotlib.colors as mcolors +import matplotlib.widgets as widgets +import matplotlib.pyplot as plt +from matplotlib.patches import Rectangle +from matplotlib.lines import Line2D +from matplotlib.testing.decorators import check_figures_equal, image_comparison +from matplotlib.testing.widgets import (click_and_drag, do_event, get_ax, + mock_event, noop) + +import numpy as np +from numpy.testing import assert_allclose + +import pytest + + +@pytest.fixture +def ax(): + return get_ax() + + +def test_save_blitted_widget_as_pdf(): + from matplotlib.widgets import CheckButtons, RadioButtons + from matplotlib.cbook import _get_running_interactive_framework + if _get_running_interactive_framework() not in ['headless', None]: + pytest.xfail("Callback exceptions are not raised otherwise.") + + fig, ax = plt.subplots( + nrows=2, ncols=2, figsize=(5, 2), width_ratios=[1, 2] + ) + default_rb = RadioButtons(ax[0, 0], ['Apples', 'Oranges']) + styled_rb = RadioButtons( + ax[0, 1], ['Apples', 'Oranges'], + label_props={'color': ['red', 'orange'], + 'fontsize': [16, 20]}, + radio_props={'edgecolor': ['red', 'orange'], + 'facecolor': ['mistyrose', 'peachpuff']} + ) + + default_cb = CheckButtons(ax[1, 0], ['Apples', 'Oranges'], + actives=[True, True]) + styled_cb = CheckButtons( + ax[1, 1], ['Apples', 'Oranges'], + actives=[True, True], + label_props={'color': ['red', 'orange'], + 'fontsize': [16, 20]}, + frame_props={'edgecolor': ['red', 'orange'], + 'facecolor': ['mistyrose', 'peachpuff']}, + check_props={'color': ['darkred', 'darkorange']} + ) + + ax[0, 0].set_title('Default') + ax[0, 1].set_title('Stylized') + # force an Agg render + fig.canvas.draw() + # force a pdf save + with io.BytesIO() as result_after: + fig.savefig(result_after, format='pdf') + + +@pytest.mark.parametrize('kwargs', [ + dict(), + dict(useblit=True, button=1), + dict(minspanx=10, minspany=10, spancoords='pixels'), + dict(props=dict(fill=True)), +]) +def test_rectangle_selector(ax, kwargs): + onselect = mock.Mock(spec=noop, return_value=None) + + tool = widgets.RectangleSelector(ax, onselect, **kwargs) + do_event(tool, 'press', xdata=100, ydata=100, button=1) + do_event(tool, 'onmove', xdata=199, ydata=199, button=1) + + # purposely drag outside of axis for release + do_event(tool, 'release', xdata=250, ydata=250, button=1) + + if kwargs.get('drawtype', None) not in ['line', 'none']: + assert_allclose(tool.geometry, + [[100., 100, 199, 199, 100], + [100, 199, 199, 100, 100]], + err_msg=tool.geometry) + + onselect.assert_called_once() + (epress, erelease), kwargs = onselect.call_args + assert epress.xdata == 100 + assert epress.ydata == 100 + assert erelease.xdata == 199 + assert erelease.ydata == 199 + assert kwargs == {} + + +@pytest.mark.parametrize('spancoords', ['data', 'pixels']) +@pytest.mark.parametrize('minspanx, x1', [[0, 10], [1, 10.5], [1, 11]]) +@pytest.mark.parametrize('minspany, y1', [[0, 10], [1, 10.5], [1, 11]]) +def test_rectangle_minspan(ax, spancoords, minspanx, x1, minspany, y1): + + onselect = mock.Mock(spec=noop, return_value=None) + + x0, y0 = (10, 10) + if spancoords == 'pixels': + minspanx, minspany = (ax.transData.transform((x1, y1)) - + ax.transData.transform((x0, y0))) + + tool = widgets.RectangleSelector(ax, onselect, interactive=True, + spancoords=spancoords, + minspanx=minspanx, minspany=minspany) + # Too small to create a selector + click_and_drag(tool, start=(x0, x1), end=(y0, y1)) + assert not tool._selection_completed + onselect.assert_not_called() + + click_and_drag(tool, start=(20, 20), end=(30, 30)) + assert tool._selection_completed + onselect.assert_called_once() + + # Too small to create a selector. Should clear existing selector, and + # trigger onselect because there was a preexisting selector + onselect.reset_mock() + click_and_drag(tool, start=(x0, y0), end=(x1, y1)) + assert not tool._selection_completed + onselect.assert_called_once() + (epress, erelease), kwargs = onselect.call_args + assert epress.xdata == x0 + assert epress.ydata == y0 + assert erelease.xdata == x1 + assert erelease.ydata == y1 + assert kwargs == {} + + +def test_deprecation_selector_visible_attribute(ax): + tool = widgets.RectangleSelector(ax, lambda *args: None) + + assert tool.get_visible() + + with pytest.warns( + MatplotlibDeprecationWarning, + match="was deprecated in Matplotlib 3.6"): + tool.visible = False + assert not tool.get_visible() + + +@pytest.mark.parametrize('drag_from_anywhere, new_center', + [[True, (60, 75)], + [False, (30, 20)]]) +def test_rectangle_drag(ax, drag_from_anywhere, new_center): + tool = widgets.RectangleSelector(ax, onselect=noop, interactive=True, + drag_from_anywhere=drag_from_anywhere) + # Create rectangle + click_and_drag(tool, start=(0, 10), end=(100, 120)) + assert tool.center == (50, 65) + # Drag inside rectangle, but away from centre handle + # + # If drag_from_anywhere == True, this will move the rectangle by (10, 10), + # giving it a new center of (60, 75) + # + # If drag_from_anywhere == False, this will create a new rectangle with + # center (30, 20) + click_and_drag(tool, start=(25, 15), end=(35, 25)) + assert tool.center == new_center + # Check that in both cases, dragging outside the rectangle draws a new + # rectangle + click_and_drag(tool, start=(175, 185), end=(185, 195)) + assert tool.center == (180, 190) + + +def test_rectangle_selector_set_props_handle_props(ax): + tool = widgets.RectangleSelector(ax, onselect=noop, interactive=True, + props=dict(facecolor='b', alpha=0.2), + handle_props=dict(alpha=0.5)) + # Create rectangle + click_and_drag(tool, start=(0, 10), end=(100, 120)) + + artist = tool._selection_artist + assert artist.get_facecolor() == mcolors.to_rgba('b', alpha=0.2) + tool.set_props(facecolor='r', alpha=0.3) + assert artist.get_facecolor() == mcolors.to_rgba('r', alpha=0.3) + + for artist in tool._handles_artists: + assert artist.get_markeredgecolor() == 'black' + assert artist.get_alpha() == 0.5 + tool.set_handle_props(markeredgecolor='r', alpha=0.3) + for artist in tool._handles_artists: + assert artist.get_markeredgecolor() == 'r' + assert artist.get_alpha() == 0.3 + + +def test_rectangle_resize(ax): + tool = widgets.RectangleSelector(ax, onselect=noop, interactive=True) + # Create rectangle + click_and_drag(tool, start=(0, 10), end=(100, 120)) + assert tool.extents == (0.0, 100.0, 10.0, 120.0) + + # resize NE handle + extents = tool.extents + xdata, ydata = extents[1], extents[3] + xdata_new, ydata_new = xdata + 10, ydata + 5 + click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new)) + assert tool.extents == (extents[0], xdata_new, extents[2], ydata_new) + + # resize E handle + extents = tool.extents + xdata, ydata = extents[1], extents[2] + (extents[3] - extents[2]) / 2 + xdata_new, ydata_new = xdata + 10, ydata + click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new)) + assert tool.extents == (extents[0], xdata_new, extents[2], extents[3]) + + # resize W handle + extents = tool.extents + xdata, ydata = extents[0], extents[2] + (extents[3] - extents[2]) / 2 + xdata_new, ydata_new = xdata + 15, ydata + click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new)) + assert tool.extents == (xdata_new, extents[1], extents[2], extents[3]) + + # resize SW handle + extents = tool.extents + xdata, ydata = extents[0], extents[2] + xdata_new, ydata_new = xdata + 20, ydata + 25 + click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new)) + assert tool.extents == (xdata_new, extents[1], ydata_new, extents[3]) + + +def test_rectangle_add_state(ax): + tool = widgets.RectangleSelector(ax, onselect=noop, interactive=True) + # Create rectangle + click_and_drag(tool, start=(70, 65), end=(125, 130)) + + with pytest.raises(ValueError): + tool.add_state('unsupported_state') + + with pytest.raises(ValueError): + tool.add_state('clear') + tool.add_state('move') + tool.add_state('square') + tool.add_state('center') + + +@pytest.mark.parametrize('add_state', [True, False]) +def test_rectangle_resize_center(ax, add_state): + tool = widgets.RectangleSelector(ax, onselect=noop, interactive=True) + # Create rectangle + click_and_drag(tool, start=(70, 65), end=(125, 130)) + assert tool.extents == (70.0, 125.0, 65.0, 130.0) + + if add_state: + tool.add_state('center') + use_key = None + else: + use_key = 'control' + + # resize NE handle + extents = tool.extents + xdata, ydata = extents[1], extents[3] + xdiff, ydiff = 10, 5 + xdata_new, ydata_new = xdata + xdiff, ydata + ydiff + click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new), + key=use_key) + assert tool.extents == (extents[0] - xdiff, xdata_new, + extents[2] - ydiff, ydata_new) + + # resize E handle + extents = tool.extents + xdata, ydata = extents[1], extents[2] + (extents[3] - extents[2]) / 2 + xdiff = 10 + xdata_new, ydata_new = xdata + xdiff, ydata + click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new), + key=use_key) + assert tool.extents == (extents[0] - xdiff, xdata_new, + extents[2], extents[3]) + + # resize E handle negative diff + extents = tool.extents + xdata, ydata = extents[1], extents[2] + (extents[3] - extents[2]) / 2 + xdiff = -20 + xdata_new, ydata_new = xdata + xdiff, ydata + click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new), + key=use_key) + assert tool.extents == (extents[0] - xdiff, xdata_new, + extents[2], extents[3]) + + # resize W handle + extents = tool.extents + xdata, ydata = extents[0], extents[2] + (extents[3] - extents[2]) / 2 + xdiff = 15 + xdata_new, ydata_new = xdata + xdiff, ydata + click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new), + key=use_key) + assert tool.extents == (xdata_new, extents[1] - xdiff, + extents[2], extents[3]) + + # resize W handle negative diff + extents = tool.extents + xdata, ydata = extents[0], extents[2] + (extents[3] - extents[2]) / 2 + xdiff = -25 + xdata_new, ydata_new = xdata + xdiff, ydata + click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new), + key=use_key) + assert tool.extents == (xdata_new, extents[1] - xdiff, + extents[2], extents[3]) + + # resize SW handle + extents = tool.extents + xdata, ydata = extents[0], extents[2] + xdiff, ydiff = 20, 25 + xdata_new, ydata_new = xdata + xdiff, ydata + ydiff + click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new), + key=use_key) + assert tool.extents == (xdata_new, extents[1] - xdiff, + ydata_new, extents[3] - ydiff) + + +@pytest.mark.parametrize('add_state', [True, False]) +def test_rectangle_resize_square(ax, add_state): + tool = widgets.RectangleSelector(ax, onselect=noop, interactive=True) + # Create rectangle + click_and_drag(tool, start=(70, 65), end=(120, 115)) + assert tool.extents == (70.0, 120.0, 65.0, 115.0) + + if add_state: + tool.add_state('square') + use_key = None + else: + use_key = 'shift' + + # resize NE handle + extents = tool.extents + xdata, ydata = extents[1], extents[3] + xdiff, ydiff = 10, 5 + xdata_new, ydata_new = xdata + xdiff, ydata + ydiff + click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new), + key=use_key) + assert tool.extents == (extents[0], xdata_new, + extents[2], extents[3] + xdiff) + + # resize E handle + extents = tool.extents + xdata, ydata = extents[1], extents[2] + (extents[3] - extents[2]) / 2 + xdiff = 10 + xdata_new, ydata_new = xdata + xdiff, ydata + click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new), + key=use_key) + assert tool.extents == (extents[0], xdata_new, + extents[2], extents[3] + xdiff) + + # resize E handle negative diff + extents = tool.extents + xdata, ydata = extents[1], extents[2] + (extents[3] - extents[2]) / 2 + xdiff = -20 + xdata_new, ydata_new = xdata + xdiff, ydata + click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new), + key=use_key) + assert tool.extents == (extents[0], xdata_new, + extents[2], extents[3] + xdiff) + + # resize W handle + extents = tool.extents + xdata, ydata = extents[0], extents[2] + (extents[3] - extents[2]) / 2 + xdiff = 15 + xdata_new, ydata_new = xdata + xdiff, ydata + click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new), + key=use_key) + assert tool.extents == (xdata_new, extents[1], + extents[2], extents[3] - xdiff) + + # resize W handle negative diff + extents = tool.extents + xdata, ydata = extents[0], extents[2] + (extents[3] - extents[2]) / 2 + xdiff = -25 + xdata_new, ydata_new = xdata + xdiff, ydata + click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new), + key=use_key) + assert tool.extents == (xdata_new, extents[1], + extents[2], extents[3] - xdiff) + + # resize SW handle + extents = tool.extents + xdata, ydata = extents[0], extents[2] + xdiff, ydiff = 20, 25 + xdata_new, ydata_new = xdata + xdiff, ydata + ydiff + click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new), + key=use_key) + assert tool.extents == (extents[0] + ydiff, extents[1], + ydata_new, extents[3]) + + +def test_rectangle_resize_square_center(ax): + tool = widgets.RectangleSelector(ax, onselect=noop, interactive=True) + # Create rectangle + click_and_drag(tool, start=(70, 65), end=(120, 115)) + tool.add_state('square') + tool.add_state('center') + assert_allclose(tool.extents, (70.0, 120.0, 65.0, 115.0)) + + # resize NE handle + extents = tool.extents + xdata, ydata = extents[1], extents[3] + xdiff, ydiff = 10, 5 + xdata_new, ydata_new = xdata + xdiff, ydata + ydiff + click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new)) + assert_allclose(tool.extents, (extents[0] - xdiff, xdata_new, + extents[2] - xdiff, extents[3] + xdiff)) + + # resize E handle + extents = tool.extents + xdata, ydata = extents[1], extents[2] + (extents[3] - extents[2]) / 2 + xdiff = 10 + xdata_new, ydata_new = xdata + xdiff, ydata + click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new)) + assert_allclose(tool.extents, (extents[0] - xdiff, xdata_new, + extents[2] - xdiff, extents[3] + xdiff)) + + # resize E handle negative diff + extents = tool.extents + xdata, ydata = extents[1], extents[2] + (extents[3] - extents[2]) / 2 + xdiff = -20 + xdata_new, ydata_new = xdata + xdiff, ydata + click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new)) + assert_allclose(tool.extents, (extents[0] - xdiff, xdata_new, + extents[2] - xdiff, extents[3] + xdiff)) + + # resize W handle + extents = tool.extents + xdata, ydata = extents[0], extents[2] + (extents[3] - extents[2]) / 2 + xdiff = 5 + xdata_new, ydata_new = xdata + xdiff, ydata + click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new)) + assert_allclose(tool.extents, (xdata_new, extents[1] - xdiff, + extents[2] + xdiff, extents[3] - xdiff)) + + # resize W handle negative diff + extents = tool.extents + xdata, ydata = extents[0], extents[2] + (extents[3] - extents[2]) / 2 + xdiff = -25 + xdata_new, ydata_new = xdata + xdiff, ydata + click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new)) + assert_allclose(tool.extents, (xdata_new, extents[1] - xdiff, + extents[2] + xdiff, extents[3] - xdiff)) + + # resize SW handle + extents = tool.extents + xdata, ydata = extents[0], extents[2] + xdiff, ydiff = 20, 25 + xdata_new, ydata_new = xdata + xdiff, ydata + ydiff + click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new)) + assert_allclose(tool.extents, (extents[0] + ydiff, extents[1] - ydiff, + ydata_new, extents[3] - ydiff)) + + +@pytest.mark.parametrize('selector_class', + [widgets.RectangleSelector, widgets.EllipseSelector]) +def test_rectangle_rotate(ax, selector_class): + tool = selector_class(ax, onselect=noop, interactive=True) + # Draw rectangle + click_and_drag(tool, start=(100, 100), end=(130, 140)) + assert tool.extents == (100, 130, 100, 140) + assert len(tool._state) == 0 + + # Rotate anticlockwise using top-right corner + do_event(tool, 'on_key_press', key='r') + assert tool._state == set(['rotate']) + assert len(tool._state) == 1 + click_and_drag(tool, start=(130, 140), end=(120, 145)) + do_event(tool, 'on_key_press', key='r') + assert len(tool._state) == 0 + # Extents shouldn't change (as shape of rectangle hasn't changed) + assert tool.extents == (100, 130, 100, 140) + assert_allclose(tool.rotation, 25.56, atol=0.01) + tool.rotation = 45 + assert tool.rotation == 45 + # Corners should move + assert_allclose(tool.corners, + np.array([[118.53, 139.75, 111.46, 90.25], + [95.25, 116.46, 144.75, 123.54]]), atol=0.01) + + # Scale using top-right corner + click_and_drag(tool, start=(110, 145), end=(110, 160)) + assert_allclose(tool.extents, (100, 139.75, 100, 151.82), atol=0.01) + + if selector_class == widgets.RectangleSelector: + with pytest.raises(ValueError): + tool._selection_artist.rotation_point = 'unvalid_value' + + +def test_rectangle_add_remove_set(ax): + tool = widgets.RectangleSelector(ax, onselect=noop, interactive=True) + # Draw rectangle + click_and_drag(tool, start=(100, 100), end=(130, 140)) + assert tool.extents == (100, 130, 100, 140) + assert len(tool._state) == 0 + for state in ['rotate', 'square', 'center']: + tool.add_state(state) + assert len(tool._state) == 1 + tool.remove_state(state) + assert len(tool._state) == 0 + + +@pytest.mark.parametrize('use_data_coordinates', [False, True]) +def test_rectangle_resize_square_center_aspect(ax, use_data_coordinates): + ax.set_aspect(0.8) + + tool = widgets.RectangleSelector(ax, onselect=noop, interactive=True, + use_data_coordinates=use_data_coordinates) + # Create rectangle + click_and_drag(tool, start=(70, 65), end=(120, 115)) + assert tool.extents == (70.0, 120.0, 65.0, 115.0) + tool.add_state('square') + tool.add_state('center') + + if use_data_coordinates: + # resize E handle + extents = tool.extents + xdata, ydata, width = extents[1], extents[3], extents[1] - extents[0] + xdiff, ycenter = 10, extents[2] + (extents[3] - extents[2]) / 2 + xdata_new, ydata_new = xdata + xdiff, ydata + ychange = width / 2 + xdiff + click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new)) + assert_allclose(tool.extents, [extents[0] - xdiff, xdata_new, + ycenter - ychange, ycenter + ychange]) + else: + # resize E handle + extents = tool.extents + xdata, ydata = extents[1], extents[3] + xdiff = 10 + xdata_new, ydata_new = xdata + xdiff, ydata + ychange = xdiff * 1 / tool._aspect_ratio_correction + click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new)) + assert_allclose(tool.extents, [extents[0] - xdiff, xdata_new, + 46.25, 133.75]) + + +def test_ellipse(ax): + """For ellipse, test out the key modifiers""" + tool = widgets.EllipseSelector(ax, onselect=noop, + grab_range=10, interactive=True) + tool.extents = (100, 150, 100, 150) + + # drag the rectangle + click_and_drag(tool, start=(125, 125), end=(145, 145)) + assert tool.extents == (120, 170, 120, 170) + + # create from center + click_and_drag(tool, start=(100, 100), end=(125, 125), key='control') + assert tool.extents == (75, 125, 75, 125) + + # create a square + click_and_drag(tool, start=(10, 10), end=(35, 30), key='shift') + extents = [int(e) for e in tool.extents] + assert extents == [10, 35, 10, 35] + + # create a square from center + click_and_drag(tool, start=(100, 100), end=(125, 130), key='ctrl+shift') + extents = [int(e) for e in tool.extents] + assert extents == [70, 130, 70, 130] + + assert tool.geometry.shape == (2, 73) + assert_allclose(tool.geometry[:, 0], [70., 100]) + + +def test_rectangle_handles(ax): + tool = widgets.RectangleSelector(ax, onselect=noop, + grab_range=10, + interactive=True, + handle_props={'markerfacecolor': 'r', + 'markeredgecolor': 'b'}) + tool.extents = (100, 150, 100, 150) + + assert_allclose(tool.corners, ((100, 150, 150, 100), (100, 100, 150, 150))) + assert tool.extents == (100, 150, 100, 150) + assert_allclose(tool.edge_centers, + ((100, 125.0, 150, 125.0), (125.0, 100, 125.0, 150))) + assert tool.extents == (100, 150, 100, 150) + + # grab a corner and move it + click_and_drag(tool, start=(100, 100), end=(120, 120)) + assert tool.extents == (120, 150, 120, 150) + + # grab the center and move it + click_and_drag(tool, start=(132, 132), end=(120, 120)) + assert tool.extents == (108, 138, 108, 138) + + # create a new rectangle + click_and_drag(tool, start=(10, 10), end=(100, 100)) + assert tool.extents == (10, 100, 10, 100) + + # Check that marker_props worked. + assert mcolors.same_color( + tool._corner_handles.artists[0].get_markerfacecolor(), 'r') + assert mcolors.same_color( + tool._corner_handles.artists[0].get_markeredgecolor(), 'b') + + +@pytest.mark.parametrize('interactive', [True, False]) +def test_rectangle_selector_onselect(ax, interactive): + # check when press and release events take place at the same position + onselect = mock.Mock(spec=noop, return_value=None) + + tool = widgets.RectangleSelector(ax, onselect, interactive=interactive) + # move outside of axis + click_and_drag(tool, start=(100, 110), end=(150, 120)) + + onselect.assert_called_once() + assert tool.extents == (100.0, 150.0, 110.0, 120.0) + + onselect.reset_mock() + click_and_drag(tool, start=(10, 100), end=(10, 100)) + onselect.assert_called_once() + + +@pytest.mark.parametrize('ignore_event_outside', [True, False]) +def test_rectangle_selector_ignore_outside(ax, ignore_event_outside): + onselect = mock.Mock(spec=noop, return_value=None) + + tool = widgets.RectangleSelector(ax, onselect, + ignore_event_outside=ignore_event_outside) + click_and_drag(tool, start=(100, 110), end=(150, 120)) + onselect.assert_called_once() + assert tool.extents == (100.0, 150.0, 110.0, 120.0) + + onselect.reset_mock() + # Trigger event outside of span + click_and_drag(tool, start=(150, 150), end=(160, 160)) + if ignore_event_outside: + # event have been ignored and span haven't changed. + onselect.assert_not_called() + assert tool.extents == (100.0, 150.0, 110.0, 120.0) + else: + # A new shape is created + onselect.assert_called_once() + assert tool.extents == (150.0, 160.0, 150.0, 160.0) + + +@pytest.mark.parametrize('orientation, onmove_callback, kwargs', [ + ('horizontal', False, dict(minspan=10, useblit=True)), + ('vertical', True, dict(button=1)), + ('horizontal', False, dict(props=dict(fill=True))), + ('horizontal', False, dict(interactive=True)), +]) +def test_span_selector(ax, orientation, onmove_callback, kwargs): + onselect = mock.Mock(spec=noop, return_value=None) + onmove = mock.Mock(spec=noop, return_value=None) + if onmove_callback: + kwargs['onmove_callback'] = onmove + + tool = widgets.SpanSelector(ax, onselect, orientation, **kwargs) + do_event(tool, 'press', xdata=100, ydata=100, button=1) + # move outside of axis + do_event(tool, 'onmove', xdata=199, ydata=199, button=1) + do_event(tool, 'release', xdata=250, ydata=250, button=1) + + onselect.assert_called_once_with(100, 199) + if onmove_callback: + onmove.assert_called_once_with(100, 199) + + +@pytest.mark.parametrize('interactive', [True, False]) +def test_span_selector_onselect(ax, interactive): + onselect = mock.Mock(spec=noop, return_value=None) + + tool = widgets.SpanSelector(ax, onselect, 'horizontal', + interactive=interactive) + # move outside of axis + click_and_drag(tool, start=(100, 100), end=(150, 100)) + onselect.assert_called_once() + assert tool.extents == (100, 150) + + onselect.reset_mock() + click_and_drag(tool, start=(10, 100), end=(10, 100)) + onselect.assert_called_once() + + +@pytest.mark.parametrize('ignore_event_outside', [True, False]) +def test_span_selector_ignore_outside(ax, ignore_event_outside): + onselect = mock.Mock(spec=noop, return_value=None) + onmove = mock.Mock(spec=noop, return_value=None) + + tool = widgets.SpanSelector(ax, onselect, 'horizontal', + onmove_callback=onmove, + ignore_event_outside=ignore_event_outside) + click_and_drag(tool, start=(100, 100), end=(125, 125)) + onselect.assert_called_once() + onmove.assert_called_once() + assert tool.extents == (100, 125) + + onselect.reset_mock() + onmove.reset_mock() + # Trigger event outside of span + click_and_drag(tool, start=(150, 150), end=(160, 160)) + if ignore_event_outside: + # event have been ignored and span haven't changed. + onselect.assert_not_called() + onmove.assert_not_called() + assert tool.extents == (100, 125) + else: + # A new shape is created + onselect.assert_called_once() + onmove.assert_called_once() + assert tool.extents == (150, 160) + + +@pytest.mark.parametrize('drag_from_anywhere', [True, False]) +def test_span_selector_drag(ax, drag_from_anywhere): + # Create span + tool = widgets.SpanSelector(ax, onselect=noop, direction='horizontal', + interactive=True, + drag_from_anywhere=drag_from_anywhere) + click_and_drag(tool, start=(10, 10), end=(100, 120)) + assert tool.extents == (10, 100) + # Drag inside span + # + # If drag_from_anywhere == True, this will move the span by 10, + # giving new value extents = 20, 110 + # + # If drag_from_anywhere == False, this will create a new span with + # value extents = 25, 35 + click_and_drag(tool, start=(25, 15), end=(35, 25)) + if drag_from_anywhere: + assert tool.extents == (20, 110) + else: + assert tool.extents == (25, 35) + + # Check that in both cases, dragging outside the span draws a new span + click_and_drag(tool, start=(175, 185), end=(185, 195)) + assert tool.extents == (175, 185) + + +def test_span_selector_direction(ax): + tool = widgets.SpanSelector(ax, onselect=noop, direction='horizontal', + interactive=True) + assert tool.direction == 'horizontal' + assert tool._edge_handles.direction == 'horizontal' + + with pytest.raises(ValueError): + tool = widgets.SpanSelector(ax, onselect=noop, + direction='invalid_direction') + + tool.direction = 'vertical' + assert tool.direction == 'vertical' + assert tool._edge_handles.direction == 'vertical' + + with pytest.raises(ValueError): + tool.direction = 'invalid_string' + + +def test_span_selector_set_props_handle_props(ax): + tool = widgets.SpanSelector(ax, onselect=noop, direction='horizontal', + interactive=True, + props=dict(facecolor='b', alpha=0.2), + handle_props=dict(alpha=0.5)) + # Create rectangle + click_and_drag(tool, start=(0, 10), end=(100, 120)) + + artist = tool._selection_artist + assert artist.get_facecolor() == mcolors.to_rgba('b', alpha=0.2) + tool.set_props(facecolor='r', alpha=0.3) + assert artist.get_facecolor() == mcolors.to_rgba('r', alpha=0.3) + + for artist in tool._handles_artists: + assert artist.get_color() == 'b' + assert artist.get_alpha() == 0.5 + tool.set_handle_props(color='r', alpha=0.3) + for artist in tool._handles_artists: + assert artist.get_color() == 'r' + assert artist.get_alpha() == 0.3 + + +@pytest.mark.parametrize('selector', ['span', 'rectangle']) +def test_selector_clear(ax, selector): + kwargs = dict(ax=ax, onselect=noop, interactive=True) + if selector == 'span': + Selector = widgets.SpanSelector + kwargs['direction'] = 'horizontal' + else: + Selector = widgets.RectangleSelector + + tool = Selector(**kwargs) + click_and_drag(tool, start=(10, 10), end=(100, 120)) + + # press-release event outside the selector to clear the selector + click_and_drag(tool, start=(130, 130), end=(130, 130)) + assert not tool._selection_completed + + kwargs['ignore_event_outside'] = True + tool = Selector(**kwargs) + assert tool.ignore_event_outside + click_and_drag(tool, start=(10, 10), end=(100, 120)) + + # press-release event outside the selector ignored + click_and_drag(tool, start=(130, 130), end=(130, 130)) + assert tool._selection_completed + + do_event(tool, 'on_key_press', key='escape') + assert not tool._selection_completed + + +@pytest.mark.parametrize('selector', ['span', 'rectangle']) +def test_selector_clear_method(ax, selector): + if selector == 'span': + tool = widgets.SpanSelector(ax, onselect=noop, direction='horizontal', + interactive=True, + ignore_event_outside=True) + else: + tool = widgets.RectangleSelector(ax, onselect=noop, interactive=True) + click_and_drag(tool, start=(10, 10), end=(100, 120)) + assert tool._selection_completed + assert tool.get_visible() + if selector == 'span': + assert tool.extents == (10, 100) + + tool.clear() + assert not tool._selection_completed + assert not tool.get_visible() + + # Do another cycle of events to make sure we can + click_and_drag(tool, start=(10, 10), end=(50, 120)) + assert tool._selection_completed + assert tool.get_visible() + if selector == 'span': + assert tool.extents == (10, 50) + + +def test_span_selector_add_state(ax): + tool = widgets.SpanSelector(ax, noop, 'horizontal', + interactive=True) + + with pytest.raises(ValueError): + tool.add_state('unsupported_state') + with pytest.raises(ValueError): + tool.add_state('center') + with pytest.raises(ValueError): + tool.add_state('square') + + tool.add_state('move') + + +def test_tool_line_handle(ax): + positions = [20, 30, 50] + tool_line_handle = widgets.ToolLineHandles(ax, positions, 'horizontal', + useblit=False) + + for artist in tool_line_handle.artists: + assert not artist.get_animated() + assert not artist.get_visible() + + tool_line_handle.set_visible(True) + tool_line_handle.set_animated(True) + + for artist in tool_line_handle.artists: + assert artist.get_animated() + assert artist.get_visible() + + assert tool_line_handle.positions == positions + + +@pytest.mark.parametrize('direction', ("horizontal", "vertical")) +def test_span_selector_bound(direction): + fig, ax = plt.subplots(1, 1) + ax.plot([10, 20], [10, 30]) + ax.figure.canvas.draw() + x_bound = ax.get_xbound() + y_bound = ax.get_ybound() + + tool = widgets.SpanSelector(ax, print, direction, interactive=True) + assert ax.get_xbound() == x_bound + assert ax.get_ybound() == y_bound + + bound = x_bound if direction == 'horizontal' else y_bound + assert tool._edge_handles.positions == list(bound) + + press_data = [10.5, 11.5] + move_data = [11, 13] # Updating selector is done in onmove + release_data = move_data + click_and_drag(tool, start=press_data, end=move_data) + + assert ax.get_xbound() == x_bound + assert ax.get_ybound() == y_bound + + index = 0 if direction == 'horizontal' else 1 + handle_positions = [press_data[index], release_data[index]] + assert tool._edge_handles.positions == handle_positions + + +@pytest.mark.backend('QtAgg', skip_on_importerror=True) +def test_span_selector_animated_artists_callback(): + """Check that the animated artists changed in callbacks are updated.""" + x = np.linspace(0, 2 * np.pi, 100) + values = np.sin(x) + + fig, ax = plt.subplots() + ln, = ax.plot(x, values, animated=True) + ln2, = ax.plot([], animated=True) + + # spin the event loop to let the backend process any pending operations + # before drawing artists + # See blitting tutorial + plt.pause(0.1) + ax.draw_artist(ln) + fig.canvas.blit(fig.bbox) + + def mean(vmin, vmax): + # Return mean of values in x between *vmin* and *vmax* + indmin, indmax = np.searchsorted(x, (vmin, vmax)) + v = values[indmin:indmax].mean() + ln2.set_data(x, np.full_like(x, v)) + + span = widgets.SpanSelector(ax, mean, direction='horizontal', + onmove_callback=mean, + interactive=True, + drag_from_anywhere=True, + useblit=True) + + # Add span selector and check that the line is draw after it was updated + # by the callback + press_data = [1, 2] + move_data = [2, 2] + do_event(span, 'press', xdata=press_data[0], ydata=press_data[1], button=1) + do_event(span, 'onmove', xdata=move_data[0], ydata=move_data[1], button=1) + assert span._get_animated_artists() == (ln, ln2) + assert ln.stale is False + assert ln2.stale + assert_allclose(ln2.get_ydata(), 0.9547335049088455) + span.update() + assert ln2.stale is False + + # Change span selector and check that the line is drawn/updated after its + # value was updated by the callback + press_data = [4, 2] + move_data = [5, 2] + release_data = [5, 2] + do_event(span, 'press', xdata=press_data[0], ydata=press_data[1], button=1) + do_event(span, 'onmove', xdata=move_data[0], ydata=move_data[1], button=1) + assert ln.stale is False + assert ln2.stale + assert_allclose(ln2.get_ydata(), -0.9424150707548072) + do_event(span, 'release', xdata=release_data[0], + ydata=release_data[1], button=1) + assert ln2.stale is False + + +def test_snapping_values_span_selector(ax): + def onselect(*args): + pass + + tool = widgets.SpanSelector(ax, onselect, direction='horizontal',) + snap_function = tool._snap + + snap_values = np.linspace(0, 5, 11) + values = np.array([-0.1, 0.1, 0.2, 0.5, 0.6, 0.7, 0.9, 4.76, 5.0, 5.5]) + expect = np.array([00.0, 0.0, 0.0, 0.5, 0.5, 0.5, 1.0, 5.00, 5.0, 5.0]) + values = snap_function(values, snap_values) + assert_allclose(values, expect) + + +def test_span_selector_snap(ax): + def onselect(vmin, vmax): + ax._got_onselect = True + + snap_values = np.arange(50) * 4 + + tool = widgets.SpanSelector(ax, onselect, direction='horizontal', + snap_values=snap_values) + tool.extents = (17, 35) + assert tool.extents == (16, 36) + + tool.snap_values = None + assert tool.snap_values is None + tool.extents = (17, 35) + assert tool.extents == (17, 35) + + +@pytest.mark.parametrize('kwargs', [ + dict(), + dict(useblit=False, props=dict(color='red')), + dict(useblit=True, button=1), +]) +def test_lasso_selector(ax, kwargs): + onselect = mock.Mock(spec=noop, return_value=None) + + tool = widgets.LassoSelector(ax, onselect, **kwargs) + do_event(tool, 'press', xdata=100, ydata=100, button=1) + do_event(tool, 'onmove', xdata=125, ydata=125, button=1) + do_event(tool, 'release', xdata=150, ydata=150, button=1) + + onselect.assert_called_once_with([(100, 100), (125, 125), (150, 150)]) + + +def test_CheckButtons(ax): + check = widgets.CheckButtons(ax, ('a', 'b', 'c'), (True, False, True)) + assert check.get_status() == [True, False, True] + check.set_active(0) + assert check.get_status() == [False, False, True] + + cid = check.on_clicked(lambda: None) + check.disconnect(cid) + + +@pytest.mark.parametrize("toolbar", ["none", "toolbar2", "toolmanager"]) +def test_TextBox(ax, toolbar): + # Avoid "toolmanager is provisional" warning. + plt.rcParams._set("toolbar", toolbar) + + submit_event = mock.Mock(spec=noop, return_value=None) + text_change_event = mock.Mock(spec=noop, return_value=None) + tool = widgets.TextBox(ax, '') + tool.on_submit(submit_event) + tool.on_text_change(text_change_event) + + assert tool.text == '' + + do_event(tool, '_click') + + tool.set_val('x**2') + + assert tool.text == 'x**2' + assert text_change_event.call_count == 1 + + tool.begin_typing() + tool.stop_typing() + + assert submit_event.call_count == 2 + + do_event(tool, '_click') + do_event(tool, '_keypress', key='+') + do_event(tool, '_keypress', key='5') + + assert text_change_event.call_count == 3 + + +@image_comparison(['check_radio_buttons.png'], style='mpl20', remove_text=True) +def test_check_radio_buttons_image(): + ax = get_ax() + fig = ax.figure + fig.subplots_adjust(left=0.3) + + rax1 = fig.add_axes([0.05, 0.7, 0.2, 0.15]) + rb1 = widgets.RadioButtons(rax1, ('Radio 1', 'Radio 2', 'Radio 3')) + with pytest.warns(DeprecationWarning, + match='The circles attribute was deprecated'): + rb1.circles # Trigger the old-style elliptic radiobuttons. + + rax2 = fig.add_axes([0.05, 0.5, 0.2, 0.15]) + cb1 = widgets.CheckButtons(rax2, ('Check 1', 'Check 2', 'Check 3'), + (False, True, True)) + with pytest.warns(DeprecationWarning, + match='The rectangles attribute was deprecated'): + cb1.rectangles # Trigger old-style Rectangle check boxes + + rax3 = fig.add_axes([0.05, 0.3, 0.2, 0.15]) + rb3 = widgets.RadioButtons( + rax3, ('Radio 1', 'Radio 2', 'Radio 3'), + label_props={'fontsize': [8, 12, 16], + 'color': ['red', 'green', 'blue']}, + radio_props={'edgecolor': ['red', 'green', 'blue'], + 'facecolor': ['mistyrose', 'palegreen', 'lightblue']}) + + rax4 = fig.add_axes([0.05, 0.1, 0.2, 0.15]) + cb4 = widgets.CheckButtons( + rax4, ('Check 1', 'Check 2', 'Check 3'), (False, True, True), + label_props={'fontsize': [8, 12, 16], + 'color': ['red', 'green', 'blue']}, + frame_props={'edgecolor': ['red', 'green', 'blue'], + 'facecolor': ['mistyrose', 'palegreen', 'lightblue']}, + check_props={'color': ['red', 'green', 'blue']}) + + +@check_figures_equal(extensions=["png"]) +def test_radio_buttons(fig_test, fig_ref): + widgets.RadioButtons(fig_test.subplots(), ["tea", "coffee"]) + ax = fig_ref.add_subplot(xticks=[], yticks=[]) + ax.scatter([.15, .15], [2/3, 1/3], transform=ax.transAxes, + s=(plt.rcParams["font.size"] / 2) ** 2, c=["C0", "none"]) + ax.text(.25, 2/3, "tea", transform=ax.transAxes, va="center") + ax.text(.25, 1/3, "coffee", transform=ax.transAxes, va="center") + + +@check_figures_equal(extensions=['png']) +def test_radio_buttons_props(fig_test, fig_ref): + label_props = {'color': ['red'], 'fontsize': [24]} + radio_props = {'facecolor': 'green', 'edgecolor': 'blue', 'linewidth': 2} + + widgets.RadioButtons(fig_ref.subplots(), ['tea', 'coffee'], + label_props=label_props, radio_props=radio_props) + + cb = widgets.RadioButtons(fig_test.subplots(), ['tea', 'coffee']) + cb.set_label_props(label_props) + # Setting the label size automatically increases default marker size, so we + # need to do that here as well. + cb.set_radio_props({**radio_props, 's': (24 / 2)**2}) + + +def test_radio_button_active_conflict(ax): + with pytest.warns(UserWarning, + match=r'Both the \*activecolor\* parameter'): + rb = widgets.RadioButtons(ax, ['tea', 'coffee'], activecolor='red', + radio_props={'facecolor': 'green'}) + # *radio_props*' facecolor wins over *activecolor* + assert mcolors.same_color(rb._buttons.get_facecolor(), ['green', 'none']) + + +@check_figures_equal(extensions=['png']) +def test_radio_buttons_activecolor_change(fig_test, fig_ref): + widgets.RadioButtons(fig_ref.subplots(), ['tea', 'coffee'], + activecolor='green') + + # Test property setter. + cb = widgets.RadioButtons(fig_test.subplots(), ['tea', 'coffee'], + activecolor='red') + cb.activecolor = 'green' + + +@check_figures_equal(extensions=["png"]) +def test_check_buttons(fig_test, fig_ref): + widgets.CheckButtons(fig_test.subplots(), ["tea", "coffee"], [True, True]) + ax = fig_ref.add_subplot(xticks=[], yticks=[]) + ax.scatter([.15, .15], [2/3, 1/3], marker='s', transform=ax.transAxes, + s=(plt.rcParams["font.size"] / 2) ** 2, c=["none", "none"]) + ax.scatter([.15, .15], [2/3, 1/3], marker='x', transform=ax.transAxes, + s=(plt.rcParams["font.size"] / 2) ** 2, c=["k", "k"]) + ax.text(.25, 2/3, "tea", transform=ax.transAxes, va="center") + ax.text(.25, 1/3, "coffee", transform=ax.transAxes, va="center") + + +@check_figures_equal(extensions=['png']) +def test_check_button_props(fig_test, fig_ref): + label_props = {'color': ['red'], 'fontsize': [24]} + frame_props = {'facecolor': 'green', 'edgecolor': 'blue', 'linewidth': 2} + check_props = {'facecolor': 'red', 'linewidth': 2} + + widgets.CheckButtons(fig_ref.subplots(), ['tea', 'coffee'], [True, True], + label_props=label_props, frame_props=frame_props, + check_props=check_props) + + cb = widgets.CheckButtons(fig_test.subplots(), ['tea', 'coffee'], + [True, True]) + cb.set_label_props(label_props) + # Setting the label size automatically increases default marker size, so we + # need to do that here as well. + cb.set_frame_props({**frame_props, 's': (24 / 2)**2}) + # FIXME: Axes.scatter promotes facecolor to edgecolor on unfilled markers, + # but Collection.update doesn't do that (it forgot the marker already). + # This means we cannot pass facecolor to both setters directly. + check_props['edgecolor'] = check_props.pop('facecolor') + cb.set_check_props({**check_props, 's': (24 / 2)**2}) + + +@check_figures_equal(extensions=["png"]) +def test_check_buttons_rectangles(fig_test, fig_ref): + # Test should be removed once .rectangles is removed + cb = widgets.CheckButtons(fig_test.subplots(), ["", ""], + [False, False]) + with pytest.warns(DeprecationWarning, + match='The rectangles attribute was deprecated'): + cb.rectangles + ax = fig_ref.add_subplot(xticks=[], yticks=[]) + ys = [2/3, 1/3] + dy = 1/3 + w, h = dy / 2, dy / 2 + rectangles = [ + Rectangle(xy=(0.05, ys[i] - h / 2), width=w, height=h, + edgecolor="black", + facecolor="none", + transform=ax.transAxes + ) + for i, y in enumerate(ys) + ] + for rectangle in rectangles: + ax.add_patch(rectangle) + + +@check_figures_equal(extensions=["png"]) +def test_check_buttons_lines(fig_test, fig_ref): + # Test should be removed once .lines is removed + cb = widgets.CheckButtons(fig_test.subplots(), ["", ""], [True, True]) + with pytest.warns(DeprecationWarning, + match='The lines attribute was deprecated'): + cb.lines + for rectangle in cb._rectangles: + rectangle.set_visible(False) + ax = fig_ref.add_subplot(xticks=[], yticks=[]) + ys = [2/3, 1/3] + dy = 1/3 + w, h = dy / 2, dy / 2 + lineparams = {'color': 'k', 'linewidth': 1.25, + 'transform': ax.transAxes, + 'solid_capstyle': 'butt'} + for i, y in enumerate(ys): + x, y = 0.05, y - h / 2 + l1 = Line2D([x, x + w], [y + h, y], **lineparams) + l2 = Line2D([x, x + w], [y, y + h], **lineparams) + + l1.set_visible(True) + l2.set_visible(True) + ax.add_line(l1) + ax.add_line(l2) + + +def test_slider_slidermin_slidermax_invalid(): + fig, ax = plt.subplots() + # test min/max with floats + with pytest.raises(ValueError): + widgets.Slider(ax=ax, label='', valmin=0.0, valmax=24.0, + slidermin=10.0) + with pytest.raises(ValueError): + widgets.Slider(ax=ax, label='', valmin=0.0, valmax=24.0, + slidermax=10.0) + + +def test_slider_slidermin_slidermax(): + fig, ax = plt.subplots() + slider_ = widgets.Slider(ax=ax, label='', valmin=0.0, valmax=24.0, + valinit=5.0) + + slider = widgets.Slider(ax=ax, label='', valmin=0.0, valmax=24.0, + valinit=1.0, slidermin=slider_) + assert slider.val == slider_.val + + slider = widgets.Slider(ax=ax, label='', valmin=0.0, valmax=24.0, + valinit=10.0, slidermax=slider_) + assert slider.val == slider_.val + + +def test_slider_valmin_valmax(): + fig, ax = plt.subplots() + slider = widgets.Slider(ax=ax, label='', valmin=0.0, valmax=24.0, + valinit=-10.0) + assert slider.val == slider.valmin + + slider = widgets.Slider(ax=ax, label='', valmin=0.0, valmax=24.0, + valinit=25.0) + assert slider.val == slider.valmax + + +def test_slider_valstep_snapping(): + fig, ax = plt.subplots() + slider = widgets.Slider(ax=ax, label='', valmin=0.0, valmax=24.0, + valinit=11.4, valstep=1) + assert slider.val == 11 + + slider = widgets.Slider(ax=ax, label='', valmin=0.0, valmax=24.0, + valinit=11.4, valstep=[0, 1, 5.5, 19.7]) + assert slider.val == 5.5 + + +def test_slider_horizontal_vertical(): + fig, ax = plt.subplots() + slider = widgets.Slider(ax=ax, label='', valmin=0, valmax=24, + valinit=12, orientation='horizontal') + slider.set_val(10) + assert slider.val == 10 + # check the dimension of the slider patch in axes units + box = slider.poly.get_extents().transformed(ax.transAxes.inverted()) + assert_allclose(box.bounds, [0, .25, 10/24, .5]) + + fig, ax = plt.subplots() + slider = widgets.Slider(ax=ax, label='', valmin=0, valmax=24, + valinit=12, orientation='vertical') + slider.set_val(10) + assert slider.val == 10 + # check the dimension of the slider patch in axes units + box = slider.poly.get_extents().transformed(ax.transAxes.inverted()) + assert_allclose(box.bounds, [.25, 0, .5, 10/24]) + + +def test_slider_reset(): + fig, ax = plt.subplots() + slider = widgets.Slider(ax=ax, label='', valmin=0, valmax=1, valinit=.5) + slider.set_val(0.75) + slider.reset() + assert slider.val == 0.5 + + +@pytest.mark.parametrize("orientation", ["horizontal", "vertical"]) +def test_range_slider(orientation): + if orientation == "vertical": + idx = [1, 0, 3, 2] + else: + idx = [0, 1, 2, 3] + + fig, ax = plt.subplots() + + slider = widgets.RangeSlider( + ax=ax, label="", valmin=0.0, valmax=1.0, orientation=orientation, + valinit=[0.1, 0.34] + ) + box = slider.poly.get_extents().transformed(ax.transAxes.inverted()) + assert_allclose(box.get_points().flatten()[idx], [0.1, 0.25, 0.34, 0.75]) + + # Check initial value is set correctly + assert_allclose(slider.val, (0.1, 0.34)) + + def handle_positions(slider): + if orientation == "vertical": + return [h.get_ydata()[0] for h in slider._handles] + else: + return [h.get_xdata()[0] for h in slider._handles] + + slider.set_val((0.4, 0.6)) + assert_allclose(slider.val, (0.4, 0.6)) + assert_allclose(handle_positions(slider), (0.4, 0.6)) + + box = slider.poly.get_extents().transformed(ax.transAxes.inverted()) + assert_allclose(box.get_points().flatten()[idx], [0.4, .25, 0.6, .75]) + + slider.set_val((0.2, 0.1)) + assert_allclose(slider.val, (0.1, 0.2)) + assert_allclose(handle_positions(slider), (0.1, 0.2)) + + slider.set_val((-1, 10)) + assert_allclose(slider.val, (0, 1)) + assert_allclose(handle_positions(slider), (0, 1)) + + slider.reset() + assert_allclose(slider.val, (0.1, 0.34)) + assert_allclose(handle_positions(slider), (0.1, 0.34)) + + +@pytest.mark.parametrize("orientation", ["horizontal", "vertical"]) +def test_range_slider_same_init_values(orientation): + if orientation == "vertical": + idx = [1, 0, 3, 2] + else: + idx = [0, 1, 2, 3] + + fig, ax = plt.subplots() + + slider = widgets.RangeSlider( + ax=ax, label="", valmin=0.0, valmax=1.0, orientation=orientation, + valinit=[0, 0] + ) + box = slider.poly.get_extents().transformed(ax.transAxes.inverted()) + assert_allclose(box.get_points().flatten()[idx], [0, 0.25, 0, 0.75]) + + +def check_polygon_selector(event_sequence, expected_result, selections_count, + **kwargs): + """ + Helper function to test Polygon Selector. + + Parameters + ---------- + event_sequence : list of tuples (etype, dict()) + A sequence of events to perform. The sequence is a list of tuples + where the first element of the tuple is an etype (e.g., 'onmove', + 'press', etc.), and the second element of the tuple is a dictionary of + the arguments for the event (e.g., xdata=5, key='shift', etc.). + expected_result : list of vertices (xdata, ydata) + The list of vertices that are expected to result from the event + sequence. + selections_count : int + Wait for the tool to call its `onselect` function `selections_count` + times, before comparing the result to the `expected_result` + **kwargs + Keyword arguments are passed to PolygonSelector. + """ + ax = get_ax() + + onselect = mock.Mock(spec=noop, return_value=None) + + tool = widgets.PolygonSelector(ax, onselect, **kwargs) + + for (etype, event_args) in event_sequence: + do_event(tool, etype, **event_args) + + assert onselect.call_count == selections_count + assert onselect.call_args == ((expected_result, ), {}) + + +def polygon_place_vertex(xdata, ydata): + return [('onmove', dict(xdata=xdata, ydata=ydata)), + ('press', dict(xdata=xdata, ydata=ydata)), + ('release', dict(xdata=xdata, ydata=ydata))] + + +def polygon_remove_vertex(xdata, ydata): + return [('onmove', dict(xdata=xdata, ydata=ydata)), + ('press', dict(xdata=xdata, ydata=ydata, button=3)), + ('release', dict(xdata=xdata, ydata=ydata, button=3))] + + +@pytest.mark.parametrize('draw_bounding_box', [False, True]) +def test_polygon_selector(draw_bounding_box): + check_selector = functools.partial( + check_polygon_selector, draw_bounding_box=draw_bounding_box) + + # Simple polygon + expected_result = [(50, 50), (150, 50), (50, 150)] + event_sequence = [ + *polygon_place_vertex(50, 50), + *polygon_place_vertex(150, 50), + *polygon_place_vertex(50, 150), + *polygon_place_vertex(50, 50), + ] + check_selector(event_sequence, expected_result, 1) + + # Move first vertex before completing the polygon. + expected_result = [(75, 50), (150, 50), (50, 150)] + event_sequence = [ + *polygon_place_vertex(50, 50), + *polygon_place_vertex(150, 50), + ('on_key_press', dict(key='control')), + ('onmove', dict(xdata=50, ydata=50)), + ('press', dict(xdata=50, ydata=50)), + ('onmove', dict(xdata=75, ydata=50)), + ('release', dict(xdata=75, ydata=50)), + ('on_key_release', dict(key='control')), + *polygon_place_vertex(50, 150), + *polygon_place_vertex(75, 50), + ] + check_selector(event_sequence, expected_result, 1) + + # Move first two vertices at once before completing the polygon. + expected_result = [(50, 75), (150, 75), (50, 150)] + event_sequence = [ + *polygon_place_vertex(50, 50), + *polygon_place_vertex(150, 50), + ('on_key_press', dict(key='shift')), + ('onmove', dict(xdata=100, ydata=100)), + ('press', dict(xdata=100, ydata=100)), + ('onmove', dict(xdata=100, ydata=125)), + ('release', dict(xdata=100, ydata=125)), + ('on_key_release', dict(key='shift')), + *polygon_place_vertex(50, 150), + *polygon_place_vertex(50, 75), + ] + check_selector(event_sequence, expected_result, 1) + + # Move first vertex after completing the polygon. + expected_result = [(75, 50), (150, 50), (50, 150)] + event_sequence = [ + *polygon_place_vertex(50, 50), + *polygon_place_vertex(150, 50), + *polygon_place_vertex(50, 150), + *polygon_place_vertex(50, 50), + ('onmove', dict(xdata=50, ydata=50)), + ('press', dict(xdata=50, ydata=50)), + ('onmove', dict(xdata=75, ydata=50)), + ('release', dict(xdata=75, ydata=50)), + ] + check_selector(event_sequence, expected_result, 2) + + # Move all vertices after completing the polygon. + expected_result = [(75, 75), (175, 75), (75, 175)] + event_sequence = [ + *polygon_place_vertex(50, 50), + *polygon_place_vertex(150, 50), + *polygon_place_vertex(50, 150), + *polygon_place_vertex(50, 50), + ('on_key_press', dict(key='shift')), + ('onmove', dict(xdata=100, ydata=100)), + ('press', dict(xdata=100, ydata=100)), + ('onmove', dict(xdata=125, ydata=125)), + ('release', dict(xdata=125, ydata=125)), + ('on_key_release', dict(key='shift')), + ] + check_selector(event_sequence, expected_result, 2) + + # Try to move a vertex and move all before placing any vertices. + expected_result = [(50, 50), (150, 50), (50, 150)] + event_sequence = [ + ('on_key_press', dict(key='control')), + ('onmove', dict(xdata=100, ydata=100)), + ('press', dict(xdata=100, ydata=100)), + ('onmove', dict(xdata=125, ydata=125)), + ('release', dict(xdata=125, ydata=125)), + ('on_key_release', dict(key='control')), + ('on_key_press', dict(key='shift')), + ('onmove', dict(xdata=100, ydata=100)), + ('press', dict(xdata=100, ydata=100)), + ('onmove', dict(xdata=125, ydata=125)), + ('release', dict(xdata=125, ydata=125)), + ('on_key_release', dict(key='shift')), + *polygon_place_vertex(50, 50), + *polygon_place_vertex(150, 50), + *polygon_place_vertex(50, 150), + *polygon_place_vertex(50, 50), + ] + check_selector(event_sequence, expected_result, 1) + + # Try to place vertex out-of-bounds, then reset, and start a new polygon. + expected_result = [(50, 50), (150, 50), (50, 150)] + event_sequence = [ + *polygon_place_vertex(50, 50), + *polygon_place_vertex(250, 50), + ('on_key_press', dict(key='escape')), + ('on_key_release', dict(key='escape')), + *polygon_place_vertex(50, 50), + *polygon_place_vertex(150, 50), + *polygon_place_vertex(50, 150), + *polygon_place_vertex(50, 50), + ] + check_selector(event_sequence, expected_result, 1) + + +@pytest.mark.parametrize('draw_bounding_box', [False, True]) +def test_polygon_selector_set_props_handle_props(ax, draw_bounding_box): + tool = widgets.PolygonSelector(ax, onselect=noop, + props=dict(color='b', alpha=0.2), + handle_props=dict(alpha=0.5), + draw_bounding_box=draw_bounding_box) + + event_sequence = [ + *polygon_place_vertex(50, 50), + *polygon_place_vertex(150, 50), + *polygon_place_vertex(50, 150), + *polygon_place_vertex(50, 50), + ] + + for (etype, event_args) in event_sequence: + do_event(tool, etype, **event_args) + + artist = tool._selection_artist + assert artist.get_color() == 'b' + assert artist.get_alpha() == 0.2 + tool.set_props(color='r', alpha=0.3) + assert artist.get_color() == 'r' + assert artist.get_alpha() == 0.3 + + for artist in tool._handles_artists: + assert artist.get_color() == 'b' + assert artist.get_alpha() == 0.5 + tool.set_handle_props(color='r', alpha=0.3) + for artist in tool._handles_artists: + assert artist.get_color() == 'r' + assert artist.get_alpha() == 0.3 + + +@check_figures_equal() +def test_rect_visibility(fig_test, fig_ref): + # Check that requesting an invisible selector makes it invisible + ax_test = fig_test.subplots() + _ = fig_ref.subplots() + + tool = widgets.RectangleSelector(ax_test, onselect=noop, + props={'visible': False}) + tool.extents = (0.2, 0.8, 0.3, 0.7) + + +# Change the order that the extra point is inserted in +@pytest.mark.parametrize('idx', [1, 2, 3]) +@pytest.mark.parametrize('draw_bounding_box', [False, True]) +def test_polygon_selector_remove(idx, draw_bounding_box): + verts = [(50, 50), (150, 50), (50, 150)] + event_sequence = [polygon_place_vertex(*verts[0]), + polygon_place_vertex(*verts[1]), + polygon_place_vertex(*verts[2]), + # Finish the polygon + polygon_place_vertex(*verts[0])] + # Add an extra point + event_sequence.insert(idx, polygon_place_vertex(200, 200)) + # Remove the extra point + event_sequence.append(polygon_remove_vertex(200, 200)) + # Flatten list of lists + event_sequence = sum(event_sequence, []) + check_polygon_selector(event_sequence, verts, 2, + draw_bounding_box=draw_bounding_box) + + +@pytest.mark.parametrize('draw_bounding_box', [False, True]) +def test_polygon_selector_remove_first_point(draw_bounding_box): + verts = [(50, 50), (150, 50), (50, 150)] + event_sequence = [ + *polygon_place_vertex(*verts[0]), + *polygon_place_vertex(*verts[1]), + *polygon_place_vertex(*verts[2]), + *polygon_place_vertex(*verts[0]), + *polygon_remove_vertex(*verts[0]), + ] + check_polygon_selector(event_sequence, verts[1:], 2, + draw_bounding_box=draw_bounding_box) + + +@pytest.mark.parametrize('draw_bounding_box', [False, True]) +def test_polygon_selector_redraw(ax, draw_bounding_box): + verts = [(50, 50), (150, 50), (50, 150)] + event_sequence = [ + *polygon_place_vertex(*verts[0]), + *polygon_place_vertex(*verts[1]), + *polygon_place_vertex(*verts[2]), + *polygon_place_vertex(*verts[0]), + # Polygon completed, now remove first two verts. + *polygon_remove_vertex(*verts[1]), + *polygon_remove_vertex(*verts[2]), + # At this point the tool should be reset so we can add more vertices. + *polygon_place_vertex(*verts[1]), + ] + + tool = widgets.PolygonSelector(ax, onselect=noop, + draw_bounding_box=draw_bounding_box) + for (etype, event_args) in event_sequence: + do_event(tool, etype, **event_args) + # After removing two verts, only one remains, and the + # selector should be automatically resete + assert tool.verts == verts[0:2] + + +@pytest.mark.parametrize('draw_bounding_box', [False, True]) +@check_figures_equal(extensions=['png']) +def test_polygon_selector_verts_setter(fig_test, fig_ref, draw_bounding_box): + verts = [(0.1, 0.4), (0.5, 0.9), (0.3, 0.2)] + ax_test = fig_test.add_subplot() + + tool_test = widgets.PolygonSelector( + ax_test, onselect=noop, draw_bounding_box=draw_bounding_box) + tool_test.verts = verts + assert tool_test.verts == verts + + ax_ref = fig_ref.add_subplot() + tool_ref = widgets.PolygonSelector( + ax_ref, onselect=noop, draw_bounding_box=draw_bounding_box) + event_sequence = [ + *polygon_place_vertex(*verts[0]), + *polygon_place_vertex(*verts[1]), + *polygon_place_vertex(*verts[2]), + *polygon_place_vertex(*verts[0]), + ] + for (etype, event_args) in event_sequence: + do_event(tool_ref, etype, **event_args) + + +def test_polygon_selector_box(ax): + # Create a diamond shape + verts = [(20, 0), (0, 20), (20, 40), (40, 20)] + event_sequence = [ + *polygon_place_vertex(*verts[0]), + *polygon_place_vertex(*verts[1]), + *polygon_place_vertex(*verts[2]), + *polygon_place_vertex(*verts[3]), + *polygon_place_vertex(*verts[0]), + ] + + # Create selector + tool = widgets.PolygonSelector(ax, onselect=noop, draw_bounding_box=True) + for (etype, event_args) in event_sequence: + do_event(tool, etype, **event_args) + + # In order to trigger the correct callbacks, trigger events on the canvas + # instead of the individual tools + t = ax.transData + canvas = ax.figure.canvas + + # Scale to half size using the top right corner of the bounding box + MouseEvent( + "button_press_event", canvas, *t.transform((40, 40)), 1)._process() + MouseEvent( + "motion_notify_event", canvas, *t.transform((20, 20)))._process() + MouseEvent( + "button_release_event", canvas, *t.transform((20, 20)), 1)._process() + np.testing.assert_allclose( + tool.verts, [(10, 0), (0, 10), (10, 20), (20, 10)]) + + # Move using the center of the bounding box + MouseEvent( + "button_press_event", canvas, *t.transform((10, 10)), 1)._process() + MouseEvent( + "motion_notify_event", canvas, *t.transform((30, 30)))._process() + MouseEvent( + "button_release_event", canvas, *t.transform((30, 30)), 1)._process() + np.testing.assert_allclose( + tool.verts, [(30, 20), (20, 30), (30, 40), (40, 30)]) + + # Remove a point from the polygon and check that the box extents update + np.testing.assert_allclose( + tool._box.extents, (20.0, 40.0, 20.0, 40.0)) + + MouseEvent( + "button_press_event", canvas, *t.transform((30, 20)), 3)._process() + MouseEvent( + "button_release_event", canvas, *t.transform((30, 20)), 3)._process() + np.testing.assert_allclose( + tool.verts, [(20, 30), (30, 40), (40, 30)]) + np.testing.assert_allclose( + tool._box.extents, (20.0, 40.0, 30.0, 40.0)) + + +@pytest.mark.parametrize("horizOn", [False, True]) +@pytest.mark.parametrize("vertOn", [False, True]) +def test_MultiCursor(horizOn, vertOn): + (ax1, ax3) = plt.figure().subplots(2, sharex=True) + ax2 = plt.figure().subplots() + + # useblit=false to avoid having to draw the figure to cache the renderer + multi = widgets.MultiCursor( + None, (ax1, ax2), useblit=False, horizOn=horizOn, vertOn=vertOn + ) + + # Only two of the axes should have a line drawn on them. + assert len(multi.vlines) == 2 + assert len(multi.hlines) == 2 + + # mock a motion_notify_event + # Can't use `do_event` as that helper requires the widget + # to have a single .ax attribute. + event = mock_event(ax1, xdata=.5, ydata=.25) + multi.onmove(event) + # force a draw + draw event to exercise clear + ax1.figure.canvas.draw() + + # the lines in the first two ax should both move + for l in multi.vlines: + assert l.get_xdata() == (.5, .5) + for l in multi.hlines: + assert l.get_ydata() == (.25, .25) + # The relevant lines get turned on after move. + assert len([line for line in multi.vlines if line.get_visible()]) == ( + 2 if vertOn else 0) + assert len([line for line in multi.hlines if line.get_visible()]) == ( + 2 if horizOn else 0) + + # After toggling settings, the opposite lines should be visible after move. + multi.horizOn = not multi.horizOn + multi.vertOn = not multi.vertOn + event = mock_event(ax1, xdata=.5, ydata=.25) + multi.onmove(event) + assert len([line for line in multi.vlines if line.get_visible()]) == ( + 0 if vertOn else 2) + assert len([line for line in multi.hlines if line.get_visible()]) == ( + 0 if horizOn else 2) + + # test a move event in an Axes not part of the MultiCursor + # the lines in ax1 and ax2 should not have moved. + event = mock_event(ax3, xdata=.75, ydata=.75) + multi.onmove(event) + for l in multi.vlines: + assert l.get_xdata() == (.5, .5) + for l in multi.hlines: + assert l.get_ydata() == (.25, .25)