matplotlibcpp.h 82 KB

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