matplotlibcpp.h 41 KB

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