1
0

matplotlibcpp.h 71 KB

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