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