matplotlibcpp.h 82 KB

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