1
0

matplotlibcpp.h 94 KB

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