matplotlibcpp.h 80 KB

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