1
0

matplotlibcpp.h 93 KB

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