matplotlibcpp.h 73 KB

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