matplotlibcpp.h 66 KB

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