matplotlibcpp.h 91 KB

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