matplotlibcpp.h 91 KB

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