matplotlibcpp.h 27 KB

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