matplotlibcpp.h 81 KB

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