matplotlibcpp.h 72 KB

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