GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — matplotlib-cpp/matplotlibcpp.h at master · lava/matplotlib-cpp Expand file tree/ Copy pathmatplotlibcpp.hMore file actions 3622 lines (2903 loc) · 121 KB / Copy pathmatplotlibcpp.hFile metadata and controls3622 lines (2903 loc) · 121 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 #pragma once // Python headers must be included before any system headers, since // they define _POSIX_C_SOURCE // Qt defines 'slots' as a macro, which clashes with a struct member in Python.h; temporarily undefine it. // So does <term.h> with 'lines' (#216). #pragma push_macro("slots") #pragma push_macro("lines") #undef slots #undef lines #include <Python.h> #pragma pop_macro("lines") #pragma pop_macro("slots") #include <vector> #include <map> #include <array> #include <numeric> #include <algorithm> #include <stdexcept> #include <iostream> #include <cstdint> // <cstdint> requires c++11 support #include <functional> #include <string> // std::stod #include <cstdio> // std::sscanf #include <cstring> // std::memcpy #include <csignal> // SIGINT #include <atomic> #ifndef WITHOUT_NUMPY #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include <numpy/arrayobject.h> #ifdef WITH_OPENCV #include <opencv2/opencv.hpp> /* * A bunch of constants were removed in OpenCV 4 in favour of enum classes, so * define the ones we need here. */ #if CV_MAJOR_VERSION > 3 #define CV_BGR2RGB cv::COLOR_BGR2RGB #define CV_BGRA2RGBA cv::COLOR_BGRA2RGBA #endif #endif // WITH_OPENCV #endif // WITHOUT_NUMPY #if PY_MAJOR_VERSION >= 3 #define PyString_FromString PyUnicode_FromString #define PyInt_FromLong PyLong_FromLong #define PyString_FromString PyUnicode_FromString #endif namespace matplotlibcpp { namespace detail { // Prints the pending Python exception, if any, which also clears it. A wrapper // whose Python call failed must not leave the exception set, or a later, // unrelated call could fail or crash because of it. inline void print_error() { if (PyErr_Occurred()) PyErr_Print(); } // Prints the pending Python exception, if any, and throws. [[noreturn]] inline void fail(const std::string& message) { print_error(); throw std::runtime_error(message); } // Releases the result of a Python call and returns whether the call // succeeded. If it failed, the Python exception is printed and cleared. inline bool check_result(PyObject* res) { if (!res) { print_error(); return false; } Py_DECREF(res); return true; } // Sets kwargs[key] = value and releases value, which must be a new reference. // Unlike PyTuple_SetItem(), PyDict_SetItemString() does not steal the // reference, so passing a new reference to it directly would leak the value. inline void set_kwarg(PyObject* kwargs, const char* key, PyObject* value) { if (!value) { // e.g. a keyword value that is not valid UTF-8 print_error(); return; } PyDict_SetItemString(kwargs, key, value); Py_DECREF(value); } // The backend selected with backend(). A function-local static in an inline // function, so that the whole program shares one, unlike a namespace-scope // static, of which every translation unit would have its own (#178). inline std::string& backend_name() { static std::string name; return name; } #ifndef WITHOUT_NUMPY // Initializes numpy's C API for the calling translation unit, if that has not // happened yet. Call it before any other numpy function. The function table, // PyArray_API, is a static variable in numpy's headers, so every translation // unit that includes this header has its own copy, and each one must be // filled in before that unit uses numpy (#178). This function is static, so // each translation unit also gets its own copy of it, which fills in its own // table. The interpreter must be initialized. static inline void import_numpy() { if (PyArray_API) return; if (_import_array() < 0) fail("Couldn't import numpy's C API"); } #endif struct _interpreter { PyObject* s_python_function_arrow; PyObject* s_python_function_show; PyObject* s_python_function_close; PyObject* s_python_function_draw; PyObject* s_python_function_pause; PyObject* s_python_function_save; PyObject* s_python_function_figure; PyObject* s_python_function_fignum_exists; PyObject* s_python_function_gcf; PyObject* s_python_function_plot; PyObject* s_python_function_quiver; PyObject* s_python_function_contour; PyObject* s_python_function_contourf; PyObject* s_python_function_semilogx; PyObject* s_python_function_semilogy; PyObject* s_python_function_loglog; PyObject* s_python_function_fill; PyObject* s_python_function_fill_between; PyObject* s_python_function_hist; PyObject* s_python_function_imshow; PyObject* s_python_function_scatter; PyObject* s_python_function_boxplot; PyObject* s_python_function_subplot; PyObject* s_python_function_subplot2grid; PyObject* s_python_function_legend; PyObject* s_python_function_xlim; PyObject* s_python_function_ion; PyObject* s_python_function_ioff; PyObject* s_python_function_ginput; PyObject* s_python_function_ylim; PyObject* s_python_function_title; PyObject* s_python_function_axis; PyObject* s_python_function_axhline; PyObject* s_python_function_axvline; PyObject* s_python_function_axvspan; PyObject* s_python_function_xlabel; PyObject* s_python_function_ylabel; PyObject* s_python_function_gca; PyObject* s_python_function_xticks; PyObject* s_python_function_yticks; PyObject* s_python_function_margins; PyObject* s_python_function_tick_params; PyObject* s_python_function_grid; PyObject* s_python_function_cla; PyObject* s_python_function_clf; PyObject* s_python_function_errorbar; PyObject* s_python_function_annotate; PyObject* s_python_function_tight_layout; PyObject* s_python_colormap; PyObject* s_python_empty_tuple; PyObject* s_python_function_stem; PyObject* s_python_function_xkcd; PyObject* s_python_function_text; PyObject* s_python_function_suptitle; PyObject* s_python_function_bar; PyObject* s_python_function_barh; PyObject* s_python_function_colorbar; PyObject* s_python_function_subplots_adjust; PyObject* s_python_function_rcparams; PyObject* s_python_function_spy; // matplotlib 3.9 renamed boxplot's `labels` keyword to `tick_labels`, // and matplotlib 3.11 removed `labels`. const char* s_boxplot_labels_keyword; /* For now, _interpreter is implemented as a singleton since its currently not possible to have multiple independent embedded python interpreters without patching the python source code or starting a separate process for each. [1] The interpreter is started by the first call to `get()` and, by default, never finalized: the operating system reclaims everything when the program exits. Finalizing it from a static destructor crashes with some backends, e.g. Qt, whose global state may already be gone by then (#268). Programs that need Python to shut down cleanly, e.g. to run atexit handlers or for leak checkers, call `matplotlibcpp::finalize()` at a time of their choosing. Since many python objects expect that they are destructed in the same thread as they were constructed [2], call it in the thread that plotted. Restarting the interpreter afterwards is not supported, because numpy cannot reliably be imported again, so `get()` throws once it has been finalized. 1: http://bytes.com/topic/python/answers/793370-multiple-independent-python-interpreters-c-c-program 2: https://github.com/lava/matplotlib-cpp/pull/202#issue-436220256 */ // Returns the interpreter, starting it on the first call. Throws // std::runtime_error if it has been finalized. static _interpreter& get() { if (state() == finalized) throw std::runtime_error("matplotlibcpp: the Python interpreter was finalized by " "matplotlibcpp::finalize(); plotting afterwards is not supported"); return instance(); } // Finalizes the interpreter; see matplotlibcpp::finalize(). static void finalize() { // Mark the interpreter as finalized even if it was never started, so // that plotting after finalize() always fails the same way. if (state().exchange(finalized) != running) return; instance().release(); Py_Finalize(); } // Kept for compatibility; the same as finalize(). It used to return the // destroyed interpreter, which could not be used anyway. static void kill() { finalize(); } // Whether finalize() has been called. Objects that hold Python references // must not touch them any more once it returns true. static bool is_finalized() { return state() == finalized; } PyObject* safe_import(PyObject* module, std::string fname) { PyObject* fn = PyObject_GetAttrString(module, fname.c_str()); if (!fn) detail::fail(std::string("Couldn't find required function: ") + fname); if (!PyFunction_Check(fn)) throw std::runtime_error(fname + std::string(" is unexpectedly not a PyFunction.")); return fn; } private: enum { not_started, running, finalized, }; // The lifecycle of the interpreter. A function-local static in an inline // function, so that the whole program shares one (#178). static std::atomic<int>& state() { static std::atomic<int> s(not_started); return s; } // The singleton. Its initialization is thread-safe. It has no destructor // that finalizes Python, since that would run during static destruction. static _interpreter& instance() { static _interpreter ctx; return ctx; } // Releases the cached Python objects, before Python is finalized. void release() { PyObject** objects[] = { &s_python_function_arrow, &s_python_function_show, &s_python_function_close, &s_python_function_draw, &s_python_function_pause, &s_python_function_save, &s_python_function_figure, &s_python_function_fignum_exists, &s_python_function_gcf, &s_python_function_plot, &s_python_function_quiver, &s_python_function_contour, &s_python_function_contourf, &s_python_function_semilogx, &s_python_function_semilogy, &s_python_function_loglog, &s_python_function_fill, &s_python_function_fill_between, &s_python_function_hist, &s_python_function_scatter, &s_python_function_boxplot, &s_python_function_subplot, &s_python_function_subplot2grid, &s_python_function_legend, &s_python_function_xlim, &s_python_function_ion, &s_python_function_ioff, &s_python_function_ginput, &s_python_function_ylim, &s_python_function_title, &s_python_function_axis, &s_python_function_axhline, &s_python_function_axvline, &s_python_function_axvspan, &s_python_function_xlabel, &s_python_function_ylabel, &s_python_function_gca, &s_python_function_xticks, &s_python_function_yticks, &s_python_function_margins, &s_python_function_tick_params, &s_python_function_grid, &s_python_function_cla, &s_python_function_clf, &s_python_function_errorbar, &s_python_function_annotate, &s_python_function_tight_layout, &s_python_colormap, &s_python_empty_tuple, &s_python_function_stem, &s_python_function_xkcd, &s_python_function_text, &s_python_function_suptitle, &s_python_function_bar, &s_python_function_barh, &s_python_function_colorbar, &s_python_function_subplots_adjust, &s_python_function_rcparams, &s_python_function_spy, #ifndef WITHOUT_NUMPY &s_python_function_imshow, #endif }; for (PyObject** object : objects) { Py_XDECREF(*object); *object = nullptr; } } // Returns the keyword that matplotlib.pyplot.boxplot() expects for the // tick labels: `tick_labels` from matplotlib 3.9 on, `labels` before. static const char* boxplot_labels_keyword(PyObject* matplotlib) { int major = 0, minor = 0; PyObject* version = PyObject_GetAttrString(matplotlib, "__version__"); if (version) { #if PY_MAJOR_VERSION >= 3 const char* s = PyUnicode_AsUTF8(version); #else const char* s = PyString_AsString(version); #endif if (!s || std::sscanf(s, "%d.%d", &major, &minor) != 2) major = minor = 0; Py_DECREF(version); } PyErr_Clear(); return (major > 3 || (major == 3 && minor >= 9)) ? "tick_labels" : "labels"; } // Even if the interpreter installs no signal handlers, the first import // of the signal module, e.g. by matplotlib, installs Python's SIGINT // handler if SIGINT has its default action. Import it now and restore // the default action, so later imports find the module already loaded. static void restore_default_sigint() { PyObject* signal = PyImport_ImportModule(const_cast<char*>("signal")); if (!signal) { print_error(); return; } PyObject* current = PyObject_CallMethod(signal, const_cast<char*>("getsignal"), const_cast<char*>("i"), SIGINT); PyObject* python_handler = PyObject_GetAttrString(signal, "default_int_handler"); if (current && current == python_handler) { PyObject* sig_dfl = PyObject_GetAttrString(signal, "SIG_DFL"); if (sig_dfl) { check_result(PyObject_CallMethod(signal, const_cast<char*>("signal"), const_cast<char*>("iO"), SIGINT, sig_dfl)); Py_DECREF(sig_dfl); } } Py_XDECREF(python_handler); Py_XDECREF(current); Py_DECREF(signal); print_error(); } _interpreter() { // optional but recommended #if PY_MAJOR_VERSION >= 3 static wchar_t name[] = L"plotting"; #else static char name[] = "plotting"; #endif // Python's SIGINT handler only raises KeyboardInterrupt the next // time Python code runs, so a program that has used matplotlib // would no longer stop on Ctrl-C (#183). Leave the signal handlers // to the embedding program; see also restore_default_sigint(). #if PY_VERSION_HEX < 0x030B0000 Py_SetProgramName(name); Py_InitializeEx(0); wchar_t const* dummy_args[] = {L"Python", NULL}; // const is needed because literals must not be modified wchar_t const** argv = dummy_args; int argc = sizeof(dummy_args) / sizeof(dummy_args[0]) - 1; #if PY_MAJOR_VERSION >= 3 PySys_SetArgv(argc, const_cast<wchar_t**>(argv)); #else PySys_SetArgv(argc, (char**)(argv)); #endif #else PyStatus status; PyConfig config; PyConfig_InitPythonConfig(&config); config.install_signal_handlers = 0; wchar_t const* dummy_args[] = {L"Python", NULL}; // const is needed because literals must not be modified wchar_t* const* argv = const_cast<wchar_t* const*>(dummy_args); int argc = sizeof(dummy_args) / sizeof(dummy_args[0]) - 1; status = PyConfig_SetString(&config, &config.program_name, name); if (PyStatus_Exception(status)) { PyConfig_Clear(&config); throw std::runtime_error("Failed to initialize Python interpreter"); } status = PyConfig_SetArgv(&config, argc, argv); if (PyStatus_Exception(status)) { PyConfig_Clear(&config); throw std::runtime_error("Failed to initialize Python interpreter"); } status = Py_InitializeFromConfig(&config); if (PyStatus_Exception(status)) { PyConfig_Clear(&config); throw std::runtime_error("Failed to initialize Python interpreter"); } PyConfig_Clear(&config); #endif restore_default_sigint(); #ifndef WITHOUT_NUMPY import_numpy(); #endif PyObject* matplotlibname = PyString_FromString("matplotlib"); PyObject* pyplotname = PyString_FromString("matplotlib.pyplot"); PyObject* cmname = PyString_FromString("matplotlib.cm"); PyObject* pylabname = PyString_FromString("pylab"); if (!pyplotname || !pylabname || !matplotlibname || !cmname) { detail::fail("couldnt create string"); } PyObject* matplotlib = PyImport_Import(matplotlibname); Py_DECREF(matplotlibname); if (!matplotlib) { PyErr_Print(); throw std::runtime_error("Error loading module matplotlib!"); } s_boxplot_labels_keyword = boxplot_labels_keyword(matplotlib); // matplotlib.use() must be called *before* pylab, matplotlib.pyplot, // or matplotlib.backends is imported for the first time if (!backend_name().empty()) { PyObject* res = PyObject_CallMethod(matplotlib, const_cast<char*>("use"), const_cast<char*>("s"), backend_name().c_str()); check_result(res); } PyObject* pymod = PyImport_Import(pyplotname); Py_DECREF(pyplotname); if (!pymod) { PyErr_Print(); throw std::runtime_error("Error loading module matplotlib.pyplot!"); } s_python_colormap = PyImport_Import(cmname); Py_DECREF(cmname); if (!s_python_colormap) { PyErr_Print(); throw std::runtime_error("Error loading module matplotlib.cm!"); } PyObject* pylabmod = PyImport_Import(pylabname); Py_DECREF(pylabname); if (!pylabmod) { PyErr_Print(); throw std::runtime_error("Error loading module pylab!"); } s_python_function_arrow = safe_import(pymod, "arrow"); s_python_function_show = safe_import(pymod, "show"); s_python_function_close = safe_import(pymod, "close"); s_python_function_draw = safe_import(pymod, "draw"); s_python_function_pause = safe_import(pymod, "pause"); s_python_function_figure = safe_import(pymod, "figure"); s_python_function_fignum_exists = safe_import(pymod, "fignum_exists"); s_python_function_gcf = safe_import(pymod, "gcf"); s_python_function_plot = safe_import(pymod, "plot"); s_python_function_quiver = safe_import(pymod, "quiver"); s_python_function_contour = safe_import(pymod, "contour"); s_python_function_contourf = safe_import(pymod, "contourf"); s_python_function_semilogx = safe_import(pymod, "semilogx"); s_python_function_semilogy = safe_import(pymod, "semilogy"); s_python_function_loglog = safe_import(pymod, "loglog"); s_python_function_fill = safe_import(pymod, "fill"); s_python_function_fill_between = safe_import(pymod, "fill_between"); s_python_function_hist = safe_import(pymod, "hist"); s_python_function_scatter = safe_import(pymod, "scatter"); s_python_function_boxplot = safe_import(pymod, "boxplot"); s_python_function_subplot = safe_import(pymod, "subplot"); s_python_function_subplot2grid = safe_import(pymod, "subplot2grid"); s_python_function_legend = safe_import(pymod, "legend"); s_python_function_xlim = safe_import(pymod, "xlim"); s_python_function_ylim = safe_import(pymod, "ylim"); s_python_function_title = safe_import(pymod, "title"); s_python_function_axis = safe_import(pymod, "axis"); s_python_function_axhline = safe_import(pymod, "axhline"); s_python_function_axvline = safe_import(pymod, "axvline"); s_python_function_axvspan = safe_import(pymod, "axvspan"); s_python_function_xlabel = safe_import(pymod, "xlabel"); s_python_function_ylabel = safe_import(pymod, "ylabel"); s_python_function_gca = safe_import(pymod, "gca"); s_python_function_xticks = safe_import(pymod, "xticks"); s_python_function_yticks = safe_import(pymod, "yticks"); s_python_function_margins = safe_import(pymod, "margins"); s_python_function_tick_params = safe_import(pymod, "tick_params"); s_python_function_grid = safe_import(pymod, "grid"); s_python_function_ion = safe_import(pymod, "ion"); s_python_function_ioff = safe_import(pymod, "ioff"); s_python_function_ginput = safe_import(pymod, "ginput"); s_python_function_save = safe_import(pylabmod, "savefig"); s_python_function_annotate = safe_import(pymod, "annotate"); s_python_function_cla = safe_import(pymod, "cla"); s_python_function_clf = safe_import(pymod, "clf"); s_python_function_errorbar = safe_import(pymod, "errorbar"); s_python_function_tight_layout = safe_import(pymod, "tight_layout"); s_python_function_stem = safe_import(pymod, "stem"); s_python_function_xkcd = safe_import(pymod, "xkcd"); s_python_function_text = safe_import(pymod, "text"); s_python_function_suptitle = safe_import(pymod, "suptitle"); s_python_function_bar = safe_import(pymod, "bar"); s_python_function_barh = safe_import(pymod, "barh"); s_python_function_colorbar = PyObject_GetAttrString(pymod, "colorbar"); s_python_function_subplots_adjust = safe_import(pymod, "subplots_adjust"); s_python_function_rcparams = PyObject_GetAttrString(pymod, "rcParams"); s_python_function_spy = PyObject_GetAttrString(pymod, "spy"); #ifndef WITHOUT_NUMPY s_python_function_imshow = safe_import(pymod, "imshow"); #endif s_python_empty_tuple = PyTuple_New(0); state() = running; } }; } // end namespace detail /// Select the backend /// /// **NOTE:** This must be called before the first plot command to have /// any effect. /// /// Mainly useful to select the non-interactive 'Agg' backend when running /// matplotlibcpp in headless mode, for example on a machine with no display. /// /// See also: https://matplotlib.org/2.0.2/api/matplotlib_configuration_api.html#matplotlib.use inline void backend(const std::string& name) { detail::backend_name() = name; } /// Shut down the embedded Python interpreter /// /// By default, the interpreter is never shut down: the operating system /// reclaims its resources when the program exits. Call finalize() when /// Python must shut down cleanly, e.g. at the end of main() so that Python's /// atexit handlers run, or so that leak checkers see the memory released. /// /// **NOTE:** No plotting function may be called afterwards; they throw /// std::runtime_error, even if nothing was plotted before. Call it in the /// thread that plotted. Calling it again does nothing, and it does not start /// the interpreter just to finalize it. inline void finalize() { detail::_interpreter::finalize(); } inline bool annotate(std::string annotation, double x, double y) { detail::_interpreter::get(); PyObject* xy = PyTuple_New(2); PyObject* str = PyString_FromString(annotation.c_str()); PyTuple_SetItem(xy, 0, PyFloat_FromDouble(x)); PyTuple_SetItem(xy, 1, PyFloat_FromDouble(y)); PyObject* kwargs = PyDict_New(); detail::set_kwarg(kwargs, "xy", xy); PyObject* args = PyTuple_New(1); PyTuple_SetItem(args, 0, str); PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_annotate, args, kwargs); Py_DECREF(args); Py_DECREF(kwargs); return detail::check_result(res); } namespace detail { #ifndef WITHOUT_NUMPY // Type selector for numpy array conversion. // Specialize on the distinct fundamental types, not on the fixed-width typedefs: // int64_t is `long` on some platforms and `long long` on others, so specializing // on both would be a redefinition there. numpy's C-type enums match the C types // on every platform, and int8_t...uint64_t resolve to one of these automatically. template <typename T> struct select_npy_type { const static NPY_TYPES type = NPY_NOTYPE; }; //Default template <> struct select_npy_type<double> { const static NPY_TYPES type = NPY_DOUBLE; }; template <> struct select_npy_type<float> { const static NPY_TYPES type = NPY_FLOAT; }; template <> struct select_npy_type<bool> { const static NPY_TYPES type = NPY_BOOL; }; template <> struct select_npy_type<signed char> { const static NPY_TYPES type = NPY_BYTE; }; template <> struct select_npy_type<short> { const static NPY_TYPES type = NPY_SHORT; }; template <> struct select_npy_type<int> { const static NPY_TYPES type = NPY_INT; }; template <> struct select_npy_type<long> { const static NPY_TYPES type = NPY_LONG; }; template <> struct select_npy_type<long long> { const static NPY_TYPES type = NPY_LONGLONG; }; template <> struct select_npy_type<unsigned char> { const static NPY_TYPES type = NPY_UBYTE; }; template <> struct select_npy_type<unsigned short> { const static NPY_TYPES type = NPY_USHORT; }; template <> struct select_npy_type<unsigned int> { const static NPY_TYPES type = NPY_UINT; }; template <> struct select_npy_type<unsigned long> { const static NPY_TYPES type = NPY_ULONG; }; template <> struct select_npy_type<unsigned long long> { const static NPY_TYPES type = NPY_ULONGLONG; }; // Returns a new numpy array with a copy of v; types that numpy has no // equivalent for are converted to double. The array must not refer to the // vector's memory: matplotlib can keep the arrays it is given, and the vector // may be a temporary, as in plot({1, 2, 3}) (#188, #350). template <typename Numeric> PyObject* get_array(const std::vector<Numeric>& v) { import_numpy(); npy_intp vsize = static_cast<npy_intp>(v.size()); NPY_TYPES type = select_npy_type<Numeric>::type; PyObject* varray = PyArray_SimpleNew(1, &vsize, type == NPY_NOTYPE ? NPY_DOUBLE : type); if (!varray) fail("Couldn't create numpy array"); void* data = PyArray_DATA(reinterpret_cast<PyArrayObject*>(varray)); if (type == NPY_NOTYPE) std::copy(v.begin(), v.end(), static_cast<double*>(data)); else std::copy(v.begin(), v.end(), static_cast<Numeric*>(data)); return varray; } template <typename Numeric> PyObject* get_2darray(const std::vector<::std::vector<Numeric>>& v) { if (v.size() < 1) throw std::runtime_error("get_2d_array v too small"); import_numpy(); npy_intp vsize[2] = {static_cast<npy_intp>(v.size()), static_cast<npy_intp>(v[0].size())}; PyArrayObject* varray = (PyArrayObject*)PyArray_SimpleNew(2, vsize, NPY_DOUBLE); double* vd_begin = static_cast<double*>(PyArray_DATA(varray)); for (const ::std::vector<Numeric>& v_row : v) { if (v_row.size() != static_cast<size_t>(vsize[1])) throw std::runtime_error("Missmatched array size"); std::copy(v_row.begin(), v_row.end(), vd_begin); vd_begin += vsize[1]; } return reinterpret_cast<PyObject*>(varray); } #else // fallback if we don't have numpy: copy every element of the given vector template <typename Numeric> PyObject* get_array(const std::vector<Numeric>& v) { PyObject* list = PyList_New(v.size()); for (size_t i = 0; i < v.size(); ++i) { PyList_SetItem(list, i, PyFloat_FromDouble(v.at(i))); } return list; } #endif // WITHOUT_NUMPY // sometimes, for labels and such, we need string arrays inline PyObject* get_array(const std::vector<std::string>& strings) { PyObject* list = PyList_New(static_cast<Py_ssize_t>(strings.size())); for (std::size_t i = 0; i < strings.size(); ++i) { PyList_SetItem(list, static_cast<Py_ssize_t>(i), PyString_FromString(strings[i].c_str())); } return list; } // not all matplotlib need 2d arrays, some prefer lists of lists template <typename Numeric> PyObject* get_listlist(const std::vector<std::vector<Numeric>>& ll) { PyObject* listlist = PyList_New(ll.size()); for (std::size_t i = 0; i < ll.size(); ++i) { PyList_SetItem(listlist, i, get_array(ll[i])); } return listlist; } // Keyword values are given as strings, but some matplotlib options only accept // numbers. For those keys, a value that is entirely numeric is passed as a // float, e.g. {"linewidth", "0.4"}; all other values are passed as strings, // so colors like "0.5", labels like "1" or fontsize "large" are unchanged. inline PyObject* keyword_value(const std::string& key, const std::string& value) { static const char* const numeric_keys[] = { "alpha", "linewidth", "lw", "linewidths", "markersize", "ms", "markeredgewidth", "mew", "zorder", "width", "widths", "scale", "headwidth", "headlength", "headaxislength", "capsize", "elinewidth", "rotation", "fontsize", "s", "shrink", "aspect", "fraction", "pad", "length", "arrow_length_ratio", "minshaft", "minlength", "capthick", "labelpad", "labelrotation", "linespacing", "vmin", "vmax", "bottom", "framealpha", "borderpad", "labelspacing", "handlelength", "handleheight", "handletextpad", "borderaxespad", "columnspacing", "markerscale"}; for (std::size_t i = 0; i < sizeof(numeric_keys) / sizeof(numeric_keys[0]); ++i) { if (key != numeric_keys[i]) continue; try { std::size_t pos; double d = std::stod(value, &pos); if (pos == value.size()) return PyFloat_FromDouble(d); } catch (const std::invalid_argument&) { } catch (const std::out_of_range&) { } break; } return PyString_FromString(value.c_str()); } // build a kwargs dict for text properties, e.g. rotation = 45 inline PyObject* text_kwargs(const std::map<std::string, std::string>& keywords) { PyObject* kwargs = PyDict_New(); for (std::map<std::string, std::string>::const_iterator it = keywords.begin(); it != keywords.end(); ++it) { PyObject* value = keyword_value(it->first, it->second); PyDict_SetItemString(kwargs, it->first.c_str(), value); Py_DECREF(value); } return kwargs; } } // namespace detail /// Plot a line through the given x and y data points.. /// /// See: https://matplotlib.org/3.2.1/api/_as_gen/matplotlib.pyplot.plot.html template <typename Numeric> bool plot(const std::vector<Numeric>& x, const std::vector<Numeric>& y, const std::map<std::string, std::string>& keywords) { assert(x.size() == y.size()); detail::_interpreter::get(); // using numpy arrays PyObject* xarray = detail::get_array(x); PyObject* yarray = detail::get_array(y); // construct positional args PyObject* args = PyTuple_New(2); PyTuple_SetItem(args, 0, xarray); PyTuple_SetItem(args, 1, yarray); // construct keyword args PyObject* kwargs = PyDict_New(); for (std::map<std::string, std::string>::const_iterator it = keywords.begin(); it != keywords.end(); ++it) { detail::set_kwarg(kwargs, it->first.c_str(), detail::keyword_value(it->first, it->second)); } PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_plot, args, kwargs); Py_DECREF(args); Py_DECREF(kwargs); return detail::check_result(res); } namespace detail { // matplotlib >= 3.6 no longer accepts `gca(projection=...)`, so reuse the // figure's current axes if it is already 3D, or add a new 3D subplot. // Returns a new reference to the axes. inline PyObject* init_3d_axis(PyObject* fig) { PyObject* axes = PyObject_GetAttrString(fig, "axes"); if (!axes) detail::fail("No axes"); Py_ssize_t naxes = PyObject_Length(axes); Py_DECREF(axes); if (naxes < 0) detail::fail("Failed to get number of axes"); if (naxes > 0) { PyObject* gca = PyObject_GetAttrString(fig, "gca"); if (!gca) detail::fail("No gca"); PyObject* axis = PyObject_CallObject(gca, _interpreter::get().s_python_empty_tuple); Py_DECREF(gca); if (!axis) detail::fail("No axis"); bool is_3d = false; PyObject* name = PyObject_GetAttrString(axis, "name"); if (name) { #if PY_MAJOR_VERSION >= 3 is_3d = PyUnicode_Check(name) && PyUnicode_CompareWithASCIIString(name, "3d") == 0; #else const char* s = PyString_AsString(name); is_3d = s && std::string(s) == "3d"; #endif Py_DECREF(name); } PyErr_Clear(); if (is_3d) return axis; Py_DECREF(axis); } PyObject* add_subplot = PyObject_GetAttrString(fig, "add_subplot"); if (!add_subplot) detail::fail("No add_subplot"); PyObject* kwargs = PyDict_New(); PyObject* projection = PyString_FromString("3d"); PyDict_SetItemString(kwargs, "projection", projection); Py_DECREF(projection); PyObject* axis = PyObject_Call(add_subplot, _interpreter::get().s_python_empty_tuple, kwargs); Py_DECREF(add_subplot); Py_DECREF(kwargs); if (!axis) detail::fail("No axis"); return axis; } // Get the figure that a 3D plot function draws into. A fig_number of 0 means // the current figure (pyplot's gcf(), which creates one if none exists). // Otherwise the given figure is used if it exists, and a new figure is // created if it does not. Returns a new reference to the figure. inline PyObject* get_3d_figure(const long fig_number) { PyObject* fig = nullptr; if (fig_number == 0) { fig = PyObject_CallObject(_interpreter::get().s_python_function_gcf, _interpreter::get().s_python_empty_tuple); if (!fig) detail::fail("Call to gcf() failed."); return fig; } PyObject* fig_args = PyTuple_New(1); PyTuple_SetItem(fig_args, 0, PyLong_FromLong(fig_number)); PyObject* fig_exists = PyObject_CallObject(_interpreter::get().s_python_function_fignum_exists, fig_args); if (!fig_exists) { Py_DECREF(fig_args); detail::fail("Call to fignum_exists() failed."); } if (!PyObject_IsTrue(fig_exists)) { fig = PyObject_CallObject(_interpreter::get().s_python_function_figure, _interpreter::get().s_python_empty_tuple); } else { fig = PyObject_CallObject(_interpreter::get().s_python_function_figure, fig_args); } Py_DECREF(fig_exists); Py_DECREF(fig_args); if (!fig) detail::fail("Call to figure() failed."); return fig; } } // namespace detail // TODO - it should be possible to make this work by implementing // a non-numpy alternative for `detail::get_2darray()`. #ifndef WITHOUT_NUMPY template <typename Numeric> void plot_surface(const std::vector<::std::vector<Numeric>>& x, const std::vector<::std::vector<Numeric>>& y, const std::vector<::std::vector<Numeric>>& z, const std::map<std::string, std::string>& keywords = std::map<std::string, std::string>(), const long fig_number = 0) { detail::_interpreter::get(); // We lazily load the modules here the first time this function is called // because I'm not sure that we can assume "matplotlib installed" implies // "mpl_toolkits installed" on all platforms, and we don't want to require // it for people who don't need 3d plots. static PyObject *mpl_toolkitsmod = nullptr, *axis3dmod = nullptr; if (!mpl_toolkitsmod) { detail::_interpreter::get(); PyObject* mpl_toolkits = PyString_FromString("mpl_toolkits"); PyObject* axis3d = PyString_FromString("mpl_toolkits.mplot3d"); if (!mpl_toolkits || !axis3d) { detail::fail("couldnt create string"); } mpl_toolkitsmod = PyImport_Import(mpl_toolkits); Py_DECREF(mpl_toolkits); if (!mpl_toolkitsmod) { detail::fail("Error loading module mpl_toolkits!"); } axis3dmod = PyImport_Import(axis3d); Py_DECREF(axis3d); if (!axis3dmod) { detail::fail("Error loading module mpl_toolkits.mplot3d!"); } } assert(x.size() == y.size()); assert(y.size() == z.size()); // using numpy arrays PyObject* xarray = detail::get_2darray(x); PyObject* yarray = detail::get_2darray(y); PyObject* zarray = detail::get_2darray(z); // construct positional args PyObject* args = PyTuple_New(3); PyTuple_SetItem(args, 0, xarray); PyTuple_SetItem(args, 1, yarray); PyTuple_SetItem(args, 2, zarray); // Build up the kw args. PyObject* kwargs = PyDict_New(); detail::set_kwarg(kwargs, "rstride", PyInt_FromLong(1)); detail::set_kwarg(kwargs, "cstride", PyInt_FromLong(1)); PyObject* python_colormap_coolwarm = PyObject_GetAttrString( detail::_interpreter::get().s_python_colormap, "coolwarm"); detail::set_kwarg(kwargs, "cmap", python_colormap_coolwarm); for (std::map<std::string, std::string>::const_iterator it = keywords.begin(); it != keywords.end(); ++it) { if (it->first == "linewidth" || it->first == "alpha") { detail::set_kwarg(kwargs, it->first.c_str(), PyFloat_FromDouble(std::stod(it->second))); |
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |