matplotlibcpp.h 36 KB

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