matplotlibcpp.h 44 KB

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