matplotlibcpp.h 25 KB

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