matplotlibcpp.h 91 KB

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