1
0

matplotlibcpp.h 85 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640
  1. #pragma once
  2. // Python headers must be included before any system headers, since
  3. // they define _POSIX_C_SOURCE
  4. #include <Python.h>
  5. #include <vector>
  6. #include <map>
  7. #include <array>
  8. #include <numeric>
  9. #include <algorithm>
  10. #include <stdexcept>
  11. #include <iostream>
  12. #include <cstdint> // <cstdint> requires c++11 support
  13. #include <functional>
  14. #ifndef WITHOUT_NUMPY
  15. # define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
  16. # include <numpy/arrayobject.h>
  17. # ifdef WITH_OPENCV
  18. # include <opencv2/opencv.hpp>
  19. # endif // WITH_OPENCV
  20. /*
  21. * A bunch of constants were removed in OpenCV 4 in favour of enum classes, so
  22. * define the ones we need here.
  23. */
  24. # if CV_MAJOR_VERSION > 3
  25. # define CV_BGR2RGB cv::COLOR_BGR2RGB
  26. # define CV_BGRA2RGBA cv::COLOR_BGRA2RGBA
  27. # endif
  28. #endif // WITHOUT_NUMPY
  29. #if PY_MAJOR_VERSION >= 3
  30. # define PyString_FromString PyUnicode_FromString
  31. # define PyInt_FromLong PyLong_FromLong
  32. # define PyString_FromString PyUnicode_FromString
  33. #endif
  34. namespace matplotlibcpp {
  35. namespace detail {
  36. static std::string s_backend;
  37. struct _interpreter {
  38. PyObject* s_python_function_arrow;
  39. PyObject *s_python_function_show;
  40. PyObject *s_python_function_close;
  41. PyObject *s_python_function_draw;
  42. PyObject *s_python_function_pause;
  43. PyObject *s_python_function_save;
  44. PyObject *s_python_function_figure;
  45. PyObject *s_python_function_fignum_exists;
  46. PyObject *s_python_function_plot;
  47. PyObject *s_python_function_quiver;
  48. PyObject* s_python_function_contour;
  49. PyObject *s_python_function_semilogx;
  50. PyObject *s_python_function_semilogy;
  51. PyObject *s_python_function_loglog;
  52. PyObject *s_python_function_fill;
  53. PyObject *s_python_function_fill_between;
  54. PyObject *s_python_function_hist;
  55. PyObject *s_python_function_imshow;
  56. PyObject *s_python_function_scatter;
  57. PyObject *s_python_function_boxplot;
  58. PyObject *s_python_function_subplot;
  59. PyObject *s_python_function_subplot2grid;
  60. PyObject *s_python_function_legend;
  61. PyObject *s_python_function_xlim;
  62. PyObject *s_python_function_ion;
  63. PyObject *s_python_function_ginput;
  64. PyObject *s_python_function_ylim;
  65. PyObject *s_python_function_title;
  66. PyObject *s_python_function_axis;
  67. PyObject *s_python_function_axvline;
  68. PyObject *s_python_function_axvspan;
  69. PyObject *s_python_function_xlabel;
  70. PyObject *s_python_function_ylabel;
  71. PyObject *s_python_function_gca;
  72. PyObject *s_python_function_xticks;
  73. PyObject *s_python_function_yticks;
  74. PyObject* s_python_function_margins;
  75. PyObject *s_python_function_tick_params;
  76. PyObject *s_python_function_grid;
  77. PyObject* s_python_function_cla;
  78. PyObject *s_python_function_clf;
  79. PyObject *s_python_function_errorbar;
  80. PyObject *s_python_function_annotate;
  81. PyObject *s_python_function_tight_layout;
  82. PyObject *s_python_colormap;
  83. PyObject *s_python_empty_tuple;
  84. PyObject *s_python_function_stem;
  85. PyObject *s_python_function_xkcd;
  86. PyObject *s_python_function_text;
  87. PyObject *s_python_function_suptitle;
  88. PyObject *s_python_function_bar;
  89. PyObject *s_python_function_barh;
  90. PyObject *s_python_function_colorbar;
  91. PyObject *s_python_function_subplots_adjust;
  92. /* For now, _interpreter is implemented as a singleton since its currently not possible to have
  93. multiple independent embedded python interpreters without patching the python source code
  94. or starting a separate process for each. [1]
  95. Furthermore, many python objects expect that they are destructed in the same thread as they
  96. were constructed. [2] So for advanced usage, a `kill()` function is provided so that library
  97. users can manually ensure that the interpreter is constructed and destroyed within the
  98. same thread.
  99. 1: http://bytes.com/topic/python/answers/793370-multiple-independent-python-interpreters-c-c-program
  100. 2: https://github.com/lava/matplotlib-cpp/pull/202#issue-436220256
  101. */
  102. static _interpreter& get() {
  103. return interkeeper(false);
  104. }
  105. static _interpreter& kill() {
  106. return interkeeper(true);
  107. }
  108. // Stores the actual singleton object referenced by `get()` and `kill()`.
  109. static _interpreter& interkeeper(bool should_kill) {
  110. static _interpreter ctx;
  111. if (should_kill)
  112. ctx.~_interpreter();
  113. return ctx;
  114. }
  115. PyObject* safe_import(PyObject* module, std::string fname) {
  116. PyObject* fn = PyObject_GetAttrString(module, fname.c_str());
  117. if (!fn)
  118. throw std::runtime_error(std::string("Couldn't find required function: ") + fname);
  119. if (!PyFunction_Check(fn))
  120. throw std::runtime_error(fname + std::string(" is unexpectedly not a PyFunction."));
  121. return fn;
  122. }
  123. private:
  124. #ifndef WITHOUT_NUMPY
  125. # if PY_MAJOR_VERSION >= 3
  126. void *import_numpy() {
  127. import_array(); // initialize C-API
  128. return NULL;
  129. }
  130. # else
  131. void import_numpy() {
  132. import_array(); // initialize C-API
  133. }
  134. # endif
  135. #endif
  136. _interpreter() {
  137. // optional but recommended
  138. #if PY_MAJOR_VERSION >= 3
  139. wchar_t name[] = L"plotting";
  140. #else
  141. char name[] = "plotting";
  142. #endif
  143. Py_SetProgramName(name);
  144. Py_Initialize();
  145. wchar_t const *dummy_args[] = {L"Python", NULL}; // const is needed because literals must not be modified
  146. wchar_t const **argv = dummy_args;
  147. int argc = sizeof(dummy_args)/sizeof(dummy_args[0])-1;
  148. PySys_SetArgv(argc, const_cast<wchar_t **>(argv));
  149. #ifndef WITHOUT_NUMPY
  150. import_numpy(); // initialize numpy C-API
  151. #endif
  152. PyObject* matplotlibname = PyString_FromString("matplotlib");
  153. PyObject* pyplotname = PyString_FromString("matplotlib.pyplot");
  154. PyObject* cmname = PyString_FromString("matplotlib.cm");
  155. PyObject* pylabname = PyString_FromString("pylab");
  156. if (!pyplotname || !pylabname || !matplotlibname || !cmname) {
  157. throw std::runtime_error("couldnt create string");
  158. }
  159. PyObject* matplotlib = PyImport_Import(matplotlibname);
  160. Py_DECREF(matplotlibname);
  161. if (!matplotlib) {
  162. PyErr_Print();
  163. throw std::runtime_error("Error loading module matplotlib!");
  164. }
  165. // matplotlib.use() must be called *before* pylab, matplotlib.pyplot,
  166. // or matplotlib.backends is imported for the first time
  167. if (!s_backend.empty()) {
  168. PyObject_CallMethod(matplotlib, const_cast<char*>("use"), const_cast<char*>("s"), s_backend.c_str());
  169. }
  170. PyObject* pymod = PyImport_Import(pyplotname);
  171. Py_DECREF(pyplotname);
  172. if (!pymod) { throw std::runtime_error("Error loading module matplotlib.pyplot!"); }
  173. s_python_colormap = PyImport_Import(cmname);
  174. Py_DECREF(cmname);
  175. if (!s_python_colormap) { throw std::runtime_error("Error loading module matplotlib.cm!"); }
  176. PyObject* pylabmod = PyImport_Import(pylabname);
  177. Py_DECREF(pylabname);
  178. if (!pylabmod) { throw std::runtime_error("Error loading module pylab!"); }
  179. s_python_function_arrow = safe_import(pymod, "arrow");
  180. s_python_function_show = safe_import(pymod, "show");
  181. s_python_function_close = safe_import(pymod, "close");
  182. s_python_function_draw = safe_import(pymod, "draw");
  183. s_python_function_pause = safe_import(pymod, "pause");
  184. s_python_function_figure = safe_import(pymod, "figure");
  185. s_python_function_fignum_exists = safe_import(pymod, "fignum_exists");
  186. s_python_function_plot = safe_import(pymod, "plot");
  187. s_python_function_quiver = safe_import(pymod, "quiver");
  188. s_python_function_contour = safe_import(pymod, "contour");
  189. s_python_function_semilogx = safe_import(pymod, "semilogx");
  190. s_python_function_semilogy = safe_import(pymod, "semilogy");
  191. s_python_function_loglog = safe_import(pymod, "loglog");
  192. s_python_function_fill = safe_import(pymod, "fill");
  193. s_python_function_fill_between = safe_import(pymod, "fill_between");
  194. s_python_function_hist = safe_import(pymod,"hist");
  195. s_python_function_scatter = safe_import(pymod,"scatter");
  196. s_python_function_boxplot = safe_import(pymod,"boxplot");
  197. s_python_function_subplot = safe_import(pymod, "subplot");
  198. s_python_function_subplot2grid = safe_import(pymod, "subplot2grid");
  199. s_python_function_legend = safe_import(pymod, "legend");
  200. s_python_function_ylim = safe_import(pymod, "ylim");
  201. s_python_function_title = safe_import(pymod, "title");
  202. s_python_function_axis = safe_import(pymod, "axis");
  203. s_python_function_axvline = safe_import(pymod, "axvline");
  204. s_python_function_axvspan = safe_import(pymod, "axvspan");
  205. s_python_function_xlabel = safe_import(pymod, "xlabel");
  206. s_python_function_ylabel = safe_import(pymod, "ylabel");
  207. s_python_function_gca = safe_import(pymod, "gca");
  208. s_python_function_xticks = safe_import(pymod, "xticks");
  209. s_python_function_yticks = safe_import(pymod, "yticks");
  210. s_python_function_margins = safe_import(pymod, "margins");
  211. s_python_function_tick_params = safe_import(pymod, "tick_params");
  212. s_python_function_grid = safe_import(pymod, "grid");
  213. s_python_function_xlim = safe_import(pymod, "xlim");
  214. s_python_function_ion = safe_import(pymod, "ion");
  215. s_python_function_ginput = safe_import(pymod, "ginput");
  216. s_python_function_save = safe_import(pylabmod, "savefig");
  217. s_python_function_annotate = safe_import(pymod,"annotate");
  218. s_python_function_cla = safe_import(pymod, "cla");
  219. s_python_function_clf = safe_import(pymod, "clf");
  220. s_python_function_errorbar = safe_import(pymod, "errorbar");
  221. s_python_function_tight_layout = safe_import(pymod, "tight_layout");
  222. s_python_function_stem = safe_import(pymod, "stem");
  223. s_python_function_xkcd = safe_import(pymod, "xkcd");
  224. s_python_function_text = safe_import(pymod, "text");
  225. s_python_function_suptitle = safe_import(pymod, "suptitle");
  226. s_python_function_bar = safe_import(pymod,"bar");
  227. s_python_function_barh = safe_import(pymod, "barh");
  228. s_python_function_colorbar = PyObject_GetAttrString(pymod, "colorbar");
  229. s_python_function_subplots_adjust = safe_import(pymod,"subplots_adjust");
  230. #ifndef WITHOUT_NUMPY
  231. s_python_function_imshow = safe_import(pymod, "imshow");
  232. #endif
  233. s_python_empty_tuple = PyTuple_New(0);
  234. }
  235. ~_interpreter() {
  236. Py_Finalize();
  237. }
  238. };
  239. } // end namespace detail
  240. /// Select the backend
  241. ///
  242. /// **NOTE:** This must be called before the first plot command to have
  243. /// any effect.
  244. ///
  245. /// Mainly useful to select the non-interactive 'Agg' backend when running
  246. /// matplotlibcpp in headless mode, for example on a machine with no display.
  247. ///
  248. /// See also: https://matplotlib.org/2.0.2/api/matplotlib_configuration_api.html#matplotlib.use
  249. inline void backend(const std::string& name)
  250. {
  251. detail::s_backend = name;
  252. }
  253. inline bool annotate(std::string annotation, double x, double y)
  254. {
  255. detail::_interpreter::get();
  256. PyObject * xy = PyTuple_New(2);
  257. PyObject * str = PyString_FromString(annotation.c_str());
  258. PyTuple_SetItem(xy,0,PyFloat_FromDouble(x));
  259. PyTuple_SetItem(xy,1,PyFloat_FromDouble(y));
  260. PyObject* kwargs = PyDict_New();
  261. PyDict_SetItemString(kwargs, "xy", xy);
  262. PyObject* args = PyTuple_New(1);
  263. PyTuple_SetItem(args, 0, str);
  264. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_annotate, args, kwargs);
  265. Py_DECREF(args);
  266. Py_DECREF(kwargs);
  267. if(res) Py_DECREF(res);
  268. return res;
  269. }
  270. namespace detail {
  271. #ifndef WITHOUT_NUMPY
  272. // Type selector for numpy array conversion
  273. template <typename T> struct select_npy_type { const static NPY_TYPES type = NPY_NOTYPE; }; //Default
  274. template <> struct select_npy_type<double> { const static NPY_TYPES type = NPY_DOUBLE; };
  275. template <> struct select_npy_type<float> { const static NPY_TYPES type = NPY_FLOAT; };
  276. template <> struct select_npy_type<bool> { const static NPY_TYPES type = NPY_BOOL; };
  277. template <> struct select_npy_type<int8_t> { const static NPY_TYPES type = NPY_INT8; };
  278. template <> struct select_npy_type<int16_t> { const static NPY_TYPES type = NPY_SHORT; };
  279. template <> struct select_npy_type<int32_t> { const static NPY_TYPES type = NPY_INT; };
  280. template <> struct select_npy_type<int64_t> { const static NPY_TYPES type = NPY_INT64; };
  281. template <> struct select_npy_type<uint8_t> { const static NPY_TYPES type = NPY_UINT8; };
  282. template <> struct select_npy_type<uint16_t> { const static NPY_TYPES type = NPY_USHORT; };
  283. template <> struct select_npy_type<uint32_t> { const static NPY_TYPES type = NPY_ULONG; };
  284. template <> struct select_npy_type<uint64_t> { const static NPY_TYPES type = NPY_UINT64; };
  285. // Sanity checks; comment them out or change the numpy type below if you're compiling on
  286. // a platform where they don't apply
  287. static_assert(sizeof(long long) == 8);
  288. template <> struct select_npy_type<long long> { const static NPY_TYPES type = NPY_INT64; };
  289. static_assert(sizeof(unsigned long long) == 8);
  290. template <> struct select_npy_type<unsigned long long> { const static NPY_TYPES type = NPY_UINT64; };
  291. // TODO: add int, long, etc.
  292. template<typename Numeric>
  293. PyObject* get_array(const std::vector<Numeric>& v)
  294. {
  295. npy_intp vsize = v.size();
  296. NPY_TYPES type = select_npy_type<Numeric>::type;
  297. if (type == NPY_NOTYPE) {
  298. size_t memsize = v.size()*sizeof(double);
  299. double* dp = static_cast<double*>(::malloc(memsize));
  300. for (size_t i=0; i<v.size(); ++i)
  301. dp[i] = v[i];
  302. PyObject* varray = PyArray_SimpleNewFromData(1, &vsize, NPY_DOUBLE, dp);
  303. PyArray_UpdateFlags(reinterpret_cast<PyArrayObject*>(varray), NPY_ARRAY_OWNDATA);
  304. return varray;
  305. }
  306. PyObject* varray = PyArray_SimpleNewFromData(1, &vsize, type, (void*)(v.data()));
  307. return varray;
  308. }
  309. template<typename Numeric>
  310. PyObject* get_2darray(const std::vector<::std::vector<Numeric>>& v)
  311. {
  312. if (v.size() < 1) throw std::runtime_error("get_2d_array v too small");
  313. npy_intp vsize[2] = {static_cast<npy_intp>(v.size()),
  314. static_cast<npy_intp>(v[0].size())};
  315. PyArrayObject *varray =
  316. (PyArrayObject *)PyArray_SimpleNew(2, vsize, NPY_DOUBLE);
  317. double *vd_begin = static_cast<double *>(PyArray_DATA(varray));
  318. for (const ::std::vector<Numeric> &v_row : v) {
  319. if (v_row.size() != static_cast<size_t>(vsize[1]))
  320. throw std::runtime_error("Missmatched array size");
  321. std::copy(v_row.begin(), v_row.end(), vd_begin);
  322. vd_begin += vsize[1];
  323. }
  324. return reinterpret_cast<PyObject *>(varray);
  325. }
  326. #else // fallback if we don't have numpy: copy every element of the given vector
  327. template<typename Numeric>
  328. PyObject* get_array(const std::vector<Numeric>& v)
  329. {
  330. PyObject* list = PyList_New(v.size());
  331. for(size_t i = 0; i < v.size(); ++i) {
  332. PyList_SetItem(list, i, PyFloat_FromDouble(v.at(i)));
  333. }
  334. return list;
  335. }
  336. #endif // WITHOUT_NUMPY
  337. // sometimes, for labels and such, we need string arrays
  338. inline PyObject * get_array(const std::vector<std::string>& strings)
  339. {
  340. PyObject* list = PyList_New(strings.size());
  341. for (std::size_t i = 0; i < strings.size(); ++i) {
  342. PyList_SetItem(list, i, PyString_FromString(strings[i].c_str()));
  343. }
  344. return list;
  345. }
  346. // not all matplotlib need 2d arrays, some prefer lists of lists
  347. template<typename Numeric>
  348. PyObject* get_listlist(const std::vector<std::vector<Numeric>>& ll)
  349. {
  350. PyObject* listlist = PyList_New(ll.size());
  351. for (std::size_t i = 0; i < ll.size(); ++i) {
  352. PyList_SetItem(listlist, i, get_array(ll[i]));
  353. }
  354. return listlist;
  355. }
  356. } // namespace detail
  357. /// Plot a line through the given x and y data points..
  358. ///
  359. /// See: https://matplotlib.org/3.2.1/api/_as_gen/matplotlib.pyplot.plot.html
  360. template<typename Numeric>
  361. bool plot(const std::vector<Numeric> &x, const std::vector<Numeric> &y, const std::map<std::string, std::string>& keywords)
  362. {
  363. assert(x.size() == y.size());
  364. detail::_interpreter::get();
  365. // using numpy arrays
  366. PyObject* xarray = detail::get_array(x);
  367. PyObject* yarray = detail::get_array(y);
  368. // construct positional args
  369. PyObject* args = PyTuple_New(2);
  370. PyTuple_SetItem(args, 0, xarray);
  371. PyTuple_SetItem(args, 1, yarray);
  372. // construct keyword args
  373. PyObject* kwargs = PyDict_New();
  374. for(std::map<std::string, std::string>::const_iterator it = keywords.begin(); it != keywords.end(); ++it)
  375. {
  376. PyDict_SetItemString(kwargs, it->first.c_str(), PyString_FromString(it->second.c_str()));
  377. }
  378. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_plot, args, kwargs);
  379. Py_DECREF(args);
  380. Py_DECREF(kwargs);
  381. if(res) Py_DECREF(res);
  382. return res;
  383. }
  384. // TODO - it should be possible to make this work by implementing
  385. // a non-numpy alternative for `detail::get_2darray()`.
  386. #ifndef WITHOUT_NUMPY
  387. template <typename Numeric>
  388. void plot_surface(const std::vector<::std::vector<Numeric>> &x,
  389. const std::vector<::std::vector<Numeric>> &y,
  390. const std::vector<::std::vector<Numeric>> &z,
  391. const std::map<std::string, std::string> &keywords =
  392. std::map<std::string, std::string>())
  393. {
  394. detail::_interpreter::get();
  395. // We lazily load the modules here the first time this function is called
  396. // because I'm not sure that we can assume "matplotlib installed" implies
  397. // "mpl_toolkits installed" on all platforms, and we don't want to require
  398. // it for people who don't need 3d plots.
  399. static PyObject *mpl_toolkitsmod = nullptr, *axis3dmod = nullptr;
  400. if (!mpl_toolkitsmod) {
  401. detail::_interpreter::get();
  402. PyObject* mpl_toolkits = PyString_FromString("mpl_toolkits");
  403. PyObject* axis3d = PyString_FromString("mpl_toolkits.mplot3d");
  404. if (!mpl_toolkits || !axis3d) { throw std::runtime_error("couldnt create string"); }
  405. mpl_toolkitsmod = PyImport_Import(mpl_toolkits);
  406. Py_DECREF(mpl_toolkits);
  407. if (!mpl_toolkitsmod) { throw std::runtime_error("Error loading module mpl_toolkits!"); }
  408. axis3dmod = PyImport_Import(axis3d);
  409. Py_DECREF(axis3d);
  410. if (!axis3dmod) { throw std::runtime_error("Error loading module mpl_toolkits.mplot3d!"); }
  411. }
  412. assert(x.size() == y.size());
  413. assert(y.size() == z.size());
  414. // using numpy arrays
  415. PyObject *xarray = detail::get_2darray(x);
  416. PyObject *yarray = detail::get_2darray(y);
  417. PyObject *zarray = detail::get_2darray(z);
  418. // construct positional args
  419. PyObject *args = PyTuple_New(3);
  420. PyTuple_SetItem(args, 0, xarray);
  421. PyTuple_SetItem(args, 1, yarray);
  422. PyTuple_SetItem(args, 2, zarray);
  423. // Build up the kw args.
  424. PyObject *kwargs = PyDict_New();
  425. PyDict_SetItemString(kwargs, "rstride", PyInt_FromLong(1));
  426. PyDict_SetItemString(kwargs, "cstride", PyInt_FromLong(1));
  427. PyObject *python_colormap_coolwarm = PyObject_GetAttrString(
  428. detail::_interpreter::get().s_python_colormap, "coolwarm");
  429. PyDict_SetItemString(kwargs, "cmap", python_colormap_coolwarm);
  430. for (std::map<std::string, std::string>::const_iterator it = keywords.begin();
  431. it != keywords.end(); ++it) {
  432. PyDict_SetItemString(kwargs, it->first.c_str(),
  433. PyString_FromString(it->second.c_str()));
  434. }
  435. PyObject *fig =
  436. PyObject_CallObject(detail::_interpreter::get().s_python_function_figure,
  437. detail::_interpreter::get().s_python_empty_tuple);
  438. if (!fig) throw std::runtime_error("Call to figure() failed.");
  439. PyObject *gca_kwargs = PyDict_New();
  440. PyDict_SetItemString(gca_kwargs, "projection", PyString_FromString("3d"));
  441. PyObject *gca = PyObject_GetAttrString(fig, "gca");
  442. if (!gca) throw std::runtime_error("No gca");
  443. Py_INCREF(gca);
  444. PyObject *axis = PyObject_Call(
  445. gca, detail::_interpreter::get().s_python_empty_tuple, gca_kwargs);
  446. if (!axis) throw std::runtime_error("No axis");
  447. Py_INCREF(axis);
  448. Py_DECREF(gca);
  449. Py_DECREF(gca_kwargs);
  450. PyObject *plot_surface = PyObject_GetAttrString(axis, "plot_surface");
  451. if (!plot_surface) throw std::runtime_error("No surface");
  452. Py_INCREF(plot_surface);
  453. PyObject *res = PyObject_Call(plot_surface, args, kwargs);
  454. if (!res) throw std::runtime_error("failed surface");
  455. Py_DECREF(plot_surface);
  456. Py_DECREF(axis);
  457. Py_DECREF(args);
  458. Py_DECREF(kwargs);
  459. if (res) Py_DECREF(res);
  460. }
  461. #endif // WITHOUT_NUMPY
  462. template <typename Numeric>
  463. void plot3(const std::vector<Numeric> &x,
  464. const std::vector<Numeric> &y,
  465. const std::vector<Numeric> &z,
  466. const std::map<std::string, std::string> &keywords =
  467. std::map<std::string, std::string>())
  468. {
  469. detail::_interpreter::get();
  470. // Same as with plot_surface: We lazily load the modules here the first time
  471. // this function is called because I'm not sure that we can assume "matplotlib
  472. // installed" implies "mpl_toolkits installed" on all platforms, and we don't
  473. // want to require it for people who don't need 3d plots.
  474. static PyObject *mpl_toolkitsmod = nullptr, *axis3dmod = nullptr;
  475. if (!mpl_toolkitsmod) {
  476. detail::_interpreter::get();
  477. PyObject* mpl_toolkits = PyString_FromString("mpl_toolkits");
  478. PyObject* axis3d = PyString_FromString("mpl_toolkits.mplot3d");
  479. if (!mpl_toolkits || !axis3d) { throw std::runtime_error("couldnt create string"); }
  480. mpl_toolkitsmod = PyImport_Import(mpl_toolkits);
  481. Py_DECREF(mpl_toolkits);
  482. if (!mpl_toolkitsmod) { throw std::runtime_error("Error loading module mpl_toolkits!"); }
  483. axis3dmod = PyImport_Import(axis3d);
  484. Py_DECREF(axis3d);
  485. if (!axis3dmod) { throw std::runtime_error("Error loading module mpl_toolkits.mplot3d!"); }
  486. }
  487. assert(x.size() == y.size());
  488. assert(y.size() == z.size());
  489. PyObject *xarray = detail::get_array(x);
  490. PyObject *yarray = detail::get_array(y);
  491. PyObject *zarray = detail::get_array(z);
  492. // construct positional args
  493. PyObject *args = PyTuple_New(3);
  494. PyTuple_SetItem(args, 0, xarray);
  495. PyTuple_SetItem(args, 1, yarray);
  496. PyTuple_SetItem(args, 2, zarray);
  497. // Build up the kw args.
  498. PyObject *kwargs = PyDict_New();
  499. for (std::map<std::string, std::string>::const_iterator it = keywords.begin();
  500. it != keywords.end(); ++it) {
  501. PyDict_SetItemString(kwargs, it->first.c_str(),
  502. PyString_FromString(it->second.c_str()));
  503. }
  504. PyObject *fig =
  505. PyObject_CallObject(detail::_interpreter::get().s_python_function_figure,
  506. detail::_interpreter::get().s_python_empty_tuple);
  507. if (!fig) throw std::runtime_error("Call to figure() failed.");
  508. PyObject *gca_kwargs = PyDict_New();
  509. PyDict_SetItemString(gca_kwargs, "projection", PyString_FromString("3d"));
  510. PyObject *gca = PyObject_GetAttrString(fig, "gca");
  511. if (!gca) throw std::runtime_error("No gca");
  512. Py_INCREF(gca);
  513. PyObject *axis = PyObject_Call(
  514. gca, detail::_interpreter::get().s_python_empty_tuple, gca_kwargs);
  515. if (!axis) throw std::runtime_error("No axis");
  516. Py_INCREF(axis);
  517. Py_DECREF(gca);
  518. Py_DECREF(gca_kwargs);
  519. PyObject *plot3 = PyObject_GetAttrString(axis, "plot");
  520. if (!plot3) throw std::runtime_error("No 3D line plot");
  521. Py_INCREF(plot3);
  522. PyObject *res = PyObject_Call(plot3, args, kwargs);
  523. if (!res) throw std::runtime_error("Failed 3D line plot");
  524. Py_DECREF(plot3);
  525. Py_DECREF(axis);
  526. Py_DECREF(args);
  527. Py_DECREF(kwargs);
  528. if (res) Py_DECREF(res);
  529. }
  530. template<typename Numeric>
  531. bool stem(const std::vector<Numeric> &x, const std::vector<Numeric> &y, const std::map<std::string, std::string>& keywords)
  532. {
  533. assert(x.size() == y.size());
  534. detail::_interpreter::get();
  535. // using numpy arrays
  536. PyObject* xarray = detail::get_array(x);
  537. PyObject* yarray = detail::get_array(y);
  538. // construct positional args
  539. PyObject* args = PyTuple_New(2);
  540. PyTuple_SetItem(args, 0, xarray);
  541. PyTuple_SetItem(args, 1, yarray);
  542. // construct keyword args
  543. PyObject* kwargs = PyDict_New();
  544. for (std::map<std::string, std::string>::const_iterator it =
  545. keywords.begin(); it != keywords.end(); ++it) {
  546. PyDict_SetItemString(kwargs, it->first.c_str(),
  547. PyString_FromString(it->second.c_str()));
  548. }
  549. PyObject* res = PyObject_Call(
  550. detail::_interpreter::get().s_python_function_stem, args, kwargs);
  551. Py_DECREF(args);
  552. Py_DECREF(kwargs);
  553. if (res)
  554. Py_DECREF(res);
  555. return res;
  556. }
  557. template< typename Numeric >
  558. bool fill(const std::vector<Numeric>& x, const std::vector<Numeric>& y, const std::map<std::string, std::string>& keywords)
  559. {
  560. assert(x.size() == y.size());
  561. detail::_interpreter::get();
  562. // using numpy arrays
  563. PyObject* xarray = detail::get_array(x);
  564. PyObject* yarray = detail::get_array(y);
  565. // construct positional args
  566. PyObject* args = PyTuple_New(2);
  567. PyTuple_SetItem(args, 0, xarray);
  568. PyTuple_SetItem(args, 1, yarray);
  569. // construct keyword args
  570. PyObject* kwargs = PyDict_New();
  571. for (auto it = keywords.begin(); it != keywords.end(); ++it) {
  572. PyDict_SetItemString(kwargs, it->first.c_str(), PyUnicode_FromString(it->second.c_str()));
  573. }
  574. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_fill, args, kwargs);
  575. Py_DECREF(args);
  576. Py_DECREF(kwargs);
  577. if (res) Py_DECREF(res);
  578. return res;
  579. }
  580. template< typename Numeric >
  581. bool fill_between(const std::vector<Numeric>& x, const std::vector<Numeric>& y1, const std::vector<Numeric>& y2, const std::map<std::string, std::string>& keywords)
  582. {
  583. assert(x.size() == y1.size());
  584. assert(x.size() == y2.size());
  585. detail::_interpreter::get();
  586. // using numpy arrays
  587. PyObject* xarray = detail::get_array(x);
  588. PyObject* y1array = detail::get_array(y1);
  589. PyObject* y2array = detail::get_array(y2);
  590. // construct positional args
  591. PyObject* args = PyTuple_New(3);
  592. PyTuple_SetItem(args, 0, xarray);
  593. PyTuple_SetItem(args, 1, y1array);
  594. PyTuple_SetItem(args, 2, y2array);
  595. // construct keyword args
  596. PyObject* kwargs = PyDict_New();
  597. for(std::map<std::string, std::string>::const_iterator it = keywords.begin(); it != keywords.end(); ++it) {
  598. PyDict_SetItemString(kwargs, it->first.c_str(), PyUnicode_FromString(it->second.c_str()));
  599. }
  600. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_fill_between, args, kwargs);
  601. Py_DECREF(args);
  602. Py_DECREF(kwargs);
  603. if(res) Py_DECREF(res);
  604. return res;
  605. }
  606. template <typename Numeric>
  607. bool arrow(Numeric x, Numeric y, Numeric end_x, Numeric end_y, const std::string& fc = "r",
  608. const std::string ec = "k", Numeric head_length = 0.25, Numeric head_width = 0.1625) {
  609. PyObject* obj_x = PyFloat_FromDouble(x);
  610. PyObject* obj_y = PyFloat_FromDouble(y);
  611. PyObject* obj_end_x = PyFloat_FromDouble(end_x);
  612. PyObject* obj_end_y = PyFloat_FromDouble(end_y);
  613. PyObject* kwargs = PyDict_New();
  614. PyDict_SetItemString(kwargs, "fc", PyString_FromString(fc.c_str()));
  615. PyDict_SetItemString(kwargs, "ec", PyString_FromString(ec.c_str()));
  616. PyDict_SetItemString(kwargs, "head_width", PyFloat_FromDouble(head_width));
  617. PyDict_SetItemString(kwargs, "head_length", PyFloat_FromDouble(head_length));
  618. PyObject* plot_args = PyTuple_New(4);
  619. PyTuple_SetItem(plot_args, 0, obj_x);
  620. PyTuple_SetItem(plot_args, 1, obj_y);
  621. PyTuple_SetItem(plot_args, 2, obj_end_x);
  622. PyTuple_SetItem(plot_args, 3, obj_end_y);
  623. PyObject* res =
  624. PyObject_Call(detail::_interpreter::get().s_python_function_arrow, plot_args, kwargs);
  625. Py_DECREF(plot_args);
  626. Py_DECREF(kwargs);
  627. if (res)
  628. Py_DECREF(res);
  629. return res;
  630. }
  631. template< typename Numeric>
  632. bool hist(const std::vector<Numeric>& y, long bins=10,std::string color="b",
  633. double alpha=1.0, bool cumulative=false)
  634. {
  635. detail::_interpreter::get();
  636. PyObject* yarray = detail::get_array(y);
  637. PyObject* kwargs = PyDict_New();
  638. PyDict_SetItemString(kwargs, "bins", PyLong_FromLong(bins));
  639. PyDict_SetItemString(kwargs, "color", PyString_FromString(color.c_str()));
  640. PyDict_SetItemString(kwargs, "alpha", PyFloat_FromDouble(alpha));
  641. PyDict_SetItemString(kwargs, "cumulative", cumulative ? Py_True : Py_False);
  642. PyObject* plot_args = PyTuple_New(1);
  643. PyTuple_SetItem(plot_args, 0, yarray);
  644. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_hist, plot_args, kwargs);
  645. Py_DECREF(plot_args);
  646. Py_DECREF(kwargs);
  647. if(res) Py_DECREF(res);
  648. return res;
  649. }
  650. #ifndef WITHOUT_NUMPY
  651. namespace detail {
  652. inline void imshow(void *ptr, const NPY_TYPES type, const int rows, const int columns, const int colors, const std::map<std::string, std::string> &keywords, PyObject** out)
  653. {
  654. assert(type == NPY_UINT8 || type == NPY_FLOAT);
  655. assert(colors == 1 || colors == 3 || colors == 4);
  656. detail::_interpreter::get();
  657. // construct args
  658. npy_intp dims[3] = { rows, columns, colors };
  659. PyObject *args = PyTuple_New(1);
  660. PyTuple_SetItem(args, 0, PyArray_SimpleNewFromData(colors == 1 ? 2 : 3, dims, type, ptr));
  661. // construct keyword args
  662. PyObject* kwargs = PyDict_New();
  663. for(std::map<std::string, std::string>::const_iterator it = keywords.begin(); it != keywords.end(); ++it)
  664. {
  665. PyDict_SetItemString(kwargs, it->first.c_str(), PyUnicode_FromString(it->second.c_str()));
  666. }
  667. PyObject *res = PyObject_Call(detail::_interpreter::get().s_python_function_imshow, args, kwargs);
  668. Py_DECREF(args);
  669. Py_DECREF(kwargs);
  670. if (!res)
  671. throw std::runtime_error("Call to imshow() failed");
  672. if (out)
  673. *out = res;
  674. else
  675. Py_DECREF(res);
  676. }
  677. } // namespace detail
  678. inline void imshow(const unsigned char *ptr, const int rows, const int columns, const int colors, const std::map<std::string, std::string> &keywords = {}, PyObject** out = nullptr)
  679. {
  680. detail::imshow((void *) ptr, NPY_UINT8, rows, columns, colors, keywords, out);
  681. }
  682. inline void imshow(const float *ptr, const int rows, const int columns, const int colors, const std::map<std::string, std::string> &keywords = {}, PyObject** out = nullptr)
  683. {
  684. detail::imshow((void *) ptr, NPY_FLOAT, rows, columns, colors, keywords, out);
  685. }
  686. #ifdef WITH_OPENCV
  687. void imshow(const cv::Mat &image, const std::map<std::string, std::string> &keywords = {})
  688. {
  689. // Convert underlying type of matrix, if needed
  690. cv::Mat image2;
  691. NPY_TYPES npy_type = NPY_UINT8;
  692. switch (image.type() & CV_MAT_DEPTH_MASK) {
  693. case CV_8U:
  694. image2 = image;
  695. break;
  696. case CV_32F:
  697. image2 = image;
  698. npy_type = NPY_FLOAT;
  699. break;
  700. default:
  701. image.convertTo(image2, CV_MAKETYPE(CV_8U, image.channels()));
  702. }
  703. // If color image, convert from BGR to RGB
  704. switch (image2.channels()) {
  705. case 3:
  706. cv::cvtColor(image2, image2, CV_BGR2RGB);
  707. break;
  708. case 4:
  709. cv::cvtColor(image2, image2, CV_BGRA2RGBA);
  710. }
  711. detail::imshow(image2.data, npy_type, image2.rows, image2.cols, image2.channels(), keywords);
  712. }
  713. #endif // WITH_OPENCV
  714. #endif // WITHOUT_NUMPY
  715. template<typename NumericX, typename NumericY>
  716. bool scatter(const std::vector<NumericX>& x,
  717. const std::vector<NumericY>& y,
  718. const double s=1.0, // The marker size in points**2
  719. const std::map<std::string, std::string> & keywords = {})
  720. {
  721. detail::_interpreter::get();
  722. assert(x.size() == y.size());
  723. PyObject* xarray = detail::get_array(x);
  724. PyObject* yarray = detail::get_array(y);
  725. PyObject* kwargs = PyDict_New();
  726. PyDict_SetItemString(kwargs, "s", PyLong_FromLong(s));
  727. for (const auto& it : keywords)
  728. {
  729. PyDict_SetItemString(kwargs, it.first.c_str(), PyString_FromString(it.second.c_str()));
  730. }
  731. PyObject* plot_args = PyTuple_New(2);
  732. PyTuple_SetItem(plot_args, 0, xarray);
  733. PyTuple_SetItem(plot_args, 1, yarray);
  734. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_scatter, plot_args, kwargs);
  735. Py_DECREF(plot_args);
  736. Py_DECREF(kwargs);
  737. if(res) Py_DECREF(res);
  738. return res;
  739. }
  740. template<typename Numeric>
  741. bool boxplot(const std::vector<std::vector<Numeric>>& data,
  742. const std::vector<std::string>& labels = {},
  743. const std::map<std::string, std::string> & keywords = {})
  744. {
  745. detail::_interpreter::get();
  746. PyObject* listlist = detail::get_listlist(data);
  747. PyObject* args = PyTuple_New(1);
  748. PyTuple_SetItem(args, 0, listlist);
  749. PyObject* kwargs = PyDict_New();
  750. // kwargs needs the labels, if there are (the correct number of) labels
  751. if (!labels.empty() && labels.size() == data.size()) {
  752. PyDict_SetItemString(kwargs, "labels", detail::get_array(labels));
  753. }
  754. // take care of the remaining keywords
  755. for (const auto& it : keywords)
  756. {
  757. PyDict_SetItemString(kwargs, it.first.c_str(), PyString_FromString(it.second.c_str()));
  758. }
  759. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_boxplot, args, kwargs);
  760. Py_DECREF(args);
  761. Py_DECREF(kwargs);
  762. if(res) Py_DECREF(res);
  763. return res;
  764. }
  765. template<typename Numeric>
  766. bool boxplot(const std::vector<Numeric>& data,
  767. const std::map<std::string, std::string> & keywords = {})
  768. {
  769. detail::_interpreter::get();
  770. PyObject* vector = detail::get_array(data);
  771. PyObject* args = PyTuple_New(1);
  772. PyTuple_SetItem(args, 0, vector);
  773. PyObject* kwargs = PyDict_New();
  774. for (const auto& it : keywords)
  775. {
  776. PyDict_SetItemString(kwargs, it.first.c_str(), PyString_FromString(it.second.c_str()));
  777. }
  778. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_boxplot, args, kwargs);
  779. Py_DECREF(args);
  780. Py_DECREF(kwargs);
  781. if(res) Py_DECREF(res);
  782. return res;
  783. }
  784. template <typename Numeric>
  785. bool bar(const std::vector<Numeric> & x,
  786. const std::vector<Numeric> & y,
  787. std::string ec = "black",
  788. std::string ls = "-",
  789. double lw = 1.0,
  790. const std::map<std::string, std::string> & keywords = {})
  791. {
  792. detail::_interpreter::get();
  793. PyObject * xarray = detail::get_array(x);
  794. PyObject * yarray = detail::get_array(y);
  795. PyObject * kwargs = PyDict_New();
  796. PyDict_SetItemString(kwargs, "ec", PyString_FromString(ec.c_str()));
  797. PyDict_SetItemString(kwargs, "ls", PyString_FromString(ls.c_str()));
  798. PyDict_SetItemString(kwargs, "lw", PyFloat_FromDouble(lw));
  799. for (std::map<std::string, std::string>::const_iterator it =
  800. keywords.begin();
  801. it != keywords.end();
  802. ++it) {
  803. PyDict_SetItemString(
  804. kwargs, it->first.c_str(), PyUnicode_FromString(it->second.c_str()));
  805. }
  806. PyObject * plot_args = PyTuple_New(2);
  807. PyTuple_SetItem(plot_args, 0, xarray);
  808. PyTuple_SetItem(plot_args, 1, yarray);
  809. PyObject * res = PyObject_Call(
  810. detail::_interpreter::get().s_python_function_bar, plot_args, kwargs);
  811. Py_DECREF(plot_args);
  812. Py_DECREF(kwargs);
  813. if (res) Py_DECREF(res);
  814. return res;
  815. }
  816. template <typename Numeric>
  817. bool bar(const std::vector<Numeric> & y,
  818. std::string ec = "black",
  819. std::string ls = "-",
  820. double lw = 1.0,
  821. const std::map<std::string, std::string> & keywords = {})
  822. {
  823. using T = typename std::remove_reference<decltype(y)>::type::value_type;
  824. detail::_interpreter::get();
  825. std::vector<T> x;
  826. for (std::size_t i = 0; i < y.size(); i++) { x.push_back(i); }
  827. return bar(x, y, ec, ls, lw, keywords);
  828. }
  829. template<typename Numeric>
  830. bool barh(const std::vector<Numeric> &x, const std::vector<Numeric> &y, std::string ec = "black", std::string ls = "-", double lw = 1.0, const std::map<std::string, std::string> &keywords = { }) {
  831. PyObject *xarray = detail::get_array(x);
  832. PyObject *yarray = detail::get_array(y);
  833. PyObject *kwargs = PyDict_New();
  834. PyDict_SetItemString(kwargs, "ec", PyString_FromString(ec.c_str()));
  835. PyDict_SetItemString(kwargs, "ls", PyString_FromString(ls.c_str()));
  836. PyDict_SetItemString(kwargs, "lw", PyFloat_FromDouble(lw));
  837. for (std::map<std::string, std::string>::const_iterator it = keywords.begin(); it != keywords.end(); ++it) {
  838. PyDict_SetItemString(kwargs, it->first.c_str(), PyUnicode_FromString(it->second.c_str()));
  839. }
  840. PyObject *plot_args = PyTuple_New(2);
  841. PyTuple_SetItem(plot_args, 0, xarray);
  842. PyTuple_SetItem(plot_args, 1, yarray);
  843. PyObject *res = PyObject_Call(detail::_interpreter::get().s_python_function_barh, plot_args, kwargs);
  844. Py_DECREF(plot_args);
  845. Py_DECREF(kwargs);
  846. if (res) Py_DECREF(res);
  847. return res;
  848. }
  849. inline bool subplots_adjust(const std::map<std::string, double>& keywords = {})
  850. {
  851. detail::_interpreter::get();
  852. PyObject* kwargs = PyDict_New();
  853. for (std::map<std::string, double>::const_iterator it =
  854. keywords.begin(); it != keywords.end(); ++it) {
  855. PyDict_SetItemString(kwargs, it->first.c_str(),
  856. PyFloat_FromDouble(it->second));
  857. }
  858. PyObject* plot_args = PyTuple_New(0);
  859. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_subplots_adjust, plot_args, kwargs);
  860. Py_DECREF(plot_args);
  861. Py_DECREF(kwargs);
  862. if(res) Py_DECREF(res);
  863. return res;
  864. }
  865. template< typename Numeric>
  866. bool named_hist(std::string label,const std::vector<Numeric>& y, long bins=10, std::string color="b", double alpha=1.0)
  867. {
  868. detail::_interpreter::get();
  869. PyObject* yarray = detail::get_array(y);
  870. PyObject* kwargs = PyDict_New();
  871. PyDict_SetItemString(kwargs, "label", PyString_FromString(label.c_str()));
  872. PyDict_SetItemString(kwargs, "bins", PyLong_FromLong(bins));
  873. PyDict_SetItemString(kwargs, "color", PyString_FromString(color.c_str()));
  874. PyDict_SetItemString(kwargs, "alpha", PyFloat_FromDouble(alpha));
  875. PyObject* plot_args = PyTuple_New(1);
  876. PyTuple_SetItem(plot_args, 0, yarray);
  877. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_hist, plot_args, kwargs);
  878. Py_DECREF(plot_args);
  879. Py_DECREF(kwargs);
  880. if(res) Py_DECREF(res);
  881. return res;
  882. }
  883. template<typename NumericX, typename NumericY>
  884. bool plot(const std::vector<NumericX>& x, const std::vector<NumericY>& y, const std::string& s = "")
  885. {
  886. assert(x.size() == y.size());
  887. detail::_interpreter::get();
  888. PyObject* xarray = detail::get_array(x);
  889. PyObject* yarray = detail::get_array(y);
  890. PyObject* pystring = PyString_FromString(s.c_str());
  891. PyObject* plot_args = PyTuple_New(3);
  892. PyTuple_SetItem(plot_args, 0, xarray);
  893. PyTuple_SetItem(plot_args, 1, yarray);
  894. PyTuple_SetItem(plot_args, 2, pystring);
  895. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_plot, plot_args);
  896. Py_DECREF(plot_args);
  897. if(res) Py_DECREF(res);
  898. return res;
  899. }
  900. template <typename NumericX, typename NumericY, typename NumericZ>
  901. bool contour(const std::vector<NumericX>& x, const std::vector<NumericY>& y,
  902. const std::vector<NumericZ>& z,
  903. const std::map<std::string, std::string>& keywords = {}) {
  904. assert(x.size() == y.size() && x.size() == z.size());
  905. PyObject* xarray = get_array(x);
  906. PyObject* yarray = get_array(y);
  907. PyObject* zarray = get_array(z);
  908. PyObject* plot_args = PyTuple_New(3);
  909. PyTuple_SetItem(plot_args, 0, xarray);
  910. PyTuple_SetItem(plot_args, 1, yarray);
  911. PyTuple_SetItem(plot_args, 2, zarray);
  912. // construct keyword args
  913. PyObject* kwargs = PyDict_New();
  914. for (std::map<std::string, std::string>::const_iterator it = keywords.begin();
  915. it != keywords.end(); ++it) {
  916. PyDict_SetItemString(kwargs, it->first.c_str(), PyUnicode_FromString(it->second.c_str()));
  917. }
  918. PyObject* res =
  919. PyObject_Call(detail::_interpreter::get().s_python_function_contour, plot_args, kwargs);
  920. Py_DECREF(kwargs);
  921. Py_DECREF(plot_args);
  922. if (res)
  923. Py_DECREF(res);
  924. return res;
  925. }
  926. template<typename NumericX, typename NumericY, typename NumericU, typename NumericW>
  927. bool quiver(const std::vector<NumericX>& x, const std::vector<NumericY>& y, const std::vector<NumericU>& u, const std::vector<NumericW>& w, const std::map<std::string, std::string>& keywords = {})
  928. {
  929. assert(x.size() == y.size() && x.size() == u.size() && u.size() == w.size());
  930. detail::_interpreter::get();
  931. PyObject* xarray = detail::get_array(x);
  932. PyObject* yarray = detail::get_array(y);
  933. PyObject* uarray = detail::get_array(u);
  934. PyObject* warray = detail::get_array(w);
  935. PyObject* plot_args = PyTuple_New(4);
  936. PyTuple_SetItem(plot_args, 0, xarray);
  937. PyTuple_SetItem(plot_args, 1, yarray);
  938. PyTuple_SetItem(plot_args, 2, uarray);
  939. PyTuple_SetItem(plot_args, 3, warray);
  940. // construct keyword args
  941. PyObject* kwargs = PyDict_New();
  942. for(std::map<std::string, std::string>::const_iterator it = keywords.begin(); it != keywords.end(); ++it)
  943. {
  944. PyDict_SetItemString(kwargs, it->first.c_str(), PyUnicode_FromString(it->second.c_str()));
  945. }
  946. PyObject* res = PyObject_Call(
  947. detail::_interpreter::get().s_python_function_quiver, plot_args, kwargs);
  948. Py_DECREF(kwargs);
  949. Py_DECREF(plot_args);
  950. if (res)
  951. Py_DECREF(res);
  952. return res;
  953. }
  954. template<typename NumericX, typename NumericY, typename NumericZ, typename NumericU, typename NumericW, typename NumericV>
  955. bool quiver(const std::vector<NumericX>& x, const std::vector<NumericY>& y, const std::vector<NumericZ>& z, const std::vector<NumericU>& u, const std::vector<NumericW>& w, const std::vector<NumericV>& v, const std::map<std::string, std::string>& keywords = {})
  956. {
  957. //set up 3d axes stuff
  958. static PyObject *mpl_toolkitsmod = nullptr, *axis3dmod = nullptr;
  959. if (!mpl_toolkitsmod) {
  960. detail::_interpreter::get();
  961. PyObject* mpl_toolkits = PyString_FromString("mpl_toolkits");
  962. PyObject* axis3d = PyString_FromString("mpl_toolkits.mplot3d");
  963. if (!mpl_toolkits || !axis3d) { throw std::runtime_error("couldnt create string"); }
  964. mpl_toolkitsmod = PyImport_Import(mpl_toolkits);
  965. Py_DECREF(mpl_toolkits);
  966. if (!mpl_toolkitsmod) { throw std::runtime_error("Error loading module mpl_toolkits!"); }
  967. axis3dmod = PyImport_Import(axis3d);
  968. Py_DECREF(axis3d);
  969. if (!axis3dmod) { throw std::runtime_error("Error loading module mpl_toolkits.mplot3d!"); }
  970. }
  971. //assert sizes match up
  972. assert(x.size() == y.size() && x.size() == u.size() && u.size() == w.size() && x.size() == z.size() && x.size() == v.size() && u.size() == v.size());
  973. //set up parameters
  974. detail::_interpreter::get();
  975. PyObject* xarray = detail::get_array(x);
  976. PyObject* yarray = detail::get_array(y);
  977. PyObject* zarray = detail::get_array(z);
  978. PyObject* uarray = detail::get_array(u);
  979. PyObject* warray = detail::get_array(w);
  980. PyObject* varray = detail::get_array(v);
  981. PyObject* plot_args = PyTuple_New(6);
  982. PyTuple_SetItem(plot_args, 0, xarray);
  983. PyTuple_SetItem(plot_args, 1, yarray);
  984. PyTuple_SetItem(plot_args, 2, zarray);
  985. PyTuple_SetItem(plot_args, 3, uarray);
  986. PyTuple_SetItem(plot_args, 4, warray);
  987. PyTuple_SetItem(plot_args, 5, varray);
  988. // construct keyword args
  989. PyObject* kwargs = PyDict_New();
  990. for(std::map<std::string, std::string>::const_iterator it = keywords.begin(); it != keywords.end(); ++it)
  991. {
  992. PyDict_SetItemString(kwargs, it->first.c_str(), PyUnicode_FromString(it->second.c_str()));
  993. }
  994. //get figure gca to enable 3d projection
  995. PyObject *fig =
  996. PyObject_CallObject(detail::_interpreter::get().s_python_function_figure,
  997. detail::_interpreter::get().s_python_empty_tuple);
  998. if (!fig) throw std::runtime_error("Call to figure() failed.");
  999. PyObject *gca_kwargs = PyDict_New();
  1000. PyDict_SetItemString(gca_kwargs, "projection", PyString_FromString("3d"));
  1001. PyObject *gca = PyObject_GetAttrString(fig, "gca");
  1002. if (!gca) throw std::runtime_error("No gca");
  1003. Py_INCREF(gca);
  1004. PyObject *axis = PyObject_Call(
  1005. gca, detail::_interpreter::get().s_python_empty_tuple, gca_kwargs);
  1006. if (!axis) throw std::runtime_error("No axis");
  1007. Py_INCREF(axis);
  1008. Py_DECREF(gca);
  1009. Py_DECREF(gca_kwargs);
  1010. //plot our boys bravely, plot them strongly, plot them with a wink and clap
  1011. PyObject *plot3 = PyObject_GetAttrString(axis, "quiver");
  1012. if (!plot3) throw std::runtime_error("No 3D line plot");
  1013. Py_INCREF(plot3);
  1014. PyObject* res = PyObject_Call(
  1015. plot3, plot_args, kwargs);
  1016. if (!res) throw std::runtime_error("Failed 3D plot");
  1017. Py_DECREF(plot3);
  1018. Py_DECREF(axis);
  1019. Py_DECREF(kwargs);
  1020. Py_DECREF(plot_args);
  1021. if (res)
  1022. Py_DECREF(res);
  1023. return res;
  1024. }
  1025. template<typename NumericX, typename NumericY>
  1026. bool stem(const std::vector<NumericX>& x, const std::vector<NumericY>& y, const std::string& s = "")
  1027. {
  1028. assert(x.size() == y.size());
  1029. detail::_interpreter::get();
  1030. PyObject* xarray = detail::get_array(x);
  1031. PyObject* yarray = detail::get_array(y);
  1032. PyObject* pystring = PyString_FromString(s.c_str());
  1033. PyObject* plot_args = PyTuple_New(3);
  1034. PyTuple_SetItem(plot_args, 0, xarray);
  1035. PyTuple_SetItem(plot_args, 1, yarray);
  1036. PyTuple_SetItem(plot_args, 2, pystring);
  1037. PyObject* res = PyObject_CallObject(
  1038. detail::_interpreter::get().s_python_function_stem, plot_args);
  1039. Py_DECREF(plot_args);
  1040. if (res)
  1041. Py_DECREF(res);
  1042. return res;
  1043. }
  1044. template<typename NumericX, typename NumericY>
  1045. bool semilogx(const std::vector<NumericX>& x, const std::vector<NumericY>& y, const std::string& s = "")
  1046. {
  1047. assert(x.size() == y.size());
  1048. detail::_interpreter::get();
  1049. PyObject* xarray = detail::get_array(x);
  1050. PyObject* yarray = detail::get_array(y);
  1051. PyObject* pystring = PyString_FromString(s.c_str());
  1052. PyObject* plot_args = PyTuple_New(3);
  1053. PyTuple_SetItem(plot_args, 0, xarray);
  1054. PyTuple_SetItem(plot_args, 1, yarray);
  1055. PyTuple_SetItem(plot_args, 2, pystring);
  1056. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_semilogx, plot_args);
  1057. Py_DECREF(plot_args);
  1058. if(res) Py_DECREF(res);
  1059. return res;
  1060. }
  1061. template<typename NumericX, typename NumericY>
  1062. bool semilogy(const std::vector<NumericX>& x, const std::vector<NumericY>& y, const std::string& s = "")
  1063. {
  1064. assert(x.size() == y.size());
  1065. detail::_interpreter::get();
  1066. PyObject* xarray = detail::get_array(x);
  1067. PyObject* yarray = detail::get_array(y);
  1068. PyObject* pystring = PyString_FromString(s.c_str());
  1069. PyObject* plot_args = PyTuple_New(3);
  1070. PyTuple_SetItem(plot_args, 0, xarray);
  1071. PyTuple_SetItem(plot_args, 1, yarray);
  1072. PyTuple_SetItem(plot_args, 2, pystring);
  1073. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_semilogy, plot_args);
  1074. Py_DECREF(plot_args);
  1075. if(res) Py_DECREF(res);
  1076. return res;
  1077. }
  1078. template<typename NumericX, typename NumericY>
  1079. bool loglog(const std::vector<NumericX>& x, const std::vector<NumericY>& y, const std::string& s = "")
  1080. {
  1081. assert(x.size() == y.size());
  1082. detail::_interpreter::get();
  1083. PyObject* xarray = detail::get_array(x);
  1084. PyObject* yarray = detail::get_array(y);
  1085. PyObject* pystring = PyString_FromString(s.c_str());
  1086. PyObject* plot_args = PyTuple_New(3);
  1087. PyTuple_SetItem(plot_args, 0, xarray);
  1088. PyTuple_SetItem(plot_args, 1, yarray);
  1089. PyTuple_SetItem(plot_args, 2, pystring);
  1090. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_loglog, plot_args);
  1091. Py_DECREF(plot_args);
  1092. if(res) Py_DECREF(res);
  1093. return res;
  1094. }
  1095. template<typename NumericX, typename NumericY>
  1096. bool errorbar(const std::vector<NumericX> &x, const std::vector<NumericY> &y, const std::vector<NumericX> &yerr, const std::map<std::string, std::string> &keywords = {})
  1097. {
  1098. assert(x.size() == y.size());
  1099. detail::_interpreter::get();
  1100. PyObject* xarray = detail::get_array(x);
  1101. PyObject* yarray = detail::get_array(y);
  1102. PyObject* yerrarray = detail::get_array(yerr);
  1103. // construct keyword args
  1104. PyObject* kwargs = PyDict_New();
  1105. for(std::map<std::string, std::string>::const_iterator it = keywords.begin(); it != keywords.end(); ++it)
  1106. {
  1107. PyDict_SetItemString(kwargs, it->first.c_str(), PyString_FromString(it->second.c_str()));
  1108. }
  1109. PyDict_SetItemString(kwargs, "yerr", yerrarray);
  1110. PyObject *plot_args = PyTuple_New(2);
  1111. PyTuple_SetItem(plot_args, 0, xarray);
  1112. PyTuple_SetItem(plot_args, 1, yarray);
  1113. PyObject *res = PyObject_Call(detail::_interpreter::get().s_python_function_errorbar, plot_args, kwargs);
  1114. Py_DECREF(kwargs);
  1115. Py_DECREF(plot_args);
  1116. if (res)
  1117. Py_DECREF(res);
  1118. else
  1119. throw std::runtime_error("Call to errorbar() failed.");
  1120. return res;
  1121. }
  1122. template<typename Numeric>
  1123. bool named_plot(const std::string& name, const std::vector<Numeric>& y, const std::string& format = "")
  1124. {
  1125. detail::_interpreter::get();
  1126. PyObject* kwargs = PyDict_New();
  1127. PyDict_SetItemString(kwargs, "label", PyString_FromString(name.c_str()));
  1128. PyObject* yarray = detail::get_array(y);
  1129. PyObject* pystring = PyString_FromString(format.c_str());
  1130. PyObject* plot_args = PyTuple_New(2);
  1131. PyTuple_SetItem(plot_args, 0, yarray);
  1132. PyTuple_SetItem(plot_args, 1, pystring);
  1133. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_plot, plot_args, kwargs);
  1134. Py_DECREF(kwargs);
  1135. Py_DECREF(plot_args);
  1136. if (res) Py_DECREF(res);
  1137. return res;
  1138. }
  1139. template<typename Numeric>
  1140. bool named_plot(const std::string& name, const std::vector<Numeric>& x, const std::vector<Numeric>& y, const std::string& format = "")
  1141. {
  1142. detail::_interpreter::get();
  1143. PyObject* kwargs = PyDict_New();
  1144. PyDict_SetItemString(kwargs, "label", PyString_FromString(name.c_str()));
  1145. PyObject* xarray = detail::get_array(x);
  1146. PyObject* yarray = detail::get_array(y);
  1147. PyObject* pystring = PyString_FromString(format.c_str());
  1148. PyObject* plot_args = PyTuple_New(3);
  1149. PyTuple_SetItem(plot_args, 0, xarray);
  1150. PyTuple_SetItem(plot_args, 1, yarray);
  1151. PyTuple_SetItem(plot_args, 2, pystring);
  1152. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_plot, plot_args, kwargs);
  1153. Py_DECREF(kwargs);
  1154. Py_DECREF(plot_args);
  1155. if (res) Py_DECREF(res);
  1156. return res;
  1157. }
  1158. template<typename Numeric>
  1159. bool named_semilogx(const std::string& name, const std::vector<Numeric>& x, const std::vector<Numeric>& y, const std::string& format = "")
  1160. {
  1161. detail::_interpreter::get();
  1162. PyObject* kwargs = PyDict_New();
  1163. PyDict_SetItemString(kwargs, "label", PyString_FromString(name.c_str()));
  1164. PyObject* xarray = detail::get_array(x);
  1165. PyObject* yarray = detail::get_array(y);
  1166. PyObject* pystring = PyString_FromString(format.c_str());
  1167. PyObject* plot_args = PyTuple_New(3);
  1168. PyTuple_SetItem(plot_args, 0, xarray);
  1169. PyTuple_SetItem(plot_args, 1, yarray);
  1170. PyTuple_SetItem(plot_args, 2, pystring);
  1171. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_semilogx, plot_args, kwargs);
  1172. Py_DECREF(kwargs);
  1173. Py_DECREF(plot_args);
  1174. if (res) Py_DECREF(res);
  1175. return res;
  1176. }
  1177. template<typename Numeric>
  1178. bool named_semilogy(const std::string& name, const std::vector<Numeric>& x, const std::vector<Numeric>& y, const std::string& format = "")
  1179. {
  1180. detail::_interpreter::get();
  1181. PyObject* kwargs = PyDict_New();
  1182. PyDict_SetItemString(kwargs, "label", PyString_FromString(name.c_str()));
  1183. PyObject* xarray = detail::get_array(x);
  1184. PyObject* yarray = detail::get_array(y);
  1185. PyObject* pystring = PyString_FromString(format.c_str());
  1186. PyObject* plot_args = PyTuple_New(3);
  1187. PyTuple_SetItem(plot_args, 0, xarray);
  1188. PyTuple_SetItem(plot_args, 1, yarray);
  1189. PyTuple_SetItem(plot_args, 2, pystring);
  1190. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_semilogy, plot_args, kwargs);
  1191. Py_DECREF(kwargs);
  1192. Py_DECREF(plot_args);
  1193. if (res) Py_DECREF(res);
  1194. return res;
  1195. }
  1196. template<typename Numeric>
  1197. bool named_loglog(const std::string& name, const std::vector<Numeric>& x, const std::vector<Numeric>& y, const std::string& format = "")
  1198. {
  1199. detail::_interpreter::get();
  1200. PyObject* kwargs = PyDict_New();
  1201. PyDict_SetItemString(kwargs, "label", PyString_FromString(name.c_str()));
  1202. PyObject* xarray = detail::get_array(x);
  1203. PyObject* yarray = detail::get_array(y);
  1204. PyObject* pystring = PyString_FromString(format.c_str());
  1205. PyObject* plot_args = PyTuple_New(3);
  1206. PyTuple_SetItem(plot_args, 0, xarray);
  1207. PyTuple_SetItem(plot_args, 1, yarray);
  1208. PyTuple_SetItem(plot_args, 2, pystring);
  1209. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_loglog, plot_args, kwargs);
  1210. Py_DECREF(kwargs);
  1211. Py_DECREF(plot_args);
  1212. if (res) Py_DECREF(res);
  1213. return res;
  1214. }
  1215. template<typename Numeric>
  1216. bool plot(const std::vector<Numeric>& y, const std::string& format = "")
  1217. {
  1218. std::vector<Numeric> x(y.size());
  1219. for(size_t i=0; i<x.size(); ++i) x.at(i) = i;
  1220. return plot(x,y,format);
  1221. }
  1222. template<typename Numeric>
  1223. bool plot(const std::vector<Numeric>& y, const std::map<std::string, std::string>& keywords)
  1224. {
  1225. std::vector<Numeric> x(y.size());
  1226. for(size_t i=0; i<x.size(); ++i) x.at(i) = i;
  1227. return plot(x,y,keywords);
  1228. }
  1229. template<typename Numeric>
  1230. bool stem(const std::vector<Numeric>& y, const std::string& format = "")
  1231. {
  1232. std::vector<Numeric> x(y.size());
  1233. for (size_t i = 0; i < x.size(); ++i) x.at(i) = i;
  1234. return stem(x, y, format);
  1235. }
  1236. template<typename Numeric>
  1237. void text(Numeric x, Numeric y, const std::string& s = "")
  1238. {
  1239. detail::_interpreter::get();
  1240. PyObject* args = PyTuple_New(3);
  1241. PyTuple_SetItem(args, 0, PyFloat_FromDouble(x));
  1242. PyTuple_SetItem(args, 1, PyFloat_FromDouble(y));
  1243. PyTuple_SetItem(args, 2, PyString_FromString(s.c_str()));
  1244. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_text, args);
  1245. if(!res) throw std::runtime_error("Call to text() failed.");
  1246. Py_DECREF(args);
  1247. Py_DECREF(res);
  1248. }
  1249. inline void colorbar(PyObject* mappable = NULL, const std::map<std::string, float>& keywords = {})
  1250. {
  1251. if (mappable == NULL)
  1252. throw std::runtime_error("Must call colorbar with PyObject* returned from an image, contour, surface, etc.");
  1253. detail::_interpreter::get();
  1254. PyObject* args = PyTuple_New(1);
  1255. PyTuple_SetItem(args, 0, mappable);
  1256. PyObject* kwargs = PyDict_New();
  1257. for(std::map<std::string, float>::const_iterator it = keywords.begin(); it != keywords.end(); ++it)
  1258. {
  1259. PyDict_SetItemString(kwargs, it->first.c_str(), PyFloat_FromDouble(it->second));
  1260. }
  1261. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_colorbar, args, kwargs);
  1262. if(!res) throw std::runtime_error("Call to colorbar() failed.");
  1263. Py_DECREF(args);
  1264. Py_DECREF(kwargs);
  1265. Py_DECREF(res);
  1266. }
  1267. inline long figure(long number = -1)
  1268. {
  1269. detail::_interpreter::get();
  1270. PyObject *res;
  1271. if (number == -1)
  1272. res = PyObject_CallObject(detail::_interpreter::get().s_python_function_figure, detail::_interpreter::get().s_python_empty_tuple);
  1273. else {
  1274. assert(number > 0);
  1275. // Make sure interpreter is initialised
  1276. detail::_interpreter::get();
  1277. PyObject *args = PyTuple_New(1);
  1278. PyTuple_SetItem(args, 0, PyLong_FromLong(number));
  1279. res = PyObject_CallObject(detail::_interpreter::get().s_python_function_figure, args);
  1280. Py_DECREF(args);
  1281. }
  1282. if(!res) throw std::runtime_error("Call to figure() failed.");
  1283. PyObject* num = PyObject_GetAttrString(res, "number");
  1284. if (!num) throw std::runtime_error("Could not get number attribute of figure object");
  1285. const long figureNumber = PyLong_AsLong(num);
  1286. Py_DECREF(num);
  1287. Py_DECREF(res);
  1288. return figureNumber;
  1289. }
  1290. inline bool fignum_exists(long number)
  1291. {
  1292. detail::_interpreter::get();
  1293. PyObject *args = PyTuple_New(1);
  1294. PyTuple_SetItem(args, 0, PyLong_FromLong(number));
  1295. PyObject *res = PyObject_CallObject(detail::_interpreter::get().s_python_function_fignum_exists, args);
  1296. if(!res) throw std::runtime_error("Call to fignum_exists() failed.");
  1297. bool ret = PyObject_IsTrue(res);
  1298. Py_DECREF(res);
  1299. Py_DECREF(args);
  1300. return ret;
  1301. }
  1302. inline void figure_size(size_t w, size_t h)
  1303. {
  1304. detail::_interpreter::get();
  1305. const size_t dpi = 100;
  1306. PyObject* size = PyTuple_New(2);
  1307. PyTuple_SetItem(size, 0, PyFloat_FromDouble((double)w / dpi));
  1308. PyTuple_SetItem(size, 1, PyFloat_FromDouble((double)h / dpi));
  1309. PyObject* kwargs = PyDict_New();
  1310. PyDict_SetItemString(kwargs, "figsize", size);
  1311. PyDict_SetItemString(kwargs, "dpi", PyLong_FromSize_t(dpi));
  1312. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_figure,
  1313. detail::_interpreter::get().s_python_empty_tuple, kwargs);
  1314. Py_DECREF(kwargs);
  1315. if(!res) throw std::runtime_error("Call to figure_size() failed.");
  1316. Py_DECREF(res);
  1317. }
  1318. inline void legend()
  1319. {
  1320. detail::_interpreter::get();
  1321. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_legend, detail::_interpreter::get().s_python_empty_tuple);
  1322. if(!res) throw std::runtime_error("Call to legend() failed.");
  1323. Py_DECREF(res);
  1324. }
  1325. inline void legend(const std::map<std::string, std::string>& keywords)
  1326. {
  1327. detail::_interpreter::get();
  1328. // construct keyword args
  1329. PyObject* kwargs = PyDict_New();
  1330. for(std::map<std::string, std::string>::const_iterator it = keywords.begin(); it != keywords.end(); ++it)
  1331. {
  1332. PyDict_SetItemString(kwargs, it->first.c_str(), PyString_FromString(it->second.c_str()));
  1333. }
  1334. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_legend, detail::_interpreter::get().s_python_empty_tuple, kwargs);
  1335. if(!res) throw std::runtime_error("Call to legend() failed.");
  1336. Py_DECREF(kwargs);
  1337. Py_DECREF(res);
  1338. }
  1339. template<typename Numeric>
  1340. void ylim(Numeric left, Numeric right)
  1341. {
  1342. detail::_interpreter::get();
  1343. PyObject* list = PyList_New(2);
  1344. PyList_SetItem(list, 0, PyFloat_FromDouble(left));
  1345. PyList_SetItem(list, 1, PyFloat_FromDouble(right));
  1346. PyObject* args = PyTuple_New(1);
  1347. PyTuple_SetItem(args, 0, list);
  1348. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_ylim, args);
  1349. if(!res) throw std::runtime_error("Call to ylim() failed.");
  1350. Py_DECREF(args);
  1351. Py_DECREF(res);
  1352. }
  1353. template<typename Numeric>
  1354. void xlim(Numeric left, Numeric right)
  1355. {
  1356. detail::_interpreter::get();
  1357. PyObject* list = PyList_New(2);
  1358. PyList_SetItem(list, 0, PyFloat_FromDouble(left));
  1359. PyList_SetItem(list, 1, PyFloat_FromDouble(right));
  1360. PyObject* args = PyTuple_New(1);
  1361. PyTuple_SetItem(args, 0, list);
  1362. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_xlim, args);
  1363. if(!res) throw std::runtime_error("Call to xlim() failed.");
  1364. Py_DECREF(args);
  1365. Py_DECREF(res);
  1366. }
  1367. inline double* xlim()
  1368. {
  1369. detail::_interpreter::get();
  1370. PyObject* args = PyTuple_New(0);
  1371. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_xlim, args);
  1372. PyObject* left = PyTuple_GetItem(res,0);
  1373. PyObject* right = PyTuple_GetItem(res,1);
  1374. double* arr = new double[2];
  1375. arr[0] = PyFloat_AsDouble(left);
  1376. arr[1] = PyFloat_AsDouble(right);
  1377. if(!res) throw std::runtime_error("Call to xlim() failed.");
  1378. Py_DECREF(res);
  1379. return arr;
  1380. }
  1381. inline double* ylim()
  1382. {
  1383. detail::_interpreter::get();
  1384. PyObject* args = PyTuple_New(0);
  1385. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_ylim, args);
  1386. PyObject* left = PyTuple_GetItem(res,0);
  1387. PyObject* right = PyTuple_GetItem(res,1);
  1388. double* arr = new double[2];
  1389. arr[0] = PyFloat_AsDouble(left);
  1390. arr[1] = PyFloat_AsDouble(right);
  1391. if(!res) throw std::runtime_error("Call to ylim() failed.");
  1392. Py_DECREF(res);
  1393. return arr;
  1394. }
  1395. template<typename Numeric>
  1396. inline void xticks(const std::vector<Numeric> &ticks, const std::vector<std::string> &labels = {}, const std::map<std::string, std::string>& keywords = {})
  1397. {
  1398. assert(labels.size() == 0 || ticks.size() == labels.size());
  1399. detail::_interpreter::get();
  1400. // using numpy array
  1401. PyObject* ticksarray = detail::get_array(ticks);
  1402. PyObject* args;
  1403. if(labels.size() == 0) {
  1404. // construct positional args
  1405. args = PyTuple_New(1);
  1406. PyTuple_SetItem(args, 0, ticksarray);
  1407. } else {
  1408. // make tuple of tick labels
  1409. PyObject* labelstuple = PyTuple_New(labels.size());
  1410. for (size_t i = 0; i < labels.size(); i++)
  1411. PyTuple_SetItem(labelstuple, i, PyUnicode_FromString(labels[i].c_str()));
  1412. // construct positional args
  1413. args = PyTuple_New(2);
  1414. PyTuple_SetItem(args, 0, ticksarray);
  1415. PyTuple_SetItem(args, 1, labelstuple);
  1416. }
  1417. // construct keyword args
  1418. PyObject* kwargs = PyDict_New();
  1419. for(std::map<std::string, std::string>::const_iterator it = keywords.begin(); it != keywords.end(); ++it)
  1420. {
  1421. PyDict_SetItemString(kwargs, it->first.c_str(), PyString_FromString(it->second.c_str()));
  1422. }
  1423. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_xticks, args, kwargs);
  1424. Py_DECREF(args);
  1425. Py_DECREF(kwargs);
  1426. if(!res) throw std::runtime_error("Call to xticks() failed");
  1427. Py_DECREF(res);
  1428. }
  1429. template<typename Numeric>
  1430. inline void xticks(const std::vector<Numeric> &ticks, const std::map<std::string, std::string>& keywords)
  1431. {
  1432. xticks(ticks, {}, keywords);
  1433. }
  1434. template<typename Numeric>
  1435. inline void yticks(const std::vector<Numeric> &ticks, const std::vector<std::string> &labels = {}, const std::map<std::string, std::string>& keywords = {})
  1436. {
  1437. assert(labels.size() == 0 || ticks.size() == labels.size());
  1438. detail::_interpreter::get();
  1439. // using numpy array
  1440. PyObject* ticksarray = detail::get_array(ticks);
  1441. PyObject* args;
  1442. if(labels.size() == 0) {
  1443. // construct positional args
  1444. args = PyTuple_New(1);
  1445. PyTuple_SetItem(args, 0, ticksarray);
  1446. } else {
  1447. // make tuple of tick labels
  1448. PyObject* labelstuple = PyTuple_New(labels.size());
  1449. for (size_t i = 0; i < labels.size(); i++)
  1450. PyTuple_SetItem(labelstuple, i, PyUnicode_FromString(labels[i].c_str()));
  1451. // construct positional args
  1452. args = PyTuple_New(2);
  1453. PyTuple_SetItem(args, 0, ticksarray);
  1454. PyTuple_SetItem(args, 1, labelstuple);
  1455. }
  1456. // construct keyword args
  1457. PyObject* kwargs = PyDict_New();
  1458. for(std::map<std::string, std::string>::const_iterator it = keywords.begin(); it != keywords.end(); ++it)
  1459. {
  1460. PyDict_SetItemString(kwargs, it->first.c_str(), PyString_FromString(it->second.c_str()));
  1461. }
  1462. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_yticks, args, kwargs);
  1463. Py_DECREF(args);
  1464. Py_DECREF(kwargs);
  1465. if(!res) throw std::runtime_error("Call to yticks() failed");
  1466. Py_DECREF(res);
  1467. }
  1468. template<typename Numeric>
  1469. inline void yticks(const std::vector<Numeric> &ticks, const std::map<std::string, std::string>& keywords)
  1470. {
  1471. yticks(ticks, {}, keywords);
  1472. }
  1473. template <typename Numeric> inline void margins(Numeric margin)
  1474. {
  1475. // construct positional args
  1476. PyObject* args = PyTuple_New(1);
  1477. PyTuple_SetItem(args, 0, PyFloat_FromDouble(margin));
  1478. PyObject* res =
  1479. PyObject_CallObject(detail::_interpreter::get().s_python_function_margins, args);
  1480. if (!res)
  1481. throw std::runtime_error("Call to margins() failed.");
  1482. Py_DECREF(args);
  1483. Py_DECREF(res);
  1484. }
  1485. template <typename Numeric> inline void margins(Numeric margin_x, Numeric margin_y)
  1486. {
  1487. // construct positional args
  1488. PyObject* args = PyTuple_New(2);
  1489. PyTuple_SetItem(args, 0, PyFloat_FromDouble(margin_x));
  1490. PyTuple_SetItem(args, 1, PyFloat_FromDouble(margin_y));
  1491. PyObject* res =
  1492. PyObject_CallObject(detail::_interpreter::get().s_python_function_margins, args);
  1493. if (!res)
  1494. throw std::runtime_error("Call to margins() failed.");
  1495. Py_DECREF(args);
  1496. Py_DECREF(res);
  1497. }
  1498. inline void tick_params(const std::map<std::string, std::string>& keywords, const std::string axis = "both")
  1499. {
  1500. detail::_interpreter::get();
  1501. // construct positional args
  1502. PyObject* args;
  1503. args = PyTuple_New(1);
  1504. PyTuple_SetItem(args, 0, PyString_FromString(axis.c_str()));
  1505. // construct keyword args
  1506. PyObject* kwargs = PyDict_New();
  1507. for (std::map<std::string, std::string>::const_iterator it = keywords.begin(); it != keywords.end(); ++it)
  1508. {
  1509. PyDict_SetItemString(kwargs, it->first.c_str(), PyString_FromString(it->second.c_str()));
  1510. }
  1511. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_tick_params, args, kwargs);
  1512. Py_DECREF(args);
  1513. Py_DECREF(kwargs);
  1514. if (!res) throw std::runtime_error("Call to tick_params() failed");
  1515. Py_DECREF(res);
  1516. }
  1517. inline void subplot(long nrows, long ncols, long plot_number)
  1518. {
  1519. detail::_interpreter::get();
  1520. // construct positional args
  1521. PyObject* args = PyTuple_New(3);
  1522. PyTuple_SetItem(args, 0, PyFloat_FromDouble(nrows));
  1523. PyTuple_SetItem(args, 1, PyFloat_FromDouble(ncols));
  1524. PyTuple_SetItem(args, 2, PyFloat_FromDouble(plot_number));
  1525. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_subplot, args);
  1526. if(!res) throw std::runtime_error("Call to subplot() failed.");
  1527. Py_DECREF(args);
  1528. Py_DECREF(res);
  1529. }
  1530. inline void subplot2grid(long nrows, long ncols, long rowid=0, long colid=0, long rowspan=1, long colspan=1)
  1531. {
  1532. detail::_interpreter::get();
  1533. PyObject* shape = PyTuple_New(2);
  1534. PyTuple_SetItem(shape, 0, PyLong_FromLong(nrows));
  1535. PyTuple_SetItem(shape, 1, PyLong_FromLong(ncols));
  1536. PyObject* loc = PyTuple_New(2);
  1537. PyTuple_SetItem(loc, 0, PyLong_FromLong(rowid));
  1538. PyTuple_SetItem(loc, 1, PyLong_FromLong(colid));
  1539. PyObject* args = PyTuple_New(4);
  1540. PyTuple_SetItem(args, 0, shape);
  1541. PyTuple_SetItem(args, 1, loc);
  1542. PyTuple_SetItem(args, 2, PyLong_FromLong(rowspan));
  1543. PyTuple_SetItem(args, 3, PyLong_FromLong(colspan));
  1544. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_subplot2grid, args);
  1545. if(!res) throw std::runtime_error("Call to subplot2grid() failed.");
  1546. Py_DECREF(shape);
  1547. Py_DECREF(loc);
  1548. Py_DECREF(args);
  1549. Py_DECREF(res);
  1550. }
  1551. inline void title(const std::string &titlestr, const std::map<std::string, std::string> &keywords = {})
  1552. {
  1553. detail::_interpreter::get();
  1554. PyObject* pytitlestr = PyString_FromString(titlestr.c_str());
  1555. PyObject* args = PyTuple_New(1);
  1556. PyTuple_SetItem(args, 0, pytitlestr);
  1557. PyObject* kwargs = PyDict_New();
  1558. for (auto it = keywords.begin(); it != keywords.end(); ++it) {
  1559. PyDict_SetItemString(kwargs, it->first.c_str(), PyUnicode_FromString(it->second.c_str()));
  1560. }
  1561. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_title, args, kwargs);
  1562. if(!res) throw std::runtime_error("Call to title() failed.");
  1563. Py_DECREF(args);
  1564. Py_DECREF(kwargs);
  1565. Py_DECREF(res);
  1566. }
  1567. inline void suptitle(const std::string &suptitlestr, const std::map<std::string, std::string> &keywords = {})
  1568. {
  1569. detail::_interpreter::get();
  1570. PyObject* pysuptitlestr = PyString_FromString(suptitlestr.c_str());
  1571. PyObject* args = PyTuple_New(1);
  1572. PyTuple_SetItem(args, 0, pysuptitlestr);
  1573. PyObject* kwargs = PyDict_New();
  1574. for (auto it = keywords.begin(); it != keywords.end(); ++it) {
  1575. PyDict_SetItemString(kwargs, it->first.c_str(), PyUnicode_FromString(it->second.c_str()));
  1576. }
  1577. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_suptitle, args, kwargs);
  1578. if(!res) throw std::runtime_error("Call to suptitle() failed.");
  1579. Py_DECREF(args);
  1580. Py_DECREF(kwargs);
  1581. Py_DECREF(res);
  1582. }
  1583. inline void axis(const std::string &axisstr)
  1584. {
  1585. detail::_interpreter::get();
  1586. PyObject* str = PyString_FromString(axisstr.c_str());
  1587. PyObject* args = PyTuple_New(1);
  1588. PyTuple_SetItem(args, 0, str);
  1589. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_axis, args);
  1590. if(!res) throw std::runtime_error("Call to title() failed.");
  1591. Py_DECREF(args);
  1592. Py_DECREF(res);
  1593. }
  1594. inline void axvline(double x, double ymin = 0., double ymax = 1., const std::map<std::string, std::string>& keywords = std::map<std::string, std::string>())
  1595. {
  1596. detail::_interpreter::get();
  1597. // construct positional args
  1598. PyObject* args = PyTuple_New(3);
  1599. PyTuple_SetItem(args, 0, PyFloat_FromDouble(x));
  1600. PyTuple_SetItem(args, 1, PyFloat_FromDouble(ymin));
  1601. PyTuple_SetItem(args, 2, PyFloat_FromDouble(ymax));
  1602. // construct keyword args
  1603. PyObject* kwargs = PyDict_New();
  1604. for(std::map<std::string, std::string>::const_iterator it = keywords.begin(); it != keywords.end(); ++it)
  1605. {
  1606. PyDict_SetItemString(kwargs, it->first.c_str(), PyString_FromString(it->second.c_str()));
  1607. }
  1608. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_axvline, args, kwargs);
  1609. Py_DECREF(args);
  1610. Py_DECREF(kwargs);
  1611. if(res) Py_DECREF(res);
  1612. }
  1613. inline void axvspan(double xmin, double xmax, double ymin = 0., double ymax = 1., const std::map<std::string, std::string>& keywords = std::map<std::string, std::string>())
  1614. {
  1615. // construct positional args
  1616. PyObject* args = PyTuple_New(4);
  1617. PyTuple_SetItem(args, 0, PyFloat_FromDouble(xmin));
  1618. PyTuple_SetItem(args, 1, PyFloat_FromDouble(xmax));
  1619. PyTuple_SetItem(args, 2, PyFloat_FromDouble(ymin));
  1620. PyTuple_SetItem(args, 3, PyFloat_FromDouble(ymax));
  1621. // construct keyword args
  1622. PyObject* kwargs = PyDict_New();
  1623. for(std::map<std::string, std::string>::const_iterator it = keywords.begin(); it != keywords.end(); ++it)
  1624. {
  1625. if (it->first == "linewidth" || it->first == "alpha")
  1626. PyDict_SetItemString(kwargs, it->first.c_str(), PyFloat_FromDouble(std::stod(it->second)));
  1627. else
  1628. PyDict_SetItemString(kwargs, it->first.c_str(), PyString_FromString(it->second.c_str()));
  1629. }
  1630. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_axvspan, args, kwargs);
  1631. Py_DECREF(args);
  1632. Py_DECREF(kwargs);
  1633. if(res) Py_DECREF(res);
  1634. }
  1635. inline void xlabel(const std::string &str, const std::map<std::string, std::string> &keywords = {})
  1636. {
  1637. detail::_interpreter::get();
  1638. PyObject* pystr = PyString_FromString(str.c_str());
  1639. PyObject* args = PyTuple_New(1);
  1640. PyTuple_SetItem(args, 0, pystr);
  1641. PyObject* kwargs = PyDict_New();
  1642. for (auto it = keywords.begin(); it != keywords.end(); ++it) {
  1643. PyDict_SetItemString(kwargs, it->first.c_str(), PyUnicode_FromString(it->second.c_str()));
  1644. }
  1645. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_xlabel, args, kwargs);
  1646. if(!res) throw std::runtime_error("Call to xlabel() failed.");
  1647. Py_DECREF(args);
  1648. Py_DECREF(kwargs);
  1649. Py_DECREF(res);
  1650. }
  1651. inline void ylabel(const std::string &str, const std::map<std::string, std::string>& keywords = {})
  1652. {
  1653. detail::_interpreter::get();
  1654. PyObject* pystr = PyString_FromString(str.c_str());
  1655. PyObject* args = PyTuple_New(1);
  1656. PyTuple_SetItem(args, 0, pystr);
  1657. PyObject* kwargs = PyDict_New();
  1658. for (auto it = keywords.begin(); it != keywords.end(); ++it) {
  1659. PyDict_SetItemString(kwargs, it->first.c_str(), PyUnicode_FromString(it->second.c_str()));
  1660. }
  1661. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_ylabel, args, kwargs);
  1662. if(!res) throw std::runtime_error("Call to ylabel() failed.");
  1663. Py_DECREF(args);
  1664. Py_DECREF(kwargs);
  1665. Py_DECREF(res);
  1666. }
  1667. inline void set_zlabel(const std::string &str, const std::map<std::string, std::string>& keywords = {})
  1668. {
  1669. detail::_interpreter::get();
  1670. // Same as with plot_surface: We lazily load the modules here the first time
  1671. // this function is called because I'm not sure that we can assume "matplotlib
  1672. // installed" implies "mpl_toolkits installed" on all platforms, and we don't
  1673. // want to require it for people who don't need 3d plots.
  1674. static PyObject *mpl_toolkitsmod = nullptr, *axis3dmod = nullptr;
  1675. if (!mpl_toolkitsmod) {
  1676. PyObject* mpl_toolkits = PyString_FromString("mpl_toolkits");
  1677. PyObject* axis3d = PyString_FromString("mpl_toolkits.mplot3d");
  1678. if (!mpl_toolkits || !axis3d) { throw std::runtime_error("couldnt create string"); }
  1679. mpl_toolkitsmod = PyImport_Import(mpl_toolkits);
  1680. Py_DECREF(mpl_toolkits);
  1681. if (!mpl_toolkitsmod) { throw std::runtime_error("Error loading module mpl_toolkits!"); }
  1682. axis3dmod = PyImport_Import(axis3d);
  1683. Py_DECREF(axis3d);
  1684. if (!axis3dmod) { throw std::runtime_error("Error loading module mpl_toolkits.mplot3d!"); }
  1685. }
  1686. PyObject* pystr = PyString_FromString(str.c_str());
  1687. PyObject* args = PyTuple_New(1);
  1688. PyTuple_SetItem(args, 0, pystr);
  1689. PyObject* kwargs = PyDict_New();
  1690. for (auto it = keywords.begin(); it != keywords.end(); ++it) {
  1691. PyDict_SetItemString(kwargs, it->first.c_str(), PyUnicode_FromString(it->second.c_str()));
  1692. }
  1693. PyObject *ax =
  1694. PyObject_CallObject(detail::_interpreter::get().s_python_function_gca,
  1695. detail::_interpreter::get().s_python_empty_tuple);
  1696. if (!ax) throw std::runtime_error("Call to gca() failed.");
  1697. Py_INCREF(ax);
  1698. PyObject *zlabel = PyObject_GetAttrString(ax, "set_zlabel");
  1699. if (!zlabel) throw std::runtime_error("Attribute set_zlabel not found.");
  1700. Py_INCREF(zlabel);
  1701. PyObject *res = PyObject_Call(zlabel, args, kwargs);
  1702. if (!res) throw std::runtime_error("Call to set_zlabel() failed.");
  1703. Py_DECREF(zlabel);
  1704. Py_DECREF(ax);
  1705. Py_DECREF(args);
  1706. Py_DECREF(kwargs);
  1707. if (res) Py_DECREF(res);
  1708. }
  1709. inline void grid(bool flag)
  1710. {
  1711. detail::_interpreter::get();
  1712. PyObject* pyflag = flag ? Py_True : Py_False;
  1713. Py_INCREF(pyflag);
  1714. PyObject* args = PyTuple_New(1);
  1715. PyTuple_SetItem(args, 0, pyflag);
  1716. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_grid, args);
  1717. if(!res) throw std::runtime_error("Call to grid() failed.");
  1718. Py_DECREF(args);
  1719. Py_DECREF(res);
  1720. }
  1721. inline void show(const bool block = true)
  1722. {
  1723. detail::_interpreter::get();
  1724. PyObject* res;
  1725. if(block)
  1726. {
  1727. res = PyObject_CallObject(
  1728. detail::_interpreter::get().s_python_function_show,
  1729. detail::_interpreter::get().s_python_empty_tuple);
  1730. }
  1731. else
  1732. {
  1733. PyObject *kwargs = PyDict_New();
  1734. PyDict_SetItemString(kwargs, "block", Py_False);
  1735. res = PyObject_Call( detail::_interpreter::get().s_python_function_show, detail::_interpreter::get().s_python_empty_tuple, kwargs);
  1736. Py_DECREF(kwargs);
  1737. }
  1738. if (!res) throw std::runtime_error("Call to show() failed.");
  1739. Py_DECREF(res);
  1740. }
  1741. inline void close()
  1742. {
  1743. detail::_interpreter::get();
  1744. PyObject* res = PyObject_CallObject(
  1745. detail::_interpreter::get().s_python_function_close,
  1746. detail::_interpreter::get().s_python_empty_tuple);
  1747. if (!res) throw std::runtime_error("Call to close() failed.");
  1748. Py_DECREF(res);
  1749. }
  1750. inline void xkcd() {
  1751. detail::_interpreter::get();
  1752. PyObject* res;
  1753. PyObject *kwargs = PyDict_New();
  1754. res = PyObject_Call(detail::_interpreter::get().s_python_function_xkcd,
  1755. detail::_interpreter::get().s_python_empty_tuple, kwargs);
  1756. Py_DECREF(kwargs);
  1757. if (!res)
  1758. throw std::runtime_error("Call to show() failed.");
  1759. Py_DECREF(res);
  1760. }
  1761. inline void draw()
  1762. {
  1763. detail::_interpreter::get();
  1764. PyObject* res = PyObject_CallObject(
  1765. detail::_interpreter::get().s_python_function_draw,
  1766. detail::_interpreter::get().s_python_empty_tuple);
  1767. if (!res) throw std::runtime_error("Call to draw() failed.");
  1768. Py_DECREF(res);
  1769. }
  1770. template<typename Numeric>
  1771. inline void pause(Numeric interval)
  1772. {
  1773. detail::_interpreter::get();
  1774. PyObject* args = PyTuple_New(1);
  1775. PyTuple_SetItem(args, 0, PyFloat_FromDouble(interval));
  1776. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_pause, args);
  1777. if(!res) throw std::runtime_error("Call to pause() failed.");
  1778. Py_DECREF(args);
  1779. Py_DECREF(res);
  1780. }
  1781. inline void save(const std::string& filename)
  1782. {
  1783. detail::_interpreter::get();
  1784. PyObject* pyfilename = PyString_FromString(filename.c_str());
  1785. PyObject* args = PyTuple_New(1);
  1786. PyTuple_SetItem(args, 0, pyfilename);
  1787. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_save, args);
  1788. if (!res) throw std::runtime_error("Call to save() failed.");
  1789. Py_DECREF(args);
  1790. Py_DECREF(res);
  1791. }
  1792. inline void clf() {
  1793. detail::_interpreter::get();
  1794. PyObject *res = PyObject_CallObject(
  1795. detail::_interpreter::get().s_python_function_clf,
  1796. detail::_interpreter::get().s_python_empty_tuple);
  1797. if (!res) throw std::runtime_error("Call to clf() failed.");
  1798. Py_DECREF(res);
  1799. }
  1800. inline void cla() {
  1801. detail::_interpreter::get();
  1802. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_cla,
  1803. detail::_interpreter::get().s_python_empty_tuple);
  1804. if (!res)
  1805. throw std::runtime_error("Call to cla() failed.");
  1806. Py_DECREF(res);
  1807. }
  1808. inline void ion() {
  1809. detail::_interpreter::get();
  1810. PyObject *res = PyObject_CallObject(
  1811. detail::_interpreter::get().s_python_function_ion,
  1812. detail::_interpreter::get().s_python_empty_tuple);
  1813. if (!res) throw std::runtime_error("Call to ion() failed.");
  1814. Py_DECREF(res);
  1815. }
  1816. inline std::vector<std::array<double, 2>> ginput(const int numClicks = 1, const std::map<std::string, std::string>& keywords = {})
  1817. {
  1818. detail::_interpreter::get();
  1819. PyObject *args = PyTuple_New(1);
  1820. PyTuple_SetItem(args, 0, PyLong_FromLong(numClicks));
  1821. // construct keyword args
  1822. PyObject* kwargs = PyDict_New();
  1823. for(std::map<std::string, std::string>::const_iterator it = keywords.begin(); it != keywords.end(); ++it)
  1824. {
  1825. PyDict_SetItemString(kwargs, it->first.c_str(), PyUnicode_FromString(it->second.c_str()));
  1826. }
  1827. PyObject* res = PyObject_Call(
  1828. detail::_interpreter::get().s_python_function_ginput, args, kwargs);
  1829. Py_DECREF(kwargs);
  1830. Py_DECREF(args);
  1831. if (!res) throw std::runtime_error("Call to ginput() failed.");
  1832. const size_t len = PyList_Size(res);
  1833. std::vector<std::array<double, 2>> out;
  1834. out.reserve(len);
  1835. for (size_t i = 0; i < len; i++) {
  1836. PyObject *current = PyList_GetItem(res, i);
  1837. std::array<double, 2> position;
  1838. position[0] = PyFloat_AsDouble(PyTuple_GetItem(current, 0));
  1839. position[1] = PyFloat_AsDouble(PyTuple_GetItem(current, 1));
  1840. out.push_back(position);
  1841. }
  1842. Py_DECREF(res);
  1843. return out;
  1844. }
  1845. // Actually, is there any reason not to call this automatically for every plot?
  1846. inline void tight_layout() {
  1847. detail::_interpreter::get();
  1848. PyObject *res = PyObject_CallObject(
  1849. detail::_interpreter::get().s_python_function_tight_layout,
  1850. detail::_interpreter::get().s_python_empty_tuple);
  1851. if (!res) throw std::runtime_error("Call to tight_layout() failed.");
  1852. Py_DECREF(res);
  1853. }
  1854. // Support for variadic plot() and initializer lists:
  1855. namespace detail {
  1856. template<typename T>
  1857. using is_function = typename std::is_function<std::remove_pointer<std::remove_reference<T>>>::type;
  1858. template<bool obj, typename T>
  1859. struct is_callable_impl;
  1860. template<typename T>
  1861. struct is_callable_impl<false, T>
  1862. {
  1863. typedef is_function<T> type;
  1864. }; // a non-object is callable iff it is a function
  1865. template<typename T>
  1866. struct is_callable_impl<true, T>
  1867. {
  1868. struct Fallback { void operator()(); };
  1869. struct Derived : T, Fallback { };
  1870. template<typename U, U> struct Check;
  1871. template<typename U>
  1872. static std::true_type test( ... ); // use a variadic function to make sure (1) it accepts everything and (2) its always the worst match
  1873. template<typename U>
  1874. static std::false_type test( Check<void(Fallback::*)(), &U::operator()>* );
  1875. public:
  1876. typedef decltype(test<Derived>(nullptr)) type;
  1877. typedef decltype(&Fallback::operator()) dtype;
  1878. static constexpr bool value = type::value;
  1879. }; // an object is callable iff it defines operator()
  1880. template<typename T>
  1881. struct is_callable
  1882. {
  1883. // dispatch to is_callable_impl<true, T> or is_callable_impl<false, T> depending on whether T is of class type or not
  1884. typedef typename is_callable_impl<std::is_class<T>::value, T>::type type;
  1885. };
  1886. template<typename IsYDataCallable>
  1887. struct plot_impl { };
  1888. template<>
  1889. struct plot_impl<std::false_type>
  1890. {
  1891. template<typename IterableX, typename IterableY>
  1892. bool operator()(const IterableX& x, const IterableY& y, const std::string& format)
  1893. {
  1894. detail::_interpreter::get();
  1895. // 2-phase lookup for distance, begin, end
  1896. using std::distance;
  1897. using std::begin;
  1898. using std::end;
  1899. auto xs = distance(begin(x), end(x));
  1900. auto ys = distance(begin(y), end(y));
  1901. assert(xs == ys && "x and y data must have the same number of elements!");
  1902. PyObject* xlist = PyList_New(xs);
  1903. PyObject* ylist = PyList_New(ys);
  1904. PyObject* pystring = PyString_FromString(format.c_str());
  1905. auto itx = begin(x), ity = begin(y);
  1906. for(size_t i = 0; i < xs; ++i) {
  1907. PyList_SetItem(xlist, i, PyFloat_FromDouble(*itx++));
  1908. PyList_SetItem(ylist, i, PyFloat_FromDouble(*ity++));
  1909. }
  1910. PyObject* plot_args = PyTuple_New(3);
  1911. PyTuple_SetItem(plot_args, 0, xlist);
  1912. PyTuple_SetItem(plot_args, 1, ylist);
  1913. PyTuple_SetItem(plot_args, 2, pystring);
  1914. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_plot, plot_args);
  1915. Py_DECREF(plot_args);
  1916. if(res) Py_DECREF(res);
  1917. return res;
  1918. }
  1919. };
  1920. template<>
  1921. struct plot_impl<std::true_type>
  1922. {
  1923. template<typename Iterable, typename Callable>
  1924. bool operator()(const Iterable& ticks, const Callable& f, const std::string& format)
  1925. {
  1926. if(begin(ticks) == end(ticks)) return true;
  1927. // We could use additional meta-programming to deduce the correct element type of y,
  1928. // but all values have to be convertible to double anyways
  1929. std::vector<double> y;
  1930. for(auto x : ticks) y.push_back(f(x));
  1931. return plot_impl<std::false_type>()(ticks,y,format);
  1932. }
  1933. };
  1934. } // end namespace detail
  1935. // recursion stop for the above
  1936. template<typename... Args>
  1937. bool plot() { return true; }
  1938. template<typename A, typename B, typename... Args>
  1939. bool plot(const A& a, const B& b, const std::string& format, Args... args)
  1940. {
  1941. return detail::plot_impl<typename detail::is_callable<B>::type>()(a,b,format) && plot(args...);
  1942. }
  1943. /*
  1944. * This group of plot() functions is needed to support initializer lists, i.e. calling
  1945. * plot( {1,2,3,4} )
  1946. */
  1947. inline bool plot(const std::vector<double>& x, const std::vector<double>& y, const std::string& format = "") {
  1948. return plot<double,double>(x,y,format);
  1949. }
  1950. inline bool plot(const std::vector<double>& y, const std::string& format = "") {
  1951. return plot<double>(y,format);
  1952. }
  1953. inline bool plot(const std::vector<double>& x, const std::vector<double>& y, const std::map<std::string, std::string>& keywords) {
  1954. return plot<double>(x,y,keywords);
  1955. }
  1956. /*
  1957. * This class allows dynamic plots, ie changing the plotted data without clearing and re-plotting
  1958. */
  1959. class Plot
  1960. {
  1961. public:
  1962. // default initialization with plot label, some data and format
  1963. template<typename Numeric>
  1964. Plot(const std::string& name, const std::vector<Numeric>& x, const std::vector<Numeric>& y, const std::string& format = "") {
  1965. detail::_interpreter::get();
  1966. assert(x.size() == y.size());
  1967. PyObject* kwargs = PyDict_New();
  1968. if(name != "")
  1969. PyDict_SetItemString(kwargs, "label", PyString_FromString(name.c_str()));
  1970. PyObject* xarray = detail::get_array(x);
  1971. PyObject* yarray = detail::get_array(y);
  1972. PyObject* pystring = PyString_FromString(format.c_str());
  1973. PyObject* plot_args = PyTuple_New(3);
  1974. PyTuple_SetItem(plot_args, 0, xarray);
  1975. PyTuple_SetItem(plot_args, 1, yarray);
  1976. PyTuple_SetItem(plot_args, 2, pystring);
  1977. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_plot, plot_args, kwargs);
  1978. Py_DECREF(kwargs);
  1979. Py_DECREF(plot_args);
  1980. if(res)
  1981. {
  1982. line= PyList_GetItem(res, 0);
  1983. if(line)
  1984. set_data_fct = PyObject_GetAttrString(line,"set_data");
  1985. else
  1986. Py_DECREF(line);
  1987. Py_DECREF(res);
  1988. }
  1989. }
  1990. // shorter initialization with name or format only
  1991. // basically calls line, = plot([], [])
  1992. Plot(const std::string& name = "", const std::string& format = "")
  1993. : Plot(name, std::vector<double>(), std::vector<double>(), format) {}
  1994. template<typename Numeric>
  1995. bool update(const std::vector<Numeric>& x, const std::vector<Numeric>& y) {
  1996. assert(x.size() == y.size());
  1997. if(set_data_fct)
  1998. {
  1999. PyObject* xarray = detail::get_array(x);
  2000. PyObject* yarray = detail::get_array(y);
  2001. PyObject* plot_args = PyTuple_New(2);
  2002. PyTuple_SetItem(plot_args, 0, xarray);
  2003. PyTuple_SetItem(plot_args, 1, yarray);
  2004. PyObject* res = PyObject_CallObject(set_data_fct, plot_args);
  2005. if (res) Py_DECREF(res);
  2006. return res;
  2007. }
  2008. return false;
  2009. }
  2010. // clears the plot but keep it available
  2011. bool clear() {
  2012. return update(std::vector<double>(), std::vector<double>());
  2013. }
  2014. // definitely remove this line
  2015. void remove() {
  2016. if(line)
  2017. {
  2018. auto remove_fct = PyObject_GetAttrString(line,"remove");
  2019. PyObject* args = PyTuple_New(0);
  2020. PyObject* res = PyObject_CallObject(remove_fct, args);
  2021. if (res) Py_DECREF(res);
  2022. }
  2023. decref();
  2024. }
  2025. ~Plot() {
  2026. decref();
  2027. }
  2028. private:
  2029. void decref() {
  2030. if(line)
  2031. Py_DECREF(line);
  2032. if(set_data_fct)
  2033. Py_DECREF(set_data_fct);
  2034. }
  2035. PyObject* line = nullptr;
  2036. PyObject* set_data_fct = nullptr;
  2037. };
  2038. } // end namespace matplotlibcpp