matplotlibcpp.h 75 KB

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