matplotlibcpp.h 53 KB

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