matplotlibcpp.h 80 KB

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