1
0

matplotlibcpp.h 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168
  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. }
  199. // must be called before the first regular call to matplotlib to have any effect
  200. void backend(const std::string& name)
  201. {
  202. detail::s_backend = name;
  203. }
  204. 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. // if PyDeCRFF, the function doesn't work on Mac OS
  660. }
  661. inline void axis(const std::string &axisstr)
  662. {
  663. PyObject* str = PyString_FromString(axisstr.c_str());
  664. PyObject* args = PyTuple_New(1);
  665. PyTuple_SetItem(args, 0, str);
  666. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_axis, args);
  667. if(!res) throw std::runtime_error("Call to title() failed.");
  668. // if PyDeCRFF, the function doesn't work on Mac OS
  669. }
  670. inline void xlabel(const std::string &str)
  671. {
  672. PyObject* pystr = PyString_FromString(str.c_str());
  673. PyObject* args = PyTuple_New(1);
  674. PyTuple_SetItem(args, 0, pystr);
  675. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_xlabel, args);
  676. if(!res) throw std::runtime_error("Call to xlabel() failed.");
  677. // if PyDeCRFF, the function doesn't work on Mac OS
  678. }
  679. inline void ylabel(const std::string &str)
  680. {
  681. PyObject* pystr = PyString_FromString(str.c_str());
  682. PyObject* args = PyTuple_New(1);
  683. PyTuple_SetItem(args, 0, pystr);
  684. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_ylabel, args);
  685. if(!res) throw std::runtime_error("Call to ylabel() failed.");
  686. // if PyDeCRFF, the function doesn't work on Mac OS
  687. }
  688. inline void grid(bool flag)
  689. {
  690. PyObject* pyflag = flag ? Py_True : Py_False;
  691. PyObject* args = PyTuple_New(1);
  692. PyTuple_SetItem(args, 0, pyflag);
  693. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_grid, args);
  694. if(!res) throw std::runtime_error("Call to grid() failed.");
  695. // if PyDeCRFF, the function doesn't work on Mac OS
  696. }
  697. inline void show(const bool block = true)
  698. {
  699. PyObject* res;
  700. if(block)
  701. {
  702. res = PyObject_CallObject(
  703. detail::_interpreter::get().s_python_function_show,
  704. detail::_interpreter::get().s_python_empty_tuple);
  705. }
  706. else
  707. {
  708. PyObject *kwargs = PyDict_New();
  709. PyDict_SetItemString(kwargs, "block", Py_False);
  710. res = PyObject_Call( detail::_interpreter::get().s_python_function_show, detail::_interpreter::get().s_python_empty_tuple, kwargs);
  711. }
  712. if (!res) throw std::runtime_error("Call to show() failed.");
  713. Py_DECREF(res);
  714. }
  715. inline void close()
  716. {
  717. PyObject* res = PyObject_CallObject(
  718. detail::_interpreter::get().s_python_function_close,
  719. detail::_interpreter::get().s_python_empty_tuple);
  720. if (!res) throw std::runtime_error("Call to close() failed.");
  721. Py_DECREF(res);
  722. }
  723. inline void xkcd() {
  724. PyObject* res;
  725. PyObject *kwargs = PyDict_New();
  726. res = PyObject_Call(detail::_interpreter::get().s_python_function_xkcd,
  727. detail::_interpreter::get().s_python_empty_tuple, kwargs);
  728. if (!res)
  729. throw std::runtime_error("Call to show() failed.");
  730. Py_DECREF(res);
  731. }
  732. inline void draw()
  733. {
  734. PyObject* res = PyObject_CallObject(
  735. detail::_interpreter::get().s_python_function_draw,
  736. detail::_interpreter::get().s_python_empty_tuple);
  737. if (!res) throw std::runtime_error("Call to draw() failed.");
  738. Py_DECREF(res);
  739. }
  740. template<typename Numeric>
  741. void pause(Numeric interval)
  742. {
  743. PyObject* args = PyTuple_New(1);
  744. PyTuple_SetItem(args, 0, PyFloat_FromDouble(interval));
  745. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_pause, args);
  746. if(!res) throw std::runtime_error("Call to pause() failed.");
  747. Py_DECREF(args);
  748. Py_DECREF(res);
  749. }
  750. inline void save(const std::string& filename)
  751. {
  752. PyObject* pyfilename = PyString_FromString(filename.c_str());
  753. PyObject* args = PyTuple_New(1);
  754. PyTuple_SetItem(args, 0, pyfilename);
  755. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_save, args);
  756. if (!res) throw std::runtime_error("Call to save() failed.");
  757. Py_DECREF(args);
  758. Py_DECREF(res);
  759. }
  760. inline void clf() {
  761. PyObject *res = PyObject_CallObject(
  762. detail::_interpreter::get().s_python_function_clf,
  763. detail::_interpreter::get().s_python_empty_tuple);
  764. if (!res) throw std::runtime_error("Call to clf() failed.");
  765. Py_DECREF(res);
  766. }
  767. inline void ion() {
  768. PyObject *res = PyObject_CallObject(
  769. detail::_interpreter::get().s_python_function_ion,
  770. detail::_interpreter::get().s_python_empty_tuple);
  771. if (!res) throw std::runtime_error("Call to ion() failed.");
  772. Py_DECREF(res);
  773. }
  774. // Actually, is there any reason not to call this automatically for every plot?
  775. inline void tight_layout() {
  776. PyObject *res = PyObject_CallObject(
  777. detail::_interpreter::get().s_python_function_tight_layout,
  778. detail::_interpreter::get().s_python_empty_tuple);
  779. if (!res) throw std::runtime_error("Call to tight_layout() failed.");
  780. Py_DECREF(res);
  781. }
  782. #if __cplusplus > 199711L || _MSC_VER > 1800
  783. // C++11-exclusive content starts here (variadic plot() and initializer list support)
  784. namespace detail {
  785. template<typename T>
  786. using is_function = typename std::is_function<std::remove_pointer<std::remove_reference<T>>>::type;
  787. template<bool obj, typename T>
  788. struct is_callable_impl;
  789. template<typename T>
  790. struct is_callable_impl<false, T>
  791. {
  792. typedef is_function<T> type;
  793. }; // a non-object is callable iff it is a function
  794. template<typename T>
  795. struct is_callable_impl<true, T>
  796. {
  797. struct Fallback { void operator()(); };
  798. struct Derived : T, Fallback { };
  799. template<typename U, U> struct Check;
  800. template<typename U>
  801. static std::true_type test( ... ); // use a variadic function to make sure (1) it accepts everything and (2) its always the worst match
  802. template<typename U>
  803. static std::false_type test( Check<void(Fallback::*)(), &U::operator()>* );
  804. public:
  805. typedef decltype(test<Derived>(nullptr)) type;
  806. typedef decltype(&Fallback::operator()) dtype;
  807. static constexpr bool value = type::value;
  808. }; // an object is callable iff it defines operator()
  809. template<typename T>
  810. struct is_callable
  811. {
  812. // dispatch to is_callable_impl<true, T> or is_callable_impl<false, T> depending on whether T is of class type or not
  813. typedef typename is_callable_impl<std::is_class<T>::value, T>::type type;
  814. };
  815. template<typename IsYDataCallable>
  816. struct plot_impl { };
  817. template<>
  818. struct plot_impl<std::false_type>
  819. {
  820. template<typename IterableX, typename IterableY>
  821. bool operator()(const IterableX& x, const IterableY& y, const std::string& format)
  822. {
  823. // 2-phase lookup for distance, begin, end
  824. using std::distance;
  825. using std::begin;
  826. using std::end;
  827. auto xs = distance(begin(x), end(x));
  828. auto ys = distance(begin(y), end(y));
  829. assert(xs == ys && "x and y data must have the same number of elements!");
  830. PyObject* xlist = PyList_New(xs);
  831. PyObject* ylist = PyList_New(ys);
  832. PyObject* pystring = PyString_FromString(format.c_str());
  833. auto itx = begin(x), ity = begin(y);
  834. for(size_t i = 0; i < xs; ++i) {
  835. PyList_SetItem(xlist, i, PyFloat_FromDouble(*itx++));
  836. PyList_SetItem(ylist, i, PyFloat_FromDouble(*ity++));
  837. }
  838. PyObject* plot_args = PyTuple_New(3);
  839. PyTuple_SetItem(plot_args, 0, xlist);
  840. PyTuple_SetItem(plot_args, 1, ylist);
  841. PyTuple_SetItem(plot_args, 2, pystring);
  842. PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_plot, plot_args);
  843. Py_DECREF(plot_args);
  844. if(res) Py_DECREF(res);
  845. return res;
  846. }
  847. };
  848. template<>
  849. struct plot_impl<std::true_type>
  850. {
  851. template<typename Iterable, typename Callable>
  852. bool operator()(const Iterable& ticks, const Callable& f, const std::string& format)
  853. {
  854. //std::cout << "Callable impl called" << std::endl;
  855. if(begin(ticks) == end(ticks)) return true;
  856. // We could use additional meta-programming to deduce the correct element type of y,
  857. // but all values have to be convertible to double anyways
  858. std::vector<double> y;
  859. for(auto x : ticks) y.push_back(f(x));
  860. return plot_impl<std::false_type>()(ticks,y,format);
  861. }
  862. };
  863. }
  864. // recursion stop for the above
  865. template<typename... Args>
  866. bool plot() { return true; }
  867. template<typename A, typename B, typename... Args>
  868. bool plot(const A& a, const B& b, const std::string& format, Args... args)
  869. {
  870. return detail::plot_impl<typename detail::is_callable<B>::type>()(a,b,format) && plot(args...);
  871. }
  872. /*
  873. * This group of plot() functions is needed to support initializer lists, i.e. calling
  874. * plot( {1,2,3,4} )
  875. */
  876. bool plot(const std::vector<double>& x, const std::vector<double>& y, const std::string& format = "") {
  877. return plot<double,double>(x,y,format);
  878. }
  879. bool plot(const std::vector<double>& y, const std::string& format = "") {
  880. return plot<double>(y,format);
  881. }
  882. bool plot(const std::vector<double>& x, const std::vector<double>& y, const std::map<std::string, std::string>& keywords) {
  883. return plot<double>(x,y,keywords);
  884. }
  885. bool stem(const std::vector<double>& x, const std::vector<double>& y, const std::string& format = "")
  886. {
  887. return stem<double, double>(x, y, format);
  888. }
  889. bool stem(const std::vector<double>& y, const std::string& format = "")
  890. {
  891. return stem<double>(y, format);
  892. }
  893. bool stem(const std::vector<double>& x, const std::vector<double>& y, const std::map<std::string, std::string>& keywords)
  894. {
  895. return stem<double>(x, y, keywords);
  896. }
  897. bool named_plot(const std::string& name, const std::vector<double>& x, const std::vector<double>& y, const std::string& format = "") {
  898. return named_plot<double>(name,x,y,format);
  899. }
  900. #endif
  901. }