matplotlibcpp.h 62 KB

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