matplotlibcpp.h 96 KB

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