matplotlibcpp.h 79 KB

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