1
0

matplotlibcpp.h 61 KB

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