matplotlibcpp.h 35 KB

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