matplotlibcpp.h 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024
  1. #pragma once
  2. #include <vector>
  3. #include <map>
  4. #include <numeric>
  5. #include <algorithm>
  6. #include <stdexcept>
  7. #include <iostream>
  8. #include <stdint.h> // <cstdint> requires c++11 support
  9. #if __cplusplus > 199711L || _MSC_VER > 1800
  10. #include <functional>
  11. #endif
  12. #include <Python.h>
  13. #ifndef WITHOUT_NUMPY
  14. #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
  15. #include <numpy/arrayobject.h>
  16. #endif // WITHOUT_NUMPY
  17. #if PY_MAJOR_VERSION >= 3
  18. #define PyString_FromString PyUnicode_FromString
  19. #endif
  20. namespace matplotlibcpp {
  21. namespace detail {
  22. static std::string s_backend;
  23. struct _interpreter {
  24. PyObject *s_python_function_show;
  25. PyObject *s_python_function_draw;
  26. PyObject *s_python_function_pause;
  27. PyObject *s_python_function_save;
  28. PyObject *s_python_function_figure;
  29. PyObject *s_python_function_plot;
  30. PyObject *s_python_function_semilogx;
  31. PyObject *s_python_function_semilogy;
  32. PyObject *s_python_function_loglog;
  33. PyObject *s_python_function_fill_between;
  34. PyObject *s_python_function_hist;
  35. PyObject *s_python_function_subplot;
  36. PyObject *s_python_function_legend;
  37. PyObject *s_python_function_xlim;
  38. PyObject *s_python_function_ylim;
  39. PyObject *s_python_function_title;
  40. PyObject *s_python_function_axis;
  41. PyObject *s_python_function_xlabel;
  42. PyObject *s_python_function_ylabel;
  43. PyObject *s_python_function_grid;
  44. PyObject *s_python_function_clf;
  45. PyObject *s_python_function_errorbar;
  46. PyObject *s_python_function_annotate;
  47. PyObject *s_python_function_tight_layout;
  48. PyObject *s_python_empty_tuple;
  49. /* For now, _interpreter is implemented as a singleton since its currently not possible to have
  50. multiple independent embedded python interpreters without patching the python source code
  51. or starting a separate process for each.
  52. http://bytes.com/topic/python/answers/793370-multiple-independent-python-interpreters-c-c-program
  53. */
  54. static _interpreter& get() {
  55. static _interpreter ctx;
  56. return ctx;
  57. }
  58. private:
  59. _interpreter() {
  60. // optional but recommended
  61. #if PY_MAJOR_VERSION >= 3
  62. wchar_t name[] = L"plotting";
  63. #else
  64. char name[] = "plotting";
  65. #endif
  66. Py_SetProgramName(name);
  67. Py_Initialize();
  68. #ifndef WITHOUT_NUMPY
  69. import_array(); // initialize numpy C-API
  70. #endif
  71. PyObject* matplotlibname = PyString_FromString("matplotlib");
  72. PyObject* pyplotname = PyString_FromString("matplotlib.pyplot");
  73. PyObject* pylabname = PyString_FromString("pylab");
  74. if (!pyplotname || !pylabname || !matplotlibname) {
  75. throw std::runtime_error("couldnt create string");
  76. }
  77. PyObject* matplotlib = PyImport_Import(matplotlibname);
  78. Py_DECREF(matplotlibname);
  79. if(!matplotlib) { throw std::runtime_error("Error loading module matplotlib!"); }
  80. // matplotlib.use() must be called *before* pylab, matplotlib.pyplot,
  81. // or matplotlib.backends is imported for the first time
  82. if (!s_backend.empty()) {
  83. PyObject_CallMethod(matplotlib, const_cast<char*>("use"), const_cast<char*>("s"), s_backend.c_str());
  84. }
  85. PyObject* pymod = PyImport_Import(pyplotname);
  86. Py_DECREF(pyplotname);
  87. if(!pymod) { throw std::runtime_error("Error loading module matplotlib.pyplot!"); }
  88. PyObject* pylabmod = PyImport_Import(pylabname);
  89. Py_DECREF(pylabname);
  90. if(!pylabmod) { throw std::runtime_error("Error loading module pylab!"); }
  91. s_python_function_show = PyObject_GetAttrString(pymod, "show");
  92. s_python_function_draw = PyObject_GetAttrString(pymod, "draw");
  93. s_python_function_pause = PyObject_GetAttrString(pymod, "pause");
  94. s_python_function_figure = PyObject_GetAttrString(pymod, "figure");
  95. s_python_function_plot = PyObject_GetAttrString(pymod, "plot");
  96. s_python_function_semilogx = PyObject_GetAttrString(pymod, "semilogx");
  97. s_python_function_semilogy = PyObject_GetAttrString(pymod, "semilogy");
  98. s_python_function_loglog = PyObject_GetAttrString(pymod, "loglog");
  99. s_python_function_fill_between = PyObject_GetAttrString(pymod, "fill_between");
  100. s_python_function_hist = PyObject_GetAttrString(pymod,"hist");
  101. s_python_function_subplot = PyObject_GetAttrString(pymod, "subplot");
  102. s_python_function_legend = PyObject_GetAttrString(pymod, "legend");
  103. s_python_function_ylim = PyObject_GetAttrString(pymod, "ylim");
  104. s_python_function_title = PyObject_GetAttrString(pymod, "title");
  105. s_python_function_axis = PyObject_GetAttrString(pymod, "axis");
  106. s_python_function_xlabel = PyObject_GetAttrString(pymod, "xlabel");
  107. s_python_function_ylabel = PyObject_GetAttrString(pymod, "ylabel");
  108. s_python_function_grid = PyObject_GetAttrString(pymod, "grid");
  109. s_python_function_xlim = PyObject_GetAttrString(pymod, "xlim");
  110. s_python_function_save = PyObject_GetAttrString(pylabmod, "savefig");
  111. s_python_function_annotate = PyObject_GetAttrString(pymod,"annotate");
  112. s_python_function_clf = PyObject_GetAttrString(pymod, "clf");
  113. s_python_function_errorbar = PyObject_GetAttrString(pymod, "errorbar");
  114. s_python_function_tight_layout = PyObject_GetAttrString(pymod, "tight_layout");
  115. if( !s_python_function_show
  116. || !s_python_function_draw
  117. || !s_python_function_pause
  118. || !s_python_function_figure
  119. || !s_python_function_plot
  120. || !s_python_function_semilogx
  121. || !s_python_function_semilogy
  122. || !s_python_function_loglog
  123. || !s_python_function_fill_between
  124. || !s_python_function_subplot
  125. || !s_python_function_legend
  126. || !s_python_function_ylim
  127. || !s_python_function_title
  128. || !s_python_function_axis
  129. || !s_python_function_xlabel
  130. || !s_python_function_ylabel
  131. || !s_python_function_grid
  132. || !s_python_function_xlim
  133. || !s_python_function_save
  134. || !s_python_function_clf
  135. || !s_python_function_annotate
  136. || !s_python_function_errorbar
  137. || !s_python_function_errorbar
  138. || !s_python_function_tight_layout
  139. ) { throw std::runtime_error("Couldn't find required function!"); }
  140. if ( !PyFunction_Check(s_python_function_show)
  141. || !PyFunction_Check(s_python_function_draw)
  142. || !PyFunction_Check(s_python_function_pause)
  143. || !PyFunction_Check(s_python_function_figure)
  144. || !PyFunction_Check(s_python_function_plot)
  145. || !PyFunction_Check(s_python_function_semilogx)
  146. || !PyFunction_Check(s_python_function_semilogy)
  147. || !PyFunction_Check(s_python_function_loglog)
  148. || !PyFunction_Check(s_python_function_fill_between)
  149. || !PyFunction_Check(s_python_function_subplot)
  150. || !PyFunction_Check(s_python_function_legend)
  151. || !PyFunction_Check(s_python_function_annotate)
  152. || !PyFunction_Check(s_python_function_ylim)
  153. || !PyFunction_Check(s_python_function_title)
  154. || !PyFunction_Check(s_python_function_axis)
  155. || !PyFunction_Check(s_python_function_xlabel)
  156. || !PyFunction_Check(s_python_function_ylabel)
  157. || !PyFunction_Check(s_python_function_grid)
  158. || !PyFunction_Check(s_python_function_xlim)
  159. || !PyFunction_Check(s_python_function_save)
  160. || !PyFunction_Check(s_python_function_clf)
  161. || !PyFunction_Check(s_python_function_tight_layout)
  162. || !PyFunction_Check(s_python_function_errorbar)
  163. ) { throw std::runtime_error("Python object is unexpectedly not a PyFunction."); }
  164. s_python_empty_tuple = PyTuple_New(0);
  165. }
  166. ~_interpreter() {
  167. Py_Finalize();
  168. }
  169. };
  170. }
  171. // must be called before the first regular call to matplotlib to have any effect
  172. void backend(const std::string& name)
  173. {
  174. detail::s_backend = name;
  175. }
  176. bool annotate(std::string annotation, double x, double y)
  177. {
  178. PyObject * xy = PyTuple_New(2);
  179. PyObject * str = PyString_FromString(annotation.c_str());
  180. PyTuple_SetItem(xy,0,PyFloat_FromDouble(x));
  181. PyTuple_SetItem(xy,1,PyFloat_FromDouble(y));
  182. PyObject* kwargs = PyDict_New();
  183. PyDict_SetItemString(kwargs, "xy", xy);
  184. PyObject* args = PyTuple_New(1);
  185. PyTuple_SetItem(args, 0, str);
  186. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_annotate, args, kwargs);
  187. Py_DECREF(args);
  188. Py_DECREF(kwargs);
  189. if(res) Py_DECREF(res);
  190. return res;
  191. }
  192. #ifndef WITHOUT_NUMPY
  193. // Type selector for numpy array conversion
  194. template <typename T> struct select_npy_type { const static NPY_TYPES type = NPY_NOTYPE; }; //Default
  195. template <> struct select_npy_type<double> { const static NPY_TYPES type = NPY_DOUBLE; };
  196. template <> struct select_npy_type<float> { const static NPY_TYPES type = NPY_FLOAT; };
  197. template <> struct select_npy_type<bool> { const static NPY_TYPES type = NPY_BOOL; };
  198. template <> struct select_npy_type<int8_t> { const static NPY_TYPES type = NPY_INT8; };
  199. template <> struct select_npy_type<int16_t> { const static NPY_TYPES type = NPY_SHORT; };
  200. template <> struct select_npy_type<int32_t> { const static NPY_TYPES type = NPY_INT; };
  201. template <> struct select_npy_type<int64_t> { const static NPY_TYPES type = NPY_INT64; };
  202. template <> struct select_npy_type<uint8_t> { const static NPY_TYPES type = NPY_UINT8; };
  203. template <> struct select_npy_type<uint16_t> { const static NPY_TYPES type = NPY_USHORT; };
  204. template <> struct select_npy_type<uint32_t> { const static NPY_TYPES type = NPY_ULONG; };
  205. template <> struct select_npy_type<uint64_t> { const static NPY_TYPES type = NPY_UINT64; };
  206. template<typename Numeric>
  207. PyObject* get_array(const std::vector<Numeric>& v)
  208. {
  209. detail::_interpreter::get(); //interpreter needs to be initialized for the numpy commands to work
  210. NPY_TYPES type = select_npy_type<Numeric>::type;
  211. if (type == NPY_NOTYPE)
  212. {
  213. std::vector<double> vd(v.size());
  214. npy_intp vsize = v.size();
  215. std::copy(v.begin(),v.end(),vd.begin());
  216. PyObject* varray = PyArray_SimpleNewFromData(1, &vsize, NPY_DOUBLE, (void*)(vd.data()));
  217. return varray;
  218. }
  219. npy_intp vsize = v.size();
  220. PyObject* varray = PyArray_SimpleNewFromData(1, &vsize, type, (void*)(v.data()));
  221. return varray;
  222. }
  223. #else // fallback if we don't have numpy: copy every element of the given vector
  224. template<typename Numeric>
  225. PyObject* get_array(const std::vector<Numeric>& v)
  226. {
  227. PyObject* list = PyList_New(v.size());
  228. for(size_t i = 0; i < v.size(); ++i) {
  229. PyList_SetItem(list, i, PyFloat_FromDouble(v.at(i)));
  230. }
  231. return list;
  232. }
  233. #endif // WITHOUT_NUMPY
  234. template<typename Numeric>
  235. bool plot(const std::vector<Numeric> &x, const std::vector<Numeric> &y, const std::map<std::string, std::string>& keywords)
  236. {
  237. assert(x.size() == y.size());
  238. // using numpy arrays
  239. PyObject* xarray = get_array(x);
  240. PyObject* yarray = get_array(y);
  241. // construct positional args
  242. PyObject* args = PyTuple_New(2);
  243. PyTuple_SetItem(args, 0, xarray);
  244. PyTuple_SetItem(args, 1, yarray);
  245. // construct keyword args
  246. PyObject* kwargs = PyDict_New();
  247. for(std::map<std::string, std::string>::const_iterator it = keywords.begin(); it != keywords.end(); ++it)
  248. {
  249. PyDict_SetItemString(kwargs, it->first.c_str(), PyString_FromString(it->second.c_str()));
  250. }
  251. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_plot, args, kwargs);
  252. Py_DECREF(args);
  253. Py_DECREF(kwargs);
  254. if(res) Py_DECREF(res);
  255. return res;
  256. }
  257. template< typename Numeric >
  258. 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)
  259. {
  260. assert(x.size() == y1.size());
  261. assert(x.size() == y2.size());
  262. // using numpy arrays
  263. PyObject* xarray = get_array(x);
  264. PyObject* y1array = get_array(y1);
  265. PyObject* y2array = get_array(y2);
  266. // construct positional args
  267. PyObject* args = PyTuple_New(3);
  268. PyTuple_SetItem(args, 0, xarray);
  269. PyTuple_SetItem(args, 1, y1array);
  270. PyTuple_SetItem(args, 2, y2array);
  271. // construct keyword args
  272. PyObject* kwargs = PyDict_New();
  273. for(std::map<std::string, std::string>::const_iterator it = keywords.begin(); it != keywords.end(); ++it)
  274. {
  275. PyDict_SetItemString(kwargs, it->first.c_str(), PyUnicode_FromString(it->second.c_str()));
  276. }
  277. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_fill_between, args, kwargs);
  278. Py_DECREF(args);
  279. Py_DECREF(kwargs);
  280. if(res) Py_DECREF(res);
  281. return res;
  282. }
  283. template< typename Numeric>
  284. bool hist(const std::vector<Numeric>& y, long bins=10,std::string color="b", double alpha=1.0)
  285. {
  286. PyObject* yarray = get_array(y);
  287. PyObject* kwargs = PyDict_New();
  288. PyDict_SetItemString(kwargs, "bins", PyLong_FromLong(bins));
  289. PyDict_SetItemString(kwargs, "color", PyString_FromString(color.c_str()));
  290. PyDict_SetItemString(kwargs, "alpha", PyFloat_FromDouble(alpha));
  291. PyObject* plot_args = PyTuple_New(1);
  292. PyTuple_SetItem(plot_args, 0, yarray);
  293. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_hist, plot_args, kwargs);
  294. Py_DECREF(plot_args);
  295. Py_DECREF(kwargs);
  296. if(res) Py_DECREF(res);
  297. return res;
  298. }
  299. template< typename Numeric>
  300. bool named_hist(std::string label,const std::vector<Numeric>& y, long bins=10, std::string color="b", double alpha=1.0)
  301. {
  302. PyObject* yarray = get_array(y);
  303. PyObject* kwargs = PyDict_New();
  304. PyDict_SetItemString(kwargs, "label", PyString_FromString(label.c_str()));
  305. PyDict_SetItemString(kwargs, "bins", PyLong_FromLong(bins));
  306. PyDict_SetItemString(kwargs, "color", PyString_FromString(color.c_str()));
  307. PyDict_SetItemString(kwargs, "alpha", PyFloat_FromDouble(alpha));
  308. PyObject* plot_args = PyTuple_New(1);
  309. PyTuple_SetItem(plot_args, 0, yarray);
  310. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_hist, plot_args, kwargs);
  311. Py_DECREF(plot_args);
  312. Py_DECREF(kwargs);
  313. if(res) Py_DECREF(res);
  314. return res;
  315. }
  316. template<typename NumericX, typename NumericY>
  317. bool plot(const std::vector<NumericX>& x, const std::vector<NumericY>& y, const std::string& s = "")
  318. {
  319. assert(x.size() == y.size());
  320. PyObject* xarray = get_array(x);
  321. PyObject* yarray = get_array(y);
  322. PyObject* pystring = PyString_FromString(s.c_str());
  323. PyObject* plot_args = PyTuple_New(3);
  324. PyTuple_SetItem(plot_args, 0, xarray);
  325. PyTuple_SetItem(plot_args, 1, yarray);
  326. PyTuple_SetItem(plot_args, 2, pystring);
  327. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_plot, plot_args);
  328. Py_DECREF(plot_args);
  329. if(res) Py_DECREF(res);
  330. return res;
  331. }
  332. template<typename NumericX, typename NumericY>
  333. bool semilogx(const std::vector<NumericX>& x, const std::vector<NumericY>& y, const std::string& s = "")
  334. {
  335. assert(x.size() == y.size());
  336. PyObject* xarray = get_array(x);
  337. PyObject* yarray = get_array(y);
  338. PyObject* pystring = PyString_FromString(s.c_str());
  339. PyObject* plot_args = PyTuple_New(3);
  340. PyTuple_SetItem(plot_args, 0, xarray);
  341. PyTuple_SetItem(plot_args, 1, yarray);
  342. PyTuple_SetItem(plot_args, 2, pystring);
  343. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_semilogx, plot_args);
  344. Py_DECREF(plot_args);
  345. if(res) Py_DECREF(res);
  346. return res;
  347. }
  348. template<typename NumericX, typename NumericY>
  349. bool semilogy(const std::vector<NumericX>& x, const std::vector<NumericY>& y, const std::string& s = "")
  350. {
  351. assert(x.size() == y.size());
  352. PyObject* xarray = get_array(x);
  353. PyObject* yarray = get_array(y);
  354. PyObject* pystring = PyString_FromString(s.c_str());
  355. PyObject* plot_args = PyTuple_New(3);
  356. PyTuple_SetItem(plot_args, 0, xarray);
  357. PyTuple_SetItem(plot_args, 1, yarray);
  358. PyTuple_SetItem(plot_args, 2, pystring);
  359. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_semilogy, plot_args);
  360. Py_DECREF(plot_args);
  361. if(res) Py_DECREF(res);
  362. return res;
  363. }
  364. template<typename NumericX, typename NumericY>
  365. bool loglog(const std::vector<NumericX>& x, const std::vector<NumericY>& y, const std::string& s = "")
  366. {
  367. assert(x.size() == y.size());
  368. PyObject* xarray = get_array(x);
  369. PyObject* yarray = get_array(y);
  370. PyObject* pystring = PyString_FromString(s.c_str());
  371. PyObject* plot_args = PyTuple_New(3);
  372. PyTuple_SetItem(plot_args, 0, xarray);
  373. PyTuple_SetItem(plot_args, 1, yarray);
  374. PyTuple_SetItem(plot_args, 2, pystring);
  375. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_loglog, plot_args);
  376. Py_DECREF(plot_args);
  377. if(res) Py_DECREF(res);
  378. return res;
  379. }
  380. template<typename NumericX, typename NumericY>
  381. bool errorbar(const std::vector<NumericX> &x, const std::vector<NumericY> &y, const std::vector<NumericX> &yerr, const std::string &s = "")
  382. {
  383. assert(x.size() == y.size());
  384. PyObject* xarray = get_array(x);
  385. PyObject* yarray = get_array(y);
  386. PyObject* yerrarray = get_array(yerr);
  387. PyObject *kwargs = PyDict_New();
  388. PyDict_SetItemString(kwargs, "yerr", yerrarray);
  389. PyObject *pystring = PyString_FromString(s.c_str());
  390. PyObject *plot_args = PyTuple_New(2);
  391. PyTuple_SetItem(plot_args, 0, xarray);
  392. PyTuple_SetItem(plot_args, 1, yarray);
  393. PyObject *res = PyObject_Call(detail::_interpreter::get().s_python_function_errorbar, plot_args, kwargs);
  394. Py_DECREF(kwargs);
  395. Py_DECREF(plot_args);
  396. if (res)
  397. Py_DECREF(res);
  398. else
  399. throw std::runtime_error("Call to errorbar() failed.");
  400. return res;
  401. }
  402. template<typename Numeric>
  403. bool named_plot(const std::string& name, const std::vector<Numeric>& y, const std::string& format = "")
  404. {
  405. PyObject* kwargs = PyDict_New();
  406. PyDict_SetItemString(kwargs, "label", PyString_FromString(name.c_str()));
  407. PyObject* yarray = get_array(y);
  408. PyObject* pystring = PyString_FromString(format.c_str());
  409. PyObject* plot_args = PyTuple_New(2);
  410. PyTuple_SetItem(plot_args, 0, yarray);
  411. PyTuple_SetItem(plot_args, 1, pystring);
  412. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_plot, plot_args, kwargs);
  413. Py_DECREF(kwargs);
  414. Py_DECREF(plot_args);
  415. if(res) Py_DECREF(res);
  416. return res;
  417. }
  418. template<typename Numeric>
  419. bool named_plot(const std::string& name, const std::vector<Numeric>& x, const std::vector<Numeric>& y, const std::string& format = "")
  420. {
  421. PyObject* kwargs = PyDict_New();
  422. PyDict_SetItemString(kwargs, "label", PyString_FromString(name.c_str()));
  423. PyObject* xarray = get_array(x);
  424. PyObject* yarray = get_array(y);
  425. PyObject* pystring = PyString_FromString(format.c_str());
  426. PyObject* plot_args = PyTuple_New(3);
  427. PyTuple_SetItem(plot_args, 0, xarray);
  428. PyTuple_SetItem(plot_args, 1, yarray);
  429. PyTuple_SetItem(plot_args, 2, pystring);
  430. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_plot, plot_args, kwargs);
  431. Py_DECREF(kwargs);
  432. Py_DECREF(plot_args);
  433. if(res) Py_DECREF(res);
  434. return res;
  435. }
  436. template<typename Numeric>
  437. bool named_semilogx(const std::string& name, const std::vector<Numeric>& x, const std::vector<Numeric>& y, const std::string& format = "")
  438. {
  439. PyObject* kwargs = PyDict_New();
  440. PyDict_SetItemString(kwargs, "label", PyString_FromString(name.c_str()));
  441. PyObject* xarray = get_array(x);
  442. PyObject* yarray = get_array(y);
  443. PyObject* pystring = PyString_FromString(format.c_str());
  444. PyObject* plot_args = PyTuple_New(3);
  445. PyTuple_SetItem(plot_args, 0, xarray);
  446. PyTuple_SetItem(plot_args, 1, yarray);
  447. PyTuple_SetItem(plot_args, 2, pystring);
  448. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_semilogx, plot_args, kwargs);
  449. Py_DECREF(kwargs);
  450. Py_DECREF(plot_args);
  451. if(res) Py_DECREF(res);
  452. return res;
  453. }
  454. template<typename Numeric>
  455. bool named_semilogy(const std::string& name, const std::vector<Numeric>& x, const std::vector<Numeric>& y, const std::string& format = "")
  456. {
  457. PyObject* kwargs = PyDict_New();
  458. PyDict_SetItemString(kwargs, "label", PyString_FromString(name.c_str()));
  459. PyObject* xarray = get_array(x);
  460. PyObject* yarray = get_array(y);
  461. PyObject* pystring = PyString_FromString(format.c_str());
  462. PyObject* plot_args = PyTuple_New(3);
  463. PyTuple_SetItem(plot_args, 0, xarray);
  464. PyTuple_SetItem(plot_args, 1, yarray);
  465. PyTuple_SetItem(plot_args, 2, pystring);
  466. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_semilogy, plot_args, kwargs);
  467. Py_DECREF(kwargs);
  468. Py_DECREF(plot_args);
  469. if(res) Py_DECREF(res);
  470. return res;
  471. }
  472. template<typename Numeric>
  473. bool named_loglog(const std::string& name, const std::vector<Numeric>& x, const std::vector<Numeric>& y, const std::string& format = "")
  474. {
  475. PyObject* kwargs = PyDict_New();
  476. PyDict_SetItemString(kwargs, "label", PyString_FromString(name.c_str()));
  477. PyObject* xarray = get_array(x);
  478. PyObject* yarray = get_array(y);
  479. PyObject* pystring = PyString_FromString(format.c_str());
  480. PyObject* plot_args = PyTuple_New(3);
  481. PyTuple_SetItem(plot_args, 0, xarray);
  482. PyTuple_SetItem(plot_args, 1, yarray);
  483. PyTuple_SetItem(plot_args, 2, pystring);
  484. PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_loglog, plot_args, kwargs);
  485. Py_DECREF(kwargs);
  486. Py_DECREF(plot_args);
  487. if(res) Py_DECREF(res);
  488. return res;
  489. }
  490. template<typename Numeric>
  491. bool plot(const std::vector<Numeric>& y, const std::string& format = "")
  492. {
  493. std::vector<Numeric> x(y.size());
  494. for(size_t i=0; i<x.size(); ++i) x.at(i) = i;
  495. return plot(x,y,format);
  496. }
  497. inline void figure()
  498. {
  499. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_figure, detail::_interpreter::get().s_python_empty_tuple);
  500. if(!res) throw std::runtime_error("Call to figure() failed.");
  501. Py_DECREF(res);
  502. }
  503. inline void legend()
  504. {
  505. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_legend, detail::_interpreter::get().s_python_empty_tuple);
  506. if(!res) throw std::runtime_error("Call to legend() failed.");
  507. Py_DECREF(res);
  508. }
  509. template<typename Numeric>
  510. void ylim(Numeric left, Numeric right)
  511. {
  512. PyObject* list = PyList_New(2);
  513. PyList_SetItem(list, 0, PyFloat_FromDouble(left));
  514. PyList_SetItem(list, 1, PyFloat_FromDouble(right));
  515. PyObject* args = PyTuple_New(1);
  516. PyTuple_SetItem(args, 0, list);
  517. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_ylim, args);
  518. if(!res) throw std::runtime_error("Call to ylim() failed.");
  519. Py_DECREF(args);
  520. Py_DECREF(res);
  521. }
  522. template<typename Numeric>
  523. void xlim(Numeric left, Numeric right)
  524. {
  525. PyObject* list = PyList_New(2);
  526. PyList_SetItem(list, 0, PyFloat_FromDouble(left));
  527. PyList_SetItem(list, 1, PyFloat_FromDouble(right));
  528. PyObject* args = PyTuple_New(1);
  529. PyTuple_SetItem(args, 0, list);
  530. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_xlim, args);
  531. if(!res) throw std::runtime_error("Call to xlim() failed.");
  532. Py_DECREF(args);
  533. Py_DECREF(res);
  534. }
  535. inline double* xlim()
  536. {
  537. PyObject* args = PyTuple_New(0);
  538. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_xlim, args);
  539. PyObject* left = PyTuple_GetItem(res,0);
  540. PyObject* right = PyTuple_GetItem(res,1);
  541. double* arr = new double[2];
  542. arr[0] = PyFloat_AsDouble(left);
  543. arr[1] = PyFloat_AsDouble(right);
  544. if(!res) throw std::runtime_error("Call to xlim() failed.");
  545. Py_DECREF(res);
  546. return arr;
  547. }
  548. inline double* ylim()
  549. {
  550. PyObject* args = PyTuple_New(0);
  551. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_ylim, args);
  552. PyObject* left = PyTuple_GetItem(res,0);
  553. PyObject* right = PyTuple_GetItem(res,1);
  554. double* arr = new double[2];
  555. arr[0] = PyFloat_AsDouble(left);
  556. arr[1] = PyFloat_AsDouble(right);
  557. if(!res) throw std::runtime_error("Call to ylim() failed.");
  558. Py_DECREF(res);
  559. return arr;
  560. }
  561. inline void subplot(long nrows, long ncols, long plot_number)
  562. {
  563. // construct positional args
  564. PyObject* args = PyTuple_New(3);
  565. PyTuple_SetItem(args, 0, PyFloat_FromDouble(nrows));
  566. PyTuple_SetItem(args, 1, PyFloat_FromDouble(ncols));
  567. PyTuple_SetItem(args, 2, PyFloat_FromDouble(plot_number));
  568. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_subplot, args);
  569. if(!res) throw std::runtime_error("Call to subplot() failed.");
  570. Py_DECREF(args);
  571. Py_DECREF(res);
  572. }
  573. inline void title(const std::string &titlestr)
  574. {
  575. PyObject* pytitlestr = PyString_FromString(titlestr.c_str());
  576. PyObject* args = PyTuple_New(1);
  577. PyTuple_SetItem(args, 0, pytitlestr);
  578. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_title, args);
  579. if(!res) throw std::runtime_error("Call to title() failed.");
  580. // if PyDeCRFF, the function doesn't work on Mac OS
  581. }
  582. inline void axis(const std::string &axisstr)
  583. {
  584. PyObject* str = PyString_FromString(axisstr.c_str());
  585. PyObject* args = PyTuple_New(1);
  586. PyTuple_SetItem(args, 0, str);
  587. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_axis, args);
  588. if(!res) throw std::runtime_error("Call to title() failed.");
  589. // if PyDeCRFF, the function doesn't work on Mac OS
  590. }
  591. inline void xlabel(const std::string &str)
  592. {
  593. PyObject* pystr = PyString_FromString(str.c_str());
  594. PyObject* args = PyTuple_New(1);
  595. PyTuple_SetItem(args, 0, pystr);
  596. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_xlabel, args);
  597. if(!res) throw std::runtime_error("Call to xlabel() failed.");
  598. // if PyDeCRFF, the function doesn't work on Mac OS
  599. }
  600. inline void ylabel(const std::string &str)
  601. {
  602. PyObject* pystr = PyString_FromString(str.c_str());
  603. PyObject* args = PyTuple_New(1);
  604. PyTuple_SetItem(args, 0, pystr);
  605. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_ylabel, args);
  606. if(!res) throw std::runtime_error("Call to ylabel() failed.");
  607. // if PyDeCRFF, the function doesn't work on Mac OS
  608. }
  609. inline void grid(bool flag)
  610. {
  611. PyObject* pyflag = flag ? Py_True : Py_False;
  612. PyObject* args = PyTuple_New(1);
  613. PyTuple_SetItem(args, 0, pyflag);
  614. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_grid, args);
  615. if(!res) throw std::runtime_error("Call to grid() failed.");
  616. // if PyDeCRFF, the function doesn't work on Mac OS
  617. }
  618. inline void show(const bool block = true)
  619. {
  620. PyObject* res;
  621. if(block)
  622. {
  623. res = PyObject_CallObject(
  624. detail::_interpreter::get().s_python_function_show,
  625. detail::_interpreter::get().s_python_empty_tuple);
  626. }
  627. else
  628. {
  629. PyObject *kwargs = PyDict_New();
  630. PyDict_SetItemString(kwargs, "block", Py_False);
  631. res = PyObject_Call( detail::_interpreter::get().s_python_function_show, detail::_interpreter::get().s_python_empty_tuple, kwargs);
  632. }
  633. if (!res) throw std::runtime_error("Call to show() failed.");
  634. Py_DECREF(res);
  635. }
  636. inline void draw()
  637. {
  638. PyObject* res = PyObject_CallObject(
  639. detail::_interpreter::get().s_python_function_draw,
  640. detail::_interpreter::get().s_python_empty_tuple);
  641. if (!res) throw std::runtime_error("Call to draw() failed.");
  642. Py_DECREF(res);
  643. }
  644. template<typename Numeric>
  645. void pause(Numeric interval)
  646. {
  647. PyObject* args = PyTuple_New(1);
  648. PyTuple_SetItem(args, 0, PyFloat_FromDouble(interval));
  649. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_pause, args);
  650. if(!res) throw std::runtime_error("Call to pause() failed.");
  651. Py_DECREF(args);
  652. Py_DECREF(res);
  653. }
  654. inline void save(const std::string& filename)
  655. {
  656. PyObject* pyfilename = PyString_FromString(filename.c_str());
  657. PyObject* args = PyTuple_New(1);
  658. PyTuple_SetItem(args, 0, pyfilename);
  659. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_save, args);
  660. if (!res) throw std::runtime_error("Call to save() failed.");
  661. Py_DECREF(args);
  662. Py_DECREF(res);
  663. }
  664. inline void clf() {
  665. PyObject *res = PyObject_CallObject(
  666. detail::_interpreter::get().s_python_function_clf,
  667. detail::_interpreter::get().s_python_empty_tuple);
  668. if (!res) throw std::runtime_error("Call to clf() failed.");
  669. Py_DECREF(res);
  670. }
  671. // Actually, is there any reason not to call this automatically for every plot?
  672. inline void tight_layout() {
  673. PyObject *res = PyObject_CallObject(
  674. detail::_interpreter::get().s_python_function_tight_layout,
  675. detail::_interpreter::get().s_python_empty_tuple);
  676. if (!res) throw std::runtime_error("Call to tight_layout() failed.");
  677. Py_DECREF(res);
  678. }
  679. #if __cplusplus > 199711L || _MSC_VER > 1800
  680. // C++11-exclusive content starts here (variadic plot() and initializer list support)
  681. namespace detail {
  682. template<typename T>
  683. using is_function = typename std::is_function<std::remove_pointer<std::remove_reference<T>>>::type;
  684. template<bool obj, typename T>
  685. struct is_callable_impl;
  686. template<typename T>
  687. struct is_callable_impl<false, T>
  688. {
  689. typedef is_function<T> type;
  690. }; // a non-object is callable iff it is a function
  691. template<typename T>
  692. struct is_callable_impl<true, T>
  693. {
  694. struct Fallback { void operator()(); };
  695. struct Derived : T, Fallback { };
  696. template<typename U, U> struct Check;
  697. template<typename U>
  698. static std::true_type test( ... ); // use a variadic function to make sure (1) it accepts everything and (2) its always the worst match
  699. template<typename U>
  700. static std::false_type test( Check<void(Fallback::*)(), &U::operator()>* );
  701. public:
  702. typedef decltype(test<Derived>(nullptr)) type;
  703. typedef decltype(&Fallback::operator()) dtype;
  704. static constexpr bool value = type::value;
  705. }; // an object is callable iff it defines operator()
  706. template<typename T>
  707. struct is_callable
  708. {
  709. // dispatch to is_callable_impl<true, T> or is_callable_impl<false, T> depending on whether T is of class type or not
  710. typedef typename is_callable_impl<std::is_class<T>::value, T>::type type;
  711. };
  712. template<typename IsYDataCallable>
  713. struct plot_impl { };
  714. template<>
  715. struct plot_impl<std::false_type>
  716. {
  717. template<typename IterableX, typename IterableY>
  718. bool operator()(const IterableX& x, const IterableY& y, const std::string& format)
  719. {
  720. // 2-phase lookup for distance, begin, end
  721. using std::distance;
  722. using std::begin;
  723. using std::end;
  724. auto xs = distance(begin(x), end(x));
  725. auto ys = distance(begin(y), end(y));
  726. assert(xs == ys && "x and y data must have the same number of elements!");
  727. PyObject* xlist = PyList_New(xs);
  728. PyObject* ylist = PyList_New(ys);
  729. PyObject* pystring = PyString_FromString(format.c_str());
  730. auto itx = begin(x), ity = begin(y);
  731. for(size_t i = 0; i < xs; ++i) {
  732. PyList_SetItem(xlist, i, PyFloat_FromDouble(*itx++));
  733. PyList_SetItem(ylist, i, PyFloat_FromDouble(*ity++));
  734. }
  735. PyObject* plot_args = PyTuple_New(3);
  736. PyTuple_SetItem(plot_args, 0, xlist);
  737. PyTuple_SetItem(plot_args, 1, ylist);
  738. PyTuple_SetItem(plot_args, 2, pystring);
  739. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_plot, plot_args);
  740. Py_DECREF(plot_args);
  741. if(res) Py_DECREF(res);
  742. return res;
  743. }
  744. };
  745. template<>
  746. struct plot_impl<std::true_type>
  747. {
  748. template<typename Iterable, typename Callable>
  749. bool operator()(const Iterable& ticks, const Callable& f, const std::string& format)
  750. {
  751. //std::cout << "Callable impl called" << std::endl;
  752. if(begin(ticks) == end(ticks)) return true;
  753. // We could use additional meta-programming to deduce the correct element type of y,
  754. // but all values have to be convertible to double anyways
  755. std::vector<double> y;
  756. for(auto x : ticks) y.push_back(f(x));
  757. return plot_impl<std::false_type>()(ticks,y,format);
  758. }
  759. };
  760. }
  761. // recursion stop for the above
  762. template<typename... Args>
  763. bool plot() { return true; }
  764. template<typename A, typename B, typename... Args>
  765. bool plot(const A& a, const B& b, const std::string& format, Args... args)
  766. {
  767. return detail::plot_impl<typename detail::is_callable<B>::type>()(a,b,format) && plot(args...);
  768. }
  769. /*
  770. * This group of plot() functions is needed to support initializer lists, i.e. calling
  771. * plot( {1,2,3,4} )
  772. */
  773. bool plot(const std::vector<double>& x, const std::vector<double>& y, const std::string& format = "") {
  774. return plot<double,double>(x,y,format);
  775. }
  776. bool plot(const std::vector<double>& y, const std::string& format = "") {
  777. return plot<double>(y,format);
  778. }
  779. bool plot(const std::vector<double>& x, const std::vector<double>& y, const std::map<std::string, std::string>& keywords) {
  780. return plot<double>(x,y,keywords);
  781. }
  782. bool named_plot(const std::string& name, const std::vector<double>& x, const std::vector<double>& y, const std::string& format = "") {
  783. return named_plot<double>(name,x,y,format);
  784. }
  785. #endif
  786. }