1
0

matplotlibcpp.h 61 KB

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